datatables-select.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. /*
  2. * MDBootstrap integration with Datatables
  3. * Learn more: https://mdbootstrap.com/docs/jquery/tables/datatables/
  4. * About MDBootstrap: https://mdbootstrap.com/
  5. *
  6. * Select for DataTables 1.2.7
  7. * 2015-2018 SpryMedia Ltd - datatables.net/license/mit
  8. */
  9. /**
  10. * @summary Select for DataTables
  11. * @description A collection of API methods, events and buttons for DataTables
  12. * that provides selection options of the items in a DataTable
  13. * @version 1.2.7
  14. * @file dataTables.select.js
  15. * @author SpryMedia Ltd (www.sprymedia.co.uk)
  16. * @contact datatables.net/forums
  17. * @copyright Copyright 2015-2018 SpryMedia Ltd.
  18. *
  19. * This source file is free software, available under the following license:
  20. * MIT license - http://datatables.net/license/mit
  21. *
  22. * This source file is distributed in the hope that it will be useful, but
  23. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  24. * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
  25. *
  26. * For details please refer to: http://www.datatables.net/extensions/select
  27. */
  28. (function( factory ){
  29. if ( typeof define === 'function' && define.amd ) {
  30. // AMD
  31. define( ['jquery', 'datatables.net'], function ( $ ) {
  32. return factory( $, window, document );
  33. } );
  34. }
  35. else if ( typeof exports === 'object' ) {
  36. // CommonJS
  37. module.exports = function (root, $) {
  38. if ( ! root ) {
  39. root = window;
  40. }
  41. if ( ! $ || ! $.fn.dataTable ) {
  42. $ = require('datatables.net')(root, $).$;
  43. }
  44. return factory( $, root, root.document );
  45. };
  46. }
  47. else {
  48. // Browser
  49. factory( jQuery, window, document );
  50. }
  51. }(function( $, window, document, undefined ) {
  52. 'use strict';
  53. var DataTable = $.fn.dataTable;
  54. // Version information for debugger
  55. DataTable.select = {};
  56. DataTable.select.version = '1.2.7';
  57. DataTable.select.init = function ( dt ) {
  58. var ctx = dt.settings()[0];
  59. var init = ctx.oInit.select;
  60. var defaults = DataTable.defaults.select;
  61. var opts = init === undefined ?
  62. defaults :
  63. init;
  64. // Set defaults
  65. var items = 'row';
  66. var style = 'api';
  67. var blurable = false;
  68. var info = true;
  69. var selector = 'td, th';
  70. var className = 'selected';
  71. var setStyle = false;
  72. ctx._select = {};
  73. // Initialisation customisations
  74. if ( opts === true ) {
  75. style = 'os';
  76. setStyle = true;
  77. }
  78. else if ( typeof opts === 'string' ) {
  79. style = opts;
  80. setStyle = true;
  81. }
  82. else if ( $.isPlainObject( opts ) ) {
  83. if ( opts.blurable !== undefined ) {
  84. blurable = opts.blurable;
  85. }
  86. if ( opts.info !== undefined ) {
  87. info = opts.info;
  88. }
  89. if ( opts.items !== undefined ) {
  90. items = opts.items;
  91. }
  92. if ( opts.style !== undefined ) {
  93. style = opts.style;
  94. setStyle = true;
  95. }
  96. if ( opts.selector !== undefined ) {
  97. selector = opts.selector;
  98. }
  99. if ( opts.className !== undefined ) {
  100. className = opts.className;
  101. }
  102. }
  103. dt.select.selector( selector );
  104. dt.select.items( items );
  105. dt.select.style( style );
  106. dt.select.blurable( blurable );
  107. dt.select.info( info );
  108. ctx._select.className = className;
  109. // Sort table based on selected rows. Requires Select Datatables extension
  110. $.fn.dataTable.ext.order['select-checkbox'] = function ( settings, col ) {
  111. return this.api().column( col, {order: 'index'} ).nodes().map( function ( td ) {
  112. if ( settings._select.items === 'row' ) {
  113. return $( td ).parent().hasClass( settings._select.className );
  114. } else if ( settings._select.items === 'cell' ) {
  115. return $( td ).hasClass( settings._select.className );
  116. }
  117. return false;
  118. });
  119. };
  120. // If the init options haven't enabled select, but there is a selectable
  121. // class name, then enable
  122. if ( ! setStyle && $( dt.table().node() ).hasClass( 'selectable' ) ) {
  123. dt.select.style( 'os' );
  124. }
  125. };
  126. /*
  127. Select is a collection of API methods, event handlers, event emitters and
  128. buttons (for the `Buttons` extension) for DataTables. It provides the following
  129. features, with an overview of how they are implemented:
  130. ## Selection of rows, columns and cells. Whether an item is selected or not is
  131. stored in:
  132. * rows: a `_select_selected` property which contains a boolean value of the
  133. DataTables' `aoData` object for each row
  134. * columns: a `_select_selected` property which contains a boolean value of the
  135. DataTables' `aoColumns` object for each column
  136. * cells: a `_selected_cells` property which contains an array of boolean values
  137. of the `aoData` object for each row. The array is the same length as the
  138. columns array, with each element of it representing a cell.
  139. This method of using boolean flags allows Select to operate when nodes have not
  140. been created for rows / cells (DataTables' defer rendering feature).
  141. ## API methods
  142. A range of API methods are available for triggering selection and de-selection
  143. of rows. Methods are also available to configure the selection events that can
  144. be triggered by an end user (such as which items are to be selected). To a large
  145. extent, these of API methods *is* Select. It is basically a collection of helper
  146. functions that can be used to select items in a DataTable.
  147. Configuration of select is held in the object `_select` which is attached to the
  148. DataTables settings object on initialisation. Select being available on a table
  149. is not optional when Select is loaded, but its default is for selection only to
  150. be available via the API - so the end user wouldn't be able to select rows
  151. without additional configuration.
  152. The `_select` object contains the following properties:
  153. ```
  154. {
  155. items:string - Can be `rows`, `columns` or `cells`. Defines what item
  156. will be selected if the user is allowed to activate row
  157. selection using the mouse.
  158. style:string - Can be `none`, `single`, `multi` or `os`. Defines the
  159. interaction style when selecting items
  160. blurable:boolean - If row selection can be cleared by clicking outside of
  161. the table
  162. info:boolean - If the selection summary should be shown in the table
  163. information elements
  164. }
  165. ```
  166. In addition to the API methods, Select also extends the DataTables selector
  167. options for rows, columns and cells adding a `selected` option to the selector
  168. options object, allowing the developer to select only selected items or
  169. unselected items.
  170. ## Mouse selection of items
  171. Clicking on items can be used to select items. This is done by a simple event
  172. handler that will select the items using the API methods.
  173. */
  174. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  175. * Local functions
  176. */
  177. /**
  178. * Add one or more cells to the selection when shift clicking in OS selection
  179. * style cell selection.
  180. *
  181. * Cell range is more complicated than row and column as we want to select
  182. * in the visible grid rather than by index in sequence. For example, if you
  183. * click first in cell 1-1 and then shift click in 2-2 - cells 1-2 and 2-1
  184. * should also be selected (and not 1-3, 1-4. etc)
  185. *
  186. * @param {DataTable.Api} dt DataTable
  187. * @param {object} idx Cell index to select to
  188. * @param {object} last Cell index to select from
  189. * @private
  190. */
  191. function cellRange( dt, idx, last )
  192. {
  193. var indexes;
  194. var columnIndexes;
  195. var rowIndexes;
  196. var selectColumns = function ( start, end ) {
  197. if ( start > end ) {
  198. var tmp = end;
  199. end = start;
  200. start = tmp;
  201. }
  202. var record = false;
  203. return dt.columns( ':visible' ).indexes().filter( function (i) {
  204. if ( i === start ) {
  205. record = true;
  206. }
  207. if ( i === end ) { // not else if, as start might === end
  208. record = false;
  209. return true;
  210. }
  211. return record;
  212. } );
  213. };
  214. var selectRows = function ( start, end ) {
  215. var indexes = dt.rows( { search: 'applied' } ).indexes();
  216. // Which comes first - might need to swap
  217. if ( indexes.indexOf( start ) > indexes.indexOf( end ) ) {
  218. var tmp = end;
  219. end = start;
  220. start = tmp;
  221. }
  222. var record = false;
  223. return indexes.filter( function (i) {
  224. if ( i === start ) {
  225. record = true;
  226. }
  227. if ( i === end ) {
  228. record = false;
  229. return true;
  230. }
  231. return record;
  232. } );
  233. };
  234. if ( ! dt.cells( { selected: true } ).any() && ! last ) {
  235. // select from the top left cell to this one
  236. columnIndexes = selectColumns( 0, idx.column );
  237. rowIndexes = selectRows( 0 , idx.row );
  238. }
  239. else {
  240. // Get column indexes between old and new
  241. columnIndexes = selectColumns( last.column, idx.column );
  242. rowIndexes = selectRows( last.row , idx.row );
  243. }
  244. indexes = dt.cells( rowIndexes, columnIndexes ).flatten();
  245. if ( ! dt.cells( idx, { selected: true } ).any() ) {
  246. // Select range
  247. dt.cells( indexes ).select();
  248. }
  249. else {
  250. // Deselect range
  251. dt.cells( indexes ).deselect();
  252. }
  253. }
  254. /**
  255. * Disable mouse selection by removing the selectors
  256. *
  257. * @param {DataTable.Api} dt DataTable to remove events from
  258. * @private
  259. */
  260. function disableMouseSelection( dt )
  261. {
  262. var ctx = dt.settings()[0];
  263. var selector = ctx._select.selector;
  264. $( dt.table().container() )
  265. .off( 'mousedown.dtSelect', selector )
  266. .off( 'mouseup.dtSelect', selector )
  267. .off( 'click.dtSelect', selector );
  268. $('body').off( 'click.dtSelect' + dt.table().node().id );
  269. }
  270. /**
  271. * Attach mouse listeners to the table to allow mouse selection of items
  272. *
  273. * @param {DataTable.Api} dt DataTable to remove events from
  274. * @private
  275. */
  276. function enableMouseSelection ( dt )
  277. {
  278. var container = $( dt.table().container() );
  279. var ctx = dt.settings()[0];
  280. var selector = ctx._select.selector;
  281. var matchSelection;
  282. container
  283. .on( 'mousedown.dtSelect', selector, function(e) {
  284. // Disallow text selection for shift clicking on the table so multi
  285. // element selection doesn't look terrible!
  286. if ( e.shiftKey || e.metaKey || e.ctrlKey ) {
  287. container
  288. .css( '-moz-user-select', 'none' )
  289. .one('selectstart.dtSelect', selector, function () {
  290. return false;
  291. } );
  292. }
  293. if ( window.getSelection ) {
  294. matchSelection = window.getSelection();
  295. }
  296. } )
  297. .on( 'mouseup.dtSelect', selector, function() {
  298. // Allow text selection to occur again, Mozilla style (tested in FF
  299. // 35.0.1 - still required)
  300. container.css( '-moz-user-select', '' );
  301. } )
  302. .on( 'click.dtSelect', selector, function ( e ) {
  303. var items = dt.select.items();
  304. var idx;
  305. // If text was selected (click and drag), then we shouldn't change
  306. // the row's selected state
  307. if ( window.getSelection ) {
  308. var selection = window.getSelection();
  309. // If the element that contains the selection is not in the table, we can ignore it
  310. // This can happen if the developer selects text from the click event
  311. if ( ! selection.anchorNode || $(selection.anchorNode).closest('table')[0] === dt.table().node() ) {
  312. if ( selection !== matchSelection ) {
  313. return;
  314. }
  315. }
  316. }
  317. var ctx = dt.settings()[0];
  318. var wrapperClass = dt.settings()[0].oClasses.sWrapper.replace(/ /g, '.');
  319. // Ignore clicks inside a sub-table
  320. if ( $(e.target).closest('div.'+wrapperClass)[0] != dt.table().container() ) {
  321. return;
  322. }
  323. var cell = dt.cell( $(e.target).closest('td, th') );
  324. // Check the cell actually belongs to the host DataTable (so child
  325. // rows, etc, are ignored)
  326. if ( ! cell.any() ) {
  327. return;
  328. }
  329. var event = $.Event('user-select.dt');
  330. eventTrigger( dt, event, [ items, cell, e ] );
  331. if ( event.isDefaultPrevented() ) {
  332. return;
  333. }
  334. var cellIndex = cell.index();
  335. if ( items === 'row' ) {
  336. idx = cellIndex.row;
  337. typeSelect( e, dt, ctx, 'row', idx );
  338. }
  339. else if ( items === 'column' ) {
  340. idx = cell.index().column;
  341. typeSelect( e, dt, ctx, 'column', idx );
  342. }
  343. else if ( items === 'cell' ) {
  344. idx = cell.index();
  345. typeSelect( e, dt, ctx, 'cell', idx );
  346. }
  347. ctx._select_lastCell = cellIndex;
  348. } );
  349. // Blurable
  350. $('body').on( 'click.dtSelect' + dt.table().node().id, function ( e ) {
  351. if ( ctx._select.blurable ) {
  352. // If the click was inside the DataTables container, don't blur
  353. if ( $(e.target).parents().filter( dt.table().container() ).length ) {
  354. return;
  355. }
  356. // Ignore elements which have been removed from the DOM (i.e. paging
  357. // buttons)
  358. if ( $(e.target).parents('html').length === 0 ) {
  359. return;
  360. }
  361. // Don't blur in Editor form
  362. if ( $(e.target).parents('div.DTE').length ) {
  363. return;
  364. }
  365. clear( ctx, true );
  366. }
  367. } );
  368. }
  369. /**
  370. * Trigger an event on a DataTable
  371. *
  372. * @param {DataTable.Api} api DataTable to trigger events on
  373. * @param {boolean} selected true if selected, false if deselected
  374. * @param {string} type Item type acting on
  375. * @param {boolean} any Require that there are values before
  376. * triggering
  377. * @private
  378. */
  379. function eventTrigger ( api, type, args, any )
  380. {
  381. if ( any && ! api.flatten().length ) {
  382. return;
  383. }
  384. if ( typeof type === 'string' ) {
  385. type = type +'.dt';
  386. }
  387. args.unshift( api );
  388. $(api.table().node()).trigger( type, args );
  389. }
  390. /**
  391. * Update the information element of the DataTable showing information about the
  392. * items selected. This is done by adding tags to the existing text
  393. *
  394. * @param {DataTable.Api} api DataTable to update
  395. * @private
  396. */
  397. function info ( api )
  398. {
  399. var ctx = api.settings()[0];
  400. if ( ! ctx._select.info || ! ctx.aanFeatures.i ) {
  401. return;
  402. }
  403. if ( api.select.style() === 'api' ) {
  404. return;
  405. }
  406. var rows = api.rows( { selected: true } ).flatten().length;
  407. var columns = api.columns( { selected: true } ).flatten().length;
  408. var cells = api.cells( { selected: true } ).flatten().length;
  409. var add = function ( el, name, num ) {
  410. el.append( $('<span class="select-item"/>').append( api.i18n(
  411. 'select.'+name+'s',
  412. { _: '%d '+name+'s selected', 0: '', 1: '1 '+name+' selected' },
  413. num
  414. ) ) );
  415. };
  416. // Internal knowledge of DataTables to loop over all information elements
  417. $.each( ctx.aanFeatures.i, function ( i, el ) {
  418. el = $(el);
  419. var output = $('<span class="select-info"/>');
  420. add( output, 'row', rows );
  421. add( output, 'column', columns );
  422. add( output, 'cell', cells );
  423. var exisiting = el.children('span.select-info');
  424. if ( exisiting.length ) {
  425. exisiting.remove();
  426. }
  427. if ( output.text() !== '' ) {
  428. el.append( output );
  429. }
  430. } );
  431. }
  432. /**
  433. * Initialisation of a new table. Attach event handlers and callbacks to allow
  434. * Select to operate correctly.
  435. *
  436. * This will occur _after_ the initial DataTables initialisation, although
  437. * before Ajax data is rendered, if there is ajax data
  438. *
  439. * @param {DataTable.settings} ctx Settings object to operate on
  440. * @private
  441. */
  442. function init ( ctx ) {
  443. var api = new DataTable.Api( ctx );
  444. // Row callback so that classes can be added to rows and cells if the item
  445. // was selected before the element was created. This will happen with the
  446. // `deferRender` option enabled.
  447. //
  448. // This method of attaching to `aoRowCreatedCallback` is a hack until
  449. // DataTables has proper events for row manipulation If you are reviewing
  450. // this code to create your own plug-ins, please do not do this!
  451. ctx.aoRowCreatedCallback.push( {
  452. fn: function ( row, data, index ) {
  453. var i, ien;
  454. var d = ctx.aoData[ index ];
  455. // Row
  456. if ( d._select_selected ) {
  457. $( row ).addClass( ctx._select.className );
  458. }
  459. // Cells and columns - if separated out, we would need to do two
  460. // loops, so it makes sense to combine them into a single one
  461. for ( i=0, ien=ctx.aoColumns.length ; i<ien ; i++ ) {
  462. if ( ctx.aoColumns[i]._select_selected || (d._selected_cells && d._selected_cells[i]) ) {
  463. $(d.anCells[i]).addClass( ctx._select.className );
  464. }
  465. }
  466. },
  467. sName: 'select-deferRender'
  468. } );
  469. // On Ajax reload we want to reselect all rows which are currently selected,
  470. // if there is an rowId (i.e. a unique value to identify each row with)
  471. api.on( 'preXhr.dt.dtSelect', function () {
  472. // note that column selection doesn't need to be cached and then
  473. // reselected, as they are already selected
  474. var rows = api.rows( { selected: true } ).ids( true ).filter( function ( d ) {
  475. return d !== undefined;
  476. } );
  477. var cells = api.cells( { selected: true } ).eq(0).map( function ( cellIdx ) {
  478. var id = api.row( cellIdx.row ).id( true );
  479. return id ?
  480. { row: id, column: cellIdx.column } :
  481. undefined;
  482. } ).filter( function ( d ) {
  483. return d !== undefined;
  484. } );
  485. // On the next draw, reselect the currently selected items
  486. api.one( 'draw.dt.dtSelect', function () {
  487. api.rows( rows ).select();
  488. // `cells` is not a cell index selector, so it needs a loop
  489. if ( cells.any() ) {
  490. cells.each( function ( id ) {
  491. api.cells( id.row, id.column ).select();
  492. } );
  493. }
  494. } );
  495. } );
  496. // Update the table information element with selected item summary
  497. api.on( 'draw.dtSelect.dt select.dtSelect.dt deselect.dtSelect.dt info.dt', function () {
  498. info( api );
  499. } );
  500. // Clean up and release
  501. api.on( 'destroy.dtSelect', function () {
  502. disableMouseSelection( api );
  503. api.off( '.dtSelect' );
  504. } );
  505. }
  506. /**
  507. * Add one or more items (rows or columns) to the selection when shift clicking
  508. * in OS selection style
  509. *
  510. * @param {DataTable.Api} dt DataTable
  511. * @param {string} type Row or column range selector
  512. * @param {object} idx Item index to select to
  513. * @param {object} last Item index to select from
  514. * @private
  515. */
  516. function rowColumnRange( dt, type, idx, last )
  517. {
  518. // Add a range of rows from the last selected row to this one
  519. var indexes = dt[type+'s']( { search: 'applied' } ).indexes();
  520. var idx1 = $.inArray( last, indexes );
  521. var idx2 = $.inArray( idx, indexes );
  522. if ( ! dt[type+'s']( { selected: true } ).any() && idx1 === -1 ) {
  523. // select from top to here - slightly odd, but both Windows and Mac OS
  524. // do this
  525. indexes.splice( $.inArray( idx, indexes )+1, indexes.length );
  526. }
  527. else {
  528. // reverse so we can shift click 'up' as well as down
  529. if ( idx1 > idx2 ) {
  530. var tmp = idx2;
  531. idx2 = idx1;
  532. idx1 = tmp;
  533. }
  534. indexes.splice( idx2+1, indexes.length );
  535. indexes.splice( 0, idx1 );
  536. }
  537. if ( ! dt[type]( idx, { selected: true } ).any() ) {
  538. // Select range
  539. dt[type+'s']( indexes ).select();
  540. }
  541. else {
  542. // Deselect range - need to keep the clicked on row selected
  543. indexes.splice( $.inArray( idx, indexes ), 1 );
  544. dt[type+'s']( indexes ).deselect();
  545. }
  546. }
  547. /**
  548. * Clear all selected items
  549. *
  550. * @param {DataTable.settings} ctx Settings object of the host DataTable
  551. * @param {boolean} [force=false] Force the de-selection to happen, regardless
  552. * of selection style
  553. * @private
  554. */
  555. function clear( ctx, force )
  556. {
  557. if ( force || ctx._select.style === 'single' ) {
  558. var api = new DataTable.Api( ctx );
  559. api.rows( { selected: true } ).deselect();
  560. api.columns( { selected: true } ).deselect();
  561. api.cells( { selected: true } ).deselect();
  562. }
  563. }
  564. /**
  565. * Select items based on the current configuration for style and items.
  566. *
  567. * @param {object} e Mouse event object
  568. * @param {DataTables.Api} dt DataTable
  569. * @param {DataTable.settings} ctx Settings object of the host DataTable
  570. * @param {string} type Items to select
  571. * @param {int|object} idx Index of the item to select
  572. * @private
  573. */
  574. function typeSelect ( e, dt, ctx, type, idx )
  575. {
  576. var style = dt.select.style();
  577. var isSelected = dt[type]( idx, { selected: true } ).any();
  578. if ( style === 'os' ) {
  579. if ( e.ctrlKey || e.metaKey ) {
  580. // Add or remove from the selection
  581. dt[type]( idx ).select( ! isSelected );
  582. }
  583. else if ( e.shiftKey ) {
  584. if ( type === 'cell' ) {
  585. cellRange( dt, idx, ctx._select_lastCell || null );
  586. }
  587. else {
  588. rowColumnRange( dt, type, idx, ctx._select_lastCell ?
  589. ctx._select_lastCell[type] :
  590. null
  591. );
  592. }
  593. }
  594. else {
  595. // No cmd or shift click - deselect if selected, or select
  596. // this row only
  597. var selected = dt[type+'s']( { selected: true } );
  598. if ( isSelected && selected.flatten().length === 1 ) {
  599. dt[type]( idx ).deselect();
  600. }
  601. else {
  602. selected.deselect();
  603. dt[type]( idx ).select();
  604. }
  605. }
  606. } else if ( style == 'multi+shift' ) {
  607. if ( e.shiftKey ) {
  608. if ( type === 'cell' ) {
  609. cellRange( dt, idx, ctx._select_lastCell || null );
  610. }
  611. else {
  612. rowColumnRange( dt, type, idx, ctx._select_lastCell ?
  613. ctx._select_lastCell[type] :
  614. null
  615. );
  616. }
  617. }
  618. else {
  619. dt[ type ]( idx ).select( ! isSelected );
  620. }
  621. }
  622. else {
  623. dt[ type ]( idx ).select( ! isSelected );
  624. }
  625. }
  626. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  627. * DataTables selectors
  628. */
  629. // row and column are basically identical just assigned to different properties
  630. // and checking a different array, so we can dynamically create the functions to
  631. // reduce the code size
  632. $.each( [
  633. { type: 'row', prop: 'aoData' },
  634. { type: 'column', prop: 'aoColumns' }
  635. ], function ( i, o ) {
  636. DataTable.ext.selector[ o.type ].push( function ( settings, opts, indexes ) {
  637. var selected = opts.selected;
  638. var data;
  639. var out = [];
  640. if ( selected !== true && selected !== false ) {
  641. return indexes;
  642. }
  643. for ( var i=0, ien=indexes.length ; i<ien ; i++ ) {
  644. data = settings[ o.prop ][ indexes[i] ];
  645. if ( (selected === true && data._select_selected === true) ||
  646. (selected === false && ! data._select_selected )
  647. ) {
  648. out.push( indexes[i] );
  649. }
  650. }
  651. return out;
  652. } );
  653. } );
  654. DataTable.ext.selector.cell.push( function ( settings, opts, cells ) {
  655. var selected = opts.selected;
  656. var rowData;
  657. var out = [];
  658. if ( selected === undefined ) {
  659. return cells;
  660. }
  661. for ( var i=0, ien=cells.length ; i<ien ; i++ ) {
  662. rowData = settings.aoData[ cells[i].row ];
  663. if ( (selected === true && rowData._selected_cells && rowData._selected_cells[ cells[i].column ] === true) ||
  664. (selected === false && ( ! rowData._selected_cells || ! rowData._selected_cells[ cells[i].column ] ) )
  665. ) {
  666. out.push( cells[i] );
  667. }
  668. }
  669. return out;
  670. } );
  671. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  672. * DataTables API
  673. *
  674. * For complete documentation, please refer to the docs/api directory or the
  675. * DataTables site
  676. */
  677. // Local variables to improve compression
  678. var apiRegister = DataTable.Api.register;
  679. var apiRegisterPlural = DataTable.Api.registerPlural;
  680. apiRegister( 'select()', function () {
  681. return this.iterator( 'table', function ( ctx ) {
  682. DataTable.select.init( new DataTable.Api( ctx ) );
  683. } );
  684. } );
  685. apiRegister( 'select.blurable()', function ( flag ) {
  686. if ( flag === undefined ) {
  687. return this.context[0]._select.blurable;
  688. }
  689. return this.iterator( 'table', function ( ctx ) {
  690. ctx._select.blurable = flag;
  691. } );
  692. } );
  693. apiRegister( 'select.info()', function ( flag ) {
  694. if ( info === undefined ) {
  695. return this.context[0]._select.info;
  696. }
  697. return this.iterator( 'table', function ( ctx ) {
  698. ctx._select.info = flag;
  699. } );
  700. } );
  701. apiRegister( 'select.items()', function ( items ) {
  702. if ( items === undefined ) {
  703. return this.context[0]._select.items;
  704. }
  705. return this.iterator( 'table', function ( ctx ) {
  706. ctx._select.items = items;
  707. eventTrigger( new DataTable.Api( ctx ), 'selectItems', [ items ] );
  708. } );
  709. } );
  710. // Takes effect from the _next_ selection. None disables future selection, but
  711. // does not clear the current selection. Use the `deselect` methods for that
  712. apiRegister( 'select.style()', function ( style ) {
  713. if ( style === undefined ) {
  714. return this.context[0]._select.style;
  715. }
  716. return this.iterator( 'table', function ( ctx ) {
  717. ctx._select.style = style;
  718. if ( ! ctx._select_init ) {
  719. init( ctx );
  720. }
  721. // Add / remove mouse event handlers. They aren't required when only
  722. // API selection is available
  723. var dt = new DataTable.Api( ctx );
  724. disableMouseSelection( dt );
  725. if ( style !== 'api' ) {
  726. enableMouseSelection( dt );
  727. }
  728. eventTrigger( new DataTable.Api( ctx ), 'selectStyle', [ style ] );
  729. } );
  730. } );
  731. apiRegister( 'select.selector()', function ( selector ) {
  732. if ( selector === undefined ) {
  733. return this.context[0]._select.selector;
  734. }
  735. return this.iterator( 'table', function ( ctx ) {
  736. disableMouseSelection( new DataTable.Api( ctx ) );
  737. ctx._select.selector = selector;
  738. if ( ctx._select.style !== 'api' ) {
  739. enableMouseSelection( new DataTable.Api( ctx ) );
  740. }
  741. } );
  742. } );
  743. apiRegisterPlural( 'rows().select()', 'row().select()', function ( select ) {
  744. var api = this;
  745. if ( select === false ) {
  746. return this.deselect();
  747. }
  748. this.iterator( 'row', function ( ctx, idx ) {
  749. clear( ctx );
  750. ctx.aoData[ idx ]._select_selected = true;
  751. $( ctx.aoData[ idx ].nTr ).addClass( ctx._select.className );
  752. } );
  753. this.iterator( 'table', function ( ctx, i ) {
  754. eventTrigger( api, 'select', [ 'row', api[i] ], true );
  755. } );
  756. return this;
  757. } );
  758. apiRegisterPlural( 'columns().select()', 'column().select()', function ( select ) {
  759. var api = this;
  760. if ( select === false ) {
  761. return this.deselect();
  762. }
  763. this.iterator( 'column', function ( ctx, idx ) {
  764. clear( ctx );
  765. ctx.aoColumns[ idx ]._select_selected = true;
  766. var column = new DataTable.Api( ctx ).column( idx );
  767. $( column.header() ).addClass( ctx._select.className );
  768. $( column.footer() ).addClass( ctx._select.className );
  769. column.nodes().to$().addClass( ctx._select.className );
  770. } );
  771. this.iterator( 'table', function ( ctx, i ) {
  772. eventTrigger( api, 'select', [ 'column', api[i] ], true );
  773. } );
  774. return this;
  775. } );
  776. apiRegisterPlural( 'cells().select()', 'cell().select()', function ( select ) {
  777. var api = this;
  778. if ( select === false ) {
  779. return this.deselect();
  780. }
  781. this.iterator( 'cell', function ( ctx, rowIdx, colIdx ) {
  782. clear( ctx );
  783. var data = ctx.aoData[ rowIdx ];
  784. if ( data._selected_cells === undefined ) {
  785. data._selected_cells = [];
  786. }
  787. data._selected_cells[ colIdx ] = true;
  788. if ( data.anCells ) {
  789. $( data.anCells[ colIdx ] ).addClass( ctx._select.className );
  790. }
  791. } );
  792. this.iterator( 'table', function ( ctx, i ) {
  793. eventTrigger( api, 'select', [ 'cell', api[i] ], true );
  794. } );
  795. return this;
  796. } );
  797. apiRegisterPlural( 'rows().deselect()', 'row().deselect()', function () {
  798. var api = this;
  799. this.iterator( 'row', function ( ctx, idx ) {
  800. ctx.aoData[ idx ]._select_selected = false;
  801. $( ctx.aoData[ idx ].nTr ).removeClass( ctx._select.className );
  802. } );
  803. this.iterator( 'table', function ( ctx, i ) {
  804. eventTrigger( api, 'deselect', [ 'row', api[i] ], true );
  805. } );
  806. return this;
  807. } );
  808. apiRegisterPlural( 'columns().deselect()', 'column().deselect()', function () {
  809. var api = this;
  810. this.iterator( 'column', function ( ctx, idx ) {
  811. ctx.aoColumns[ idx ]._select_selected = false;
  812. var api = new DataTable.Api( ctx );
  813. var column = api.column( idx );
  814. $( column.header() ).removeClass( ctx._select.className );
  815. $( column.footer() ).removeClass( ctx._select.className );
  816. // Need to loop over each cell, rather than just using
  817. // `column().nodes()` as cells which are individually selected should
  818. // not have the `selected` class removed from them
  819. api.cells( null, idx ).indexes().each( function (cellIdx) {
  820. var data = ctx.aoData[ cellIdx.row ];
  821. var cellSelected = data._selected_cells;
  822. if ( data.anCells && (! cellSelected || ! cellSelected[ cellIdx.column ]) ) {
  823. $( data.anCells[ cellIdx.column ] ).removeClass( ctx._select.className );
  824. }
  825. } );
  826. } );
  827. this.iterator( 'table', function ( ctx, i ) {
  828. eventTrigger( api, 'deselect', [ 'column', api[i] ], true );
  829. } );
  830. return this;
  831. } );
  832. apiRegisterPlural( 'cells().deselect()', 'cell().deselect()', function () {
  833. var api = this;
  834. this.iterator( 'cell', function ( ctx, rowIdx, colIdx ) {
  835. var data = ctx.aoData[ rowIdx ];
  836. data._selected_cells[ colIdx ] = false;
  837. // Remove class only if the cells exist, and the cell is not column
  838. // selected, in which case the class should remain (since it is selected
  839. // in the column)
  840. if ( data.anCells && ! ctx.aoColumns[ colIdx ]._select_selected ) {
  841. $( data.anCells[ colIdx ] ).removeClass( ctx._select.className );
  842. }
  843. } );
  844. this.iterator( 'table', function ( ctx, i ) {
  845. eventTrigger( api, 'deselect', [ 'cell', api[i] ], true );
  846. } );
  847. return this;
  848. } );
  849. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  850. * Buttons
  851. */
  852. function i18n( label, def ) {
  853. return function (dt) {
  854. return dt.i18n( 'buttons.'+label, def );
  855. };
  856. }
  857. // Common events with suitable namespaces
  858. function namespacedEvents ( config ) {
  859. var unique = config._eventNamespace;
  860. return 'draw.dt.DT'+unique+' select.dt.DT'+unique+' deselect.dt.DT'+unique;
  861. }
  862. function enabled ( dt, config ) {
  863. if ( $.inArray( 'rows', config.limitTo ) !== -1 && dt.rows( { selected: true } ).any() ) {
  864. return true;
  865. }
  866. if ( $.inArray( 'columns', config.limitTo ) !== -1 && dt.columns( { selected: true } ).any() ) {
  867. return true;
  868. }
  869. if ( $.inArray( 'cells', config.limitTo ) !== -1 && dt.cells( { selected: true } ).any() ) {
  870. return true;
  871. }
  872. return false;
  873. }
  874. var _buttonNamespace = 0;
  875. $.extend( DataTable.ext.buttons, {
  876. selected: {
  877. text: i18n( 'selected', 'Selected' ),
  878. className: 'buttons-selected',
  879. limitTo: [ 'rows', 'columns', 'cells' ],
  880. init: function ( dt, node, config ) {
  881. var that = this;
  882. config._eventNamespace = '.select'+(_buttonNamespace++);
  883. // .DT namespace listeners are removed by DataTables automatically
  884. // on table destroy
  885. dt.on( namespacedEvents(config), function () {
  886. that.enable( enabled(dt, config) );
  887. } );
  888. this.disable();
  889. },
  890. destroy: function ( dt, node, config ) {
  891. dt.off( config._eventNamespace );
  892. }
  893. },
  894. selectedSingle: {
  895. text: i18n( 'selectedSingle', 'Selected single' ),
  896. className: 'buttons-selected-single',
  897. init: function ( dt, node, config ) {
  898. var that = this;
  899. config._eventNamespace = '.select'+(_buttonNamespace++);
  900. dt.on( namespacedEvents(config), function () {
  901. var count = dt.rows( { selected: true } ).flatten().length +
  902. dt.columns( { selected: true } ).flatten().length +
  903. dt.cells( { selected: true } ).flatten().length;
  904. that.enable( count === 1 );
  905. } );
  906. this.disable();
  907. },
  908. destroy: function ( dt, node, config ) {
  909. dt.off( config._eventNamespace );
  910. }
  911. },
  912. selectAll: {
  913. text: i18n( 'selectAll', 'Select all' ),
  914. className: 'buttons-select-all',
  915. action: function () {
  916. var items = this.select.items();
  917. this[ items+'s' ]().select();
  918. }
  919. },
  920. selectNone: {
  921. text: i18n( 'selectNone', 'Deselect all' ),
  922. className: 'buttons-select-none',
  923. action: function () {
  924. clear( this.settings()[0], true );
  925. },
  926. init: function ( dt, node, config ) {
  927. var that = this;
  928. config._eventNamespace = '.select'+(_buttonNamespace++);
  929. dt.on( namespacedEvents(config), function () {
  930. var count = dt.rows( { selected: true } ).flatten().length +
  931. dt.columns( { selected: true } ).flatten().length +
  932. dt.cells( { selected: true } ).flatten().length;
  933. that.enable( count > 0 );
  934. } );
  935. this.disable();
  936. },
  937. destroy: function ( dt, node, config ) {
  938. dt.off( config._eventNamespace );
  939. }
  940. }
  941. } );
  942. $.each( [ 'Row', 'Column', 'Cell' ], function ( i, item ) {
  943. var lc = item.toLowerCase();
  944. DataTable.ext.buttons[ 'select'+item+'s' ] = {
  945. text: i18n( 'select'+item+'s', 'Select '+lc+'s' ),
  946. className: 'buttons-select-'+lc+'s',
  947. action: function () {
  948. this.select.items( lc );
  949. },
  950. init: function ( dt ) {
  951. var that = this;
  952. dt.on( 'selectItems.dt.DT', function ( e, ctx, items ) {
  953. that.active( items === lc );
  954. } );
  955. }
  956. };
  957. } );
  958. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  959. * Initialisation
  960. */
  961. // DataTables creation - check if select has been defined in the options. Note
  962. // this required that the table be in the document! If it isn't then something
  963. // needs to trigger this method unfortunately. The next major release of
  964. // DataTables will rework the events and address this.
  965. $(document).on( 'preInit.dt.dtSelect', function (e, ctx) {
  966. if ( e.namespace !== 'dt' ) {
  967. return;
  968. }
  969. DataTable.select.init( new DataTable.Api( ctx ) );
  970. } );
  971. return DataTable.select;
  972. }));