tabledrag.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  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. switch (event.keyCode) {
  456. // Left arrow.
  457. case 37:
  458. // Safari left arrow.
  459. case 63234:
  460. keyChange = true;
  461. self.rowObject.indent(-1 * self.rtl);
  462. break;
  463. // Up arrow.
  464. case 38:
  465. // Safari up arrow.
  466. case 63232:
  467. var $previousRow = $(self.rowObject.element).prev('tr:first-of-type');
  468. var previousRow = $previousRow.get(0);
  469. while (previousRow && $previousRow.is(':hidden')) {
  470. $previousRow = $(previousRow).prev('tr:first-of-type');
  471. previousRow = $previousRow.get(0);
  472. }
  473. if (previousRow) {
  474. // Do not allow the onBlur cleanup.
  475. self.safeBlur = false;
  476. self.rowObject.direction = 'up';
  477. keyChange = true;
  478. if ($(item).is('.tabledrag-root')) {
  479. // Swap with the previous top-level row.
  480. groupHeight = 0;
  481. while (previousRow && $previousRow.find('.js-indentation').length) {
  482. $previousRow = $(previousRow).prev('tr:first-of-type');
  483. previousRow = $previousRow.get(0);
  484. groupHeight += $previousRow.is(':hidden') ? 0 : previousRow.offsetHeight;
  485. }
  486. if (previousRow) {
  487. self.rowObject.swap('before', previousRow);
  488. // No need to check for indentation, 0 is the only valid one.
  489. window.scrollBy(0, -groupHeight);
  490. }
  491. }
  492. else if (self.table.tBodies[0].rows[0] !== previousRow || $previousRow.is('.draggable')) {
  493. // Swap with the previous row (unless previous row is the first
  494. // one and undraggable).
  495. self.rowObject.swap('before', previousRow);
  496. self.rowObject.interval = null;
  497. self.rowObject.indent(0);
  498. window.scrollBy(0, -parseInt(item.offsetHeight, 10));
  499. }
  500. // Regain focus after the DOM manipulation.
  501. handle.trigger('focus');
  502. }
  503. break;
  504. // Right arrow.
  505. case 39:
  506. // Safari right arrow.
  507. case 63235:
  508. keyChange = true;
  509. self.rowObject.indent(self.rtl);
  510. break;
  511. // Down arrow.
  512. case 40:
  513. // Safari down arrow.
  514. case 63233:
  515. var $nextRow = $(self.rowObject.group).eq(-1).next('tr:first-of-type');
  516. var nextRow = $nextRow.get(0);
  517. while (nextRow && $nextRow.is(':hidden')) {
  518. $nextRow = $(nextRow).next('tr:first-of-type');
  519. nextRow = $nextRow.get(0);
  520. }
  521. if (nextRow) {
  522. // Do not allow the onBlur cleanup.
  523. self.safeBlur = false;
  524. self.rowObject.direction = 'down';
  525. keyChange = true;
  526. if ($(item).is('.tabledrag-root')) {
  527. // Swap with the next group (necessarily a top-level one).
  528. groupHeight = 0;
  529. var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
  530. if (nextGroup) {
  531. $(nextGroup.group).each(function () {
  532. groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
  533. });
  534. var nextGroupRow = $(nextGroup.group).eq(-1).get(0);
  535. self.rowObject.swap('after', nextGroupRow);
  536. // No need to check for indentation, 0 is the only valid one.
  537. window.scrollBy(0, parseInt(groupHeight, 10));
  538. }
  539. }
  540. else {
  541. // Swap with the next row.
  542. self.rowObject.swap('after', nextRow);
  543. self.rowObject.interval = null;
  544. self.rowObject.indent(0);
  545. window.scrollBy(0, parseInt(item.offsetHeight, 10));
  546. }
  547. // Regain focus after the DOM manipulation.
  548. handle.trigger('focus');
  549. }
  550. break;
  551. }
  552. if (self.rowObject && self.rowObject.changed === true) {
  553. $(item).addClass('drag');
  554. if (self.oldRowElement) {
  555. $(self.oldRowElement).removeClass('drag-previous');
  556. }
  557. self.oldRowElement = item;
  558. if (self.striping === true) {
  559. self.restripeTable();
  560. }
  561. self.onDrag();
  562. }
  563. // Returning false if we have an arrow key to prevent scrolling.
  564. if (keyChange) {
  565. return false;
  566. }
  567. });
  568. // Compatibility addition, return false on keypress to prevent unwanted
  569. // scrolling. IE and Safari will suppress scrolling on keydown, but all
  570. // other browsers need to return false on keypress.
  571. // http://www.quirksmode.org/js/keys.html
  572. handle.on('keypress', function (event) {
  573. switch (event.keyCode) {
  574. // Left arrow.
  575. case 37:
  576. // Up arrow.
  577. case 38:
  578. // Right arrow.
  579. case 39:
  580. // Down arrow.
  581. case 40:
  582. return false;
  583. }
  584. });
  585. };
  586. /**
  587. * Pointer event initiator, creates drag object and information.
  588. *
  589. * @param {jQuery.Event} event
  590. * The event object that trigger the drag.
  591. * @param {Drupal.tableDrag} self
  592. * The drag handle.
  593. * @param {HTMLElement} item
  594. * The item that that is being dragged.
  595. */
  596. Drupal.tableDrag.prototype.dragStart = function (event, self, item) {
  597. // Create a new dragObject recording the pointer information.
  598. self.dragObject = {};
  599. self.dragObject.initOffset = self.getPointerOffset(item, event);
  600. self.dragObject.initPointerCoords = self.pointerCoords(event);
  601. if (self.indentEnabled) {
  602. self.dragObject.indentPointerPos = self.dragObject.initPointerCoords;
  603. }
  604. // If there's a lingering row object from the keyboard, remove its focus.
  605. if (self.rowObject) {
  606. $(self.rowObject.element).find('a.tabledrag-handle').trigger('blur');
  607. }
  608. // Create a new rowObject for manipulation of this row.
  609. self.rowObject = new self.row(item, 'pointer', self.indentEnabled, self.maxDepth, true);
  610. // Save the position of the table.
  611. self.table.topY = $(self.table).offset().top;
  612. self.table.bottomY = self.table.topY + self.table.offsetHeight;
  613. // Add classes to the handle and row.
  614. $(item).addClass('drag');
  615. // Set the document to use the move cursor during drag.
  616. $('body').addClass('drag');
  617. if (self.oldRowElement) {
  618. $(self.oldRowElement).removeClass('drag-previous');
  619. }
  620. };
  621. /**
  622. * Pointer movement handler, bound to document.
  623. *
  624. * @param {jQuery.Event} event
  625. * The pointer event.
  626. * @param {Drupal.tableDrag} self
  627. * The tableDrag instance.
  628. *
  629. * @return {bool|undefined}
  630. * Undefined if no dragObject is defined, false otherwise.
  631. */
  632. Drupal.tableDrag.prototype.dragRow = function (event, self) {
  633. if (self.dragObject) {
  634. self.currentPointerCoords = self.pointerCoords(event);
  635. var y = self.currentPointerCoords.y - self.dragObject.initOffset.y;
  636. var x = self.currentPointerCoords.x - self.dragObject.initOffset.x;
  637. // Check for row swapping and vertical scrolling.
  638. if (y !== self.oldY) {
  639. self.rowObject.direction = y > self.oldY ? 'down' : 'up';
  640. // Update the old value.
  641. self.oldY = y;
  642. // Check if the window should be scrolled (and how fast).
  643. var scrollAmount = self.checkScroll(self.currentPointerCoords.y);
  644. // Stop any current scrolling.
  645. clearInterval(self.scrollInterval);
  646. // Continue scrolling if the mouse has moved in the scroll direction.
  647. if (scrollAmount > 0 && self.rowObject.direction === 'down' || scrollAmount < 0 && self.rowObject.direction === 'up') {
  648. self.setScroll(scrollAmount);
  649. }
  650. // If we have a valid target, perform the swap and restripe the table.
  651. var currentRow = self.findDropTargetRow(x, y);
  652. if (currentRow) {
  653. if (self.rowObject.direction === 'down') {
  654. self.rowObject.swap('after', currentRow, self);
  655. }
  656. else {
  657. self.rowObject.swap('before', currentRow, self);
  658. }
  659. if (self.striping === true) {
  660. self.restripeTable();
  661. }
  662. }
  663. }
  664. // Similar to row swapping, handle indentations.
  665. if (self.indentEnabled) {
  666. var xDiff = self.currentPointerCoords.x - self.dragObject.indentPointerPos.x;
  667. // Set the number of indentations the pointer has been moved left or
  668. // right.
  669. var indentDiff = Math.round(xDiff / self.indentAmount);
  670. // Indent the row with our estimated diff, which may be further
  671. // restricted according to the rows around this row.
  672. var indentChange = self.rowObject.indent(indentDiff);
  673. // Update table and pointer indentations.
  674. self.dragObject.indentPointerPos.x += self.indentAmount * indentChange * self.rtl;
  675. self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
  676. }
  677. return false;
  678. }
  679. };
  680. /**
  681. * Pointerup behavior.
  682. *
  683. * @param {jQuery.Event} event
  684. * The pointer event.
  685. * @param {Drupal.tableDrag} self
  686. * The tableDrag instance.
  687. */
  688. Drupal.tableDrag.prototype.dropRow = function (event, self) {
  689. var droppedRow;
  690. var $droppedRow;
  691. // Drop row functionality.
  692. if (self.rowObject !== null) {
  693. droppedRow = self.rowObject.element;
  694. $droppedRow = $(droppedRow);
  695. // The row is already in the right place so we just release it.
  696. if (self.rowObject.changed === true) {
  697. // Update the fields in the dropped row.
  698. self.updateFields(droppedRow);
  699. // If a setting exists for affecting the entire group, update all the
  700. // fields in the entire dragged group.
  701. for (var group in self.tableSettings) {
  702. if (self.tableSettings.hasOwnProperty(group)) {
  703. var rowSettings = self.rowSettings(group, droppedRow);
  704. if (rowSettings.relationship === 'group') {
  705. for (var n in self.rowObject.children) {
  706. if (self.rowObject.children.hasOwnProperty(n)) {
  707. self.updateField(self.rowObject.children[n], group);
  708. }
  709. }
  710. }
  711. }
  712. }
  713. self.rowObject.markChanged();
  714. if (self.changed === false) {
  715. $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
  716. self.changed = true;
  717. }
  718. }
  719. if (self.indentEnabled) {
  720. self.rowObject.removeIndentClasses();
  721. }
  722. if (self.oldRowElement) {
  723. $(self.oldRowElement).removeClass('drag-previous');
  724. }
  725. $droppedRow.removeClass('drag').addClass('drag-previous');
  726. self.oldRowElement = droppedRow;
  727. self.onDrop();
  728. self.rowObject = null;
  729. }
  730. // Functionality specific only to pointerup events.
  731. if (self.dragObject !== null) {
  732. self.dragObject = null;
  733. $('body').removeClass('drag');
  734. clearInterval(self.scrollInterval);
  735. }
  736. };
  737. /**
  738. * Get the coordinates from the event (allowing for browser differences).
  739. *
  740. * @param {jQuery.Event} event
  741. * The pointer event.
  742. *
  743. * @return {object}
  744. * An object with `x` and `y` keys indicating the position.
  745. */
  746. Drupal.tableDrag.prototype.pointerCoords = function (event) {
  747. if (event.pageX || event.pageY) {
  748. return {x: event.pageX, y: event.pageY};
  749. }
  750. return {
  751. x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
  752. y: event.clientY + document.body.scrollTop - document.body.clientTop
  753. };
  754. };
  755. /**
  756. * Get the event offset from the target element.
  757. *
  758. * Given a target element and a pointer event, get the event offset from that
  759. * element. To do this we need the element's position and the target position.
  760. *
  761. * @param {HTMLElement} target
  762. * The target HTML element.
  763. * @param {jQuery.Event} event
  764. * The pointer event.
  765. *
  766. * @return {object}
  767. * An object with `x` and `y` keys indicating the position.
  768. */
  769. Drupal.tableDrag.prototype.getPointerOffset = function (target, event) {
  770. var docPos = $(target).offset();
  771. var pointerPos = this.pointerCoords(event);
  772. return {x: pointerPos.x - docPos.left, y: pointerPos.y - docPos.top};
  773. };
  774. /**
  775. * Find the row the mouse is currently over.
  776. *
  777. * This row is then taken and swapped with the one being dragged.
  778. *
  779. * @param {number} x
  780. * The x coordinate of the mouse on the page (not the screen).
  781. * @param {number} y
  782. * The y coordinate of the mouse on the page (not the screen).
  783. *
  784. * @return {*}
  785. * The drop target row, if found.
  786. */
  787. Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
  788. var rows = $(this.table.tBodies[0].rows).not(':hidden');
  789. for (var n = 0; n < rows.length; n++) {
  790. var row = rows[n];
  791. var $row = $(row);
  792. var rowY = $row.offset().top;
  793. var rowHeight;
  794. // Because Safari does not report offsetHeight on table rows, but does on
  795. // table cells, grab the firstChild of the row and use that instead.
  796. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
  797. if (row.offsetHeight === 0) {
  798. rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
  799. }
  800. // Other browsers.
  801. else {
  802. rowHeight = parseInt(row.offsetHeight, 10) / 2;
  803. }
  804. // Because we always insert before, we need to offset the height a bit.
  805. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
  806. if (this.indentEnabled) {
  807. // Check that this row is not a child of the row being dragged.
  808. for (n in this.rowObject.group) {
  809. if (this.rowObject.group[n] === row) {
  810. return null;
  811. }
  812. }
  813. }
  814. else {
  815. // Do not allow a row to be swapped with itself.
  816. if (row === this.rowObject.element) {
  817. return null;
  818. }
  819. }
  820. // Check that swapping with this row is allowed.
  821. if (!this.rowObject.isValidSwap(row)) {
  822. return null;
  823. }
  824. // We may have found the row the mouse just passed over, but it doesn't
  825. // take into account hidden rows. Skip backwards until we find a
  826. // draggable row.
  827. while ($row.is(':hidden') && $row.prev('tr').is(':hidden')) {
  828. $row = $row.prev('tr:first-of-type');
  829. row = $row.get(0);
  830. }
  831. return row;
  832. }
  833. }
  834. return null;
  835. };
  836. /**
  837. * After the row is dropped, update the table fields.
  838. *
  839. * @param {HTMLElement} changedRow
  840. * DOM object for the row that was just dropped.
  841. */
  842. Drupal.tableDrag.prototype.updateFields = function (changedRow) {
  843. for (var group in this.tableSettings) {
  844. if (this.tableSettings.hasOwnProperty(group)) {
  845. // Each group may have a different setting for relationship, so we find
  846. // the source rows for each separately.
  847. this.updateField(changedRow, group);
  848. }
  849. }
  850. };
  851. /**
  852. * After the row is dropped, update a single table field.
  853. *
  854. * @param {HTMLElement} changedRow
  855. * DOM object for the row that was just dropped.
  856. * @param {string} group
  857. * The settings group on which field updates will occur.
  858. */
  859. Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
  860. var rowSettings = this.rowSettings(group, changedRow);
  861. var $changedRow = $(changedRow);
  862. var sourceRow;
  863. var $previousRow;
  864. var previousRow;
  865. var useSibling;
  866. // Set the row as its own target.
  867. if (rowSettings.relationship === 'self' || rowSettings.relationship === 'group') {
  868. sourceRow = changedRow;
  869. }
  870. // Siblings are easy, check previous and next rows.
  871. else if (rowSettings.relationship === 'sibling') {
  872. $previousRow = $changedRow.prev('tr:first-of-type');
  873. previousRow = $previousRow.get(0);
  874. var $nextRow = $changedRow.next('tr:first-of-type');
  875. var nextRow = $nextRow.get(0);
  876. sourceRow = changedRow;
  877. if ($previousRow.is('.draggable') && $previousRow.find('.' + group).length) {
  878. if (this.indentEnabled) {
  879. if ($previousRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) {
  880. sourceRow = previousRow;
  881. }
  882. }
  883. else {
  884. sourceRow = previousRow;
  885. }
  886. }
  887. else if ($nextRow.is('.draggable') && $nextRow.find('.' + group).length) {
  888. if (this.indentEnabled) {
  889. if ($nextRow.find('.js-indentations').length === $changedRow.find('.js-indentations').length) {
  890. sourceRow = nextRow;
  891. }
  892. }
  893. else {
  894. sourceRow = nextRow;
  895. }
  896. }
  897. }
  898. // Parents, look up the tree until we find a field not in this group.
  899. // Go up as many parents as indentations in the changed row.
  900. else if (rowSettings.relationship === 'parent') {
  901. $previousRow = $changedRow.prev('tr');
  902. previousRow = $previousRow;
  903. while ($previousRow.length && $previousRow.find('.js-indentation').length >= this.rowObject.indents) {
  904. $previousRow = $previousRow.prev('tr');
  905. previousRow = $previousRow;
  906. }
  907. // If we found a row.
  908. if ($previousRow.length) {
  909. sourceRow = $previousRow.get(0);
  910. }
  911. // Otherwise we went all the way to the left of the table without finding
  912. // a parent, meaning this item has been placed at the root level.
  913. else {
  914. // Use the first row in the table as source, because it's guaranteed to
  915. // be at the root level. Find the first item, then compare this row
  916. // against it as a sibling.
  917. sourceRow = $(this.table).find('tr.draggable:first-of-type').get(0);
  918. if (sourceRow === this.rowObject.element) {
  919. sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
  920. }
  921. useSibling = true;
  922. }
  923. }
  924. // Because we may have moved the row from one category to another,
  925. // take a look at our sibling and borrow its sources and targets.
  926. this.copyDragClasses(sourceRow, changedRow, group);
  927. rowSettings = this.rowSettings(group, changedRow);
  928. // In the case that we're looking for a parent, but the row is at the top
  929. // of the tree, copy our sibling's values.
  930. if (useSibling) {
  931. rowSettings.relationship = 'sibling';
  932. rowSettings.source = rowSettings.target;
  933. }
  934. var targetClass = '.' + rowSettings.target;
  935. var targetElement = $changedRow.find(targetClass).get(0);
  936. // Check if a target element exists in this row.
  937. if (targetElement) {
  938. var sourceClass = '.' + rowSettings.source;
  939. var sourceElement = $(sourceClass, sourceRow).get(0);
  940. switch (rowSettings.action) {
  941. case 'depth':
  942. // Get the depth of the target row.
  943. targetElement.value = $(sourceElement).closest('tr').find('.js-indentation').length;
  944. break;
  945. case 'match':
  946. // Update the value.
  947. targetElement.value = sourceElement.value;
  948. break;
  949. case 'order':
  950. var siblings = this.rowObject.findSiblings(rowSettings);
  951. if ($(targetElement).is('select')) {
  952. // Get a list of acceptable values.
  953. var values = [];
  954. $(targetElement).find('option').each(function () {
  955. values.push(this.value);
  956. });
  957. var maxVal = values[values.length - 1];
  958. // Populate the values in the siblings.
  959. $(siblings).find(targetClass).each(function () {
  960. // If there are more items than possible values, assign the
  961. // maximum value to the row.
  962. if (values.length > 0) {
  963. this.value = values.shift();
  964. }
  965. else {
  966. this.value = maxVal;
  967. }
  968. });
  969. }
  970. else {
  971. // Assume a numeric input field.
  972. var weight = parseInt($(siblings[0]).find(targetClass).val(), 10) || 0;
  973. $(siblings).find(targetClass).each(function () {
  974. this.value = weight;
  975. weight++;
  976. });
  977. }
  978. break;
  979. }
  980. }
  981. };
  982. /**
  983. * Copy all tableDrag related classes from one row to another.
  984. *
  985. * Copy all special tableDrag classes from one row's form elements to a
  986. * different one, removing any special classes that the destination row
  987. * may have had.
  988. *
  989. * @param {HTMLElement} sourceRow
  990. * The element for the source row.
  991. * @param {HTMLElement} targetRow
  992. * The element for the target row.
  993. * @param {string} group
  994. * The group selector.
  995. */
  996. Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
  997. var sourceElement = $(sourceRow).find('.' + group);
  998. var targetElement = $(targetRow).find('.' + group);
  999. if (sourceElement.length && targetElement.length) {
  1000. targetElement[0].className = sourceElement[0].className;
  1001. }
  1002. };
  1003. /**
  1004. * Check the suggested scroll of the table.
  1005. *
  1006. * @param {number} cursorY
  1007. * The Y position of the cursor.
  1008. *
  1009. * @return {number}
  1010. * The suggested scroll.
  1011. */
  1012. Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
  1013. var de = document.documentElement;
  1014. var b = document.body;
  1015. var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth !== 0 ? de.clientHeight : b.offsetHeight);
  1016. var scrollY;
  1017. if (document.all) {
  1018. scrollY = this.scrollY = !de.scrollTop ? b.scrollTop : de.scrollTop;
  1019. }
  1020. else {
  1021. scrollY = this.scrollY = window.pageYOffset ? window.pageYOffset : window.scrollY;
  1022. }
  1023. var trigger = this.scrollSettings.trigger;
  1024. var delta = 0;
  1025. // Return a scroll speed relative to the edge of the screen.
  1026. if (cursorY - scrollY > windowHeight - trigger) {
  1027. delta = trigger / (windowHeight + scrollY - cursorY);
  1028. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  1029. return delta * this.scrollSettings.amount;
  1030. }
  1031. else if (cursorY - scrollY < trigger) {
  1032. delta = trigger / (cursorY - scrollY);
  1033. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  1034. return -delta * this.scrollSettings.amount;
  1035. }
  1036. };
  1037. /**
  1038. * Set the scroll for the table.
  1039. *
  1040. * @param {number} scrollAmount
  1041. * The amount of scroll to apply to the window.
  1042. */
  1043. Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
  1044. var self = this;
  1045. this.scrollInterval = setInterval(function () {
  1046. // Update the scroll values stored in the object.
  1047. self.checkScroll(self.currentPointerCoords.y);
  1048. var aboveTable = self.scrollY > self.table.topY;
  1049. var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
  1050. if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
  1051. window.scrollBy(0, scrollAmount);
  1052. }
  1053. }, this.scrollSettings.interval);
  1054. };
  1055. /**
  1056. * Command to restripe table properly.
  1057. */
  1058. Drupal.tableDrag.prototype.restripeTable = function () {
  1059. // :even and :odd are reversed because jQuery counts from 0 and
  1060. // we count from 1, so we're out of sync.
  1061. // Match immediate children of the parent element to allow nesting.
  1062. $(this.table).find('> tbody > tr.draggable:visible, > tr.draggable:visible')
  1063. .removeClass('odd even')
  1064. .filter(':odd').addClass('even').end()
  1065. .filter(':even').addClass('odd');
  1066. };
  1067. /**
  1068. * Stub function. Allows a custom handler when a row begins dragging.
  1069. *
  1070. * @return {null}
  1071. * Returns null when the stub function is used.
  1072. */
  1073. Drupal.tableDrag.prototype.onDrag = function () {
  1074. return null;
  1075. };
  1076. /**
  1077. * Stub function. Allows a custom handler when a row is dropped.
  1078. *
  1079. * @return {null}
  1080. * Returns null when the stub function is used.
  1081. */
  1082. Drupal.tableDrag.prototype.onDrop = function () {
  1083. return null;
  1084. };
  1085. /**
  1086. * Constructor to make a new object to manipulate a table row.
  1087. *
  1088. * @param {HTMLElement} tableRow
  1089. * The DOM element for the table row we will be manipulating.
  1090. * @param {string} method
  1091. * The method in which this row is being moved. Either 'keyboard' or
  1092. * 'mouse'.
  1093. * @param {bool} indentEnabled
  1094. * Whether the containing table uses indentations. Used for optimizations.
  1095. * @param {number} maxDepth
  1096. * The maximum amount of indentations this row may contain.
  1097. * @param {bool} addClasses
  1098. * Whether we want to add classes to this row to indicate child
  1099. * relationships.
  1100. */
  1101. Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
  1102. var $tableRow = $(tableRow);
  1103. this.element = tableRow;
  1104. this.method = method;
  1105. this.group = [tableRow];
  1106. this.groupDepth = $tableRow.find('.js-indentation').length;
  1107. this.changed = false;
  1108. this.table = $tableRow.closest('table')[0];
  1109. this.indentEnabled = indentEnabled;
  1110. this.maxDepth = maxDepth;
  1111. // Direction the row is being moved.
  1112. this.direction = '';
  1113. if (this.indentEnabled) {
  1114. this.indents = $tableRow.find('.js-indentation').length;
  1115. this.children = this.findChildren(addClasses);
  1116. this.group = $.merge(this.group, this.children);
  1117. // Find the depth of this entire group.
  1118. for (var n = 0; n < this.group.length; n++) {
  1119. this.groupDepth = Math.max($(this.group[n]).find('.js-indentation').length, this.groupDepth);
  1120. }
  1121. }
  1122. };
  1123. /**
  1124. * Find all children of rowObject by indentation.
  1125. *
  1126. * @param {bool} addClasses
  1127. * Whether we want to add classes to this row to indicate child
  1128. * relationships.
  1129. *
  1130. * @return {Array}
  1131. * An array of children of the row.
  1132. */
  1133. Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
  1134. var parentIndentation = this.indents;
  1135. var currentRow = $(this.element, this.table).next('tr.draggable');
  1136. var rows = [];
  1137. var child = 0;
  1138. function rowIndentation(indentNum, el) {
  1139. var self = $(el);
  1140. if (child === 1 && (indentNum === parentIndentation)) {
  1141. self.addClass('tree-child-first');
  1142. }
  1143. if (indentNum === parentIndentation) {
  1144. self.addClass('tree-child');
  1145. }
  1146. else if (indentNum > parentIndentation) {
  1147. self.addClass('tree-child-horizontal');
  1148. }
  1149. }
  1150. while (currentRow.length) {
  1151. // A greater indentation indicates this is a child.
  1152. if (currentRow.find('.js-indentation').length > parentIndentation) {
  1153. child++;
  1154. rows.push(currentRow[0]);
  1155. if (addClasses) {
  1156. currentRow.find('.js-indentation').each(rowIndentation);
  1157. }
  1158. }
  1159. else {
  1160. break;
  1161. }
  1162. currentRow = currentRow.next('tr.draggable');
  1163. }
  1164. if (addClasses && rows.length) {
  1165. $(rows[rows.length - 1]).find('.js-indentation:nth-child(' + (parentIndentation + 1) + ')').addClass('tree-child-last');
  1166. }
  1167. return rows;
  1168. };
  1169. /**
  1170. * Ensure that two rows are allowed to be swapped.
  1171. *
  1172. * @param {HTMLElement} row
  1173. * DOM object for the row being considered for swapping.
  1174. *
  1175. * @return {bool}
  1176. * Whether the swap is a valid swap or not.
  1177. */
  1178. Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
  1179. var $row = $(row);
  1180. if (this.indentEnabled) {
  1181. var prevRow;
  1182. var nextRow;
  1183. if (this.direction === 'down') {
  1184. prevRow = row;
  1185. nextRow = $row.next('tr').get(0);
  1186. }
  1187. else {
  1188. prevRow = $row.prev('tr').get(0);
  1189. nextRow = row;
  1190. }
  1191. this.interval = this.validIndentInterval(prevRow, nextRow);
  1192. // We have an invalid swap if the valid indentations interval is empty.
  1193. if (this.interval.min > this.interval.max) {
  1194. return false;
  1195. }
  1196. }
  1197. // Do not let an un-draggable first row have anything put before it.
  1198. if (this.table.tBodies[0].rows[0] === row && $row.is(':not(.draggable)')) {
  1199. return false;
  1200. }
  1201. return true;
  1202. };
  1203. /**
  1204. * Perform the swap between two rows.
  1205. *
  1206. * @param {string} position
  1207. * Whether the swap will occur 'before' or 'after' the given row.
  1208. * @param {HTMLElement} row
  1209. * DOM element what will be swapped with the row group.
  1210. */
  1211. Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
  1212. // Makes sure only DOM object are passed to Drupal.detachBehaviors().
  1213. this.group.forEach(function (row) {
  1214. Drupal.detachBehaviors(row, drupalSettings, 'move');
  1215. });
  1216. $(row)[position](this.group);
  1217. // Makes sure only DOM object are passed to Drupal.attachBehaviors()s.
  1218. this.group.forEach(function (row) {
  1219. Drupal.attachBehaviors(row, drupalSettings);
  1220. });
  1221. this.changed = true;
  1222. this.onSwap(row);
  1223. };
  1224. /**
  1225. * Determine the valid indentations interval for the row at a given position.
  1226. *
  1227. * @param {?HTMLElement} prevRow
  1228. * DOM object for the row before the tested position
  1229. * (or null for first position in the table).
  1230. * @param {?HTMLElement} nextRow
  1231. * DOM object for the row after the tested position
  1232. * (or null for last position in the table).
  1233. *
  1234. * @return {object}
  1235. * An object with the keys `min` and `max` to indicate the valid indent
  1236. * interval.
  1237. */
  1238. Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
  1239. var $prevRow = $(prevRow);
  1240. var minIndent;
  1241. var maxIndent;
  1242. // Minimum indentation:
  1243. // Do not orphan the next row.
  1244. minIndent = nextRow ? $(nextRow).find('.js-indentation').length : 0;
  1245. // Maximum indentation:
  1246. if (!prevRow || $prevRow.is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
  1247. // Do not indent:
  1248. // - the first row in the table,
  1249. // - rows dragged below a non-draggable row,
  1250. // - 'root' rows.
  1251. maxIndent = 0;
  1252. }
  1253. else {
  1254. // Do not go deeper than as a child of the previous row.
  1255. maxIndent = $prevRow.find('.js-indentation').length + ($prevRow.is('.tabledrag-leaf') ? 0 : 1);
  1256. // Limit by the maximum allowed depth for the table.
  1257. if (this.maxDepth) {
  1258. maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
  1259. }
  1260. }
  1261. return {min: minIndent, max: maxIndent};
  1262. };
  1263. /**
  1264. * Indent a row within the legal bounds of the table.
  1265. *
  1266. * @param {number} indentDiff
  1267. * The number of additional indentations proposed for the row (can be
  1268. * positive or negative). This number will be adjusted to nearest valid
  1269. * indentation level for the row.
  1270. *
  1271. * @return {number}
  1272. * The number of indentations applied.
  1273. */
  1274. Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
  1275. var $group = $(this.group);
  1276. // Determine the valid indentations interval if not available yet.
  1277. if (!this.interval) {
  1278. var prevRow = $(this.element).prev('tr').get(0);
  1279. var nextRow = $group.eq(-1).next('tr').get(0);
  1280. this.interval = this.validIndentInterval(prevRow, nextRow);
  1281. }
  1282. // Adjust to the nearest valid indentation.
  1283. var indent = this.indents + indentDiff;
  1284. indent = Math.max(indent, this.interval.min);
  1285. indent = Math.min(indent, this.interval.max);
  1286. indentDiff = indent - this.indents;
  1287. for (var n = 1; n <= Math.abs(indentDiff); n++) {
  1288. // Add or remove indentations.
  1289. if (indentDiff < 0) {
  1290. $group.find('.js-indentation:first-of-type').remove();
  1291. this.indents--;
  1292. }
  1293. else {
  1294. $group.find('td:first-of-type').prepend(Drupal.theme('tableDragIndentation'));
  1295. this.indents++;
  1296. }
  1297. }
  1298. if (indentDiff) {
  1299. // Update indentation for this row.
  1300. this.changed = true;
  1301. this.groupDepth += indentDiff;
  1302. this.onIndent();
  1303. }
  1304. return indentDiff;
  1305. };
  1306. /**
  1307. * Find all siblings for a row.
  1308. *
  1309. * According to its subgroup or indentation. Note that the passed-in row is
  1310. * included in the list of siblings.
  1311. *
  1312. * @param {object} rowSettings
  1313. * The field settings we're using to identify what constitutes a sibling.
  1314. *
  1315. * @return {Array}
  1316. * An array of siblings.
  1317. */
  1318. Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
  1319. var siblings = [];
  1320. var directions = ['prev', 'next'];
  1321. var rowIndentation = this.indents;
  1322. var checkRowIndentation;
  1323. for (var d = 0; d < directions.length; d++) {
  1324. var checkRow = $(this.element)[directions[d]]();
  1325. while (checkRow.length) {
  1326. // Check that the sibling contains a similar target field.
  1327. if (checkRow.find('.' + rowSettings.target)) {
  1328. // Either add immediately if this is a flat table, or check to ensure
  1329. // that this row has the same level of indentation.
  1330. if (this.indentEnabled) {
  1331. checkRowIndentation = checkRow.find('.js-indentation').length;
  1332. }
  1333. if (!(this.indentEnabled) || (checkRowIndentation === rowIndentation)) {
  1334. siblings.push(checkRow[0]);
  1335. }
  1336. else if (checkRowIndentation < rowIndentation) {
  1337. // No need to keep looking for siblings when we get to a parent.
  1338. break;
  1339. }
  1340. }
  1341. else {
  1342. break;
  1343. }
  1344. checkRow = checkRow[directions[d]]();
  1345. }
  1346. // Since siblings are added in reverse order for previous, reverse the
  1347. // completed list of previous siblings. Add the current row and continue.
  1348. if (directions[d] === 'prev') {
  1349. siblings.reverse();
  1350. siblings.push(this.element);
  1351. }
  1352. }
  1353. return siblings;
  1354. };
  1355. /**
  1356. * Remove indentation helper classes from the current row group.
  1357. */
  1358. Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
  1359. for (var n in this.children) {
  1360. if (this.children.hasOwnProperty(n)) {
  1361. $(this.children[n]).find('.js-indentation')
  1362. .removeClass('tree-child')
  1363. .removeClass('tree-child-first')
  1364. .removeClass('tree-child-last')
  1365. .removeClass('tree-child-horizontal');
  1366. }
  1367. }
  1368. };
  1369. /**
  1370. * Add an asterisk or other marker to the changed row.
  1371. */
  1372. Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
  1373. var marker = Drupal.theme('tableDragChangedMarker');
  1374. var cell = $(this.element).find('td:first-of-type');
  1375. if (cell.find('abbr.tabledrag-changed').length === 0) {
  1376. cell.append(marker);
  1377. }
  1378. };
  1379. /**
  1380. * Stub function. Allows a custom handler when a row is indented.
  1381. *
  1382. * @return {null}
  1383. * Returns null when the stub function is used.
  1384. */
  1385. Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
  1386. return null;
  1387. };
  1388. /**
  1389. * Stub function. Allows a custom handler when a row is swapped.
  1390. *
  1391. * @param {HTMLElement} swappedRow
  1392. * The element for the swapped row.
  1393. *
  1394. * @return {null}
  1395. * Returns null when the stub function is used.
  1396. */
  1397. Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
  1398. return null;
  1399. };
  1400. $.extend(Drupal.theme, /** @lends Drupal.theme */{
  1401. /**
  1402. * @return {string}
  1403. * Markup for the marker.
  1404. */
  1405. tableDragChangedMarker: function () {
  1406. return '<abbr class="warning tabledrag-changed" title="' + Drupal.t('Changed') + '">*</abbr>';
  1407. },
  1408. /**
  1409. * @return {string}
  1410. * Markup for the indentation.
  1411. */
  1412. tableDragIndentation: function () {
  1413. return '<div class="js-indentation indentation">&nbsp;</div>';
  1414. },
  1415. /**
  1416. * @return {string}
  1417. * Markup for the warning.
  1418. */
  1419. tableDragChangedWarning: function () {
  1420. return '<div class="tabledrag-changed-warning messages messages--warning" role="alert">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('You have unsaved changes.') + '</div>';
  1421. }
  1422. });
  1423. })(jQuery, Drupal, drupalSettings);