removecolumncommand.js 2.4 KB

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