25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

dataTables.scroller.js 38KB

2 yıl önce
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. /*! Scroller 2.0.5
  2. * ©2011-2021 SpryMedia Ltd - datatables.net/license
  3. */
  4. /**
  5. * @summary Scroller
  6. * @description Virtual rendering for DataTables
  7. * @version 2.0.5
  8. * @file dataTables.scroller.js
  9. * @author SpryMedia Ltd (www.sprymedia.co.uk)
  10. * @contact www.sprymedia.co.uk/contact
  11. * @copyright Copyright 2011-2021 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 Scroller. 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. labelHeight: 0,
  198. xbar: 0
  199. },
  200. topRowFloat: 0,
  201. scrollDrawDiff: null,
  202. loaderVisible: false,
  203. forceReposition: false,
  204. baseRowTop: 0,
  205. baseScrollTop: 0,
  206. mousedown: false,
  207. lastScrollTop: 0
  208. };
  209. // @todo The defaults should extend a `c` property and the internal settings
  210. // only held in the `s` property. At the moment they are mixed
  211. this.s = $.extend( this.s, Scroller.oDefaults, opts );
  212. // Workaround for row height being read from height object (see above comment)
  213. this.s.heights.row = this.s.rowHeight;
  214. /**
  215. * DOM elements used by the class instance
  216. * @private
  217. * @namespace
  218. *
  219. */
  220. this.dom = {
  221. "force": document.createElement('div'),
  222. "label": $('<div class="dts_label">0</div>'),
  223. "scroller": null,
  224. "table": null,
  225. "loader": null
  226. };
  227. // Attach the instance to the DataTables instance so it can be accessed in
  228. // future. Don't initialise Scroller twice on the same table
  229. if ( this.s.dt.oScroller ) {
  230. return;
  231. }
  232. this.s.dt.oScroller = this;
  233. /* Let's do it */
  234. this.construct();
  235. };
  236. $.extend( Scroller.prototype, {
  237. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  238. * Public methods - to be exposed via the DataTables API
  239. */
  240. /**
  241. * Calculate and store information about how many rows are to be displayed
  242. * in the scrolling viewport, based on current dimensions in the browser's
  243. * rendering. This can be particularly useful if the table is initially
  244. * drawn in a hidden element - for example in a tab.
  245. * @param {bool} [redraw=true] Redraw the table automatically after the recalculation, with
  246. * the new dimensions forming the basis for the draw.
  247. * @returns {void}
  248. */
  249. measure: function ( redraw )
  250. {
  251. if ( this.s.autoHeight )
  252. {
  253. this._calcRowHeight();
  254. }
  255. var heights = this.s.heights;
  256. if ( heights.row ) {
  257. heights.viewport = this._parseHeight($(this.dom.scroller).css('max-height'));
  258. this.s.viewportRows = parseInt( heights.viewport / heights.row, 10 )+1;
  259. this.s.dt._iDisplayLength = this.s.viewportRows * this.s.displayBuffer;
  260. }
  261. var label = this.dom.label.outerHeight();
  262. heights.xbar = this.dom.scroller.offsetHeight - this.dom.scroller.clientHeight;
  263. heights.labelHeight = label;
  264. if ( redraw === undefined || redraw )
  265. {
  266. this.s.dt.oInstance.fnDraw( false );
  267. }
  268. },
  269. /**
  270. * Get information about current displayed record range. This corresponds to
  271. * the information usually displayed in the "Info" block of the table.
  272. *
  273. * @returns {object} info as an object:
  274. * {
  275. * start: {int}, // the 0-indexed record at the top of the viewport
  276. * end: {int}, // the 0-indexed record at the bottom of the viewport
  277. * }
  278. */
  279. pageInfo: function()
  280. {
  281. var
  282. dt = this.s.dt,
  283. iScrollTop = this.dom.scroller.scrollTop,
  284. iTotal = dt.fnRecordsDisplay(),
  285. iPossibleEnd = Math.ceil(this.pixelsToRow(iScrollTop + this.s.heights.viewport, false, this.s.ani));
  286. return {
  287. start: Math.floor(this.pixelsToRow(iScrollTop, false, this.s.ani)),
  288. end: iTotal < iPossibleEnd ? iTotal-1 : iPossibleEnd-1
  289. };
  290. },
  291. /**
  292. * Calculate the row number that will be found at the given pixel position
  293. * (y-scroll).
  294. *
  295. * Please note that when the height of the full table exceeds 1 million
  296. * pixels, Scroller switches into a non-linear mode for the scrollbar to fit
  297. * all of the records into a finite area, but this function returns a linear
  298. * value (relative to the last non-linear positioning).
  299. * @param {int} pixels Offset from top to calculate the row number of
  300. * @param {int} [intParse=true] If an integer value should be returned
  301. * @param {int} [virtual=false] Perform the calculations in the virtual domain
  302. * @returns {int} Row index
  303. */
  304. pixelsToRow: function ( pixels, intParse, virtual )
  305. {
  306. var diff = pixels - this.s.baseScrollTop;
  307. var row = virtual ?
  308. (this._domain( 'physicalToVirtual', this.s.baseScrollTop ) + diff) / this.s.heights.row :
  309. ( diff / this.s.heights.row ) + this.s.baseRowTop;
  310. return intParse || intParse === undefined ?
  311. parseInt( row, 10 ) :
  312. row;
  313. },
  314. /**
  315. * Calculate the pixel position from the top of the scrolling container for
  316. * a given row
  317. * @param {int} iRow Row number to calculate the position of
  318. * @returns {int} Pixels
  319. */
  320. rowToPixels: function ( rowIdx, intParse, virtual )
  321. {
  322. var pixels;
  323. var diff = rowIdx - this.s.baseRowTop;
  324. if ( virtual ) {
  325. pixels = this._domain( 'virtualToPhysical', this.s.baseScrollTop );
  326. pixels += diff * this.s.heights.row;
  327. }
  328. else {
  329. pixels = this.s.baseScrollTop;
  330. pixels += diff * this.s.heights.row;
  331. }
  332. return intParse || intParse === undefined ?
  333. parseInt( pixels, 10 ) :
  334. pixels;
  335. },
  336. /**
  337. * Calculate the row number that will be found at the given pixel position (y-scroll)
  338. * @param {int} row Row index to scroll to
  339. * @param {bool} [animate=true] Animate the transition or not
  340. * @returns {void}
  341. */
  342. scrollToRow: function ( row, animate )
  343. {
  344. var that = this;
  345. var ani = false;
  346. var px = this.rowToPixels( row );
  347. // We need to know if the table will redraw or not before doing the
  348. // scroll. If it will not redraw, then we need to use the currently
  349. // displayed table, and scroll with the physical pixels. Otherwise, we
  350. // need to calculate the table's new position from the virtual
  351. // transform.
  352. var preRows = ((this.s.displayBuffer-1)/2) * this.s.viewportRows;
  353. var drawRow = row - preRows;
  354. if ( drawRow < 0 ) {
  355. drawRow = 0;
  356. }
  357. if ( (px > this.s.redrawBottom || px < this.s.redrawTop) && this.s.dt._iDisplayStart !== drawRow ) {
  358. ani = true;
  359. px = this._domain( 'virtualToPhysical', row * this.s.heights.row );
  360. // If we need records outside the current draw region, but the new
  361. // scrolling position is inside that (due to the non-linear nature
  362. // for larger numbers of records), we need to force position update.
  363. if ( this.s.redrawTop < px && px < this.s.redrawBottom ) {
  364. this.s.forceReposition = true;
  365. animate = false;
  366. }
  367. }
  368. if ( animate === undefined || animate )
  369. {
  370. this.s.ani = ani;
  371. $(this.dom.scroller).animate( {
  372. "scrollTop": px
  373. }, function () {
  374. // This needs to happen after the animation has completed and
  375. // the final scroll event fired
  376. setTimeout( function () {
  377. that.s.ani = false;
  378. }, 250 );
  379. } );
  380. }
  381. else
  382. {
  383. $(this.dom.scroller).scrollTop( px );
  384. }
  385. },
  386. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  387. * Constructor
  388. */
  389. /**
  390. * Initialisation for Scroller
  391. * @returns {void}
  392. * @private
  393. */
  394. construct: function ()
  395. {
  396. var that = this;
  397. var dt = this.s.dtApi;
  398. /* Sanity check */
  399. if ( !this.s.dt.oFeatures.bPaginate ) {
  400. this.s.dt.oApi._fnLog( this.s.dt, 0, 'Pagination must be enabled for Scroller' );
  401. return;
  402. }
  403. /* Insert a div element that we can use to force the DT scrolling container to
  404. * the height that would be required if the whole table was being displayed
  405. */
  406. this.dom.force.style.position = "relative";
  407. this.dom.force.style.top = "0px";
  408. this.dom.force.style.left = "0px";
  409. this.dom.force.style.width = "1px";
  410. this.dom.scroller = $('div.'+this.s.dt.oClasses.sScrollBody, this.s.dt.nTableWrapper)[0];
  411. this.dom.scroller.appendChild( this.dom.force );
  412. this.dom.scroller.style.position = "relative";
  413. this.dom.table = $('>table', this.dom.scroller)[0];
  414. this.dom.table.style.position = "absolute";
  415. this.dom.table.style.top = "0px";
  416. this.dom.table.style.left = "0px";
  417. // Add class to 'announce' that we are a Scroller table
  418. $(dt.table().container()).addClass('dts DTS');
  419. // Add a 'loading' indicator
  420. if ( this.s.loadingIndicator )
  421. {
  422. this.dom.loader = $('<div class="dataTables_processing dts_loading">'+this.s.dt.oLanguage.sLoadingRecords+'</div>')
  423. .css('display', 'none');
  424. $(this.dom.scroller.parentNode)
  425. .css('position', 'relative')
  426. .append( this.dom.loader );
  427. }
  428. this.dom.label.appendTo(this.dom.scroller);
  429. /* Initial size calculations */
  430. if ( this.s.heights.row && this.s.heights.row != 'auto' )
  431. {
  432. this.s.autoHeight = false;
  433. }
  434. // Scrolling callback to see if a page change is needed
  435. this.s.ingnoreScroll = true;
  436. $(this.dom.scroller).on( 'scroll.dt-scroller', function (e) {
  437. that._scroll.call( that );
  438. } );
  439. // In iOS we catch the touchstart event in case the user tries to scroll
  440. // while the display is already scrolling
  441. $(this.dom.scroller).on('touchstart.dt-scroller', function () {
  442. that._scroll.call( that );
  443. } );
  444. $(this.dom.scroller)
  445. .on('mousedown.dt-scroller', function () {
  446. that.s.mousedown = true;
  447. })
  448. .on('mouseup.dt-scroller', function () {
  449. that.s.labelVisible = false;
  450. that.s.mousedown = false;
  451. that.dom.label.css('display', 'none');
  452. });
  453. // On resize, update the information element, since the number of rows shown might change
  454. $(window).on( 'resize.dt-scroller', function () {
  455. that.measure( false );
  456. that._info();
  457. } );
  458. // Add a state saving parameter to the DT state saving so we can restore the exact
  459. // position of the scrolling.
  460. var initialStateSave = true;
  461. var loadedState = dt.state.loaded();
  462. dt.on( 'stateSaveParams.scroller', function ( e, settings, data ) {
  463. if ( initialStateSave && loadedState ) {
  464. data.scroller = loadedState.scroller;
  465. initialStateSave = false;
  466. }
  467. else {
  468. // Need to used the saved position on init
  469. data.scroller = {
  470. topRow: that.s.topRowFloat,
  471. baseScrollTop: that.s.baseScrollTop,
  472. baseRowTop: that.s.baseRowTop,
  473. scrollTop: that.s.lastScrollTop
  474. };
  475. }
  476. } );
  477. if ( loadedState && loadedState.scroller ) {
  478. this.s.topRowFloat = loadedState.scroller.topRow;
  479. this.s.baseScrollTop = loadedState.scroller.baseScrollTop;
  480. this.s.baseRowTop = loadedState.scroller.baseRowTop;
  481. }
  482. this.measure( false );
  483. that.s.stateSaveThrottle = that.s.dt.oApi._fnThrottle( function () {
  484. that.s.dtApi.state.save();
  485. }, 500 );
  486. dt.on( 'init.scroller', function () {
  487. that.measure( false );
  488. // Setting to `jump` will instruct _draw to calculate the scroll top
  489. // position
  490. that.s.scrollType = 'jump';
  491. that._draw();
  492. // Update the scroller when the DataTable is redrawn
  493. dt.on( 'draw.scroller', function () {
  494. that._draw();
  495. });
  496. } );
  497. // Set height before the draw happens, allowing everything else to update
  498. // on draw complete without worry for roder.
  499. dt.on( 'preDraw.dt.scroller', function () {
  500. that._scrollForce();
  501. } );
  502. // Destructor
  503. dt.on( 'destroy.scroller', function () {
  504. $(window).off( 'resize.dt-scroller' );
  505. $(that.dom.scroller).off('.dt-scroller');
  506. $(that.s.dt.nTable).off( '.scroller' );
  507. $(that.s.dt.nTableWrapper).removeClass('DTS');
  508. $('div.DTS_Loading', that.dom.scroller.parentNode).remove();
  509. that.dom.table.style.position = "";
  510. that.dom.table.style.top = "";
  511. that.dom.table.style.left = "";
  512. } );
  513. },
  514. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  515. * Private methods
  516. */
  517. /**
  518. * Automatic calculation of table row height. This is just a little tricky here as using
  519. * initialisation DataTables has tale the table out of the document, so we need to create
  520. * a new table and insert it into the document, calculate the row height and then whip the
  521. * table out.
  522. * @returns {void}
  523. * @private
  524. */
  525. _calcRowHeight: function ()
  526. {
  527. var dt = this.s.dt;
  528. var origTable = dt.nTable;
  529. var nTable = origTable.cloneNode( false );
  530. var tbody = $('<tbody/>').appendTo( nTable );
  531. var container = $(
  532. '<div class="'+dt.oClasses.sWrapper+' DTS">'+
  533. '<div class="'+dt.oClasses.sScrollWrapper+'">'+
  534. '<div class="'+dt.oClasses.sScrollBody+'"></div>'+
  535. '</div>'+
  536. '</div>'
  537. );
  538. // Want 3 rows in the sizing table so :first-child and :last-child
  539. // CSS styles don't come into play - take the size of the middle row
  540. $('tbody tr:lt(4)', origTable).clone().appendTo( tbody );
  541. var rowsCount = $('tr', tbody).length;
  542. if ( rowsCount === 1 ) {
  543. tbody.prepend('<tr><td>&#160;</td></tr>');
  544. tbody.append('<tr><td>&#160;</td></tr>');
  545. }
  546. else {
  547. for (; rowsCount < 3; rowsCount++) {
  548. tbody.append('<tr><td>&#160;</td></tr>');
  549. }
  550. }
  551. $('div.'+dt.oClasses.sScrollBody, container).append( nTable );
  552. // If initialised using `dom`, use the holding element as the insert point
  553. var insertEl = this.s.dt.nHolding || origTable.parentNode;
  554. if ( ! $(insertEl).is(':visible') ) {
  555. insertEl = 'body';
  556. }
  557. // Remove form element links as they might select over others (particularly radio and checkboxes)
  558. container.find("input").removeAttr("name");
  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.scroller != '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.scroller.scrollTop );
  629. // In order to prevent layout thrashing we need another
  630. // small delay
  631. setTimeout( function () {
  632. that.s.ingnoreScroll = false;
  633. }, 0 );
  634. }, 0 );
  635. }
  636. }
  637. else {
  638. that.s.ingnoreScroll = false;
  639. }
  640. // Because of the order of the DT callbacks, the info update will
  641. // take precedence over the one we want here. So a 'thread' break is
  642. // needed. Only add the thread break if bInfo is set
  643. if ( this.s.dt.oFeatures.bInfo ) {
  644. setTimeout( function () {
  645. that._info.call( that );
  646. }, 0 );
  647. }
  648. $(this.s.dt.nTable).triggerHandler('position.dts.dt', tableTop);
  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. // Store calcuated value, in case the following condition is not met, but so
  894. // that the draw function will still use it.
  895. this.s.targetTop = iTopRow;
  896. if ( iTopRow != this.s.dt._iDisplayStart ) {
  897. /* Cache the new table position for quick lookups */
  898. this.s.tableTop = $(this.s.dt.nTable).offset().top;
  899. this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop;
  900. var draw = function () {
  901. that.s.dt._iDisplayStart = that.s.targetTop;
  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. this.s.forceReposition = true;
  909. clearTimeout( this.s.drawTO );
  910. this.s.drawTO = setTimeout( draw, this.s.serverWait );
  911. }
  912. else {
  913. draw();
  914. }
  915. if ( this.dom.loader && ! this.s.loaderVisible ) {
  916. this.dom.loader.css( 'display', 'block' );
  917. this.s.loaderVisible = true;
  918. }
  919. }
  920. }
  921. else {
  922. this.s.topRowFloat = this.pixelsToRow( iScrollTop, false, true );
  923. }
  924. this.s.lastScrollTop = iScrollTop;
  925. this.s.stateSaveThrottle();
  926. if ( this.s.scrollType === 'jump' && this.s.mousedown ) {
  927. this.s.labelVisible = true;
  928. }
  929. if (this.s.labelVisible) {
  930. var labelFactor = (heights.viewport-heights.labelHeight - heights.xbar) / heights.scroll;
  931. this.dom.label
  932. .html( this.s.dt.fnFormatNumber( parseInt( this.s.topRowFloat, 10 )+1 ) )
  933. .css( 'top', iScrollTop + (iScrollTop * labelFactor) )
  934. .css( 'display', 'block' );
  935. }
  936. },
  937. /**
  938. * Force the scrolling container to have height beyond that of just the
  939. * table that has been drawn so the user can scroll the whole data set.
  940. *
  941. * Note that if the calculated required scrolling height exceeds a maximum
  942. * value (1 million pixels - hard-coded) the forcing element will be set
  943. * only to that maximum value and virtual / physical domain transforms will
  944. * be used to allow Scroller to display tables of any number of records.
  945. * @returns {void}
  946. * @private
  947. */
  948. _scrollForce: function ()
  949. {
  950. var heights = this.s.heights;
  951. var max = 1000000;
  952. heights.virtual = heights.row * this.s.dt.fnRecordsDisplay();
  953. heights.scroll = heights.virtual;
  954. if ( heights.scroll > max ) {
  955. heights.scroll = max;
  956. }
  957. // Minimum height so there is always a row visible (the 'no rows found'
  958. // if reduced to zero filtering)
  959. this.dom.force.style.height = heights.scroll > this.s.heights.row ?
  960. heights.scroll+'px' :
  961. this.s.heights.row+'px';
  962. }
  963. } );
  964. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  965. * Statics
  966. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  967. /**
  968. * Scroller default settings for initialisation
  969. * @namespace
  970. * @name Scroller.defaults
  971. * @static
  972. */
  973. Scroller.defaults = {
  974. /**
  975. * Scroller uses the boundary scaling factor to decide when to redraw the table - which it
  976. * typically does before you reach the end of the currently loaded data set (in order to
  977. * allow the data to look continuous to a user scrolling through the data). If given as 0
  978. * then the table will be redrawn whenever the viewport is scrolled, while 1 would not
  979. * redraw the table until the currently loaded data has all been shown. You will want
  980. * something in the middle - the default factor of 0.5 is usually suitable.
  981. * @type float
  982. * @default 0.5
  983. * @static
  984. */
  985. boundaryScale: 0.5,
  986. /**
  987. * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch
  988. * for scrolling. Scroller automatically adjusts DataTables' display length to pre-fetch
  989. * rows that will be shown in "near scrolling" (i.e. just beyond the current display area).
  990. * The value is based upon the number of rows that can be displayed in the viewport (i.e.
  991. * a value of 1), and will apply the display range to records before before and after the
  992. * current viewport - i.e. a factor of 3 will allow Scroller to pre-fetch 1 viewport's worth
  993. * of rows before the current viewport, the current viewport's rows and 1 viewport's worth
  994. * of rows after the current viewport. Adjusting this value can be useful for ensuring
  995. * smooth scrolling based on your data set.
  996. * @type int
  997. * @default 7
  998. * @static
  999. */
  1000. displayBuffer: 9,
  1001. /**
  1002. * Show (or not) the loading element in the background of the table. Note that you should
  1003. * include the dataTables.scroller.css file for this to be displayed correctly.
  1004. * @type boolean
  1005. * @default false
  1006. * @static
  1007. */
  1008. loadingIndicator: false,
  1009. /**
  1010. * Scroller will attempt to automatically calculate the height of rows for it's internal
  1011. * calculations. However the height that is used can be overridden using this parameter.
  1012. * @type int|string
  1013. * @default auto
  1014. * @static
  1015. */
  1016. rowHeight: "auto",
  1017. /**
  1018. * When using server-side processing, Scroller will wait a small amount of time to allow
  1019. * the scrolling to finish before requesting more data from the server. This prevents
  1020. * you from DoSing your own server! The wait time can be configured by this parameter.
  1021. * @type int
  1022. * @default 200
  1023. * @static
  1024. */
  1025. serverWait: 200
  1026. };
  1027. Scroller.oDefaults = Scroller.defaults;
  1028. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1029. * Constants
  1030. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1031. /**
  1032. * Scroller version
  1033. * @type String
  1034. * @default See code
  1035. * @name Scroller.version
  1036. * @static
  1037. */
  1038. Scroller.version = "2.0.5";
  1039. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1040. * Initialisation
  1041. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  1042. // Attach a listener to the document which listens for DataTables initialisation
  1043. // events so we can automatically initialise
  1044. $(document).on( 'preInit.dt.dtscroller', function (e, settings) {
  1045. if ( e.namespace !== 'dt' ) {
  1046. return;
  1047. }
  1048. var init = settings.oInit.scroller;
  1049. var defaults = DataTable.defaults.scroller;
  1050. if ( init || defaults ) {
  1051. var opts = $.extend( {}, init, defaults );
  1052. if ( init !== false ) {
  1053. new Scroller( settings, opts );
  1054. }
  1055. }
  1056. } );
  1057. // Attach Scroller to DataTables so it can be accessed as an 'extra'
  1058. $.fn.dataTable.Scroller = Scroller;
  1059. $.fn.DataTable.Scroller = Scroller;
  1060. // DataTables 1.10 API method aliases
  1061. var Api = $.fn.dataTable.Api;
  1062. Api.register( 'scroller()', function () {
  1063. return this;
  1064. } );
  1065. // Undocumented and deprecated - is it actually useful at all?
  1066. Api.register( 'scroller().rowToPixels()', function ( rowIdx, intParse, virtual ) {
  1067. var ctx = this.context;
  1068. if ( ctx.length && ctx[0].oScroller ) {
  1069. return ctx[0].oScroller.rowToPixels( rowIdx, intParse, virtual );
  1070. }
  1071. // undefined
  1072. } );
  1073. // Undocumented and deprecated - is it actually useful at all?
  1074. Api.register( 'scroller().pixelsToRow()', function ( pixels, intParse, virtual ) {
  1075. var ctx = this.context;
  1076. if ( ctx.length && ctx[0].oScroller ) {
  1077. return ctx[0].oScroller.pixelsToRow( pixels, intParse, virtual );
  1078. }
  1079. // undefined
  1080. } );
  1081. // `scroller().scrollToRow()` is undocumented and deprecated. Use `scroller.toPosition()
  1082. Api.register( ['scroller().scrollToRow()', 'scroller.toPosition()'], function ( idx, ani ) {
  1083. this.iterator( 'table', function ( ctx ) {
  1084. if ( ctx.oScroller ) {
  1085. ctx.oScroller.scrollToRow( idx, ani );
  1086. }
  1087. } );
  1088. return this;
  1089. } );
  1090. Api.register( 'row().scrollTo()', function ( ani ) {
  1091. var that = this;
  1092. this.iterator( 'row', function ( ctx, rowIdx ) {
  1093. if ( ctx.oScroller ) {
  1094. var displayIdx = that
  1095. .rows( { order: 'applied', search: 'applied' } )
  1096. .indexes()
  1097. .indexOf( rowIdx );
  1098. ctx.oScroller.scrollToRow( displayIdx, ani );
  1099. }
  1100. } );
  1101. return this;
  1102. } );
  1103. Api.register( 'scroller.measure()', function ( redraw ) {
  1104. this.iterator( 'table', function ( ctx ) {
  1105. if ( ctx.oScroller ) {
  1106. ctx.oScroller.measure( redraw );
  1107. }
  1108. } );
  1109. return this;
  1110. } );
  1111. Api.register( 'scroller.page()', function() {
  1112. var ctx = this.context;
  1113. if ( ctx.length && ctx[0].oScroller ) {
  1114. return ctx[0].oScroller.pageInfo();
  1115. }
  1116. // undefined
  1117. } );
  1118. return Scroller;
  1119. }));