removecolumncommand.js 2.2 KB

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