inserttablecommand.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * @license Copyright (c) 2003-2019, 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 `'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. * @fires execute
  41. */
  42. execute( options = {} ) {
  43. const model = this.editor.model;
  44. const selection = model.document.selection;
  45. const tableUtils = this.editor.plugins.get( 'TableUtils' );
  46. const rows = parseInt( options.rows ) || 2;
  47. const columns = parseInt( options.columns ) || 2;
  48. const insertPosition = findOptimalInsertionPosition( selection, model );
  49. model.change( writer => {
  50. const table = tableUtils.createTable( writer, rows, columns );
  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. }