dataTables.scroller.js 38 KB

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