paragraphcommand.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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/paragraphcommand
  7. */
  8. import Command from '@ckeditor/ckeditor5-core/src/command';
  9. import first from '@ckeditor/ckeditor5-utils/src/first';
  10. /**
  11. * The paragraph command.
  12. *
  13. * @extends module:core/command~Command
  14. */
  15. export default class ParagraphCommand extends Command {
  16. /**
  17. * The value of the command. Indicates whether the selection start is placed in a paragraph.
  18. *
  19. * @readonly
  20. * @observable
  21. * @member {Boolean} #value
  22. */
  23. /**
  24. * @inheritDoc
  25. */
  26. refresh() {
  27. const model = this.editor.model;
  28. const document = model.document;
  29. const block = first( document.selection.getSelectedBlocks() );
  30. this.value = !!block && block.is( 'paragraph' );
  31. this.isEnabled = !!block && checkCanBecomeParagraph( block, model.schema );
  32. }
  33. /**
  34. * Executes the command. All the blocks (see {@link module:engine/model/schema~Schema}) in the selection
  35. * will be turned to paragraphs.
  36. *
  37. * @fires execute
  38. * @param {Object} [options] Options for the executed command.
  39. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} [options.selection]
  40. * The selection that the command should be applied to.
  41. * By default, if not provided, the command is applied to the {@link module:engine/model/document~Document#selection}.
  42. */
  43. execute( options = {} ) {
  44. const model = this.editor.model;
  45. const document = model.document;
  46. model.change( writer => {
  47. const blocks = ( options.selection || document.selection ).getSelectedBlocks();
  48. for ( const block of blocks ) {
  49. if ( !block.is( 'paragraph' ) && checkCanBecomeParagraph( block, model.schema ) ) {
  50. writer.rename( block, 'paragraph' );
  51. }
  52. }
  53. } );
  54. }
  55. }
  56. // Checks whether the given block can be replaced by a paragraph.
  57. //
  58. // @private
  59. // @param {module:engine/model/element~Element} block A block to be tested.
  60. // @param {module:engine/model/schema~Schema} schema The schema of the document.
  61. // @returns {Boolean}
  62. function checkCanBecomeParagraph( block, schema ) {
  63. return schema.checkChild( block.parent, 'paragraph' ) && !schema.isObject( block );
  64. }