removecolumncommand.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module table/commands/removecolumncommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import TableWalker from '../tablewalker';
  10. import { findAncestor, updateNumericAttribute } from './utils';
  11. /**
  12. * The remove column command.
  13. *
  14. * The command is registered by {@link module:table/tableediting~TableEditing} as `'removeTableColumn'` editor command.
  15. *
  16. * To remove the column containing the selected cell, execute the command:
  17. *
  18. * editor.execute( 'removeTableColumn' );
  19. *
  20. * @extends module:core/command~Command
  21. */
  22. export default class RemoveColumnCommand extends Command {
  23. /**
  24. * @inheritDoc
  25. */
  26. refresh() {
  27. const editor = this.editor;
  28. const selection = editor.model.document.selection;
  29. const tableUtils = editor.plugins.get( 'TableUtils' );
  30. const tableCell = findAncestor( 'tableCell', selection.getFirstPosition() );
  31. this.isEnabled = !!tableCell && tableUtils.getColumns( tableCell.parent.parent ) > 1;
  32. }
  33. /**
  34. * @inheritDoc
  35. */
  36. execute() {
  37. const model = this.editor.model;
  38. const selection = model.document.selection;
  39. const firstPosition = selection.getFirstPosition();
  40. const tableCell = findAncestor( 'tableCell', firstPosition );
  41. const tableRow = tableCell.parent;
  42. const table = tableRow.parent;
  43. const headingColumns = table.getAttribute( 'headingColumns' ) || 0;
  44. const row = table.getChildIndex( tableRow );
  45. // Cache the table before removing or updating colspans.
  46. const tableMap = [ ...new TableWalker( table ) ];
  47. // Get column index of removed column.
  48. const cellData = tableMap.find( value => value.cell === tableCell );
  49. const removedColumn = cellData.column;
  50. model.change( writer => {
  51. // Update heading columns attribute if removing a row from head section.
  52. if ( headingColumns && row <= headingColumns ) {
  53. writer.setAttribute( 'headingColumns', headingColumns - 1, table );
  54. }
  55. for ( const { cell, column, colspan } of tableMap ) {
  56. // If colspaned cell overlaps removed column decrease it's span.
  57. if ( column <= removedColumn && colspan > 1 && column + colspan > removedColumn ) {
  58. updateNumericAttribute( 'colspan', colspan - 1, cell, writer );
  59. } else if ( column === removedColumn ) {
  60. // The cell in removed column has colspan of 1.
  61. writer.remove( cell );
  62. }
  63. }
  64. } );
  65. }
  66. }