tabledrag.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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. if (event.pageX || event.pageY) {
  532. return { x: event.pageX, y: event.pageY };
  533. }
  534. return {
  535. x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
  536. y: event.clientY + document.body.scrollTop - document.body.clientTop
  537. };
  538. };
  539. /**
  540. * Given a target element and a mouse event, get the mouse offset from that
  541. * element. To do this we need the element's position and the mouse position.
  542. */
  543. Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
  544. var docPos = $(target).offset();
  545. var mousePos = this.mouseCoords(event);
  546. return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
  547. };
  548. /**
  549. * Find the row the mouse is currently over. This row is then taken and swapped
  550. * with the one being dragged.
  551. *
  552. * @param x
  553. * The x coordinate of the mouse on the page (not the screen).
  554. * @param y
  555. * The y coordinate of the mouse on the page (not the screen).
  556. */
  557. Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
  558. var rows = $(this.table.tBodies[0].rows).not(':hidden');
  559. for (var n = 0; n < rows.length; n++) {
  560. var row = rows[n];
  561. var indentDiff = 0;
  562. var rowY = $(row).offset().top;
  563. // Because Safari does not report offsetHeight on table rows, but does on
  564. // table cells, grab the firstChild of the row and use that instead.
  565. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
  566. if (row.offsetHeight == 0) {
  567. var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
  568. }
  569. // Other browsers.
  570. else {
  571. var rowHeight = parseInt(row.offsetHeight, 10) / 2;
  572. }
  573. // Because we always insert before, we need to offset the height a bit.
  574. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
  575. if (this.indentEnabled) {
  576. // Check that this row is not a child of the row being dragged.
  577. for (var n in this.rowObject.group) {
  578. if (this.rowObject.group[n] == row) {
  579. return null;
  580. }
  581. }
  582. }
  583. else {
  584. // Do not allow a row to be swapped with itself.
  585. if (row == this.rowObject.element) {
  586. return null;
  587. }
  588. }
  589. // Check that swapping with this row is allowed.
  590. if (!this.rowObject.isValidSwap(row)) {
  591. return null;
  592. }
  593. // We may have found the row the mouse just passed over, but it doesn't
  594. // take into account hidden rows. Skip backwards until we find a draggable
  595. // row.
  596. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
  597. row = $(row).prev('tr').get(0);
  598. }
  599. return row;
  600. }
  601. }
  602. return null;
  603. };
  604. /**
  605. * After the row is dropped, update the table fields according to the settings
  606. * set for this table.
  607. *
  608. * @param changedRow
  609. * DOM object for the row that was just dropped.
  610. */
  611. Drupal.tableDrag.prototype.updateFields = function (changedRow) {
  612. for (var group in this.tableSettings) {
  613. // Each group may have a different setting for relationship, so we find
  614. // the source rows for each separately.
  615. this.updateField(changedRow, group);
  616. }
  617. };
  618. /**
  619. * After the row is dropped, update a single table field according to specific
  620. * settings.
  621. *
  622. * @param changedRow
  623. * DOM object for the row that was just dropped.
  624. * @param group
  625. * The settings group on which field updates will occur.
  626. */
  627. Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
  628. var rowSettings = this.rowSettings(group, changedRow);
  629. // Set the row as its own target.
  630. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
  631. var sourceRow = changedRow;
  632. }
  633. // Siblings are easy, check previous and next rows.
  634. else if (rowSettings.relationship == 'sibling') {
  635. var previousRow = $(changedRow).prev('tr').get(0);
  636. var nextRow = $(changedRow).next('tr').get(0);
  637. var sourceRow = changedRow;
  638. if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
  639. if (this.indentEnabled) {
  640. if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
  641. sourceRow = previousRow;
  642. }
  643. }
  644. else {
  645. sourceRow = previousRow;
  646. }
  647. }
  648. else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
  649. if (this.indentEnabled) {
  650. if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
  651. sourceRow = nextRow;
  652. }
  653. }
  654. else {
  655. sourceRow = nextRow;
  656. }
  657. }
  658. }
  659. // Parents, look up the tree until we find a field not in this group.
  660. // Go up as many parents as indentations in the changed row.
  661. else if (rowSettings.relationship == 'parent') {
  662. var previousRow = $(changedRow).prev('tr');
  663. while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
  664. previousRow = previousRow.prev('tr');
  665. }
  666. // If we found a row.
  667. if (previousRow.length) {
  668. sourceRow = previousRow[0];
  669. }
  670. // Otherwise we went all the way to the left of the table without finding
  671. // a parent, meaning this item has been placed at the root level.
  672. else {
  673. // Use the first row in the table as source, because it's guaranteed to
  674. // be at the root level. Find the first item, then compare this row
  675. // against it as a sibling.
  676. sourceRow = $(this.table).find('tr.draggable:first').get(0);
  677. if (sourceRow == this.rowObject.element) {
  678. sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
  679. }
  680. var useSibling = true;
  681. }
  682. }
  683. // Because we may have moved the row from one category to another,
  684. // take a look at our sibling and borrow its sources and targets.
  685. this.copyDragClasses(sourceRow, changedRow, group);
  686. rowSettings = this.rowSettings(group, changedRow);
  687. // In the case that we're looking for a parent, but the row is at the top
  688. // of the tree, copy our sibling's values.
  689. if (useSibling) {
  690. rowSettings.relationship = 'sibling';
  691. rowSettings.source = rowSettings.target;
  692. }
  693. var targetClass = '.' + rowSettings.target;
  694. var targetElement = $(targetClass, changedRow).get(0);
  695. // Check if a target element exists in this row.
  696. if (targetElement) {
  697. var sourceClass = '.' + rowSettings.source;
  698. var sourceElement = $(sourceClass, sourceRow).get(0);
  699. switch (rowSettings.action) {
  700. case 'depth':
  701. // Get the depth of the target row.
  702. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length;
  703. break;
  704. case 'match':
  705. // Update the value.
  706. targetElement.value = sourceElement.value;
  707. break;
  708. case 'order':
  709. var siblings = this.rowObject.findSiblings(rowSettings);
  710. if ($(targetElement).is('select')) {
  711. // Get a list of acceptable values.
  712. var values = [];
  713. $('option', targetElement).each(function () {
  714. values.push(this.value);
  715. });
  716. var maxVal = values[values.length - 1];
  717. // Populate the values in the siblings.
  718. $(targetClass, siblings).each(function () {
  719. // If there are more items than possible values, assign the maximum value to the row.
  720. if (values.length > 0) {
  721. this.value = values.shift();
  722. }
  723. else {
  724. this.value = maxVal;
  725. }
  726. });
  727. }
  728. else {
  729. // Assume a numeric input field.
  730. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
  731. $(targetClass, siblings).each(function () {
  732. this.value = weight;
  733. weight++;
  734. });
  735. }
  736. break;
  737. }
  738. }
  739. };
  740. /**
  741. * Copy all special tableDrag classes from one row's form elements to a
  742. * different one, removing any special classes that the destination row
  743. * may have had.
  744. */
  745. Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
  746. var sourceElement = $('.' + group, sourceRow);
  747. var targetElement = $('.' + group, targetRow);
  748. if (sourceElement.length && targetElement.length) {
  749. targetElement[0].className = sourceElement[0].className;
  750. }
  751. };
  752. Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
  753. var de = document.documentElement;
  754. var b = document.body;
  755. var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
  756. var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
  757. var trigger = this.scrollSettings.trigger;
  758. var delta = 0;
  759. // Return a scroll speed relative to the edge of the screen.
  760. if (cursorY - scrollY > windowHeight - trigger) {
  761. delta = trigger / (windowHeight + scrollY - cursorY);
  762. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  763. return delta * this.scrollSettings.amount;
  764. }
  765. else if (cursorY - scrollY < trigger) {
  766. delta = trigger / (cursorY - scrollY);
  767. delta = (delta > 0 && delta < trigger) ? delta : trigger;
  768. return -delta * this.scrollSettings.amount;
  769. }
  770. };
  771. Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
  772. var self = this;
  773. this.scrollInterval = setInterval(function () {
  774. // Update the scroll values stored in the object.
  775. self.checkScroll(self.currentMouseCoords.y);
  776. var aboveTable = self.scrollY > self.table.topY;
  777. var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
  778. if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
  779. window.scrollBy(0, scrollAmount);
  780. }
  781. }, this.scrollSettings.interval);
  782. };
  783. Drupal.tableDrag.prototype.restripeTable = function () {
  784. // :even and :odd are reversed because jQuery counts from 0 and
  785. // we count from 1, so we're out of sync.
  786. // Match immediate children of the parent element to allow nesting.
  787. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
  788. .removeClass('odd even')
  789. .filter(':odd').addClass('even').end()
  790. .filter(':even').addClass('odd');
  791. };
  792. /**
  793. * Stub function. Allows a custom handler when a row begins dragging.
  794. */
  795. Drupal.tableDrag.prototype.onDrag = function () {
  796. return null;
  797. };
  798. /**
  799. * Stub function. Allows a custom handler when a row is dropped.
  800. */
  801. Drupal.tableDrag.prototype.onDrop = function () {
  802. return null;
  803. };
  804. /**
  805. * Constructor to make a new object to manipulate a table row.
  806. *
  807. * @param tableRow
  808. * The DOM element for the table row we will be manipulating.
  809. * @param method
  810. * The method in which this row is being moved. Either 'keyboard' or 'mouse'.
  811. * @param indentEnabled
  812. * Whether the containing table uses indentations. Used for optimizations.
  813. * @param maxDepth
  814. * The maximum amount of indentations this row may contain.
  815. * @param addClasses
  816. * Whether we want to add classes to this row to indicate child relationships.
  817. */
  818. Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
  819. this.element = tableRow;
  820. this.method = method;
  821. this.group = [tableRow];
  822. this.groupDepth = $('.indentation', tableRow).length;
  823. this.changed = false;
  824. this.table = $(tableRow).closest('table').get(0);
  825. this.indentEnabled = indentEnabled;
  826. this.maxDepth = maxDepth;
  827. this.direction = ''; // Direction the row is being moved.
  828. if (this.indentEnabled) {
  829. this.indents = $('.indentation', tableRow).length;
  830. this.children = this.findChildren(addClasses);
  831. this.group = $.merge(this.group, this.children);
  832. // Find the depth of this entire group.
  833. for (var n = 0; n < this.group.length; n++) {
  834. this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth);
  835. }
  836. }
  837. };
  838. /**
  839. * Find all children of rowObject by indentation.
  840. *
  841. * @param addClasses
  842. * Whether we want to add classes to this row to indicate child relationships.
  843. */
  844. Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
  845. var parentIndentation = this.indents;
  846. var currentRow = $(this.element, this.table).next('tr.draggable');
  847. var rows = [];
  848. var child = 0;
  849. while (currentRow.length) {
  850. var rowIndentation = $('.indentation', currentRow).length;
  851. // A greater indentation indicates this is a child.
  852. if (rowIndentation > parentIndentation) {
  853. child++;
  854. rows.push(currentRow[0]);
  855. if (addClasses) {
  856. $('.indentation', currentRow).each(function (indentNum) {
  857. if (child == 1 && (indentNum == parentIndentation)) {
  858. $(this).addClass('tree-child-first');
  859. }
  860. if (indentNum == parentIndentation) {
  861. $(this).addClass('tree-child');
  862. }
  863. else if (indentNum > parentIndentation) {
  864. $(this).addClass('tree-child-horizontal');
  865. }
  866. });
  867. }
  868. }
  869. else {
  870. break;
  871. }
  872. currentRow = currentRow.next('tr.draggable');
  873. }
  874. if (addClasses && rows.length) {
  875. $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
  876. }
  877. return rows;
  878. };
  879. /**
  880. * Ensure that two rows are allowed to be swapped.
  881. *
  882. * @param row
  883. * DOM object for the row being considered for swapping.
  884. */
  885. Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
  886. if (this.indentEnabled) {
  887. var prevRow, nextRow;
  888. if (this.direction == 'down') {
  889. prevRow = row;
  890. nextRow = $(row).next('tr').get(0);
  891. }
  892. else {
  893. prevRow = $(row).prev('tr').get(0);
  894. nextRow = row;
  895. }
  896. this.interval = this.validIndentInterval(prevRow, nextRow);
  897. // We have an invalid swap if the valid indentations interval is empty.
  898. if (this.interval.min > this.interval.max) {
  899. return false;
  900. }
  901. }
  902. // Do not let an un-draggable first row have anything put before it.
  903. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
  904. return false;
  905. }
  906. return true;
  907. };
  908. /**
  909. * Perform the swap between two rows.
  910. *
  911. * @param position
  912. * Whether the swap will occur 'before' or 'after' the given row.
  913. * @param row
  914. * DOM element what will be swapped with the row group.
  915. */
  916. Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
  917. Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
  918. $(row)[position](this.group);
  919. Drupal.attachBehaviors(this.group, Drupal.settings);
  920. this.changed = true;
  921. this.onSwap(row);
  922. };
  923. /**
  924. * Determine the valid indentations interval for the row at a given position
  925. * in the table.
  926. *
  927. * @param prevRow
  928. * DOM object for the row before the tested position
  929. * (or null for first position in the table).
  930. * @param nextRow
  931. * DOM object for the row after the tested position
  932. * (or null for last position in the table).
  933. */
  934. Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
  935. var minIndent, maxIndent;
  936. // Minimum indentation:
  937. // Do not orphan the next row.
  938. minIndent = nextRow ? $('.indentation', nextRow).length : 0;
  939. // Maximum indentation:
  940. if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
  941. // Do not indent:
  942. // - the first row in the table,
  943. // - rows dragged below a non-draggable row,
  944. // - 'root' rows.
  945. maxIndent = 0;
  946. }
  947. else {
  948. // Do not go deeper than as a child of the previous row.
  949. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1);
  950. // Limit by the maximum allowed depth for the table.
  951. if (this.maxDepth) {
  952. maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
  953. }
  954. }
  955. return { 'min': minIndent, 'max': maxIndent };
  956. };
  957. /**
  958. * Indent a row within the legal bounds of the table.
  959. *
  960. * @param indentDiff
  961. * The number of additional indentations proposed for the row (can be
  962. * positive or negative). This number will be adjusted to nearest valid
  963. * indentation level for the row.
  964. */
  965. Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
  966. // Determine the valid indentations interval if not available yet.
  967. if (!this.interval) {
  968. var prevRow = $(this.element).prev('tr').get(0);
  969. var nextRow = $(this.group).filter(':last').next('tr').get(0);
  970. this.interval = this.validIndentInterval(prevRow, nextRow);
  971. }
  972. // Adjust to the nearest valid indentation.
  973. var indent = this.indents + indentDiff;
  974. indent = Math.max(indent, this.interval.min);
  975. indent = Math.min(indent, this.interval.max);
  976. indentDiff = indent - this.indents;
  977. for (var n = 1; n <= Math.abs(indentDiff); n++) {
  978. // Add or remove indentations.
  979. if (indentDiff < 0) {
  980. $('.indentation:first', this.group).remove();
  981. this.indents--;
  982. }
  983. else {
  984. $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
  985. this.indents++;
  986. }
  987. }
  988. if (indentDiff) {
  989. // Update indentation for this row.
  990. this.changed = true;
  991. this.groupDepth += indentDiff;
  992. this.onIndent();
  993. }
  994. return indentDiff;
  995. };
  996. /**
  997. * Find all siblings for a row, either according to its subgroup or indentation.
  998. * Note that the passed-in row is included in the list of siblings.
  999. *
  1000. * @param settings
  1001. * The field settings we're using to identify what constitutes a sibling.
  1002. */
  1003. Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
  1004. var siblings = [];
  1005. var directions = ['prev', 'next'];
  1006. var rowIndentation = this.indents;
  1007. for (var d = 0; d < directions.length; d++) {
  1008. var checkRow = $(this.element)[directions[d]]();
  1009. while (checkRow.length) {
  1010. // Check that the sibling contains a similar target field.
  1011. if ($('.' + rowSettings.target, checkRow)) {
  1012. // Either add immediately if this is a flat table, or check to ensure
  1013. // that this row has the same level of indentation.
  1014. if (this.indentEnabled) {
  1015. var checkRowIndentation = $('.indentation', checkRow).length;
  1016. }
  1017. if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) {
  1018. siblings.push(checkRow[0]);
  1019. }
  1020. else if (checkRowIndentation < rowIndentation) {
  1021. // No need to keep looking for siblings when we get to a parent.
  1022. break;
  1023. }
  1024. }
  1025. else {
  1026. break;
  1027. }
  1028. checkRow = $(checkRow)[directions[d]]();
  1029. }
  1030. // Since siblings are added in reverse order for previous, reverse the
  1031. // completed list of previous siblings. Add the current row and continue.
  1032. if (directions[d] == 'prev') {
  1033. siblings.reverse();
  1034. siblings.push(this.element);
  1035. }
  1036. }
  1037. return siblings;
  1038. };
  1039. /**
  1040. * Remove indentation helper classes from the current row group.
  1041. */
  1042. Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
  1043. for (var n in this.children) {
  1044. $('.indentation', this.children[n])
  1045. .removeClass('tree-child')
  1046. .removeClass('tree-child-first')
  1047. .removeClass('tree-child-last')
  1048. .removeClass('tree-child-horizontal');
  1049. }
  1050. };
  1051. /**
  1052. * Add an asterisk or other marker to the changed row.
  1053. */
  1054. Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
  1055. var marker = Drupal.theme('tableDragChangedMarker');
  1056. var cell = $('td:first', this.element);
  1057. if ($('span.tabledrag-changed', cell).length == 0) {
  1058. cell.append(marker);
  1059. }
  1060. };
  1061. /**
  1062. * Stub function. Allows a custom handler when a row is indented.
  1063. */
  1064. Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
  1065. return null;
  1066. };
  1067. /**
  1068. * Stub function. Allows a custom handler when a row is swapped.
  1069. */
  1070. Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
  1071. return null;
  1072. };
  1073. Drupal.theme.prototype.tableDragChangedMarker = function () {
  1074. return '<span class="warning tabledrag-changed">*</span>';
  1075. };
  1076. Drupal.theme.prototype.tableDragIndentation = function () {
  1077. return '<div class="indentation">&nbsp;</div>';
  1078. };
  1079. Drupal.theme.prototype.tableDragChangedWarning = function () {
  1080. 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>';
  1081. };
  1082. })(jQuery);