inserttablecommand.js 2.3 KB

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