tabledrag.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. (function ($) {
  2. /**
  3. * Drag and drop table rows with field manipulation.
  4. *
  5. * Using the drupal_add_tabledrag() function, any table with weights or parent
  6. * relationships may be made into draggable tables. Columns containing a field
  7. * may optionally be hidden, providing a better user experience.
  8. *
  9. * Created tableDrag instances may be modified with custom behaviors by
  10. * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
  11. * See blocks.js for an example of adding additional functionality to tableDrag.
  12. */
  13. Drupal.behaviors.tableDrag = {
  14. attach: function (context, settings) {
  15. for (var base in settings.tableDrag) {
  16. $('#' + base, context).once('tabledrag', function () {
  17. // Create the new tableDrag instance. Save in the Drupal variable
  18. // to allow other scripts access to the object.
  19. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]);
  20. });
  21. }
  22. }
  23. };
  24. /**
  25. * Constructor for the tableDrag object. Provides table and field manipulation.
  26. *
  27. * @param table
  28. * DOM object for the table to be made draggable.
  29. * @param tableSettings
  30. * Settings for the table added via drupal_add_dragtable().
  31. */
  32. Drupal.tableDrag = function (table, tableSettings) {
  33. var self = this;
  34. // Required object variables.
  35. this.table = table;
  36. this.tableSettings = tableSettings;
  37. this.dragObject = null; // Used to hold information about a current drag operation.
  38. this.rowObject = null; // Provides operations for row manipulation.
  39. this.oldRowElement = null; // Remember the previous element.
  40. this.oldY = 0; // Used to determine up or down direction from last mouse move.
  41. this.changed = false; // Whether anything in the entire table has changed.
  42. this.maxDepth = 0; // Maximum amount of allowed parenting.
  43. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table.
  44. // Configure the scroll settings.
  45. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 };
  46. this.scrollInterval = null;
  47. this.scrollY = 0;
  48. this.windowHeight = 0;
  49. // Check this table's settings to see if there are parent relationships in
  50. // this table. For efficiency, large sections of code can be skipped if we
  51. // don't need to track horizontal movement and indentations.
  52. this.indentEnabled = false;
  53. for (var group in tableSettings) {
  54. for (var n in tableSettings[group]) {
  55. if (tableSettings[group][n].relationship == 'parent') {
  56. this.indentEnabled = true;
  57. }
  58. if (tableSettings[group][n].limit > 0) {
  59. this.maxDepth = tableSettings[group][n].limit;
  60. }
  61. }
  62. }
  63. if (this.indentEnabled) {
  64. this.indentCount = 1; // Total width of indents, set in makeDraggable.
  65. // Find the width of indentations to measure mouse movements against.
  66. // Because the table doesn't need to start with any indentations, we
  67. // manually append 2 indentations in the first draggable row, measure
  68. // the offset, then remove.
  69. var indent = Drupal.theme('tableDragIndentation');
  70. var testRow = $('<tr/>').addClass('draggable').appendTo(table);
  71. var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
  72. this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft;
  73. testRow.remove();
  74. }
  75. // Make each applicable row draggable.
  76. // Match immediate children of the parent element to allow nesting.
  77. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); });
  78. // Add a link before the table for users to show or hide weight columns.
  79. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>')
  80. .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
  81. .click(function () {
  82. if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
  83. self.hideColumns();
  84. }
  85. else {
  86. self.showColumns();
  87. }
  88. return false;
  89. })
  90. .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
  91. .parent()
  92. );
  93. // Initialize the specified columns (for example, weight or parent columns)
  94. // to show or hide according to user preference. This aids accessibility
  95. // so that, e.g., screen reader users can choose to enter weight values and
  96. // manipulate form elements directly, rather than using drag-and-drop..
  97. self.initColumns();
  98. // Add mouse bindings to the document. The self variable is passed along
  99. // as event handlers do not have direct access to the tableDrag object.
  100. $(document).bind('mousemove pointermove', function (event) { return self.dragRow(event, self); });
  101. $(document).bind('mouseup pointerup', function (event) { return self.dropRow(event, self); });
  102. $(document).bind('touchmove', function (event) { return self.dragRow(event.originalEvent.touches[0], self); });
  103. $(document).bind('touchend', function (event) { return self.dropRow(event.originalEvent.touches[0], self); });
  104. };
  105. /**
  106. * Initialize columns containing form elements to be hidden by default,
  107. * according to the settings for this tableDrag instance.
  108. *
  109. * Identify and mark each cell with a CSS class so we can easily toggle
  110. * show/hide it. Finally, hide columns if user does not have a
  111. * 'Drupal.tableDrag.showWeight' cookie.
  112. */
  113. Drupal.tableDrag.prototype.initColumns = function () {
  114. for (var group in this.tableSettings) {
  115. // Find the first field in this group.
  116. for (var d in this.tableSettings[group]) {
  117. var field = $('.' + this.tableSettings[group][d].target + ':first', this.table);
  118. if (field.length && this.tableSettings[group][d].hidden) {
  119. var hidden = this.tableSettings[group][d].hidden;
  120. var cell = field.closest('td');
  121. break;
  122. }
  123. }
  124. // Mark the column containing this field so it can be hidden.
  125. if (hidden && cell[0]) {
  126. // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based.
  127. // Match immediate children of the parent element to allow nesting.
  128. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1;
  129. $('> thead > tr, > tbody > tr, > tr', this.table).each(function () {
  130. // Get the columnIndex and adjust for any colspans in this row.
  131. var index = columnIndex;
  132. var cells = $(this).children();
  133. cells.each(function (n) {
  134. if (n < index && this.colSpan && this.colSpan > 1) {
  135. index -= this.colSpan - 1;
  136. }
  137. });
  138. if (index > 0) {
  139. cell = cells.filter(':nth-child(' + index + ')');
  140. if (cell[0].colSpan && cell[0].colSpan > 1) {
  141. // If this cell has a colspan, mark it so we can reduce the colspan.
  142. cell.addClass('tabledrag-has-colspan');
  143. }
  144. else {
  145. // Mark this cell so we can hide it.
  146. cell.addClass('tabledrag-hide');
  147. }
  148. }
  149. });
  150. }
  151. }
  152. // Now hide cells and reduce colspans unless cookie indicates previous choice.
  153. // Set a cookie if it is not already present.
  154. if ($.cookie('Drupal.tableDrag.showWeight') === null) {
  155. $.cookie('Drupal.tableDrag.showWeight', 0, {
  156. path: Drupal.settings.basePath,
  157. // The cookie expires in one year.
  158. expires: 365
  159. });
  160. this.hideColumns();
  161. }
  162. // Check cookie value and show/hide weight columns accordingly.
  163. else {
  164. if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
  165. this.showColumns();
  166. }
  167. else {
  168. this.hideColumns();
  169. }
  170. }
  171. };
  172. /**
  173. * Hide the columns containing weight/parent form elements.
  174. * Undo showColumns().
  175. */
  176. Drupal.tableDrag.prototype.hideColumns = function () {
  177. // Hide weight/parent cells and headers.
  178. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none');
  179. // Show TableDrag handles.
  180. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', '');
  181. // Reduce the colspan of any effected multi-span columns.
  182. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
  183. this.colSpan = this.colSpan - 1;
  184. });
  185. // Change link text.
  186. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
  187. // Change cookie.
  188. $.cookie('Drupal.tableDrag.showWeight', 0, {
  189. path: Drupal.settings.basePath,
  190. // The cookie expires in one year.
  191. expires: 365
  192. });
  193. // Trigger an event to allow other scripts to react to this display change.
  194. $('table.tabledrag-processed').trigger('columnschange', 'hide');
  195. };
  196. /**
  197. * Show the columns containing weight/parent form elements
  198. * Undo hideColumns().
  199. */
  200. Drupal.tableDrag.prototype.showColumns = function () {
  201. // Show weight/parent cells and headers.
  202. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', '');
  203. // Hide TableDrag handles.
  204. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none');
  205. // Increase the colspan for any columns where it was previously reduced.
  206. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
  207. this.colSpan = this.colSpan + 1;
  208. });
  209. // Change link text.
  210. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
  211. // Change cookie.
  212. $.cookie('Drupal.tableDrag.showWeight', 1, {
  213. path: Drupal.settings.basePath,
  214. // The cookie expires in one year.
  215. expires: 365
  216. });
  217. // Trigger an event to allow other scripts to react to this display change.
  218. $('table.tabledrag-processed').trigger('columnschange', 'show');
  219. };
  220. /**
  221. * Find the target used within a particular row and group.
  222. */
  223. Drupal.tableDrag.prototype.rowSettings = function (group, row) {
  224. var field = $('.' + group, row);
  225. for (var delta in this.tableSettings[group]) {
  226. var targetClass = this.tableSettings[group][delta].target;
  227. if (field.is('.' + targetClass)) {
  228. // Return a copy of the row settings.
  229. var rowSettings = {};
  230. for (var n in this.tableSettings[group][delta]) {
  231. rowSettings[n] = this.tableSettings[group][delta][n];
  232. }
  233. return rowSettings;
  234. }
  235. }
  236. };
  237. /**
  238. * Take an item and add event handlers to make it become draggable.
  239. */
  240. Drupal.tableDrag.prototype.makeDraggable = function (item) {
  241. var self = this;
  242. // Create the handle.
  243. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order'));
  244. // Insert the handle after indentations (if any).
  245. if ($('td:first .indentation:last', item).length) {
  246. $('td:first .indentation:last', item).after(handle);
  247. // Update the total width of indentation in this entire table.
  248. self.indentCount = Math.max($('.indentation', item).length, self.indentCount);
  249. }
  250. else {
  251. $('td:first', item).prepend(handle);
  252. }
  253. // Add hover action for the handle.
  254. handle.hover(function () {
  255. self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null;
  256. }, function () {
  257. self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null;
  258. });
  259. // Add the mousedown action for the handle.
  260. handle.bind('mousedown touchstart pointerdown', function (event) {
  261. if (event.originalEvent.type == "touchstart") {
  262. event = event.originalEvent.touches[0];
  263. }
  264. // Create a new dragObject recording the event information.
  265. self.dragObject = {};
  266. self.dragObject.initMouseOffset = self.getMouseOffset(item, event);
  267. self.dragObject.initMouseCoords = self.mouseCoords(event);
  268. if (self.indentEnabled) {
  269. self.dragObject.indentMousePos = self.dragObject.initMouseCoords;
  270. }
  271. // If there's a lingering row object from the keyboard, remove its focus.
  272. if (self.rowObject) {
  273. $('a.tabledrag-handle', self.rowObject.element).blur();
  274. }
  275. // Create a new rowObject for manipulation of this row.
  276. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true);
  277. // Save the position of the table.
  278. self.table.topY = $(self.table).offset().top;
  279. self.table.bottomY = self.table.topY + self.table.offsetHeight;
  280. // Add classes to the handle and row.
  281. $(this).addClass('tabledrag-handle-hover');
  282. $(item).addClass('drag');
  283. // Set the document to use the move cursor during drag.
  284. $('body').addClass('drag');
  285. if (self.oldRowElement) {
  286. $(self.oldRowElement).removeClass('drag-previous');
  287. }
  288. // Hack for IE6 that flickers uncontrollably if select lists are moved.
  289. if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
  290. $('select', this.table).css('display', 'none');
  291. }
  292. // Hack for Konqueror, prevent the blur handler from firing.
  293. // Konqueror always gives links focus, even after returning false on mousedown.
  294. self.safeBlur = false;
  295. // Call optional placeholder function.
  296. self.onDrag();
  297. return false;
  298. });
  299. // Prevent the anchor tag from jumping us to the top of the page.
  300. handle.click(function () {
  301. return false;
  302. });
  303. // Similar to the hover event, add a class when the handle is focused.
  304. handle.focus(function () {
  305. $(this).addClass('tabledrag-handle-hover');
  306. self.safeBlur = true;
  307. });
  308. // Remove the handle class on blur and fire the same function as a mouseup.
  309. handle.blur(function (event) {
  310. $(this).removeClass('tabledrag-handle-hover');
  311. if (self.rowObject && self.safeBlur) {
  312. self.dropRow(event, self);
  313. }
  314. });
  315. // Add arrow-key support to the handle.
  316. handle.keydown(function (event) {
  317. // If a rowObject doesn't yet exist and this isn't the tab key.
  318. if (event.keyCode != 9 && !self.rowObject) {
  319. self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
  320. }
  321. var keyChange = false;
  322. switch (event.keyCode) {
  323. case 37: // Left arrow.
  324. case 63234: // Safari left arrow.
  325. keyChange = true;
  326. self.rowObject.indent(-1 * self.rtl);
  327. break;
  328. case 38: // Up arrow.
  329. case 63232: // Safari up arrow.
  330. var previousRow = $(self.rowObject.element).prev('tr').get(0);
  331. while (previousRow && $(previousRow).is(':hidden')) {
  332. previousRow = $(previousRow).prev('tr').get(0);
  333. }
  334. if (previousRow) {
  335. self.safeBlur = false; // Do not allow the onBlur cleanup.
  336. self.rowObject.direction = 'up';
  337. keyChange = true;
  338. if ($(item).is('.tabledrag-root')) {
  339. // Swap with the previous top-level row.
  340. var groupHeight = 0;
  341. while (previousRow && $('.indentation', previousRow).length) {
  342. previousRow = $(previousRow).prev('tr').get(0);
  343. groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight;
  344. }
  345. if (previousRow) {
  346. self.rowObject.swap('before', previousRow);
  347. // No need to check for indentation, 0 is the only valid one.
  348. window.scrollBy(0, -groupHeight);
  349. }
  350. }
  351. else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) {
  352. // Swap with the previous row (unless previous row is the first one
  353. // and undraggable).
  354. self.rowObject.swap('before', previousRow);
  355. self.rowObject.interval = null;
  356. self.rowObject.indent(0);
  357. window.scrollBy(0, -parseInt(item.offsetHeight, 10));
  358. }
  359. handle.get(0).focus(); // Regain focus after the DOM manipulation.
  360. }
  361. break;
  362. case 39: // Right arrow.
  363. case 63235: // Safari right arrow.
  364. keyChange = true;
  365. self.rowObject.indent(1 * self.rtl);
  366. break;
  367. case 40: // Down arrow.
  368. case 63233: // Safari down arrow.
  369. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0);
  370. while (nextRow && $(nextRow).is(':hidden')) {
  371. nextRow = $(nextRow).next('tr').get(0);
  372. }
  373. if (nextRow) {
  374. self.safeBlur = false; // Do not allow the onBlur cleanup.
  375. self.rowObject.direction = 'down';
  376. keyChange = true;
  377. if ($(item).is('.tabledrag-root')) {
  378. // Swap with the next group (necessarily a top-level one).
  379. var groupHeight = 0;
  380. var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
  381. if (nextGroup) {
  382. $(nextGroup.group).each(function () {
  383. groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
  384. });
  385. var nextGroupRow = $(nextGroup.group).filter(':last').get(0);
  386. self.rowObject.swap('after', nextGroupRow);
  387. // No need to check for indentation, 0 is the only valid one.
  388. window.scrollBy(0, parseInt(groupHeight, 10));
  389. }
  390. }
  391. else {
  392. // Swap with the next row.
  393. self.rowObject.swap('after', nextRow);
  394. self.rowObject.interval = null;
  395. self.rowObject.indent(0);
  396. window.scrollBy(0, parseInt(item.offsetHeight, 10));
  397. }
  398. handle.get(0).focus(); // Regain focus after the DOM manipulation.
  399. }
  400. break;
  401. }
  402. if (self.rowObject && self.rowObject.changed == true) {
  403. $(item).addClass('drag');
  404. if (self.oldRowElement) {
  405. $(self.oldRowElement).removeClass('drag-previous');
  406. }
  407. self.oldRowElement = item;
  408. self.restripeTable();
  409. self.onDrag();
  410. }
  411. // Returning false if we have an arrow key to prevent scrolling.
  412. if (keyChange) {
  413. return false;
  414. }
  415. });
  416. // Compatibility addition, return false on keypress to prevent unwanted scrolling.
  417. // IE and Safari will suppress scrolling on keydown, but all other browsers
  418. // need to return false on keypress. http://www.quirksmode.org/js/keys.html
  419. handle.keypress(function (event) {
  420. switch (event.keyCode) {
  421. case 37: // Left arrow.
  422. case 38: // Up arrow.
  423. case 39: // Right arrow.
  424. case 40: // Down arrow.
  425. return false;
  426. }
  427. });
  428. };
  429. /**
  430. * Mousemove event handler, bound to document.
  431. */
  432. Drupal.tableDrag.prototype.dragRow = function (event, self) {
  433. if (self.dragObject) {
  434. self.currentMouseCoords = self.mouseCoords(event);
  435. var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
  436. var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
  437. // Check for row swapping and vertical scrolling.
  438. if (y != self.oldY) {
  439. self.rowObject.direction = y > self.oldY ? 'down' : 'up';
  440. self.oldY = y; // Update the old value.
  441. // Check if the window should be scrolled (and how fast).
  442. var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
  443. // Stop any current scrolling.
  444. clearInterval(self.scrollInterval);
  445. // Continue scrolling if the mouse has moved in the scroll direction.
  446. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
  447. self.setScroll(scrollAmount);
  448. }
  449. // If we have a valid target, perform the swap and restripe the table.
  450. var currentRow = self.findDropTargetRow(x, y);
  451. if (currentRow) {
  452. if (self.rowObject.direction == 'down') {
  453. self.rowObject.swap('after', currentRow, self);
  454. }
  455. else {
  456. self.rowObject.swap('before', currentRow, self);
  457. }
  458. self.restripeTable();
  459. }
  460. }
  461. // Similar to row swapping, handle indentations.
  462. if (self.indentEnabled) {
  463. var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x;
  464. // Set the number of indentations the mouse has been moved left or right.
  465. var indentDiff = Math.round(xDiff / self.indentAmount);
  466. // Indent the row with our estimated diff, which may be further
  467. // restricted according to the rows around this row.
  468. var indentChange = self.rowObject.indent(indentDiff);
  469. // Update table and mouse indentations.
  470. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl;
  471. self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
  472. }
  473. return false;
  474. }
  475. };
  476. /**
  477. * Mouseup event handler, bound to document.
  478. * Blur event handler, bound to drag handle for keyboard support.
  479. */
  480. Drupal.tableDrag.prototype.dropRow = function (event, self) {
  481. // Drop row functionality shared between mouseup and blur events.
  482. if (self.rowObject != null) {
  483. var droppedRow = self.rowObject.element;
  484. // The row is already in the right place so we just release it.
  485. if (self.rowObject.changed == true) {
  486. // Update the fields in the dropped row.
  487. self.updateFields(droppedRow);
  488. // If a setting exists for affecting the entire group, update all the
  489. // fields in the entire dragged group.
  490. for (var group in self.tableSettings) {
  491. var rowSettings = self.rowSettings(group, droppedRow);
  492. if (rowSettings.relationship == 'group') {
  493. for (var n in self.rowObject.children) {
  494. self.updateField(self.rowObject.children[n], group);
  495. }
  496. }
  497. }
  498. self.rowObject.markChanged();
  499. if (self.changed == false) {
  500. $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
  501. self.changed = true;
  502. }
  503. }
  504. if (self.indentEnabled) {
  505. self.rowObject.removeIndentClasses();
  506. }
  507. if (self.oldRowElement) {
  508. $(self.oldRowElement).removeClass('drag-previous');
  509. }
  510. $(droppedRow).removeClass('drag').addClass('drag-previous');
  511. self.oldRowElement = droppedRow;
  512. self.onDrop();
  513. self.rowObject = null;
  514. }
  515. // Functionality specific only to mouseup event.
  516. if (self.dragObject != null) {
  517. $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
  518. self.dragObject = null;
  519. $('body').removeClass('drag');
  520. clearInterval(self.scrollInterval);
  521. // Hack for IE6 that flickers uncontrollably if select lists are moved.
  522. if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
  523. $('select', this.table).css('display', 'block');
  524. }
  525. }
  526. };
  527. /**
  528. * Get the mouse coordinates from the event (allowing for browser differences).
  529. */
  530. Drupal.tableDrag.prototype.mouseCoords = function (event) {
  531. // Complete support for pointer events was only introduced to jQuery in
  532. // version 1.11.1; between versions 1.7 and 1.11.0 pointer events have the
  533. // clientX and clientY properties undefined. In those cases, the properties
  534. // must be retrieved from the event.originalEvent object instead.
  535. var clientX = event.clientX || event.originalEvent.clientX;
  536. var clientY = event.clientY || event.originalEvent.clientY;
  537. if (event.pageX || event.pageY) {
  538. return { x: event.pageX, y: event.pageY };
  539. }
  540. return {
  541. x: clientX + document.body.scrollLeft - document.body.clientLeft,
  542. y: clientY + document.body.scrollTop - document.body.clientTop
  543. };
  544. };
  545. /**
  546. * Given a target element and a mouse event, get the mouse offset from that
  547. * element. To do this we need the element's position and the mouse position.
  548. */
  549. Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
  550. var docPos = $(target).offset();
  551. var mousePos = this.mouseCoords(event);
  552. return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
  553. };
  554. /**
  555. * Find the row the mouse is currently over. This row is then taken and swapped
  556. * with the one being dragged.
  557. *
  558. * @param x
  559. * The x coordinate of the mouse on the page (not the screen).
  560. * @param y
  561. * The y coordinate of the mouse on the page (not the screen).
  562. */
  563. Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
  564. var rows = $(this.table.tBodies[0].rows).not(':hidden');
  565. for (var n = 0; n < rows.length; n++) {
  566. var row = rows[n];
  567. var indentDiff = 0;
  568. var rowY = $(row).offset().top;
  569. // Because Safari does not report offsetHeight on table rows, but does on
  570. // table cells, grab the firstChild of the row and use that instead.
  571. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
  572. if (row.offsetHeight == 0) {
  573. var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
  574. }
  575. // Other browsers.
  576. else {
  577. var rowHeight = parseInt(row.offsetHeight, 10) / 2;
  578. }
  579. // Because we always insert before, we need to offset the height a bit.
  580. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
  581. if (this.indentEnabled) {
  582. // Check that this row is not a child of the row being dragged.
  583. for (var n in this.rowObject.group) {
  584. if (this.rowObject.group[n] == row) {
  585. return null;
  586. }
  587. }
  588. }
  589. else {
  590. // Do not allow a row to be swapped with itself.
  591. if (row == this.rowObject.element) {
  592. return null;
  593. }
  594. }
  595. // Check that swapping with this row is allowed.
  596. if (!this.rowObject.isValidSwap(row)) {
  597. return null;
  598. }
  599. // We may have found the row the mouse just passed over, but it doesn't
  600. // take into account hidden rows. Skip backwards until we find a draggable
  601. // row.
  602. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
  603. row = $(row).prev('tr').get(0);
  604. }
  605. return row;
  606. }
  607. }
  608. return null;
  609. };
  610. /**
  611. * After the row is dropped, update the table fields according to the settings
  612. * set for this table.
  613. *
  614. * @param changedRow
  615. * DOM object for the row that was just dropped.
  616. */
  617. Drupal.tableDrag.prototype.updateFields = function (changedRow) {
  618. for (var group in this.tableSettings) {
  619. // Each group may have a different setting for relationship, so we find
  620. // the source rows for each separately.
  621. this.updateField(changedRow, group);
  622. }
  623. };
  624. /**
  625. * After the row is dropped, update a single table field according to specific
  626. * settings.
  627. *
  628. * @param changedRow
  629. * DOM object for the row that was just dropped.
  630. * @param group
  631. * The settings group on which field updates will occur.
  632. */
  633. Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
  634. var rowSettings = this.rowSettings(group, changedRow);
  635. // Set the row as its own target.
  636. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
  637. var sourceRow = changedRow;
  638. }
  639. // Siblings are easy, check previous and next rows.
  640. else if (rowSettings.relationship == 'sibling') {
  641. var previousRow = $(changedRow).prev('tr').get(0);
  642. var nextRow = $(changedRow).next('tr').get(0);
  643. var sourceRow = changedRow;
  644. if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
  645. if (this.indentEnabled) {
  646. if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
  647. sourceRow = previousRow;
  648. }
  649. }
  650. else {
  651. sourceRow = previousRow;
  652. }
  653. }
  654. else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
  655. if (this.indentEnabled) {
  656. if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
  657. sourceRow = nextRow;
  658. }
  659. }
  660. else {
  661. sourceRow = nextRow;
  662. }
  663. }
  664. }
  665. // Parents, look up the tree until we find a field not in this group.
  666. // Go up as many parents as indentations in the changed row.
  667. else if (rowSettings.relationship == 'parent') {
  668. var previousRow = $(changedRow).prev('tr');
  669. while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
  670. previousRow = previousRow.prev('tr');
  671. }
  672. // If we found a row.
  673. if (previousRow.length) {
  674. sourceRow = previousRow[0];
  675. }
  676. // Otherwise we went all the way to the left of the table without finding
  677. // a parent, meaning this item has been placed at the root level.
  678. else {
  679. // Use the first row in the table as source, because it's guaranteed to
  680. // be at the root level. Find the first item, then compare this row
  681. // against it as a sibling.
  682. sourceRow = $(this.table).find('tr.draggable:first').get(0);
  683. if (sourceRow == this.rowObject.element) {
  684. sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
  685. }
  686. var useSibling = true;
  687. }
  688. }
  689. // Because we may have moved the row from one category to another,
  690. // take a look at our sibling and borrow its sources and targets.
  691. this.copyDragClasses(sourceRow, changedRow, group);
  692. rowSettings = this.rowSettings(group, changedRow);
  693. // In the case that we're looking for a parent, but the row is at the top
  694. // of the tree, copy our sibling's values.
  695. if (useSibling) {
  696. rowSettings.relationship = 'sibling';
  697. rowSettings.source = rowSettings.target;
  698. }
  699. var targetClass = '.' + rowSettings.target;
  700. var targetElement = $(targetClass, changedRow).get(0);
  701. // Check if a target element exists in this row.
  702. if (targetElement) {
  703. var sourceClass = '.' + rowSettings.source;
  704. var sourceElement = $(sourceClass, sourceRow).get(0);
  705. switch (rowSettings.action) {
  706. case 'depth':
  707. // Get the depth of the target row.
  708. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length;
  709. break;
  710. case 'match':
  711. // Update the value.
  712. targetElement.value = sourceElement.value;
  713. break;
  714. case 'order':
  715. var siblings = this.rowObject.findSiblings(rowSettings);
  716. if ($(targetElement).is('select')) {
  717. // Get a list of acceptable values.
  718. var values = [];
  719. $('option', targetElement).each(function () {
  720. values.push(this.value);
  721. });
  722. var maxVal = values[values.length - 1];
  723. // Populate the values in the siblings.
  724. $(targetClass, siblings).each(function () {
  725. // If there are more items than possible values, assign the maximum value to the row.
  726. if (values.length > 0) {
  727. this.value = values.shift();
  728. }
  729. else {
  730. this.value = maxVal;
  731. }
  732. });
  733. }
  734. else {
  735. // Assume a numeric input field.
  736. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
  737. $(targetClass, siblings).each(function () {
  738. this.value = weight;
  739. weight++;
  740. });
  741. }
  742. break;
  743. }
  744. }
  745. };
  746. /**
  747. * Copy all special tableDrag classes from one row's form elements to a
  748. * different one, removing any special classes that the destination row
  749. * may have had.
  750. */
  751. Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
  752. var sourceElement = $('.' + group, sourceRow);
  753. var targetElement = $('.' + group, targetRow);
  754. if (sourceElement.length && targetElement.length) {
  755. targetElement[0].className = sourceElement[0].className;
  756. }
  757. };
  758. Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
  759. var de = document.documentElement;
  760. var b = document.body;
  761. var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
  762. var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
  763. var trigger = this.scrollSettings.trigger;
  764. var delta = 0;
  765. // Return a scroll speed relative to the edge of the screen.
  766. if (cursorY - scrollY > windowHeight - trigger) {
  767. delta = trigger / (windowHeight + scrollY - cursorY);
  768. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  769. return delta * this.scrollSettings.amount;
  770. }
  771. else if (cursorY - scrollY < trigger) {
  772. delta = trigger / (cursorY - scrollY);
  773. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  774. return -delta * this.scrollSettings.amount;
  775. }
  776. };
  777. Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
  778. var self = this;
  779. this.scrollInterval = setInterval(function () {
  780. // Update the scroll values stored in the object.
  781. self.checkScroll(self.currentMouseCoords.y);
  782. var aboveTable = self.scrollY > self.table.topY;
  783. var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
  784. if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
  785. window.scrollBy(0, scrollAmount);
  786. }
  787. }, this.scrollSettings.interval);
  788. };
  789. Drupal.tableDrag.prototype.restripeTable = function () {
  790. // :even and :odd are reversed because jQuery counts from 0 and
  791. // we count from 1, so we're out of sync.
  792. // Match immediate children of the parent element to allow nesting.
  793. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
  794. .removeClass('odd even')
  795. .filter(':odd').addClass('even').end()
  796. .filter(':even').addClass('odd');
  797. };
  798. /**
  799. * Stub function. Allows a custom handler when a row begins dragging.
  800. */
  801. Drupal.tableDrag.prototype.onDrag = function () {
  802. return null;
  803. };
  804. /**
  805. * Stub function. Allows a custom handler when a row is dropped.
  806. */
  807. Drupal.tableDrag.prototype.onDrop = function () {
  808. return null;
  809. };
  810. /**
  811. * Constructor to make a new object to manipulate a table row.
  812. *
  813. * @param tableRow
  814. * The DOM element for the table row we will be manipulating.
  815. * @param method
  816. * The method in which this row is being moved. Either 'keyboard' or 'mouse'.
  817. * @param indentEnabled
  818. * Whether the containing table uses indentations. Used for optimizations.
  819. * @param maxDepth
  820. * The maximum amount of indentations this row may contain.
  821. * @param addClasses
  822. * Whether we want to add classes to this row to indicate child relationships.
  823. */
  824. Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
  825. this.element = tableRow;
  826. this.method = method;
  827. this.group = [tableRow];
  828. this.groupDepth = $('.indentation', tableRow).length;
  829. this.changed = false;
  830. this.table = $(tableRow).closest('table').get(0);
  831. this.indentEnabled = indentEnabled;
  832. this.maxDepth = maxDepth;
  833. this.direction = ''; // Direction the row is being moved.
  834. if (this.indentEnabled) {
  835. this.indents = $('.indentation', tableRow).length;
  836. this.children = this.findChildren(addClasses);
  837. this.group = $.merge(this.group, this.children);
  838. // Find the depth of this entire group.
  839. for (var n = 0; n < this.group.length; n++) {
  840. this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth);
  841. }
  842. }
  843. };
  844. /**
  845. * Find all children of rowObject by indentation.
  846. *
  847. * @param addClasses
  848. * Whether we want to add classes to this row to indicate child relationships.
  849. */
  850. Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
  851. var parentIndentation = this.indents;
  852. var currentRow = $(this.element, this.table).next('tr.draggable');
  853. var rows = [];
  854. var child = 0;
  855. while (currentRow.length) {
  856. var rowIndentation = $('.indentation', currentRow).length;
  857. // A greater indentation indicates this is a child.
  858. if (rowIndentation > parentIndentation) {
  859. child++;
  860. rows.push(currentRow[0]);
  861. if (addClasses) {
  862. $('.indentation', currentRow).each(function (indentNum) {
  863. if (child == 1 && (indentNum == parentIndentation)) {
  864. $(this).addClass('tree-child-first');
  865. }
  866. if (indentNum == parentIndentation) {
  867. $(this).addClass('tree-child');
  868. }
  869. else if (indentNum > parentIndentation) {
  870. $(this).addClass('tree-child-horizontal');
  871. }
  872. });
  873. }
  874. }
  875. else {
  876. break;
  877. }
  878. currentRow = currentRow.next('tr.draggable');
  879. }
  880. if (addClasses && rows.length) {
  881. $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
  882. }
  883. return rows;
  884. };
  885. /**
  886. * Ensure that two rows are allowed to be swapped.
  887. *
  888. * @param row
  889. * DOM object for the row being considered for swapping.
  890. */
  891. Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
  892. if (this.indentEnabled) {
  893. var prevRow, nextRow;
  894. if (this.direction == 'down') {
  895. prevRow = row;
  896. nextRow = $(row).next('tr').get(0);
  897. }
  898. else {
  899. prevRow = $(row).prev('tr').get(0);
  900. nextRow = row;
  901. }
  902. this.interval = this.validIndentInterval(prevRow, nextRow);
  903. // We have an invalid swap if the valid indentations interval is empty.
  904. if (this.interval.min > this.interval.max) {
  905. return false;
  906. }
  907. }
  908. // Do not let an un-draggable first row have anything put before it.
  909. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
  910. return false;
  911. }
  912. return true;
  913. };
  914. /**
  915. * Perform the swap between two rows.
  916. *
  917. * @param position
  918. * Whether the swap will occur 'before' or 'after' the given row.
  919. * @param row
  920. * DOM element what will be swapped with the row group.
  921. */
  922. Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
  923. Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
  924. $(row)[position](this.group);
  925. Drupal.attachBehaviors(this.group, Drupal.settings);
  926. this.changed = true;
  927. this.onSwap(row);
  928. };
  929. /**
  930. * Determine the valid indentations interval for the row at a given position
  931. * in the table.
  932. *
  933. * @param prevRow
  934. * DOM object for the row before the tested position
  935. * (or null for first position in the table).
  936. * @param nextRow
  937. * DOM object for the row after the tested position
  938. * (or null for last position in the table).
  939. */
  940. Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
  941. var minIndent, maxIndent;
  942. // Minimum indentation:
  943. // Do not orphan the next row.
  944. minIndent = nextRow ? $('.indentation', nextRow).length : 0;
  945. // Maximum indentation:
  946. if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
  947. // Do not indent:
  948. // - the first row in the table,
  949. // - rows dragged below a non-draggable row,
  950. // - 'root' rows.
  951. maxIndent = 0;
  952. }
  953. else {
  954. // Do not go deeper than as a child of the previous row.
  955. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1);
  956. // Limit by the maximum allowed depth for the table.
  957. if (this.maxDepth) {
  958. maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
  959. }
  960. }
  961. return { 'min': minIndent, 'max': maxIndent };
  962. };
  963. /**
  964. * Indent a row within the legal bounds of the table.
  965. *
  966. * @param indentDiff
  967. * The number of additional indentations proposed for the row (can be
  968. * positive or negative). This number will be adjusted to nearest valid
  969. * indentation level for the row.
  970. */
  971. Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
  972. // Determine the valid indentations interval if not available yet.
  973. if (!this.interval) {
  974. var prevRow = $(this.element).prev('tr').get(0);
  975. var nextRow = $(this.group).filter(':last').next('tr').get(0);
  976. this.interval = this.validIndentInterval(prevRow, nextRow);
  977. }
  978. // Adjust to the nearest valid indentation.
  979. var indent = this.indents + indentDiff;
  980. indent = Math.max(indent, this.interval.min);
  981. indent = Math.min(indent, this.interval.max);
  982. indentDiff = indent - this.indents;
  983. for (var n = 1; n <= Math.abs(indentDiff); n++) {
  984. // Add or remove indentations.
  985. if (indentDiff < 0) {
  986. $('.indentation:first', this.group).remove();
  987. this.indents--;
  988. }
  989. else {
  990. $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
  991. this.indents++;
  992. }
  993. }
  994. if (indentDiff) {
  995. // Update indentation for this row.
  996. this.changed = true;
  997. this.groupDepth += indentDiff;
  998. this.onIndent();
  999. }
  1000. return indentDiff;
  1001. };
  1002. /**
  1003. * Find all siblings for a row, either according to its subgroup or indentation.
  1004. * Note that the passed-in row is included in the list of siblings.
  1005. *
  1006. * @param settings
  1007. * The field settings we're using to identify what constitutes a sibling.
  1008. */
  1009. Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
  1010. var siblings = [];
  1011. var directions = ['prev', 'next'];
  1012. var rowIndentation = this.indents;
  1013. for (var d = 0; d < directions.length; d++) {
  1014. var checkRow = $(this.element)[directions[d]]();
  1015. while (checkRow.length) {
  1016. // Check that the sibling contains a similar target field.
  1017. if ($('.' + rowSettings.target, checkRow)) {
  1018. // Either add immediately if this is a flat table, or check to ensure
  1019. // that this row has the same level of indentation.
  1020. if (this.indentEnabled) {
  1021. var checkRowIndentation = $('.indentation', checkRow).length;
  1022. }
  1023. if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) {
  1024. siblings.push(checkRow[0]);
  1025. }
  1026. else if (checkRowIndentation < rowIndentation) {
  1027. // No need to keep looking for siblings when we get to a parent.
  1028. break;
  1029. }
  1030. }
  1031. else {
  1032. break;
  1033. }
  1034. checkRow = $(checkRow)[directions[d]]();
  1035. }
  1036. // Since siblings are added in reverse order for previous, reverse the
  1037. // completed list of previous siblings. Add the current row and continue.
  1038. if (directions[d] == 'prev') {
  1039. siblings.reverse();
  1040. siblings.push(this.element);
  1041. }
  1042. }
  1043. return siblings;
  1044. };
  1045. /**
  1046. * Remove indentation helper classes from the current row group.
  1047. */
  1048. Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
  1049. for (var n in this.children) {
  1050. $('.indentation', this.children[n])
  1051. .removeClass('tree-child')
  1052. .removeClass('tree-child-first')
  1053. .removeClass('tree-child-last')
  1054. .removeClass('tree-child-horizontal');
  1055. }
  1056. };
  1057. /**
  1058. * Add an asterisk or other marker to the changed row.
  1059. */
  1060. Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
  1061. var marker = Drupal.theme('tableDragChangedMarker');
  1062. var cell = $('td:first', this.element);
  1063. if ($('span.tabledrag-changed', cell).length == 0) {
  1064. cell.append(marker);
  1065. }
  1066. };
  1067. /**
  1068. * Stub function. Allows a custom handler when a row is indented.
  1069. */
  1070. Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
  1071. return null;
  1072. };
  1073. /**
  1074. * Stub function. Allows a custom handler when a row is swapped.
  1075. */
  1076. Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
  1077. return null;
  1078. };
  1079. Drupal.theme.prototype.tableDragChangedMarker = function () {
  1080. return '<span class="warning tabledrag-changed">*</span>';
  1081. };
  1082. Drupal.theme.prototype.tableDragIndentation = function () {
  1083. return '<div class="indentation">&nbsp;</div>';
  1084. };
  1085. Drupal.theme.prototype.tableDragChangedWarning = function () {
  1086. return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>';
  1087. };
  1088. })(jQuery);