selectcolumncommand.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module table/commands/selectcolumncommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import TableWalker from '../tablewalker';
  10. import { findAncestor } from './utils';
  11. import { getSelectionAffectedTableCells } from '../utils/selection';
  12. /**
  13. * The select column command.
  14. *
  15. * The command is registered by {@link module:table/tableediting~TableEditing} as the `'selectTableColumn'` editor command.
  16. *
  17. * To select the columns containing the selected cells, execute the command:
  18. *
  19. * editor.execute( 'selectTableColumn' );
  20. *
  21. * @extends module:core/command~Command
  22. */
  23. export default class SelectColumnCommand extends Command {
  24. /**
  25. * @inheritDoc
  26. */
  27. refresh() {
  28. const selectedCells = getSelectionAffectedTableCells( this.editor.model.document.selection );
  29. this.isEnabled = selectedCells.length > 0;
  30. }
  31. /**
  32. * @inheritDoc
  33. */
  34. execute() {
  35. const model = this.editor.model;
  36. const referenceCells = getSelectionAffectedTableCells( model.document.selection );
  37. const firstCell = referenceCells[ 0 ];
  38. const lastCell = referenceCells.pop();
  39. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  40. const startLocation = tableUtils.getCellLocation( firstCell );
  41. const endLocation = tableUtils.getCellLocation( lastCell );
  42. const startColumn = Math.min( startLocation.column, endLocation.column );
  43. const endColumn = Math.max( startLocation.column, endLocation.column );
  44. const rangesToSelect = [];
  45. for ( const cellInfo of new TableWalker( findAncestor( 'table', firstCell ) ) ) {
  46. if ( cellInfo.column >= startColumn && cellInfo.column <= endColumn ) {
  47. rangesToSelect.push( model.createRangeOn( cellInfo.cell ) );
  48. }
  49. }
  50. model.change( writer => {
  51. writer.setSelection( rangesToSelect );
  52. } );
  53. }
  54. }