insertrowcommand.js 2.3 KB

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