Skip to content

Build your personal knowledge base with Trilium Notes

fix(ckeditor): don't crash pasting a format over mixed formatting (closes #11977)

Swastik Tripathi2f179c2d1792
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts
index 30cb318856..617a3e0732 100644
--- a/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.spec.ts
@@ -140,6 +140,16 @@ describe("FormatPainterEditing", () => {
expect(data).not.toContain("italic");
});
+ it("clears formatting that only part of the target carries", () => {
+ copyCommand().value = { italic: true };
+
+ // Clearing `bold` merges the three text nodes into one.
+ setModelData(editor.model, "<paragraph>[f<$text bold=\"true\">o</$text>o]</paragraph>");
+ pasteCommand().execute();
+
+ expect(model()).toBe("<paragraph><$text italic=\"true\">foo</$text></paragraph>");
+ });
+
it("applies stored formatting as selection attributes at a collapsed caret, clearing existing ones", () => {
copyCommand().value = { bold: true };
diff --git a/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts
index 34a33f8342..f4fb74ab98 100644
--- a/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts
+++ b/packages/ckeditor5/src/plugins/format_painter/format_painter_editing.ts
@@ -1,4 +1,4 @@
-import { Command, type Editor, Plugin } from "ckeditor5";
+import { Command, type Editor, type ModelRange, Plugin } from "ckeditor5";
import { COPY_FORMAT_COMMAND, PASTE_FORMAT_COMMAND } from "./constants.js";
@@ -156,17 +156,24 @@ function applyFormatting(editor: Editor, formatting: FormattingAttributes): void
for (const range of [ ...selection.getRanges() ]) {
// Clearing first is what makes the paste replace the target's formatting rather than
// layer onto it. Attribute edits never shift offsets, so `range` stays valid afterwards.
- for (const item of [ ...range.getItems() ]) {
+ // Clearing a text node can merge it with its neighbors and detach the text proxies read
+ // before the change, so every item range is created before anything is cleared.
+ const clears: [ ModelRange, string[] ][] = [];
+
+ for (const item of range.getItems()) {
if (!item.is("$textProxy")) {
continue;
}
- const itemRange = writer.createRangeOn(item);
+ const names = [ ...item.getAttributeKeys() ]
+ .filter((name) => schema.getAttributeProperties(name).isFormatting);
+
+ clears.push([ writer.createRangeOn(item), names ]);
+ }
- for (const name of [ ...item.getAttributeKeys() ]) {
- if (schema.getAttributeProperties(name).isFormatting) {
- writer.removeAttribute(name, itemRange);
- }
+ for (const [ itemRange, names ] of clears) {
+ for (const name of names) {
+ writer.removeAttribute(name, itemRange);
}
}