dataTables.buttons.js 50 KB

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