UNPKG

2.68 kBJavaScriptView Raw
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 */
5import { Command } from 'ckeditor5/src/core';
6/**
7 * The table cell attribute command.
8 *
9 * This command is a base command for other table property commands.
10 */
11export default class TablePropertyCommand extends Command {
12 /**
13 * Creates a new `TablePropertyCommand` instance.
14 *
15 * @param editor An editor in which this command will be used.
16 * @param attributeName Table cell attribute name.
17 * @param defaultValue The default value of the attribute.
18 */
19 constructor(editor, attributeName, defaultValue) {
20 super(editor);
21 this.attributeName = attributeName;
22 this._defaultValue = defaultValue;
23 }
24 /**
25 * @inheritDoc
26 */
27 refresh() {
28 const editor = this.editor;
29 const selection = editor.model.document.selection;
30 const table = selection.getFirstPosition().findAncestor('table');
31 this.isEnabled = !!table;
32 this.value = this._getValue(table);
33 }
34 /**
35 * Executes the command.
36 *
37 * @fires execute
38 * @param options.value If set, the command will set the attribute on the selected table.
39 * If not set, the command will remove the attribute from the selected table.
40 * @param options.batch Pass the model batch instance to the command to aggregate changes,
41 * for example, to allow a single undo step for multiple executions.
42 */
43 execute(options = {}) {
44 const model = this.editor.model;
45 const selection = model.document.selection;
46 const { value, batch } = options;
47 const table = selection.getFirstPosition().findAncestor('table');
48 const valueToSet = this._getValueToSet(value);
49 model.enqueueChange(batch, writer => {
50 if (valueToSet) {
51 writer.setAttribute(this.attributeName, valueToSet, table);
52 }
53 else {
54 writer.removeAttribute(this.attributeName, table);
55 }
56 });
57 }
58 /**
59 * Returns the attribute value for a table.
60 */
61 _getValue(table) {
62 if (!table) {
63 return;
64 }
65 const value = table.getAttribute(this.attributeName);
66 if (value === this._defaultValue) {
67 return;
68 }
69 return value;
70 }
71 /**
72 * Returns the proper model value. It can be used to add a default unit to numeric values.
73 */
74 _getValueToSet(value) {
75 if (value === this._defaultValue) {
76 return;
77 }
78 return value;
79 }
80}