dataTables.colReorder.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. /*! ColReorder 1.3.1
  2. * ©2010-2015 SpryMedia Ltd - datatables.net/license
  3. */
  4. /**
  5. * @summary ColReorder
  6. * @description Provide the ability to reorder columns in a DataTable
  7. * @version 1.3.1
  8. * @file dataTables.colReorder.js
  9. * @author SpryMedia Ltd (www.sprymedia.co.uk)
  10. * @contact www.sprymedia.co.uk/contact
  11. * @copyright Copyright 2010-2014 SpryMedia Ltd.
  12. *
  13. * This source file is free software, available under the following license:
  14. * MIT license - http://datatables.net/license/mit
  15. *
  16. * This source file is distributed in the hope that it will be useful, but
  17. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  18. * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
  19. *
  20. * For details please refer to: http://www.datatables.net
  21. */
  22. (function( factory ){
  23. if ( typeof define === 'function' && define.amd ) {
  24. // AMD
  25. define( ['jquery', 'datatables.net'], function ( $ ) {
  26. return factory( $, window, document );
  27. } );
  28. }
  29. else if ( typeof exports === 'object' ) {
  30. // CommonJS
  31. module.exports = function (root, $) {
  32. if ( ! root ) {
  33. root = window;
  34. }
  35. if ( ! $ || ! $.fn.dataTable ) {
  36. $ = require('datatables.net')(root, $).$;
  37. }
  38. return factory( $, root, root.document );
  39. };
  40. }
  41. else {
  42. // Browser
  43. factory( jQuery, window, document );
  44. }
  45. }(function( $, window, document, undefined ) {
  46. 'use strict';
  47. var DataTable = $.fn.dataTable;
  48. /**
  49. * Switch the key value pairing of an index array to be value key (i.e. the old value is now the
  50. * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ].
  51. * @method fnInvertKeyValues
  52. * @param array aIn Array to switch around
  53. * @returns array
  54. */
  55. function fnInvertKeyValues( aIn )
  56. {
  57. var aRet=[];
  58. for ( var i=0, iLen=aIn.length ; i<iLen ; i++ )
  59. {
  60. aRet[ aIn[i] ] = i;
  61. }
  62. return aRet;
  63. }
  64. /**
  65. * Modify an array by switching the position of two elements
  66. * @method fnArraySwitch
  67. * @param array aArray Array to consider, will be modified by reference (i.e. no return)
  68. * @param int iFrom From point
  69. * @param int iTo Insert point
  70. * @returns void
  71. */
  72. function fnArraySwitch( aArray, iFrom, iTo )
  73. {
  74. var mStore = aArray.splice( iFrom, 1 )[0];
  75. aArray.splice( iTo, 0, mStore );
  76. }
  77. /**
  78. * Switch the positions of nodes in a parent node (note this is specifically designed for
  79. * table rows). Note this function considers all element nodes under the parent!
  80. * @method fnDomSwitch
  81. * @param string sTag Tag to consider
  82. * @param int iFrom Element to move
  83. * @param int Point to element the element to (before this point), can be null for append
  84. * @returns void
  85. */
  86. function fnDomSwitch( nParent, iFrom, iTo )
  87. {
  88. var anTags = [];
  89. for ( var i=0, iLen=nParent.childNodes.length ; i<iLen ; i++ )
  90. {
  91. if ( nParent.childNodes[i].nodeType == 1 )
  92. {
  93. anTags.push( nParent.childNodes[i] );
  94. }
  95. }
  96. var nStore = anTags[ iFrom ];
  97. if ( iTo !== null )
  98. {
  99. nParent.insertBefore( nStore, anTags[iTo] );
  100. }
  101. else
  102. {
  103. nParent.appendChild( nStore );
  104. }
  105. }
  106. /**
  107. * Plug-in for DataTables which will reorder the internal column structure by taking the column
  108. * from one position (iFrom) and insert it into a given point (iTo).
  109. * @method $.fn.dataTableExt.oApi.fnColReorder
  110. * @param object oSettings DataTables settings object - automatically added by DataTables!
  111. * @param int iFrom Take the column to be repositioned from this point
  112. * @param int iTo and insert it into this point
  113. * @param bool drop Indicate if the reorder is the final one (i.e. a drop)
  114. * not a live reorder
  115. * @returns void
  116. */
  117. $.fn.dataTableExt.oApi.fnColReorder = function ( oSettings, iFrom, iTo, drop )
  118. {
  119. var i, iLen, j, jLen, jen, iCols=oSettings.aoColumns.length, nTrs, oCol;
  120. var attrMap = function ( obj, prop, mapping ) {
  121. if ( ! obj[ prop ] || typeof obj[ prop ] === 'function' ) {
  122. return;
  123. }
  124. var a = obj[ prop ].split('.');
  125. var num = a.shift();
  126. if ( isNaN( num*1 ) ) {
  127. return;
  128. }
  129. obj[ prop ] = mapping[ num*1 ]+'.'+a.join('.');
  130. };
  131. /* Sanity check in the input */
  132. if ( iFrom == iTo )
  133. {
  134. /* Pointless reorder */
  135. return;
  136. }
  137. if ( iFrom < 0 || iFrom >= iCols )
  138. {
  139. this.oApi._fnLog( oSettings, 1, "ColReorder 'from' index is out of bounds: "+iFrom );
  140. return;
  141. }
  142. if ( iTo < 0 || iTo >= iCols )
  143. {
  144. this.oApi._fnLog( oSettings, 1, "ColReorder 'to' index is out of bounds: "+iTo );
  145. return;
  146. }
  147. /*
  148. * Calculate the new column array index, so we have a mapping between the old and new
  149. */
  150. var aiMapping = [];
  151. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  152. {
  153. aiMapping[i] = i;
  154. }
  155. fnArraySwitch( aiMapping, iFrom, iTo );
  156. var aiInvertMapping = fnInvertKeyValues( aiMapping );
  157. /*
  158. * Convert all internal indexing to the new column order indexes
  159. */
  160. /* Sorting */
  161. for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ )
  162. {
  163. oSettings.aaSorting[i][0] = aiInvertMapping[ oSettings.aaSorting[i][0] ];
  164. }
  165. /* Fixed sorting */
  166. if ( oSettings.aaSortingFixed !== null )
  167. {
  168. for ( i=0, iLen=oSettings.aaSortingFixed.length ; i<iLen ; i++ )
  169. {
  170. oSettings.aaSortingFixed[i][0] = aiInvertMapping[ oSettings.aaSortingFixed[i][0] ];
  171. }
  172. }
  173. /* Data column sorting (the column which the sort for a given column should take place on) */
  174. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  175. {
  176. oCol = oSettings.aoColumns[i];
  177. for ( j=0, jLen=oCol.aDataSort.length ; j<jLen ; j++ )
  178. {
  179. oCol.aDataSort[j] = aiInvertMapping[ oCol.aDataSort[j] ];
  180. }
  181. // Update the column indexes
  182. oCol.idx = aiInvertMapping[ oCol.idx ];
  183. }
  184. // Update 1.10 optimised sort class removal variable
  185. $.each( oSettings.aLastSort, function (i, val) {
  186. oSettings.aLastSort[i].src = aiInvertMapping[ val.src ];
  187. } );
  188. /* Update the Get and Set functions for each column */
  189. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  190. {
  191. oCol = oSettings.aoColumns[i];
  192. if ( typeof oCol.mData == 'number' ) {
  193. oCol.mData = aiInvertMapping[ oCol.mData ];
  194. }
  195. else if ( $.isPlainObject( oCol.mData ) ) {
  196. // HTML5 data sourced
  197. attrMap( oCol.mData, '_', aiInvertMapping );
  198. attrMap( oCol.mData, 'filter', aiInvertMapping );
  199. attrMap( oCol.mData, 'sort', aiInvertMapping );
  200. attrMap( oCol.mData, 'type', aiInvertMapping );
  201. }
  202. }
  203. /*
  204. * Move the DOM elements
  205. */
  206. if ( oSettings.aoColumns[iFrom].bVisible )
  207. {
  208. /* Calculate the current visible index and the point to insert the node before. The insert
  209. * before needs to take into account that there might not be an element to insert before,
  210. * in which case it will be null, and an appendChild should be used
  211. */
  212. var iVisibleIndex = this.oApi._fnColumnIndexToVisible( oSettings, iFrom );
  213. var iInsertBeforeIndex = null;
  214. i = iTo < iFrom ? iTo : iTo + 1;
  215. while ( iInsertBeforeIndex === null && i < iCols )
  216. {
  217. iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible( oSettings, i );
  218. i++;
  219. }
  220. /* Header */
  221. nTrs = oSettings.nTHead.getElementsByTagName('tr');
  222. for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
  223. {
  224. fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex );
  225. }
  226. /* Footer */
  227. if ( oSettings.nTFoot !== null )
  228. {
  229. nTrs = oSettings.nTFoot.getElementsByTagName('tr');
  230. for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
  231. {
  232. fnDomSwitch( nTrs[i], iVisibleIndex, iInsertBeforeIndex );
  233. }
  234. }
  235. /* Body */
  236. for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
  237. {
  238. if ( oSettings.aoData[i].nTr !== null )
  239. {
  240. fnDomSwitch( oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex );
  241. }
  242. }
  243. }
  244. /*
  245. * Move the internal array elements
  246. */
  247. /* Columns */
  248. fnArraySwitch( oSettings.aoColumns, iFrom, iTo );
  249. // regenerate the get / set functions
  250. for ( i=0, iLen=iCols ; i<iLen ; i++ ) {
  251. oSettings.oApi._fnColumnOptions( oSettings, i, {} );
  252. }
  253. /* Search columns */
  254. fnArraySwitch( oSettings.aoPreSearchCols, iFrom, iTo );
  255. /* Array array - internal data anodes cache */
  256. for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ )
  257. {
  258. var data = oSettings.aoData[i];
  259. var cells = data.anCells;
  260. if ( cells ) {
  261. fnArraySwitch( cells, iFrom, iTo );
  262. // Longer term, should this be moved into the DataTables' invalidate
  263. // methods?
  264. for ( j=0, jen=cells.length ; j<jen ; j++ ) {
  265. if ( cells[j] && cells[j]._DT_CellIndex ) {
  266. cells[j]._DT_CellIndex.column = j;
  267. }
  268. }
  269. }
  270. // For DOM sourced data, the invalidate will reread the cell into
  271. // the data array, but for data sources as an array, they need to
  272. // be flipped
  273. if ( data.src !== 'dom' && $.isArray( data._aData ) ) {
  274. fnArraySwitch( data._aData, iFrom, iTo );
  275. }
  276. }
  277. /* Reposition the header elements in the header layout array */
  278. for ( i=0, iLen=oSettings.aoHeader.length ; i<iLen ; i++ )
  279. {
  280. fnArraySwitch( oSettings.aoHeader[i], iFrom, iTo );
  281. }
  282. if ( oSettings.aoFooter !== null )
  283. {
  284. for ( i=0, iLen=oSettings.aoFooter.length ; i<iLen ; i++ )
  285. {
  286. fnArraySwitch( oSettings.aoFooter[i], iFrom, iTo );
  287. }
  288. }
  289. // Invalidate row cached data for sorting, filtering etc
  290. var api = new $.fn.dataTable.Api( oSettings );
  291. api.rows().invalidate();
  292. /*
  293. * Update DataTables' event handlers
  294. */
  295. /* Sort listener */
  296. for ( i=0, iLen=iCols ; i<iLen ; i++ )
  297. {
  298. $(oSettings.aoColumns[i].nTh).off('click.DT');
  299. this.oApi._fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i );
  300. }
  301. /* Fire an event so other plug-ins can update */
  302. $(oSettings.oInstance).trigger( 'column-reorder.dt', [ oSettings, {
  303. from: iFrom,
  304. to: iTo,
  305. mapping: aiInvertMapping,
  306. drop: drop,
  307. // Old style parameters for compatibility
  308. iFrom: iFrom,
  309. iTo: iTo,
  310. aiInvertMapping: aiInvertMapping
  311. } ] );
  312. };
  313. /**
  314. * ColReorder provides column visibility control for DataTables
  315. * @class ColReorder
  316. * @constructor
  317. * @param {object} dt DataTables settings object
  318. * @param {object} opts ColReorder options
  319. */
  320. var ColReorder = function( dt, opts )
  321. {
  322. var settings = new $.fn.dataTable.Api( dt ).settings()[0];
  323. // Ensure that we can't initialise on the same table twice
  324. if ( settings._colReorder ) {
  325. return settings._colReorder;
  326. }
  327. // Allow the options to be a boolean for defaults
  328. if ( opts === true ) {
  329. opts = {};
  330. }
  331. // Convert from camelCase to Hungarian, just as DataTables does
  332. var camelToHungarian = $.fn.dataTable.camelToHungarian;
  333. if ( camelToHungarian ) {
  334. camelToHungarian( ColReorder.defaults, ColReorder.defaults, true );
  335. camelToHungarian( ColReorder.defaults, opts || {} );
  336. }
  337. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  338. * Public class variables
  339. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  340. /**
  341. * @namespace Settings object which contains customisable information for ColReorder instance
  342. */
  343. this.s = {
  344. /**
  345. * DataTables settings object
  346. * @property dt
  347. * @type Object
  348. * @default null
  349. */
  350. "dt": null,
  351. /**
  352. * Initialisation object used for this instance
  353. * @property init
  354. * @type object
  355. * @default {}
  356. */
  357. "init": $.extend( true, {}, ColReorder.defaults, opts ),
  358. /**
  359. * Number of columns to fix (not allow to be reordered)
  360. * @property fixed
  361. * @type int
  362. * @default 0
  363. */
  364. "fixed": 0,
  365. /**
  366. * Number of columns to fix counting from right (not allow to be reordered)
  367. * @property fixedRight
  368. * @type int
  369. * @default 0
  370. */
  371. "fixedRight": 0,
  372. /**
  373. * Callback function for once the reorder has been done
  374. * @property reorderCallback
  375. * @type function
  376. * @default null
  377. */
  378. "reorderCallback": null,
  379. /**
  380. * @namespace Information used for the mouse drag
  381. */
  382. "mouse": {
  383. "startX": -1,
  384. "startY": -1,
  385. "offsetX": -1,
  386. "offsetY": -1,
  387. "target": -1,
  388. "targetIndex": -1,
  389. "fromIndex": -1
  390. },
  391. /**
  392. * Information which is used for positioning the insert cusor and knowing where to do the
  393. * insert. Array of objects with the properties:
  394. * x: x-axis position
  395. * to: insert point
  396. * @property aoTargets
  397. * @type array
  398. * @default []
  399. */
  400. "aoTargets": []
  401. };
  402. /**
  403. * @namespace Common and useful DOM elements for the class instance
  404. */
  405. this.dom = {
  406. /**
  407. * Dragging element (the one the mouse is moving)
  408. * @property drag
  409. * @type element
  410. * @default null
  411. */
  412. "drag": null,
  413. /**
  414. * The insert cursor
  415. * @property pointer
  416. * @type element
  417. * @default null
  418. */
  419. "pointer": null
  420. };
  421. /* Constructor logic */
  422. this.s.dt = settings;
  423. this.s.dt._colReorder = this;
  424. this._fnConstruct();
  425. return this;
  426. };
  427. $.extend( ColReorder.prototype, {
  428. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  429. * Public methods
  430. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  431. /**
  432. * Reset the column ordering to the original ordering that was detected on
  433. * start up.
  434. * @return {this} Returns `this` for chaining.
  435. *
  436. * @example
  437. * // DataTables initialisation with ColReorder
  438. * var table = $('#example').dataTable( {
  439. * "sDom": 'Rlfrtip'
  440. * } );
  441. *
  442. * // Add click event to a button to reset the ordering
  443. * $('#resetOrdering').click( function (e) {
  444. * e.preventDefault();
  445. * $.fn.dataTable.ColReorder( table ).fnReset();
  446. * } );
  447. */
  448. "fnReset": function ()
  449. {
  450. this._fnOrderColumns( this.fnOrder() );
  451. return this;
  452. },
  453. /**
  454. * `Deprecated` - Get the current order of the columns, as an array.
  455. * @return {array} Array of column identifiers
  456. * @deprecated `fnOrder` should be used in preference to this method.
  457. * `fnOrder` acts as a getter/setter.
  458. */
  459. "fnGetCurrentOrder": function ()
  460. {
  461. return this.fnOrder();
  462. },
  463. /**
  464. * Get the current order of the columns, as an array. Note that the values
  465. * given in the array are unique identifiers for each column. Currently
  466. * these are the original ordering of the columns that was detected on
  467. * start up, but this could potentially change in future.
  468. * @return {array} Array of column identifiers
  469. *
  470. * @example
  471. * // Get column ordering for the table
  472. * var order = $.fn.dataTable.ColReorder( dataTable ).fnOrder();
  473. *//**
  474. * Set the order of the columns, from the positions identified in the
  475. * ordering array given. Note that ColReorder takes a brute force approach
  476. * to reordering, so it is possible multiple reordering events will occur
  477. * before the final order is settled upon.
  478. * @param {array} [set] Array of column identifiers in the new order. Note
  479. * that every column must be included, uniquely, in this array.
  480. * @return {this} Returns `this` for chaining.
  481. *
  482. * @example
  483. * // Swap the first and second columns
  484. * $.fn.dataTable.ColReorder( dataTable ).fnOrder( [1, 0, 2, 3, 4] );
  485. *
  486. * @example
  487. * // Move the first column to the end for the table `#example`
  488. * var curr = $.fn.dataTable.ColReorder( '#example' ).fnOrder();
  489. * var first = curr.shift();
  490. * curr.push( first );
  491. * $.fn.dataTable.ColReorder( '#example' ).fnOrder( curr );
  492. *
  493. * @example
  494. * // Reverse the table's order
  495. * $.fn.dataTable.ColReorder( '#example' ).fnOrder(
  496. * $.fn.dataTable.ColReorder( '#example' ).fnOrder().reverse()
  497. * );
  498. */
  499. "fnOrder": function ( set, original )
  500. {
  501. var a = [], i, ien, j, jen;
  502. var columns = this.s.dt.aoColumns;
  503. if ( set === undefined ){
  504. for ( i=0, ien=columns.length ; i<ien ; i++ ) {
  505. a.push( columns[i]._ColReorder_iOrigCol );
  506. }
  507. return a;
  508. }
  509. // The order given is based on the original indexes, rather than the
  510. // existing ones, so we need to translate from the original to current
  511. // before then doing the order
  512. if ( original ) {
  513. var order = this.fnOrder();
  514. for ( i=0, ien=set.length ; i<ien ; i++ ) {
  515. a.push( $.inArray( set[i], order ) );
  516. }
  517. set = a;
  518. }
  519. this._fnOrderColumns( fnInvertKeyValues( set ) );
  520. return this;
  521. },
  522. /**
  523. * Convert from the original column index, to the original
  524. *
  525. * @param {int|array} idx Index(es) to convert
  526. * @param {string} dir Transpose direction - `fromOriginal` / `toCurrent`
  527. * or `'toOriginal` / `fromCurrent`
  528. * @return {int|array} Converted values
  529. */
  530. fnTranspose: function ( idx, dir )
  531. {
  532. if ( ! dir ) {
  533. dir = 'toCurrent';
  534. }
  535. var order = this.fnOrder();
  536. var columns = this.s.dt.aoColumns;
  537. if ( dir === 'toCurrent' ) {
  538. // Given an original index, want the current
  539. return ! $.isArray( idx ) ?
  540. $.inArray( idx, order ) :
  541. $.map( idx, function ( index ) {
  542. return $.inArray( index, order );
  543. } );
  544. }
  545. else {
  546. // Given a current index, want the original
  547. return ! $.isArray( idx ) ?
  548. columns[idx]._ColReorder_iOrigCol :
  549. $.map( idx, function ( index ) {
  550. return columns[index]._ColReorder_iOrigCol;
  551. } );
  552. }
  553. },
  554. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  555. * Private methods (they are of course public in JS, but recommended as private)
  556. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  557. /**
  558. * Constructor logic
  559. * @method _fnConstruct
  560. * @returns void
  561. * @private
  562. */
  563. "_fnConstruct": function ()
  564. {
  565. var that = this;
  566. var iLen = this.s.dt.aoColumns.length;
  567. var table = this.s.dt.nTable;
  568. var i;
  569. /* Columns discounted from reordering - counting left to right */
  570. if ( this.s.init.iFixedColumns )
  571. {
  572. this.s.fixed = this.s.init.iFixedColumns;
  573. }
  574. if ( this.s.init.iFixedColumnsLeft )
  575. {
  576. this.s.fixed = this.s.init.iFixedColumnsLeft;
  577. }
  578. /* Columns discounted from reordering - counting right to left */
  579. this.s.fixedRight = this.s.init.iFixedColumnsRight ?
  580. this.s.init.iFixedColumnsRight :
  581. 0;
  582. /* Drop callback initialisation option */
  583. if ( this.s.init.fnReorderCallback )
  584. {
  585. this.s.reorderCallback = this.s.init.fnReorderCallback;
  586. }
  587. /* Add event handlers for the drag and drop, and also mark the original column order */
  588. for ( i = 0; i < iLen; i++ )
  589. {
  590. if ( i > this.s.fixed-1 && i < iLen - this.s.fixedRight )
  591. {
  592. this._fnMouseListener( i, this.s.dt.aoColumns[i].nTh );
  593. }
  594. /* Mark the original column order for later reference */
  595. this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i;
  596. }
  597. /* State saving */
  598. this.s.dt.oApi._fnCallbackReg( this.s.dt, 'aoStateSaveParams', function (oS, oData) {
  599. that._fnStateSave.call( that, oData );
  600. }, "ColReorder_State" );
  601. /* An initial column order has been specified */
  602. var aiOrder = null;
  603. if ( this.s.init.aiOrder )
  604. {
  605. aiOrder = this.s.init.aiOrder.slice();
  606. }
  607. /* State loading, overrides the column order given */
  608. if ( this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' &&
  609. this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length )
  610. {
  611. aiOrder = this.s.dt.oLoadedState.ColReorder;
  612. }
  613. /* If we have an order to apply - do so */
  614. if ( aiOrder )
  615. {
  616. /* We might be called during or after the DataTables initialisation. If before, then we need
  617. * to wait until the draw is done, if after, then do what we need to do right away
  618. */
  619. if ( !that.s.dt._bInitComplete )
  620. {
  621. var bDone = false;
  622. $(table).on( 'draw.dt.colReorder', function () {
  623. if ( !that.s.dt._bInitComplete && !bDone )
  624. {
  625. bDone = true;
  626. var resort = fnInvertKeyValues( aiOrder );
  627. that._fnOrderColumns.call( that, resort );
  628. }
  629. } );
  630. }
  631. else
  632. {
  633. var resort = fnInvertKeyValues( aiOrder );
  634. that._fnOrderColumns.call( that, resort );
  635. }
  636. }
  637. else {
  638. this._fnSetColumnIndexes();
  639. }
  640. // Destroy clean up
  641. $(table).on( 'destroy.dt.colReorder', function () {
  642. $(table).off( 'destroy.dt.colReorder draw.dt.colReorder' );
  643. $(that.s.dt.nTHead).find( '*' ).off( '.ColReorder' );
  644. $.each( that.s.dt.aoColumns, function (i, column) {
  645. $(column.nTh).removeAttr('data-column-index');
  646. } );
  647. that.s.dt._colReorder = null;
  648. that.s = null;
  649. } );
  650. },
  651. /**
  652. * Set the column order from an array
  653. * @method _fnOrderColumns
  654. * @param array a An array of integers which dictate the column order that should be applied
  655. * @returns void
  656. * @private
  657. */
  658. "_fnOrderColumns": function ( a )
  659. {
  660. var changed = false;
  661. if ( a.length != this.s.dt.aoColumns.length )
  662. {
  663. this.s.dt.oInstance.oApi._fnLog( this.s.dt, 1, "ColReorder - array reorder does not "+
  664. "match known number of columns. Skipping." );
  665. return;
  666. }
  667. for ( var i=0, iLen=a.length ; i<iLen ; i++ )
  668. {
  669. var currIndex = $.inArray( i, a );
  670. if ( i != currIndex )
  671. {
  672. /* Reorder our switching array */
  673. fnArraySwitch( a, currIndex, i );
  674. /* Do the column reorder in the table */
  675. this.s.dt.oInstance.fnColReorder( currIndex, i, true );
  676. changed = true;
  677. }
  678. }
  679. this._fnSetColumnIndexes();
  680. // Has anything actually changed? If not, then nothing else to do
  681. if ( ! changed ) {
  682. return;
  683. }
  684. /* When scrolling we need to recalculate the column sizes to allow for the shift */
  685. if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" )
  686. {
  687. this.s.dt.oInstance.fnAdjustColumnSizing( false );
  688. }
  689. /* Save the state */
  690. this.s.dt.oInstance.oApi._fnSaveState( this.s.dt );
  691. if ( this.s.reorderCallback !== null )
  692. {
  693. this.s.reorderCallback.call( this );
  694. }
  695. },
  696. /**
  697. * Because we change the indexes of columns in the table, relative to their starting point
  698. * we need to reorder the state columns to what they are at the starting point so we can
  699. * then rearrange them again on state load!
  700. * @method _fnStateSave
  701. * @param object oState DataTables state
  702. * @returns string JSON encoded cookie string for DataTables
  703. * @private
  704. */
  705. "_fnStateSave": function ( oState )
  706. {
  707. var i, iLen, aCopy, iOrigColumn;
  708. var oSettings = this.s.dt;
  709. var columns = oSettings.aoColumns;
  710. oState.ColReorder = [];
  711. /* Sorting */
  712. if ( oState.aaSorting ) {
  713. // 1.10.0-
  714. for ( i=0 ; i<oState.aaSorting.length ; i++ ) {
  715. oState.aaSorting[i][0] = columns[ oState.aaSorting[i][0] ]._ColReorder_iOrigCol;
  716. }
  717. var aSearchCopy = $.extend( true, [], oState.aoSearchCols );
  718. for ( i=0, iLen=columns.length ; i<iLen ; i++ )
  719. {
  720. iOrigColumn = columns[i]._ColReorder_iOrigCol;
  721. /* Column filter */
  722. oState.aoSearchCols[ iOrigColumn ] = aSearchCopy[i];
  723. /* Visibility */
  724. oState.abVisCols[ iOrigColumn ] = columns[i].bVisible;
  725. /* Column reordering */
  726. oState.ColReorder.push( iOrigColumn );
  727. }
  728. }
  729. else if ( oState.order ) {
  730. // 1.10.1+
  731. for ( i=0 ; i<oState.order.length ; i++ ) {
  732. oState.order[i][0] = columns[ oState.order[i][0] ]._ColReorder_iOrigCol;
  733. }
  734. var stateColumnsCopy = $.extend( true, [], oState.columns );
  735. for ( i=0, iLen=columns.length ; i<iLen ; i++ )
  736. {
  737. iOrigColumn = columns[i]._ColReorder_iOrigCol;
  738. /* Columns */
  739. oState.columns[ iOrigColumn ] = stateColumnsCopy[i];
  740. /* Column reordering */
  741. oState.ColReorder.push( iOrigColumn );
  742. }
  743. }
  744. },
  745. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  746. * Mouse drop and drag
  747. */
  748. /**
  749. * Add a mouse down listener to a particluar TH element
  750. * @method _fnMouseListener
  751. * @param int i Column index
  752. * @param element nTh TH element clicked on
  753. * @returns void
  754. * @private
  755. */
  756. "_fnMouseListener": function ( i, nTh )
  757. {
  758. var that = this;
  759. $(nTh).on( 'mousedown.ColReorder', function (e) {
  760. e.preventDefault();
  761. that._fnMouseDown.call( that, e, nTh );
  762. } );
  763. },
  764. /**
  765. * Mouse down on a TH element in the table header
  766. * @method _fnMouseDown
  767. * @param event e Mouse event
  768. * @param element nTh TH element to be dragged
  769. * @returns void
  770. * @private
  771. */
  772. "_fnMouseDown": function ( e, nTh )
  773. {
  774. var that = this;
  775. /* Store information about the mouse position */
  776. var target = $(e.target).closest('th, td');
  777. var offset = target.offset();
  778. var idx = parseInt( $(nTh).attr('data-column-index'), 10 );
  779. if ( idx === undefined ) {
  780. return;
  781. }
  782. this.s.mouse.startX = e.pageX;
  783. this.s.mouse.startY = e.pageY;
  784. this.s.mouse.offsetX = e.pageX - offset.left;
  785. this.s.mouse.offsetY = e.pageY - offset.top;
  786. this.s.mouse.target = this.s.dt.aoColumns[ idx ].nTh;//target[0];
  787. this.s.mouse.targetIndex = idx;
  788. this.s.mouse.fromIndex = idx;
  789. this._fnRegions();
  790. /* Add event handlers to the document */
  791. $(document)
  792. .on( 'mousemove.ColReorder', function (e) {
  793. that._fnMouseMove.call( that, e );
  794. } )
  795. .on( 'mouseup.ColReorder', function (e) {
  796. that._fnMouseUp.call( that, e );
  797. } );
  798. },
  799. /**
  800. * Deal with a mouse move event while dragging a node
  801. * @method _fnMouseMove
  802. * @param event e Mouse event
  803. * @returns void
  804. * @private
  805. */
  806. "_fnMouseMove": function ( e )
  807. {
  808. var that = this;
  809. if ( this.dom.drag === null )
  810. {
  811. /* Only create the drag element if the mouse has moved a specific distance from the start
  812. * point - this allows the user to make small mouse movements when sorting and not have a
  813. * possibly confusing drag element showing up
  814. */
  815. if ( Math.pow(
  816. Math.pow(e.pageX - this.s.mouse.startX, 2) +
  817. Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5 ) < 5 )
  818. {
  819. return;
  820. }
  821. this._fnCreateDragNode();
  822. }
  823. /* Position the element - we respect where in the element the click occured */
  824. this.dom.drag.css( {
  825. left: e.pageX - this.s.mouse.offsetX,
  826. top: e.pageY - this.s.mouse.offsetY
  827. } );
  828. /* Based on the current mouse position, calculate where the insert should go */
  829. var bSet = false;
  830. var lastToIndex = this.s.mouse.toIndex;
  831. for ( var i=1, iLen=this.s.aoTargets.length ; i<iLen ; i++ )
  832. {
  833. if ( e.pageX < this.s.aoTargets[i-1].x + ((this.s.aoTargets[i].x-this.s.aoTargets[i-1].x)/2) )
  834. {
  835. this.dom.pointer.css( 'left', this.s.aoTargets[i-1].x );
  836. this.s.mouse.toIndex = this.s.aoTargets[i-1].to;
  837. bSet = true;
  838. break;
  839. }
  840. }
  841. // The insert element wasn't positioned in the array (less than
  842. // operator), so we put it at the end
  843. if ( !bSet )
  844. {
  845. this.dom.pointer.css( 'left', this.s.aoTargets[this.s.aoTargets.length-1].x );
  846. this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length-1].to;
  847. }
  848. // Perform reordering if realtime updating is on and the column has moved
  849. if ( this.s.init.bRealtime && lastToIndex !== this.s.mouse.toIndex ) {
  850. this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex, false );
  851. this.s.mouse.fromIndex = this.s.mouse.toIndex;
  852. this._fnRegions();
  853. }
  854. },
  855. /**
  856. * Finish off the mouse drag and insert the column where needed
  857. * @method _fnMouseUp
  858. * @param event e Mouse event
  859. * @returns void
  860. * @private
  861. */
  862. "_fnMouseUp": function ( e )
  863. {
  864. var that = this;
  865. $(document).off( 'mousemove.ColReorder mouseup.ColReorder' );
  866. if ( this.dom.drag !== null )
  867. {
  868. /* Remove the guide elements */
  869. this.dom.drag.remove();
  870. this.dom.pointer.remove();
  871. this.dom.drag = null;
  872. this.dom.pointer = null;
  873. /* Actually do the reorder */
  874. this.s.dt.oInstance.fnColReorder( this.s.mouse.fromIndex, this.s.mouse.toIndex, true );
  875. this._fnSetColumnIndexes();
  876. /* When scrolling we need to recalculate the column sizes to allow for the shift */
  877. if ( this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "" )
  878. {
  879. this.s.dt.oInstance.fnAdjustColumnSizing( false );
  880. }
  881. /* Save the state */
  882. this.s.dt.oInstance.oApi._fnSaveState( this.s.dt );
  883. if ( this.s.reorderCallback !== null )
  884. {
  885. this.s.reorderCallback.call( this );
  886. }
  887. }
  888. },
  889. /**
  890. * Calculate a cached array with the points of the column inserts, and the
  891. * 'to' points
  892. * @method _fnRegions
  893. * @returns void
  894. * @private
  895. */
  896. "_fnRegions": function ()
  897. {
  898. var aoColumns = this.s.dt.aoColumns;
  899. this.s.aoTargets.splice( 0, this.s.aoTargets.length );
  900. this.s.aoTargets.push( {
  901. "x": $(this.s.dt.nTable).offset().left,
  902. "to": 0
  903. } );
  904. var iToPoint = 0;
  905. var total = $(aoColumns[0].nTh).offset().left; // Offset of the first column
  906. for ( var i=0, iLen=aoColumns.length ; i<iLen ; i++ )
  907. {
  908. /* For the column / header in question, we want it's position to remain the same if the
  909. * position is just to it's immediate left or right, so we only increment the counter for
  910. * other columns
  911. */
  912. if ( i != this.s.mouse.fromIndex )
  913. {
  914. iToPoint++;
  915. }
  916. if ( aoColumns[i].bVisible && aoColumns[i].nTh.style.display !=='none' )
  917. {
  918. total += $(aoColumns[i].nTh).outerWidth();
  919. this.s.aoTargets.push( {
  920. "x": total,
  921. "to": iToPoint
  922. } );
  923. }
  924. }
  925. /* Disallow columns for being reordered by drag and drop, counting right to left */
  926. if ( this.s.fixedRight !== 0 )
  927. {
  928. this.s.aoTargets.splice( this.s.aoTargets.length - this.s.fixedRight );
  929. }
  930. /* Disallow columns for being reordered by drag and drop, counting left to right */
  931. if ( this.s.fixed !== 0 )
  932. {
  933. this.s.aoTargets.splice( 0, this.s.fixed );
  934. }
  935. },
  936. /**
  937. * Copy the TH element that is being drags so the user has the idea that they are actually
  938. * moving it around the page.
  939. * @method _fnCreateDragNode
  940. * @returns void
  941. * @private
  942. */
  943. "_fnCreateDragNode": function ()
  944. {
  945. var scrolling = this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "";
  946. var origCell = this.s.dt.aoColumns[ this.s.mouse.targetIndex ].nTh;
  947. var origTr = origCell.parentNode;
  948. var origThead = origTr.parentNode;
  949. var origTable = origThead.parentNode;
  950. var cloneCell = $(origCell).clone();
  951. // This is a slightly odd combination of jQuery and DOM, but it is the
  952. // fastest and least resource intensive way I could think of cloning
  953. // the table with just a single header cell in it.
  954. this.dom.drag = $(origTable.cloneNode(false))
  955. .addClass( 'DTCR_clonedTable' )
  956. .append(
  957. $(origThead.cloneNode(false)).append(
  958. $(origTr.cloneNode(false)).append(
  959. cloneCell[0]
  960. )
  961. )
  962. )
  963. .css( {
  964. position: 'absolute',
  965. top: 0,
  966. left: 0,
  967. width: $(origCell).outerWidth(),
  968. height: $(origCell).outerHeight()
  969. } )
  970. .appendTo( 'body' );
  971. this.dom.pointer = $('<div></div>')
  972. .addClass( 'DTCR_pointer' )
  973. .css( {
  974. position: 'absolute',
  975. top: scrolling ?
  976. $('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top :
  977. $(this.s.dt.nTable).offset().top,
  978. height : scrolling ?
  979. $('div.dataTables_scroll', this.s.dt.nTableWrapper).height() :
  980. $(this.s.dt.nTable).height()
  981. } )
  982. .appendTo( 'body' );
  983. },
  984. /**
  985. * Add a data attribute to the column headers, so we know the index of
  986. * the row to be reordered. This allows fast detection of the index, and
  987. * for this plug-in to work with FixedHeader which clones the nodes.
  988. * @private
  989. */
  990. "_fnSetColumnIndexes": function ()
  991. {
  992. $.each( this.s.dt.aoColumns, function (i, column) {
  993. $(column.nTh).attr('data-column-index', i);
  994. } );
  995. }
  996. } );
  997. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  998. * Static parameters
  999. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1000. /**
  1001. * ColReorder default settings for initialisation
  1002. * @namespace
  1003. * @static
  1004. */
  1005. ColReorder.defaults = {
  1006. /**
  1007. * Predefined ordering for the columns that will be applied automatically
  1008. * on initialisation. If not specified then the order that the columns are
  1009. * found to be in the HTML is the order used.
  1010. * @type array
  1011. * @default null
  1012. * @static
  1013. */
  1014. aiOrder: null,
  1015. /**
  1016. * Redraw the table's column ordering as the end user draws the column
  1017. * (`true`) or wait until the mouse is released (`false` - default). Note
  1018. * that this will perform a redraw on each reordering, which involves an
  1019. * Ajax request each time if you are using server-side processing in
  1020. * DataTables.
  1021. * @type boolean
  1022. * @default false
  1023. * @static
  1024. */
  1025. bRealtime: true,
  1026. /**
  1027. * Indicate how many columns should be fixed in position (counting from the
  1028. * left). This will typically be 1 if used, but can be as high as you like.
  1029. * @type int
  1030. * @default 0
  1031. * @static
  1032. */
  1033. iFixedColumnsLeft: 0,
  1034. /**
  1035. * As `iFixedColumnsRight` but counting from the right.
  1036. * @type int
  1037. * @default 0
  1038. * @static
  1039. */
  1040. iFixedColumnsRight: 0,
  1041. /**
  1042. * Callback function that is fired when columns are reordered. The `column-
  1043. * reorder` event is preferred over this callback
  1044. * @type function():void
  1045. * @default null
  1046. * @static
  1047. */
  1048. fnReorderCallback: null
  1049. };
  1050. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1051. * Constants
  1052. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1053. /**
  1054. * ColReorder version
  1055. * @constant version
  1056. * @type String
  1057. * @default As code
  1058. */
  1059. ColReorder.version = "1.3.1";
  1060. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1061. * DataTables interfaces
  1062. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1063. // Expose
  1064. $.fn.dataTable.ColReorder = ColReorder;
  1065. $.fn.DataTable.ColReorder = ColReorder;
  1066. // Register a new feature with DataTables
  1067. if ( typeof $.fn.dataTable == "function" &&
  1068. typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
  1069. $.fn.dataTableExt.fnVersionCheck('1.10.8') )
  1070. {
  1071. $.fn.dataTableExt.aoFeatures.push( {
  1072. "fnInit": function( settings ) {
  1073. var table = settings.oInstance;
  1074. if ( ! settings._colReorder ) {
  1075. var dtInit = settings.oInit;
  1076. var opts = dtInit.colReorder || dtInit.oColReorder || {};
  1077. new ColReorder( settings, opts );
  1078. }
  1079. else {
  1080. table.oApi._fnLog( settings, 1, "ColReorder attempted to initialise twice. Ignoring second" );
  1081. }
  1082. return null; /* No node for DataTables to insert */
  1083. },
  1084. "cFeature": "R",
  1085. "sFeature": "ColReorder"
  1086. } );
  1087. }
  1088. else {
  1089. alert( "Warning: ColReorder requires DataTables 1.10.8 or greater - www.datatables.net/download");
  1090. }
  1091. // Attach a listener to the document which listens for DataTables initialisation
  1092. // events so we can automatically initialise
  1093. $(document).on( 'preInit.dt.colReorder', function (e, settings) {
  1094. if ( e.namespace !== 'dt' ) {
  1095. return;
  1096. }
  1097. var init = settings.oInit.colReorder;
  1098. var defaults = DataTable.defaults.colReorder;
  1099. if ( init || defaults ) {
  1100. var opts = $.extend( {}, init, defaults );
  1101. if ( init !== false ) {
  1102. new ColReorder( settings, opts );
  1103. }
  1104. }
  1105. } );
  1106. // API augmentation
  1107. $.fn.dataTable.Api.register( 'colReorder.reset()', function () {
  1108. return this.iterator( 'table', function ( ctx ) {
  1109. ctx._colReorder.fnReset();
  1110. } );
  1111. } );
  1112. $.fn.dataTable.Api.register( 'colReorder.order()', function ( set, original ) {
  1113. if ( set ) {
  1114. return this.iterator( 'table', function ( ctx ) {
  1115. ctx._colReorder.fnOrder( set, original );
  1116. } );
  1117. }
  1118. return this.context.length ?
  1119. this.context[0]._colReorder.fnOrder() :
  1120. null;
  1121. } );
  1122. $.fn.dataTable.Api.register( 'colReorder.transpose()', function ( idx, dir ) {
  1123. return this.context.length && this.context[0]._colReorder ?
  1124. this.context[0]._colReorder.fnTranspose( idx, dir ) :
  1125. idx;
  1126. } );
  1127. return ColReorder;
  1128. }));