insertparagraphcommand.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 paragraph/insertparagraphcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. /**
  10. * The insert paragraph command. It inserts a new paragraph at a specific
  11. * {@link module:engine/model/position~Position document position}.
  12. *
  13. * // Insert a new paragraph before an element in the document.
  14. * editor.execute( 'insertParagraph', {
  15. * position: editor.model.createPositionBefore( element )
  16. * } );
  17. *
  18. * If a paragraph is disallowed in the context of the specific position, the command
  19. * will attempt to split position ancestors to find a place where it is possible
  20. * to insert a paragraph.
  21. *
  22. * **Note**: This command moves the selection to the inserted paragraph.
  23. *
  24. * @extends module:core/command~Command
  25. */
  26. export default class InsertParagraphCommand extends Command {
  27. /**
  28. * Executes the command.
  29. *
  30. * @param {Object} options Options for the executed command.
  31. * @param {module:engine/model/position~Position} options.position The model position at which
  32. * the new paragraph will be inserted.
  33. * @fires execute
  34. */
  35. execute( options ) {
  36. const model = this.editor.model;
  37. let position = options.position;
  38. model.change( writer => {
  39. const paragraph = writer.createElement( 'paragraph' );
  40. if ( !model.schema.checkChild( position.parent, paragraph ) ) {
  41. const allowedParent = model.schema.findAllowedParent( position, paragraph );
  42. // It could be there's no ancestor limit that would allow paragraph.
  43. // In theory, "paragraph" could be disallowed even in the "$root".
  44. if ( !allowedParent ) {
  45. return;
  46. }
  47. position = writer.split( position, allowedParent ).position;
  48. }
  49. model.insertContent( paragraph, position );
  50. writer.setSelection( paragraph, 'in' );
  51. } );
  52. }
  53. }