selectcolumncommand.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 { getSelectionAffectedTableCells } from '../utils/selection';
  11. /**
  12. * The select column command.
  13. *
  14. * The command is registered by {@link module:table/tableediting~TableEditing} as the `'selectTableColumn'` editor command.
  15. *
  16. * To select the columns containing the selected cells, execute the command:
  17. *
  18. * editor.execute( 'selectTableColumn' );
  19. *
  20. * @extends module:core/command~Command
  21. */
  22. export default class SelectColumnCommand extends Command {
  23. /**
  24. * @inheritDoc
  25. */
  26. refresh() {
  27. const selectedCells = getSelectionAffectedTableCells( this.editor.model.document.selection );
  28. this.isEnabled = selectedCells.length > 0;
  29. }
  30. /**
  31. * @inheritDoc
  32. */
  33. execute() {
  34. const model = this.editor.model;
  35. const referenceCells = getSelectionAffectedTableCells( model.document.selection );
  36. const firstCell = referenceCells[ 0 ];
  37. const lastCell = referenceCells.pop();
  38. const table = firstCell.findAncestor( 'table' );
  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( table, { startColumn, endColumn } ) ) {
  46. rangesToSelect.push( model.createRangeOn( cellInfo.cell ) );
  47. }
  48. model.change( writer => {
  49. writer.setSelection( rangesToSelect );
  50. } );
  51. }
  52. }