tabledrag.es6.js 50 KB

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