diff --git a/packages/core/src/editor/normalizeBlockNesting.test.ts b/packages/core/src/editor/normalizeBlockNesting.test.ts new file mode 100644 index 0000000000..00332803d9 --- /dev/null +++ b/packages/core/src/editor/normalizeBlockNesting.test.ts @@ -0,0 +1,281 @@ +// @vitest-environment jsdom +import { TextSelection } from "@tiptap/pm/state"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; + +import { BlockNoteEditor } from "./BlockNoteEditor.js"; +import { normalizeBlockNesting } from "./normalizeBlockNesting.js"; + +let editor: BlockNoteEditor; + +beforeEach(() => { + editor = BlockNoteEditor.create({ + initialContent: [ + { + id: "parent", + type: "paragraph", + content: "Parent", + children: [ + { + id: "child", + type: "paragraph", + content: "Child", + children: [ + { + id: "grandchild", + type: "paragraph", + content: [ + { type: "text", text: "Grandchild", styles: { bold: true } }, + ], + }, + ], + }, + { id: "cousin", type: "paragraph", content: "Cousin" }, + ], + }, + { id: "sibling", type: "paragraph", content: "Sibling" }, + { + id: "target", + type: "paragraph", + content: "Target", + children: [ + { id: "nested", type: "paragraph", content: "Nested target" }, + ], + }, + ], + trailingBlock: false, + }); + editor.mount(document.createElement("div")); +}); + +afterEach(() => { + vi.restoreAllMocks(); + editor.unmount(); + editor._tiptapEditor.destroy(); +}); + +function position(id: string, offset: number) { + let found: number | undefined; + editor.prosemirrorState.doc.descendants((node, pos) => { + if (node.type.name === "blockContainer" && node.attrs.id === id) { + found = pos + 2 + offset; + } + }); + if (found === undefined) { + throw new Error(`Missing fixture block: ${id}`); + } + return found; +} + +function selection(from: readonly [string, number], to = from) { + return TextSelection.create( + editor.prosemirrorState.doc, + position(...from), + position(...to), + ); +} + +function clipboardHTML(source: TextSelection) { + return editor.prosemirrorView.serializeForClipboard(source.content()).dom + .innerHTML; +} + +function expectUndo(doc: typeof editor.prosemirrorState.doc) { + editor.prosemirrorState.doc.check(); + expect(editor.undo()).toBe(true); + expect(editor.prosemirrorState.doc.eq(doc)).toBe(true); +} + +it.each([ + ["external", "child"], + ["external-deep", "child"], + ["external", "grandchild"], + ["copy", "child"], + ["move", "child"], + ["move", "grandchild"], +] as const)("normalizes a %s drop starting in %s", (mode, from) => { + const view = editor.prosemirrorView; + const doc = view.state.doc; + const source = + from === "child" + ? selection(["child", 0], ["sibling", 7]) + : selection(["grandchild", 1], ["cousin", 3]); + const slice = source.content(); + const normalized = normalizeBlockNesting(slice); + expect(normalizeBlockNesting(normalized).eq(normalized)).toBe(true); + const html = clipboardHTML(source); + const internal = mode === "copy" || mode === "move"; + const destination = internal + ? source + : selection([mode === "external-deep" ? "nested" : "parent", 0]); + editor.transact((tr) => tr.setSelection(destination)); + const remainingText = + mode === "move" + ? view.state.tr.deleteSelection().doc.textContent + : doc.textContent; + if (internal) { + view.dragging = { slice, move: mode === "move" }; + } + // jsdom has no layout: supply only the hit-test result, not drop handling. + vi.spyOn(view, "posAtCoords").mockReturnValue({ + pos: position("nested", 13), + inside: -1, + }); + const event = new MouseEvent("drop", { + bubbles: true, + cancelable: true, + ctrlKey: mode === "copy", + altKey: mode === "copy", + }); + Object.defineProperty(event, "dataTransfer", { + value: { + types: ["text/html"], + getData: (format: string) => (format === "text/html" ? html : ""), + files: [], + }, + }); + view.dom.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); + const inserted = + from === "child" ? "ChildGrandchildCousinSibling" : "randchildCou"; + expect(view.state.doc.textContent).toBe( + remainingText.replace("Nested target", "Nested target" + inserted), + ); + expect( + editor.getBlock("target")?.children.map((block) => block.content), + ).toEqual( + from === "child" + ? ["Nested targetChild", "Cousin", "Sibling"].map((text) => [ + { type: "text", text, styles: {} }, + ]) + : [ + [ + { type: "text", text: "Nested target", styles: {} }, + { type: "text", text: "randchild", styles: { bold: true } }, + ], + [{ type: "text", text: "Cou", styles: {} }], + ], + ); + expect(view.dragging).toBeNull(); + expectUndo(doc); +}); + +it.each([ + ["child", 0, "sibling", 7, "target", false, "ChildGrandchildCousinSibling"], + ["grandchild", 0, "sibling", 7, "target", false, "GrandchildCousinSibling"], + ["grandchild", 3, "cousin", 3, "target", false, "ndchildCou"], + ["grandchild", 3, "cousin", 3, "target", true, "ndchildCou"], + ["child", 0, "sibling", 7, "nested", false, "ChildGrandchildCousinSibling"], +] as const)( + "pastes %s (offset %i) → %s (offset %i) into %s (replace: %s)", + (from, offset, to, end, target, replace, inserted) => { + const doc = editor.prosemirrorState.doc; + const html = clipboardHTML(selection([from, offset], [to, end])); + const targetEnd = target === "target" ? 6 : 13; + const destination = selection( + [target, replace ? 2 : targetEnd], + [target, replace ? 4 : targetEnd], + ); + editor.transact((tr) => tr.setSelection(destination)); + editor.pasteHTML(html, true); + + const result = editor.prosemirrorState.doc; + const before = doc.textContent; + const start = before.indexOf( + target === "target" ? "Target" : "Nested target", + ); + expect(result.textContent).toBe( + before.slice(0, start + (replace ? 2 : targetEnd)) + + inserted + + before.slice(start + (replace ? 4 : targetEnd)), + ); + const copiedBold: string[] = []; + result.descendants((node, pos) => { + if ( + pos >= destination.from && + node.isText && + node.marks.some((mark) => mark.type.name === "bold") + ) { + copiedBold.push(node.text!); + } + }); + expect(copiedBold.join("")).toBe( + from === "grandchild" ? "Grandchild".slice(offset) : "Grandchild", + ); + if (target === "nested") { + // Selected siblings stay together at the destination's nesting level. + expect(editor.document).toHaveLength(3); + expect(editor.document[2].children.map((block) => block.content)).toEqual( + [ + [{ type: "text", text: "Nested targetChild", styles: {} }], + [{ type: "text", text: "Cousin", styles: {} }], + [{ type: "text", text: "Sibling", styles: {} }], + ], + ); + } + expectUndo(doc); + }, +); + +it("preserves empty selected paragraphs instead of accepting a text-equal no-op", () => { + editor.removeBlocks(["grandchild", "cousin", "nested"]); + editor.updateBlock("child", { content: [] }); + editor.updateBlock("sibling", { content: [] }); + const doc = editor.prosemirrorState.doc; + const source = selection(["child", 0], ["sibling", 0]); + const html = clipboardHTML(source); + const destination = selection(["target", 6]); + editor.transact((tr) => tr.setSelection(destination)); + expect( + editor.prosemirrorState.tr.replaceSelection(source.content()).doc.eq(doc), + ).toBe(true); + editor.pasteHTML(html, true); + expect(editor.document).toHaveLength(4); + expect(editor.document[3].content).toEqual([]); + expect(editor.prosemirrorState.doc.textContent).toBe(doc.textContent); + editor.prosemirrorState.doc.check(); +}); + +it.each([ + { targetText: "", children: false }, + { targetText: "Target", children: false }, + { targetText: "", children: true }, + { targetText: "Target", children: true }, +])( + "pastes differing paragraph attributes over '$targetText' (children: $children)", + ({ targetText, children }) => { + editor.transact((tr) => { + editor.removeBlocks(["cousin"]); + editor.updateBlock("child", { props: { textColor: "red" } }); + editor.replaceBlocks( + ["target"], + [ + { + id: "target", + type: "paragraph", + content: targetText, + children: children + ? [{ id: "existing", type: "paragraph", content: "Existing" }] + : [], + }, + ], + ); + tr.setMeta("addToHistory", false); + }); + const doc = editor.prosemirrorState.doc; + const html = clipboardHTML(selection(["child", 0], ["sibling", 7])); + const destination = selection(["target", 0], ["target", targetText.length]); + editor.transact((tr) => tr.setSelection(destination)); + editor.pasteHTML(html, true); + + expect(editor.prosemirrorState.doc.textContent).toBe( + "ParentChildGrandchildSiblingChildGrandchildSibling" + + (children ? "Existing" : ""), + ); + // Existing children retain the target paragraph; otherwise source attrs win. + expect(editor.document[2]).toMatchObject({ + type: "paragraph", + props: { textColor: children ? "default" : "red" }, + }); + expectUndo(doc); + }, +); diff --git a/packages/core/src/editor/normalizeBlockNesting.ts b/packages/core/src/editor/normalizeBlockNesting.ts new file mode 100644 index 0000000000..c831e756ab --- /dev/null +++ b/packages/core/src/editor/normalizeBlockNesting.ts @@ -0,0 +1,45 @@ +import { Fragment, Slice } from "@tiptap/pm/model"; + +/** + * Open selections can start with contentless ancestor containers (#1117). + * Remove unselected ancestor shells so paste and drop both insert the selected + * block forest. No destination/selection lookup is needed; normal fitting handles + * endpoint joining, attributes, and the actual insertion position. + */ +export function normalizeBlockNesting(slice: Slice): Slice { + if (slice.openEnd < 3) { + return slice; + } + + let { content, openStart, openEnd } = slice; + while (openStart > 3) { + const group = content.firstChild; + const shell = group?.firstChild; + const nested = shell?.firstChild; + if ( + content.childCount !== 1 || + group?.type.name !== "blockGroup" || + shell?.type.name !== "blockContainer" || + shell.childCount !== 1 || + nested?.type.name !== "blockGroup" + ) { + break; + } + if (group.childCount === 1) { + // Both endpoints lie inside this unselected ancestor. + if (openEnd <= 3) { + break; + } + content = Fragment.from(nested); + openEnd -= 2; + } else { + content = Fragment.from( + group.copy(nested.content.append(group.content.cut(shell.nodeSize))), + ); + } + openStart -= 2; + } + return openStart === slice.openStart + ? slice + : new Slice(content, openStart, openEnd); +} diff --git a/packages/core/src/editor/transformPasted.ts b/packages/core/src/editor/transformPasted.ts index 9976216c1c..7b73c2502b 100644 --- a/packages/core/src/editor/transformPasted.ts +++ b/packages/core/src/editor/transformPasted.ts @@ -3,6 +3,23 @@ import { EditorView } from "@tiptap/pm/view"; import { getBlockInfoFromSelection } from "../api/getBlockInfoFromPos.js"; import { findParentNodeClosestToPos } from "@tiptap/core"; +import { normalizeBlockNesting } from "./normalizeBlockNesting.js"; + +const transforms: ((slice: Slice, view: EditorView) => Slice | null)[] = [ + normalizeBlockNesting, + wrapTableRows, + retypeLeadingParagraphForEmptyTarget, + normalizeTableCellContent, + wrapBlockContent, +]; + +/** Normalize clipboard and drop content before ProseMirror fits it. */ +export function transformPasted(slice: Slice, view: EditorView): Slice { + for (const transform of transforms) { + slice = transform(slice, view) ?? slice; + } + return slice; +} /** * Checks if the current selection is inside a table cell. @@ -68,7 +85,8 @@ function removeChild(node: Fragment, n: number) { * This makes sure the content that we paste is always a table (and not a tableRow) * A table works better for the remaing paste handling logic, as it's actually a content node */ -export function wrapTableRows(f: Fragment, schema: Schema) { +function wrapTableRows(slice: Slice, view: EditorView): Slice | null { + const f = slice.content; const newItems: any[] = []; for (let i = 0; i < f.childCount; i++) { if (f.child(i).type.name === "tableRow") { @@ -79,7 +97,7 @@ export function wrapTableRows(f: Fragment, schema: Schema) { newItems[newItems.length - 1] = newTable; } else { // create new table to wrap tableRow with - const newTable = schema.nodes.table.createChecked( + const newTable = view.state.schema.nodes.table.createChecked( undefined, f.child(i), ); @@ -89,32 +107,17 @@ export function wrapTableRows(f: Fragment, schema: Schema) { newItems.push(f.child(i)); } } - f = Fragment.from(newItems); - return f; + const content = Fragment.from(newItems); + return content.eq(f) + ? null + : new Slice(content, slice.openStart, slice.openEnd); } -/** - * fix for https://github.com/ProseMirror/prosemirror/issues/1430#issuecomment-1822570821 - * - * This fix wraps pasted ProseMirror nodes in their own `blockContainer` nodes - * in most cases. This is to ensure that ProseMirror inserts them as separate - * blocks, which it sometimes doesn't do because it doesn't have enough context - * about the hierarchy of the pasted nodes. The issue can be seen when pasting - * e.g. an image or two consecutive paragraphs, where PM tries to nest the - * pasted block(s) when it shouldn't. - * - * However, the fix is not applied in a few cases. See `shouldApplyFix` for - * which cases are excluded. - */ -export function transformPasted(slice: Slice, view: EditorView) { - let f = Fragment.from(slice.content); - f = wrapTableRows(f, view.state.schema); - - const retyped = retypeLeadingParagraphForEmptyTarget(f, view, slice); - if (retyped) { - return retyped; - } - +function normalizeTableCellContent( + slice: Slice, + view: EditorView, +): Slice | null { + const f = slice.content; // `tableParagraph` only exists in schemas with the default table blocks. A // schema with a custom table implementation (e.g. container-block cells, // which hold real blocks and need no inline conversion) skips this branch. @@ -139,10 +142,27 @@ export function transformPasted(slice: Slice, view: EditorView) { ); } } + return null; +} +/** + * fix for https://github.com/ProseMirror/prosemirror/issues/1430#issuecomment-1822570821 + * + * This fix wraps pasted ProseMirror nodes in their own `blockContainer` nodes + * in most cases. This is to ensure that ProseMirror inserts them as separate + * blocks, which it sometimes doesn't do because it doesn't have enough context + * about the hierarchy of the pasted nodes. The issue can be seen when pasting + * e.g. an image or two consecutive paragraphs, where PM tries to nest the + * pasted block(s) when it shouldn't. + * + * However, the fix is not applied in a few cases. See `shouldApplyFix` for + * which cases are excluded. + */ +function wrapBlockContent(slice: Slice, view: EditorView): Slice | null { + let f = slice.content; if (!shouldApplyFix(f, view)) { // Don't apply the fix. - return new Slice(f, slice.openStart, slice.openEnd); + return null; } for (let i = 0; i < f.childCount; i++) { @@ -197,9 +217,8 @@ export function transformPasted(slice: Slice, view: EditorView) { * we keep the existing replace behavior. */ function retypeLeadingParagraphForEmptyTarget( - fragment: Fragment, - view: EditorView, slice: Slice, + view: EditorView, ): Slice | null { if (isInTableCell(view)) { return null; @@ -224,7 +243,7 @@ function retypeLeadingParagraphForEmptyTarget( } const target = blockInfo.content.node; - const blockGroup = fragment.firstChild; + const blockGroup = slice.content.firstChild; const blockContainer = blockGroup?.firstChild; const leading = blockContainer?.firstChild; if ( @@ -243,7 +262,7 @@ function retypeLeadingParagraphForEmptyTarget( blockGroup.content.replaceChild(0, newBlockContainer), ); return new Slice( - fragment.replaceChild(0, newBlockGroup), + slice.content.replaceChild(0, newBlockGroup), slice.openStart, slice.openEnd, ); diff --git a/tests/src/unit/core/clipboard/copyPasteEquality/copyPasteEqualityTestInstances.ts b/tests/src/unit/core/clipboard/copyPasteEquality/copyPasteEqualityTestInstances.ts index e3bc47da79..98d9724954 100644 --- a/tests/src/unit/core/clipboard/copyPasteEquality/copyPasteEqualityTestInstances.ts +++ b/tests/src/unit/core/clipboard/copyPasteEquality/copyPasteEqualityTestInstances.ts @@ -22,6 +22,16 @@ export const copyPasteEqualityTestInstances: TestInstance< name: testCase.name, document: testCase.document, getCopyAndPasteSelection: testCase.getCopySelection, + // These selections start in the first parent's children and end in the + // following parent. The selected forest now stays at the starting depth + // instead of restoring the unselected ancestor boundary on paste. + getExpectedDocument: + testCase.name === "childrenToNextParent" || + testCase.name === "childrenToNextParentsChildren" + ? ([parent, nextParent]) => [ + { ...parent, children: [...parent.children, nextParent] }, + ] + : undefined, }, executeTest: testCopyPasteEquality, })); diff --git a/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestCase.ts b/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestCase.ts index 186078ca3d..dadce8bc43 100644 --- a/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestCase.ts +++ b/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestCase.ts @@ -1,4 +1,5 @@ import { + Block, BlockSchema, InlineContentSchema, PartialBlock, @@ -15,4 +16,6 @@ export type CopyPasteEqualityTestCase< name: string; document: PartialBlock[]; getCopyAndPasteSelection: (pmDoc: Node) => Selection; + // Cross-level selections keep their selected forest at the destination depth. + getExpectedDocument?: (document: Block[]) => Block[]; }; diff --git a/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestExecutors.ts b/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestExecutors.ts index 72e396b3bf..8abd0e1c9d 100644 --- a/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestExecutors.ts +++ b/tests/src/unit/shared/clipboard/copyPasteEquality/copyPasteEqualityTestExecutors.ts @@ -36,5 +36,7 @@ export const testCopyPasteEquality = async < ); const newDocument = editor.document; - expect(newDocument).toStrictEqual(originalDocument); + expect(newDocument).toStrictEqual( + testCase.getExpectedDocument?.(originalDocument) ?? originalDocument, + ); };