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 */
5/**
6 * Injects a table caption post-fixer into the model.
7 *
8 * The role of the table caption post-fixer is to ensure that the table with caption have the correct structure
9 * after a {@link module:engine/model/model~Model#change `change()`} block was executed.
10 *
11 * The correct structure means that:
12 *
13 * * If there are many caption model element, they are merged into one model.
14 * * A final, merged caption model is placed at the end of the table.
15 */
16export default function injectTableCaptionPostFixer(model) {
17 model.document.registerPostFixer(writer => tableCaptionPostFixer(writer, model));
18}
19/**
20 * The table caption post-fixer.
21 */
22function tableCaptionPostFixer(writer, model) {
23 const changes = model.document.differ.getChanges();
24 let wasFixed = false;
25 for (const entry of changes) {
26 if (entry.type != 'insert') {
27 continue;
28 }
29 const positionParent = entry.position.parent;
30 if (positionParent.is('element', 'table') || entry.name == 'table') {
31 const table = (entry.name == 'table' ? entry.position.nodeAfter : positionParent);
32 const captionsToMerge = Array.from(table.getChildren())
33 .filter((child) => child.is('element', 'caption'));
34 const firstCaption = captionsToMerge.shift();
35 if (!firstCaption) {
36 continue;
37 }
38 // Move all the contents of the captions to the first one.
39 for (const caption of captionsToMerge) {
40 writer.move(writer.createRangeIn(caption), firstCaption, 'end');
41 writer.remove(caption);
42 }
43 // Make sure the final caption is at the end of the table.
44 if (firstCaption.nextSibling) {
45 writer.move(writer.createRangeOn(firstCaption), table, 'end');
46 wasFixed = true;
47 }
48 // Do we merged captions and/or moved the single caption to the end of the table?
49 wasFixed = !!captionsToMerge.length || wasFixed;
50 }
51 }
52 return wasFixed;
53}