UNPKG

2.25 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 TableWalker from '../tablewalker';
6/**
7 * A table headings refresh handler which marks the table cells or rows in the differ to have it re-rendered
8 * if the headings attribute changed.
9 *
10 * Table heading rows and heading columns are represented in the model by a `headingRows` and `headingColumns` attributes.
11 *
12 * When table headings attribute changes, all the cells/rows are marked to re-render to change between `<td>` and `<th>`.
13 */
14export default function tableHeadingsRefreshHandler(model, editing) {
15 const differ = model.document.differ;
16 for (const change of differ.getChanges()) {
17 let table;
18 let isRowChange = false;
19 if (change.type == 'attribute') {
20 const element = change.range.start.nodeAfter;
21 if (!element || !element.is('element', 'table')) {
22 continue;
23 }
24 if (change.attributeKey != 'headingRows' && change.attributeKey != 'headingColumns') {
25 continue;
26 }
27 table = element;
28 isRowChange = change.attributeKey == 'headingRows';
29 }
30 else if (change.name == 'tableRow' || change.name == 'tableCell') {
31 table = change.position.findAncestor('table');
32 isRowChange = change.name == 'tableRow';
33 }
34 if (!table) {
35 continue;
36 }
37 const headingRows = table.getAttribute('headingRows') || 0;
38 const headingColumns = table.getAttribute('headingColumns') || 0;
39 const tableWalker = new TableWalker(table);
40 for (const tableSlot of tableWalker) {
41 const isHeading = tableSlot.row < headingRows || tableSlot.column < headingColumns;
42 const expectedElementName = isHeading ? 'th' : 'td';
43 const viewElement = editing.mapper.toViewElement(tableSlot.cell);
44 if (viewElement && viewElement.is('element') && viewElement.name != expectedElementName) {
45 editing.reconvertItem((isRowChange ? tableSlot.cell.parent : tableSlot.cell));
46 }
47 }
48 }
49}