tabledrag.js 41 KB

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