8
0

inserttablecommand.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 { findOptimalInsertionPosition } from '@ckeditor/ckeditor5-widget/src/utils';
  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 insertPosition = findOptimalInsertionPosition( selection, model );
  50. model.change( writer => {
  51. const table = tableUtils.createTable( writer, rows, columns );
  52. model.insertContent( table, insertPosition );
  53. writer.setSelection( writer.createPositionAt( table.getNodeByPath( [ 0, 0, 0 ] ), 0 ) );
  54. } );
  55. }
  56. }
  57. // Returns valid parent to insert table
  58. //
  59. // @param {module:engine/model/position} position
  60. function getInsertTableParent( position ) {
  61. const parent = position.parent;
  62. return parent === parent.root ? parent : parent.parent;
  63. }