dataTables.select.js 30 KB

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