inserttablecommand.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/inserttablecommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import { findOptimalInsertionPosition } from '@ckeditor/ckeditor5-widget/src/utils';
  10. /**
  11. * The insert table command.
  12. *
  13. * The command is registered by {@link module:table/tableediting~TableEditing} as the `'insertTable'` editor command.
  14. *
  15. * To insert a table at the current selection, execute the command and specify the dimensions:
  16. *
  17. * editor.execute( 'insertTable', { rows: 20, columns: 5 } );
  18. *
  19. * @extends module:core/command~Command
  20. */
  21. export default class InsertTableCommand extends Command {
  22. /**
  23. * @inheritDoc
  24. */
  25. refresh() {
  26. const model = this.editor.model;
  27. const selection = model.document.selection;
  28. const schema = model.schema;
  29. const validParent = getInsertTableParent( selection.getFirstPosition() );
  30. this.isEnabled = schema.checkChild( validParent, 'table' );
  31. }
  32. /**
  33. * Executes the command.
  34. *
  35. * Inserts a table with the given number of rows and columns into the editor.
  36. *
  37. * @param {Object} options
  38. * @param {Number} [options.rows=2] The number of rows to create in the inserted table.
  39. * @param {Number} [options.columns=2] The number of columns to create in the inserted table.
  40. * @param {Number} [options.headingRows=0] The number of heading rows.
  41. * @param {Number} [options.headingColumns=0] The number of heading columns.
  42. * @fires execute
  43. */
  44. execute( options = {} ) {
  45. const model = this.editor.model;
  46. const selection = model.document.selection;
  47. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  48. const insertPosition = findOptimalInsertionPosition( selection, model );
  49. model.change( writer => {
  50. const table = tableUtils.createTable( writer, options );
  51. model.insertContent( table, insertPosition );
  52. writer.setSelection( writer.createPositionAt( table.getNodeByPath( [ 0, 0, 0 ] ), 0 ) );
  53. } );
  54. }
  55. }
  56. // Returns valid parent to insert table
  57. //
  58. // @param {module:engine/model/position} position
  59. function getInsertTableParent( position ) {
  60. const parent = position.parent;
  61. return parent === parent.root ? parent : parent.parent;
  62. }