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

/source/chrome/javascript/common/jquery/tablednd.js

https://gitlab.com/e0/web-developer
JavaScript | 314 lines | 187 code | 23 blank | 104 comment | 58 complexity | 6c170e7cfdf9cc35acaeed24046b062d MD5 | raw file
  1. /**
  2. * TableDnD plug-in for JQuery, allows you to drag and drop table rows
  3. * You can set up various options to control how the system will work
  4. * Copyright © Denis Howlett <denish@isocra.com>
  5. * Licensed like jQuery, see http://docs.jquery.com/License.
  6. *
  7. * Configuration options:
  8. *
  9. * onDragStyle
  10. * This is the style that is assigned to the row during drag. There are limitations to the styles that can be
  11. * associated with a row (such as you can't assign a border—well you can, but it won't be
  12. * displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
  13. * a map (as used in the jQuery css(...) function).
  14. * onDropStyle
  15. * This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
  16. * to what you can do. Also this replaces the original style, so again consider using onDragClass which
  17. * is simply added and then removed on drop.
  18. * onDragClass
  19. * This class is added for the duration of the drag and then removed when the row is dropped. It is more
  20. * flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
  21. * is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
  22. * stylesheet.
  23. * onDrop
  24. * Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
  25. * and the row that was dropped. You can work out the new order of the rows by using
  26. * table.rows.
  27. * onDragStart
  28. * Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
  29. * table and the row which the user has started to drag.
  30. * onAllowDrop
  31. * Pass a function that will be called as a row is over another row. If the function returns true, allow
  32. * dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
  33. * the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
  34. * scrollAmount
  35. * This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
  36. * window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
  37. * FF3 beta)
  38. *
  39. * Other ways to control behaviour:
  40. *
  41. * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
  42. * that you don't want to be draggable.
  43. *
  44. * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
  45. * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
  46. * an ID as must all the rows.
  47. *
  48. * Known problems:
  49. * - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
  50. *
  51. * Version 0.2: 2008-02-20 First public version
  52. * Version 0.3: 2008-02-07 Added onDragStart option
  53. * Made the scroll amount configurable (default is 5 as before)
  54. * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
  55. * Added onAllowDrop to control dropping
  56. * Fixed a bug which meant that you couldn't set the scroll amount in both directions
  57. * Added serialise method
  58. */
  59. jQuery.tableDnD = {
  60. /** Keep hold of the current table being dragged */
  61. currentTable : null,
  62. /** Keep hold of the current drag object if any */
  63. dragObject: null,
  64. /** The current mouse offset */
  65. mouseOffset: null,
  66. /** Remember the old value of Y so that we don't do too much processing */
  67. oldY: 0,
  68. /** Actually build the structure */
  69. build: function(options) {
  70. // Make sure options exists
  71. options = options || {};
  72. // Set up the defaults if any
  73. this.each(function() {
  74. // Remember the options
  75. this.tableDnDConfig = {
  76. onDragStyle: options.onDragStyle,
  77. onDropStyle: options.onDropStyle,
  78. // Add in the default class for whileDragging
  79. onDragClass: options.onDragClass ? options.onDragClass : "tDnD_whileDrag",
  80. onDrop: options.onDrop,
  81. onDragStart: options.onDragStart,
  82. scrollAmount: options.scrollAmount ? options.scrollAmount : 5
  83. };
  84. // Now make the rows draggable
  85. jQuery.tableDnD.makeDraggable(this);
  86. });
  87. // Now we need to capture the mouse up and mouse move event
  88. // We can use bind so that we don't interfere with other event handlers
  89. jQuery(document)
  90. .bind('mousemove', jQuery.tableDnD.mousemove)
  91. .bind('mouseup', jQuery.tableDnD.mouseup);
  92. // Don't break the chain
  93. return this;
  94. },
  95. /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
  96. makeDraggable: function(table) {
  97. // Now initialise the rows
  98. var rows = table.rows; //getElementsByTagName("tr")
  99. var config = table.tableDnDConfig;
  100. for (var i=0; i<rows.length; i++) {
  101. // To make non-draggable rows, add the nodrag class (eg for Category and Header rows)
  102. // inspired by John Tarr and Famic
  103. var nodrag = $(rows[i]).hasClass("nodrag");
  104. if (! nodrag) { //There is no NoDnD attribute on rows I want to drag
  105. jQuery(rows[i]).mousedown(function(ev) {
  106. if (ev.target.tagName == "TD") {
  107. jQuery.tableDnD.dragObject = this;
  108. jQuery.tableDnD.currentTable = table;
  109. jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
  110. if (config.onDragStart) {
  111. // Call the onDrop method if there is one
  112. config.onDragStart(table, this);
  113. }
  114. return false;
  115. }
  116. }).css("cursor", "move"); // Store the tableDnD object
  117. }
  118. }
  119. },
  120. /** Get the mouse coordinates from the event (allowing for browser differences) */
  121. mouseCoords: function(ev){
  122. if(ev.pageX || ev.pageY){
  123. return {x:ev.pageX, y:ev.pageY};
  124. }
  125. return {
  126. x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
  127. y:ev.clientY + document.body.scrollTop - document.body.clientTop
  128. };
  129. },
  130. /** Given a target element and a mouse event, get the mouse offset from that element.
  131. To do this we need the element's position and the mouse position */
  132. getMouseOffset: function(target, ev) {
  133. ev = ev || window.event;
  134. var docPos = this.getPosition(target);
  135. var mousePos = this.mouseCoords(ev);
  136. return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
  137. },
  138. /** Get the position of an element by going up the DOM tree and adding up all the offsets */
  139. getPosition: function(e){
  140. var left = 0;
  141. var top = 0;
  142. /** Safari fix -- thanks to Luis Chato for this! */
  143. if (e.offsetHeight == 0) {
  144. /** Safari 2 doesn't correctly grab the offsetTop of a table row
  145. this is detailed here:
  146. http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
  147. the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
  148. note that firefox will return a text node as a first child, so designing a more thorough
  149. solution may need to take that into account, for now this seems to work in firefox, safari, ie */
  150. e = e.firstChild; // a table cell
  151. }
  152. while (e.offsetParent){
  153. left += e.offsetLeft;
  154. top += e.offsetTop;
  155. e = e.offsetParent;
  156. }
  157. left += e.offsetLeft;
  158. top += e.offsetTop;
  159. return {x:left, y:top};
  160. },
  161. mousemove: function(ev) {
  162. if (jQuery.tableDnD.dragObject == null) {
  163. return;
  164. }
  165. var dragObj = jQuery(jQuery.tableDnD.dragObject);
  166. var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  167. var mousePos = jQuery.tableDnD.mouseCoords(ev);
  168. var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
  169. //auto scroll the window
  170. var yOffset = window.pageYOffset;
  171. if (document.all) {
  172. // Windows version
  173. //yOffset=document.body.scrollTop;
  174. if (typeof document.compatMode != 'undefined' &&
  175. document.compatMode != 'BackCompat') {
  176. yOffset = document.documentElement.scrollTop;
  177. }
  178. else if (typeof document.body != 'undefined') {
  179. yOffset=document.body.scrollTop;
  180. }
  181. }
  182. if (mousePos.y-yOffset < config.scrollAmount) {
  183. window.scrollBy(0, -config.scrollAmount);
  184. } else {
  185. var windowHeight = window.innerHeight ? window.innerHeight
  186. : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
  187. if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
  188. window.scrollBy(0, config.scrollAmount);
  189. }
  190. }
  191. if (y != jQuery.tableDnD.oldY) {
  192. // work out if we're going up or down...
  193. var movingDown = y > jQuery.tableDnD.oldY;
  194. // update the old value
  195. jQuery.tableDnD.oldY = y;
  196. // update the style to show we're dragging
  197. if (config.onDragClass) {
  198. dragObj.addClass(config.onDragClass);
  199. } else {
  200. dragObj.css(config.onDragStyle);
  201. }
  202. // If we're over a row then move the dragged row to there so that the user sees the
  203. // effect dynamically
  204. var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
  205. if (currentRow) {
  206. // TODO worry about what happens when there are multiple TBODIES
  207. if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
  208. jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
  209. } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
  210. jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
  211. }
  212. }
  213. }
  214. return false;
  215. },
  216. /** We're only worried about the y position really, because we can only move rows up and down */
  217. findDropTargetRow: function(draggedRow, y) {
  218. var rows = jQuery.tableDnD.currentTable.rows;
  219. for (var i=0; i<rows.length; i++) {
  220. var row = rows[i];
  221. var rowY = this.getPosition(row).y;
  222. var rowHeight = parseInt(row.offsetHeight)/2;
  223. if (row.offsetHeight == 0) {
  224. rowY = this.getPosition(row.firstChild).y;
  225. rowHeight = parseInt(row.firstChild.offsetHeight)/2;
  226. }
  227. // Because we always have to insert before, we need to offset the height a bit
  228. if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
  229. // that's the row we're over
  230. // If it's the same as the current row, ignore it
  231. if (row == draggedRow) {return null;}
  232. var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  233. if (config.onAllowDrop) {
  234. if (config.onAllowDrop(draggedRow, row)) {
  235. return row;
  236. } else {
  237. return null;
  238. }
  239. } else {
  240. // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
  241. var nodrop = $(row).hasClass("nodrop");
  242. if (! nodrop) {
  243. return row;
  244. } else {
  245. return null;
  246. }
  247. }
  248. return row;
  249. }
  250. }
  251. return null;
  252. },
  253. mouseup: function(e) {
  254. if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
  255. var droppedRow = jQuery.tableDnD.dragObject;
  256. var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  257. // If we have a dragObject, then we need to release it,
  258. // The row will already have been moved to the right place so we just reset stuff
  259. if (config.onDragClass) {
  260. jQuery(droppedRow).removeClass(config.onDragClass);
  261. } else {
  262. jQuery(droppedRow).css(config.onDropStyle);
  263. }
  264. jQuery.tableDnD.dragObject = null;
  265. if (config.onDrop) {
  266. // Call the onDrop method if there is one
  267. config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
  268. }
  269. jQuery.tableDnD.currentTable = null; // let go of the table too
  270. }
  271. },
  272. serialize: function() {
  273. if (jQuery.tableDnD.currentTable) {
  274. var result = "";
  275. var tableId = jQuery.tableDnD.currentTable.id;
  276. var rows = jQuery.tableDnD.currentTable.rows;
  277. for (var i=0; i<rows.length; i++) {
  278. if (result.length > 0) result += "&";
  279. result += tableId + '[]=' + rows[i].id;
  280. }
  281. return result;
  282. } else {
  283. return "Error: No Table id set, you need to set an id on your table and every row";
  284. }
  285. }
  286. }
  287. jQuery.fn.extend(
  288. {
  289. tableDnD : jQuery.tableDnD.build
  290. }
  291. );