UNPKG

2.46 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 heading/headingcommand
7 */
8import { Command } from 'ckeditor5/src/core.js';
9import { first } from 'ckeditor5/src/utils.js';
10/**
11 * The heading command. It is used by the {@link module:heading/heading~Heading heading feature} to apply headings.
12 */
13export default class HeadingCommand extends Command {
14 /**
15 * Creates an instance of the command.
16 *
17 * @param editor Editor instance.
18 * @param modelElements Names of the element which this command can apply in the model.
19 */
20 constructor(editor, modelElements) {
21 super(editor);
22 this.modelElements = modelElements;
23 }
24 /**
25 * @inheritDoc
26 */
27 refresh() {
28 const block = first(this.editor.model.document.selection.getSelectedBlocks());
29 this.value = !!block && this.modelElements.includes(block.name) && block.name;
30 this.isEnabled = !!block && this.modelElements.some(heading => checkCanBecomeHeading(block, heading, this.editor.model.schema));
31 }
32 /**
33 * Executes the command. Applies the heading to the selected blocks or, if the first selected
34 * block is a heading already, turns selected headings (of this level only) to paragraphs.
35 *
36 * @param options.value Name of the element which this command will apply in the model.
37 * @fires execute
38 */
39 execute(options) {
40 const model = this.editor.model;
41 const document = model.document;
42 const modelElement = options.value;
43 model.change(writer => {
44 const blocks = Array.from(document.selection.getSelectedBlocks())
45 .filter(block => {
46 return checkCanBecomeHeading(block, modelElement, model.schema);
47 });
48 for (const block of blocks) {
49 if (!block.is('element', modelElement)) {
50 writer.rename(block, modelElement);
51 }
52 }
53 });
54 }
55}
56/**
57 * Checks whether the given block can be replaced by a specific heading.
58 *
59 * @param block A block to be tested.
60 * @param heading Command element name in the model.
61 * @param schema The schema of the document.
62 */
63function checkCanBecomeHeading(block, heading, schema) {
64 return schema.checkChild(block.parent, heading) && !schema.isObject(block);
65}