1
0

dataTables.scroller.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. /*! Scroller 2.0.1
  2. * ©2011-2019 SpryMedia Ltd - datatables.net/license
  3. */
  4. /**
  5. * @summary Scroller
  6. * @description Virtual rendering for DataTables
  7. * @version 2.0.1
  8. * @file dataTables.scroller.js
  9. * @author SpryMedia Ltd (www.sprymedia.co.uk)
  10. * @contact www.sprymedia.co.uk/contact
  11. * @copyright Copyright 2011-2019 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 ( 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. }, 250 );
  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. // Setting to `jump` will instruct _draw to calculate the scroll top
  491. // position
  492. that.s.scrollType = 'jump';
  493. that._draw();
  494. // Update the scroller when the DataTable is redrawn
  495. dt.on( 'draw.scroller', function () {
  496. that._draw();
  497. });
  498. } );
  499. // Set height before the draw happens, allowing everything else to update
  500. // on draw complete without worry for roder.
  501. dt.on( 'preDraw.dt.scroller', function () {
  502. that._scrollForce();
  503. } );
  504. // Destructor
  505. dt.on( 'destroy.scroller', function () {
  506. $(window).off( 'resize.dt-scroller' );
  507. $(that.dom.scroller).off('.dt-scroller');
  508. $(that.s.dt.nTable).off( '.scroller' );
  509. $(that.s.dt.nTableWrapper).removeClass('DTS');
  510. $('div.DTS_Loading', that.dom.scroller.parentNode).remove();
  511. that.dom.table.style.position = "";
  512. that.dom.table.style.top = "";
  513. that.dom.table.style.left = "";
  514. } );
  515. },
  516. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  517. * Private methods
  518. */
  519. /**
  520. * Automatic calculation of table row height. This is just a little tricky here as using
  521. * initialisation DataTables has tale the table out of the document, so we need to create
  522. * a new table and insert it into the document, calculate the row height and then whip the
  523. * table out.
  524. * @returns {void}
  525. * @private
  526. */
  527. _calcRowHeight: function ()
  528. {
  529. var dt = this.s.dt;
  530. var origTable = dt.nTable;
  531. var nTable = origTable.cloneNode( false );
  532. var tbody = $('<tbody/>').appendTo( nTable );
  533. var container = $(
  534. '<div class="'+dt.oClasses.sWrapper+' DTS">'+
  535. '<div class="'+dt.oClasses.sScrollWrapper+'">'+
  536. '<div class="'+dt.oClasses.sScrollBody+'"></div>'+
  537. '</div>'+
  538. '</div>'
  539. );
  540. // Want 3 rows in the sizing table so :first-child and :last-child
  541. // CSS styles don't come into play - take the size of the middle row
  542. $('tbody tr:lt(4)', origTable).clone().appendTo( tbody );
  543. var rowsCount = $('tr', tbody).length;
  544. if ( rowsCount === 1 ) {
  545. tbody.prepend('<tr><td>&#160;</td></tr>');
  546. tbody.append('<tr><td>&#160;</td></tr>');
  547. }
  548. else {
  549. for (; rowsCount < 3; rowsCount++) {
  550. tbody.append('<tr><td>&#160;</td></tr>');
  551. }
  552. }
  553. $('div.'+dt.oClasses.sScrollBody, container).append( nTable );
  554. // If initialised using `dom`, use the holding element as the insert point
  555. var insertEl = this.s.dt.nHolding || origTable.parentNode;
  556. if ( ! $(insertEl).is(':visible') ) {
  557. insertEl = 'body';
  558. }
  559. container.appendTo( insertEl );
  560. this.s.heights.row = $('tr', tbody).eq(1).outerHeight();
  561. container.remove();
  562. },
  563. /**
  564. * Draw callback function which is fired when the DataTable is redrawn. The main function of
  565. * this method is to position the drawn table correctly the scrolling container for the rows
  566. * that is displays as a result of the scrolling position.
  567. * @returns {void}
  568. * @private
  569. */
  570. _draw: function ()
  571. {
  572. var
  573. that = this,
  574. heights = this.s.heights,
  575. iScrollTop = this.dom.scroller.scrollTop,
  576. iTableHeight = $(this.s.dt.nTable).height(),
  577. displayStart = this.s.dt._iDisplayStart,
  578. displayLen = this.s.dt._iDisplayLength,
  579. displayEnd = this.s.dt.fnRecordsDisplay();
  580. // Disable the scroll event listener while we are updating the DOM
  581. this.s.skip = true;
  582. // If paging is reset
  583. if ( (this.s.dt.bSorted || this.s.dt.bFiltered) && displayStart === 0 && !this.s.dt._drawHold ) {
  584. this.s.topRowFloat = 0;
  585. }
  586. iScrollTop = this.s.scrollType === 'jump' ?
  587. this._domain( 'virtualToPhysical', this.s.topRowFloat * heights.row ) :
  588. iScrollTop;
  589. // Store positional information so positional calculations can be based
  590. // upon the current table draw position
  591. this.s.baseScrollTop = iScrollTop;
  592. this.s.baseRowTop = this.s.topRowFloat;
  593. // Position the table in the virtual scroller
  594. var tableTop = iScrollTop - ((this.s.topRowFloat - displayStart) * heights.row);
  595. if ( displayStart === 0 ) {
  596. tableTop = 0;
  597. }
  598. else if ( displayStart + displayLen >= displayEnd ) {
  599. tableTop = heights.scroll - iTableHeight;
  600. }
  601. this.dom.table.style.top = tableTop+'px';
  602. /* Cache some information for the scroller */
  603. this.s.tableTop = tableTop;
  604. this.s.tableBottom = iTableHeight + this.s.tableTop;
  605. // Calculate the boundaries for where a redraw will be triggered by the
  606. // scroll event listener
  607. var boundaryPx = (iScrollTop - this.s.tableTop) * this.s.boundaryScale;
  608. this.s.redrawTop = iScrollTop - boundaryPx;
  609. this.s.redrawBottom = iScrollTop + boundaryPx > heights.scroll - heights.viewport - heights.row ?
  610. heights.scroll - heights.viewport - heights.row :
  611. iScrollTop + boundaryPx;
  612. this.s.skip = false;
  613. // Restore the scrolling position that was saved by DataTable's state
  614. // saving Note that this is done on the second draw when data is Ajax
  615. // sourced, and the first draw when DOM soured
  616. if ( this.s.dt.oFeatures.bStateSave && this.s.dt.oLoadedState !== null &&
  617. typeof this.s.dt.oLoadedState.iScroller != 'undefined' )
  618. {
  619. // A quirk of DataTables is that the draw callback will occur on an
  620. // empty set if Ajax sourced, but not if server-side processing.
  621. var ajaxSourced = (this.s.dt.sAjaxSource || that.s.dt.ajax) && ! this.s.dt.oFeatures.bServerSide ?
  622. true :
  623. false;
  624. if ( ( ajaxSourced && this.s.dt.iDraw == 2) ||
  625. (!ajaxSourced && this.s.dt.iDraw == 1) )
  626. {
  627. setTimeout( function () {
  628. $(that.dom.scroller).scrollTop( that.s.dt.oLoadedState.iScroller );
  629. that.s.redrawTop = that.s.dt.oLoadedState.iScroller - (heights.viewport/2);
  630. // In order to prevent layout thrashing we need another
  631. // small delay
  632. setTimeout( function () {
  633. that.s.ingnoreScroll = false;
  634. }, 0 );
  635. }, 0 );
  636. }
  637. }
  638. else {
  639. that.s.ingnoreScroll = false;
  640. }
  641. // Because of the order of the DT callbacks, the info update will
  642. // take precedence over the one we want here. So a 'thread' break is
  643. // needed. Only add the thread break if bInfo is set
  644. if ( this.s.dt.oFeatures.bInfo ) {
  645. setTimeout( function () {
  646. that._info.call( that );
  647. }, 0 );
  648. }
  649. // Hide the loading indicator
  650. if ( this.dom.loader && this.s.loaderVisible ) {
  651. this.dom.loader.css( 'display', 'none' );
  652. this.s.loaderVisible = false;
  653. }
  654. },
  655. /**
  656. * Convert from one domain to another. The physical domain is the actual
  657. * pixel count on the screen, while the virtual is if we had browsers which
  658. * had scrolling containers of infinite height (i.e. the absolute value)
  659. *
  660. * @param {string} dir Domain transform direction, `virtualToPhysical` or
  661. * `physicalToVirtual`
  662. * @returns {number} Calculated transform
  663. * @private
  664. */
  665. _domain: function ( dir, val )
  666. {
  667. var heights = this.s.heights;
  668. var diff;
  669. var magic = 10000; // the point at which the non-linear calculations start to happen
  670. // If the virtual and physical height match, then we use a linear
  671. // transform between the two, allowing the scrollbar to be linear
  672. if ( heights.virtual === heights.scroll ) {
  673. return val;
  674. }
  675. // In the first 10k pixels and the last 10k pixels, we want the scrolling
  676. // to be linear. After that it can be non-linear. It would be unusual for
  677. // anyone to mouse wheel through that much.
  678. if ( val < magic ) {
  679. return val;
  680. }
  681. else if ( dir === 'virtualToPhysical' && val >= heights.virtual - magic ) {
  682. diff = heights.virtual - val;
  683. return heights.scroll - diff;
  684. }
  685. else if ( dir === 'physicalToVirtual' && val >= heights.scroll - magic ) {
  686. diff = heights.scroll - val;
  687. return heights.virtual - diff;
  688. }
  689. // Otherwise, we want a non-linear scrollbar to take account of the
  690. // redrawing regions at the start and end of the table, otherwise these
  691. // can stutter badly - on large tables 30px (for example) scroll might
  692. // be hundreds of rows, so the table would be redrawing every few px at
  693. // the start and end. Use a simple linear eq. to stop this, effectively
  694. // causing a kink in the scrolling ratio. It does mean the scrollbar is
  695. // non-linear, but with such massive data sets, the scrollbar is going
  696. // to be a best guess anyway
  697. var m = (heights.virtual - magic - magic) / (heights.scroll - magic - magic);
  698. var c = magic - (m*magic);
  699. return dir === 'virtualToPhysical' ?
  700. (val-c) / m :
  701. (m*val) + c;
  702. },
  703. /**
  704. * Update any information elements that are controlled by the DataTable based on the scrolling
  705. * viewport and what rows are visible in it. This function basically acts in the same way as
  706. * _fnUpdateInfo in DataTables, and effectively replaces that function.
  707. * @returns {void}
  708. * @private
  709. */
  710. _info: function ()
  711. {
  712. if ( !this.s.dt.oFeatures.bInfo )
  713. {
  714. return;
  715. }
  716. var
  717. dt = this.s.dt,
  718. language = dt.oLanguage,
  719. iScrollTop = this.dom.scroller.scrollTop,
  720. iStart = Math.floor( this.pixelsToRow(iScrollTop, false, this.s.ani)+1 ),
  721. iMax = dt.fnRecordsTotal(),
  722. iTotal = dt.fnRecordsDisplay(),
  723. iPossibleEnd = Math.ceil( this.pixelsToRow(iScrollTop+this.s.heights.viewport, false, this.s.ani) ),
  724. iEnd = iTotal < iPossibleEnd ? iTotal : iPossibleEnd,
  725. sStart = dt.fnFormatNumber( iStart ),
  726. sEnd = dt.fnFormatNumber( iEnd ),
  727. sMax = dt.fnFormatNumber( iMax ),
  728. sTotal = dt.fnFormatNumber( iTotal ),
  729. sOut;
  730. if ( dt.fnRecordsDisplay() === 0 &&
  731. dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
  732. {
  733. /* Empty record set */
  734. sOut = language.sInfoEmpty+ language.sInfoPostFix;
  735. }
  736. else if ( dt.fnRecordsDisplay() === 0 )
  737. {
  738. /* Empty record set after filtering */
  739. sOut = language.sInfoEmpty +' '+
  740. language.sInfoFiltered.replace('_MAX_', sMax)+
  741. language.sInfoPostFix;
  742. }
  743. else if ( dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
  744. {
  745. /* Normal record set */
  746. sOut = language.sInfo.
  747. replace('_START_', sStart).
  748. replace('_END_', sEnd).
  749. replace('_MAX_', sMax).
  750. replace('_TOTAL_', sTotal)+
  751. language.sInfoPostFix;
  752. }
  753. else
  754. {
  755. /* Record set after filtering */
  756. sOut = language.sInfo.
  757. replace('_START_', sStart).
  758. replace('_END_', sEnd).
  759. replace('_MAX_', sMax).
  760. replace('_TOTAL_', sTotal) +' '+
  761. language.sInfoFiltered.replace(
  762. '_MAX_',
  763. dt.fnFormatNumber(dt.fnRecordsTotal())
  764. )+
  765. language.sInfoPostFix;
  766. }
  767. var callback = language.fnInfoCallback;
  768. if ( callback ) {
  769. sOut = callback.call( dt.oInstance,
  770. dt, iStart, iEnd, iMax, iTotal, sOut
  771. );
  772. }
  773. var n = dt.aanFeatures.i;
  774. if ( typeof n != 'undefined' )
  775. {
  776. for ( var i=0, iLen=n.length ; i<iLen ; i++ )
  777. {
  778. $(n[i]).html( sOut );
  779. }
  780. }
  781. // DT doesn't actually (yet) trigger this event, but it will in future
  782. $(dt.nTable).triggerHandler( 'info.dt' );
  783. },
  784. /**
  785. * Parse CSS height property string as number
  786. *
  787. * An attempt is made to parse the string as a number. Currently supported units are 'px',
  788. * 'vh', and 'rem'. 'em' is partially supported; it works as long as the parent element's
  789. * font size matches the body element. Zero is returned for unrecognized strings.
  790. * @param {string} cssHeight CSS height property string
  791. * @returns {number} height
  792. * @private
  793. */
  794. _parseHeight: function(cssHeight) {
  795. var height;
  796. var matches = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(px|em|rem|vh)$/.exec(cssHeight);
  797. if (matches === null) {
  798. return 0;
  799. }
  800. var value = parseFloat(matches[1]);
  801. var unit = matches[2];
  802. if ( unit === 'px' ) {
  803. height = value;
  804. }
  805. else if ( unit === 'vh' ) {
  806. height = ( value / 100 ) * $(window).height();
  807. }
  808. else if ( unit === 'rem' ) {
  809. height = value * parseFloat($(':root').css('font-size'));
  810. }
  811. else if ( unit === 'em' ) {
  812. height = value * parseFloat($('body').css('font-size'));
  813. }
  814. return height ?
  815. height :
  816. 0;
  817. },
  818. /**
  819. * Scrolling function - fired whenever the scrolling position is changed.
  820. * This method needs to use the stored values to see if the table should be
  821. * redrawn as we are moving towards the end of the information that is
  822. * currently drawn or not. If needed, then it will redraw the table based on
  823. * the new position.
  824. * @returns {void}
  825. * @private
  826. */
  827. _scroll: function ()
  828. {
  829. var
  830. that = this,
  831. heights = this.s.heights,
  832. iScrollTop = this.dom.scroller.scrollTop,
  833. iTopRow;
  834. if ( this.s.skip ) {
  835. return;
  836. }
  837. if ( this.s.ingnoreScroll ) {
  838. return;
  839. }
  840. if ( iScrollTop === this.s.lastScrollTop ) {
  841. return;
  842. }
  843. /* If the table has been sorted or filtered, then we use the redraw that
  844. * DataTables as done, rather than performing our own
  845. */
  846. if ( this.s.dt.bFiltered || this.s.dt.bSorted ) {
  847. this.s.lastScrollTop = 0;
  848. return;
  849. }
  850. /* Update the table's information display for what is now in the viewport */
  851. this._info();
  852. /* We don't want to state save on every scroll event - that's heavy
  853. * handed, so use a timeout to update the state saving only when the
  854. * scrolling has finished
  855. */
  856. clearTimeout( this.s.stateTO );
  857. this.s.stateTO = setTimeout( function () {
  858. that.s.dtApi.state.save();
  859. }, 250 );
  860. this.s.scrollType = Math.abs(iScrollTop - this.s.lastScrollTop) > heights.viewport ?
  861. 'jump' :
  862. 'cont';
  863. this.s.topRowFloat = this.s.scrollType === 'cont' ?
  864. this.pixelsToRow( iScrollTop, false, false ) :
  865. this._domain( 'physicalToVirtual', iScrollTop ) / heights.row;
  866. if ( this.s.topRowFloat < 0 ) {
  867. this.s.topRowFloat = 0;
  868. }
  869. /* Check if the scroll point is outside the trigger boundary which would required
  870. * a DataTables redraw
  871. */
  872. if ( this.s.forceReposition || iScrollTop < this.s.redrawTop || iScrollTop > this.s.redrawBottom ) {
  873. var preRows = Math.ceil( ((this.s.displayBuffer-1)/2) * this.s.viewportRows );
  874. iTopRow = parseInt(this.s.topRowFloat, 10) - preRows;
  875. this.s.forceReposition = false;
  876. if ( iTopRow <= 0 ) {
  877. /* At the start of the table */
  878. iTopRow = 0;
  879. }
  880. else if ( iTopRow + this.s.dt._iDisplayLength > this.s.dt.fnRecordsDisplay() ) {
  881. /* At the end of the table */
  882. iTopRow = this.s.dt.fnRecordsDisplay() - this.s.dt._iDisplayLength;
  883. if ( iTopRow < 0 ) {
  884. iTopRow = 0;
  885. }
  886. }
  887. else if ( iTopRow % 2 !== 0 ) {
  888. // For the row-striping classes (odd/even) we want only to start
  889. // on evens otherwise the stripes will change between draws and
  890. // look rubbish
  891. iTopRow++;
  892. }
  893. if ( iTopRow != this.s.dt._iDisplayStart ) {
  894. /* Cache the new table position for quick lookups */
  895. this.s.tableTop = $(this.s.dt.nTable).offset().top;
  896. this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop;
  897. var draw = function () {
  898. if ( that.s.scrollDrawReq === null ) {
  899. that.s.scrollDrawReq = iScrollTop;
  900. }
  901. that.s.dt._iDisplayStart = iTopRow;
  902. that.s.dt.oApi._fnDraw( that.s.dt );
  903. };
  904. /* Do the DataTables redraw based on the calculated start point - note that when
  905. * using server-side processing we introduce a small delay to not DoS the server...
  906. */
  907. if ( this.s.dt.oFeatures.bServerSide ) {
  908. clearTimeout( this.s.drawTO );
  909. this.s.drawTO = setTimeout( draw, this.s.serverWait );
  910. }
  911. else {
  912. draw();
  913. }
  914. if ( this.dom.loader && ! this.s.loaderVisible ) {
  915. this.dom.loader.css( 'display', 'block' );
  916. this.s.loaderVisible = true;
  917. }
  918. }
  919. }
  920. else {
  921. this.s.topRowFloat = this.pixelsToRow( iScrollTop, false, true );
  922. }
  923. this.s.lastScrollTop = iScrollTop;
  924. this.s.stateSaveThrottle();
  925. if ( this.s.scrollType === 'jump' && this.s.mousedown ) {
  926. this.dom.label
  927. .html( this.s.dt.fnFormatNumber( parseInt( this.s.topRowFloat, 10 )+1 ) )
  928. .css( 'top', iScrollTop + (iScrollTop * heights.labelFactor ) )
  929. .css( 'display', 'block' );
  930. }
  931. },
  932. /**
  933. * Force the scrolling container to have height beyond that of just the
  934. * table that has been drawn so the user can scroll the whole data set.
  935. *
  936. * Note that if the calculated required scrolling height exceeds a maximum
  937. * value (1 million pixels - hard-coded) the forcing element will be set
  938. * only to that maximum value and virtual / physical domain transforms will
  939. * be used to allow Scroller to display tables of any number of records.
  940. * @returns {void}
  941. * @private
  942. */
  943. _scrollForce: function ()
  944. {
  945. var heights = this.s.heights;
  946. var max = 1000000;
  947. heights.virtual = heights.row * this.s.dt.fnRecordsDisplay();
  948. heights.scroll = heights.virtual;
  949. if ( heights.scroll > max ) {
  950. heights.scroll = max;
  951. }
  952. // Minimum height so there is always a row visible (the 'no rows found'
  953. // if reduced to zero filtering)
  954. this.dom.force.style.height = heights.scroll > this.s.heights.row ?
  955. heights.scroll+'px' :
  956. this.s.heights.row+'px';
  957. }
  958. } );
  959. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  960. * Statics
  961. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  962. /**
  963. * Scroller default settings for initialisation
  964. * @namespace
  965. * @name Scroller.defaults
  966. * @static
  967. */
  968. Scroller.defaults = {
  969. /**
  970. * Scroller uses the boundary scaling factor to decide when to redraw the table - which it
  971. * typically does before you reach the end of the currently loaded data set (in order to
  972. * allow the data to look continuous to a user scrolling through the data). If given as 0
  973. * then the table will be redrawn whenever the viewport is scrolled, while 1 would not
  974. * redraw the table until the currently loaded data has all been shown. You will want
  975. * something in the middle - the default factor of 0.5 is usually suitable.
  976. * @type float
  977. * @default 0.5
  978. * @static
  979. */
  980. boundaryScale: 0.5,
  981. /**
  982. * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch
  983. * for scrolling. Scroller automatically adjusts DataTables' display length to pre-fetch
  984. * rows that will be shown in "near scrolling" (i.e. just beyond the current display area).
  985. * The value is based upon the number of rows that can be displayed in the viewport (i.e.
  986. * a value of 1), and will apply the display range to records before before and after the
  987. * current viewport - i.e. a factor of 3 will allow Scroller to pre-fetch 1 viewport's worth
  988. * of rows before the current viewport, the current viewport's rows and 1 viewport's worth
  989. * of rows after the current viewport. Adjusting this value can be useful for ensuring
  990. * smooth scrolling based on your data set.
  991. * @type int
  992. * @default 7
  993. * @static
  994. */
  995. displayBuffer: 9,
  996. /**
  997. * Show (or not) the loading element in the background of the table. Note that you should
  998. * include the dataTables.scroller.css file for this to be displayed correctly.
  999. * @type boolean
  1000. * @default false
  1001. * @static
  1002. */
  1003. loadingIndicator: false,
  1004. /**
  1005. * Scroller will attempt to automatically calculate the height of rows for it's internal
  1006. * calculations. However the height that is used can be overridden using this parameter.
  1007. * @type int|string
  1008. * @default auto
  1009. * @static
  1010. */
  1011. rowHeight: "auto",
  1012. /**
  1013. * When using server-side processing, Scroller will wait a small amount of time to allow
  1014. * the scrolling to finish before requesting more data from the server. This prevents
  1015. * you from DoSing your own server! The wait time can be configured by this parameter.
  1016. * @type int
  1017. * @default 200
  1018. * @static
  1019. */
  1020. serverWait: 200
  1021. };
  1022. Scroller.oDefaults = Scroller.defaults;
  1023. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1024. * Constants
  1025. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1026. /**
  1027. * Scroller version
  1028. * @type String
  1029. * @default See code
  1030. * @name Scroller.version
  1031. * @static
  1032. */
  1033. Scroller.version = "2.0.1";
  1034. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1035. * Initialisation
  1036. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1037. // Attach a listener to the document which listens for DataTables initialisation
  1038. // events so we can automatically initialise
  1039. $(document).on( 'preInit.dt.dtscroller', function (e, settings) {
  1040. if ( e.namespace !== 'dt' ) {
  1041. return;
  1042. }
  1043. var init = settings.oInit.scroller;
  1044. var defaults = DataTable.defaults.scroller;
  1045. if ( init || defaults ) {
  1046. var opts = $.extend( {}, init, defaults );
  1047. if ( init !== false ) {
  1048. new Scroller( settings, opts );
  1049. }
  1050. }
  1051. } );
  1052. // Attach Scroller to DataTables so it can be accessed as an 'extra'
  1053. $.fn.dataTable.Scroller = Scroller;
  1054. $.fn.DataTable.Scroller = Scroller;
  1055. // DataTables 1.10 API method aliases
  1056. var Api = $.fn.dataTable.Api;
  1057. Api.register( 'scroller()', function () {
  1058. return this;
  1059. } );
  1060. // Undocumented and deprecated - is it actually useful at all?
  1061. Api.register( 'scroller().rowToPixels()', function ( rowIdx, intParse, virtual ) {
  1062. var ctx = this.context;
  1063. if ( ctx.length && ctx[0].oScroller ) {
  1064. return ctx[0].oScroller.rowToPixels( rowIdx, intParse, virtual );
  1065. }
  1066. // undefined
  1067. } );
  1068. // Undocumented and deprecated - is it actually useful at all?
  1069. Api.register( 'scroller().pixelsToRow()', function ( pixels, intParse, virtual ) {
  1070. var ctx = this.context;
  1071. if ( ctx.length && ctx[0].oScroller ) {
  1072. return ctx[0].oScroller.pixelsToRow( pixels, intParse, virtual );
  1073. }
  1074. // undefined
  1075. } );
  1076. // `scroller().scrollToRow()` is undocumented and deprecated. Use `scroller.toPosition()
  1077. Api.register( ['scroller().scrollToRow()', 'scroller.toPosition()'], function ( idx, ani ) {
  1078. this.iterator( 'table', function ( ctx ) {
  1079. if ( ctx.oScroller ) {
  1080. ctx.oScroller.scrollToRow( idx, ani );
  1081. }
  1082. } );
  1083. return this;
  1084. } );
  1085. Api.register( 'row().scrollTo()', function ( ani ) {
  1086. var that = this;
  1087. this.iterator( 'row', function ( ctx, rowIdx ) {
  1088. if ( ctx.oScroller ) {
  1089. var displayIdx = that
  1090. .rows( { order: 'applied', search: 'applied' } )
  1091. .indexes()
  1092. .indexOf( rowIdx );
  1093. ctx.oScroller.scrollToRow( displayIdx, ani );
  1094. }
  1095. } );
  1096. return this;
  1097. } );
  1098. Api.register( 'scroller.measure()', function ( redraw ) {
  1099. this.iterator( 'table', function ( ctx ) {
  1100. if ( ctx.oScroller ) {
  1101. ctx.oScroller.measure( redraw );
  1102. }
  1103. } );
  1104. return this;
  1105. } );
  1106. Api.register( 'scroller.page()', function() {
  1107. var ctx = this.context;
  1108. if ( ctx.length && ctx[0].oScroller ) {
  1109. return ctx[0].oScroller.pageInfo();
  1110. }
  1111. // undefined
  1112. } );
  1113. return Scroller;
  1114. }));