Chris@0: /** Chris@0: * @file Chris@0: * Provide dragging capabilities to admin uis. Chris@0: */ Chris@0: Chris@0: /** Chris@0: * Triggers when weights columns are toggled. Chris@0: * Chris@0: * @event columnschange Chris@0: */ Chris@0: Chris@17: (function($, Drupal, drupalSettings) { Chris@0: /** Chris@0: * Store the state of weight columns display for all tables. Chris@0: * Chris@0: * Default value is to hide weight columns. Chris@0: */ Chris@17: let showWeight = JSON.parse( Chris@17: localStorage.getItem('Drupal.tableDrag.showWeight'), Chris@17: ); Chris@0: Chris@0: /** Chris@0: * Drag and drop table rows with field manipulation. Chris@0: * Chris@0: * Using the drupal_attach_tabledrag() function, any table with weights or Chris@0: * parent relationships may be made into draggable tables. Columns containing Chris@0: * a field may optionally be hidden, providing a better user experience. Chris@0: * Chris@0: * Created tableDrag instances may be modified with custom behaviors by Chris@0: * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. Chris@0: * See blocks.js for an example of adding additional functionality to Chris@0: * tableDrag. Chris@0: * Chris@0: * @type {Drupal~behavior} Chris@0: */ Chris@0: Drupal.behaviors.tableDrag = { Chris@0: attach(context, settings) { Chris@0: function initTableDrag(table, base) { Chris@0: if (table.length) { Chris@0: // Create the new tableDrag instance. Save in the Drupal variable Chris@0: // to allow other scripts access to the object. Chris@17: Drupal.tableDrag[base] = new Drupal.tableDrag( Chris@17: table[0], Chris@17: settings.tableDrag[base], Chris@17: ); Chris@0: } Chris@0: } Chris@0: Chris@17: Object.keys(settings.tableDrag || {}).forEach(base => { Chris@17: initTableDrag( Chris@17: $(context) Chris@17: .find(`#${base}`) Chris@17: .once('tabledrag'), Chris@17: base, Chris@17: ); Chris@14: }); Chris@0: }, Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Provides table and field manipulation. Chris@0: * Chris@0: * @constructor Chris@0: * Chris@0: * @param {HTMLElement} table Chris@0: * DOM object for the table to be made draggable. Chris@0: * @param {object} tableSettings Chris@0: * Settings for the table added via drupal_add_dragtable(). Chris@0: */ Chris@17: Drupal.tableDrag = function(table, tableSettings) { Chris@0: const self = this; Chris@0: const $table = $(table); Chris@0: Chris@0: /** Chris@0: * @type {jQuery} Chris@0: */ Chris@0: this.$table = $(table); Chris@0: Chris@0: /** Chris@0: * Chris@0: * @type {HTMLElement} Chris@0: */ Chris@0: this.table = table; Chris@0: Chris@0: /** Chris@0: * @type {object} Chris@0: */ Chris@0: this.tableSettings = tableSettings; Chris@0: Chris@0: /** Chris@0: * Used to hold information about a current drag operation. Chris@0: * Chris@0: * @type {?HTMLElement} Chris@0: */ Chris@0: this.dragObject = null; Chris@0: Chris@0: /** Chris@0: * Provides operations for row manipulation. Chris@0: * Chris@0: * @type {?HTMLElement} Chris@0: */ Chris@0: this.rowObject = null; Chris@0: Chris@0: /** Chris@0: * Remember the previous element. Chris@0: * Chris@0: * @type {?HTMLElement} Chris@0: */ Chris@0: this.oldRowElement = null; Chris@0: Chris@0: /** Chris@0: * Used to determine up or down direction from last mouse move. Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@0: this.oldY = 0; Chris@0: Chris@0: /** Chris@0: * Whether anything in the entire table has changed. Chris@0: * Chris@0: * @type {bool} Chris@0: */ Chris@0: this.changed = false; Chris@0: Chris@0: /** Chris@0: * Maximum amount of allowed parenting. Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@0: this.maxDepth = 0; Chris@0: Chris@0: /** Chris@0: * Direction of the table. Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@0: this.rtl = $(this.table).css('direction') === 'rtl' ? -1 : 1; Chris@0: Chris@0: /** Chris@0: * Chris@0: * @type {bool} Chris@0: */ Chris@0: this.striping = $(this.table).data('striping') === 1; Chris@0: Chris@0: /** Chris@0: * Configure the scroll settings. Chris@0: * Chris@0: * @type {object} Chris@0: * Chris@0: * @prop {number} amount Chris@0: * @prop {number} interval Chris@0: * @prop {number} trigger Chris@0: */ Chris@0: this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; Chris@0: Chris@0: /** Chris@0: * Chris@0: * @type {?number} Chris@0: */ Chris@0: this.scrollInterval = null; Chris@0: Chris@0: /** Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@0: this.scrollY = 0; Chris@0: Chris@0: /** Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@0: this.windowHeight = 0; Chris@0: Chris@0: /** Chris@0: * Check this table's settings for parent relationships. Chris@0: * Chris@0: * For efficiency, large sections of code can be skipped if we don't need to Chris@0: * track horizontal movement and indentations. Chris@0: * Chris@0: * @type {bool} Chris@0: */ Chris@0: this.indentEnabled = false; Chris@17: Object.keys(tableSettings || {}).forEach(group => { Chris@17: Object.keys(tableSettings[group] || {}).forEach(n => { Chris@14: if (tableSettings[group][n].relationship === 'parent') { Chris@14: this.indentEnabled = true; Chris@0: } Chris@14: if (tableSettings[group][n].limit > 0) { Chris@14: this.maxDepth = tableSettings[group][n].limit; Chris@14: } Chris@14: }); Chris@14: }); Chris@0: if (this.indentEnabled) { Chris@0: /** Chris@0: * Total width of indents, set in makeDraggable. Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@0: this.indentCount = 1; Chris@0: // Find the width of indentations to measure mouse movements against. Chris@0: // Because the table doesn't need to start with any indentations, we Chris@0: // manually append 2 indentations in the first draggable row, measure Chris@0: // the offset, then remove. Chris@0: const indent = Drupal.theme('tableDragIndentation'); Chris@17: const testRow = $('') Chris@17: .addClass('draggable') Chris@17: .appendTo(table); Chris@17: const testCell = $('') Chris@17: .appendTo(testRow) Chris@17: .prepend(indent) Chris@17: .prepend(indent); Chris@0: const $indentation = testCell.find('.js-indentation'); Chris@0: Chris@0: /** Chris@0: * Chris@0: * @type {number} Chris@0: */ Chris@17: this.indentAmount = Chris@17: $indentation.get(1).offsetLeft - $indentation.get(0).offsetLeft; Chris@0: testRow.remove(); Chris@0: } Chris@0: Chris@0: // Make each applicable row draggable. Chris@0: // Match immediate children of the parent element to allow nesting. Chris@17: $table.find('> tr.draggable, > tbody > tr.draggable').each(function() { Chris@0: self.makeDraggable(this); Chris@0: }); Chris@0: Chris@0: // Add a link before the table for users to show or hide weight columns. Chris@17: $table.before( Chris@17: $('') Chris@17: .on( Chris@17: 'click', Chris@17: $.proxy(function(e) { Chris@17: e.preventDefault(); Chris@17: this.toggleColumns(); Chris@17: }, this), Chris@17: ) Chris@17: .wrap('
') Chris@17: .parent(), Chris@0: ); Chris@0: Chris@0: // Initialize the specified columns (for example, weight or parent columns) Chris@0: // to show or hide according to user preference. This aids accessibility Chris@0: // so that, e.g., screen reader users can choose to enter weight values and Chris@0: // manipulate form elements directly, rather than using drag-and-drop.. Chris@0: self.initColumns(); Chris@0: Chris@0: // Add event bindings to the document. The self variable is passed along Chris@0: // as event handlers do not have direct access to the tableDrag object. Chris@17: $(document).on('touchmove', event => Chris@17: self.dragRow(event.originalEvent.touches[0], self), Chris@17: ); Chris@17: $(document).on('touchend', event => Chris@17: self.dropRow(event.originalEvent.touches[0], self), Chris@17: ); Chris@0: $(document).on('mousemove pointermove', event => self.dragRow(event, self)); Chris@0: $(document).on('mouseup pointerup', event => self.dropRow(event, self)); Chris@0: Chris@0: // React to localStorage event showing or hiding weight columns. Chris@17: $(window).on( Chris@17: 'storage', Chris@17: $.proxy(function(e) { Chris@17: // Only react to 'Drupal.tableDrag.showWeight' value change. Chris@17: if (e.originalEvent.key === 'Drupal.tableDrag.showWeight') { Chris@17: // This was changed in another window, get the new value for this Chris@17: // window. Chris@17: showWeight = JSON.parse(e.originalEvent.newValue); Chris@17: this.displayColumns(showWeight); Chris@17: } Chris@17: }, this), Chris@17: ); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Initialize columns containing form elements to be hidden by default. Chris@0: * Chris@0: * Identify and mark each cell with a CSS class so we can easily toggle Chris@0: * show/hide it. Finally, hide columns if user does not have a Chris@0: * 'Drupal.tableDrag.showWeight' localStorage value. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.initColumns = function() { Chris@0: const $table = this.$table; Chris@0: let hidden; Chris@0: let cell; Chris@0: let columnIndex; Chris@17: Object.keys(this.tableSettings || {}).forEach(group => { Chris@14: // Find the first field in this group. Chris@17: Object.keys(this.tableSettings[group]).some(tableSetting => { Chris@17: const field = $table Chris@17: .find(`.${this.tableSettings[group][tableSetting].target}`) Chris@17: .eq(0); Chris@17: if (field.length && this.tableSettings[group][tableSetting].hidden) { Chris@17: hidden = this.tableSettings[group][tableSetting].hidden; Chris@17: cell = field.closest('td'); Chris@17: return true; Chris@0: } Chris@17: return false; Chris@17: }); Chris@0: Chris@14: // Mark the column containing this field so it can be hidden. Chris@14: if (hidden && cell[0]) { Chris@14: // Add 1 to our indexes. The nth-child selector is 1 based, not 0 Chris@14: // based. Match immediate children of the parent element to allow Chris@14: // nesting. Chris@17: columnIndex = Chris@17: cell Chris@17: .parent() Chris@17: .find('> td') Chris@17: .index(cell.get(0)) + 1; Chris@17: $table Chris@17: .find('> thead > tr, > tbody > tr, > tr') Chris@17: .each(this.addColspanClass(columnIndex)); Chris@0: } Chris@14: }); Chris@0: this.displayColumns(showWeight); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Mark cells that have colspan. Chris@0: * Chris@0: * In order to adjust the colspan instead of hiding them altogether. Chris@0: * Chris@0: * @param {number} columnIndex Chris@0: * The column index to add colspan class to. Chris@0: * Chris@0: * @return {function} Chris@0: * Function to add colspan class. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.addColspanClass = function(columnIndex) { Chris@17: return function() { Chris@0: // Get the columnIndex and adjust for any colspans in this row. Chris@0: const $row = $(this); Chris@0: let index = columnIndex; Chris@0: const cells = $row.children(); Chris@0: let cell; Chris@17: cells.each(function(n) { Chris@0: if (n < index && this.colSpan && this.colSpan > 1) { Chris@0: index -= this.colSpan - 1; Chris@0: } Chris@0: }); Chris@0: if (index > 0) { Chris@0: cell = cells.filter(`:nth-child(${index})`); Chris@0: if (cell[0].colSpan && cell[0].colSpan > 1) { Chris@0: // If this cell has a colspan, mark it so we can reduce the colspan. Chris@0: cell.addClass('tabledrag-has-colspan'); Chris@17: } else { Chris@0: // Mark this cell so we can hide it. Chris@0: cell.addClass('tabledrag-hide'); Chris@0: } Chris@0: } Chris@0: }; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Hide or display weight columns. Triggers an event on change. Chris@0: * Chris@0: * @fires event:columnschange Chris@0: * Chris@0: * @param {bool} displayWeight Chris@0: * 'true' will show weight columns. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.displayColumns = function(displayWeight) { Chris@0: if (displayWeight) { Chris@0: this.showColumns(); Chris@0: } Chris@0: // Default action is to hide columns. Chris@0: else { Chris@0: this.hideColumns(); Chris@0: } Chris@0: // Trigger an event to allow other scripts to react to this display change. Chris@0: // Force the extra parameter as a bool. Chris@17: $('table') Chris@17: .findOnce('tabledrag') Chris@17: .trigger('columnschange', !!displayWeight); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Toggle the weight column depending on 'showWeight' value. Chris@0: * Chris@0: * Store only default override. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.toggleColumns = function() { Chris@0: showWeight = !showWeight; Chris@0: this.displayColumns(showWeight); Chris@0: if (showWeight) { Chris@0: // Save default override. Chris@0: localStorage.setItem('Drupal.tableDrag.showWeight', showWeight); Chris@17: } else { Chris@0: // Reset the value to its default. Chris@0: localStorage.removeItem('Drupal.tableDrag.showWeight'); Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Hide the columns containing weight/parent form elements. Chris@0: * Chris@0: * Undo showColumns(). Chris@0: */ Chris@17: Drupal.tableDrag.prototype.hideColumns = function() { Chris@0: const $tables = $('table').findOnce('tabledrag'); Chris@0: // Hide weight/parent cells and headers. Chris@0: $tables.find('.tabledrag-hide').css('display', 'none'); Chris@0: // Show TableDrag handles. Chris@0: $tables.find('.tabledrag-handle').css('display', ''); Chris@0: // Reduce the colspan of any effected multi-span columns. Chris@17: $tables.find('.tabledrag-has-colspan').each(function() { Chris@0: this.colSpan = this.colSpan - 1; Chris@0: }); Chris@0: // Change link text. Chris@0: $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Show the columns containing weight/parent form elements. Chris@0: * Chris@0: * Undo hideColumns(). Chris@0: */ Chris@17: Drupal.tableDrag.prototype.showColumns = function() { Chris@0: const $tables = $('table').findOnce('tabledrag'); Chris@0: // Show weight/parent cells and headers. Chris@0: $tables.find('.tabledrag-hide').css('display', ''); Chris@0: // Hide TableDrag handles. Chris@0: $tables.find('.tabledrag-handle').css('display', 'none'); Chris@0: // Increase the colspan for any columns where it was previously reduced. Chris@17: $tables.find('.tabledrag-has-colspan').each(function() { Chris@0: this.colSpan = this.colSpan + 1; Chris@0: }); Chris@0: // Change link text. Chris@0: $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Find the target used within a particular row and group. Chris@0: * Chris@0: * @param {string} group Chris@0: * Group selector. Chris@0: * @param {HTMLElement} row Chris@0: * The row HTML element. Chris@0: * Chris@0: * @return {object} Chris@0: * The table row settings. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.rowSettings = function(group, row) { Chris@0: const field = $(row).find(`.${group}`); Chris@0: const tableSettingsGroup = this.tableSettings[group]; Chris@17: return Object.keys(tableSettingsGroup) Chris@17: .map(delta => { Chris@0: const targetClass = tableSettingsGroup[delta].target; Chris@17: let rowSettings; Chris@0: if (field.is(`.${targetClass}`)) { Chris@0: // Return a copy of the row settings. Chris@17: rowSettings = {}; Chris@17: Object.keys(tableSettingsGroup[delta]).forEach(n => { Chris@17: rowSettings[n] = tableSettingsGroup[delta][n]; Chris@17: }); Chris@0: } Chris@17: return rowSettings; Chris@17: }) Chris@17: .filter(rowSetting => rowSetting)[0]; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Take an item and add event handlers to make it become draggable. Chris@0: * Chris@0: * @param {HTMLElement} item Chris@0: * The item to add event handlers to. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.makeDraggable = function(item) { Chris@0: const self = this; Chris@0: const $item = $(item); Chris@0: // Add a class to the title link. Chris@17: $item Chris@17: .find('td:first-of-type') Chris@17: .find('a') Chris@17: .addClass('menu-item__link'); Chris@0: // Create the handle. Chris@17: const handle = $( Chris@17: '
 
', Chris@17: ).attr('title', Drupal.t('Drag to re-order')); Chris@0: // Insert the handle after indentations (if any). Chris@17: const $indentationLast = $item Chris@17: .find('td:first-of-type') Chris@17: .find('.js-indentation') Chris@17: .eq(-1); Chris@0: if ($indentationLast.length) { Chris@0: $indentationLast.after(handle); Chris@0: // Update the total width of indentation in this entire table. Chris@17: self.indentCount = Math.max( Chris@17: $item.find('.js-indentation').length, Chris@17: self.indentCount, Chris@17: ); Chris@17: } else { Chris@17: $item Chris@17: .find('td') Chris@17: .eq(0) Chris@17: .prepend(handle); Chris@0: } Chris@0: Chris@17: handle.on('mousedown touchstart pointerdown', event => { Chris@0: event.preventDefault(); Chris@0: if (event.originalEvent.type === 'touchstart') { Chris@0: event = event.originalEvent.touches[0]; Chris@0: } Chris@0: self.dragStart(event, self, item); Chris@0: }); Chris@0: Chris@0: // Prevent the anchor tag from jumping us to the top of the page. Chris@17: handle.on('click', e => { Chris@0: e.preventDefault(); Chris@0: }); Chris@0: Chris@0: // Set blur cleanup when a handle is focused. Chris@0: handle.on('focus', () => { Chris@0: self.safeBlur = true; Chris@0: }); Chris@0: Chris@0: // On blur, fire the same function as a touchend/mouseup. This is used to Chris@0: // update values after a row has been moved through the keyboard support. Chris@17: handle.on('blur', event => { Chris@0: if (self.rowObject && self.safeBlur) { Chris@0: self.dropRow(event, self); Chris@0: } Chris@0: }); Chris@0: Chris@0: // Add arrow-key support to the handle. Chris@17: handle.on('keydown', event => { Chris@0: // If a rowObject doesn't yet exist and this isn't the tab key. Chris@0: if (event.keyCode !== 9 && !self.rowObject) { Chris@17: self.rowObject = new self.row( Chris@17: item, Chris@17: 'keyboard', Chris@17: self.indentEnabled, Chris@17: self.maxDepth, Chris@17: true, Chris@17: ); Chris@0: } Chris@0: Chris@0: let keyChange = false; Chris@0: let groupHeight; Chris@0: Chris@0: /* eslint-disable no-fallthrough */ Chris@0: Chris@0: switch (event.keyCode) { Chris@0: // Left arrow. Chris@0: case 37: Chris@0: // Safari left arrow. Chris@0: case 63234: Chris@0: keyChange = true; Chris@0: self.rowObject.indent(-1 * self.rtl); Chris@0: break; Chris@0: Chris@0: // Up arrow. Chris@0: case 38: Chris@0: // Safari up arrow. Chris@14: case 63232: { Chris@17: let $previousRow = $(self.rowObject.element) Chris@17: .prev('tr') Chris@17: .eq(0); Chris@14: let previousRow = $previousRow.get(0); Chris@0: while (previousRow && $previousRow.is(':hidden')) { Chris@17: $previousRow = $(previousRow) Chris@17: .prev('tr') Chris@17: .eq(0); Chris@0: previousRow = $previousRow.get(0); Chris@0: } Chris@0: if (previousRow) { Chris@0: // Do not allow the onBlur cleanup. Chris@0: self.safeBlur = false; Chris@0: self.rowObject.direction = 'up'; Chris@0: keyChange = true; Chris@0: Chris@0: if ($(item).is('.tabledrag-root')) { Chris@0: // Swap with the previous top-level row. Chris@0: groupHeight = 0; Chris@17: while ( Chris@17: previousRow && Chris@17: $previousRow.find('.js-indentation').length Chris@17: ) { Chris@17: $previousRow = $(previousRow) Chris@17: .prev('tr') Chris@17: .eq(0); Chris@0: previousRow = $previousRow.get(0); Chris@17: groupHeight += $previousRow.is(':hidden') Chris@17: ? 0 Chris@17: : previousRow.offsetHeight; Chris@0: } Chris@0: if (previousRow) { Chris@0: self.rowObject.swap('before', previousRow); Chris@0: // No need to check for indentation, 0 is the only valid one. Chris@0: window.scrollBy(0, -groupHeight); Chris@0: } Chris@17: } else if ( Chris@17: self.table.tBodies[0].rows[0] !== previousRow || Chris@17: $previousRow.is('.draggable') Chris@17: ) { Chris@0: // Swap with the previous row (unless previous row is the first Chris@0: // one and undraggable). Chris@0: self.rowObject.swap('before', previousRow); Chris@0: self.rowObject.interval = null; Chris@0: self.rowObject.indent(0); Chris@0: window.scrollBy(0, -parseInt(item.offsetHeight, 10)); Chris@0: } Chris@0: // Regain focus after the DOM manipulation. Chris@0: handle.trigger('focus'); Chris@0: } Chris@0: break; Chris@14: } Chris@0: // Right arrow. Chris@0: case 39: Chris@0: // Safari right arrow. Chris@0: case 63235: Chris@0: keyChange = true; Chris@0: self.rowObject.indent(self.rtl); Chris@0: break; Chris@0: Chris@0: // Down arrow. Chris@0: case 40: Chris@0: // Safari down arrow. Chris@14: case 63233: { Chris@17: let $nextRow = $(self.rowObject.group) Chris@17: .eq(-1) Chris@17: .next('tr') Chris@17: .eq(0); Chris@14: let nextRow = $nextRow.get(0); Chris@0: while (nextRow && $nextRow.is(':hidden')) { Chris@17: $nextRow = $(nextRow) Chris@17: .next('tr') Chris@17: .eq(0); Chris@0: nextRow = $nextRow.get(0); Chris@0: } Chris@0: if (nextRow) { Chris@0: // Do not allow the onBlur cleanup. Chris@0: self.safeBlur = false; Chris@0: self.rowObject.direction = 'down'; Chris@0: keyChange = true; Chris@0: Chris@0: if ($(item).is('.tabledrag-root')) { Chris@0: // Swap with the next group (necessarily a top-level one). Chris@0: groupHeight = 0; Chris@17: const nextGroup = new self.row( Chris@17: nextRow, Chris@17: 'keyboard', Chris@17: self.indentEnabled, Chris@17: self.maxDepth, Chris@17: false, Chris@17: ); Chris@0: if (nextGroup) { Chris@17: $(nextGroup.group).each(function() { Chris@0: groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; Chris@0: }); Chris@17: const nextGroupRow = $(nextGroup.group) Chris@17: .eq(-1) Chris@17: .get(0); Chris@0: self.rowObject.swap('after', nextGroupRow); Chris@0: // No need to check for indentation, 0 is the only valid one. Chris@0: window.scrollBy(0, parseInt(groupHeight, 10)); Chris@0: } Chris@17: } else { Chris@0: // Swap with the next row. Chris@0: self.rowObject.swap('after', nextRow); Chris@0: self.rowObject.interval = null; Chris@0: self.rowObject.indent(0); Chris@0: window.scrollBy(0, parseInt(item.offsetHeight, 10)); Chris@0: } Chris@0: // Regain focus after the DOM manipulation. Chris@0: handle.trigger('focus'); Chris@0: } Chris@0: break; Chris@14: } Chris@0: } Chris@0: Chris@0: /* eslint-enable no-fallthrough */ Chris@0: Chris@0: if (self.rowObject && self.rowObject.changed === true) { Chris@0: $(item).addClass('drag'); Chris@0: if (self.oldRowElement) { Chris@0: $(self.oldRowElement).removeClass('drag-previous'); Chris@0: } Chris@0: self.oldRowElement = item; Chris@0: if (self.striping === true) { Chris@0: self.restripeTable(); Chris@0: } Chris@0: self.onDrag(); Chris@0: } Chris@0: Chris@0: // Returning false if we have an arrow key to prevent scrolling. Chris@0: if (keyChange) { Chris@0: return false; Chris@0: } Chris@0: }); Chris@0: Chris@0: // Compatibility addition, return false on keypress to prevent unwanted Chris@0: // scrolling. IE and Safari will suppress scrolling on keydown, but all Chris@0: // other browsers need to return false on keypress. Chris@0: // http://www.quirksmode.org/js/keys.html Chris@17: handle.on('keypress', event => { Chris@0: /* eslint-disable no-fallthrough */ Chris@0: Chris@0: switch (event.keyCode) { Chris@0: // Left arrow. Chris@0: case 37: Chris@0: // Up arrow. Chris@0: case 38: Chris@0: // Right arrow. Chris@0: case 39: Chris@0: // Down arrow. Chris@0: case 40: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /* eslint-enable no-fallthrough */ Chris@0: }); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Pointer event initiator, creates drag object and information. Chris@0: * Chris@0: * @param {jQuery.Event} event Chris@0: * The event object that trigger the drag. Chris@0: * @param {Drupal.tableDrag} self Chris@0: * The drag handle. Chris@0: * @param {HTMLElement} item Chris@0: * The item that that is being dragged. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.dragStart = function(event, self, item) { Chris@0: // Create a new dragObject recording the pointer information. Chris@0: self.dragObject = {}; Chris@0: self.dragObject.initOffset = self.getPointerOffset(item, event); Chris@0: self.dragObject.initPointerCoords = self.pointerCoords(event); Chris@0: if (self.indentEnabled) { Chris@0: self.dragObject.indentPointerPos = self.dragObject.initPointerCoords; Chris@0: } Chris@0: Chris@0: // If there's a lingering row object from the keyboard, remove its focus. Chris@0: if (self.rowObject) { Chris@17: $(self.rowObject.element) Chris@17: .find('a.tabledrag-handle') Chris@17: .trigger('blur'); Chris@0: } Chris@0: Chris@0: // Create a new rowObject for manipulation of this row. Chris@17: self.rowObject = new self.row( Chris@17: item, Chris@17: 'pointer', Chris@17: self.indentEnabled, Chris@17: self.maxDepth, Chris@17: true, Chris@17: ); Chris@0: Chris@0: // Save the position of the table. Chris@0: self.table.topY = $(self.table).offset().top; Chris@0: self.table.bottomY = self.table.topY + self.table.offsetHeight; Chris@0: Chris@0: // Add classes to the handle and row. Chris@0: $(item).addClass('drag'); Chris@0: Chris@0: // Set the document to use the move cursor during drag. Chris@0: $('body').addClass('drag'); Chris@0: if (self.oldRowElement) { Chris@0: $(self.oldRowElement).removeClass('drag-previous'); Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Pointer movement handler, bound to document. Chris@0: * Chris@0: * @param {jQuery.Event} event Chris@0: * The pointer event. Chris@0: * @param {Drupal.tableDrag} self Chris@0: * The tableDrag instance. Chris@0: * Chris@0: * @return {bool|undefined} Chris@0: * Undefined if no dragObject is defined, false otherwise. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.dragRow = function(event, self) { Chris@0: if (self.dragObject) { Chris@0: self.currentPointerCoords = self.pointerCoords(event); Chris@0: const y = self.currentPointerCoords.y - self.dragObject.initOffset.y; Chris@0: const x = self.currentPointerCoords.x - self.dragObject.initOffset.x; Chris@0: Chris@0: // Check for row swapping and vertical scrolling. Chris@0: if (y !== self.oldY) { Chris@0: self.rowObject.direction = y > self.oldY ? 'down' : 'up'; Chris@0: // Update the old value. Chris@0: self.oldY = y; Chris@0: // Check if the window should be scrolled (and how fast). Chris@0: const scrollAmount = self.checkScroll(self.currentPointerCoords.y); Chris@0: // Stop any current scrolling. Chris@0: clearInterval(self.scrollInterval); Chris@0: // Continue scrolling if the mouse has moved in the scroll direction. Chris@17: if ( Chris@17: (scrollAmount > 0 && self.rowObject.direction === 'down') || Chris@17: (scrollAmount < 0 && self.rowObject.direction === 'up') Chris@17: ) { Chris@0: self.setScroll(scrollAmount); Chris@0: } Chris@0: Chris@0: // If we have a valid target, perform the swap and restripe the table. Chris@0: const currentRow = self.findDropTargetRow(x, y); Chris@0: if (currentRow) { Chris@0: if (self.rowObject.direction === 'down') { Chris@0: self.rowObject.swap('after', currentRow, self); Chris@17: } else { Chris@0: self.rowObject.swap('before', currentRow, self); Chris@0: } Chris@0: if (self.striping === true) { Chris@0: self.restripeTable(); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Similar to row swapping, handle indentations. Chris@0: if (self.indentEnabled) { Chris@17: const xDiff = Chris@17: self.currentPointerCoords.x - self.dragObject.indentPointerPos.x; Chris@0: // Set the number of indentations the pointer has been moved left or Chris@0: // right. Chris@0: const indentDiff = Math.round(xDiff / self.indentAmount); Chris@0: // Indent the row with our estimated diff, which may be further Chris@0: // restricted according to the rows around this row. Chris@0: const indentChange = self.rowObject.indent(indentDiff); Chris@0: // Update table and pointer indentations. Chris@17: self.dragObject.indentPointerPos.x += Chris@17: self.indentAmount * indentChange * self.rtl; Chris@0: self.indentCount = Math.max(self.indentCount, self.rowObject.indents); Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Pointerup behavior. Chris@0: * Chris@0: * @param {jQuery.Event} event Chris@0: * The pointer event. Chris@0: * @param {Drupal.tableDrag} self Chris@0: * The tableDrag instance. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.dropRow = function(event, self) { Chris@0: let droppedRow; Chris@0: let $droppedRow; Chris@0: Chris@0: // Drop row functionality. Chris@0: if (self.rowObject !== null) { Chris@0: droppedRow = self.rowObject.element; Chris@0: $droppedRow = $(droppedRow); Chris@0: // The row is already in the right place so we just release it. Chris@0: if (self.rowObject.changed === true) { Chris@0: // Update the fields in the dropped row. Chris@0: self.updateFields(droppedRow); Chris@0: Chris@0: // If a setting exists for affecting the entire group, update all the Chris@0: // fields in the entire dragged group. Chris@17: Object.keys(self.tableSettings || {}).forEach(group => { Chris@14: const rowSettings = self.rowSettings(group, droppedRow); Chris@14: if (rowSettings.relationship === 'group') { Chris@17: Object.keys(self.rowObject.children || {}).forEach(n => { Chris@14: self.updateField(self.rowObject.children[n], group); Chris@14: }); Chris@0: } Chris@14: }); Chris@0: Chris@0: self.rowObject.markChanged(); Chris@0: if (self.changed === false) { Chris@17: $(Drupal.theme('tableDragChangedWarning')) Chris@17: .insertBefore(self.table) Chris@17: .hide() Chris@17: .fadeIn('slow'); Chris@0: self.changed = true; Chris@0: } Chris@0: } Chris@0: Chris@0: if (self.indentEnabled) { Chris@0: self.rowObject.removeIndentClasses(); Chris@0: } Chris@0: if (self.oldRowElement) { Chris@0: $(self.oldRowElement).removeClass('drag-previous'); Chris@0: } Chris@0: $droppedRow.removeClass('drag').addClass('drag-previous'); Chris@0: self.oldRowElement = droppedRow; Chris@0: self.onDrop(); Chris@0: self.rowObject = null; Chris@0: } Chris@0: Chris@0: // Functionality specific only to pointerup events. Chris@0: if (self.dragObject !== null) { Chris@0: self.dragObject = null; Chris@0: $('body').removeClass('drag'); Chris@0: clearInterval(self.scrollInterval); Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Get the coordinates from the event (allowing for browser differences). Chris@0: * Chris@0: * @param {jQuery.Event} event Chris@0: * The pointer event. Chris@0: * Chris@0: * @return {object} Chris@0: * An object with `x` and `y` keys indicating the position. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.pointerCoords = function(event) { Chris@0: if (event.pageX || event.pageY) { Chris@0: return { x: event.pageX, y: event.pageY }; Chris@0: } Chris@0: return { Chris@17: x: event.clientX + document.body.scrollLeft - document.body.clientLeft, Chris@17: y: event.clientY + document.body.scrollTop - document.body.clientTop, Chris@0: }; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Get the event offset from the target element. Chris@0: * Chris@0: * Given a target element and a pointer event, get the event offset from that Chris@0: * element. To do this we need the element's position and the target position. Chris@0: * Chris@0: * @param {HTMLElement} target Chris@0: * The target HTML element. Chris@0: * @param {jQuery.Event} event Chris@0: * The pointer event. Chris@0: * Chris@0: * @return {object} Chris@0: * An object with `x` and `y` keys indicating the position. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.getPointerOffset = function(target, event) { Chris@0: const docPos = $(target).offset(); Chris@0: const pointerPos = this.pointerCoords(event); Chris@0: return { x: pointerPos.x - docPos.left, y: pointerPos.y - docPos.top }; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Find the row the mouse is currently over. Chris@0: * Chris@0: * This row is then taken and swapped with the one being dragged. Chris@0: * Chris@0: * @param {number} x Chris@0: * The x coordinate of the mouse on the page (not the screen). Chris@0: * @param {number} y Chris@0: * The y coordinate of the mouse on the page (not the screen). Chris@0: * Chris@0: * @return {*} Chris@0: * The drop target row, if found. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.findDropTargetRow = function(x, y) { Chris@0: const rows = $(this.table.tBodies[0].rows).not(':hidden'); Chris@0: for (let n = 0; n < rows.length; n++) { Chris@0: let row = rows[n]; Chris@0: let $row = $(row); Chris@0: const rowY = $row.offset().top; Chris@14: let rowHeight; Chris@0: // Because Safari does not report offsetHeight on table rows, but does on Chris@0: // table cells, grab the firstChild of the row and use that instead. Chris@0: // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. Chris@0: if (row.offsetHeight === 0) { Chris@0: rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; Chris@0: } Chris@0: // Other browsers. Chris@0: else { Chris@0: rowHeight = parseInt(row.offsetHeight, 10) / 2; Chris@0: } Chris@0: Chris@0: // Because we always insert before, we need to offset the height a bit. Chris@17: if (y > rowY - rowHeight && y < rowY + rowHeight) { Chris@0: if (this.indentEnabled) { Chris@0: // Check that this row is not a child of the row being dragged. Chris@17: if ( Chris@17: Object.keys(this.rowObject.group).some( Chris@17: o => this.rowObject.group[o] === row, Chris@17: ) Chris@17: ) { Chris@17: return null; Chris@0: } Chris@0: } Chris@14: // Do not allow a row to be swapped with itself. Chris@14: else if (row === this.rowObject.element) { Chris@14: return null; Chris@0: } Chris@0: Chris@0: // Check that swapping with this row is allowed. Chris@0: if (!this.rowObject.isValidSwap(row)) { Chris@0: return null; Chris@0: } Chris@0: Chris@0: // We may have found the row the mouse just passed over, but it doesn't Chris@0: // take into account hidden rows. Skip backwards until we find a Chris@0: // draggable row. Chris@0: while ($row.is(':hidden') && $row.prev('tr').is(':hidden')) { Chris@0: $row = $row.prev('tr:first-of-type'); Chris@0: row = $row.get(0); Chris@0: } Chris@0: return row; Chris@0: } Chris@0: } Chris@0: return null; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * After the row is dropped, update the table fields. Chris@0: * Chris@0: * @param {HTMLElement} changedRow Chris@0: * DOM object for the row that was just dropped. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.updateFields = function(changedRow) { Chris@17: Object.keys(this.tableSettings || {}).forEach(group => { Chris@14: // Each group may have a different setting for relationship, so we find Chris@14: // the source rows for each separately. Chris@14: this.updateField(changedRow, group); Chris@14: }); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * After the row is dropped, update a single table field. Chris@0: * Chris@0: * @param {HTMLElement} changedRow Chris@0: * DOM object for the row that was just dropped. Chris@0: * @param {string} group Chris@0: * The settings group on which field updates will occur. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.updateField = function(changedRow, group) { Chris@0: let rowSettings = this.rowSettings(group, changedRow); Chris@0: const $changedRow = $(changedRow); Chris@0: let sourceRow; Chris@0: let $previousRow; Chris@0: let previousRow; Chris@0: let useSibling; Chris@0: // Set the row as its own target. Chris@17: if ( Chris@17: rowSettings.relationship === 'self' || Chris@17: rowSettings.relationship === 'group' Chris@17: ) { Chris@0: sourceRow = changedRow; Chris@0: } Chris@0: // Siblings are easy, check previous and next rows. Chris@0: else if (rowSettings.relationship === 'sibling') { Chris@0: $previousRow = $changedRow.prev('tr:first-of-type'); Chris@0: previousRow = $previousRow.get(0); Chris@0: const $nextRow = $changedRow.next('tr:first-of-type'); Chris@0: const nextRow = $nextRow.get(0); Chris@0: sourceRow = changedRow; Chris@17: if ( Chris@17: $previousRow.is('.draggable') && Chris@17: $previousRow.find(`.${group}`).length Chris@17: ) { Chris@0: if (this.indentEnabled) { Chris@17: if ( Chris@17: $previousRow.find('.js-indentations').length === Chris@17: $changedRow.find('.js-indentations').length Chris@17: ) { Chris@0: sourceRow = previousRow; Chris@0: } Chris@17: } else { Chris@0: sourceRow = previousRow; Chris@0: } Chris@17: } else if ( Chris@17: $nextRow.is('.draggable') && Chris@17: $nextRow.find(`.${group}`).length Chris@17: ) { Chris@0: if (this.indentEnabled) { Chris@17: if ( Chris@17: $nextRow.find('.js-indentations').length === Chris@17: $changedRow.find('.js-indentations').length Chris@17: ) { Chris@0: sourceRow = nextRow; Chris@0: } Chris@17: } else { Chris@0: sourceRow = nextRow; Chris@0: } Chris@0: } Chris@0: } Chris@0: // Parents, look up the tree until we find a field not in this group. Chris@0: // Go up as many parents as indentations in the changed row. Chris@0: else if (rowSettings.relationship === 'parent') { Chris@0: $previousRow = $changedRow.prev('tr'); Chris@0: previousRow = $previousRow; Chris@17: while ( Chris@17: $previousRow.length && Chris@17: $previousRow.find('.js-indentation').length >= this.rowObject.indents Chris@17: ) { Chris@0: $previousRow = $previousRow.prev('tr'); Chris@0: previousRow = $previousRow; Chris@0: } Chris@0: // If we found a row. Chris@0: if ($previousRow.length) { Chris@0: sourceRow = $previousRow.get(0); Chris@0: } Chris@0: // Otherwise we went all the way to the left of the table without finding Chris@0: // a parent, meaning this item has been placed at the root level. Chris@0: else { Chris@0: // Use the first row in the table as source, because it's guaranteed to Chris@0: // be at the root level. Find the first item, then compare this row Chris@0: // against it as a sibling. Chris@17: sourceRow = $(this.table) Chris@17: .find('tr.draggable:first-of-type') Chris@17: .get(0); Chris@0: if (sourceRow === this.rowObject.element) { Chris@17: sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]) Chris@17: .next('tr.draggable') Chris@17: .get(0); Chris@0: } Chris@0: useSibling = true; Chris@0: } Chris@0: } Chris@0: Chris@0: // Because we may have moved the row from one category to another, Chris@0: // take a look at our sibling and borrow its sources and targets. Chris@0: this.copyDragClasses(sourceRow, changedRow, group); Chris@0: rowSettings = this.rowSettings(group, changedRow); Chris@0: Chris@0: // In the case that we're looking for a parent, but the row is at the top Chris@0: // of the tree, copy our sibling's values. Chris@0: if (useSibling) { Chris@0: rowSettings.relationship = 'sibling'; Chris@0: rowSettings.source = rowSettings.target; Chris@0: } Chris@0: Chris@0: const targetClass = `.${rowSettings.target}`; Chris@0: const targetElement = $changedRow.find(targetClass).get(0); Chris@0: Chris@0: // Check if a target element exists in this row. Chris@0: if (targetElement) { Chris@0: const sourceClass = `.${rowSettings.source}`; Chris@0: const sourceElement = $(sourceClass, sourceRow).get(0); Chris@0: switch (rowSettings.action) { Chris@0: case 'depth': Chris@0: // Get the depth of the target row. Chris@17: targetElement.value = $(sourceElement) Chris@17: .closest('tr') Chris@17: .find('.js-indentation').length; Chris@0: break; Chris@0: Chris@0: case 'match': Chris@0: // Update the value. Chris@0: targetElement.value = sourceElement.value; Chris@0: break; Chris@0: Chris@14: case 'order': { Chris@14: const siblings = this.rowObject.findSiblings(rowSettings); Chris@0: if ($(targetElement).is('select')) { Chris@0: // Get a list of acceptable values. Chris@0: const values = []; Chris@17: $(targetElement) Chris@17: .find('option') Chris@17: .each(function() { Chris@17: values.push(this.value); Chris@17: }); Chris@0: const maxVal = values[values.length - 1]; Chris@0: // Populate the values in the siblings. Chris@17: $(siblings) Chris@17: .find(targetClass) Chris@17: .each(function() { Chris@17: // If there are more items than possible values, assign the Chris@17: // maximum value to the row. Chris@17: if (values.length > 0) { Chris@17: this.value = values.shift(); Chris@17: } else { Chris@17: this.value = maxVal; Chris@17: } Chris@17: }); Chris@17: } else { Chris@0: // Assume a numeric input field. Chris@17: let weight = Chris@17: parseInt( Chris@17: $(siblings[0]) Chris@17: .find(targetClass) Chris@17: .val(), Chris@17: 10, Chris@17: ) || 0; Chris@17: $(siblings) Chris@17: .find(targetClass) Chris@17: .each(function() { Chris@17: this.value = weight; Chris@17: weight++; Chris@17: }); Chris@0: } Chris@0: break; Chris@14: } Chris@0: } Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Copy all tableDrag related classes from one row to another. Chris@0: * Chris@0: * Copy all special tableDrag classes from one row's form elements to a Chris@0: * different one, removing any special classes that the destination row Chris@0: * may have had. Chris@0: * Chris@0: * @param {HTMLElement} sourceRow Chris@0: * The element for the source row. Chris@0: * @param {HTMLElement} targetRow Chris@0: * The element for the target row. Chris@0: * @param {string} group Chris@0: * The group selector. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.copyDragClasses = function( Chris@17: sourceRow, Chris@17: targetRow, Chris@17: group, Chris@17: ) { Chris@0: const sourceElement = $(sourceRow).find(`.${group}`); Chris@0: const targetElement = $(targetRow).find(`.${group}`); Chris@0: if (sourceElement.length && targetElement.length) { Chris@0: targetElement[0].className = sourceElement[0].className; Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Check the suggested scroll of the table. Chris@0: * Chris@0: * @param {number} cursorY Chris@0: * The Y position of the cursor. Chris@0: * Chris@0: * @return {number} Chris@0: * The suggested scroll. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.checkScroll = function(cursorY) { Chris@0: const de = document.documentElement; Chris@0: const b = document.body; Chris@0: Chris@17: const windowHeight = Chris@17: window.innerHeight || Chris@17: (de.clientHeight && de.clientWidth !== 0 Chris@17: ? de.clientHeight Chris@17: : b.offsetHeight); Chris@14: this.windowHeight = windowHeight; Chris@0: let scrollY; Chris@0: if (document.all) { Chris@14: scrollY = !de.scrollTop ? b.scrollTop : de.scrollTop; Chris@17: } else { Chris@14: scrollY = window.pageYOffset ? window.pageYOffset : window.scrollY; Chris@0: } Chris@14: this.scrollY = scrollY; Chris@0: const trigger = this.scrollSettings.trigger; Chris@0: let delta = 0; Chris@0: Chris@0: // Return a scroll speed relative to the edge of the screen. Chris@0: if (cursorY - scrollY > windowHeight - trigger) { Chris@17: delta = trigger / (windowHeight + scrollY - cursorY); Chris@17: delta = delta > 0 && delta < trigger ? delta : trigger; Chris@0: return delta * this.scrollSettings.amount; Chris@0: } Chris@17: if (cursorY - scrollY < trigger) { Chris@0: delta = trigger / (cursorY - scrollY); Chris@17: delta = delta > 0 && delta < trigger ? delta : trigger; Chris@0: return -delta * this.scrollSettings.amount; Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Set the scroll for the table. Chris@0: * Chris@0: * @param {number} scrollAmount Chris@0: * The amount of scroll to apply to the window. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.setScroll = function(scrollAmount) { Chris@0: const self = this; Chris@0: Chris@0: this.scrollInterval = setInterval(() => { Chris@0: // Update the scroll values stored in the object. Chris@0: self.checkScroll(self.currentPointerCoords.y); Chris@0: const aboveTable = self.scrollY > self.table.topY; Chris@0: const belowTable = self.scrollY + self.windowHeight < self.table.bottomY; Chris@17: if ( Chris@17: (scrollAmount > 0 && belowTable) || Chris@17: (scrollAmount < 0 && aboveTable) Chris@17: ) { Chris@0: window.scrollBy(0, scrollAmount); Chris@0: } Chris@0: }, this.scrollSettings.interval); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Command to restripe table properly. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.restripeTable = function() { Chris@0: // :even and :odd are reversed because jQuery counts from 0 and Chris@0: // we count from 1, so we're out of sync. Chris@0: // Match immediate children of the parent element to allow nesting. Chris@14: $(this.table) Chris@14: .find('> tbody > tr.draggable, > tr.draggable') Chris@0: .filter(':visible') Chris@14: .filter(':odd') Chris@14: .removeClass('odd') Chris@14: .addClass('even') Chris@14: .end() Chris@14: .filter(':even') Chris@14: .removeClass('even') Chris@14: .addClass('odd'); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Stub function. Allows a custom handler when a row begins dragging. Chris@0: * Chris@0: * @return {null} Chris@0: * Returns null when the stub function is used. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.onDrag = function() { Chris@0: return null; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Stub function. Allows a custom handler when a row is dropped. Chris@0: * Chris@0: * @return {null} Chris@0: * Returns null when the stub function is used. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.onDrop = function() { Chris@0: return null; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Constructor to make a new object to manipulate a table row. Chris@0: * Chris@0: * @param {HTMLElement} tableRow Chris@0: * The DOM element for the table row we will be manipulating. Chris@0: * @param {string} method Chris@0: * The method in which this row is being moved. Either 'keyboard' or Chris@0: * 'mouse'. Chris@0: * @param {bool} indentEnabled Chris@0: * Whether the containing table uses indentations. Used for optimizations. Chris@0: * @param {number} maxDepth Chris@0: * The maximum amount of indentations this row may contain. Chris@0: * @param {bool} addClasses Chris@0: * Whether we want to add classes to this row to indicate child Chris@0: * relationships. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row = function( Chris@17: tableRow, Chris@17: method, Chris@17: indentEnabled, Chris@17: maxDepth, Chris@17: addClasses, Chris@17: ) { Chris@0: const $tableRow = $(tableRow); Chris@0: Chris@0: this.element = tableRow; Chris@0: this.method = method; Chris@0: this.group = [tableRow]; Chris@0: this.groupDepth = $tableRow.find('.js-indentation').length; Chris@0: this.changed = false; Chris@0: this.table = $tableRow.closest('table')[0]; Chris@0: this.indentEnabled = indentEnabled; Chris@0: this.maxDepth = maxDepth; Chris@0: // Direction the row is being moved. Chris@0: this.direction = ''; Chris@0: if (this.indentEnabled) { Chris@0: this.indents = $tableRow.find('.js-indentation').length; Chris@0: this.children = this.findChildren(addClasses); Chris@0: this.group = $.merge(this.group, this.children); Chris@0: // Find the depth of this entire group. Chris@0: for (let n = 0; n < this.group.length; n++) { Chris@17: this.groupDepth = Math.max( Chris@17: $(this.group[n]).find('.js-indentation').length, Chris@17: this.groupDepth, Chris@17: ); Chris@0: } Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Find all children of rowObject by indentation. Chris@0: * Chris@0: * @param {bool} addClasses Chris@0: * Whether we want to add classes to this row to indicate child Chris@0: * relationships. Chris@0: * Chris@0: * @return {Array} Chris@0: * An array of children of the row. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.findChildren = function(addClasses) { Chris@0: const parentIndentation = this.indents; Chris@0: let currentRow = $(this.element, this.table).next('tr.draggable'); Chris@0: const rows = []; Chris@0: let child = 0; Chris@0: Chris@0: function rowIndentation(indentNum, el) { Chris@0: const self = $(el); Chris@17: if (child === 1 && indentNum === parentIndentation) { Chris@0: self.addClass('tree-child-first'); Chris@0: } Chris@0: if (indentNum === parentIndentation) { Chris@0: self.addClass('tree-child'); Chris@17: } else if (indentNum > parentIndentation) { Chris@0: self.addClass('tree-child-horizontal'); Chris@0: } Chris@0: } Chris@0: Chris@0: while (currentRow.length) { Chris@0: // A greater indentation indicates this is a child. Chris@0: if (currentRow.find('.js-indentation').length > parentIndentation) { Chris@0: child++; Chris@0: rows.push(currentRow[0]); Chris@0: if (addClasses) { Chris@0: currentRow.find('.js-indentation').each(rowIndentation); Chris@0: } Chris@17: } else { Chris@0: break; Chris@0: } Chris@0: currentRow = currentRow.next('tr.draggable'); Chris@0: } Chris@0: if (addClasses && rows.length) { Chris@17: $(rows[rows.length - 1]) Chris@17: .find(`.js-indentation:nth-child(${parentIndentation + 1})`) Chris@17: .addClass('tree-child-last'); Chris@0: } Chris@0: return rows; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Ensure that two rows are allowed to be swapped. Chris@0: * Chris@0: * @param {HTMLElement} row Chris@0: * DOM object for the row being considered for swapping. Chris@0: * Chris@0: * @return {bool} Chris@0: * Whether the swap is a valid swap or not. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(row) { Chris@0: const $row = $(row); Chris@0: if (this.indentEnabled) { Chris@0: let prevRow; Chris@0: let nextRow; Chris@0: if (this.direction === 'down') { Chris@0: prevRow = row; Chris@0: nextRow = $row.next('tr').get(0); Chris@17: } else { Chris@0: prevRow = $row.prev('tr').get(0); Chris@0: nextRow = row; Chris@0: } Chris@0: this.interval = this.validIndentInterval(prevRow, nextRow); Chris@0: Chris@0: // We have an invalid swap if the valid indentations interval is empty. Chris@0: if (this.interval.min > this.interval.max) { Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: // Do not let an un-draggable first row have anything put before it. Chris@0: if (this.table.tBodies[0].rows[0] === row && $row.is(':not(.draggable)')) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: return true; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Perform the swap between two rows. Chris@0: * Chris@0: * @param {string} position Chris@0: * Whether the swap will occur 'before' or 'after' the given row. Chris@0: * @param {HTMLElement} row Chris@0: * DOM element what will be swapped with the row group. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.swap = function(position, row) { Chris@0: // Makes sure only DOM object are passed to Drupal.detachBehaviors(). Chris@17: this.group.forEach(row => { Chris@0: Drupal.detachBehaviors(row, drupalSettings, 'move'); Chris@0: }); Chris@0: $(row)[position](this.group); Chris@0: // Makes sure only DOM object are passed to Drupal.attachBehaviors()s. Chris@17: this.group.forEach(row => { Chris@0: Drupal.attachBehaviors(row, drupalSettings); Chris@0: }); Chris@0: this.changed = true; Chris@0: this.onSwap(row); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Determine the valid indentations interval for the row at a given position. Chris@0: * Chris@0: * @param {?HTMLElement} prevRow Chris@0: * DOM object for the row before the tested position Chris@0: * (or null for first position in the table). Chris@0: * @param {?HTMLElement} nextRow Chris@0: * DOM object for the row after the tested position Chris@0: * (or null for last position in the table). Chris@0: * Chris@0: * @return {object} Chris@0: * An object with the keys `min` and `max` to indicate the valid indent Chris@0: * interval. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function( Chris@17: prevRow, Chris@17: nextRow, Chris@17: ) { Chris@0: const $prevRow = $(prevRow); Chris@0: let maxIndent; Chris@0: Chris@0: // Minimum indentation: Chris@0: // Do not orphan the next row. Chris@14: const minIndent = nextRow ? $(nextRow).find('.js-indentation').length : 0; Chris@0: Chris@0: // Maximum indentation: Chris@17: if ( Chris@17: !prevRow || Chris@17: $prevRow.is(':not(.draggable)') || Chris@17: $(this.element).is('.tabledrag-root') Chris@17: ) { Chris@0: // Do not indent: Chris@0: // - the first row in the table, Chris@0: // - rows dragged below a non-draggable row, Chris@0: // - 'root' rows. Chris@0: maxIndent = 0; Chris@17: } else { Chris@0: // Do not go deeper than as a child of the previous row. Chris@17: maxIndent = Chris@17: $prevRow.find('.js-indentation').length + Chris@17: ($prevRow.is('.tabledrag-leaf') ? 0 : 1); Chris@0: // Limit by the maximum allowed depth for the table. Chris@0: if (this.maxDepth) { Chris@17: maxIndent = Math.min( Chris@17: maxIndent, Chris@17: this.maxDepth - (this.groupDepth - this.indents), Chris@17: ); Chris@0: } Chris@0: } Chris@0: Chris@0: return { min: minIndent, max: maxIndent }; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Indent a row within the legal bounds of the table. Chris@0: * Chris@0: * @param {number} indentDiff Chris@0: * The number of additional indentations proposed for the row (can be Chris@0: * positive or negative). This number will be adjusted to nearest valid Chris@0: * indentation level for the row. Chris@0: * Chris@0: * @return {number} Chris@0: * The number of indentations applied. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.indent = function(indentDiff) { Chris@0: const $group = $(this.group); Chris@0: // Determine the valid indentations interval if not available yet. Chris@0: if (!this.interval) { Chris@17: const prevRow = $(this.element) Chris@17: .prev('tr') Chris@17: .get(0); Chris@17: const nextRow = $group Chris@17: .eq(-1) Chris@17: .next('tr') Chris@17: .get(0); Chris@0: this.interval = this.validIndentInterval(prevRow, nextRow); Chris@0: } Chris@0: Chris@0: // Adjust to the nearest valid indentation. Chris@0: let indent = this.indents + indentDiff; Chris@0: indent = Math.max(indent, this.interval.min); Chris@0: indent = Math.min(indent, this.interval.max); Chris@0: indentDiff = indent - this.indents; Chris@0: Chris@0: for (let n = 1; n <= Math.abs(indentDiff); n++) { Chris@0: // Add or remove indentations. Chris@0: if (indentDiff < 0) { Chris@0: $group.find('.js-indentation:first-of-type').remove(); Chris@0: this.indents--; Chris@17: } else { Chris@17: $group Chris@17: .find('td:first-of-type') Chris@17: .prepend(Drupal.theme('tableDragIndentation')); Chris@0: this.indents++; Chris@0: } Chris@0: } Chris@0: if (indentDiff) { Chris@0: // Update indentation for this row. Chris@0: this.changed = true; Chris@0: this.groupDepth += indentDiff; Chris@0: this.onIndent(); Chris@0: } Chris@0: Chris@0: return indentDiff; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Find all siblings for a row. Chris@0: * Chris@0: * According to its subgroup or indentation. Note that the passed-in row is Chris@0: * included in the list of siblings. Chris@0: * Chris@0: * @param {object} rowSettings Chris@0: * The field settings we're using to identify what constitutes a sibling. Chris@0: * Chris@0: * @return {Array} Chris@0: * An array of siblings. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.findSiblings = function( Chris@17: rowSettings, Chris@17: ) { Chris@0: const siblings = []; Chris@0: const directions = ['prev', 'next']; Chris@0: const rowIndentation = this.indents; Chris@0: let checkRowIndentation; Chris@0: for (let d = 0; d < directions.length; d++) { Chris@0: let checkRow = $(this.element)[directions[d]](); Chris@0: while (checkRow.length) { Chris@0: // Check that the sibling contains a similar target field. Chris@0: if (checkRow.find(`.${rowSettings.target}`)) { Chris@0: // Either add immediately if this is a flat table, or check to ensure Chris@0: // that this row has the same level of indentation. Chris@0: if (this.indentEnabled) { Chris@0: checkRowIndentation = checkRow.find('.js-indentation').length; Chris@0: } Chris@0: Chris@17: if (!this.indentEnabled || checkRowIndentation === rowIndentation) { Chris@0: siblings.push(checkRow[0]); Chris@17: } else if (checkRowIndentation < rowIndentation) { Chris@0: // No need to keep looking for siblings when we get to a parent. Chris@0: break; Chris@0: } Chris@17: } else { Chris@0: break; Chris@0: } Chris@0: checkRow = checkRow[directions[d]](); Chris@0: } Chris@0: // Since siblings are added in reverse order for previous, reverse the Chris@0: // completed list of previous siblings. Add the current row and continue. Chris@0: if (directions[d] === 'prev') { Chris@0: siblings.reverse(); Chris@0: siblings.push(this.element); Chris@0: } Chris@0: } Chris@0: return siblings; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Remove indentation helper classes from the current row group. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function() { Chris@17: Object.keys(this.children || {}).forEach(n => { Chris@17: $(this.children[n]) Chris@17: .find('.js-indentation') Chris@14: .removeClass('tree-child') Chris@14: .removeClass('tree-child-first') Chris@14: .removeClass('tree-child-last') Chris@14: .removeClass('tree-child-horizontal'); Chris@14: }); Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Add an asterisk or other marker to the changed row. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.markChanged = function() { Chris@0: const marker = Drupal.theme('tableDragChangedMarker'); Chris@0: const cell = $(this.element).find('td:first-of-type'); Chris@0: if (cell.find('abbr.tabledrag-changed').length === 0) { Chris@0: cell.append(marker); Chris@0: } Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Stub function. Allows a custom handler when a row is indented. Chris@0: * Chris@0: * @return {null} Chris@0: * Returns null when the stub function is used. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.onIndent = function() { Chris@0: return null; Chris@0: }; Chris@0: Chris@0: /** Chris@0: * Stub function. Allows a custom handler when a row is swapped. Chris@0: * Chris@0: * @param {HTMLElement} swappedRow Chris@0: * The element for the swapped row. Chris@0: * Chris@0: * @return {null} Chris@0: * Returns null when the stub function is used. Chris@0: */ Chris@17: Drupal.tableDrag.prototype.row.prototype.onSwap = function(swappedRow) { Chris@0: return null; Chris@0: }; Chris@0: Chris@17: $.extend( Chris@17: Drupal.theme, Chris@17: /** @lends Drupal.theme */ { Chris@17: /** Chris@17: * @return {string} Chris@17: * Markup for the marker. Chris@17: */ Chris@17: tableDragChangedMarker() { Chris@17: return `*`; Chris@17: }, Chris@0: Chris@17: /** Chris@17: * @return {string} Chris@17: * Markup for the indentation. Chris@17: */ Chris@17: tableDragIndentation() { Chris@17: return '
 
'; Chris@17: }, Chris@17: Chris@17: /** Chris@17: * @return {string} Chris@17: * Markup for the warning. Chris@17: */ Chris@17: tableDragChangedWarning() { Chris@17: return ``; Chris@17: }, Chris@0: }, Chris@17: ); Chris@17: })(jQuery, Drupal, drupalSettings);