dataTables.buttons.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  1. /*! Buttons for DataTables 1.6.1
  2. * ©2016-2019 SpryMedia Ltd - datatables.net/license
  3. */
  4. (function( factory ){
  5. if ( typeof define === 'function' && define.amd ) {
  6. // AMD
  7. define( ['jquery', 'datatables.net'], function ( $ ) {
  8. return factory( $, window, document );
  9. } );
  10. }
  11. else if ( typeof exports === 'object' ) {
  12. // CommonJS
  13. module.exports = function (root, $) {
  14. if ( ! root ) {
  15. root = window;
  16. }
  17. if ( ! $ || ! $.fn.dataTable ) {
  18. $ = require('datatables.net')(root, $).$;
  19. }
  20. return factory( $, root, root.document );
  21. };
  22. }
  23. else {
  24. // Browser
  25. factory( jQuery, window, document );
  26. }
  27. }(function( $, window, document, undefined ) {
  28. 'use strict';
  29. var DataTable = $.fn.dataTable;
  30. // Used for namespacing events added to the document by each instance, so they
  31. // can be removed on destroy
  32. var _instCounter = 0;
  33. // Button namespacing counter for namespacing events on individual buttons
  34. var _buttonCounter = 0;
  35. var _dtButtons = DataTable.ext.buttons;
  36. /**
  37. * [Buttons description]
  38. * @param {[type]}
  39. * @param {[type]}
  40. */
  41. var Buttons = function( dt, config )
  42. {
  43. // If not created with a `new` keyword then we return a wrapper function that
  44. // will take the settings object for a DT. This allows easy use of new instances
  45. // with the `layout` option - e.g. `topLeft: $.fn.dataTable.Buttons( ... )`.
  46. if ( !(this instanceof Buttons) ) {
  47. return function (settings) {
  48. return new Buttons( settings, dt ).container();
  49. };
  50. }
  51. // If there is no config set it to an empty object
  52. if ( typeof( config ) === 'undefined' ) {
  53. config = {};
  54. }
  55. // Allow a boolean true for defaults
  56. if ( config === true ) {
  57. config = {};
  58. }
  59. // For easy configuration of buttons an array can be given
  60. if ( $.isArray( config ) ) {
  61. config = { buttons: config };
  62. }
  63. this.c = $.extend( true, {}, Buttons.defaults, config );
  64. // Don't want a deep copy for the buttons
  65. if ( config.buttons ) {
  66. this.c.buttons = config.buttons;
  67. }
  68. this.s = {
  69. dt: new DataTable.Api( dt ),
  70. buttons: [],
  71. listenKeys: '',
  72. namespace: 'dtb'+(_instCounter++)
  73. };
  74. this.dom = {
  75. container: $('<'+this.c.dom.container.tag+'/>')
  76. .addClass( this.c.dom.container.className )
  77. };
  78. this._constructor();
  79. };
  80. $.extend( Buttons.prototype, {
  81. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  82. * Public methods
  83. */
  84. /**
  85. * Get the action of a button
  86. * @param {int|string} Button index
  87. * @return {function}
  88. *//**
  89. * Set the action of a button
  90. * @param {node} node Button element
  91. * @param {function} action Function to set
  92. * @return {Buttons} Self for chaining
  93. */
  94. action: function ( node, action )
  95. {
  96. var button = this._nodeToButton( node );
  97. if ( action === undefined ) {
  98. return button.conf.action;
  99. }
  100. button.conf.action = action;
  101. return this;
  102. },
  103. /**
  104. * Add an active class to the button to make to look active or get current
  105. * active state.
  106. * @param {node} node Button element
  107. * @param {boolean} [flag] Enable / disable flag
  108. * @return {Buttons} Self for chaining or boolean for getter
  109. */
  110. active: function ( node, flag ) {
  111. var button = this._nodeToButton( node );
  112. var klass = this.c.dom.button.active;
  113. var jqNode = $(button.node);
  114. if ( flag === undefined ) {
  115. return jqNode.hasClass( klass );
  116. }
  117. jqNode.toggleClass( klass, flag === undefined ? true : flag );
  118. return this;
  119. },
  120. /**
  121. * Add a new button
  122. * @param {object} config Button configuration object, base string name or function
  123. * @param {int|string} [idx] Button index for where to insert the button
  124. * @return {Buttons} Self for chaining
  125. */
  126. add: function ( config, idx )
  127. {
  128. var buttons = this.s.buttons;
  129. if ( typeof idx === 'string' ) {
  130. var split = idx.split('-');
  131. var base = this.s;
  132. for ( var i=0, ien=split.length-1 ; i<ien ; i++ ) {
  133. base = base.buttons[ split[i]*1 ];
  134. }
  135. buttons = base.buttons;
  136. idx = split[ split.length-1 ]*1;
  137. }
  138. this._expandButton( buttons, config, base !== undefined, idx );
  139. this._draw();
  140. return this;
  141. },
  142. /**
  143. * Get the container node for the buttons
  144. * @return {jQuery} Buttons node
  145. */
  146. container: function ()
  147. {
  148. return this.dom.container;
  149. },
  150. /**
  151. * Disable a button
  152. * @param {node} node Button node
  153. * @return {Buttons} Self for chaining
  154. */
  155. disable: function ( node ) {
  156. var button = this._nodeToButton( node );
  157. $(button.node).addClass( this.c.dom.button.disabled );
  158. return this;
  159. },
  160. /**
  161. * Destroy the instance, cleaning up event handlers and removing DOM
  162. * elements
  163. * @return {Buttons} Self for chaining
  164. */
  165. destroy: function ()
  166. {
  167. // Key event listener
  168. $('body').off( 'keyup.'+this.s.namespace );
  169. // Individual button destroy (so they can remove their own events if
  170. // needed). Take a copy as the array is modified by `remove`
  171. var buttons = this.s.buttons.slice();
  172. var i, ien;
  173. for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
  174. this.remove( buttons[i].node );
  175. }
  176. // Container
  177. this.dom.container.remove();
  178. // Remove from the settings object collection
  179. var buttonInsts = this.s.dt.settings()[0];
  180. for ( i=0, ien=buttonInsts.length ; i<ien ; i++ ) {
  181. if ( buttonInsts.inst === this ) {
  182. buttonInsts.splice( i, 1 );
  183. break;
  184. }
  185. }
  186. return this;
  187. },
  188. /**
  189. * Enable / disable a button
  190. * @param {node} node Button node
  191. * @param {boolean} [flag=true] Enable / disable flag
  192. * @return {Buttons} Self for chaining
  193. */
  194. enable: function ( node, flag )
  195. {
  196. if ( flag === false ) {
  197. return this.disable( node );
  198. }
  199. var button = this._nodeToButton( node );
  200. $(button.node).removeClass( this.c.dom.button.disabled );
  201. return this;
  202. },
  203. /**
  204. * Get the instance name for the button set selector
  205. * @return {string} Instance name
  206. */
  207. name: function ()
  208. {
  209. return this.c.name;
  210. },
  211. /**
  212. * Get a button's node of the buttons container if no button is given
  213. * @param {node} [node] Button node
  214. * @return {jQuery} Button element, or container
  215. */
  216. node: function ( node )
  217. {
  218. if ( ! node ) {
  219. return this.dom.container;
  220. }
  221. var button = this._nodeToButton( node );
  222. return $(button.node);
  223. },
  224. /**
  225. * Set / get a processing class on the selected button
  226. * @param {element} node Triggering button node
  227. * @param {boolean} flag true to add, false to remove, undefined to get
  228. * @return {boolean|Buttons} Getter value or this if a setter.
  229. */
  230. processing: function ( node, flag )
  231. {
  232. var dt = this.s.dt;
  233. var button = this._nodeToButton( node );
  234. if ( flag === undefined ) {
  235. return $(button.node).hasClass( 'processing' );
  236. }
  237. $(button.node).toggleClass( 'processing', flag );
  238. $(dt.table().node()).triggerHandler( 'buttons-processing.dt', [
  239. flag, dt.button( node ), dt, $(node), button.conf
  240. ] );
  241. return this;
  242. },
  243. /**
  244. * Remove a button.
  245. * @param {node} node Button node
  246. * @return {Buttons} Self for chaining
  247. */
  248. remove: function ( node )
  249. {
  250. var button = this._nodeToButton( node );
  251. var host = this._nodeToHost( node );
  252. var dt = this.s.dt;
  253. // Remove any child buttons first
  254. if ( button.buttons.length ) {
  255. for ( var i=button.buttons.length-1 ; i>=0 ; i-- ) {
  256. this.remove( button.buttons[i].node );
  257. }
  258. }
  259. // Allow the button to remove event handlers, etc
  260. if ( button.conf.destroy ) {
  261. button.conf.destroy.call( dt.button(node), dt, $(node), button.conf );
  262. }
  263. this._removeKey( button.conf );
  264. $(button.node).remove();
  265. var idx = $.inArray( button, host );
  266. host.splice( idx, 1 );
  267. return this;
  268. },
  269. /**
  270. * Get the text for a button
  271. * @param {int|string} node Button index
  272. * @return {string} Button text
  273. *//**
  274. * Set the text for a button
  275. * @param {int|string|function} node Button index
  276. * @param {string} label Text
  277. * @return {Buttons} Self for chaining
  278. */
  279. text: function ( node, label )
  280. {
  281. var button = this._nodeToButton( node );
  282. var buttonLiner = this.c.dom.collection.buttonLiner;
  283. var linerTag = button.inCollection && buttonLiner && buttonLiner.tag ?
  284. buttonLiner.tag :
  285. this.c.dom.buttonLiner.tag;
  286. var dt = this.s.dt;
  287. var jqNode = $(button.node);
  288. var text = function ( opt ) {
  289. return typeof opt === 'function' ?
  290. opt( dt, jqNode, button.conf ) :
  291. opt;
  292. };
  293. if ( label === undefined ) {
  294. return text( button.conf.text );
  295. }
  296. button.conf.text = label;
  297. if ( linerTag ) {
  298. jqNode.children( linerTag ).html( text(label) );
  299. }
  300. else {
  301. jqNode.html( text(label) );
  302. }
  303. return this;
  304. },
  305. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  306. * Constructor
  307. */
  308. /**
  309. * Buttons constructor
  310. * @private
  311. */
  312. _constructor: function ()
  313. {
  314. var that = this;
  315. var dt = this.s.dt;
  316. var dtSettings = dt.settings()[0];
  317. var buttons = this.c.buttons;
  318. if ( ! dtSettings._buttons ) {
  319. dtSettings._buttons = [];
  320. }
  321. dtSettings._buttons.push( {
  322. inst: this,
  323. name: this.c.name
  324. } );
  325. for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
  326. this.add( buttons[i] );
  327. }
  328. dt.on( 'destroy', function ( e, settings ) {
  329. if ( settings === dtSettings ) {
  330. that.destroy();
  331. }
  332. } );
  333. // Global key event binding to listen for button keys
  334. $('body').on( 'keyup.'+this.s.namespace, function ( e ) {
  335. if ( ! document.activeElement || document.activeElement === document.body ) {
  336. // SUse a string of characters for fast lookup of if we need to
  337. // handle this
  338. var character = String.fromCharCode(e.keyCode).toLowerCase();
  339. if ( that.s.listenKeys.toLowerCase().indexOf( character ) !== -1 ) {
  340. that._keypress( character, e );
  341. }
  342. }
  343. } );
  344. },
  345. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  346. * Private methods
  347. */
  348. /**
  349. * Add a new button to the key press listener
  350. * @param {object} conf Resolved button configuration object
  351. * @private
  352. */
  353. _addKey: function ( conf )
  354. {
  355. if ( conf.key ) {
  356. this.s.listenKeys += $.isPlainObject( conf.key ) ?
  357. conf.key.key :
  358. conf.key;
  359. }
  360. },
  361. /**
  362. * Insert the buttons into the container. Call without parameters!
  363. * @param {node} [container] Recursive only - Insert point
  364. * @param {array} [buttons] Recursive only - Buttons array
  365. * @private
  366. */
  367. _draw: function ( container, buttons )
  368. {
  369. if ( ! container ) {
  370. container = this.dom.container;
  371. buttons = this.s.buttons;
  372. }
  373. container.children().detach();
  374. for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
  375. container.append( buttons[i].inserter );
  376. container.append( ' ' );
  377. if ( buttons[i].buttons && buttons[i].buttons.length ) {
  378. this._draw( buttons[i].collection, buttons[i].buttons );
  379. }
  380. }
  381. },
  382. /**
  383. * Create buttons from an array of buttons
  384. * @param {array} attachTo Buttons array to attach to
  385. * @param {object} button Button definition
  386. * @param {boolean} inCollection true if the button is in a collection
  387. * @private
  388. */
  389. _expandButton: function ( attachTo, button, inCollection, attachPoint )
  390. {
  391. var dt = this.s.dt;
  392. var buttonCounter = 0;
  393. var buttons = ! $.isArray( button ) ?
  394. [ button ] :
  395. button;
  396. for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
  397. var conf = this._resolveExtends( buttons[i] );
  398. if ( ! conf ) {
  399. continue;
  400. }
  401. // If the configuration is an array, then expand the buttons at this
  402. // point
  403. if ( $.isArray( conf ) ) {
  404. this._expandButton( attachTo, conf, inCollection, attachPoint );
  405. continue;
  406. }
  407. var built = this._buildButton( conf, inCollection );
  408. if ( ! built ) {
  409. continue;
  410. }
  411. if ( attachPoint !== undefined ) {
  412. attachTo.splice( attachPoint, 0, built );
  413. attachPoint++;
  414. }
  415. else {
  416. attachTo.push( built );
  417. }
  418. if ( built.conf.buttons ) {
  419. built.collection = $('<'+this.c.dom.collection.tag+'/>');
  420. built.conf._collection = built.collection;
  421. this._expandButton( built.buttons, built.conf.buttons, true, attachPoint );
  422. }
  423. // init call is made here, rather than buildButton as it needs to
  424. // be selectable, and for that it needs to be in the buttons array
  425. if ( conf.init ) {
  426. conf.init.call( dt.button( built.node ), dt, $(built.node), conf );
  427. }
  428. buttonCounter++;
  429. }
  430. },
  431. /**
  432. * Create an individual button
  433. * @param {object} config Resolved button configuration
  434. * @param {boolean} inCollection `true` if a collection button
  435. * @return {jQuery} Created button node (jQuery)
  436. * @private
  437. */
  438. _buildButton: function ( config, inCollection )
  439. {
  440. var buttonDom = this.c.dom.button;
  441. var linerDom = this.c.dom.buttonLiner;
  442. var collectionDom = this.c.dom.collection;
  443. var dt = this.s.dt;
  444. var text = function ( opt ) {
  445. return typeof opt === 'function' ?
  446. opt( dt, button, config ) :
  447. opt;
  448. };
  449. if ( inCollection && collectionDom.button ) {
  450. buttonDom = collectionDom.button;
  451. }
  452. if ( inCollection && collectionDom.buttonLiner ) {
  453. linerDom = collectionDom.buttonLiner;
  454. }
  455. // Make sure that the button is available based on whatever requirements
  456. // it has. For example, Flash buttons require Flash
  457. if ( config.available && ! config.available( dt, config ) ) {
  458. return false;
  459. }
  460. var action = function ( e, dt, button, config ) {
  461. config.action.call( dt.button( button ), e, dt, button, config );
  462. $(dt.table().node()).triggerHandler( 'buttons-action.dt', [
  463. dt.button( button ), dt, button, config
  464. ] );
  465. };
  466. var tag = config.tag || buttonDom.tag;
  467. var clickBlurs = config.clickBlurs === undefined ? true : config.clickBlurs
  468. var button = $('<'+tag+'/>')
  469. .addClass( buttonDom.className )
  470. .attr( 'tabindex', this.s.dt.settings()[0].iTabIndex )
  471. .attr( 'aria-controls', this.s.dt.table().node().id )
  472. .on( 'click.dtb', function (e) {
  473. e.preventDefault();
  474. if ( ! button.hasClass( buttonDom.disabled ) && config.action ) {
  475. action( e, dt, button, config );
  476. }
  477. if( clickBlurs ) {
  478. button.blur();
  479. }
  480. } )
  481. .on( 'keyup.dtb', function (e) {
  482. if ( e.keyCode === 13 ) {
  483. if ( ! button.hasClass( buttonDom.disabled ) && config.action ) {
  484. action( e, dt, button, config );
  485. }
  486. }
  487. } );
  488. // Make `a` tags act like a link
  489. if ( tag.toLowerCase() === 'a' ) {
  490. button.attr( 'href', '#' );
  491. }
  492. // Button tags should have `type=button` so they don't have any default behaviour
  493. if ( tag.toLowerCase() === 'button' ) {
  494. button.attr( 'type', 'button' );
  495. }
  496. if ( linerDom.tag ) {
  497. var liner = $('<'+linerDom.tag+'/>')
  498. .html( text( config.text ) )
  499. .addClass( linerDom.className );
  500. if ( linerDom.tag.toLowerCase() === 'a' ) {
  501. liner.attr( 'href', '#' );
  502. }
  503. button.append( liner );
  504. }
  505. else {
  506. button.html( text( config.text ) );
  507. }
  508. if ( config.enabled === false ) {
  509. button.addClass( buttonDom.disabled );
  510. }
  511. if ( config.className ) {
  512. button.addClass( config.className );
  513. }
  514. if ( config.titleAttr ) {
  515. button.attr( 'title', text( config.titleAttr ) );
  516. }
  517. if ( config.attr ) {
  518. button.attr( config.attr );
  519. }
  520. if ( ! config.namespace ) {
  521. config.namespace = '.dt-button-'+(_buttonCounter++);
  522. }
  523. var buttonContainer = this.c.dom.buttonContainer;
  524. var inserter;
  525. if ( buttonContainer && buttonContainer.tag ) {
  526. inserter = $('<'+buttonContainer.tag+'/>')
  527. .addClass( buttonContainer.className )
  528. .append( button );
  529. }
  530. else {
  531. inserter = button;
  532. }
  533. this._addKey( config );
  534. // Style integration callback for DOM manipulation
  535. // Note that this is _not_ documented. It is currently
  536. // for style integration only
  537. if( this.c.buttonCreated ) {
  538. inserter = this.c.buttonCreated( config, inserter );
  539. }
  540. return {
  541. conf: config,
  542. node: button.get(0),
  543. inserter: inserter,
  544. buttons: [],
  545. inCollection: inCollection,
  546. collection: null
  547. };
  548. },
  549. /**
  550. * Get the button object from a node (recursive)
  551. * @param {node} node Button node
  552. * @param {array} [buttons] Button array, uses base if not defined
  553. * @return {object} Button object
  554. * @private
  555. */
  556. _nodeToButton: function ( node, buttons )
  557. {
  558. if ( ! buttons ) {
  559. buttons = this.s.buttons;
  560. }
  561. for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
  562. if ( buttons[i].node === node ) {
  563. return buttons[i];
  564. }
  565. if ( buttons[i].buttons.length ) {
  566. var ret = this._nodeToButton( node, buttons[i].buttons );
  567. if ( ret ) {
  568. return ret;
  569. }
  570. }
  571. }
  572. },
  573. /**
  574. * Get container array for a button from a button node (recursive)
  575. * @param {node} node Button node
  576. * @param {array} [buttons] Button array, uses base if not defined
  577. * @return {array} Button's host array
  578. * @private
  579. */
  580. _nodeToHost: function ( node, buttons )
  581. {
  582. if ( ! buttons ) {
  583. buttons = this.s.buttons;
  584. }
  585. for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
  586. if ( buttons[i].node === node ) {
  587. return buttons;
  588. }
  589. if ( buttons[i].buttons.length ) {
  590. var ret = this._nodeToHost( node, buttons[i].buttons );
  591. if ( ret ) {
  592. return ret;
  593. }
  594. }
  595. }
  596. },
  597. /**
  598. * Handle a key press - determine if any button's key configured matches
  599. * what was typed and trigger the action if so.
  600. * @param {string} character The character pressed
  601. * @param {object} e Key event that triggered this call
  602. * @private
  603. */
  604. _keypress: function ( character, e )
  605. {
  606. // Check if this button press already activated on another instance of Buttons
  607. if ( e._buttonsHandled ) {
  608. return;
  609. }
  610. var run = function ( conf, node ) {
  611. if ( ! conf.key ) {
  612. return;
  613. }
  614. if ( conf.key === character ) {
  615. e._buttonsHandled = true;
  616. $(node).click();
  617. }
  618. else if ( $.isPlainObject( conf.key ) ) {
  619. if ( conf.key.key !== character ) {
  620. return;
  621. }
  622. if ( conf.key.shiftKey && ! e.shiftKey ) {
  623. return;
  624. }
  625. if ( conf.key.altKey && ! e.altKey ) {
  626. return;
  627. }
  628. if ( conf.key.ctrlKey && ! e.ctrlKey ) {
  629. return;
  630. }
  631. if ( conf.key.metaKey && ! e.metaKey ) {
  632. return;
  633. }
  634. // Made it this far - it is good
  635. e._buttonsHandled = true;
  636. $(node).click();
  637. }
  638. };
  639. var recurse = function ( a ) {
  640. for ( var i=0, ien=a.length ; i<ien ; i++ ) {
  641. run( a[i].conf, a[i].node );
  642. if ( a[i].buttons.length ) {
  643. recurse( a[i].buttons );
  644. }
  645. }
  646. };
  647. recurse( this.s.buttons );
  648. },
  649. /**
  650. * Remove a key from the key listener for this instance (to be used when a
  651. * button is removed)
  652. * @param {object} conf Button configuration
  653. * @private
  654. */
  655. _removeKey: function ( conf )
  656. {
  657. if ( conf.key ) {
  658. var character = $.isPlainObject( conf.key ) ?
  659. conf.key.key :
  660. conf.key;
  661. // Remove only one character, as multiple buttons could have the
  662. // same listening key
  663. var a = this.s.listenKeys.split('');
  664. var idx = $.inArray( character, a );
  665. a.splice( idx, 1 );
  666. this.s.listenKeys = a.join('');
  667. }
  668. },
  669. /**
  670. * Resolve a button configuration
  671. * @param {string|function|object} conf Button config to resolve
  672. * @return {object} Button configuration
  673. * @private
  674. */
  675. _resolveExtends: function ( conf )
  676. {
  677. var dt = this.s.dt;
  678. var i, ien;
  679. var toConfObject = function ( base ) {
  680. var loop = 0;
  681. // Loop until we have resolved to a button configuration, or an
  682. // array of button configurations (which will be iterated
  683. // separately)
  684. while ( ! $.isPlainObject(base) && ! $.isArray(base) ) {
  685. if ( base === undefined ) {
  686. return;
  687. }
  688. if ( typeof base === 'function' ) {
  689. base = base( dt, conf );
  690. if ( ! base ) {
  691. return false;
  692. }
  693. }
  694. else if ( typeof base === 'string' ) {
  695. if ( ! _dtButtons[ base ] ) {
  696. throw 'Unknown button type: '+base;
  697. }
  698. base = _dtButtons[ base ];
  699. }
  700. loop++;
  701. if ( loop > 30 ) {
  702. // Protect against misconfiguration killing the browser
  703. throw 'Buttons: Too many iterations';
  704. }
  705. }
  706. return $.isArray( base ) ?
  707. base :
  708. $.extend( {}, base );
  709. };
  710. conf = toConfObject( conf );
  711. while ( conf && conf.extend ) {
  712. // Use `toConfObject` in case the button definition being extended
  713. // is itself a string or a function
  714. if ( ! _dtButtons[ conf.extend ] ) {
  715. throw 'Cannot extend unknown button type: '+conf.extend;
  716. }
  717. var objArray = toConfObject( _dtButtons[ conf.extend ] );
  718. if ( $.isArray( objArray ) ) {
  719. return objArray;
  720. }
  721. else if ( ! objArray ) {
  722. // This is a little brutal as it might be possible to have a
  723. // valid button without the extend, but if there is no extend
  724. // then the host button would be acting in an undefined state
  725. return false;
  726. }
  727. // Stash the current class name
  728. var originalClassName = objArray.className;
  729. conf = $.extend( {}, objArray, conf );
  730. // The extend will have overwritten the original class name if the
  731. // `conf` object also assigned a class, but we want to concatenate
  732. // them so they are list that is combined from all extended buttons
  733. if ( originalClassName && conf.className !== originalClassName ) {
  734. conf.className = originalClassName+' '+conf.className;
  735. }
  736. // Buttons to be added to a collection -gives the ability to define
  737. // if buttons should be added to the start or end of a collection
  738. var postfixButtons = conf.postfixButtons;
  739. if ( postfixButtons ) {
  740. if ( ! conf.buttons ) {
  741. conf.buttons = [];
  742. }
  743. for ( i=0, ien=postfixButtons.length ; i<ien ; i++ ) {
  744. conf.buttons.push( postfixButtons[i] );
  745. }
  746. conf.postfixButtons = null;
  747. }
  748. var prefixButtons = conf.prefixButtons;
  749. if ( prefixButtons ) {
  750. if ( ! conf.buttons ) {
  751. conf.buttons = [];
  752. }
  753. for ( i=0, ien=prefixButtons.length ; i<ien ; i++ ) {
  754. conf.buttons.splice( i, 0, prefixButtons[i] );
  755. }
  756. conf.prefixButtons = null;
  757. }
  758. // Although we want the `conf` object to overwrite almost all of
  759. // the properties of the object being extended, the `extend`
  760. // property should come from the object being extended
  761. conf.extend = objArray.extend;
  762. }
  763. return conf;
  764. },
  765. /**
  766. * Display (and replace if there is an existing one) a popover attached to a button
  767. * @param {string|node} content Content to show
  768. * @param {DataTable.Api} hostButton DT API instance of the button
  769. * @param {object} inOpts Options (see object below for all options)
  770. */
  771. _popover: function ( content, hostButton, inOpts ) {
  772. var dt = hostButton;
  773. var buttonsSettings = this.c;
  774. var options = $.extend( {
  775. align: 'button-left', // button-right, dt-container
  776. autoClose: false,
  777. background: true,
  778. backgroundClassName: 'dt-button-background',
  779. contentClassName: buttonsSettings.dom.collection.className,
  780. collectionLayout: '',
  781. collectionTitle: '',
  782. dropup: false,
  783. fade: 400,
  784. rightAlignClassName: 'dt-button-right',
  785. tag: buttonsSettings.dom.collection.tag
  786. }, inOpts );
  787. var hostNode = hostButton.node();
  788. var close = function () {
  789. $('.dt-button-collection').stop().fadeOut( options.fade, function () {
  790. $(this).detach();
  791. } );
  792. $(dt.buttons( '[aria-haspopup="true"][aria-expanded="true"]' ).nodes())
  793. .attr('aria-expanded', 'false');
  794. $('div.dt-button-background').off( 'click.dtb-collection' );
  795. Buttons.background( false, options.backgroundClassName, options.fade, hostNode );
  796. $('body').off( '.dtb-collection' );
  797. dt.off( 'buttons-action.b-internal' );
  798. };
  799. if (content === false) {
  800. close();
  801. }
  802. var existingExpanded = $(dt.buttons( '[aria-haspopup="true"][aria-expanded="true"]' ).nodes());
  803. if ( existingExpanded.length ) {
  804. hostNode = existingExpanded.eq(0);
  805. close();
  806. }
  807. var display = $('<div/>')
  808. .addClass('dt-button-collection')
  809. .addClass(options.collectionLayout)
  810. .css('display', 'none');
  811. content = $(content)
  812. .addClass(options.contentClassName)
  813. .attr('role', 'menu')
  814. .appendTo(display);
  815. hostNode.attr( 'aria-expanded', 'true' );
  816. if ( hostNode.parents('body')[0] !== document.body ) {
  817. hostNode = document.body.lastChild;
  818. }
  819. if ( options.collectionTitle ) {
  820. display.prepend('<div class="dt-button-collection-title">'+options.collectionTitle+'</div>');
  821. }
  822. display
  823. .insertAfter( hostNode )
  824. .fadeIn( options.fade );
  825. var tableContainer = $( hostButton.table().container() );
  826. var position = display.css( 'position' );
  827. if ( options.align === 'dt-container' ) {
  828. hostNode = hostNode.parent();
  829. display.css('width', tableContainer.width());
  830. }
  831. if ( position === 'absolute' ) {
  832. var hostPosition = hostNode.position();
  833. display.css( {
  834. top: hostPosition.top + hostNode.outerHeight(),
  835. left: hostPosition.left
  836. } );
  837. // calculate overflow when positioned beneath
  838. var collectionHeight = display.outerHeight();
  839. var collectionWidth = display.outerWidth();
  840. var tableBottom = tableContainer.offset().top + tableContainer.height();
  841. var listBottom = hostPosition.top + hostNode.outerHeight() + collectionHeight;
  842. var bottomOverflow = listBottom - tableBottom;
  843. // calculate overflow when positioned above
  844. var listTop = hostPosition.top - collectionHeight;
  845. var tableTop = tableContainer.offset().top;
  846. var topOverflow = tableTop - listTop;
  847. // if bottom overflow is larger, move to the top because it fits better, or if dropup is requested
  848. var moveTop = hostPosition.top - collectionHeight - 5;
  849. if ( (bottomOverflow > topOverflow || options.dropup) && -moveTop < tableTop ) {
  850. display.css( 'top', moveTop);
  851. }
  852. // Right alignment is enabled on a class, e.g. bootstrap:
  853. // $.fn.dataTable.Buttons.defaults.dom.collection.className += " dropdown-menu-right";
  854. if ( display.hasClass( options.rightAlignClassName ) || options.align === 'button-right' ) {
  855. display.css( 'left', hostPosition.left + hostNode.outerWidth() - collectionWidth );
  856. }
  857. // Right alignment in table container
  858. var listRight = hostPosition.left + collectionWidth;
  859. var tableRight = tableContainer.offset().left + tableContainer.width();
  860. if ( listRight > tableRight ) {
  861. display.css( 'left', hostPosition.left - ( listRight - tableRight ) );
  862. }
  863. // Right alignment to window
  864. var listOffsetRight = hostNode.offset().left + collectionWidth;
  865. if ( listOffsetRight > $(window).width() ) {
  866. display.css( 'left', hostPosition.left - (listOffsetRight-$(window).width()) );
  867. }
  868. }
  869. else {
  870. // Fix position - centre on screen
  871. var top = display.height() / 2;
  872. if ( top > $(window).height() / 2 ) {
  873. top = $(window).height() / 2;
  874. }
  875. display.css( 'marginTop', top*-1 );
  876. }
  877. if ( options.background ) {
  878. Buttons.background( true, options.backgroundClassName, options.fade, hostNode );
  879. }
  880. // This is bonkers, but if we don't have a click listener on the
  881. // background element, iOS Safari will ignore the body click
  882. // listener below. An empty function here is all that is
  883. // required to make it work...
  884. $('div.dt-button-background').on( 'click.dtb-collection', function () {} );
  885. $('body')
  886. .on( 'click.dtb-collection', function (e) {
  887. // andSelf is deprecated in jQ1.8, but we want 1.7 compat
  888. var back = $.fn.addBack ? 'addBack' : 'andSelf';
  889. if ( ! $(e.target).parents()[back]().filter( content ).length ) {
  890. close();
  891. }
  892. } )
  893. .on( 'keyup.dtb-collection', function (e) {
  894. if ( e.keyCode === 27 ) {
  895. close();
  896. }
  897. } );
  898. if ( options.autoClose ) {
  899. setTimeout( function () {
  900. dt.on( 'buttons-action.b-internal', function (e, btn, dt, node) {
  901. if ( node[0] === hostNode[0] ) {
  902. return;
  903. }
  904. close();
  905. } );
  906. }, 0);
  907. }
  908. }
  909. } );
  910. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  911. * Statics
  912. */
  913. /**
  914. * Show / hide a background layer behind a collection
  915. * @param {boolean} Flag to indicate if the background should be shown or
  916. * hidden
  917. * @param {string} Class to assign to the background
  918. * @static
  919. */
  920. Buttons.background = function ( show, className, fade, insertPoint ) {
  921. if ( fade === undefined ) {
  922. fade = 400;
  923. }
  924. if ( ! insertPoint ) {
  925. insertPoint = document.body;
  926. }
  927. if ( show ) {
  928. $('<div/>')
  929. .addClass( className )
  930. .css( 'display', 'none' )
  931. .insertAfter( insertPoint )
  932. .stop()
  933. .fadeIn( fade );
  934. }
  935. else {
  936. $('div.'+className)
  937. .stop()
  938. .fadeOut( fade, function () {
  939. $(this)
  940. .removeClass( className )
  941. .remove();
  942. } );
  943. }
  944. };
  945. /**
  946. * Instance selector - select Buttons instances based on an instance selector
  947. * value from the buttons assigned to a DataTable. This is only useful if
  948. * multiple instances are attached to a DataTable.
  949. * @param {string|int|array} Instance selector - see `instance-selector`
  950. * documentation on the DataTables site
  951. * @param {array} Button instance array that was attached to the DataTables
  952. * settings object
  953. * @return {array} Buttons instances
  954. * @static
  955. */
  956. Buttons.instanceSelector = function ( group, buttons )
  957. {
  958. if ( group === undefined || group === null ) {
  959. return $.map( buttons, function ( v ) {
  960. return v.inst;
  961. } );
  962. }
  963. var ret = [];
  964. var names = $.map( buttons, function ( v ) {
  965. return v.name;
  966. } );
  967. // Flatten the group selector into an array of single options
  968. var process = function ( input ) {
  969. if ( $.isArray( input ) ) {
  970. for ( var i=0, ien=input.length ; i<ien ; i++ ) {
  971. process( input[i] );
  972. }
  973. return;
  974. }
  975. if ( typeof input === 'string' ) {
  976. if ( input.indexOf( ',' ) !== -1 ) {
  977. // String selector, list of names
  978. process( input.split(',') );
  979. }
  980. else {
  981. // String selector individual name
  982. var idx = $.inArray( $.trim(input), names );
  983. if ( idx !== -1 ) {
  984. ret.push( buttons[ idx ].inst );
  985. }
  986. }
  987. }
  988. else if ( typeof input === 'number' ) {
  989. // Index selector
  990. ret.push( buttons[ input ].inst );
  991. }
  992. };
  993. process( group );
  994. return ret;
  995. };
  996. /**
  997. * Button selector - select one or more buttons from a selector input so some
  998. * operation can be performed on them.
  999. * @param {array} Button instances array that the selector should operate on
  1000. * @param {string|int|node|jQuery|array} Button selector - see
  1001. * `button-selector` documentation on the DataTables site
  1002. * @return {array} Array of objects containing `inst` and `idx` properties of
  1003. * the selected buttons so you know which instance each button belongs to.
  1004. * @static
  1005. */
  1006. Buttons.buttonSelector = function ( insts, selector )
  1007. {
  1008. var ret = [];
  1009. var nodeBuilder = function ( a, buttons, baseIdx ) {
  1010. var button;
  1011. var idx;
  1012. for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
  1013. button = buttons[i];
  1014. if ( button ) {
  1015. idx = baseIdx !== undefined ?
  1016. baseIdx+i :
  1017. i+'';
  1018. a.push( {
  1019. node: button.node,
  1020. name: button.conf.name,
  1021. idx: idx
  1022. } );
  1023. if ( button.buttons ) {
  1024. nodeBuilder( a, button.buttons, idx+'-' );
  1025. }
  1026. }
  1027. }
  1028. };
  1029. var run = function ( selector, inst ) {
  1030. var i, ien;
  1031. var buttons = [];
  1032. nodeBuilder( buttons, inst.s.buttons );
  1033. var nodes = $.map( buttons, function (v) {
  1034. return v.node;
  1035. } );
  1036. if ( $.isArray( selector ) || selector instanceof $ ) {
  1037. for ( i=0, ien=selector.length ; i<ien ; i++ ) {
  1038. run( selector[i], inst );
  1039. }
  1040. return;
  1041. }
  1042. if ( selector === null || selector === undefined || selector === '*' ) {
  1043. // Select all
  1044. for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
  1045. ret.push( {
  1046. inst: inst,
  1047. node: buttons[i].node
  1048. } );
  1049. }
  1050. }
  1051. else if ( typeof selector === 'number' ) {
  1052. // Main button index selector
  1053. ret.push( {
  1054. inst: inst,
  1055. node: inst.s.buttons[ selector ].node
  1056. } );
  1057. }
  1058. else if ( typeof selector === 'string' ) {
  1059. if ( selector.indexOf( ',' ) !== -1 ) {
  1060. // Split
  1061. var a = selector.split(',');
  1062. for ( i=0, ien=a.length ; i<ien ; i++ ) {
  1063. run( $.trim(a[i]), inst );
  1064. }
  1065. }
  1066. else if ( selector.match( /^\d+(\-\d+)*$/ ) ) {
  1067. // Sub-button index selector
  1068. var indexes = $.map( buttons, function (v) {
  1069. return v.idx;
  1070. } );
  1071. ret.push( {
  1072. inst: inst,
  1073. node: buttons[ $.inArray( selector, indexes ) ].node
  1074. } );
  1075. }
  1076. else if ( selector.indexOf( ':name' ) !== -1 ) {
  1077. // Button name selector
  1078. var name = selector.replace( ':name', '' );
  1079. for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
  1080. if ( buttons[i].name === name ) {
  1081. ret.push( {
  1082. inst: inst,
  1083. node: buttons[i].node
  1084. } );
  1085. }
  1086. }
  1087. }
  1088. else {
  1089. // jQuery selector on the nodes
  1090. $( nodes ).filter( selector ).each( function () {
  1091. ret.push( {
  1092. inst: inst,
  1093. node: this
  1094. } );
  1095. } );
  1096. }
  1097. }
  1098. else if ( typeof selector === 'object' && selector.nodeName ) {
  1099. // Node selector
  1100. var idx = $.inArray( selector, nodes );
  1101. if ( idx !== -1 ) {
  1102. ret.push( {
  1103. inst: inst,
  1104. node: nodes[ idx ]
  1105. } );
  1106. }
  1107. }
  1108. };
  1109. for ( var i=0, ien=insts.length ; i<ien ; i++ ) {
  1110. var inst = insts[i];
  1111. run( selector, inst );
  1112. }
  1113. return ret;
  1114. };
  1115. /**
  1116. * Buttons defaults. For full documentation, please refer to the docs/option
  1117. * directory or the DataTables site.
  1118. * @type {Object}
  1119. * @static
  1120. */
  1121. Buttons.defaults = {
  1122. buttons: [ 'copy', 'excel', 'csv', 'pdf', 'print' ],
  1123. name: 'main',
  1124. tabIndex: 0,
  1125. dom: {
  1126. container: {
  1127. tag: 'div',
  1128. className: 'dt-buttons'
  1129. },
  1130. collection: {
  1131. tag: 'div',
  1132. className: ''
  1133. },
  1134. button: {
  1135. // Flash buttons will not work with `<button>` in IE - it has to be `<a>`
  1136. tag: 'ActiveXObject' in window ?
  1137. 'a' :
  1138. 'button',
  1139. className: 'dt-button',
  1140. active: 'active',
  1141. disabled: 'disabled'
  1142. },
  1143. buttonLiner: {
  1144. tag: 'span',
  1145. className: ''
  1146. }
  1147. }
  1148. };
  1149. /**
  1150. * Version information
  1151. * @type {string}
  1152. * @static
  1153. */
  1154. Buttons.version = '1.6.1';
  1155. $.extend( _dtButtons, {
  1156. collection: {
  1157. text: function ( dt ) {
  1158. return dt.i18n( 'buttons.collection', 'Collection' );
  1159. },
  1160. className: 'buttons-collection',
  1161. init: function ( dt, button, config ) {
  1162. button.attr( 'aria-expanded', false );
  1163. },
  1164. action: function ( e, dt, button, config ) {
  1165. e.stopPropagation();
  1166. if ( config._collection.parents('body').length ) {
  1167. this.popover(false, config);
  1168. }
  1169. else {
  1170. this.popover(config._collection, config);
  1171. }
  1172. },
  1173. attr: {
  1174. 'aria-haspopup': true
  1175. }
  1176. // Also the popover options, defined in Buttons.popover
  1177. },
  1178. copy: function ( dt, conf ) {
  1179. if ( _dtButtons.copyHtml5 ) {
  1180. return 'copyHtml5';
  1181. }
  1182. if ( _dtButtons.copyFlash && _dtButtons.copyFlash.available( dt, conf ) ) {
  1183. return 'copyFlash';
  1184. }
  1185. },
  1186. csv: function ( dt, conf ) {
  1187. // Common option that will use the HTML5 or Flash export buttons
  1188. if ( _dtButtons.csvHtml5 && _dtButtons.csvHtml5.available( dt, conf ) ) {
  1189. return 'csvHtml5';
  1190. }
  1191. if ( _dtButtons.csvFlash && _dtButtons.csvFlash.available( dt, conf ) ) {
  1192. return 'csvFlash';
  1193. }
  1194. },
  1195. excel: function ( dt, conf ) {
  1196. // Common option that will use the HTML5 or Flash export buttons
  1197. if ( _dtButtons.excelHtml5 && _dtButtons.excelHtml5.available( dt, conf ) ) {
  1198. return 'excelHtml5';
  1199. }
  1200. if ( _dtButtons.excelFlash && _dtButtons.excelFlash.available( dt, conf ) ) {
  1201. return 'excelFlash';
  1202. }
  1203. },
  1204. pdf: function ( dt, conf ) {
  1205. // Common option that will use the HTML5 or Flash export buttons
  1206. if ( _dtButtons.pdfHtml5 && _dtButtons.pdfHtml5.available( dt, conf ) ) {
  1207. return 'pdfHtml5';
  1208. }
  1209. if ( _dtButtons.pdfFlash && _dtButtons.pdfFlash.available( dt, conf ) ) {
  1210. return 'pdfFlash';
  1211. }
  1212. },
  1213. pageLength: function ( dt ) {
  1214. var lengthMenu = dt.settings()[0].aLengthMenu;
  1215. var vals = $.isArray( lengthMenu[0] ) ? lengthMenu[0] : lengthMenu;
  1216. var lang = $.isArray( lengthMenu[0] ) ? lengthMenu[1] : lengthMenu;
  1217. var text = function ( dt ) {
  1218. return dt.i18n( 'buttons.pageLength', {
  1219. "-1": 'Show all rows',
  1220. _: 'Show %d rows'
  1221. }, dt.page.len() );
  1222. };
  1223. return {
  1224. extend: 'collection',
  1225. text: text,
  1226. className: 'buttons-page-length',
  1227. autoClose: true,
  1228. buttons: $.map( vals, function ( val, i ) {
  1229. return {
  1230. text: lang[i],
  1231. className: 'button-page-length',
  1232. action: function ( e, dt ) {
  1233. dt.page.len( val ).draw();
  1234. },
  1235. init: function ( dt, node, conf ) {
  1236. var that = this;
  1237. var fn = function () {
  1238. that.active( dt.page.len() === val );
  1239. };
  1240. dt.on( 'length.dt'+conf.namespace, fn );
  1241. fn();
  1242. },
  1243. destroy: function ( dt, node, conf ) {
  1244. dt.off( 'length.dt'+conf.namespace );
  1245. }
  1246. };
  1247. } ),
  1248. init: function ( dt, node, conf ) {
  1249. var that = this;
  1250. dt.on( 'length.dt'+conf.namespace, function () {
  1251. that.text( conf.text );
  1252. } );
  1253. },
  1254. destroy: function ( dt, node, conf ) {
  1255. dt.off( 'length.dt'+conf.namespace );
  1256. }
  1257. };
  1258. }
  1259. } );
  1260. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1261. * DataTables API
  1262. *
  1263. * For complete documentation, please refer to the docs/api directory or the
  1264. * DataTables site
  1265. */
  1266. // Buttons group and individual button selector
  1267. DataTable.Api.register( 'buttons()', function ( group, selector ) {
  1268. // Argument shifting
  1269. if ( selector === undefined ) {
  1270. selector = group;
  1271. group = undefined;
  1272. }
  1273. this.selector.buttonGroup = group;
  1274. var res = this.iterator( true, 'table', function ( ctx ) {
  1275. if ( ctx._buttons ) {
  1276. return Buttons.buttonSelector(
  1277. Buttons.instanceSelector( group, ctx._buttons ),
  1278. selector
  1279. );
  1280. }
  1281. }, true );
  1282. res._groupSelector = group;
  1283. return res;
  1284. } );
  1285. // Individual button selector
  1286. DataTable.Api.register( 'button()', function ( group, selector ) {
  1287. // just run buttons() and truncate
  1288. var buttons = this.buttons( group, selector );
  1289. if ( buttons.length > 1 ) {
  1290. buttons.splice( 1, buttons.length );
  1291. }
  1292. return buttons;
  1293. } );
  1294. // Active buttons
  1295. DataTable.Api.registerPlural( 'buttons().active()', 'button().active()', function ( flag ) {
  1296. if ( flag === undefined ) {
  1297. return this.map( function ( set ) {
  1298. return set.inst.active( set.node );
  1299. } );
  1300. }
  1301. return this.each( function ( set ) {
  1302. set.inst.active( set.node, flag );
  1303. } );
  1304. } );
  1305. // Get / set button action
  1306. DataTable.Api.registerPlural( 'buttons().action()', 'button().action()', function ( action ) {
  1307. if ( action === undefined ) {
  1308. return this.map( function ( set ) {
  1309. return set.inst.action( set.node );
  1310. } );
  1311. }
  1312. return this.each( function ( set ) {
  1313. set.inst.action( set.node, action );
  1314. } );
  1315. } );
  1316. // Enable / disable buttons
  1317. DataTable.Api.register( ['buttons().enable()', 'button().enable()'], function ( flag ) {
  1318. return this.each( function ( set ) {
  1319. set.inst.enable( set.node, flag );
  1320. } );
  1321. } );
  1322. // Disable buttons
  1323. DataTable.Api.register( ['buttons().disable()', 'button().disable()'], function () {
  1324. return this.each( function ( set ) {
  1325. set.inst.disable( set.node );
  1326. } );
  1327. } );
  1328. // Get button nodes
  1329. DataTable.Api.registerPlural( 'buttons().nodes()', 'button().node()', function () {
  1330. var jq = $();
  1331. // jQuery will automatically reduce duplicates to a single entry
  1332. $( this.each( function ( set ) {
  1333. jq = jq.add( set.inst.node( set.node ) );
  1334. } ) );
  1335. return jq;
  1336. } );
  1337. // Get / set button processing state
  1338. DataTable.Api.registerPlural( 'buttons().processing()', 'button().processing()', function ( flag ) {
  1339. if ( flag === undefined ) {
  1340. return this.map( function ( set ) {
  1341. return set.inst.processing( set.node );
  1342. } );
  1343. }
  1344. return this.each( function ( set ) {
  1345. set.inst.processing( set.node, flag );
  1346. } );
  1347. } );
  1348. // Get / set button text (i.e. the button labels)
  1349. DataTable.Api.registerPlural( 'buttons().text()', 'button().text()', function ( label ) {
  1350. if ( label === undefined ) {
  1351. return this.map( function ( set ) {
  1352. return set.inst.text( set.node );
  1353. } );
  1354. }
  1355. return this.each( function ( set ) {
  1356. set.inst.text( set.node, label );
  1357. } );
  1358. } );
  1359. // Trigger a button's action
  1360. DataTable.Api.registerPlural( 'buttons().trigger()', 'button().trigger()', function () {
  1361. return this.each( function ( set ) {
  1362. set.inst.node( set.node ).trigger( 'click' );
  1363. } );
  1364. } );
  1365. // Button resolver to the popover
  1366. DataTable.Api.register( 'button().popover()', function (content, options) {
  1367. return this.map( function ( set ) {
  1368. return set.inst._popover( content, this.button(this[0].node), options );
  1369. } );
  1370. } );
  1371. // Get the container elements
  1372. DataTable.Api.register( 'buttons().containers()', function () {
  1373. var jq = $();
  1374. var groupSelector = this._groupSelector;
  1375. // We need to use the group selector directly, since if there are no buttons
  1376. // the result set will be empty
  1377. this.iterator( true, 'table', function ( ctx ) {
  1378. if ( ctx._buttons ) {
  1379. var insts = Buttons.instanceSelector( groupSelector, ctx._buttons );
  1380. for ( var i=0, ien=insts.length ; i<ien ; i++ ) {
  1381. jq = jq.add( insts[i].container() );
  1382. }
  1383. }
  1384. } );
  1385. return jq;
  1386. } );
  1387. DataTable.Api.register( 'buttons().container()', function () {
  1388. // API level of nesting is `buttons()` so we can zip into the containers method
  1389. return this.containers().eq(0);
  1390. } );
  1391. // Add a new button
  1392. DataTable.Api.register( 'button().add()', function ( idx, conf ) {
  1393. var ctx = this.context;
  1394. // Don't use `this` as it could be empty - select the instances directly
  1395. if ( ctx.length ) {
  1396. var inst = Buttons.instanceSelector( this._groupSelector, ctx[0]._buttons );
  1397. if ( inst.length ) {
  1398. inst[0].add( conf, idx );
  1399. }
  1400. }
  1401. return this.button( this._groupSelector, idx );
  1402. } );
  1403. // Destroy the button sets selected
  1404. DataTable.Api.register( 'buttons().destroy()', function () {
  1405. this.pluck( 'inst' ).unique().each( function ( inst ) {
  1406. inst.destroy();
  1407. } );
  1408. return this;
  1409. } );
  1410. // Remove a button
  1411. DataTable.Api.registerPlural( 'buttons().remove()', 'buttons().remove()', function () {
  1412. this.each( function ( set ) {
  1413. set.inst.remove( set.node );
  1414. } );
  1415. return this;
  1416. } );
  1417. // Information box that can be used by buttons
  1418. var _infoTimer;
  1419. DataTable.Api.register( 'buttons.info()', function ( title, message, time ) {
  1420. var that = this;
  1421. if ( title === false ) {
  1422. this.off('destroy.btn-info');
  1423. $('#datatables_buttons_info').fadeOut( function () {
  1424. $(this).remove();
  1425. } );
  1426. clearTimeout( _infoTimer );
  1427. _infoTimer = null;
  1428. return this;
  1429. }
  1430. if ( _infoTimer ) {
  1431. clearTimeout( _infoTimer );
  1432. }
  1433. if ( $('#datatables_buttons_info').length ) {
  1434. $('#datatables_buttons_info').remove();
  1435. }
  1436. title = title ? '<h2>'+title+'</h2>' : '';
  1437. $('<div id="datatables_buttons_info" class="dt-button-info"/>')
  1438. .html( title )
  1439. .append( $('<div/>')[ typeof message === 'string' ? 'html' : 'append' ]( message ) )
  1440. .css( 'display', 'none' )
  1441. .appendTo( 'body' )
  1442. .fadeIn();
  1443. if ( time !== undefined && time !== 0 ) {
  1444. _infoTimer = setTimeout( function () {
  1445. that.buttons.info( false );
  1446. }, time );
  1447. }
  1448. this.on('destroy.btn-info', function () {
  1449. that.buttons.info(false);
  1450. });
  1451. return this;
  1452. } );
  1453. // Get data from the table for export - this is common to a number of plug-in
  1454. // buttons so it is included in the Buttons core library
  1455. DataTable.Api.register( 'buttons.exportData()', function ( options ) {
  1456. if ( this.context.length ) {
  1457. return _exportData( new DataTable.Api( this.context[0] ), options );
  1458. }
  1459. } );
  1460. // Get information about the export that is common to many of the export data
  1461. // types (DRY)
  1462. DataTable.Api.register( 'buttons.exportInfo()', function ( conf ) {
  1463. if ( ! conf ) {
  1464. conf = {};
  1465. }
  1466. return {
  1467. filename: _filename( conf ),
  1468. title: _title( conf ),
  1469. messageTop: _message(this, conf.message || conf.messageTop, 'top'),
  1470. messageBottom: _message(this, conf.messageBottom, 'bottom')
  1471. };
  1472. } );
  1473. /**
  1474. * Get the file name for an exported file.
  1475. *
  1476. * @param {object} config Button configuration
  1477. * @param {boolean} incExtension Include the file name extension
  1478. */
  1479. var _filename = function ( config )
  1480. {
  1481. // Backwards compatibility
  1482. var filename = config.filename === '*' && config.title !== '*' && config.title !== undefined && config.title !== null && config.title !== '' ?
  1483. config.title :
  1484. config.filename;
  1485. if ( typeof filename === 'function' ) {
  1486. filename = filename();
  1487. }
  1488. if ( filename === undefined || filename === null ) {
  1489. return null;
  1490. }
  1491. if ( filename.indexOf( '*' ) !== -1 ) {
  1492. filename = $.trim( filename.replace( '*', $('head > title').text() ) );
  1493. }
  1494. // Strip characters which the OS will object to
  1495. filename = filename.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, "");
  1496. var extension = _stringOrFunction( config.extension );
  1497. if ( ! extension ) {
  1498. extension = '';
  1499. }
  1500. return filename + extension;
  1501. };
  1502. /**
  1503. * Simply utility method to allow parameters to be given as a function
  1504. *
  1505. * @param {undefined|string|function} option Option
  1506. * @return {null|string} Resolved value
  1507. */
  1508. var _stringOrFunction = function ( option )
  1509. {
  1510. if ( option === null || option === undefined ) {
  1511. return null;
  1512. }
  1513. else if ( typeof option === 'function' ) {
  1514. return option();
  1515. }
  1516. return option;
  1517. };
  1518. /**
  1519. * Get the title for an exported file.
  1520. *
  1521. * @param {object} config Button configuration
  1522. */
  1523. var _title = function ( config )
  1524. {
  1525. var title = _stringOrFunction( config.title );
  1526. return title === null ?
  1527. null : title.indexOf( '*' ) !== -1 ?
  1528. title.replace( '*', $('head > title').text() || 'Exported data' ) :
  1529. title;
  1530. };
  1531. var _message = function ( dt, option, position )
  1532. {
  1533. var message = _stringOrFunction( option );
  1534. if ( message === null ) {
  1535. return null;
  1536. }
  1537. var caption = $('caption', dt.table().container()).eq(0);
  1538. if ( message === '*' ) {
  1539. var side = caption.css( 'caption-side' );
  1540. if ( side !== position ) {
  1541. return null;
  1542. }
  1543. return caption.length ?
  1544. caption.text() :
  1545. '';
  1546. }
  1547. return message;
  1548. };
  1549. var _exportTextarea = $('<textarea/>')[0];
  1550. var _exportData = function ( dt, inOpts )
  1551. {
  1552. var config = $.extend( true, {}, {
  1553. rows: null,
  1554. columns: '',
  1555. modifier: {
  1556. search: 'applied',
  1557. order: 'applied'
  1558. },
  1559. orthogonal: 'display',
  1560. stripHtml: true,
  1561. stripNewlines: true,
  1562. decodeEntities: true,
  1563. trim: true,
  1564. format: {
  1565. header: function ( d ) {
  1566. return strip( d );
  1567. },
  1568. footer: function ( d ) {
  1569. return strip( d );
  1570. },
  1571. body: function ( d ) {
  1572. return strip( d );
  1573. }
  1574. },
  1575. customizeData: null
  1576. }, inOpts );
  1577. var strip = function ( str ) {
  1578. if ( typeof str !== 'string' ) {
  1579. return str;
  1580. }
  1581. // Always remove script tags
  1582. str = str.replace( /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '' );
  1583. // Always remove comments
  1584. str = str.replace( /<!\-\-.*?\-\->/g, '' );
  1585. if ( config.stripHtml ) {
  1586. str = str.replace( /<[^>]*>/g, '' );
  1587. }
  1588. if ( config.trim ) {
  1589. str = str.replace( /^\s+|\s+$/g, '' );
  1590. }
  1591. if ( config.stripNewlines ) {
  1592. str = str.replace( /\n/g, ' ' );
  1593. }
  1594. if ( config.decodeEntities ) {
  1595. _exportTextarea.innerHTML = str;
  1596. str = _exportTextarea.value;
  1597. }
  1598. return str;
  1599. };
  1600. var header = dt.columns( config.columns ).indexes().map( function (idx) {
  1601. var el = dt.column( idx ).header();
  1602. return config.format.header( el.innerHTML, idx, el );
  1603. } ).toArray();
  1604. var footer = dt.table().footer() ?
  1605. dt.columns( config.columns ).indexes().map( function (idx) {
  1606. var el = dt.column( idx ).footer();
  1607. return config.format.footer( el ? el.innerHTML : '', idx, el );
  1608. } ).toArray() :
  1609. null;
  1610. // If Select is available on this table, and any rows are selected, limit the export
  1611. // to the selected rows. If no rows are selected, all rows will be exported. Specify
  1612. // a `selected` modifier to control directly.
  1613. var modifier = $.extend( {}, config.modifier );
  1614. if ( dt.select && typeof dt.select.info === 'function' && modifier.selected === undefined ) {
  1615. if ( dt.rows( config.rows, $.extend( { selected: true }, modifier ) ).any() ) {
  1616. $.extend( modifier, { selected: true } )
  1617. }
  1618. }
  1619. var rowIndexes = dt.rows( config.rows, modifier ).indexes().toArray();
  1620. var selectedCells = dt.cells( rowIndexes, config.columns );
  1621. var cells = selectedCells
  1622. .render( config.orthogonal )
  1623. .toArray();
  1624. var cellNodes = selectedCells
  1625. .nodes()
  1626. .toArray();
  1627. var columns = header.length;
  1628. var rows = columns > 0 ? cells.length / columns : 0;
  1629. var body = [];
  1630. var cellCounter = 0;
  1631. for ( var i=0, ien=rows ; i<ien ; i++ ) {
  1632. var row = [ columns ];
  1633. for ( var j=0 ; j<columns ; j++ ) {
  1634. row[j] = config.format.body( cells[ cellCounter ], i, j, cellNodes[ cellCounter ] );
  1635. cellCounter++;
  1636. }
  1637. body[i] = row;
  1638. }
  1639. var data = {
  1640. header: header,
  1641. footer: footer,
  1642. body: body
  1643. };
  1644. if ( config.customizeData ) {
  1645. config.customizeData( data );
  1646. }
  1647. return data;
  1648. };
  1649. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  1650. * DataTables interface
  1651. */
  1652. // Attach to DataTables objects for global access
  1653. $.fn.dataTable.Buttons = Buttons;
  1654. $.fn.DataTable.Buttons = Buttons;
  1655. // DataTables creation - check if the buttons have been defined for this table,
  1656. // they will have been if the `B` option was used in `dom`, otherwise we should
  1657. // create the buttons instance here so they can be inserted into the document
  1658. // using the API. Listen for `init` for compatibility with pre 1.10.10, but to
  1659. // be removed in future.
  1660. $(document).on( 'init.dt plugin-init.dt', function (e, settings) {
  1661. if ( e.namespace !== 'dt' ) {
  1662. return;
  1663. }
  1664. var opts = settings.oInit.buttons || DataTable.defaults.buttons;
  1665. if ( opts && ! settings._buttons ) {
  1666. new Buttons( settings, opts ).container();
  1667. }
  1668. } );
  1669. function _init ( settings ) {
  1670. var api = new DataTable.Api( settings );
  1671. var opts = api.init().buttons || DataTable.defaults.buttons;
  1672. return new Buttons( api, opts ).container();
  1673. }
  1674. // DataTables `dom` feature option
  1675. DataTable.ext.feature.push( {
  1676. fnInit: _init,
  1677. cFeature: "B"
  1678. } );
  1679. // DataTables 2 layout feature
  1680. if ( DataTable.ext.features ) {
  1681. DataTable.ext.features.register( 'buttons', _init );
  1682. }
  1683. return Buttons;
  1684. }));