UNPKG

2.4 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4 */
5/**
6 * @module paragraph/paragraphcommand
7 */
8import { Command } from '@ckeditor/ckeditor5-core';
9import { first } from '@ckeditor/ckeditor5-utils';
10/**
11 * The paragraph command.
12 */
13export default class ParagraphCommand extends Command {
14 constructor(editor) {
15 super(editor);
16 // Since this command may pass selection in execution block, it should be checked directly.
17 this._isEnabledBasedOnSelection = false;
18 }
19 /**
20 * @inheritDoc
21 */
22 refresh() {
23 const model = this.editor.model;
24 const document = model.document;
25 const block = first(document.selection.getSelectedBlocks());
26 this.value = !!block && block.is('element', 'paragraph');
27 this.isEnabled = !!block && checkCanBecomeParagraph(block, model.schema);
28 }
29 /**
30 * Executes the command. All the blocks (see {@link module:engine/model/schema~Schema}) in the selection
31 * will be turned to paragraphs.
32 *
33 * @fires execute
34 * @param options Options for the executed command.
35 * @param options.selection The selection that the command should be applied to. By default,
36 * if not provided, the command is applied to the {@link module:engine/model/document~Document#selection}.
37 */
38 execute(options = {}) {
39 const model = this.editor.model;
40 const document = model.document;
41 const selection = options.selection || document.selection;
42 // Don't execute command if selection is in non-editable place.
43 if (!model.canEditAt(selection)) {
44 return;
45 }
46 model.change(writer => {
47 const blocks = selection.getSelectedBlocks();
48 for (const block of blocks) {
49 if (!block.is('element', 'paragraph') && checkCanBecomeParagraph(block, model.schema)) {
50 writer.rename(block, 'paragraph');
51 }
52 }
53 });
54 }
55}
56/**
57 * Checks whether the given block can be replaced by a paragraph.
58 *
59 * @param block A block to be tested.
60 * @param schema The schema of the document.
61 */
62function checkCanBecomeParagraph(block, schema) {
63 return schema.checkChild(block.parent, 'paragraph') && !schema.isObject(block);
64}