UNPKG

2.56 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';
6import { normalizeColumnWidths } from './utils';
7/**
8 * Command used by the {@link module:table/tablecolumnresize~TableColumnResize Table column resize feature} that
9 * updates the width of the whole table as well as its individual columns.
10 */
11export default class TableWidthsCommand extends Command {
12 /**
13 * @inheritDoc
14 */
15 refresh() {
16 // The command is always enabled as it doesn't care about the actual selection - table can be resized
17 // even if the selection is elsewhere.
18 this.isEnabled = true;
19 }
20 /**
21 * Updated the `tableWidth` attribute of the table and the `columnWidth` attribute of the columns of that table.
22 */
23 execute(options = {}) {
24 const { model, plugins } = this.editor;
25 let { table = model.document.selection.getSelectedElement(), columnWidths, tableWidth } = options;
26 if (columnWidths) {
27 // For backwards compatibility, columnWidths might be an array or a string of comma-separated values.
28 columnWidths = Array.isArray(columnWidths) ?
29 columnWidths :
30 columnWidths.split(',');
31 }
32 model.change(writer => {
33 if (tableWidth) {
34 writer.setAttribute('tableWidth', tableWidth, table);
35 }
36 else {
37 writer.removeAttribute('tableWidth', table);
38 }
39 const tableColumnGroup = plugins
40 .get('TableColumnResizeEditing')
41 .getColumnGroupElement(table);
42 if (!columnWidths && !tableColumnGroup) {
43 return;
44 }
45 if (!columnWidths) {
46 return writer.remove(tableColumnGroup);
47 }
48 const widths = normalizeColumnWidths(columnWidths);
49 if (!tableColumnGroup) {
50 const colGroupElement = writer.createElement('tableColumnGroup');
51 widths.forEach(columnWidth => writer.appendElement('tableColumn', { columnWidth }, colGroupElement));
52 writer.append(colGroupElement, table);
53 }
54 else {
55 Array
56 .from(tableColumnGroup.getChildren())
57 .forEach((column, index) => writer.setAttribute('columnWidth', widths[index], column));
58 }
59 });
60 }
61}