選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

dataTables.select.js 39KB

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