PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/misc/tabledrag.js

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