dataTables.ColReorder.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /*
  2. * File: ColReorder.js
  3. * Version: 1.0.8
  4. * CVS: $Id$
  5. * Description: Allow columns to be reordered in a DataTable
  6. * Author: Allan Jardine (www.sprymedia.co.uk)
  7. * Created: Wed Sep 15 18:23:29 BST 2010
  8. * Modified: $Date$ by $Author$
  9. * Language: Javascript
  10. * License: GPL v2 or BSD 3 point style
  11. * Project: DataTables
  12. * Contact: www.sprymedia.co.uk/contact
  13. *
  14. * Copyright 2010-2011 Allan Jardine, all rights reserved.
  15. *
  16. * This source file is free software, under either the GPL v2 license or a
  17. * BSD style license, available at:
  18. * http://datatables.net/license_gpl2
  19. * http://datatables.net/license_bsd
  20. *
  21. */
  22. (function($, window, document) {
  23. /**
  24. * Switch the key value pairing of an index array to be value key (i.e. the old value is now the
  25. * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ].
  26. * @method fnInvertKeyValues
  27. * @param array aIn Array to switch around
  28. * @returns array
  29. */
  30. function fnInvertKeyValues( aIn )
  31. {
  32. var aRet=[];
  33. for ( var i=0, iLen=aIn.length ; i<iLen ; i++ )
  34. {
  35. aRet[ aIn[i] ] = i;
  36. }
  37. return aRet;
  38. }
  39. /**
  40. * Modify an array by switching the position of two elements
  41. * @method fnArraySwitch
  42. * @param array aArray Array to consider, will be modified by reference (i.e. no return)
  43. * @param int iFrom From point
  44. * @param int iTo Insert point
  45. * @returns void
  46. */
  47. function fnArraySwitch( aArray, iFrom, iTo )
  48. {
  49. var mStore = aArray.splice( iFrom, 1 )[0];
  50. aArray.splice( iTo, 0, mStore );
  51. }
  52. /**
  53. * Switch the positions of nodes in a parent node (note this is specifically designed for
  54. * table rows). Note this function considers all element nodes under the parent!
  55. * @method fnDomSwitch
  56. * @param string sTag Tag to consider
  57. * @param int iFrom Element to move
  58. * @param int Point to element the element to (before this point), can be null for append
  59. * @returns void
  60. */
  61. function fnDomSwitch( nParent, iFrom, iTo )
  62. {
  63. var anTags = [];
  64. for ( var i=0, iLen=nParent.childNodes.length ; i<iLen ; i++ )
  65. {
  66. if ( nParent.childNodes[i].nodeType == 1 )
  67. {
  68. anTags.push( nParent.childNodes[i] );
  69. }
  70. }
  71. var nStore = anTags[ iFrom ];
  72. if ( iTo !== null )
  73. {
  74. nParent.insertBefore( nStore, anTags[iTo] );
  75. }
  76. else
  77. {
  78. nParent.appendChild( nStore );
  79. }
  80. }
  81. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  82. * DataTables plug-in API functions
  83. *
  84. * This are required by ColReorder in order to perform the tasks required, and also keep this
  85. * code portable, to be used for other column reordering projects with DataTables, if needed.
  86. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  87. /**
  88. * Plug-in for DataTables which will reorder the internal column structure by taking the column
  89. * from one position (iFrom) and insert it into a given point (iTo).
  90. * @method $.fn.dataTableExt.oApi.fnColReorder
  91. * @param object oSettings DataTables settings object - automatically added by DataTables!
  92. * @param int iFrom Take the column to be repositioned from this point
  93. * @param int iTo and insert it into this point
  94. * @returns void
  95. */
  96. $.fn.dataTableExt.oApi.fnColReorder = function ( oSettings, iFrom, iTo )
  97. {
  98. var i, iLen, j, jLen, iCols=oSettings.aoColumns.length, nTrs, oCol;
  99. /* Sanity check in the input */
  100. if ( iFrom == iTo )
  101. {
  102. /* Pointless reorder */
  103. return;
  104. }
  105. if ( iFrom < 0 || iFrom >= iCols )
  106. {
  107. this.oApi._fnLog( oSettings, 1, "ColReorder 'from' index is out of bounds: "+iFrom );
  108. return;
  109. }
  110. if ( iTo < 0 || iTo >= iCols )
  111. {
  112. this.oApi._fnLog( oSettings, 1, "ColReorder 'to' index is out of bounds: "+iTo );
  113. return;
  114. }
  115. /*
  116. * Calculate the new column array index, so we have a mapping between the old and new
  117. */
  118. var aiMapping = [];
  119. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  120. {
  121. aiMapping[i] = i;
  122. }
  123. fnArraySwitch( aiMapping, iFrom, iTo );
  124. var aiInvertMapping = fnInvertKeyValues( aiMapping );
  125. /*
  126. * Convert all internal indexing to the new column order indexes
  127. */
  128. /* Sorting */
  129. for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ )
  130. {
  131. oSettings.aaSorting[i][0] = aiInvertMapping[ oSettings.aaSorting[i][0] ];
  132. }
  133. /* Fixed sorting */
  134. if ( oSettings.aaSortingFixed !== null )
  135. {
  136. for ( i=0, iLen=oSettings.aaSortingFixed.length ; i<iLen ; i++ )
  137. {
  138. oSettings.aaSortingFixed[i][0] = aiInvertMapping[ oSettings.aaSortingFixed[i][0] ];
  139. }
  140. }
  141. /* Data column sorting (the column which the sort for a given column should take place on) */
  142. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  143. {
  144. oCol = oSettings.aoColumns[i];
  145. for ( j=0, jLen=oCol.aDataSort.length ; j<jLen ; j++ )
  146. {
  147. oCol.aDataSort[j] = aiInvertMapping[ oCol.aDataSort[j] ];
  148. }
  149. }
  150. /* Update the Get and Set functions for each column */
  151. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  152. {
  153. oCol = oSettings.aoColumns[i];
  154. if ( typeof oCol.mData == 'number' ) {
  155. oCol.mData = aiInvertMapping[ oCol.mData ];
  156. oCol.fnGetData = oSettings.oApi._fnGetObjectDataFn( oCol.mData );
  157. oCol.fnSetData = oSettings.oApi._fnSetObjectDataFn( oCol.mData );
  158. }
  159. }
  160. /*
  161. * Move the DOM elements
  162. */
  163. if ( oSettings.aoColumns[iFrom].bVisible )
  164. {
  165. /* Calculate the current visible index and the point to insert the node before. The insert
  166. * before needs to take into account that there might not be an element to insert before,
  167. * in which case it will be null, and an appendChild should be used
  168. */
  169. var iVisibleIndex = this.oApi._fnColumnIndexToVisible( oSettings, iFrom );
  170. var iInsertBeforeIndex = null;
  171. i = iTo < iFrom ? iTo : iTo + 1;
  172. while ( iInsertBeforeIndex === null && i < iCols )
  173. {
  174. iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible( oSettings, i );
  175. i++;
  176. }
  177. /* Header */
  178. nTrs = oSettings.nTHead.getElementsByTagName('tr');
  179. for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
  180. {
  181. fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex );
  182. }
  183. /* Footer */
  184. if ( oSettings.nTFoot !== null )
  185. {
  186. nTrs = oSettings.nTFoot.getElementsByTagName('tr');
  187. for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
  188. {
  189. fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex );
  190. }
  191. }
  192. /* Body */
  193. for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
  194. {
  195. if ( oSettings.aoData[i].nTr !== null )
  196. {
  197. fnDomSwitch( oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex );
  198. }
  199. }
  200. }
  201. /*
  202. * Move the internal array elements
  203. */
  204. /* Columns */
  205. fnArraySwitch( oSettings.aoColumns, iFrom, iTo );
  206. /* Search columns */
  207. fnArraySwitch( oSettings.aoPreSearchCols, iFrom, iTo );
  208. /* Array array - internal data anodes cache */
  209. for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
  210. {
  211. if ( $.isArray( oSettings.aoData[i]._aData ) ) {
  212. fnArraySwitch( oSettings.aoData[i]._aData, iFrom, iTo );
  213. }
  214. fnArraySwitch( oSettings.aoData[i]._anHidden, iFrom, iTo );
  215. }
  216. /* Reposition the header elements in the header layout array */
  217. for ( i=0, iLen=oSettings.aoHeader.length ; i<iLen ; i++ )
  218. {
  219. fnArraySwitch( oSettings.aoHeader[i], iFrom, iTo );
  220. }
  221. if ( oSettings.aoFooter !== null )
  222. {
  223. for ( i=0, iLen=oSettings.aoFooter.length ; i<iLen ; i++ )
  224. {
  225. fnArraySwitch( oSettings.aoFooter[i], iFrom, iTo );
  226. }
  227. }
  228. /*
  229. * Update DataTables' event handlers
  230. */
  231. /* Sort listener */
  232. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  233. {
  234. $(oSettings.aoColumns[i].nTh).unbind('click');
  235. this.oApi._fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i );
  236. }
  237. /* Fire an event so other plug-ins can update */
  238. $(oSettings.oInstance).trigger( 'column-reorder', [ oSettings, {
  239. "iFrom": iFrom,
  240. "iTo": iTo,
  241. "aiInvertMapping": aiInvertMapping
  242. } ] );
  243. if ( typeof oSettings.oInstance._oPluginFixedHeader != 'undefined' )
  244. {
  245. oSettings.oInstance._oPluginFixedHeader.fnUpdate();
  246. }
  247. };
  248. /**
  249. * ColReorder provides column visiblity control for DataTables
  250. * @class ColReorder
  251. * @constructor
  252. * @param {object} DataTables settings object
  253. * @param {object} ColReorder options
  254. */
  255. ColReorder = function( oDTSettings, oOpts )
  256. {
  257. /* Santiy check that we are a new instance */
  258. if ( !this.CLASS || this.CLASS != "ColReorder" )
  259. {
  260. alert( "Warning: ColReorder must be initialised with the keyword 'new'" );
  261. }
  262. if ( typeof oOpts == 'undefined' )
  263. {
  264. oOpts = {};
  265. }
  266. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  267. * Public class variables
  268. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  269. /**
  270. * @namespace Settings object which contains customisable information for ColReorder instance
  271. */
  272. this.s = {
  273. /**
  274. * DataTables settings object
  275. * @property dt
  276. * @type Object
  277. * @default null
  278. */
  279. "dt": null,
  280. /**
  281. * Initialisation object used for this instance
  282. * @property init
  283. * @type object
  284. * @default {}
  285. */
  286. "init": oOpts,
  287. /**
  288. * Number of columns to fix (not allow to be reordered)
  289. * @property fixed
  290. * @type int
  291. * @default 0
  292. */
  293. "fixed": 0,
  294. /**
  295. * Callback function for once the reorder has been done
  296. * @property dropcallback
  297. * @type function
  298. * @default null
  299. */
  300. "dropCallback": null,
  301. /**
  302. * @namespace Information used for the mouse drag
  303. */
  304. "mouse": {
  305. "startX": -1,
  306. "startY": -1,
  307. "offsetX": -1,
  308. "offsetY": -1,
  309. "target": -1,
  310. "targetIndex": -1,
  311. "fromIndex": -1
  312. },
  313. /**
  314. * Information which is used for positioning the insert cusor and knowing where to do the
  315. * insert. Array of objects with the properties:
  316. * x: x-axis position
  317. * to: insert point
  318. * @property aoTargets
  319. * @type array
  320. * @default []
  321. */
  322. "aoTargets": []
  323. };
  324. /**
  325. * @namespace Common and useful DOM elements for the class instance
  326. */
  327. this.dom = {
  328. /**
  329. * Dragging element (the one the mouse is moving)
  330. * @property drag
  331. * @type element
  332. * @default null
  333. */
  334. "drag": null,
  335. /**
  336. * The insert cursor
  337. * @property pointer
  338. * @type element
  339. * @default null
  340. */
  341. "pointer": null
  342. };
  343. /* Constructor logic */
  344. this.s.dt = oDTSettings.oInstance.fnSettings();
  345. this._fnConstruct();
  346. /* Add destroy callback */
  347. oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', jQuery.proxy(this._fnDestroy, this), 'ColReorder');
  348. /* Store the instance for later use */
  349. ColReorder.aoInstances.push( this );
  350. return this;
  351. };
  352. ColReorder.prototype = {
  353. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  354. * Public methods
  355. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  356. "fnReset": function ()
  357. {
  358. var a = [];
  359. for ( var i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
  360. {
  361. a.push( this.s.dt.aoColumns[i]._ColReorder_iOrigCol );
  362. }
  363. this._fnOrderColumns( a );
  364. },
  365. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  366. * Private methods (they are of course public in JS, but recommended as private)
  367. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  368. /**
  369. * Constructor logic
  370. * @method _fnConstruct
  371. * @returns void
  372. * @private
  373. */
  374. "_fnConstruct": function ()
  375. {
  376. var that = this;
  377. var i, iLen;
  378. /* Columns discounted from reordering - counting left to right */
  379. if ( typeof this.s.init.iFixedColumns != 'undefined' )
  380. {
  381. this.s.fixed = this.s.init.iFixedColumns;
  382. }
  383. /* Drop callback initialisation option */
  384. if ( typeof this.s.init.fnReorderCallback != 'undefined' )
  385. {
  386. this.s.dropCallback = this.s.init.fnReorderCallback;
  387. }
  388. /* Add event handlers for the drag and drop, and also mark the original column order */
  389. for ( i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
  390. {
  391. if ( i > this.s.fixed-1 )
  392. {
  393. this._fnMouseListener( i, this.s.dt.aoColumns[i].nTh );
  394. }
  395. /* Mark the original column order for later reference */
  396. this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i;
  397. }
  398. /* State saving */
  399. this.s.dt.oApi._fnCallbackReg( this.s.dt, 'aoStateSaveParams', function (oS, oData) {
  400. that._fnStateSave.call( that, oData );
  401. }, "ColReorder_State" );
  402. /* An initial column order has been specified */
  403. var aiOrder = null;
  404. if ( typeof this.s.init.aiOrder != 'undefined' )
  405. {
  406. aiOrder = this.s.init.aiOrder.slice();
  407. }
  408. /* State loading, overrides the column order given */
  409. if ( this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' &&
  410. this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length )
  411. {
  412. aiOrder = this.s.dt.oLoadedState.ColReorder;
  413. }
  414. /* If we have an order to apply - do so */
  415. if ( aiOrder )
  416. {
  417. /* We might be called during or after the DataTables initialisation. If before, then we need
  418. * to wait until the draw is done, if after, then do what we need to do right away
  419. */
  420. if ( !that.s.dt._bInitComplete )
  421. {
  422. var bDone = false;
  423. this.s.dt.aoDrawCallback.push( {
  424. "fn": function () {
  425. if ( !that.s.dt._bInitComplete && !bDone )
  426. {
  427. bDone = true;
  428. var resort = fnInvertKeyValues( aiOrder );
  429. that._fnOrderColumns.call( that, resort );
  430. }
  431. },
  432. "sName": "ColReorder_Pre"
  433. } );
  434. }
  435. else
  436. {
  437. var resort = fnInvertKeyValues( aiOrder );
  438. that._fnOrderColumns.call( that, resort );
  439. }
  440. }
  441. },
  442. /**
  443. * Set the column order from an array
  444. * @method _fnOrderColumns
  445. * @param array a An array of integers which dictate the column order that should be applied
  446. * @returns void
  447. * @private
  448. */
  449. "_fnOrderColumns": function ( a )
  450. {
  451. if ( a.length != this.s.dt.aoColumns.length )
  452. {
  453. this.s.dt.oInstance.oApi._fnLog( this.s.dt, 1, "ColReorder - array reorder does not "+
  454. "match known number of columns. Skipping." );
  455. return;
  456. }
  457. for ( var i=0, iLen=a.length ; i<iLen ; i++ )
  458. {
  459. var currIndex = $.inArray( i, a );
  460. if ( i != currIndex )
  461. {
  462. /* Reorder our switching array */
  463. fnArraySwitch( a, currIndex, i );
  464. /* Do the column reorder in the table */
  465. this.s.dt.oInstance.fnColReorder( currIndex, i );
  466. }
  467. }
  468. /* When scrolling we need to recalculate the column sizes to allow for the shift */
  469. if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" )
  470. {
  471. this.s.dt.oInstance.fnAdjustColumnSizing();
  472. }
  473. /* Save the state */
  474. this.s.dt.oInstance.oApi._fnSaveState( this.s.dt );
  475. },
  476. /**
  477. * Because we change the indexes of columns in the table, relative to their starting point
  478. * we need to reorder the state columns to what they are at the starting point so we can
  479. * then rearrange them again on state load!
  480. * @method _fnStateSave
  481. * @param object oState DataTables state
  482. * @returns string JSON encoded cookie string for DataTables
  483. * @private
  484. */
  485. "_fnStateSave": function ( oState )
  486. {
  487. var i, iLen, aCopy, iOrigColumn;
  488. var oSettings = this.s.dt;
  489. /* Sorting */
  490. for ( i=0 ; i<oState.aaSorting.length ; i++ )
  491. {
  492. oState.aaSorting[i][0] = oSettings.aoColumns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol;
  493. }
  494. aSearchCopy = $.extend( true, [], oState.aoSearchCols );
  495. oState.ColReorder = [];
  496. for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
  497. {
  498. iOrigColumn = oSettings.aoColumns[i]._ColReorder_iOrigCol;
  499. /* Column filter */
  500. oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i];
  501. /* Visibility */
  502. oState.abVisCols[ iOrigColumn ] = oSettings.aoColumns[i].bVisible;
  503. /* Column reordering */
  504. oState.ColReorder.push( iOrigColumn );
  505. }
  506. },
  507. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  508. * Mouse drop and drag
  509. */
  510. /**
  511. * Add a mouse down listener to a particluar TH element
  512. * @method _fnMouseListener
  513. * @param int i Column index
  514. * @param element nTh TH element clicked on
  515. * @returns void
  516. * @private
  517. */
  518. "_fnMouseListener": function ( i, nTh )
  519. {
  520. var that = this;
  521. $(nTh).bind( 'mousedown.ColReorder', function (e) {
  522. e.preventDefault();
  523. that._fnMouseDown.call( that, e, nTh );
  524. } );
  525. },
  526. /**
  527. * Mouse down on a TH element in the table header
  528. * @method _fnMouseDown
  529. * @param event e Mouse event
  530. * @param element nTh TH element to be dragged
  531. * @returns void
  532. * @private
  533. */
  534. "_fnMouseDown": function ( e, nTh )
  535. {
  536. var
  537. that = this,
  538. aoColumns = this.s.dt.aoColumns;
  539. /* Store information about the mouse position */
  540. var nThTarget = e.target.nodeName == "TH" ? e.target : $(e.target).parents('TH')[0];
  541. var offset = $(nThTarget).offset();
  542. this.s.mouse.startX = e.pageX;
  543. this.s.mouse.startY = e.pageY;
  544. this.s.mouse.offsetX = e.pageX - offset.left;
  545. this.s.mouse.offsetY = e.pageY - offset.top;
  546. this.s.mouse.target = nTh;
  547. this.s.mouse.targetIndex = $('th', nTh.parentNode).index( nTh );
  548. this.s.mouse.fromIndex = this.s.dt.oInstance.oApi._fnVisibleToColumnIndex( this.s.dt,
  549. this.s.mouse.targetIndex );
  550. /* Calculate a cached array with the points of the column inserts, and the 'to' points */
  551. this.s.aoTargets.splice( 0, this.s.aoTargets.length );
  552. this.s.aoTargets.push( {
  553. "x": $(this.s.dt.nTable).offset().left,
  554. "to": 0
  555. } );
  556. var iToPoint = 0;
  557. for ( var i=0, iLen=aoColumns.length ; i<iLen ; i++ )
  558. {
  559. /* For the column / header in question, we want it's position to remain the same if the
  560. * position is just to it's immediate left or right, so we only incremement the counter for
  561. * other columns
  562. */
  563. if ( i != this.s.mouse.fromIndex )
  564. {
  565. iToPoint++;
  566. }
  567. if ( aoColumns[i].bVisible )
  568. {
  569. this.s.aoTargets.push( {
  570. "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(),
  571. "to": iToPoint
  572. } );
  573. }
  574. }
  575. /* Disallow columns for being reordered by drag and drop, counting left to right */
  576. if ( this.s.fixed !== 0 )
  577. {
  578. this.s.aoTargets.splice( 0, this.s.fixed );
  579. }
  580. /* Add event handlers to the document */
  581. $(document).bind( 'mousemove.ColReorder', function (e) {
  582. that._fnMouseMove.call( that, e );
  583. } );
  584. $(document).bind( 'mouseup.ColReorder', function (e) {
  585. that._fnMouseUp.call( that, e );
  586. } );
  587. },
  588. /**
  589. * Deal with a mouse move event while dragging a node
  590. * @method _fnMouseMove
  591. * @param event e Mouse event
  592. * @returns void
  593. * @private
  594. */
  595. "_fnMouseMove": function ( e )
  596. {
  597. var that = this;
  598. if ( this.dom.drag === null )
  599. {
  600. /* Only create the drag element if the mouse has moved a specific distance from the start
  601. * point - this allows the user to make small mouse movements when sorting and not have a
  602. * possibly confusing drag element showing up
  603. */
  604. if ( Math.pow(
  605. Math.pow(e.pageX - this.s.mouse.startX, 2) +
  606. Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5 ) < 5 )
  607. {
  608. return;
  609. }
  610. this._fnCreateDragNode();
  611. }
  612. /* Position the element - we respect where in the element the click occured */
  613. this.dom.drag.style.left = (e.pageX - this.s.mouse.offsetX) + "px";
  614. this.dom.drag.style.top = (e.pageY - this.s.mouse.offsetY) + "px";
  615. /* Based on the current mouse position, calculate where the insert should go */
  616. var bSet = false;
  617. for ( var i=1, iLen=this.s.aoTargets.length ; i<iLen ; i++ )
  618. {
  619. if ( e.pageX < this.s.aoTargets[i-1].x + ((this.s.aoTargets[i].x-this.s.aoTargets[i-1].x)/2) )
  620. {
  621. this.dom.pointer.style.left = this.s.aoTargets[i-1].x +"px";
  622. this.s.mouse.toIndex = this.s.aoTargets[i-1].to;
  623. bSet = true;
  624. break;
  625. }
  626. }
  627. /* The insert element wasn't positioned in the array (less than operator), so we put it at
  628. * the end
  629. */
  630. if ( !bSet )
  631. {
  632. this.dom.pointer.style.left = this.s.aoTargets[this.s.aoTargets.length-1].x +"px";
  633. this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length-1].to;
  634. }
  635. },
  636. /**
  637. * Finish off the mouse drag and insert the column where needed
  638. * @method _fnMouseUp
  639. * @param event e Mouse event
  640. * @returns void
  641. * @private
  642. */
  643. "_fnMouseUp": function ( e )
  644. {
  645. var that = this;
  646. $(document).unbind( 'mousemove.ColReorder' );
  647. $(document).unbind( 'mouseup.ColReorder' );
  648. if ( this.dom.drag !== null )
  649. {
  650. /* Remove the guide elements */
  651. document.body.removeChild( this.dom.drag );
  652. document.body.removeChild( this.dom.pointer );
  653. this.dom.drag = null;
  654. this.dom.pointer = null;
  655. /* Actually do the reorder */
  656. this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex );
  657. /* When scrolling we need to recalculate the column sizes to allow for the shift */
  658. if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" )
  659. {
  660. this.s.dt.oInstance.fnAdjustColumnSizing();
  661. }
  662. if ( this.s.dropCallback !== null )
  663. {
  664. this.s.dropCallback.call( this );
  665. }
  666. /* Save the state */
  667. this.s.dt.oInstance.oApi._fnSaveState( this.s.dt );
  668. }
  669. },
  670. /**
  671. * Copy the TH element that is being drags so the user has the idea that they are actually
  672. * moving it around the page.
  673. * @method _fnCreateDragNode
  674. * @returns void
  675. * @private
  676. */
  677. "_fnCreateDragNode": function ()
  678. {
  679. var that = this;
  680. this.dom.drag = $(this.s.dt.nTHead.parentNode).clone(true)[0];
  681. this.dom.drag.className += " DTCR_clonedTable";
  682. while ( this.dom.drag.getElementsByTagName('caption').length > 0 )
  683. {
  684. this.dom.drag.removeChild( this.dom.drag.getElementsByTagName('caption')[0] );
  685. }
  686. while ( this.dom.drag.getElementsByTagName('tbody').length > 0 )
  687. {
  688. this.dom.drag.removeChild( this.dom.drag.getElementsByTagName('tbody')[0] );
  689. }
  690. while ( this.dom.drag.getElementsByTagName('tfoot').length > 0 )
  691. {
  692. this.dom.drag.removeChild( this.dom.drag.getElementsByTagName('tfoot')[0] );
  693. }
  694. $('thead tr:eq(0)', this.dom.drag).each( function () {
  695. $('th', this).eq(that.s.mouse.targetIndex).siblings().remove();
  696. } );
  697. $('tr', this.dom.drag).height( $('tr:eq(0)', that.s.dt.nTHead).height() );
  698. $('thead tr:gt(0)', this.dom.drag).remove();
  699. $('thead th:eq(0)', this.dom.drag).each( function (i) {
  700. this.style.width = $('th:eq('+that.s.mouse.targetIndex+')', that.s.dt.nTHead).width()+"px";
  701. } );
  702. this.dom.drag.style.position = "absolute";
  703. this.dom.drag.style.top = "0px";
  704. this.dom.drag.style.left = "0px";
  705. this.dom.drag.style.width = $('th:eq('+that.s.mouse.targetIndex+')', that.s.dt.nTHead).outerWidth()+"px";
  706. this.dom.pointer = document.createElement( 'div' );
  707. this.dom.pointer.className = "DTCR_pointer";
  708. this.dom.pointer.style.position = "absolute";
  709. if ( this.s.dt.oScroll.sX === "" && this.s.dt.oScroll.sY === "" )
  710. {
  711. this.dom.pointer.style.top = $(this.s.dt.nTable).offset().top+"px";
  712. this.dom.pointer.style.height = $(this.s.dt.nTable).height()+"px";
  713. }
  714. else
  715. {
  716. this.dom.pointer.style.top = $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top+"px";
  717. this.dom.pointer.style.height = $('div.dataTables_scroll', this.s.dt.nTableWrapper).height()+"px";
  718. }
  719. document.body.appendChild( this.dom.pointer );
  720. document.body.appendChild( this.dom.drag );
  721. },
  722. /**
  723. * Clean up ColReorder memory references and event handlers
  724. * @method _fnDestroy
  725. * @returns void
  726. * @private
  727. */
  728. "_fnDestroy": function ()
  729. {
  730. for ( var i=0, iLen=ColReorder.aoInstances.length ; i<iLen ; i++ )
  731. {
  732. if ( ColReorder.aoInstances[i] === this )
  733. {
  734. ColReorder.aoInstances.splice( i, 1 );
  735. break;
  736. }
  737. }
  738. $(this.s.dt.nTHead).find( '*' ).unbind( '.ColReorder' );
  739. this.s.dt.oInstance._oPluginColReorder = null;
  740. this.s = null;
  741. }
  742. };
  743. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  744. * Static parameters
  745. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  746. /**
  747. * Array of all ColReorder instances for later reference
  748. * @property ColReorder.aoInstances
  749. * @type array
  750. * @default []
  751. * @static
  752. */
  753. ColReorder.aoInstances = [];
  754. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  755. * Static functions
  756. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  757. /**
  758. * Reset the column ordering for a DataTables instance
  759. * @method ColReorder.fnReset
  760. * @param object oTable DataTables instance to consider
  761. * @returns void
  762. * @static
  763. */
  764. ColReorder.fnReset = function ( oTable )
  765. {
  766. for ( var i=0, iLen=ColReorder.aoInstances.length ; i<iLen ; i++ )
  767. {
  768. if ( ColReorder.aoInstances[i].s.dt.oInstance == oTable )
  769. {
  770. ColReorder.aoInstances[i].fnReset();
  771. }
  772. }
  773. };
  774. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  775. * Constants
  776. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  777. /**
  778. * Name of this class
  779. * @constant CLASS
  780. * @type String
  781. * @default ColReorder
  782. */
  783. ColReorder.prototype.CLASS = "ColReorder";
  784. /**
  785. * ColReorder version
  786. * @constant VERSION
  787. * @type String
  788. * @default As code
  789. */
  790. ColReorder.VERSION = "1.0.8";
  791. ColReorder.prototype.VERSION = ColReorder.VERSION;
  792. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  793. * Initialisation
  794. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  795. /*
  796. * Register a new feature with DataTables
  797. */
  798. if ( typeof $.fn.dataTable == "function" &&
  799. typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
  800. $.fn.dataTableExt.fnVersionCheck('1.9.3') )
  801. {
  802. $.fn.dataTableExt.aoFeatures.push( {
  803. "fnInit": function( oDTSettings ) {
  804. var oTable = oDTSettings.oInstance;
  805. if ( typeof oTable._oPluginColReorder == 'undefined' ) {
  806. var opts = typeof oDTSettings.oInit.oColReorder != 'undefined' ?
  807. oDTSettings.oInit.oColReorder : {};
  808. oTable._oPluginColReorder = new ColReorder( oDTSettings, opts );
  809. } else {
  810. oTable.oApi._fnLog( oDTSettings, 1, "ColReorder attempted to initialise twice. Ignoring second" );
  811. }
  812. return null; /* No node to insert */
  813. },
  814. "cFeature": "R",
  815. "sFeature": "ColReorder"
  816. } );
  817. }
  818. else
  819. {
  820. alert( "Warning: ColReorder requires DataTables 1.9.3 or greater - www.datatables.net/download");
  821. }
  822. })(jQuery, window, document);