dataTables.select.js 32 KB

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