splitcellcommand.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/splitcellcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findAncestor } from './utils';
  10. import { getTableCellsInSelection } from '../tableselection/utils';
  11. /**
  12. * The split cell command.
  13. *
  14. * The command is registered by {@link module:table/tableediting~TableEditing} as the `'splitTableCellVertically'`
  15. * and `'splitTableCellHorizontally'` editor commands.
  16. *
  17. * You can split any cell vertically or horizontally by executing this command. For example, to split the selected table cell vertically:
  18. *
  19. * editor.execute( 'splitTableCellVertically' );
  20. *
  21. * @extends module:core/command~Command
  22. */
  23. export default class SplitCellCommand extends Command {
  24. /**
  25. * Creates a new `SplitCellCommand` instance.
  26. *
  27. * @param {module:core/editor/editor~Editor} editor The editor on which this command will be used.
  28. * @param {Object} options
  29. * @param {String} options.direction Indicates whether the command should split cells `'horizontally'` or `'vertically'`.
  30. */
  31. constructor( editor, options = {} ) {
  32. super( editor );
  33. /**
  34. * The direction that indicates which cell will be split.
  35. *
  36. * @readonly
  37. * @member {String} #direction
  38. */
  39. this.direction = options.direction || 'horizontally';
  40. }
  41. /**
  42. * @inheritDoc
  43. */
  44. refresh() {
  45. const selectedCells = getTableCellsInSelection( this.editor.model.document.selection, true );
  46. this.isEnabled = selectedCells.length === 1;
  47. }
  48. /**
  49. * @inheritDoc
  50. */
  51. execute() {
  52. const model = this.editor.model;
  53. const document = model.document;
  54. const selection = document.selection;
  55. const firstPosition = selection.getFirstPosition();
  56. const tableCell = findAncestor( 'tableCell', firstPosition );
  57. const isHorizontally = this.direction === 'horizontally';
  58. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  59. if ( isHorizontally ) {
  60. tableUtils.splitCellHorizontally( tableCell, 2 );
  61. } else {
  62. tableUtils.splitCellVertically( tableCell, 2 );
  63. }
  64. }
  65. }