dataTables.scroller.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. /*! Scroller 2.0.0
  2. * ©2011-2018 SpryMedia Ltd - datatables.net/license
  3. */
  4. /**
  5. * @summary Scroller
  6. * @description Virtual rendering for DataTables
  7. * @version 2.0.0
  8. * @file dataTables.scroller.js
  9. * @author SpryMedia Ltd (www.sprymedia.co.uk)
  10. * @contact www.sprymedia.co.uk/contact
  11. * @copyright Copyright 2011-2018 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. * Scroller is a virtual rendering plug-in for DataTables which allows large
  50. * datasets to be drawn on screen every quickly. What the virtual rendering means
  51. * is that only the visible portion of the table (and a bit to either side to make
  52. * the scrolling smooth) is drawn, while the scrolling container gives the
  53. * visual impression that the whole table is visible. This is done by making use
  54. * of the pagination abilities of DataTables and moving the table around in the
  55. * scrolling container DataTables adds to the page. The scrolling container is
  56. * forced to the height it would be for the full table display using an extra
  57. * element.
  58. *
  59. * Note that rows in the table MUST all be the same height. Information in a cell
  60. * which expands on to multiple lines will cause some odd behaviour in the scrolling.
  61. *
  62. * Scroller is initialised by simply including the letter 'S' in the sDom for the
  63. * table you want to have this feature enabled on. Note that the 'S' must come
  64. * AFTER the 't' parameter in `dom`.
  65. *
  66. * Key features include:
  67. * <ul class="limit_length">
  68. * <li>Speed! The aim of Scroller for DataTables is to make rendering large data sets fast</li>
  69. * <li>Full compatibility with deferred rendering in DataTables for maximum speed</li>
  70. * <li>Display millions of rows</li>
  71. * <li>Integration with state saving in DataTables (scrolling position is saved)</li>
  72. * <li>Easy to use</li>
  73. * </ul>
  74. *
  75. * @class
  76. * @constructor
  77. * @global
  78. * @param {object} dt DataTables settings object or API instance
  79. * @param {object} [opts={}] Configuration object for FixedColumns. Options
  80. * are defined by {@link Scroller.defaults}
  81. *
  82. * @requires jQuery 1.7+
  83. * @requires DataTables 1.10.0+
  84. *
  85. * @example
  86. * $(document).ready(function() {
  87. * $('#example').DataTable( {
  88. * "scrollY": "200px",
  89. * "ajax": "media/dataset/large.txt",
  90. * "scroller": true,
  91. * "deferRender": true
  92. * } );
  93. * } );
  94. */
  95. var Scroller = function ( dt, opts ) {
  96. /* Sanity check - you just know it will happen */
  97. if ( ! (this instanceof Scroller) ) {
  98. alert( "Scroller warning: Scroller must be initialised with the 'new' keyword." );
  99. return;
  100. }
  101. if ( opts === undefined ) {
  102. opts = {};
  103. }
  104. var dtApi = $.fn.dataTable.Api( dt );
  105. /**
  106. * Settings object which contains customisable information for the Scroller instance
  107. * @namespace
  108. * @private
  109. * @extends Scroller.defaults
  110. */
  111. this.s = {
  112. /**
  113. * DataTables settings object
  114. * @type object
  115. * @default Passed in as first parameter to constructor
  116. */
  117. dt: dtApi.settings()[0],
  118. /**
  119. * DataTables API instance
  120. * @type DataTable.Api
  121. */
  122. dtApi: dtApi,
  123. /**
  124. * Pixel location of the top of the drawn table in the viewport
  125. * @type int
  126. * @default 0
  127. */
  128. tableTop: 0,
  129. /**
  130. * Pixel location of the bottom of the drawn table in the viewport
  131. * @type int
  132. * @default 0
  133. */
  134. tableBottom: 0,
  135. /**
  136. * Pixel location of the boundary for when the next data set should be loaded and drawn
  137. * when scrolling up the way.
  138. * @type int
  139. * @default 0
  140. * @private
  141. */
  142. redrawTop: 0,
  143. /**
  144. * Pixel location of the boundary for when the next data set should be loaded and drawn
  145. * when scrolling down the way. Note that this is actually calculated as the offset from
  146. * the top.
  147. * @type int
  148. * @default 0
  149. * @private
  150. */
  151. redrawBottom: 0,
  152. /**
  153. * Auto row height or not indicator
  154. * @type bool
  155. * @default 0
  156. */
  157. autoHeight: true,
  158. /**
  159. * Number of rows calculated as visible in the visible viewport
  160. * @type int
  161. * @default 0
  162. */
  163. viewportRows: 0,
  164. /**
  165. * setTimeout reference for state saving, used when state saving is enabled in the DataTable
  166. * and when the user scrolls the viewport in order to stop the cookie set taking too much
  167. * CPU!
  168. * @type int
  169. * @default 0
  170. */
  171. stateTO: null,
  172. /**
  173. * setTimeout reference for the redraw, used when server-side processing is enabled in the
  174. * DataTables in order to prevent DoSing the server
  175. * @type int
  176. * @default null
  177. */
  178. drawTO: null,
  179. heights: {
  180. jump: null,
  181. page: null,
  182. virtual: null,
  183. scroll: null,
  184. /**
  185. * Height of rows in the table
  186. * @type int
  187. * @default 0
  188. */
  189. row: null,
  190. /**
  191. * Pixel height of the viewport
  192. * @type int
  193. * @default 0
  194. */
  195. viewport: null,
  196. labelFactor: 1
  197. },
  198. topRowFloat: 0,
  199. scrollDrawDiff: null,
  200. loaderVisible: false,
  201. forceReposition: false,
  202. baseRowTop: 0,
  203. baseScrollTop: 0,
  204. mousedown: false,
  205. lastScrollTop: 0
  206. };
  207. // @todo The defaults should extend a `c` property and the internal settings
  208. // only held in the `s` property. At the moment they are mixed
  209. this.s = $.extend( this.s, Scroller.oDefaults, opts );
  210. // Workaround for row height being read from height object (see above comment)
  211. this.s.heights.row = this.s.rowHeight;
  212. /**
  213. * DOM elements used by the class instance
  214. * @private
  215. * @namespace
  216. *
  217. */
  218. this.dom = {
  219. "force": document.createElement('div'),
  220. "label": $('<div class="dts_label">0</div>'),
  221. "scroller": null,
  222. "table": null,
  223. "loader": null
  224. };
  225. // Attach the instance to the DataTables instance so it can be accessed in
  226. // future. Don't initialise Scroller twice on the same table
  227. if ( this.s.dt.oScroller ) {
  228. return;
  229. }
  230. this.s.dt.oScroller = this;
  231. /* Let's do it */
  232. this.construct();
  233. };
  234. $.extend( Scroller.prototype, {
  235. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  236. * Public methods - to be exposed via the DataTables API
  237. */
  238. /**
  239. * Calculate and store information about how many rows are to be displayed
  240. * in the scrolling viewport, based on current dimensions in the browser's
  241. * rendering. This can be particularly useful if the table is initially
  242. * drawn in a hidden element - for example in a tab.
  243. * @param {bool} [redraw=true] Redraw the table automatically after the recalculation, with
  244. * the new dimensions forming the basis for the draw.
  245. * @returns {void}
  246. */
  247. measure: function ( redraw )
  248. {
  249. if ( this.s.autoHeight )
  250. {
  251. this._calcRowHeight();
  252. }
  253. var heights = this.s.heights;
  254. if ( heights.row ) {
  255. heights.viewport = $.contains(document, this.dom.scroller) ?
  256. this.dom.scroller.clientHeight :
  257. this._parseHeight($(this.dom.scroller).css('height'));
  258. // If collapsed (no height) use the max-height parameter
  259. if ( ! heights.viewport ) {
  260. heights.viewport = this._parseHeight($(this.dom.scroller).css('max-height'));
  261. }
  262. this.s.viewportRows = parseInt( heights.viewport / heights.row, 10 )+1;
  263. this.s.dt._iDisplayLength = this.s.viewportRows * this.s.displayBuffer;
  264. }
  265. var label = this.dom.label.outerHeight();
  266. heights.labelFactor = (heights.viewport-label) / heights.scroll;
  267. if ( redraw === undefined || redraw )
  268. {
  269. this.s.dt.oInstance.fnDraw( false );
  270. }
  271. },
  272. /**
  273. * Get information about current displayed record range. This corresponds to
  274. * the information usually displayed in the "Info" block of the table.
  275. *
  276. * @returns {object} info as an object:
  277. * {
  278. * start: {int}, // the 0-indexed record at the top of the viewport
  279. * end: {int}, // the 0-indexed record at the bottom of the viewport
  280. * }
  281. */
  282. pageInfo: function()
  283. {
  284. var
  285. dt = this.s.dt,
  286. iScrollTop = this.dom.scroller.scrollTop,
  287. iTotal = dt.fnRecordsDisplay(),
  288. iPossibleEnd = Math.ceil(this.pixelsToRow(iScrollTop + this.s.heights.viewport, false, this.s.ani));
  289. return {
  290. start: Math.floor(this.pixelsToRow(iScrollTop, false, this.s.ani)),
  291. end: iTotal < iPossibleEnd ? iTotal-1 : iPossibleEnd-1
  292. };
  293. },
  294. /**
  295. * Calculate the row number that will be found at the given pixel position
  296. * (y-scroll).
  297. *
  298. * Please note that when the height of the full table exceeds 1 million
  299. * pixels, Scroller switches into a non-linear mode for the scrollbar to fit
  300. * all of the records into a finite area, but this function returns a linear
  301. * value (relative to the last non-linear positioning).
  302. * @param {int} pixels Offset from top to calculate the row number of
  303. * @param {int} [intParse=true] If an integer value should be returned
  304. * @param {int} [virtual=false] Perform the calculations in the virtual domain
  305. * @returns {int} Row index
  306. */
  307. pixelsToRow: function ( pixels, intParse, virtual )
  308. {
  309. var diff = pixels - this.s.baseScrollTop;
  310. var row = virtual ?
  311. (this._domain( 'physicalToVirtual', this.s.baseScrollTop ) + diff) / this.s.heights.row :
  312. ( diff / this.s.heights.row ) + this.s.baseRowTop;
  313. return intParse || intParse === undefined ?
  314. parseInt( row, 10 ) :
  315. row;
  316. },
  317. /**
  318. * Calculate the pixel position from the top of the scrolling container for
  319. * a given row
  320. * @param {int} iRow Row number to calculate the position of
  321. * @returns {int} Pixels
  322. */
  323. rowToPixels: function ( rowIdx, intParse, virtual )
  324. {
  325. var pixels;
  326. var diff = rowIdx - this.s.baseRowTop;
  327. if ( virtual ) {
  328. pixels = this._domain( 'virtualToPhysical', this.s.baseScrollTop );
  329. pixels += diff * this.s.heights.row;
  330. }
  331. else {
  332. pixels = this.s.baseScrollTop;
  333. pixels += diff * this.s.heights.row;
  334. }
  335. return intParse || intParse === undefined ?
  336. parseInt( pixels, 10 ) :
  337. pixels;
  338. },
  339. /**
  340. * Calculate the row number that will be found at the given pixel position (y-scroll)
  341. * @param {int} row Row index to scroll to
  342. * @param {bool} [animate=true] Animate the transition or not
  343. * @returns {void}
  344. */
  345. scrollToRow: function ( row, animate )
  346. {
  347. var that = this;
  348. var ani = false;
  349. var px = this.rowToPixels( row );
  350. // We need to know if the table will redraw or not before doing the
  351. // scroll. If it will not redraw, then we need to use the currently
  352. // displayed table, and scroll with the physical pixels. Otherwise, we
  353. // need to calculate the table's new position from the virtual
  354. // transform.
  355. var preRows = ((this.s.displayBuffer-1)/2) * this.s.viewportRows;
  356. var drawRow = row - preRows;
  357. if ( drawRow < 0 ) {
  358. drawRow = 0;
  359. }
  360. if ( (px > this.s.redrawBottom || px < this.s.redrawTop) && this.s.dt._iDisplayStart !== drawRow ) {
  361. ani = true;
  362. px = this._domain( 'virtualToPhysical', row * this.s.heights.row );
  363. // If we need records outside the current draw region, but the new
  364. // scrolling position is inside that (due to the non-linear nature
  365. // for larger numbers of records), we need to force position update.
  366. if ( this.s.redrawTop < px && px < this.s.redrawBottom ) {
  367. this.s.forceReposition = true;
  368. animate = false;
  369. }
  370. }
  371. if ( typeof animate == 'undefined' || animate )
  372. {
  373. this.s.ani = ani;
  374. $(this.dom.scroller).animate( {
  375. "scrollTop": px
  376. }, function () {
  377. // This needs to happen after the animation has completed and
  378. // the final scroll event fired
  379. setTimeout( function () {
  380. that.s.ani = false;
  381. }, 25 );
  382. } );
  383. }
  384. else
  385. {
  386. $(this.dom.scroller).scrollTop( px );
  387. }
  388. },
  389. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  390. * Constructor
  391. */
  392. /**
  393. * Initialisation for Scroller
  394. * @returns {void}
  395. * @private
  396. */
  397. construct: function ()
  398. {
  399. var that = this;
  400. var dt = this.s.dtApi;
  401. /* Sanity check */
  402. if ( !this.s.dt.oFeatures.bPaginate ) {
  403. this.s.dt.oApi._fnLog( this.s.dt, 0, 'Pagination must be enabled for Scroller' );
  404. return;
  405. }
  406. /* Insert a div element that we can use to force the DT scrolling container to
  407. * the height that would be required if the whole table was being displayed
  408. */
  409. this.dom.force.style.position = "relative";
  410. this.dom.force.style.top = "0px";
  411. this.dom.force.style.left = "0px";
  412. this.dom.force.style.width = "1px";
  413. this.dom.scroller = $('div.'+this.s.dt.oClasses.sScrollBody, this.s.dt.nTableWrapper)[0];
  414. this.dom.scroller.appendChild( this.dom.force );
  415. this.dom.scroller.style.position = "relative";
  416. this.dom.table = $('>table', this.dom.scroller)[0];
  417. this.dom.table.style.position = "absolute";
  418. this.dom.table.style.top = "0px";
  419. this.dom.table.style.left = "0px";
  420. // Add class to 'announce' that we are a Scroller table
  421. $(dt.table().container()).addClass('dts DTS');
  422. // Add a 'loading' indicator
  423. if ( this.s.loadingIndicator )
  424. {
  425. this.dom.loader = $('<div class="dataTables_processing dts_loading">'+this.s.dt.oLanguage.sLoadingRecords+'</div>')
  426. .css('display', 'none');
  427. $(this.dom.scroller.parentNode)
  428. .css('position', 'relative')
  429. .append( this.dom.loader );
  430. }
  431. this.dom.label.appendTo(this.dom.scroller);
  432. /* Initial size calculations */
  433. if ( this.s.heights.row && this.s.heights.row != 'auto' )
  434. {
  435. this.s.autoHeight = false;
  436. }
  437. this.measure( false );
  438. // Scrolling callback to see if a page change is needed - use a throttled
  439. // function for the save save callback so we aren't hitting it on every
  440. // scroll
  441. this.s.ingnoreScroll = true;
  442. this.s.stateSaveThrottle = this.s.dt.oApi._fnThrottle( function () {
  443. that.s.dtApi.state.save();
  444. }, 500 );
  445. $(this.dom.scroller).on( 'scroll.dt-scroller', function (e) {
  446. that._scroll.call( that );
  447. } );
  448. // In iOS we catch the touchstart event in case the user tries to scroll
  449. // while the display is already scrolling
  450. $(this.dom.scroller).on('touchstart.dt-scroller', function () {
  451. that._scroll.call( that );
  452. } );
  453. $(this.dom.scroller)
  454. .on('mousedown.dt-scroller', function () {
  455. that.s.mousedown = true;
  456. })
  457. .on('mouseup.dt-scroller', function () {
  458. that.s.mouseup = false;
  459. that.dom.label.css('display', 'none');
  460. });
  461. // On resize, update the information element, since the number of rows shown might change
  462. $(window).on( 'resize.dt-scroller', function () {
  463. that.measure( false );
  464. that._info();
  465. } );
  466. // Add a state saving parameter to the DT state saving so we can restore the exact
  467. // position of the scrolling. Slightly surprisingly the scroll position isn't actually
  468. // stored, but rather tha base units which are needed to calculate it. This allows for
  469. // virtual scrolling as well.
  470. var initialStateSave = true;
  471. var loadedState = dt.state.loaded();
  472. dt.on( 'stateSaveParams.scroller', function ( e, settings, data ) {
  473. // Need to used the saved position on init
  474. data.scroller = {
  475. topRow: initialStateSave && loadedState && loadedState.scroller ?
  476. loadedState.scroller.topRow :
  477. that.s.topRowFloat,
  478. baseScrollTop: that.s.baseScrollTop,
  479. baseRowTop: that.s.baseRowTop
  480. };
  481. initialStateSave = false;
  482. } );
  483. if ( loadedState && loadedState.scroller ) {
  484. this.s.topRowFloat = loadedState.scroller.topRow;
  485. this.s.baseScrollTop = loadedState.scroller.baseScrollTop;
  486. this.s.baseRowTop = loadedState.scroller.baseRowTop;
  487. }
  488. dt.on( 'init.scroller', function () {
  489. that.measure( false );
  490. that._draw();
  491. // Update the scroller when the DataTable is redrawn
  492. dt.on( 'draw.scroller', function () {
  493. that._draw();
  494. });
  495. } );
  496. // Set height before the draw happens, allowing everything else to update
  497. // on draw complete without worry for roder.
  498. dt.on( 'preDraw.dt.scroller', function () {
  499. that._scrollForce();
  500. } );
  501. // Destructor
  502. dt.on( 'destroy.scroller', function () {
  503. $(window).off( 'resize.dt-scroller' );
  504. $(that.dom.scroller).off('.dt-scroller');
  505. $(that.s.dt.nTable).off( '.scroller' );
  506. $(that.s.dt.nTableWrapper).removeClass('DTS');
  507. $('div.DTS_Loading', that.dom.scroller.parentNode).remove();
  508. that.dom.table.style.position = "";
  509. that.dom.table.style.top = "";
  510. that.dom.table.style.left = "";
  511. } );
  512. },
  513. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  514. * Private methods
  515. */
  516. /**
  517. * Automatic calculation of table row height. This is just a little tricky here as using
  518. * initialisation DataTables has tale the table out of the document, so we need to create
  519. * a new table and insert it into the document, calculate the row height and then whip the
  520. * table out.
  521. * @returns {void}
  522. * @private
  523. */
  524. _calcRowHeight: function ()
  525. {
  526. var dt = this.s.dt;
  527. var origTable = dt.nTable;
  528. var nTable = origTable.cloneNode( false );
  529. var tbody = $('<tbody/>').appendTo( nTable );
  530. var container = $(
  531. '<div class="'+dt.oClasses.sWrapper+' DTS">'+
  532. '<div class="'+dt.oClasses.sScrollWrapper+'">'+
  533. '<div class="'+dt.oClasses.sScrollBody+'"></div>'+
  534. '</div>'+
  535. '</div>'
  536. );
  537. // Want 3 rows in the sizing table so :first-child and :last-child
  538. // CSS styles don't come into play - take the size of the middle row
  539. $('tbody tr:lt(4)', origTable).clone().appendTo( tbody );
  540. var rowsCount = $('tr', tbody).length;
  541. if ( rowsCount === 1 ) {
  542. tbody.prepend('<tr><td>&#160;</td></tr>');
  543. tbody.append('<tr><td>&#160;</td></tr>');
  544. }
  545. else {
  546. for (; rowsCount < 3; rowsCount++) {
  547. tbody.append('<tr><td>&#160;</td></tr>');
  548. }
  549. }
  550. $('div.'+dt.oClasses.sScrollBody, container).append( nTable );
  551. // If initialised using `dom`, use the holding element as the insert point
  552. var insertEl = this.s.dt.nHolding || origTable.parentNode;
  553. if ( ! $(insertEl).is(':visible') ) {
  554. insertEl = 'body';
  555. }
  556. container.appendTo( insertEl );
  557. this.s.heights.row = $('tr', tbody).eq(1).outerHeight();
  558. container.remove();
  559. },
  560. /**
  561. * Draw callback function which is fired when the DataTable is redrawn. The main function of
  562. * this method is to position the drawn table correctly the scrolling container for the rows
  563. * that is displays as a result of the scrolling position.
  564. * @returns {void}
  565. * @private
  566. */
  567. _draw: function ()
  568. {
  569. var
  570. that = this,
  571. heights = this.s.heights,
  572. iScrollTop = this.dom.scroller.scrollTop,
  573. iActualScrollTop = iScrollTop,
  574. iScrollBottom = iScrollTop + heights.viewport,
  575. iTableHeight = $(this.s.dt.nTable).height(),
  576. displayStart = this.s.dt._iDisplayStart,
  577. displayLen = this.s.dt._iDisplayLength,
  578. displayEnd = this.s.dt.fnRecordsDisplay();
  579. // Disable the scroll event listener while we are updating the DOM
  580. this.s.skip = true;
  581. // If paging is reset
  582. if ( (this.s.dt.bSorted || this.s.dt.bFiltered) && displayStart === 0 && !this.s.dt._drawHold ) {
  583. this.s.topRowFloat = 0;
  584. }
  585. iScrollTop = this.scrollType === 'jump' ?
  586. this._domain( 'physicalToVirtual', this.s.topRowFloat * heights.row ) :
  587. iScrollTop;
  588. // This doesn't work when scrolling with the mouse wheel
  589. $(that.dom.scroller).scrollTop(iScrollTop);
  590. // Store positional information so positional calculations can be based
  591. // upon the current table draw position
  592. this.s.baseScrollTop = iScrollTop;
  593. this.s.baseRowTop = this.s.topRowFloat;
  594. // Position the table in the virtual scroller
  595. var tableTop = iScrollTop - ((this.s.topRowFloat - displayStart) * heights.row);
  596. if ( displayStart === 0 ) {
  597. tableTop = 0;
  598. }
  599. else if ( displayStart + displayLen >= displayEnd ) {
  600. tableTop = heights.scroll - iTableHeight;
  601. }
  602. this.dom.table.style.top = tableTop+'px';
  603. /* Cache some information for the scroller */
  604. this.s.tableTop = tableTop;
  605. this.s.tableBottom = iTableHeight + this.s.tableTop;
  606. // Calculate the boundaries for where a redraw will be triggered by the
  607. // scroll event listener
  608. var boundaryPx = (iScrollTop - this.s.tableTop) * this.s.boundaryScale;
  609. this.s.redrawTop = iScrollTop - boundaryPx;
  610. this.s.redrawBottom = iScrollTop + boundaryPx > heights.scroll - heights.viewport - heights.row ?
  611. heights.scroll - heights.viewport - heights.row :
  612. iScrollTop + boundaryPx;
  613. this.s.skip = false;
  614. // Restore the scrolling position that was saved by DataTable's state
  615. // saving Note that this is done on the second draw when data is Ajax
  616. // sourced, and the first draw when DOM soured
  617. if ( this.s.dt.oFeatures.bStateSave && this.s.dt.oLoadedState !== null &&
  618. typeof this.s.dt.oLoadedState.iScroller != 'undefined' )
  619. {
  620. // A quirk of DataTables is that the draw callback will occur on an
  621. // empty set if Ajax sourced, but not if server-side processing.
  622. var ajaxSourced = (this.s.dt.sAjaxSource || that.s.dt.ajax) && ! this.s.dt.oFeatures.bServerSide ?
  623. true :
  624. false;
  625. if ( ( ajaxSourced && this.s.dt.iDraw == 2) ||
  626. (!ajaxSourced && this.s.dt.iDraw == 1) )
  627. {
  628. setTimeout( function () {
  629. $(that.dom.scroller).scrollTop( that.s.dt.oLoadedState.iScroller );
  630. that.s.redrawTop = that.s.dt.oLoadedState.iScroller - (heights.viewport/2);
  631. // In order to prevent layout thrashing we need another
  632. // small delay
  633. setTimeout( function () {
  634. that.s.ingnoreScroll = false;
  635. }, 0 );
  636. }, 0 );
  637. }
  638. }
  639. else {
  640. that.s.ingnoreScroll = false;
  641. }
  642. // Because of the order of the DT callbacks, the info update will
  643. // take precedence over the one we want here. So a 'thread' break is
  644. // needed. Only add the thread break if bInfo is set
  645. if ( this.s.dt.oFeatures.bInfo ) {
  646. setTimeout( function () {
  647. that._info.call( that );
  648. }, 0 );
  649. }
  650. // Hide the loading indicator
  651. if ( this.dom.loader && this.s.loaderVisible ) {
  652. this.dom.loader.css( 'display', 'none' );
  653. this.s.loaderVisible = false;
  654. }
  655. },
  656. /**
  657. * Convert from one domain to another. The physical domain is the actual
  658. * pixel count on the screen, while the virtual is if we had browsers which
  659. * had scrolling containers of infinite height (i.e. the absolute value)
  660. *
  661. * @param {string} dir Domain transform direction, `virtualToPhysical` or
  662. * `physicalToVirtual`
  663. * @returns {number} Calculated transform
  664. * @private
  665. */
  666. _domain: function ( dir, val )
  667. {
  668. var heights = this.s.heights;
  669. var diff;
  670. var magic = 10000; // the point at which the non-linear calculations start to happen
  671. // If the virtual and physical height match, then we use a linear
  672. // transform between the two, allowing the scrollbar to be linear
  673. if ( heights.virtual === heights.scroll ) {
  674. return val;
  675. }
  676. // In the first 10k pixels and the last 10k pixels, we want the scrolling
  677. // to be linear. After that it can be non-linear. It would be unusual for
  678. // anyone to mouse wheel through that much.
  679. if ( val < magic ) {
  680. return val;
  681. }
  682. else if ( dir === 'virtualToPhysical' && val > heights.virtual - magic ) {
  683. diff = heights.virtual - val;
  684. return heights.scroll - diff;
  685. }
  686. else if ( dir === 'physicalToVirtual' && val > heights.scroll - magic ) {
  687. diff = heights.scroll - val;
  688. return heights.virtual - diff;
  689. }
  690. // Otherwise, we want a non-linear scrollbar to take account of the
  691. // redrawing regions at the start and end of the table, otherwise these
  692. // can stutter badly - on large tables 30px (for example) scroll might
  693. // be hundreds of rows, so the table would be redrawing every few px at
  694. // the start and end. Use a simple linear eq. to stop this, effectively
  695. // causing a kink in the scrolling ratio. It does mean the scrollbar is
  696. // non-linear, but with such massive data sets, the scrollbar is going
  697. // to be a best guess anyway
  698. var xMax = dir === 'virtualToPhysical' ?
  699. heights.virtual :
  700. heights.scroll;
  701. var yMax = dir === 'virtualToPhysical' ?
  702. heights.scroll :
  703. heights.virtual;
  704. var m = (yMax - magic) / (xMax - magic);
  705. var c = magic - (m*magic);
  706. return (m*val) + c;
  707. },
  708. /**
  709. * Update any information elements that are controlled by the DataTable based on the scrolling
  710. * viewport and what rows are visible in it. This function basically acts in the same way as
  711. * _fnUpdateInfo in DataTables, and effectively replaces that function.
  712. * @returns {void}
  713. * @private
  714. */
  715. _info: function ()
  716. {
  717. if ( !this.s.dt.oFeatures.bInfo )
  718. {
  719. return;
  720. }
  721. var
  722. dt = this.s.dt,
  723. language = dt.oLanguage,
  724. iScrollTop = this.dom.scroller.scrollTop,
  725. iStart = Math.floor( this.pixelsToRow(iScrollTop, false, this.s.ani)+1 ),
  726. iMax = dt.fnRecordsTotal(),
  727. iTotal = dt.fnRecordsDisplay(),
  728. iPossibleEnd = Math.ceil( this.pixelsToRow(iScrollTop+this.s.heights.viewport, false, this.s.ani) ),
  729. iEnd = iTotal < iPossibleEnd ? iTotal : iPossibleEnd,
  730. sStart = dt.fnFormatNumber( iStart ),
  731. sEnd = dt.fnFormatNumber( iEnd ),
  732. sMax = dt.fnFormatNumber( iMax ),
  733. sTotal = dt.fnFormatNumber( iTotal ),
  734. sOut;
  735. if ( dt.fnRecordsDisplay() === 0 &&
  736. dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
  737. {
  738. /* Empty record set */
  739. sOut = language.sInfoEmpty+ language.sInfoPostFix;
  740. }
  741. else if ( dt.fnRecordsDisplay() === 0 )
  742. {
  743. /* Empty record set after filtering */
  744. sOut = language.sInfoEmpty +' '+
  745. language.sInfoFiltered.replace('_MAX_', sMax)+
  746. language.sInfoPostFix;
  747. }
  748. else if ( dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
  749. {
  750. /* Normal record set */
  751. sOut = language.sInfo.
  752. replace('_START_', sStart).
  753. replace('_END_', sEnd).
  754. replace('_MAX_', sMax).
  755. replace('_TOTAL_', sTotal)+
  756. language.sInfoPostFix;
  757. }
  758. else
  759. {
  760. /* Record set after filtering */
  761. sOut = language.sInfo.
  762. replace('_START_', sStart).
  763. replace('_END_', sEnd).
  764. replace('_MAX_', sMax).
  765. replace('_TOTAL_', sTotal) +' '+
  766. language.sInfoFiltered.replace(
  767. '_MAX_',
  768. dt.fnFormatNumber(dt.fnRecordsTotal())
  769. )+
  770. language.sInfoPostFix;
  771. }
  772. var callback = language.fnInfoCallback;
  773. if ( callback ) {
  774. sOut = callback.call( dt.oInstance,
  775. dt, iStart, iEnd, iMax, iTotal, sOut
  776. );
  777. }
  778. var n = dt.aanFeatures.i;
  779. if ( typeof n != 'undefined' )
  780. {
  781. for ( var i=0, iLen=n.length ; i<iLen ; i++ )
  782. {
  783. $(n[i]).html( sOut );
  784. }
  785. }
  786. // DT doesn't actually (yet) trigger this event, but it will in future
  787. $(dt.nTable).triggerHandler( 'info.dt' );
  788. },
  789. /**
  790. * Parse CSS height property string as number
  791. *
  792. * An attempt is made to parse the string as a number. Currently supported units are 'px',
  793. * 'vh', and 'rem'. 'em' is partially supported; it works as long as the parent element's
  794. * font size matches the body element. Zero is returned for unrecognized strings.
  795. * @param {string} cssHeight CSS height property string
  796. * @returns {number} height
  797. * @private
  798. */
  799. _parseHeight: function(cssHeight) {
  800. var height;
  801. var matches = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(px|em|rem|vh)$/.exec(cssHeight);
  802. if (matches === null) {
  803. return 0;
  804. }
  805. var value = parseFloat(matches[1]);
  806. var unit = matches[2];
  807. if ( unit === 'px' ) {
  808. height = value;
  809. }
  810. else if ( unit === 'vh' ) {
  811. height = ( value / 100 ) * $(window).height();
  812. }
  813. else if ( unit === 'rem' ) {
  814. height = value * parseFloat($(':root').css('font-size'));
  815. }
  816. else if ( unit === 'em' ) {
  817. height = value * parseFloat($('body').css('font-size'));
  818. }
  819. return height ?
  820. height :
  821. 0;
  822. },
  823. /**
  824. * Scrolling function - fired whenever the scrolling position is changed.
  825. * This method needs to use the stored values to see if the table should be
  826. * redrawn as we are moving towards the end of the information that is
  827. * currently drawn or not. If needed, then it will redraw the table based on
  828. * the new position.
  829. * @returns {void}
  830. * @private
  831. */
  832. _scroll: function ()
  833. {
  834. var
  835. that = this,
  836. heights = this.s.heights,
  837. iScrollTop = this.dom.scroller.scrollTop,
  838. iTopRow;
  839. if ( this.s.skip ) {
  840. return;
  841. }
  842. if ( this.s.ingnoreScroll ) {
  843. return;
  844. }
  845. if ( iScrollTop === this.s.lastScrollTop ) {
  846. return;
  847. }
  848. /* If the table has been sorted or filtered, then we use the redraw that
  849. * DataTables as done, rather than performing our own
  850. */
  851. if ( this.s.dt.bFiltered || this.s.dt.bSorted ) {
  852. this.s.lastScrollTop = 0;
  853. return;
  854. }
  855. /* Update the table's information display for what is now in the viewport */
  856. this._info();
  857. /* We don't want to state save on every scroll event - that's heavy
  858. * handed, so use a timeout to update the state saving only when the
  859. * scrolling has finished
  860. */
  861. clearTimeout( this.s.stateTO );
  862. this.s.stateTO = setTimeout( function () {
  863. that.s.dtApi.state.save();
  864. }, 250 );
  865. this.s.scrollType = Math.abs(iScrollTop - this.s.lastScrollTop) > heights.viewport ?
  866. 'jump' :
  867. 'cont';
  868. this.s.topRowFloat = this.s.scrollType === 'cont' ?
  869. this.pixelsToRow( iScrollTop, false, false ) :
  870. this._domain( 'physicalToVirtual', iScrollTop ) / heights.row;
  871. if ( this.s.topRowFloat < 0 ) {
  872. this.s.topRowFloat = 0;
  873. }
  874. /* Check if the scroll point is outside the trigger boundary which would required
  875. * a DataTables redraw
  876. */
  877. if ( this.s.forceReposition || iScrollTop < this.s.redrawTop || iScrollTop > this.s.redrawBottom ) {
  878. var preRows = Math.ceil( ((this.s.displayBuffer-1)/2) * this.s.viewportRows );
  879. iTopRow = parseInt(this.s.topRowFloat, 10) - preRows;
  880. this.s.forceReposition = false;
  881. if ( iTopRow <= 0 ) {
  882. /* At the start of the table */
  883. iTopRow = 0;
  884. }
  885. else if ( iTopRow + this.s.dt._iDisplayLength > this.s.dt.fnRecordsDisplay() ) {
  886. /* At the end of the table */
  887. iTopRow = this.s.dt.fnRecordsDisplay() - this.s.dt._iDisplayLength;
  888. if ( iTopRow < 0 ) {
  889. iTopRow = 0;
  890. }
  891. }
  892. else if ( iTopRow % 2 !== 0 ) {
  893. // For the row-striping classes (odd/even) we want only to start
  894. // on evens otherwise the stripes will change between draws and
  895. // look rubbish
  896. iTopRow++;
  897. }
  898. if ( iTopRow != this.s.dt._iDisplayStart ) {
  899. /* Cache the new table position for quick lookups */
  900. this.s.tableTop = $(this.s.dt.nTable).offset().top;
  901. this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop;
  902. var draw = function () {
  903. if ( that.s.scrollDrawReq === null ) {
  904. that.s.scrollDrawReq = iScrollTop;
  905. }
  906. that.s.dt._iDisplayStart = iTopRow;
  907. that.s.dt.oApi._fnDraw( that.s.dt );
  908. };
  909. /* Do the DataTables redraw based on the calculated start point - note that when
  910. * using server-side processing we introduce a small delay to not DoS the server...
  911. */
  912. if ( this.s.dt.oFeatures.bServerSide ) {
  913. clearTimeout( this.s.drawTO );
  914. this.s.drawTO = setTimeout( draw, this.s.serverWait );
  915. }
  916. else {
  917. draw();
  918. }
  919. if ( this.dom.loader && ! this.s.loaderVisible ) {
  920. this.dom.loader.css( 'display', 'block' );
  921. this.s.loaderVisible = true;
  922. }
  923. }
  924. }
  925. else {
  926. this.s.topRowFloat = this.pixelsToRow( iScrollTop, false, true );
  927. }
  928. this.s.lastScrollTop = iScrollTop;
  929. this.s.stateSaveThrottle();
  930. if ( this.s.scrollType === 'jump' && this.s.mousedown ) {
  931. this.dom.label
  932. .html( this.s.dt.fnFormatNumber( parseInt( this.s.topRowFloat, 10 )+1 ) )
  933. .css( 'top', iScrollTop + (iScrollTop * heights.labelFactor ) )
  934. .css( 'display', 'block' );
  935. }
  936. },
  937. /**
  938. * Force the scrolling container to have height beyond that of just the
  939. * table that has been drawn so the user can scroll the whole data set.
  940. *
  941. * Note that if the calculated required scrolling height exceeds a maximum
  942. * value (1 million pixels - hard-coded) the forcing element will be set
  943. * only to that maximum value and virtual / physical domain transforms will
  944. * be used to allow Scroller to display tables of any number of records.
  945. * @returns {void}
  946. * @private
  947. */
  948. _scrollForce: function ()
  949. {
  950. var heights = this.s.heights;
  951. var max = 1000000;
  952. heights.virtual = heights.row * this.s.dt.fnRecordsDisplay();
  953. heights.scroll = heights.virtual;
  954. if ( heights.scroll > max ) {
  955. heights.scroll = max;
  956. }
  957. // Minimum height so there is always a row visible (the 'no rows found'
  958. // if reduced to zero filtering)
  959. this.dom.force.style.height = heights.scroll > this.s.heights.row ?
  960. heights.scroll+'px' :
  961. this.s.heights.row+'px';
  962. }
  963. } );
  964. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  965. * Statics
  966. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  967. /**
  968. * Scroller default settings for initialisation
  969. * @namespace
  970. * @name Scroller.defaults
  971. * @static
  972. */
  973. Scroller.defaults = {
  974. /**
  975. * Scroller uses the boundary scaling factor to decide when to redraw the table - which it
  976. * typically does before you reach the end of the currently loaded data set (in order to
  977. * allow the data to look continuous to a user scrolling through the data). If given as 0
  978. * then the table will be redrawn whenever the viewport is scrolled, while 1 would not
  979. * redraw the table until the currently loaded data has all been shown. You will want
  980. * something in the middle - the default factor of 0.5 is usually suitable.
  981. * @type float
  982. * @default 0.5
  983. * @static
  984. */
  985. boundaryScale: 0.5,
  986. /**
  987. * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch
  988. * for scrolling. Scroller automatically adjusts DataTables' display length to pre-fetch
  989. * rows that will be shown in "near scrolling" (i.e. just beyond the current display area).
  990. * The value is based upon the number of rows that can be displayed in the viewport (i.e.
  991. * a value of 1), and will apply the display range to records before before and after the
  992. * current viewport - i.e. a factor of 3 will allow Scroller to pre-fetch 1 viewport's worth
  993. * of rows before the current viewport, the current viewport's rows and 1 viewport's worth
  994. * of rows after the current viewport. Adjusting this value can be useful for ensuring
  995. * smooth scrolling based on your data set.
  996. * @type int
  997. * @default 7
  998. * @static
  999. */
  1000. displayBuffer: 9,
  1001. /**
  1002. * Show (or not) the loading element in the background of the table. Note that you should
  1003. * include the dataTables.scroller.css file for this to be displayed correctly.
  1004. * @type boolean
  1005. * @default false
  1006. * @static
  1007. */
  1008. loadingIndicator: false,
  1009. /**
  1010. * Scroller will attempt to automatically calculate the height of rows for it's internal
  1011. * calculations. However the height that is used can be overridden using this parameter.
  1012. * @type int|string
  1013. * @default auto
  1014. * @static
  1015. */
  1016. rowHeight: "auto",
  1017. /**
  1018. * When using server-side processing, Scroller will wait a small amount of time to allow
  1019. * the scrolling to finish before requesting more data from the server. This prevents
  1020. * you from DoSing your own server! The wait time can be configured by this parameter.
  1021. * @type int
  1022. * @default 200
  1023. * @static
  1024. */
  1025. serverWait: 200
  1026. };
  1027. Scroller.oDefaults = Scroller.defaults;
  1028. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1029. * Constants
  1030. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1031. /**
  1032. * Scroller version
  1033. * @type String
  1034. * @default See code
  1035. * @name Scroller.version
  1036. * @static
  1037. */
  1038. Scroller.version = "2.0.0";
  1039. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1040. * Initialisation
  1041. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1042. // Attach a listener to the document which listens for DataTables initialisation
  1043. // events so we can automatically initialise
  1044. $(document).on( 'preInit.dt.dtscroller', function (e, settings) {
  1045. if ( e.namespace !== 'dt' ) {
  1046. return;
  1047. }
  1048. var init = settings.oInit.scroller;
  1049. var defaults = DataTable.defaults.scroller;
  1050. if ( init || defaults ) {
  1051. var opts = $.extend( {}, init, defaults );
  1052. if ( init !== false ) {
  1053. new Scroller( settings, opts );
  1054. }
  1055. }
  1056. } );
  1057. // Attach Scroller to DataTables so it can be accessed as an 'extra'
  1058. $.fn.dataTable.Scroller = Scroller;
  1059. $.fn.DataTable.Scroller = Scroller;
  1060. // DataTables 1.10 API method aliases
  1061. var Api = $.fn.dataTable.Api;
  1062. Api.register( 'scroller()', function () {
  1063. return this;
  1064. } );
  1065. // Undocumented and deprecated - is it actually useful at all?
  1066. Api.register( 'scroller().rowToPixels()', function ( rowIdx, intParse, virtual ) {
  1067. var ctx = this.context;
  1068. if ( ctx.length && ctx[0].oScroller ) {
  1069. return ctx[0].oScroller.rowToPixels( rowIdx, intParse, virtual );
  1070. }
  1071. // undefined
  1072. } );
  1073. // Undocumented and deprecated - is it actually useful at all?
  1074. Api.register( 'scroller().pixelsToRow()', function ( pixels, intParse, virtual ) {
  1075. var ctx = this.context;
  1076. if ( ctx.length && ctx[0].oScroller ) {
  1077. return ctx[0].oScroller.pixelsToRow( pixels, intParse, virtual );
  1078. }
  1079. // undefined
  1080. } );
  1081. // `scroller().scrollToRow()` is undocumented and deprecated. Use `scroller.toPosition()
  1082. Api.register( ['scroller().scrollToRow()', 'scroller.toPosition()'], function ( idx, ani ) {
  1083. this.iterator( 'table', function ( ctx ) {
  1084. if ( ctx.oScroller ) {
  1085. ctx.oScroller.scrollToRow( idx, ani );
  1086. }
  1087. } );
  1088. return this;
  1089. } );
  1090. Api.register( 'row().scrollTo()', function ( ani ) {
  1091. var that = this;
  1092. this.iterator( 'row', function ( ctx, rowIdx ) {
  1093. if ( ctx.oScroller ) {
  1094. var displayIdx = that
  1095. .rows( { order: 'applied', search: 'applied' } )
  1096. .indexes()
  1097. .indexOf( rowIdx );
  1098. ctx.oScroller.scrollToRow( displayIdx, ani );
  1099. }
  1100. } );
  1101. return this;
  1102. } );
  1103. Api.register( 'scroller.measure()', function ( redraw ) {
  1104. this.iterator( 'table', function ( ctx ) {
  1105. if ( ctx.oScroller ) {
  1106. ctx.oScroller.measure( redraw );
  1107. }
  1108. } );
  1109. return this;
  1110. } );
  1111. Api.register( 'scroller.page()', function() {
  1112. var ctx = this.context;
  1113. if ( ctx.length && ctx[0].oScroller ) {
  1114. return ctx[0].oScroller.pageInfo();
  1115. }
  1116. // undefined
  1117. } );
  1118. return Scroller;
  1119. }));