dataTables.buttons.js 45 KB

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