tabledrag.es6.js 50 KB

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