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/insertcolumncommand
|
7 | */
|
8 | import { Command } from 'ckeditor5/src/core';
|
9 | /**
|
10 | * The insert column command.
|
11 | *
|
12 | * The command is registered by {@link module:table/tableediting~TableEditing} as the `'insertTableColumnLeft'` and
|
13 | * `'insertTableColumnRight'` editor commands.
|
14 | *
|
15 | * To insert a column to the left of the selected cell, execute the following command:
|
16 | *
|
17 | * ```ts
|
18 | * editor.execute( 'insertTableColumnLeft' );
|
19 | * ```
|
20 | *
|
21 | * To insert a column to the right of the selected cell, execute the following command:
|
22 | *
|
23 | * ```ts
|
24 | * editor.execute( 'insertTableColumnRight' );
|
25 | * ```
|
26 | */
|
27 | export default class InsertColumnCommand extends Command {
|
28 | /**
|
29 | * Creates a new `InsertColumnCommand` instance.
|
30 | *
|
31 | * @param editor An editor on which this command will be used.
|
32 | * @param options.order The order of insertion relative to the column in which the caret is located.
|
33 | * Possible values: `"left"` and `"right"`. Default value is "right".
|
34 | */
|
35 | constructor(editor, options = {}) {
|
36 | super(editor);
|
37 | this.order = options.order || 'right';
|
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 column to the `'left'` or `'right'` of the column
|
52 | * in which the selection is set.
|
53 | *
|
54 | * @fires execute
|
55 | */
|
56 | execute() {
|
57 | const editor = this.editor;
|
58 | const selection = editor.model.document.selection;
|
59 | const tableUtils = editor.plugins.get('TableUtils');
|
60 | const insertBefore = this.order === 'left';
|
61 | const affectedTableCells = tableUtils.getSelectionAffectedTableCells(selection);
|
62 | const columnIndexes = tableUtils.getColumnIndexes(affectedTableCells);
|
63 | const column = insertBefore ? columnIndexes.first : columnIndexes.last;
|
64 | const table = affectedTableCells[0].findAncestor('table');
|
65 | tableUtils.insertColumns(table, { columns: 1, at: insertBefore ? column : column + 1 });
|
66 | }
|
67 | }
|