insertcolumncommand.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/insertcolumncommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findAncestor } from './utils';
  10. /**
  11. * The insert column command.
  12. *
  13. * The command is registered by {@link module:table/tableediting~TableEditing} as `'insertTableColumnLeft'` and
  14. * `'insertTableColumnRight'` editor commands.
  15. *
  16. * To insert a column to the left of the selected cell, execute the following command:
  17. *
  18. * editor.execute( 'insertTableColumnLeft' );
  19. *
  20. * To insert a column to the right of the selected cell, execute the following command:
  21. *
  22. * editor.execute( 'insertTableColumnRight' );
  23. *
  24. * @extends module:core/command~Command
  25. */
  26. export default class InsertColumnCommand extends Command {
  27. /**
  28. * Creates a new `InsertColumnCommand` instance.
  29. *
  30. * @param {module:core/editor/editor~Editor} editor An editor on which this command will be used.
  31. * @param {Object} options
  32. * @param {String} [options.order="right"] The order of insertion relative to the column in which the caret is located.
  33. * Possible values: `"left"` and `"right"`.
  34. */
  35. constructor( editor, options = {} ) {
  36. super( editor );
  37. /**
  38. * The order of insertion relative to the column in which the caret is located.
  39. *
  40. * @readonly
  41. * @member {String} module:table/commands/insertcolumncommand~InsertColumnCommand#order
  42. */
  43. this.order = options.order || 'right';
  44. }
  45. /**
  46. * @inheritDoc
  47. */
  48. refresh() {
  49. const selection = this.editor.model.document.selection;
  50. const tableParent = findAncestor( 'table', selection.getFirstPosition() );
  51. this.isEnabled = !!tableParent;
  52. }
  53. /**
  54. * Executes the command.
  55. *
  56. * Depending on the command's {@link #order} value, it inserts a column to the `'left'` or `'right'` of the column
  57. * in which the selection is set.
  58. *
  59. * @fires execute
  60. */
  61. execute() {
  62. const editor = this.editor;
  63. const selection = editor.model.document.selection;
  64. const tableUtils = editor.plugins.get( 'TableUtils' );
  65. const firstPosition = selection.getFirstPosition();
  66. const tableCell = findAncestor( 'tableCell', firstPosition );
  67. const table = tableCell.parent.parent;
  68. const { column } = tableUtils.getCellLocation( tableCell );
  69. const insertAt = this.order === 'right' ? column + 1 : column;
  70. tableUtils.insertColumns( table, { columns: 1, at: insertAt } );
  71. }
  72. }