1 | /**
|
2 | * @license Copyright (c) 2003-2023, 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 | import { Command } from 'ckeditor5/src/core';
|
6 | import { isFirstBlockOfListItem, isListItemBlock, sortBlocks, splitListItemBefore } from './utils/model';
|
7 | /**
|
8 | * The document list split command that splits the list item at the selection.
|
9 | *
|
10 | * It is used by the {@link module:list/documentlist~DocumentList document list feature}.
|
11 | */
|
12 | export default class DocumentListSplitCommand extends Command {
|
13 | /**
|
14 | * Creates an instance of the command.
|
15 | *
|
16 | * @param editor The editor instance.
|
17 | * @param direction Whether list item should be split before or after the selected block.
|
18 | */
|
19 | constructor(editor, direction) {
|
20 | super(editor);
|
21 | this._direction = direction;
|
22 | }
|
23 | /**
|
24 | * @inheritDoc
|
25 | */
|
26 | refresh() {
|
27 | this.isEnabled = this._checkEnabled();
|
28 | }
|
29 | /**
|
30 | * Splits the list item at the selection.
|
31 | *
|
32 | * @fires execute
|
33 | * @fires afterExecute
|
34 | */
|
35 | execute() {
|
36 | const editor = this.editor;
|
37 | editor.model.change(writer => {
|
38 | const changedBlocks = splitListItemBefore(this._getStartBlock(), writer);
|
39 | this._fireAfterExecute(changedBlocks);
|
40 | });
|
41 | }
|
42 | /**
|
43 | * Fires the `afterExecute` event.
|
44 | *
|
45 | * @param changedBlocks The changed list elements.
|
46 | */
|
47 | _fireAfterExecute(changedBlocks) {
|
48 | this.fire('afterExecute', sortBlocks(new Set(changedBlocks)));
|
49 | }
|
50 | /**
|
51 | * Checks whether the command can be enabled in the current context.
|
52 | *
|
53 | * @returns Whether the command should be enabled.
|
54 | */
|
55 | _checkEnabled() {
|
56 | const selection = this.editor.model.document.selection;
|
57 | const block = this._getStartBlock();
|
58 | return selection.isCollapsed &&
|
59 | isListItemBlock(block) &&
|
60 | !isFirstBlockOfListItem(block);
|
61 | }
|
62 | /**
|
63 | * Returns the model element that is the main focus of the command (according to the current selection and command direction).
|
64 | */
|
65 | _getStartBlock() {
|
66 | const doc = this.editor.model.document;
|
67 | const positionParent = doc.selection.getFirstPosition().parent;
|
68 | return (this._direction == 'before' ? positionParent : positionParent.nextSibling);
|
69 | }
|
70 | }
|