Drupal investigation

tabledrag.js 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  1. /**
  2. * @file
  3. * Provide dragging capabilities to admin uis.
  4. */
  5. /**
  6. * Triggers when weights columns are toggled.
  7. *
  8. * @event columnschange
  9. */
  10. (function ($, Drupal, drupalSettings) {
  11. 'use strict';
  12. /**
  13. * Store the state of weight columns display for all tables.
  14. *
  15. * Default value is to hide weight columns.
  16. */
  17. var showWeight = JSON.parse(localStorage.getItem('Drupal.tableDrag.showWeight'));
  18. /**
  19. * Drag and drop table rows with field manipulation.
  20. *
  21. * Using the drupal_attach_tabledrag() function, any table with weights or
  22. * parent relationships may be made into draggable tables. Columns containing
  23. * a field may optionally be hidden, providing a better user experience.
  24. *
  25. * Created tableDrag instances may be modified with custom behaviors by
  26. * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
  27. * See blocks.js for an example of adding additional functionality to
  28. * tableDrag.
  29. *
  30. * @type {Drupal~behavior}
  31. */
  32. Drupal.behaviors.tableDrag = {
  33. attach: function (context, settings) {
  34. function initTableDrag(table, base) {
  35. if (table.length) {
  36. // Create the new tableDrag instance. Save in the Drupal variable
  37. // to allow other scripts access to the object.
  38. Drupal.tableDrag[base] = new Drupal.tableDrag(table[0], settings.tableDrag[base]);
  39. }
  40. }
  41. for (var base in settings.tableDrag) {
  42. if (settings.tableDrag.hasOwnProperty(base)) {
  43. initTableDrag($(context).find('#' + base).once('tabledrag'), base);
  44. }
  45. }
  46. }
  47. };
  48. /**
  49. * Provides table and field manipulation.
  50. *
  51. * @constructor
  52. *
  53. * @param {HTMLElement} table
  54. * DOM object for the table to be made draggable.
  55. * @param {object} tableSettings
  56. * Settings for the table added via drupal_add_dragtable().
  57. */
  58. Drupal.tableDrag = function (table, tableSettings) {
  59. var self = this;
  60. var $table = $(table);
  61. /**
  62. * @type {jQuery}
  63. */
  64. this.$table = $(table);
  65. /**
  66. *
  67. * @type {HTMLElement}
  68. */
  69. this.table = table;
  70. /**
  71. * @type {object}
  72. */
  73. this.tableSettings = tableSettings;
  74. /**
  75. * Used to hold information about a current drag operation.
  76. *
  77. * @type {?HTMLElement}
  78. */
  79. this.dragObject = null;
  80. /**
  81. * Provides operations for row manipulation.
  82. *
  83. * @type {?HTMLElement}
  84. */
  85. this.rowObject = null;
  86. /**
  87. * Remember the previous element.
  88. *
  89. * @type {?HTMLElement}
  90. */
  91. this.oldRowElement = null;
  92. /**
  93. * Used to determine up or down direction from last mouse move.
  94. *
  95. * @type {number}
  96. */
  97. this.oldY = 0;
  98. /**
  99. * Whether anything in the entire table has changed.
  100. *
  101. * @type {bool}
  102. */
  103. this.changed = false;
  104. /**
  105. * Maximum amount of allowed parenting.
  106. *
  107. * @type {number}
  108. */
  109. this.maxDepth = 0;
  110. /**
  111. * Direction of the table.
  112. *
  113. * @type {number}
  114. */
  115. this.rtl = $(this.table).css('direction') === 'rtl' ? -1 : 1;
  116. /**
  117. *
  118. * @type {bool}
  119. */
  120. this.striping = $(this.table).data('striping') === 1;
  121. /**
  122. * Configure the scroll settings.
  123. *
  124. * @type {object}
  125. *
  126. * @prop {number} amount
  127. * @prop {number} interval
  128. * @prop {number} trigger
  129. */
  130. this.scrollSettings = {amount: 4, interval: 50, trigger: 70};
  131. /**
  132. *
  133. * @type {?number}
  134. */
  135. this.scrollInterval = null;
  136. /**
  137. *
  138. * @type {number}
  139. */
  140. this.scrollY = 0;
  141. /**
  142. *
  143. * @type {number}
  144. */
  145. this.windowHeight = 0;
  146. /**
  147. * Check this table's settings for parent relationships.
  148. *
  149. * For efficiency, large sections of code can be skipped if we don't need to
  150. * track horizontal movement and indentations.
  151. *
  152. * @type {bool}
  153. */
  154. this.indentEnabled = false;
  155. for (var group in tableSettings) {
  156. if (tableSettings.hasOwnProperty(group)) {
  157. for (var n in tableSettings[group]) {
  158. if (tableSettings[group].hasOwnProperty(n)) {
  159. if (tableSettings[group][n].relationship === 'parent') {
  160. this.indentEnabled = true;
  161. }
  162. if (tableSettings[group][n].limit > 0) {
  163. this.maxDepth = tableSettings[group][n].limit;
  164. }
  165. }
  166. }
  167. }
  168. }
  169. if (this.indentEnabled) {
  170. /**
  171. * Total width of indents, set in makeDraggable.
  172. *
  173. * @type {number}
  174. */
  175. this.indentCount = 1;
  176. // Find the width of indentations to measure mouse movements against.
  177. // Because the table doesn't need to start with any indentations, we
  178. // manually append 2 indentations in the first draggable row, measure
  179. // the offset, then remove.
  180. var indent = Drupal.theme('tableDragIndentation');
  181. var testRow = $('<tr/>').addClass('draggable').appendTo(table);
  182. var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
  183. var $indentation = testCell.find('.js-indentation');
  184. /**
  185. *
  186. * @type {number}
  187. */
  188. this.indentAmount = $indentation.get(1).offsetLeft - $indentation.get(0).offsetLeft;
  189. testRow.remove();
  190. }
  191. // Make each applicable row draggable.
  192. // Match immediate children of the parent element to allow nesting.
  193. $table.find('> tr.draggable, > tbody > tr.draggable').each(function () { self.makeDraggable(this); });
  194. // Add a link before the table for users to show or hide weight columns.
  195. $table.before($('<button type="button" class="link tabledrag-toggle-weight"></button>')
  196. .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
  197. .on('click', $.proxy(function (e) {
  198. e.preventDefault();
  199. this.toggleColumns();
  200. }, this))
  201. .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
  202. .parent()
  203. );
  204. // Initialize the specified columns (for example, weight or parent columns)
  205. // to show or hide according to user preference. This aids accessibility
  206. // so that, e.g., screen reader users can choose to enter weight values and
  207. // manipulate form elements directly, rather than using drag-and-drop..
  208. self.initColumns();
  209. // Add event bindings to the document. The self variable is passed along
  210. // as event handlers do not have direct access to the tableDrag object.
  211. $(document).on('touchmove', function (event) { return self.dragRow(event.originalEvent.touches[0], self); });
  212. $(document).on('touchend', function (event) { return self.dropRow(event.originalEvent.touches[0], self); });
  213. $(document).on('mousemove pointermove', function (event) { return self.dragRow(event, self); });
  214. $(document).on('mouseup pointerup', function (event) { return self.dropRow(event, self); });
  215. // React to localStorage event showing or hiding weight columns.
  216. $(window).on('storage', $.proxy(function (e) {
  217. // Only react to 'Drupal.tableDrag.showWeight' value change.
  218. if (e.originalEvent.key === 'Drupal.tableDrag.showWeight') {
  219. // This was changed in another window, get the new value for this
  220. // window.
  221. showWeight = JSON.parse(e.originalEvent.newValue);
  222. this.displayColumns(showWeight);
  223. }
  224. }, this));
  225. };
  226. /**
  227. * Initialize columns containing form elements to be hidden by default.
  228. *
  229. * Identify and mark each cell with a CSS class so we can easily toggle
  230. * show/hide it. Finally, hide columns if user does not have a
  231. * 'Drupal.tableDrag.showWeight' localStorage value.
  232. */
  233. Drupal.tableDrag.prototype.initColumns = function () {
  234. var $table = this.$table;
  235. var hidden;
  236. var cell;
  237. var columnIndex;
  238. for (var group in this.tableSettings) {
  239. if (this.tableSettings.hasOwnProperty(group)) {
  240. // Find the first field in this group.
  241. for (var d in this.tableSettings[group]) {
  242. if (this.tableSettings[group].hasOwnProperty(d)) {
  243. var field = $table.find('.' + this.tableSettings[group][d].target).eq(0);
  244. if (field.length && this.tableSettings[group][d].hidden) {
  245. hidden = this.tableSettings[group][d].hidden;
  246. cell = field.closest('td');
  247. break;
  248. }
  249. }
  250. }
  251. // Mark the column containing this field so it can be hidden.
  252. if (hidden && cell[0]) {
  253. // Add 1 to our indexes. The nth-child selector is 1 based, not 0
  254. // based. Match immediate children of the parent element to allow
  255. // nesting.
  256. columnIndex = cell.parent().find('> td').index(cell.get(0)) + 1;
  257. $table.find('> thead > tr, > tbody > tr, > tr').each(this.addColspanClass(columnIndex));
  258. }
  259. }
  260. }
  261. this.displayColumns(showWeight);
  262. };
  263. /**
  264. * Mark cells that have colspan.
  265. *
  266. * In order to adjust the colspan instead of hiding them altogether.
  267. *
  268. * @param {number} columnIndex
  269. * The column index to add colspan class to.
  270. *
  271. * @return {function}
  272. * Function to add colspan class.
  273. */
  274. Drupal.tableDrag.prototype.addColspanClass = function (columnIndex) {
  275. return function () {
  276. // Get the columnIndex and adjust for any colspans in this row.
  277. var $row = $(this);
  278. var index = columnIndex;
  279. var cells = $row.children();
  280. var cell;
  281. cells.each(function (n) {
  282. if (n < index && this.colSpan && this.colSpan > 1) {
  283. index -= this.colSpan - 1;
  284. }
  285. });
  286. if (index > 0) {
  287. cell = cells.filter(':nth-child(' + index + ')');
  288. if (cell[0].colSpan && cell[0].colSpan > 1) {
  289. // If this cell has a colspan, mark it so we can reduce the colspan.
  290. cell.addClass('tabledrag-has-colspan');
  291. }
  292. else {
  293. // Mark this cell so we can hide it.
  294. cell.addClass('tabledrag-hide');
  295. }
  296. }
  297. };
  298. };
  299. /**
  300. * Hide or display weight columns. Triggers an event on change.
  301. *
  302. * @fires event:columnschange
  303. *
  304. * @param {bool} displayWeight
  305. * 'true' will show weight columns.
  306. */
  307. Drupal.tableDrag.prototype.displayColumns = function (displayWeight) {
  308. if (displayWeight) {
  309. this.showColumns();
  310. }
  311. // Default action is to hide columns.
  312. else {
  313. this.hideColumns();
  314. }
  315. // Trigger an event to allow other scripts to react to this display change.
  316. // Force the extra parameter as a bool.
  317. $('table').findOnce('tabledrag').trigger('columnschange', !!displayWeight);
  318. };
  319. /**
  320. * Toggle the weight column depending on 'showWeight' value.
  321. *
  322. * Store only default override.
  323. */
  324. Drupal.tableDrag.prototype.toggleColumns = function () {
  325. showWeight = !showWeight;
  326. this.displayColumns(showWeight);
  327. if (showWeight) {
  328. // Save default override.
  329. localStorage.setItem('Drupal.tableDrag.showWeight', showWeight);
  330. }
  331. else {
  332. // Reset the value to its default.
  333. localStorage.removeItem('Drupal.tableDrag.showWeight');
  334. }
  335. };
  336. /**
  337. * Hide the columns containing weight/parent form elements.
  338. *
  339. * Undo showColumns().
  340. */
  341. Drupal.tableDrag.prototype.hideColumns = function () {
  342. var $tables = $('table').findOnce('tabledrag');
  343. // Hide weight/parent cells and headers.
  344. $tables.find('.tabledrag-hide').css('display', 'none');
  345. // Show TableDrag handles.
  346. $tables.find('.tabledrag-handle').css('display', '');
  347. // Reduce the colspan of any effected multi-span columns.
  348. $tables.find('.tabledrag-has-colspan').each(function () {
  349. this.colSpan = this.colSpan - 1;
  350. });
  351. // Change link text.
  352. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
  353. };
  354. /**
  355. * Show the columns containing weight/parent form elements.
  356. *
  357. * Undo hideColumns().
  358. */
  359. Drupal.tableDrag.prototype.showColumns = function () {
  360. var $tables = $('table').findOnce('tabledrag');
  361. // Show weight/parent cells and headers.
  362. $tables.find('.tabledrag-hide').css('display', '');
  363. // Hide TableDrag handles.
  364. $tables.find('.tabledrag-handle').css('display', 'none');
  365. // Increase the colspan for any columns where it was previously reduced.
  366. $tables.find('.tabledrag-has-colspan').each(function () {
  367. this.colSpan = this.colSpan + 1;
  368. });
  369. // Change link text.
  370. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
  371. };
  372. /**
  373. * Find the target used within a particular row and group.
  374. *
  375. * @param {string} group
  376. * Group selector.
  377. * @param {HTMLElement} row
  378. * The row HTML element.
  379. *
  380. * @return {object}
  381. * The table row settings.
  382. */
  383. Drupal.tableDrag.prototype.rowSettings = function (group, row) {
  384. var field = $(row).find('.' + group);
  385. var tableSettingsGroup = this.tableSettings[group];
  386. for (var delta in tableSettingsGroup) {
  387. if (tableSettingsGroup.hasOwnProperty(delta)) {
  388. var targetClass = tableSettingsGroup[delta].target;
  389. if (field.is('.' + targetClass)) {
  390. // Return a copy of the row settings.
  391. var rowSettings = {};
  392. for (var n in tableSettingsGroup[delta]) {
  393. if (tableSettingsGroup[delta].hasOwnProperty(n)) {
  394. rowSettings[n] = tableSettingsGroup[delta][n];
  395. }
  396. }
  397. return rowSettings;
  398. }
  399. }
  400. }
  401. };
  402. /**
  403. * Take an item and add event handlers to make it become draggable.
  404. *
  405. * @param {HTMLElement} item
  406. * The item to add event handlers to.
  407. */
  408. Drupal.tableDrag.prototype.makeDraggable = function (item) {
  409. var self = this;
  410. var $item = $(item);
  411. // Add a class to the title link.
  412. $item.find('td:first-of-type').find('a').addClass('menu-item__link');
  413. // Create the handle.
  414. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order'));
  415. // Insert the handle after indentations (if any).
  416. var $indentationLast = $item.find('td:first-of-type').find('.js-indentation').eq(-1);
  417. if ($indentationLast.length) {
  418. $indentationLast.after(handle);
  419. // Update the total width of indentation in this entire table.
  420. self.indentCount = Math.max($item.find('.js-indentation').length, self.indentCount);
  421. }
  422. else {
  423. $item.find('td').eq(0).prepend(handle);
  424. }
  425. handle.on('mousedown touchstart pointerdown', function (event) {
  426. event.preventDefault();
  427. if (event.originalEvent.type === 'touchstart') {
  428. event = event.originalEvent.touches[0];
  429. }
  430. self.dragStart(event, self, item);
  431. });
  432. // Prevent the anchor tag from jumping us to the top of the page.
  433. handle.on('click', function (e) {
  434. e.preventDefault();
  435. });
  436. // Set blur cleanup when a handle is focused.
  437. handle.on('focus', function () {
  438. self.safeBlur = true;
  439. });
  440. // On blur, fire the same function as a touchend/mouseup. This is used to
  441. // update values after a row has been moved through the keyboard support.
  442. handle.on('blur', function (event) {
  443. if (self.rowObject && self.safeBlur) {
  444. self.dropRow(event, self);
  445. }
  446. });
  447. // Add arrow-key support to the handle.
  448. handle.on('keydown', function (event) {
  449. // If a rowObject doesn't yet exist and this isn't the tab key.
  450. if (event.keyCode !== 9 && !self.rowObject) {
  451. self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
  452. }
  453. var keyChange = false;
  454. var groupHeight;
  455. /* eslint-disable no-fallthrough */
  456. switch (event.keyCode) {
  457. // Left arrow.
  458. case 37:
  459. // Safari left arrow.
  460. case 63234:
  461. keyChange = true;
  462. self.rowObject.indent(-1 * self.rtl);
  463. break;
  464. // Up arrow.
  465. case 38:
  466. // Safari up arrow.
  467. case 63232:
  468. var $previousRow = $(self.rowObject.element).prev('tr:first-of-type');
  469. var previousRow = $previousRow.get(0);
  470. while (previousRow && $previousRow.is(':hidden')) {
  471. $previousRow = $(previousRow).prev('tr:first-of-type');
  472. previousRow = $previousRow.get(0);
  473. }
  474. if (previousRow) {
  475. // Do not allow the onBlur cleanup.
  476. self.safeBlur = false;
  477. self.rowObject.direction = 'up';
  478. keyChange = true;
  479. if ($(item).is('.tabledrag-root')) {
  480. // Swap with the previous top-level row.
  481. groupHeight = 0;
  482. while (previousRow && $previousRow.find('.js-indentation').length) {
  483. $previousRow = $(previousRow).prev('tr:first-of-type');
  484. previousRow = $previousRow.get(0);
  485. groupHeight += $previousRow.is(':hidden') ? 0 : previousRow.offsetHeight;
  486. }
  487. if (previousRow) {
  488. self.rowObject.swap('before', previousRow);
  489. // No need to check for indentation, 0 is the only valid one.
  490. window.scrollBy(0, -groupHeight);
  491. }
  492. }
  493. else if (self.table.tBodies[0].rows[0] !== previousRow || $previousRow.is('.draggable')) {
  494. // Swap with the previous row (unless previous row is the first
  495. // one and undraggable).
  496. self.rowObject.swap('before', previousRow);
  497. self.rowObject.interval = null;
  498. self.rowObject.indent(0);
  499. window.scrollBy(0, -parseInt(item.offsetHeight, 10));
  500. }
  501. // Regain focus after the DOM manipulation.
  502. handle.trigger('focus');
  503. }
  504. break;
  505. // Right arrow.
  506. case 39:
  507. // Safari right arrow.
  508. case 63235:
  509. keyChange = true;
  510. self.rowObject.indent(self.rtl);
  511. break;
  512. // Down arrow.
  513. case 40:
  514. // Safari down arrow.
  515. case 63233:
  516. var $nextRow = $(self.rowObject.group).eq(-1).next('tr:first-of-type');
  517. var nextRow = $nextRow.get(0);
  518. while (nextRow && $nextRow.is(':hidden')) {
  519. $nextRow = $(nextRow).next('tr:first-of-type');
  520. nextRow = $nextRow.get(0);
  521. }
  522. if (nextRow) {
  523. // Do not allow the onBlur cleanup.
  524. self.safeBlur = false;
  525. self.rowObject.direction = 'down';
  526. keyChange = true;
  527. if ($(item).is('.tabledrag-root')) {
  528. // Swap with the next group (necessarily a top-level one).
  529. groupHeight = 0;
  530. var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
  531. if (nextGroup) {
  532. $(nextGroup.group).each(function () {
  533. groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
  534. });
  535. var nextGroupRow = $(nextGroup.group).eq(-1).get(0);
  536. self.rowObject.swap('after', nextGroupRow);
  537. // No need to check for indentation, 0 is the only valid one.
  538. window.scrollBy(0, parseInt(groupHeight, 10));
  539. }
  540. }
  541. else {
  542. // Swap with the next row.
  543. self.rowObject.swap('after', nextRow);
  544. self.rowObject.interval = null;
  545. self.rowObject.indent(0);
  546. window.scrollBy(0, parseInt(item.offsetHeight, 10));
  547. }
  548. // Regain focus after the DOM manipulation.
  549. handle.trigger('focus');
  550. }
  551. break;
  552. }
  553. /* eslint-enable no-fallthrough */
  554. if (self.rowObject && self.rowObject.changed === true) {
  555. $(item).addClass('drag');
  556. if (self.oldRowElement) {
  557. $(self.oldRowElement).removeClass('drag-previous');
  558. }
  559. self.oldRowElement = item;
  560. if (self.striping === true) {
  561. self.restripeTable();
  562. }
  563. self.onDrag();
  564. }
  565. // Returning false if we have an arrow key to prevent scrolling.
  566. if (keyChange) {
  567. return false;
  568. }
  569. });
  570. // Compatibility addition, return false on keypress to prevent unwanted
  571. // scrolling. IE and Safari will suppress scrolling on keydown, but all
  572. // other browsers need to return false on keypress.
  573. // http://www.quirksmode.org/js/keys.html
  574. handle.on('keypress', function (event) {
  575. /* eslint-disable no-fallthrough */
  576. switch (event.keyCode) {
  577. // Left arrow.
  578. case 37:
  579. // Up arrow.
  580. case 38:
  581. // Right arrow.
  582. case 39:
  583. // Down arrow.
  584. case 40:
  585. return false;
  586. }
  587. /* eslint-enable no-fallthrough */
  588. });
  589. };
  590. /**
  591. * Pointer event initiator, creates drag object and information.
  592. *
  593. * @param {jQuery.Event} event
  594. * The event object that trigger the drag.
  595. * @param {Drupal.tableDrag} self
  596. * The drag handle.
  597. * @param {HTMLElement} item
  598. * The item that that is being dragged.
  599. */
  600. Drupal.tableDrag.prototype.dragStart = function (event, self, item) {
  601. // Create a new dragObject recording the pointer information.
  602. self.dragObject = {};
  603. self.dragObject.initOffset = self.getPointerOffset(item, event);
  604. self.dragObject.initPointerCoords = self.pointerCoords(event);
  605. if (self.indentEnabled) {
  606. self.dragObject.indentPointerPos = self.dragObject.initPointerCoords;
  607. }
  608. // If there's a lingering row object from the keyboard, remove its focus.
  609. if (self.rowObject) {
  610. $(self.rowObject.element).find('a.tabledrag-handle').trigger('blur');
  611. }
  612. // Create a new rowObject for manipulation of this row.
  613. self.rowObject = new self.row(item, 'pointer', self.indentEnabled, self.maxDepth, true);
  614. // Save the position of the table.
  615. self.table.topY = $(self.table).offset().top;
  616. self.table.bottomY = self.table.topY + self.table.offsetHeight;
  617. // Add classes to the handle and row.
  618. $(item).addClass('drag');
  619. // Set the document to use the move cursor during drag.
  620. $('body').addClass('drag');
  621. if (self.oldRowElement) {
  622. $(self.oldRowElement).removeClass('drag-previous');
  623. }
  624. };
  625. /**
  626. * Pointer movement handler, bound to document.
  627. *
  628. * @param {jQuery.Event} event
  629. * The pointer event.
  630. * @param {Drupal.tableDrag} self
  631. * The tableDrag instance.
  632. *
  633. * @return {bool|undefined}
  634. * Undefined if no dragObject is defined, false otherwise.
  635. */
  636. Drupal.tableDrag.prototype.dragRow = function (event, self) {
  637. if (self.dragObject) {
  638. self.currentPointerCoords = self.pointerCoords(event);
  639. var y = self.currentPointerCoords.y - self.dragObject.initOffset.y;
  640. var x = self.currentPointerCoords.x - self.dragObject.initOffset.x;
  641. // Check for row swapping and vertical scrolling.
  642. if (y !== self.oldY) {
  643. self.rowObject.direction = y > self.oldY ? 'down' : 'up';
  644. // Update the old value.
  645. self.oldY = y;
  646. // Check if the window should be scrolled (and how fast).
  647. var scrollAmount = self.checkScroll(self.currentPointerCoords.y);
  648. // Stop any current scrolling.
  649. clearInterval(self.scrollInterval);
  650. // Continue scrolling if the mouse has moved in the scroll direction.
  651. if (scrollAmount > 0 && self.rowObject.direction === 'down' || scrollAmount < 0 && self.rowObject.direction === 'up') {
  652. self.setScroll(scrollAmount);
  653. }
  654. // If we have a valid target, perform the swap and restripe the table.
  655. var currentRow = self.findDropTargetRow(x, y);
  656. if (currentRow) {
  657. if (self.rowObject.direction === 'down') {
  658. self.rowObject.swap('after', currentRow, self);
  659. }
  660. else {
  661. self.rowObject.swap('before', currentRow, self);
  662. }
  663. if (self.striping === true) {
  664. self.restripeTable();
  665. }
  666. }
  667. }
  668. // Similar to row swapping, handle indentations.
  669. if (self.indentEnabled) {
  670. var xDiff = self.currentPointerCoords.x - self.dragObject.indentPointerPos.x;
  671. // Set the number of indentations the pointer has been moved left or
  672. // right.
  673. var indentDiff = Math.round(xDiff / self.indentAmount);
  674. // Indent the row with our estimated diff, which may be further
  675. // restricted according to the rows around this row.
  676. var indentChange = self.rowObject.indent(indentDiff);
  677. // Update table and pointer indentations.
  678. self.dragObject.indentPointerPos.x += self.indentAmount * indentChange * self.rtl;
  679. self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
  680. }
  681. return false;
  682. }
  683. };
  684. /**
  685. * Pointerup behavior.
  686. *
  687. * @param {jQuery.Event} event
  688. * The pointer event.
  689. * @param {Drupal.tableDrag} self
  690. * The tableDrag instance.
  691. */
  692. Drupal.tableDrag.prototype.dropRow = function (event, self) {
  693. var droppedRow;
  694. var $droppedRow;
  695. // Drop row functionality.
  696. if (self.rowObject !== null) {
  697. droppedRow = self.rowObject.element;
  698. $droppedRow = $(droppedRow);
  699. // The row is already in the right place so we just release it.
  700. if (self.rowObject.changed === true) {
  701. // Update the fields in the dropped row.
  702. self.updateFields(droppedRow);
  703. // If a setting exists for affecting the entire group, update all the
  704. // fields in the entire dragged group.
  705. for (var group in self.tableSettings) {
  706. if (self.tableSettings.hasOwnProperty(group)) {
  707. var rowSettings = self.rowSettings(group, droppedRow);
  708. if (rowSettings.relationship === 'group') {
  709. for (var n in self.rowObject.children) {
  710. if (self.rowObject.children.hasOwnProperty(n)) {
  711. self.updateField(self.rowObject.children[n], group);
  712. }
  713. }
  714. }
  715. }
  716. }
  717. self.rowObject.markChanged();
  718. if (self.changed === false) {
  719. $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
  720. self.changed = true;
  721. }
  722. }
  723. if (self.indentEnabled) {
  724. self.rowObject.removeIndentClasses();
  725. }
  726. if (self.oldRowElement) {
  727. $(self.oldRowElement).removeClass('drag-previous');
  728. }
  729. $droppedRow.removeClass('drag').addClass('drag-previous');
  730. self.oldRowElement = droppedRow;
  731. self.onDrop();
  732. self.rowObject = null;
  733. }
  734. // Functionality specific only to pointerup events.
  735. if (self.dragObject !== null) {
  736. self.dragObject = null;
  737. $('body').removeClass('drag');
  738. clearInterval(self.scrollInterval);
  739. }
  740. };
  741. /**
  742. * Get the coordinates from the event (allowing for browser differences).
  743. *
  744. * @param {jQuery.Event} event
  745. * The pointer event.
  746. *
  747. * @return {object}
  748. * An object with `x` and `y` keys indicating the position.
  749. */
  750. Drupal.tableDrag.prototype.pointerCoords = function (event) {
  751. if (event.pageX || event.pageY) {
  752. return {x: event.pageX, y: event.pageY};
  753. }
  754. return {
  755. x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
  756. y: event.clientY + document.body.scrollTop - document.body.clientTop
  757. };
  758. };
  759. /**
  760. * Get the event offset from the target element.
  761. *
  762. * Given a target element and a pointer event, get the event offset from that
  763. * element. To do this we need the element's position and the target position.
  764. *
  765. * @param {HTMLElement} target
  766. * The target HTML element.
  767. * @param {jQuery.Event} event
  768. * The pointer event.
  769. *
  770. * @return {object}
  771. * An object with `x` and `y` keys indicating the position.
  772. */
  773. Drupal.tableDrag.prototype.getPointerOffset = function (target, event) {
  774. var docPos = $(target).offset();
  775. var pointerPos = this.pointerCoords(event);
  776. return {x: pointerPos.x - docPos.left, y: pointerPos.y - docPos.top};
  777. };
  778. /**
  779. * Find the row the mouse is currently over.
  780. *
  781. * This row is then taken and swapped with the one being dragged.
  782. *
  783. * @param {number} x
  784. * The x coordinate of the mouse on the page (not the screen).
  785. * @param {number} y
  786. * The y coordinate of the mouse on the page (not the screen).
  787. *
  788. * @return {*}
  789. * The drop target row, if found.
  790. */
  791. Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
  792. var rows = $(this.table.tBodies[0].rows).not(':hidden');
  793. for (var n = 0; n < rows.length; n++) {
  794. var row = rows[n];
  795. var $row = $(row);
  796. var rowY = $row.offset().top;
  797. var rowHeight;
  798. // Because Safari does not report offsetHeight on table rows, but does on
  799. // table cells, grab the firstChild of the row and use that instead.
  800. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
  801. if (row.offsetHeight === 0) {
  802. rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
  803. }
  804. // Other browsers.
  805. else {
  806. rowHeight = parseInt(row.offsetHeight, 10) / 2;
  807. }
  808. // Because we always insert before, we need to offset the height a bit.
  809. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
  810. if (this.indentEnabled) {
  811. // Check that this row is not a child of the row being dragged.
  812. for (n in this.rowObject.group) {
  813. if (this.rowObject.group[n] === row) {
  814. return null;
  815. }
  816. }
  817. }
  818. else {
  819. // Do not allow a row to be swapped with itself.
  820. if (row === this.rowObject.element) {
  821. return null;
  822. }
  823. }
  824. // Check that swapping with this row is allowed.
  825. if (!this.rowObject.isValidSwap(row)) {
  826. return null;
  827. }
  828. // We may have found the row the mouse just passed over, but it doesn't
  829. // take into account hidden rows. Skip backwards until we find a
  830. // draggable row.
  831. while ($row.is(':hidden') && $row.prev('tr').is(':hidden')) {
  832. $row = $row.prev('tr:first-of-type');
  833. row = $row.get(0);
  834. }
  835. return row;
  836. }
  837. }
  838. return null;
  839. };
  840. /**
  841. * After the row is dropped, update the table fields.
  842. *
  843. * @param {HTMLElement} changedRow
  844. * DOM object for the row that was just dropped.
  845. */
  846. Drupal.tableDrag.prototype.updateFields = function (changedRow) {
  847. for (var group in this.tableSettings) {
  848. if (this.tableSettings.hasOwnProperty(group)) {
  849. // Each group may have a different setting for relationship, so we find
  850. // the source rows for each separately.
  851. this.updateField(changedRow, group);
  852. }
  853. }
  854. };
  855. /**
  856. * After the row is dropped, update a single table field.
  857. *
  858. * @param {HTMLElement} changedRow
  859. * DOM object for the row that was just dropped.
  860. * @param {string} group
  861. * The settings group on which field updates will occur.
  862. */
  863. Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
  864. var rowSettings = this.rowSettings(group, changedRow);
  865. var $changedRow = $(changedRow);
  866. var sourceRow;
  867. var $previousRow;
  868. var previousRow;
  869. var useSibling;
  870. // Set the row as its own target.
  871. if (rowSettings.relationship === 'self' || rowSettings.relationship === 'group') {
  872. sourceRow = changedRow;
  873. }
  874. // Siblings are easy, check previous and next rows.
  875. else if (rowSettings.relationship === 'sibling') {
  876. $previousRow = $changedRow.prev('tr:first-of-type');
  877. previousRow = $previousRow.get(0);
  878. var $nextRow = $changedRow.next('tr:first-of-type');
  879. var nextRow = $nextRow.get(0);
  880. sourceRow = changedRow;
  881. if ($previousRow.is('.draggable') && $previousRow.find('.' + group).length) {
  882. if (this.indentEnabled) {
  883. if ($previousRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) {
  884. sourceRow = previousRow;
  885. }
  886. }
  887. else {
  888. sourceRow = previousRow;
  889. }
  890. }
  891. else if ($nextRow.is('.draggable') && $nextRow.find('.' + group).length) {
  892. if (this.indentEnabled) {
  893. if ($nextRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) {
  894. sourceRow = nextRow;
  895. }
  896. }
  897. else {
  898. sourceRow = nextRow;
  899. }
  900. }
  901. }
  902. // Parents, look up the tree until we find a field not in this group.
  903. // Go up as many parents as indentations in the changed row.
  904. else if (rowSettings.relationship === 'parent') {
  905. $previousRow = $changedRow.prev('tr');
  906. previousRow = $previousRow;
  907. while ($previousRow.length && $previousRow.find('.js-indentation').length >= this.rowObject.indents) {
  908. $previousRow = $previousRow.prev('tr');
  909. previousRow = $previousRow;
  910. }
  911. // If we found a row.
  912. if ($previousRow.length) {
  913. sourceRow = $previousRow.get(0);
  914. }
  915. // Otherwise we went all the way to the left of the table without finding
  916. // a parent, meaning this item has been placed at the root level.
  917. else {
  918. // Use the first row in the table as source, because it's guaranteed to
  919. // be at the root level. Find the first item, then compare this row
  920. // against it as a sibling.
  921. sourceRow = $(this.table).find('tr.draggable:first-of-type').get(0);
  922. if (sourceRow === this.rowObject.element) {
  923. sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
  924. }
  925. useSibling = true;
  926. }
  927. }
  928. // Because we may have moved the row from one category to another,
  929. // take a look at our sibling and borrow its sources and targets.
  930. this.copyDragClasses(sourceRow, changedRow, group);
  931. rowSettings = this.rowSettings(group, changedRow);
  932. // In the case that we're looking for a parent, but the row is at the top
  933. // of the tree, copy our sibling's values.
  934. if (useSibling) {
  935. rowSettings.relationship = 'sibling';
  936. rowSettings.source = rowSettings.target;
  937. }
  938. var targetClass = '.' + rowSettings.target;
  939. var targetElement = $changedRow.find(targetClass).get(0);
  940. // Check if a target element exists in this row.
  941. if (targetElement) {
  942. var sourceClass = '.' + rowSettings.source;
  943. var sourceElement = $(sourceClass, sourceRow).get(0);
  944. switch (rowSettings.action) {
  945. case 'depth':
  946. // Get the depth of the target row.
  947. targetElement.value = $(sourceElement).closest('tr').find('.js-indentation').length;
  948. break;
  949. case 'match':
  950. // Update the value.
  951. targetElement.value = sourceElement.value;
  952. break;
  953. case 'order':
  954. var siblings = this.rowObject.findSiblings(rowSettings);
  955. if ($(targetElement).is('select')) {
  956. // Get a list of acceptable values.
  957. var values = [];
  958. $(targetElement).find('option').each(function () {
  959. values.push(this.value);
  960. });
  961. var maxVal = values[values.length - 1];
  962. // Populate the values in the siblings.
  963. $(siblings).find(targetClass).each(function () {
  964. // If there are more items than possible values, assign the
  965. // maximum value to the row.
  966. if (values.length > 0) {
  967. this.value = values.shift();
  968. }
  969. else {
  970. this.value = maxVal;
  971. }
  972. });
  973. }
  974. else {
  975. // Assume a numeric input field.
  976. var weight = parseInt($(siblings[0]).find(targetClass).val(), 10) || 0;
  977. $(siblings).find(targetClass).each(function () {
  978. this.value = weight;
  979. weight++;
  980. });
  981. }
  982. break;
  983. }
  984. }
  985. };
  986. /**
  987. * Copy all tableDrag related classes from one row to another.
  988. *
  989. * Copy all special tableDrag classes from one row's form elements to a
  990. * different one, removing any special classes that the destination row
  991. * may have had.
  992. *
  993. * @param {HTMLElement} sourceRow
  994. * The element for the source row.
  995. * @param {HTMLElement} targetRow
  996. * The element for the target row.
  997. * @param {string} group
  998. * The group selector.
  999. */
  1000. Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
  1001. var sourceElement = $(sourceRow).find('.' + group);
  1002. var targetElement = $(targetRow).find('.' + group);
  1003. if (sourceElement.length && targetElement.length) {
  1004. targetElement[0].className = sourceElement[0].className;
  1005. }
  1006. };
  1007. /**
  1008. * Check the suggested scroll of the table.
  1009. *
  1010. * @param {number} cursorY
  1011. * The Y position of the cursor.
  1012. *
  1013. * @return {number}
  1014. * The suggested scroll.
  1015. */
  1016. Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
  1017. var de = document.documentElement;
  1018. var b = document.body;
  1019. var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth !== 0 ? de.clientHeight : b.offsetHeight);
  1020. var scrollY;
  1021. if (document.all) {
  1022. scrollY = this.scrollY = !de.scrollTop ? b.scrollTop : de.scrollTop;
  1023. }
  1024. else {
  1025. scrollY = this.scrollY = window.pageYOffset ? window.pageYOffset : window.scrollY;
  1026. }
  1027. var trigger = this.scrollSettings.trigger;
  1028. var delta = 0;
  1029. // Return a scroll speed relative to the edge of the screen.
  1030. if (cursorY - scrollY > windowHeight - trigger) {
  1031. delta = trigger / (windowHeight + scrollY - cursorY);
  1032. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  1033. return delta * this.scrollSettings.amount;
  1034. }
  1035. else if (cursorY - scrollY < trigger) {
  1036. delta = trigger / (cursorY - scrollY);
  1037. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  1038. return -delta * this.scrollSettings.amount;
  1039. }
  1040. };
  1041. /**
  1042. * Set the scroll for the table.
  1043. *
  1044. * @param {number} scrollAmount
  1045. * The amount of scroll to apply to the window.
  1046. */
  1047. Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
  1048. var self = this;
  1049. this.scrollInterval = setInterval(function () {
  1050. // Update the scroll values stored in the object.
  1051. self.checkScroll(self.currentPointerCoords.y);
  1052. var aboveTable = self.scrollY > self.table.topY;
  1053. var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
  1054. if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
  1055. window.scrollBy(0, scrollAmount);
  1056. }
  1057. }, this.scrollSettings.interval);
  1058. };
  1059. /**
  1060. * Command to restripe table properly.
  1061. */
  1062. Drupal.tableDrag.prototype.restripeTable = function () {
  1063. // :even and :odd are reversed because jQuery counts from 0 and
  1064. // we count from 1, so we're out of sync.
  1065. // Match immediate children of the parent element to allow nesting.
  1066. $(this.table).find('> tbody > tr.draggable:visible, > tr.draggable:visible')
  1067. .removeClass('odd even')
  1068. .filter(':odd').addClass('even').end()
  1069. .filter(':even').addClass('odd');
  1070. };
  1071. /**
  1072. * Stub function. Allows a custom handler when a row begins dragging.
  1073. *
  1074. * @return {null}
  1075. * Returns null when the stub function is used.
  1076. */
  1077. Drupal.tableDrag.prototype.onDrag = function () {
  1078. return null;
  1079. };
  1080. /**
  1081. * Stub function. Allows a custom handler when a row is dropped.
  1082. *
  1083. * @return {null}
  1084. * Returns null when the stub function is used.
  1085. */
  1086. Drupal.tableDrag.prototype.onDrop = function () {
  1087. return null;
  1088. };
  1089. /**
  1090. * Constructor to make a new object to manipulate a table row.
  1091. *
  1092. * @param {HTMLElement} tableRow
  1093. * The DOM element for the table row we will be manipulating.
  1094. * @param {string} method
  1095. * The method in which this row is being moved. Either 'keyboard' or
  1096. * 'mouse'.
  1097. * @param {bool} indentEnabled
  1098. * Whether the containing table uses indentations. Used for optimizations.
  1099. * @param {number} maxDepth
  1100. * The maximum amount of indentations this row may contain.
  1101. * @param {bool} addClasses
  1102. * Whether we want to add classes to this row to indicate child
  1103. * relationships.
  1104. */
  1105. Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
  1106. var $tableRow = $(tableRow);
  1107. this.element = tableRow;
  1108. this.method = method;
  1109. this.group = [tableRow];
  1110. this.groupDepth = $tableRow.find('.js-indentation').length;
  1111. this.changed = false;
  1112. this.table = $tableRow.closest('table')[0];
  1113. this.indentEnabled = indentEnabled;
  1114. this.maxDepth = maxDepth;
  1115. // Direction the row is being moved.
  1116. this.direction = '';
  1117. if (this.indentEnabled) {
  1118. this.indents = $tableRow.find('.js-indentation').length;
  1119. this.children = this.findChildren(addClasses);
  1120. this.group = $.merge(this.group, this.children);
  1121. // Find the depth of this entire group.
  1122. for (var n = 0; n < this.group.length; n++) {
  1123. this.groupDepth = Math.max($(this.group[n]).find('.js-indentation').length, this.groupDepth);
  1124. }
  1125. }
  1126. };
  1127. /**
  1128. * Find all children of rowObject by indentation.
  1129. *
  1130. * @param {bool} addClasses
  1131. * Whether we want to add classes to this row to indicate child
  1132. * relationships.
  1133. *
  1134. * @return {Array}
  1135. * An array of children of the row.
  1136. */
  1137. Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
  1138. var parentIndentation = this.indents;
  1139. var currentRow = $(this.element, this.table).next('tr.draggable');
  1140. var rows = [];
  1141. var child = 0;
  1142. function rowIndentation(indentNum, el) {
  1143. var self = $(el);
  1144. if (child === 1 && (indentNum === parentIndentation)) {
  1145. self.addClass('tree-child-first');
  1146. }
  1147. if (indentNum === parentIndentation) {
  1148. self.addClass('tree-child');
  1149. }
  1150. else if (indentNum > parentIndentation) {
  1151. self.addClass('tree-child-horizontal');
  1152. }
  1153. }
  1154. while (currentRow.length) {
  1155. // A greater indentation indicates this is a child.
  1156. if (currentRow.find('.js-indentation').length > parentIndentation) {
  1157. child++;
  1158. rows.push(currentRow[0]);
  1159. if (addClasses) {
  1160. currentRow.find('.js-indentation').each(rowIndentation);
  1161. }
  1162. }
  1163. else {
  1164. break;
  1165. }
  1166. currentRow = currentRow.next('tr.draggable');
  1167. }
  1168. if (addClasses && rows.length) {
  1169. $(rows[rows.length - 1]).find('.js-indentation:nth-child(' + (parentIndentation + 1) + ')').addClass('tree-child-last');
  1170. }
  1171. return rows;
  1172. };
  1173. /**
  1174. * Ensure that two rows are allowed to be swapped.
  1175. *
  1176. * @param {HTMLElement} row
  1177. * DOM object for the row being considered for swapping.
  1178. *
  1179. * @return {bool}
  1180. * Whether the swap is a valid swap or not.
  1181. */
  1182. Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
  1183. var $row = $(row);
  1184. if (this.indentEnabled) {
  1185. var prevRow;
  1186. var nextRow;
  1187. if (this.direction === 'down') {
  1188. prevRow = row;
  1189. nextRow = $row.next('tr').get(0);
  1190. }
  1191. else {
  1192. prevRow = $row.prev('tr').get(0);
  1193. nextRow = row;
  1194. }
  1195. this.interval = this.validIndentInterval(prevRow, nextRow);
  1196. // We have an invalid swap if the valid indentations interval is empty.
  1197. if (this.interval.min > this.interval.max) {
  1198. return false;
  1199. }
  1200. }
  1201. // Do not let an un-draggable first row have anything put before it.
  1202. if (this.table.tBodies[0].rows[0] === row && $row.is(':not(.draggable)')) {
  1203. return false;
  1204. }
  1205. return true;
  1206. };
  1207. /**
  1208. * Perform the swap between two rows.
  1209. *
  1210. * @param {string} position
  1211. * Whether the swap will occur 'before' or 'after' the given row.
  1212. * @param {HTMLElement} row
  1213. * DOM element what will be swapped with the row group.
  1214. */
  1215. Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
  1216. // Makes sure only DOM object are passed to Drupal.detachBehaviors().
  1217. this.group.forEach(function (row) {
  1218. Drupal.detachBehaviors(row, drupalSettings, 'move');
  1219. });
  1220. $(row)[position](this.group);
  1221. // Makes sure only DOM object are passed to Drupal.attachBehaviors()s.
  1222. this.group.forEach(function (row) {
  1223. Drupal.attachBehaviors(row, drupalSettings);
  1224. });
  1225. this.changed = true;
  1226. this.onSwap(row);
  1227. };
  1228. /**
  1229. * Determine the valid indentations interval for the row at a given position.
  1230. *
  1231. * @param {?HTMLElement} prevRow
  1232. * DOM object for the row before the tested position
  1233. * (or null for first position in the table).
  1234. * @param {?HTMLElement} nextRow
  1235. * DOM object for the row after the tested position
  1236. * (or null for last position in the table).
  1237. *
  1238. * @return {object}
  1239. * An object with the keys `min` and `max` to indicate the valid indent
  1240. * interval.
  1241. */
  1242. Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
  1243. var $prevRow = $(prevRow);
  1244. var minIndent;
  1245. var maxIndent;
  1246. // Minimum indentation:
  1247. // Do not orphan the next row.
  1248. minIndent = nextRow ? $(nextRow).find('.js-indentation').length : 0;
  1249. // Maximum indentation:
  1250. if (!prevRow || $prevRow.is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
  1251. // Do not indent:
  1252. // - the first row in the table,
  1253. // - rows dragged below a non-draggable row,
  1254. // - 'root' rows.
  1255. maxIndent = 0;
  1256. }
  1257. else {
  1258. // Do not go deeper than as a child of the previous row.
  1259. maxIndent = $prevRow.find('.js-indentation').length + ($prevRow.is('.tabledrag-leaf') ? 0 : 1);
  1260. // Limit by the maximum allowed depth for the table.
  1261. if (this.maxDepth) {
  1262. maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
  1263. }
  1264. }
  1265. return {min: minIndent, max: maxIndent};
  1266. };
  1267. /**
  1268. * Indent a row within the legal bounds of the table.
  1269. *
  1270. * @param {number} indentDiff
  1271. * The number of additional indentations proposed for the row (can be
  1272. * positive or negative). This number will be adjusted to nearest valid
  1273. * indentation level for the row.
  1274. *
  1275. * @return {number}
  1276. * The number of indentations applied.
  1277. */
  1278. Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
  1279. var $group = $(this.group);
  1280. // Determine the valid indentations interval if not available yet.
  1281. if (!this.interval) {
  1282. var prevRow = $(this.element).prev('tr').get(0);
  1283. var nextRow = $group.eq(-1).next('tr').get(0);
  1284. this.interval = this.validIndentInterval(prevRow, nextRow);
  1285. }
  1286. // Adjust to the nearest valid indentation.
  1287. var indent = this.indents + indentDiff;
  1288. indent = Math.max(indent, this.interval.min);
  1289. indent = Math.min(indent, this.interval.max);
  1290. indentDiff = indent - this.indents;
  1291. for (var n = 1; n <= Math.abs(indentDiff); n++) {
  1292. // Add or remove indentations.
  1293. if (indentDiff < 0) {
  1294. $group.find('.js-indentation:first-of-type').remove();
  1295. this.indents--;
  1296. }
  1297. else {
  1298. $group.find('td:first-of-type').prepend(Drupal.theme('tableDragIndentation'));
  1299. this.indents++;
  1300. }
  1301. }
  1302. if (indentDiff) {
  1303. // Update indentation for this row.
  1304. this.changed = true;
  1305. this.groupDepth += indentDiff;
  1306. this.onIndent();
  1307. }
  1308. return indentDiff;
  1309. };
  1310. /**
  1311. * Find all siblings for a row.
  1312. *
  1313. * According to its subgroup or indentation. Note that the passed-in row is
  1314. * included in the list of siblings.
  1315. *
  1316. * @param {object} rowSettings
  1317. * The field settings we're using to identify what constitutes a sibling.
  1318. *
  1319. * @return {Array}
  1320. * An array of siblings.
  1321. */
  1322. Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
  1323. var siblings = [];
  1324. var directions = ['prev', 'next'];
  1325. var rowIndentation = this.indents;
  1326. var checkRowIndentation;
  1327. for (var d = 0; d < directions.length; d++) {
  1328. var checkRow = $(this.element)[directions[d]]();
  1329. while (checkRow.length) {
  1330. // Check that the sibling contains a similar target field.
  1331. if (checkRow.find('.' + rowSettings.target)) {
  1332. // Either add immediately if this is a flat table, or check to ensure
  1333. // that this row has the same level of indentation.
  1334. if (this.indentEnabled) {
  1335. checkRowIndentation = checkRow.find('.js-indentation').length;
  1336. }
  1337. if (!(this.indentEnabled) || (checkRowIndentation === rowIndentation)) {
  1338. siblings.push(checkRow[0]);
  1339. }
  1340. else if (checkRowIndentation < rowIndentation) {
  1341. // No need to keep looking for siblings when we get to a parent.
  1342. break;
  1343. }
  1344. }
  1345. else {
  1346. break;
  1347. }
  1348. checkRow = checkRow[directions[d]]();
  1349. }
  1350. // Since siblings are added in reverse order for previous, reverse the
  1351. // completed list of previous siblings. Add the current row and continue.
  1352. if (directions[d] === 'prev') {
  1353. siblings.reverse();
  1354. siblings.push(this.element);
  1355. }
  1356. }
  1357. return siblings;
  1358. };
  1359. /**
  1360. * Remove indentation helper classes from the current row group.
  1361. */
  1362. Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
  1363. for (var n in this.children) {
  1364. if (this.children.hasOwnProperty(n)) {
  1365. $(this.children[n]).find('.js-indentation')
  1366. .removeClass('tree-child')
  1367. .removeClass('tree-child-first')
  1368. .removeClass('tree-child-last')
  1369. .removeClass('tree-child-horizontal');
  1370. }
  1371. }
  1372. };
  1373. /**
  1374. * Add an asterisk or other marker to the changed row.
  1375. */
  1376. Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
  1377. var marker = Drupal.theme('tableDragChangedMarker');
  1378. var cell = $(this.element).find('td:first-of-type');
  1379. if (cell.find('abbr.tabledrag-changed').length === 0) {
  1380. cell.append(marker);
  1381. }
  1382. };
  1383. /**
  1384. * Stub function. Allows a custom handler when a row is indented.
  1385. *
  1386. * @return {null}
  1387. * Returns null when the stub function is used.
  1388. */
  1389. Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
  1390. return null;
  1391. };
  1392. /**
  1393. * Stub function. Allows a custom handler when a row is swapped.
  1394. *
  1395. * @param {HTMLElement} swappedRow
  1396. * The element for the swapped row.
  1397. *
  1398. * @return {null}
  1399. * Returns null when the stub function is used.
  1400. */
  1401. Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
  1402. return null;
  1403. };
  1404. $.extend(Drupal.theme, /** @lends Drupal.theme */{
  1405. /**
  1406. * @return {string}
  1407. * Markup for the marker.
  1408. */
  1409. tableDragChangedMarker: function () {
  1410. return '<abbr class="warning tabledrag-changed" title="' + Drupal.t('Changed') + '">*</abbr>';
  1411. },
  1412. /**
  1413. * @return {string}
  1414. * Markup for the indentation.
  1415. */
  1416. tableDragIndentation: function () {
  1417. return '<div class="js-indentation indentation">&nbsp;</div>';
  1418. },
  1419. /**
  1420. * @return {string}
  1421. * Markup for the warning.
  1422. */
  1423. tableDragChangedWarning: function () {
  1424. return '<div class="tabledrag-changed-warning messages messages--warning" role="alert">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('You have unsaved changes.') + '</div>';
  1425. }
  1426. });
  1427. })(jQuery, Drupal, drupalSettings);