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 | /**
|
6 | * @module table/commands/insertrowcommand
|
7 | */
|
8 | import { Command } from 'ckeditor5/src/core';
|
9 | /**
|
10 | * The insert row command.
|
11 | *
|
12 | * The command is registered by {@link module:table/tableediting~TableEditing} as the `'insertTableRowBelow'` and
|
13 | * `'insertTableRowAbove'` editor commands.
|
14 | *
|
15 | * To insert a row below the selected cell, execute the following command:
|
16 | *
|
17 | * ```ts
|
18 | * editor.execute( 'insertTableRowBelow' );
|
19 | * ```
|
20 | *
|
21 | * To insert a row above the selected cell, execute the following command:
|
22 | *
|
23 | * ```ts
|
24 | * editor.execute( 'insertTableRowAbove' );
|
25 | * ```
|
26 | */
|
27 | export default class InsertRowCommand extends Command {
|
28 | /**
|
29 | * Creates a new `InsertRowCommand` instance.
|
30 | *
|
31 | * @param editor The editor on which this command will be used.
|
32 | * @param options.order The order of insertion relative to the row in which the caret is located.
|
33 | * Possible values: `"above"` and `"below"`. Default value is "below"
|
34 | */
|
35 | constructor(editor, options = {}) {
|
36 | super(editor);
|
37 | this.order = options.order || 'below';
|
38 | }
|
39 | /**
|
40 | * @inheritDoc
|
41 | */
|
42 | refresh() {
|
43 | const selection = this.editor.model.document.selection;
|
44 | const tableUtils = this.editor.plugins.get('TableUtils');
|
45 | const isAnyCellSelected = !!tableUtils.getSelectionAffectedTableCells(selection).length;
|
46 | this.isEnabled = isAnyCellSelected;
|
47 | }
|
48 | /**
|
49 | * Executes the command.
|
50 | *
|
51 | * Depending on the command's {@link #order} value, it inserts a row `'below'` or `'above'` the row in which selection is set.
|
52 | *
|
53 | * @fires execute
|
54 | */
|
55 | execute() {
|
56 | const editor = this.editor;
|
57 | const selection = editor.model.document.selection;
|
58 | const tableUtils = editor.plugins.get('TableUtils');
|
59 | const insertAbove = this.order === 'above';
|
60 | const affectedTableCells = tableUtils.getSelectionAffectedTableCells(selection);
|
61 | const rowIndexes = tableUtils.getRowIndexes(affectedTableCells);
|
62 | const row = insertAbove ? rowIndexes.first : rowIndexes.last;
|
63 | const table = affectedTableCells[0].findAncestor('table');
|
64 | tableUtils.insertRows(table, { at: insertAbove ? row : row + 1, copyStructureFromAbove: !insertAbove });
|
65 | }
|
66 | }
|