From c47d9653efb25bcfe5cf01fb7b8cdb6427e2cd4c Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Mon, 30 Nov 2026 15:36:35 +0100 Subject: [PATCH 1/4] Fix caret position after dropping a block in the gutter --- .../extensions/SideMenu/blockDropHandling.ts | 40 ++++++------------- .../src/end-to-end/dragdrop/dragdrop.test.tsx | 25 ++++++++++++ 2 files changed, 38 insertions(+), 27 deletions(-) diff --git a/packages/core/src/extensions/SideMenu/blockDropHandling.ts b/packages/core/src/extensions/SideMenu/blockDropHandling.ts index 3f0dad159c..45103bc5af 100644 --- a/packages/core/src/extensions/SideMenu/blockDropHandling.ts +++ b/packages/core/src/extensions/SideMenu/blockDropHandling.ts @@ -282,11 +282,8 @@ export function registerBlockDropHandlers( * and handles drop events for all editors. * * It specifically handles the following cases: - * - If we are both the drag origin and drop point: - * - Let normal drop handling take over - * - If we are the drop point but not the drag origin: - * - Collapse selection to prevent PM from deleting unrelated content - * - If drop event is outside our editor bounds, dispatch synthetic drop event to our editor + * - If we are the drop point, prepare the selection and forward any drop + * outside the block bounds to the editor. * - If we are the drag origin but not the drop point: * - Delete the dragged content from our editor after a delay */ @@ -307,30 +304,19 @@ export function registerBlockDropHandlers( } const { isDropPoint, isDropWithinEditorBounds, isDragOrigin } = context; - if (!isDropWithinEditorBounds && isDropPoint) { - // Any time that the drop event is outside of the editor bounds (but still close to an editor instance) - // We dispatch a synthetic event that is in the bounds of the editor instance, to have the correct drop point - dispatchSyntheticEvent(event); - } - if (isDropPoint) { - // The current instance is the drop point - - if (view.dragging) { - // Do not collapse selection when text content is being dragged - return; + if (!view.dragging) { + // Collapse any unrelated selection before ProseMirror handles the drop. + const tr = view.state.tr; + view.dispatch( + tr.setSelection(TextSelection.create(tr.doc, tr.selection.anchor)), + ); + } + if (!isDropWithinEditorBounds) { + // The forwarded drop runs synchronously and sets the selection at the + // insertion point. Leave that selection in place. + dispatchSyntheticEvent(event); } - // Because the editor selection is unrelated to the dragged content, we - // don't want PM to delete its content. Therefore, we collapse the - // selection. - view.dispatch( - view.state.tr.setSelection( - TextSelection.create( - view.state.tr.doc, - view.state.tr.selection.anchor, - ), - ), - ); return; } else if (isDragOrigin) { // The current instance is the drag origin, but not the drop point diff --git a/tests/src/end-to-end/dragdrop/dragdrop.test.tsx b/tests/src/end-to-end/dragdrop/dragdrop.test.tsx index aa26bd25bc..f9c0f8cbfd 100644 --- a/tests/src/end-to-end/dragdrop/dragdrop.test.tsx +++ b/tests/src/end-to-end/dragdrop/dragdrop.test.tsx @@ -613,6 +613,31 @@ describe.skipIf(browserName === "firefox")("Dropping into a block", () => { describe.skipIf(browserName === "firefox")( "Focus after dragging a block", () => { + it("types into the moved block after dropping in the editor gutter", async ({ + onTestFinished, + setupEditor, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "a", type: "paragraph", content: "Block A" }, + { id: "b", type: "paragraph", content: "Block B" }, + ], + }); + const target = getRect(block("b").querySelector(".bn-block-content")!); + await startBlockDrag(block("a"), onTestFinished); + await mouseSequence([ + { type: "move", x: target.left - 8, y: target.bottom - 2, steps: 10 }, + { type: "move", x: target.left - 7, y: target.bottom - 2 }, + { type: "up" }, + ]); + + await expect.poll(() => ids(editor.document)).toEqual(["b", "a"]); + await waitForSelectorDetached(".bn-drag-preview"); + await userEvent.keyboard("!"); + expect(block("b").textContent).toBe("Block B"); + expect(block("a").textContent).toBe("Block A!"); + }); + // The drop leaves a text cursor in the editor, so the keyboard works on it // right away, e.g. to undo the drop (#3165). it("undoes a drop with the keyboard", async ({ setupEditor }) => { From b0e896606f5c309815caa3c702509badddef2882 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Mon, 30 Nov 2026 15:38:17 +0100 Subject: [PATCH 2/4] Move drag-and-drop coverage to browser integration tests --- .../dragdrop/dragdrop.browser.test.tsx} | 0 tests/tsconfig.browser.json | 1 + 2 files changed, 1 insertion(+) rename tests/src/{end-to-end/dragdrop/dragdrop.test.tsx => integration/dragdrop/dragdrop.browser.test.tsx} (100%) diff --git a/tests/src/end-to-end/dragdrop/dragdrop.test.tsx b/tests/src/integration/dragdrop/dragdrop.browser.test.tsx similarity index 100% rename from tests/src/end-to-end/dragdrop/dragdrop.test.tsx rename to tests/src/integration/dragdrop/dragdrop.browser.test.tsx diff --git a/tests/tsconfig.browser.json b/tests/tsconfig.browser.json index 8939e89b11..22158adb04 100644 --- a/tests/tsconfig.browser.json +++ b/tests/tsconfig.browser.json @@ -21,6 +21,7 @@ } }, "include": [ + "src/examples.d.ts", "src/utils/**/*.ts", "src/utils/**/*.tsx", "src/fixtures/**/*.tsx", From 1e212a1a58f1d07cc9727b3eab5f01a525557de5 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Mon, 30 Nov 2026 15:48:26 +0100 Subject: [PATCH 3/4] Limit example component typings to app imports --- tests/src/examples.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/src/examples.d.ts b/tests/src/examples.d.ts index 606fad1ad9..aa30543848 100644 --- a/tests/src/examples.d.ts +++ b/tests/src/examples.d.ts @@ -1,11 +1,11 @@ -// e2e tests mount example apps via `import App from "@examples///src/App"`. +// Browser tests mount example apps via `import App from "@examples///src/App"`. // The `@examples` alias is resolved by Vite at runtime (see vite.config.browser.ts). // We declare it ambiently as a React component so `tsc` resolves the import to a // type WITHOUT descending into the example sources (which live outside the tests // rootDir and would otherwise break the composite build with TS6059). A tsconfig // `paths` entry would do the opposite — resolve to the real files — so we use this // ambient module instead. -declare module "@examples/*" { +declare module "@examples/*/src/App" { import type { ComponentType } from "react"; const App: ComponentType; export default App; From b5bc4571544e8830d14c0de7c8079750eade1ef1 Mon Sep 17 00:00:00 2001 From: Nick the Sick Date: Mon, 30 Nov 2026 16:07:33 +0100 Subject: [PATCH 4/4] Colocate drag-and-drop tests and share browser drag commands --- .../blockDropHandling.browser.test.ts | 215 +++++ ...rmattingToolbarController.browser.test.tsx | 48 + .../SideMenuController.browser.test.tsx | 57 ++ tests/src/commands/browser/blockDrag.ts | 236 +++++ tests/src/commands/index.ts | 7 + tests/src/examples.d.ts | 4 +- .../dragdrop/dragdrop.browser.test.tsx | 908 +++++------------- tests/src/utils/mouse.ts | 230 +---- tests/tsconfig.browser.json | 1 - 9 files changed, 802 insertions(+), 904 deletions(-) create mode 100644 packages/core/src/extensions/SideMenu/blockDropHandling.browser.test.ts create mode 100644 tests/src/commands/browser/blockDrag.ts diff --git a/packages/core/src/extensions/SideMenu/blockDropHandling.browser.test.ts b/packages/core/src/extensions/SideMenu/blockDropHandling.browser.test.ts new file mode 100644 index 0000000000..2bc3fa01ae --- /dev/null +++ b/packages/core/src/extensions/SideMenu/blockDropHandling.browser.test.ts @@ -0,0 +1,215 @@ +import { describe, expect } from "vite-plus/test"; +import "../../editor/Block.css"; +import type { BlockNoteEditor } from "../../editor/BlockNoteEditor.js"; +import { SideMenuExtension } from "./SideMenu.js"; + +function blockContent(editor: BlockNoteEditor, id: string) { + return editor.domElement!.querySelector( + `[data-id="${id}"] .bn-block-content`, + )!; +} + +function dropNextTo( + editor: BlockNoteEditor, + source: string, + target: string, + side: "before" | "after", +) { + const content = blockContent(editor, target); + const rect = content.getBoundingClientRect(); + dropBlock(editor, source, content, { + x: side === "before" ? rect.left + 1 : rect.right - 1, + y: (rect.top + rect.bottom) / 2, + }); +} + +function dropBlock( + editor: BlockNoteEditor, + source: string, + target: Element, + { x, y }: { x: number; y: number }, +) { + const sideMenu = editor.getExtension(SideMenuExtension)!; + const dataTransfer = new DataTransfer(); + sideMenu.blockDragStart({ dataTransfer, clientY: y }, source); + const options = { + bubbles: true, + cancelable: true, + dataTransfer, + clientX: x, + clientY: y, + }; + try { + // The handle dispatches dragstart outside the editable surface. The + // editor reads the BlockNote payload when that event reaches its root. + editor.domElement!.parentElement!.dispatchEvent( + new DragEvent("dragstart", options), + ); + target.dispatchEvent(new DragEvent("dragover", options)); + target.dispatchEvent(new DragEvent("drop", options)); + target.dispatchEvent(new DragEvent("dragend", options)); + } finally { + sideMenu.blockDragEnd(); + } +} + +describe("dropping blocks", () => { + it("moves a block into and back out of a nested group", async ({ + setupEditor, + }) => { + const { editor } = await setupEditor({ + mountType: "dom", + initialContent: [ + { id: "moving", type: "paragraph", content: "Moving" }, + { + id: "parent", + type: "paragraph", + content: "Parent", + children: [{ id: "child", type: "paragraph", content: "Child" }], + }, + { id: "last", type: "paragraph", content: "Last" }, + ], + }); + const [moving, parent, last] = editor.document; + + dropNextTo(editor, "moving", "child", "before"); + expect(editor.document).toEqual([ + { ...parent, children: [moving, ...parent.children] }, + last, + ]); + + dropNextTo(editor, "moving", "last", "before"); + expect(editor.document).toEqual([parent, moving, last]); + }); + + it("keeps the dropped block in view when the previous caret is scrolled out", async ({ + setupEditor, + onTestFinished, + }) => { + const scroller = document.createElement("div"); + scroller.style.height = "180px"; + scroller.style.overflowY = "auto"; + document.body.append(scroller); + onTestFinished(() => scroller.remove()); + const { editor } = await setupEditor({ + mountType: false, + initialContent: Array.from({ length: 20 }, (_, index) => ({ + id: `p${index}`, + type: "paragraph" as const, + content: `Paragraph ${index}`, + })), + }); + editor.mount(scroller); + editor.setTextCursorPosition("p0"); + editor.focus(); + scroller.scrollTop += + blockContent(editor, "p15").getBoundingClientRect().top - + scroller.getBoundingClientRect().top - + 20; + + expect( + blockContent(editor, "p0").getBoundingClientRect().bottom, + ).toBeLessThan(scroller.getBoundingClientRect().top); + dropNextTo(editor, "p15", "p17", "after"); + + expect(editor.document.slice(15, 18).map(({ id }) => id)).toEqual([ + "p16", + "p17", + "p15", + ]); + await expect + .poll(() => { + const viewport = scroller.getBoundingClientRect(); + const moved = blockContent(editor, "p15").getBoundingClientRect(); + return moved.top >= viewport.top && moved.bottom <= viewport.bottom; + }) + .toBe(true); + }); + + it.for(["content", "gutter"] as const)( + "types into the moved block after dropping in the %s", + async (area, { setupEditor, userEvent }) => { + const { editor } = await setupEditor({ + mountType: "dom", + initialContent: [ + { id: "a", type: "paragraph", content: "Block A" }, + { id: "b", type: "paragraph", content: "Block B" }, + ], + }); + const target = blockContent(editor, "b"); + const rect = target.getBoundingClientRect(); + dropBlock(editor, "a", area === "gutter" ? editor.domElement! : target, { + x: area === "gutter" ? rect.left - 7 : rect.right - 1, + y: rect.bottom - 2, + }); + + expect(editor.document.map((block) => block.id)).toEqual(["b", "a"]); + await expect.poll(() => document.activeElement).toBe(editor.domElement); + await userEvent.keyboard("!"); + expect(blockContent(editor, "b").textContent).toBe("Block B"); + expect(blockContent(editor, "a").textContent).toBe("Block A!"); + }, + ); + + it.for(["paragraph", "image", "selection", "toggle"] as const)( + "restores the dragged %s and its visible selection on keyboard undo", + async (kind, { setupEditor, MOD, userEvent }) => { + const initialContent = + kind === "selection" + ? [ + { id: "a", type: "paragraph", content: "A" } as const, + { id: "b", type: "paragraph", content: "B" } as const, + { id: "target", type: "paragraph", content: "Target" } as const, + ] + : [ + kind === "image" + ? ({ id: "a", type: "image" } as const) + : ({ id: "a", type: "paragraph", content: "A" } as const), + { + id: "target", + type: kind === "toggle" ? "toggleListItem" : "paragraph", + content: "Target", + } as const, + ]; + const { editor } = await setupEditor({ + mountType: "dom", + initialContent, + }); + const originalDocument = editor.document; + if (kind === "selection") { + editor.setSelection("a", "b"); + } + const target = blockContent(editor, "target"); + const rect = target.getBoundingClientRect(); + dropBlock(editor, "a", target, { + x: kind === "toggle" ? (rect.left + rect.right) / 2 : rect.right - 1, + y: (rect.top + rect.bottom) / 2, + }); + if (kind === "toggle") { + expect(editor.document[0].children.map(({ id }) => id)).toEqual(["a"]); + } else { + expect(editor.document.map(({ id }) => id)).toEqual( + kind === "selection" ? ["target", "a", "b"] : ["target", "a"], + ); + } + + await expect.poll(() => document.activeElement).toBe(editor.domElement); + await userEvent.keyboard(`{${MOD}>}z{/${MOD}}`); + expect(editor.document).toEqual(originalDocument); + expect(editor.getSelectionCutBlocks()).toMatchObject({ + blocks: + kind === "selection" ? [{ id: "a" }, { id: "b" }] : [{ id: "a" }], + blockCutAtStart: undefined, + blockCutAtEnd: undefined, + }); + const nativeSelection = document.getSelection()!; + expect(nativeSelection.isCollapsed).toBe(false); + expect( + nativeSelection.getRangeAt(0).intersectsNode(blockContent(editor, "a")), + ).toBe(true); + expect( + editor.domElement!.classList.contains("ProseMirror-hideselection"), + ).toBe(false); + }, + ); +}); diff --git a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx index da315fac6d..390ef84b26 100644 --- a/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx +++ b/packages/react/src/components/FormattingToolbar/DesktopFormattingToolbarController.browser.test.tsx @@ -83,6 +83,54 @@ describe("DesktopFormattingToolbarController", () => { }); describe("integration", () => { + it("does not show a toolbar while dragging an image block", async ({ + setupEditor, + blockDrag, + }) => { + const { editor, rootNode } = await setupEditor({ + initialContent: [ + { id: "image", type: "image" }, + { id: "target", type: "paragraph", content: "Target" }, + ], + props: { formattingToolbar: false }, + children: , + }); + editor.setTextCursorPosition("target"); + editor.focus(); + const editable = editor.domElement!; + const selector = ".bn-formatting-toolbar"; + expect(rootNode.querySelector(selector)).toBeNull(); + + // Observe mounts during the gesture, including a toolbar that disappears on drop. + let toolbarMounted = false; + function recordToolbar(records: MutationRecord[]) { + toolbarMounted ||= records.some((record) => + [...record.addedNodes].some( + (node) => + node instanceof Element && + (node.matches(selector) || node.querySelector(selector) !== null), + ), + ); + } + const observer = new MutationObserver(recordToolbar); + observer.observe(rootNode, { childList: true, subtree: true }); + try { + await blockDrag.move( + editable.querySelector('[data-id="image"] .bn-block-content')!, + editable.querySelector('[data-id="target"] .bn-block-content')!, + false, + ); + await expect + .poll(() => editor.document.map(({ id }) => id)) + .toEqual(["target", "image"]); + recordToolbar(observer.takeRecords()); + } finally { + observer.disconnect(); + } + expect(toolbarMounted).toBe(false); + expect(rootNode.querySelector(selector)).toBeNull(); + }); + it("does not steal editor focus when the default toolbar appears", async ({ setupEditor, selectText, diff --git a/packages/react/src/components/SideMenu/SideMenuController.browser.test.tsx b/packages/react/src/components/SideMenu/SideMenuController.browser.test.tsx index aebe57c3a7..40d3dcae08 100644 --- a/packages/react/src/components/SideMenu/SideMenuController.browser.test.tsx +++ b/packages/react/src/components/SideMenu/SideMenuController.browser.test.tsx @@ -1,7 +1,27 @@ +import { BlockNoteSchema } from "@blocknote/core"; import { SideMenuExtension } from "@blocknote/core/extensions"; import { assert, describe, expect } from "vite-plus/test"; +import { createReactBlockSpec } from "../../schema/ReactBlockSpec.js"; import { SideMenuController } from "./SideMenuController.js"; +const ReactPanel = createReactBlockSpec( + { type: "reactPanel", propSchema: {}, content: "none", layoutOnly: true }, + { + renderFrame: ({ slotRef }) => ( +
+
+ React panel +
+
+
+ ), + }, +); + +const panelSchema = BlockNoteSchema.create().extend({ + blockSpecs: { reactPanel: ReactPanel() }, +}); + describe("SideMenuController", () => { describe("unit", () => { it("mounts its custom menu when requested and unmounts it on dismissal", async ({ @@ -115,5 +135,42 @@ describe("SideMenuController", () => { await expect.element(handle).not.toBeInTheDocument(); expect(editor.document).toEqual(before); }); + + // These cases need the native gesture that starts from the hovered row's handle. + describe("dragging React layout blocks", () => { + it.for([ + { row: "the layout frame", selector: ".panel-label" }, + { row: "a child inside the frame", selector: '[data-id="child"]' }, + ])( + "starts a drag from $row", + async ({ selector }, { setupEditor, blockDrag }) => { + const { editor } = await setupEditor({ + schema: panelSchema, + initialContent: [ + { + id: "panel", + type: "reactPanel", + children: [ + { + id: "child", + type: "paragraph", + content: "Inside the panel", + }, + ], + }, + ], + }); + const row = editor.domElement!.querySelector(selector)!; + const drag = await blockDrag.start(row); + const preview = document.querySelector(".bn-drag-preview")!; + expect(preview.textContent).toContain("Inside the panel"); + expect(preview.textContent?.includes("React panel")).toBe( + selector === ".panel-label", + ); + expect(preview.getBoundingClientRect().height).toBeGreaterThan(0); + await drag.drop(row, true); + }, + ); + }); }); }); diff --git a/tests/src/commands/browser/blockDrag.ts b/tests/src/commands/browser/blockDrag.ts new file mode 100644 index 0000000000..029112c773 --- /dev/null +++ b/tests/src/commands/browser/blockDrag.ts @@ -0,0 +1,236 @@ +import { + expect, + onTestFinished as finishCurrentTest, + type TestContext, +} from "vite-plus/test"; +import { DRAG_HANDLE_SELECTOR } from "../../utils/const.js"; +import { waitForSelector } from "../../utils/editor.js"; +import { commands } from "../transport.js"; +import type { MouseAction } from "../transport/positionalMouse.js"; + +function runMouse(actions: MouseAction[]): Promise { + return commands.positionalMouse(...actions); +} + +/** Bounding rect of an element, resolved from a selector or the element itself. */ +export function getRect(selectorOrElement: string | Element): DOMRect { + const element = + typeof selectorOrElement === "string" + ? document.querySelector(selectorOrElement) + : selectorOrElement; + if (!element) { + throw new Error(`Element not found: ${JSON.stringify(selectorOrElement)}`); + } + return element.getBoundingClientRect(); +} + +function center(rect: DOMRect) { + return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; +} + +/** + * Drives the real Playwright mouse through a sequence of actions. Coordinates + * are iframe-relative (i.e. `getBoundingClientRect()` space) — see `getRect`. + */ +export function mouseSequence(actions: MouseAction[]): Promise { + return runMouse(actions); +} + +/** Single (or multi-) click at iframe-relative coordinates. */ +export function clickAt(x: number, y: number, clickCount = 1): Promise { + return runMouse([{ type: "click", x, y, clickCount }]); +} + +/** Moves the mouse to the centre of an element (e.g. to reveal hover UI). */ +export async function moveMouseOverElement( + selectorOrElement: string | Element, +) { + const element = + typeof selectorOrElement === "string" + ? await waitForSelector(selectorOrElement) + : selectorOrElement; + const { x, y } = center(element.getBoundingClientRect()); + await runMouse([{ type: "move", x, y, steps: 5 }]); +} + +/** + * Starts dragging a block by its drag handle: hovers the block to reveal the + * handle, presses on it, and moves the mouse a little, so the browser starts + * the drag. Finish it with `drag.drop(...)` or a raw `mouseSequence` mouse-up. + * Pass the calling test's cleanup hook before acquiring the native button. + */ +export async function startBlockDrag( + dragTarget: string | Element, + onTestFinished: TestContext["onTestFinished"], +) { + const owner = crypto.randomUUID(); + let started = false; + let finished = false; + + function cancel() { + return runMouse([{ type: "cancel", owner }]); + } + + // Bind to this attempt before any await. If it ends while we are still + // finding the handle, do not acquire the page's native button afterward. + onTestFinished(async () => { + finished = true; + if (started) { + await cancel(); + } + }); + + const target = + typeof dragTarget === "string" + ? await waitForSelector(dragTarget) + : dragTarget; + await moveMouseOverElement(target); + + const handle = await waitForDragHandle(target); + const handleCenter = center(handle.getBoundingClientRect()); + const previousPreview = document.querySelector(".bn-drag-preview"); + + async function cancelAfterFailure() { + try { + await cancel(); + } catch { + // The browser may have disconnected. Report the original drag failure. + } + } + + if (finished) { + throw new Error("The test ended before the drag acquired the mouse."); + } + started = true; + try { + await runMouse([ + { type: "move", x: handleCenter.x, y: handleCenter.y, steps: 5 }, + { type: "down", owner }, + { + type: "move", + x: handleCenter.x + 10, + y: handleCenter.y + 10, + steps: 5, + }, + ]); + // BlockNote creates this on native dragstart, not on mouse down. + await expect + .poll(() => { + const preview = document.querySelector(".bn-drag-preview"); + return preview !== null && preview !== previousPreview; + }) + .toBe(true); + } catch (error) { + await cancelAfterFailure(); + throw error; + } + + /** Drops on the target's left edge (`dropAbove`) or right edge. */ + async function drop(dropTarget: string | Element, dropAbove: boolean) { + try { + const dropRect = getRect(dropTarget); + const x = dropAbove ? dropRect.left + 1 : dropRect.right - 1; + const y = dropRect.top + dropRect.height / 2; + await runMouse([ + { type: "move", x, y, steps: 5, owner }, + { type: "up", owner }, + ]); + } catch (error) { + await cancelAfterFailure(); + throw error; + } + } + + return { drop }; +} + +const BLOCK_ID_SELECTOR = "[data-node-type][data-id]"; +const BLOCK_OUTER_SELECTOR = '[data-node-type="blockOuter"]'; +const BLOCK_ROOT_SELECTOR = `${BLOCK_ID_SELECTOR}:not(${BLOCK_OUTER_SELECTOR})`; + +/** Waits for the hovered block's own handle to be positioned on its row. */ +export async function waitForDragHandle(target: Element) { + const targetBlock = target.closest(BLOCK_ID_SELECTOR); + const blockId = targetBlock?.getAttribute("data-id"); + const container = target.closest(".bn-container"); + if (!targetBlock || !blockId || !container) { + throw new Error("The drag handle target must belong to an editor block."); + } + + const idSelector = `[data-id="${CSS.escape(blockId)}"]`; + const handleSelector = `${DRAG_HANDLE_SELECTOR}[data-side-menu-block-id="${CSS.escape(blockId)}"]`; + const block = targetBlock.matches(BLOCK_OUTER_SELECTOR) + ? targetBlock.querySelector(`${BLOCK_ROOT_SELECTOR}${idSelector}`) + : targetBlock; + if (!block || block.closest(".bn-container") !== container) { + throw new Error( + `Could not resolve the drag handle target block ${blockId}.`, + ); + } + + function findHandle(block: Element, container: Element) { + // A regular block's box includes its children. Find its own content row, + // even when a toggle or another frame wraps that row. Layout blocks have + // no content row of their own; the handle's block ID disambiguates them. + const row = block.matches('[data-node-type="blockContainer"]') + ? [...block.querySelectorAll(".bn-block-content")].find( + (content) => + content.closest(BLOCK_ROOT_SELECTOR) === block && + content.closest(".bn-container") === container, + ) + : block; + if (!row) { + return undefined; + } + const { top, bottom } = row.getBoundingClientRect(); + return [...container.querySelectorAll(handleSelector)].find((handle) => { + if (handle.closest(".bn-container") !== container) { + return false; + } + const { x, y } = center(handle.getBoundingClientRect()); + const button = handle.closest("button") ?? handle; + return ( + y >= top && + y <= bottom && + button.contains(document.elementFromPoint(x, y)) + ); + }); + } + + let handle: Element | undefined; + await expect + .poll(() => (handle = findHandle(block, container))) + .toBeDefined(); + return handle!; +} + +/** + * Drags a block onto another via its drag handle. Hovers the drag target to + * reveal the handle, presses on the handle, then drops on the left edge + * (`dropAbove`) or right edge of the drop target. Uses the current test's + * finish hook by default; pass the bound hook if calling from a shared fixture. + */ +export async function dragAndDropBlock( + dragTarget: string | Element, + dropTarget: string | Element, + dropAbove: boolean, + onTestFinished: TestContext["onTestFinished"] = finishCurrentTest, +) { + const drag = await startBlockDrag(dragTarget, onTestFinished); + await drag.drop(dropTarget, dropAbove); +} + +export function bindBlockDrag(onTestFinished: TestContext["onTestFinished"]) { + return { + start(target: string | Element) { + return startBlockDrag(target, onTestFinished); + }, + move( + source: string | Element, + destination: string | Element, + dropAbove: boolean, + ) { + return dragAndDropBlock(source, destination, dropAbove, onTestFinished); + }, + }; +} diff --git a/tests/src/commands/index.ts b/tests/src/commands/index.ts index 00ee9e9a32..1460e0bfe4 100644 --- a/tests/src/commands/index.ts +++ b/tests/src/commands/index.ts @@ -15,6 +15,9 @@ export type CommandContext = Pick< page: typeof page; userEvent: typeof userEvent; setupEditor: SetupEditor; + blockDrag: ReturnType< + typeof import("./browser/blockDrag.js").bindBlockDrag + >; }; /** Top-level test fixtures; pass this collection to test.extend unchanged. */ @@ -40,6 +43,10 @@ export const commands: Required< positionalMouse: async ({}, use) => { await use(nodeCommands.positionalMouse); }, + blockDrag: async ({ onTestFinished }, use) => { + const { bindBlockDrag } = await import("./browser/blockDrag.js"); + await use(bindBlockDrag(onTestFinished)); + }, imeComposition: async ({}, use) => { await use(nodeCommands.imeComposition); }, diff --git a/tests/src/examples.d.ts b/tests/src/examples.d.ts index aa30543848..606fad1ad9 100644 --- a/tests/src/examples.d.ts +++ b/tests/src/examples.d.ts @@ -1,11 +1,11 @@ -// Browser tests mount example apps via `import App from "@examples///src/App"`. +// e2e tests mount example apps via `import App from "@examples///src/App"`. // The `@examples` alias is resolved by Vite at runtime (see vite.config.browser.ts). // We declare it ambiently as a React component so `tsc` resolves the import to a // type WITHOUT descending into the example sources (which live outside the tests // rootDir and would otherwise break the composite build with TS6059). A tsconfig // `paths` entry would do the opposite — resolve to the real files — so we use this // ambient module instead. -declare module "@examples/*/src/App" { +declare module "@examples/*" { import type { ComponentType } from "react"; const App: ComponentType; export default App; diff --git a/tests/src/integration/dragdrop/dragdrop.browser.test.tsx b/tests/src/integration/dragdrop/dragdrop.browser.test.tsx index f9c0f8cbfd..6098901638 100644 --- a/tests/src/integration/dragdrop/dragdrop.browser.test.tsx +++ b/tests/src/integration/dragdrop/dragdrop.browser.test.tsx @@ -1,723 +1,271 @@ -import { - BlockNoteSchema, - createBlockSpec, - isDOMNode, - type PartialBlock, -} from "@blocknote/core"; -import "@blocknote/core/fonts/inter.css"; -import "@blocknote/mantine/style.css"; +import { BlockNoteSchema, createBlockSpec, isDOMNode } from "@blocknote/core"; import { createReactBlockSpec } from "@blocknote/react"; -import PdfFileApp from "@examples/06-custom-schema/04-pdf-file-block/src/App"; -import { describe, expect, test } from "vite-plus/test"; -import { render } from "vitest-browser-react"; -import type { SetupEditor } from "../../commands/browser/setupEditor.js"; -import { - BLOCK_CONTAINER_SELECTOR, - EDITOR_SELECTOR, - H_ONE_BLOCK_SELECTOR, - H_THREE_BLOCK_SELECTOR, - H_TWO_BLOCK_SELECTOR, - IMAGE_SELECTOR, - PARAGRAPH_SELECTOR, - PDF_SELECTOR, -} from "../../utils/const.js"; -import { browserName, MOD, userEvent } from "../../utils/context.js"; -import { - sleep, - waitForSelector, - waitForSelectorDetached, -} from "../../utils/editor.js"; -import { - dragAndDropBlock, - getRect, - mouseSequence, - startBlockDrag, -} from "../../utils/mouse.js"; +import { describe, expect } from "vite-plus/test"; -// `expect.element` is augmented against the bare `vitest` module, but vite-plus -// types `expect` from an internal module, so the augmentation doesn't attach. -// Type the accessor locally. -type ElementMatchers = { - toHaveFocus(): Promise; -}; -type ElementExpect = (element: Element | null) => ElementMatchers; -const expectElement = (expect as unknown as { element: ElementExpect }).element; - -function heading( - id: string, - level: 1 | 2 | 3, - children?: PartialBlock[], -): PartialBlock { - return { - id, - type: "heading", - props: { level }, - content: "Heading", - children, - }; -} - -const imageDocument: PartialBlock[] = [ - { id: "0", type: "image" }, - heading("1", 1), -]; - -describe("Check Block Dragging Functionality", () => { - // Playwright doesn't correctly simulate drag events in Firefox. - it.skipIf(browserName === "firefox")( - "Should be able to drag & drop non-nested blocks", - async ({ setupEditor }) => { - const { editor } = await setupEditor({ - initialContent: [heading("0", 1), heading("1", 2), heading("2", 3)], - }); - const [h1, h2, h3] = editor.document; - editor.setTextCursorPosition("2", "end"); - editor.focus(); - - await dragAndDropBlock(H_ONE_BLOCK_SELECTOR, H_TWO_BLOCK_SELECTOR, false); - - expect(editor.document).toEqual([h2, h1, h3]); - }, - ); - - it.skipIf(browserName === "firefox")( - "Should be able to drag & drop nested blocks", - async ({ setupEditor }) => { - const { editor } = await setupEditor({ - initialContent: [ - heading("0", 1), - { - id: "1", - type: "paragraph", - content: "Paragraph", - children: [ - heading("2", 2), - { - id: "3", - type: "paragraph", - content: "Paragraph", - children: [heading("4", 3)], - }, - ], - }, - { id: "5", type: "paragraph" }, - ], - }); - const [h1, paragraph, last] = editor.document; - const [h2, childParagraph] = paragraph.children; - const [h3] = childParagraph.children; - editor.setTextCursorPosition("5"); - editor.focus(); - - // Dragging first heading into next nested element. - await dragAndDropBlock(H_ONE_BLOCK_SELECTOR, H_TWO_BLOCK_SELECTOR, true); - - // Dragging second heading into next nested element. - await dragAndDropBlock( - H_TWO_BLOCK_SELECTOR, - H_THREE_BLOCK_SELECTOR, - true, - ); - - const lastParagraph = document.querySelectorAll(PARAGRAPH_SELECTOR); - await dragAndDropBlock( - H_THREE_BLOCK_SELECTOR, - lastParagraph[lastParagraph.length - 1] as HTMLElement, - true, - ); - - expect(editor.document).toEqual([ - { ...paragraph, children: [h1, { ...childParagraph, children: [h2] }] }, - h3, - last, - ]); - }, - ); - - it.skipIf(browserName === "firefox")( - "Should be able to drag image", - async ({ setupEditor }) => { - const { editor } = await setupEditor({ initialContent: imageDocument }); - const [image, h1] = editor.document; - editor.setTextCursorPosition("1", "end"); - editor.focus(); - - await dragAndDropBlock(IMAGE_SELECTOR, H_ONE_BLOCK_SELECTOR, false); - - expect(editor.document).toEqual([h1, image]); - }, - ); - - it.skipIf(browserName === "firefox")( - "Formatting toolbar should not appear when dragging image block", - async ({ setupEditor }) => { - const { editor } = await setupEditor({ initialContent: imageDocument }); - editor.setTextCursorPosition("1", "end"); - editor.focus(); - - const toolbarSelector = ".bn-formatting-toolbar"; - expect(document.querySelector(toolbarSelector)).toBeNull(); - - // Observe the whole gesture. Waiting for the toolbar to disappear - // after mouseup also passes if it was visible throughout the drag. - let toolbarMounted = false; - function recordToolbar(records: MutationRecord[]) { - toolbarMounted ||= records.some((record) => - Array.from(record.addedNodes).some( - (node) => - node instanceof Element && - (node.matches(toolbarSelector) || - node.querySelector(toolbarSelector) !== null), - ), - ); - } - const observer = new MutationObserver(recordToolbar); - observer.observe(document.body, { childList: true, subtree: true }); - try { - await dragAndDropBlock(IMAGE_SELECTOR, H_ONE_BLOCK_SELECTOR, false); - await expect - .poll(() => editor.document.map((block) => block.id)) - .toEqual(["1", "0"]); - recordToolbar(observer.takeRecords()); - } finally { - observer.disconnect(); - } - - expect(toolbarMounted).toBe(false); - expect(document.querySelector(toolbarSelector)).toBeNull(); - }, - ); - - test.skipIf(browserName === "firefox")( - "releases the dragged PDF block in its original position without losing or duplicating it", - async () => { - await render(); - const editor = await waitForSelector(EDITOR_SELECTOR); - await waitForSelector(PDF_SELECTOR); - - const firstParagraph = await waitForSelector(PARAGRAPH_SELECTOR); - await userEvent.click(firstParagraph); - function blockIds() { - return [...editor.querySelectorAll(BLOCK_CONTAINER_SELECTOR)].map( - (block) => block.getAttribute("data-id"), - ); - } - const idsBefore = blockIds(); - expect(idsBefore).toHaveLength(3); - expect(idsBefore.every(Boolean)).toBe(true); - // The PDF already sits just after this paragraph. Verify that a real - // drop reaches the editor, then check that the PDF is neither lost - // nor duplicated when dropped back into the same position. - let dropped = false; - function recordDrop(event: DragEvent) { - dropped ||= - event.isTrusted && - isDOMNode(event.target) && - firstParagraph.contains(event.target); - } - editor.addEventListener("drop", recordDrop, true); - try { - await dragAndDropBlock(PDF_SELECTOR, firstParagraph, false); - } finally { - editor.removeEventListener("drop", recordDrop, true); - } - expect(dropped).toBe(true); - expect(blockIds()).toEqual(idsBefore); - const blocks = [ - ...editor.querySelectorAll(".bn-block-content"), - ]; - expect(blocks.map((block) => block.dataset.contentType)).toEqual([ - "paragraph", - "pdf", - "paragraph", - ]); - expect(blocks[0].textContent).toBe("Welcome to this demo!"); - expect( - blocks[1] - .querySelector('embed[type="application/pdf"]') - ?.getAttribute("src"), - ).toBe("https://pdfobject.com/pdf/sample.pdf"); - expect(blocks[2].textContent).toBe( - "Press the '/' key to open the Slash Menu and add another PDF", - ); - }, - ); - - it.skipIf(browserName === "firefox")( - "keeps the dropped block visible when the previous selection is offscreen", - async ({ setupEditor }) => { - const { editor, rootNode } = await setupEditor({ - initialContent: Array.from({ length: 70 }, (_, index) => ({ - id: `paragraph-${index}`, - type: "paragraph" as const, - content: `Paragraph ${index}`, - })), - outside: ({ children }) => ( -
- {children} -
+describe("Native block drops", () => { + it("drops an embedded PDF back in place without losing or duplicating it", async ({ + setupEditor, + blockDrag, + }) => { + const pdfUrl = "about:blank"; + const pdf = createReactBlockSpec( + { type: "pdf", propSchema: { url: { default: "" } }, content: "none" }, + { + render: ({ block }) => ( + ), - }); - const scroller = rootNode.firstElementChild as HTMLElement; - const selectedBlock = await waitForSelector('[data-id="paragraph-0"]'); - const source = await waitForSelector('[data-id="paragraph-60"]'); - const destination = await waitForSelector('[data-id="paragraph-62"]'); - editor.setTextCursorPosition("paragraph-0", "start"); - editor.focus(); - - // Keep the native selection near the start while scrolling to later blocks. - // Refocusing on drop must not scroll back to that old selection. - scroller.scrollTop += - source.getBoundingClientRect().top - - scroller.getBoundingClientRect().top - - 80; - expect(selectedBlock.getBoundingClientRect().bottom).toBeLessThan( - scroller.getBoundingClientRect().top, - ); - expect(editor.getTextCursorPosition().block.id).toBe("paragraph-0"); - - await dragAndDropBlock(source, destination, false); - - await expect - .poll(() => { - const ids = editor.document.map((block) => block.id); - return ids[ids.indexOf("paragraph-62") + 1]; - }) - .toBe("paragraph-60"); - await expect - .poll(() => { - const moved = scroller.querySelector('[data-id="paragraph-60"]'); - if (!moved) { - return false; - } - const blockRect = moved.getBoundingClientRect(); - const viewport = scroller.getBoundingClientRect(); - return ( - blockRect.top >= viewport.top && blockRect.bottom <= viewport.bottom - ); - }) - .toBe(true); - }, - ); -}); - -// Dragging layout blocks by their drag handle: the drag preview shows the -// dragged block, and a drop places the dragged block itself, not a new copy -// of its parent around it. - -/** - * A layout block's frame: a label (chrome) above the slot. The drag handle of the - * layout block shows when the mouse is on its chrome. - */ -function labelledFrame(label: string) { - const dom = document.createElement("section"); - dom.style.border = "1px solid gray"; - dom.style.padding = "8px"; - const chrome = document.createElement("div"); - chrome.className = "label"; - chrome.contentEditable = "false"; - chrome.textContent = label; - const slot = document.createElement("div"); - dom.append(chrome, slot); - return { dom, slot }; -} - -// A React layout block: React wraps its frame in elements of its own. -const createReactPanel = createReactBlockSpec( - { type: "reactPanel", propSchema: {}, content: "none", layoutOnly: true }, - { - renderFrame: (props) => ( -
-
- React panel -
-
-
- ), - }, -); - -// A list of items. An item is placed only in a list (`namedOnly`), and it -// keeps its drag handle (`draggable`), like the steps of a stepper. -const Item = createBlockSpec( - { - type: "item", - propSchema: {}, - content: "none", - layoutOnly: true, - placeable: "namedOnly", - }, - { - meta: { draggable: true }, - renderFrame: () => labelledFrame("Item"), - }, -); - -const List = createBlockSpec( - { - type: "list", - propSchema: {}, - content: "none", - layoutOnly: true, - children: { allow: ["item"], min: 1 }, - }, - { - renderFrame: () => { - const dom = document.createElement("div"); - return { dom, slot: dom }; - }, - }, -); - -const schema = BlockNoteSchema.create().extend({ - blockSpecs: { - reactPanel: createReactPanel(), - item: Item(), - list: List(), - }, -}); - -function item(id: string, text: string): typeof schema.PartialBlock { - return { - id, - type: "item", - children: [{ type: "paragraph", content: text }], - }; -} - -async function setupLayoutEditors( - setupEditor: SetupEditor, - ...documents: (typeof schema.PartialBlock)[][] -) { - const editors: (typeof schema.BlockNoteEditor)[] = []; - for (const initialContent of documents) { - const { editor } = await setupEditor({ schema, initialContent }); - editors.push(editor); - } - return editors; -} - -/** The element of the block with the ID. */ -function block(id: string) { - return document.querySelector(`[data-id="${id}"]`)!; -} - -function expectVisibleBlockSelection( - editor: typeof schema.BlockNoteEditor, - blockIds: string[], -) { - expect(editor.transact((tr) => tr.selection.toJSON().type)).toBe( - "multiple-node", - ); - const selection = editor.getSelectionCutBlocks(); - expect(selection.blocks.map((block) => block.id)).toEqual(blockIds); - expect(selection.blockCutAtStart).toBeUndefined(); - expect(selection.blockCutAtEnd).toBeUndefined(); - expect( - editor.domElement?.classList.contains("ProseMirror-hideselection"), - ).toBe(false); - - const nativeSelection = document.getSelection()!; - expect(nativeSelection.rangeCount).toBe(1); - expect(nativeSelection.isCollapsed).toBe(false); - const range = nativeSelection.getRangeAt(0); - for (const id of blockIds) { - expect(range.intersectsNode(block(id))).toBe(true); - } - expect(range.getBoundingClientRect().height).toBeGreaterThan(0); -} - -/** - * Where the mouse picks the block with the ID: the chrome of a layout block, or - * else the block's element. - */ -function handleOf(id: string) { - return block(id).querySelector(":scope > .label") ?? block(id); -} - -/** The IDs of the blocks. */ -function ids(blocks: { id: string }[]) { - return blocks.map((block) => block.id); -} - -/** The number of `list` blocks in a block tree. */ -function lists(blocks: (typeof schema.Block)[]): number { - return blocks.reduce( - (count, block) => - count + (block.type === "list" ? 1 : 0) + lists(block.children), - 0, - ); -} + }, + ); + const { editor } = await setupEditor({ + schema: BlockNoteSchema.create().extend({ blockSpecs: { pdf: pdf() } }), + initialContent: [ + { id: "before", type: "paragraph", content: "Before the PDF" }, + { id: "pdf", type: "pdf", props: { url: pdfUrl } }, + { id: "after", type: "paragraph", content: "After the PDF" }, + ], + }); + const originalDocument = editor.document; + const editable = editor.domElement!; + const firstParagraph = editable.querySelector( + '[data-id="before"] .bn-block-content', + )!; + const pdfBlock = editable.querySelector('[data-content-type="pdf"]')!; + editor.setTextCursorPosition("before"); + editor.focus(); + + let dropped = false; + function recordDrop(event: DragEvent) { + dropped ||= + event.isTrusted && + isDOMNode(event.target) && + firstParagraph.contains(event.target); + } + editable.addEventListener("drop", recordDrop, true); + try { + await blockDrag.move(pdfBlock, firstParagraph, false); + } finally { + editable.removeEventListener("drop", recordDrop, true); + } + + expect(dropped).toBe(true); + expect(editor.document).toEqual(originalDocument); + expect( + editable + .querySelector('embed[type="application/pdf"]') + ?.getAttribute("src"), + ).toBe(pdfUrl); + }); -// Playwright doesn't correctly simulate drag events in Firefox. -describe.skipIf(browserName === "firefox")("Dragging layout blocks", () => { - it.for([ - { name: "a React layout block", id: "reactPanel", text: "In React" }, - { - name: "a block in a React layout block", - id: "inReact", - text: "In React", - }, - ])( - "shows $name in the drag preview", - async ({ id, text }, { setupEditor, onTestFinished }) => { - await setupLayoutEditors(setupEditor, [ - { - id: "reactPanel", - type: "reactPanel", - children: [{ id: "inReact", type: "paragraph", content: "In React" }], - }, - ]); + it("drops onto a closed toggle after its target becomes highlighted", async ({ + setupEditor, + blockDrag, + positionalMouse, + }) => { + const { editor } = await setupEditor({ + initialContent: [ + { id: "toggle", type: "toggleListItem", content: "Toggle" }, + { id: "dragged", type: "paragraph", content: "Dragged" }, + ], + }); + const dragged = editor.domElement!.querySelector('[data-id="dragged"]')!; + const target = editor.domElement!.querySelector( + '[data-id="toggle"] .bn-block-content', + )!; + await blockDrag.start(dragged); + const rect = target.getBoundingClientRect(); + await positionalMouse({ + type: "move", + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + steps: 5, + }); + // A highlight that replaces the hovered DOM node can cancel a native drop. + await expect + .poll(() => target.closest('[data-drop-target="true"]')) + .not.toBeNull(); + await positionalMouse({ type: "up" }); - const drag = await startBlockDrag(handleOf(id), onTestFinished); - const preview = await waitForSelector(".bn-drag-preview"); - expect(preview.textContent).toContain(text); - const { width, height } = preview.getBoundingClientRect(); - expect(width).toBeGreaterThan(0); - expect(height).toBeGreaterThan(0); - await drag.drop(block(id), true); - }, - ); + await expect + .poll(() => editor.document.map(({ id }) => id)) + .toEqual(["toggle"]); + expect(editor.document[0].children.map(({ id }) => id)).toEqual([ + "dragged", + ]); + }); - // The preview is outside the editor, so it copies the editor's theme, - // classes and width, and app CSS that sizes the editor does not apply. - it("draws the drag preview like the editor", async ({ - onTestFinished, + it("keeps the editor's theme and width in the detached drag preview", async ({ setupEditor, + onTestFinished, + blockDrag, }) => { - const appCSS = document.createElement("style"); - appCSS.textContent = ".bn-editor { min-height: 500px; }"; - document.head.appendChild(appCSS); - onTestFinished(() => appCSS.remove()); - await setupLayoutEditors(setupEditor, [ - { - id: "table", - type: "table", - content: { type: "tableContent", rows: [{ cells: ["A", "B"] }] }, - }, - ]); + const style = document.createElement("style"); + style.textContent = ".bn-editor { min-height: 500px; }"; + document.head.appendChild(style); + onTestFinished(() => style.remove()); + const { editor, rootNode } = await setupEditor({ + initialContent: [ + { + id: "table", + type: "table", + content: { type: "tableContent", rows: [{ cells: ["A", "B"] }] }, + }, + ], + }); + const table = editor.domElement!.querySelector('[data-id="table"]')!; + const drag = await blockDrag.start(table); + const preview = document.querySelector(".bn-drag-preview")!; + const previewTable = preview.querySelector('[data-id="table"]')!; - const drag = await startBlockDrag(handleOf("table"), onTestFinished); - const preview = await waitForSelector(".bn-drag-preview"); - const copy = preview.querySelector('[data-id="table"]')!; - expect(copy.getBoundingClientRect().width).toBe( - block("table").getBoundingClientRect().width, + expect(previewTable.getBoundingClientRect().width).toBe( + table.getBoundingClientRect().width, ); expect(preview.getBoundingClientRect().height).toBeLessThan(500); expect(getComputedStyle(preview.querySelector("td")!).borderTopStyle).toBe( "solid", ); expect(preview.getAttribute("data-color-scheme")).toBe( - document + rootNode .querySelector(".bn-container")! .getAttribute("data-color-scheme"), ); - await drag.drop(block("table"), true); + await drag.drop(table, true); }); - it("moves a namedOnly layout block in its list, without a copy of the list", async ({ - setupEditor, - }) => { - const editors = await setupLayoutEditors(setupEditor, [ - { - id: "list", - type: "list", - children: [item("i1", "One"), item("i2", "Two"), item("i3", "Three")], + const Item = createBlockSpec( + { + type: "item", + propSchema: {}, + content: "none", + layoutOnly: true, + placeable: "namedOnly", + }, + { + meta: { draggable: true }, + renderFrame: () => { + const dom = document.createElement("section"); + const label = document.createElement("div"); + label.className = "item-label"; + label.contentEditable = "false"; + label.textContent = "Item"; + const slot = document.createElement("div"); + dom.append(label, slot); + return { dom, slot }; }, - ]); - - await dragAndDropBlock(handleOf("i1"), handleOf("i3"), true); - - // The item moved: the list holds the same items, and no new list. - await expect - .poll(() => ids(editors[0].document[0].children)) - .toEqual(["i2", "i1", "i3"]); - expect(lists(editors[0].document)).toBe(1); + }, + ); + const List = createBlockSpec( + { + type: "list", + propSchema: {}, + content: "none", + layoutOnly: true, + children: { allow: ["item"], min: 1 }, + }, + { + renderFrame: () => { + const dom = document.createElement("div"); + return { dom, slot: dom }; + }, + }, + ); + const schema = BlockNoteSchema.create().extend({ + blockSpecs: { item: Item(), list: List() }, }); - it("moves a namedOnly layout block into a list of another editor", async ({ + function item(id: string, text: string): typeof schema.PartialBlock { + return { + id, + type: "item", + children: [{ type: "paragraph", content: text }], + }; + } + + it("reorders named-only blocks without copying their parent layout", async ({ setupEditor, + blockDrag, }) => { - const editors = await setupLayoutEditors( - setupEditor, - [ + const { editor } = await setupEditor({ + schema, + initialContent: [ { id: "list", type: "list", - children: [item("i1", "One"), item("i2", "Two")], + children: [ + item("one", "One"), + item("two", "Two"), + item("three", "Three"), + ], }, ], - [{ id: "list2", type: "list", children: [item("j1", "Uno")] }], + }); + const [list] = editor.document; + const [one, two, three] = list.children; + const editable = editor.domElement!; + + await blockDrag.move( + editable.querySelector('[data-id="one"] .item-label')!, + editable.querySelector('[data-id="three"] .item-label')!, + true, ); - await dragAndDropBlock(handleOf("i1"), handleOf("j1"), true); - await expect - .poll(() => ids(editors[0].document[0].children)) - .toEqual(["i2"]); - // The item moved into the other list, without a new list around it. - await expect - .poll(() => - editors[1].document[0].children.map((child) => ({ - type: child.type, - text: child.children[0]?.content, - })), - ) - .toEqual( - ["One", "Uno"].map((text) => ({ - type: "item", - text: [{ type: "text", text, styles: {} }], - })), - ); - expect(lists(editors[1].document)).toBe(1); + .poll(() => editor.document) + .toEqual([{ ...list, children: [two, one, three] }]); }); -}); -// Playwright doesn't correctly simulate drag events in Firefox. -describe.skipIf(browserName === "firefox")("Dropping into a block", () => { - // The highlight of the toggle used to be set on its element directly, which - // ProseMirror read back as a DOM change and drew the toggle again: the - // browser then dropped the drag without a `drop` event. - it("drops a block onto a closed toggle as its first child", async ({ - onTestFinished, + it("moves a named-only block between editors without copying its parent layout", async ({ setupEditor, + blockDrag, }) => { - const editors = await setupLayoutEditors(setupEditor, [ - { id: "toggle", type: "toggleListItem", content: "Toggle" }, - { id: "dragged", type: "paragraph", content: "Dragged" }, - ]); + const { editor: source } = await setupEditor({ + schema, + initialContent: [ + { + id: "source", + type: "list", + children: [item("one", "One"), item("two", "Two")], + }, + ], + }); + const { editor: destination } = await setupEditor({ + schema, + initialContent: [ + { id: "destination", type: "list", children: [item("three", "Three")] }, + ], + }); + const [sourceList] = source.document; + const [destinationList] = destination.document; + const [movedItem, remainingItem] = sourceList.children; + + await blockDrag.move( + source.domElement!.querySelector('[data-id="one"] .item-label')!, + destination.domElement!.querySelector('[data-id="three"] .item-label')!, + true, + ); - await startBlockDrag(block("dragged"), onTestFinished); - const target = getRect(block("toggle").querySelector(".bn-block-content")!); - await mouseSequence([ + await expect + .poll(() => source.document) + .toEqual([{ ...sourceList, children: [remainingItem] }]); + expect(destination.document).toEqual([ { - type: "move", - x: target.x + target.width / 2, - y: target.y + target.height / 2, - steps: 5, + ...destinationList, + children: [ + { + ...movedItem, + id: expect.any(String), + children: movedItem.children.map((child) => ({ + ...child, + id: expect.any(String), + })), + }, + ...destinationList.children, + ], }, ]); - // The drop goes into the toggle once it is highlighted. - await waitForSelector("[data-drop-target]"); - // Hovers before the drop, as a user does, which gave ProseMirror the time - // to draw the toggle again. - await sleep(200); - await mouseSequence([{ type: "up" }]); - - await expect.poll(() => ids(editors[0].document)).toEqual(["toggle"]); - expect(ids(editors[0].document[0].children)).toEqual(["dragged"]); }); }); - -// Playwright doesn't correctly simulate drag events in Firefox. -describe.skipIf(browserName === "firefox")( - "Focus after dragging a block", - () => { - it("types into the moved block after dropping in the editor gutter", async ({ - onTestFinished, - setupEditor, - }) => { - const { editor } = await setupEditor({ - initialContent: [ - { id: "a", type: "paragraph", content: "Block A" }, - { id: "b", type: "paragraph", content: "Block B" }, - ], - }); - const target = getRect(block("b").querySelector(".bn-block-content")!); - await startBlockDrag(block("a"), onTestFinished); - await mouseSequence([ - { type: "move", x: target.left - 8, y: target.bottom - 2, steps: 10 }, - { type: "move", x: target.left - 7, y: target.bottom - 2 }, - { type: "up" }, - ]); - - await expect.poll(() => ids(editor.document)).toEqual(["b", "a"]); - await waitForSelectorDetached(".bn-drag-preview"); - await userEvent.keyboard("!"); - expect(block("b").textContent).toBe("Block B"); - expect(block("a").textContent).toBe("Block A!"); - }); - - // The drop leaves a text cursor in the editor, so the keyboard works on it - // right away, e.g. to undo the drop (#3165). - it("undoes a drop with the keyboard", async ({ setupEditor }) => { - const editors = await setupLayoutEditors(setupEditor, [ - { id: "a", type: "paragraph", content: "A" }, - { id: "b", type: "paragraph", content: "B" }, - ]); - - await dragAndDropBlock(block("a"), block("b"), false); - await expectElement(editors[0].domElement ?? null).toHaveFocus(); - expect(ids(editors[0].document)).toEqual(["b", "a"]); - await waitForSelectorDetached(".bn-side-menu"); - // A text cursor shows no formatting toolbar. - await waitForSelectorDetached(".bn-formatting-toolbar"); - - await userEvent.keyboard(`{${MOD}>}z{/${MOD}}`); - expect(ids(editors[0].document)).toEqual(["a", "b"]); - await expectElement(editors[0].domElement ?? null).toHaveFocus(); - expectVisibleBlockSelection(editors[0], ["a"]); - await waitForSelectorDetached(".bn-formatting-toolbar"); - }); - - it("undoes a drop into a toggle with the keyboard", async ({ - setupEditor, - }) => { - const editors = await setupLayoutEditors(setupEditor, [ - { id: "toggle", type: "toggleListItem", content: "Toggle" }, - { id: "dragged", type: "paragraph", content: "Dragged" }, - ]); - - await dragAndDropBlock( - block("dragged"), - block("toggle").querySelector(".bn-block-content")!, - false, - ); - await expectElement(editors[0].domElement ?? null).toHaveFocus(); - expect(ids(editors[0].document[0].children)).toEqual(["dragged"]); - - await userEvent.keyboard(`{${MOD}>}z{/${MOD}}`); - expect(ids(editors[0].document)).toEqual(["toggle", "dragged"]); - expectVisibleBlockSelection(editors[0], ["dragged"]); - }); - - // A dropped block without text has no place for a text cursor. - it("undoes a drop of an image with the keyboard", async ({ - setupEditor, - }) => { - const editors = await setupLayoutEditors(setupEditor, [ - { id: "a", type: "paragraph", content: "A" }, - { id: "image", type: "image" }, - { id: "b", type: "paragraph", content: "B" }, - ]); - - await dragAndDropBlock(block("image"), block("b"), false); - await expectElement(editors[0].domElement ?? null).toHaveFocus(); - expect(ids(editors[0].document)).toEqual(["a", "b", "image"]); - await waitForSelectorDetached(".bn-formatting-toolbar"); - - await userEvent.keyboard(`{${MOD}>}z{/${MOD}}`); - expect(ids(editors[0].document)).toEqual(["a", "image", "b"]); - expectVisibleBlockSelection(editors[0], ["image"]); - }); - - it("restores a visible multi-block selection after undoing a drop", async ({ - setupEditor, - }) => { - const editors = await setupLayoutEditors(setupEditor, [ - { id: "a", type: "paragraph", content: "A" }, - { id: "b", type: "paragraph", content: "B" }, - { id: "c", type: "paragraph", content: "C" }, - ]); - editors[0].setSelection("a", "b"); - - await dragAndDropBlock(block("a"), block("c"), false); - expect(ids(editors[0].document)).toEqual(["c", "a", "b"]); - await expectElement(editors[0].domElement ?? null).toHaveFocus(); - await userEvent.keyboard(`{${MOD}>}z{/${MOD}}`); - expect(ids(editors[0].document)).toEqual(["a", "b", "c"]); - expectVisibleBlockSelection(editors[0], ["a", "b"]); - await waitForSelectorDetached(".bn-formatting-toolbar"); - }); - }, -); diff --git a/tests/src/utils/mouse.ts b/tests/src/utils/mouse.ts index 5c55fa93a7..c9358b427c 100644 --- a/tests/src/utils/mouse.ts +++ b/tests/src/utils/mouse.ts @@ -1,221 +1,9 @@ -import { - expect, - onTestFinished as finishCurrentTest, - type TestContext, -} from "vite-plus/test"; -import { commands } from "./context.js"; -import { DRAG_HANDLE_SELECTOR } from "./const.js"; -import { waitForSelector } from "./editor.js"; -import type { MouseAction } from "../commands/transport/positionalMouse.js"; - -function runMouse(actions: MouseAction[]): Promise { - return commands.positionalMouse(...actions); -} - -/** Bounding rect of an element, resolved from a selector or the element itself. */ -export function getRect(selectorOrElement: string | Element): DOMRect { - const element = - typeof selectorOrElement === "string" - ? document.querySelector(selectorOrElement) - : selectorOrElement; - if (!element) { - throw new Error(`Element not found: ${JSON.stringify(selectorOrElement)}`); - } - return element.getBoundingClientRect(); -} - -function center(rect: DOMRect) { - return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; -} - -/** - * Drives the real Playwright mouse through a sequence of actions. Coordinates - * are iframe-relative (i.e. `getBoundingClientRect()` space) — see `getRect`. - */ -export function mouseSequence(actions: MouseAction[]): Promise { - return runMouse(actions); -} - -/** Single (or multi-) click at iframe-relative coordinates. */ -export function clickAt(x: number, y: number, clickCount = 1): Promise { - return runMouse([{ type: "click", x, y, clickCount }]); -} - -/** Moves the mouse to the centre of an element (e.g. to reveal hover UI). */ -export async function moveMouseOverElement( - selectorOrElement: string | Element, -) { - const element = - typeof selectorOrElement === "string" - ? await waitForSelector(selectorOrElement) - : selectorOrElement; - const { x, y } = center(element.getBoundingClientRect()); - await runMouse([{ type: "move", x, y, steps: 5 }]); -} - -/** - * Starts dragging a block by its drag handle: hovers the block to reveal the - * handle, presses on it, and moves the mouse a little, so the browser starts - * the drag. Finish it with `drag.drop(...)` or a raw `mouseSequence` mouse-up. - * Pass the calling test's cleanup hook before acquiring the native button. - */ -export async function startBlockDrag( - dragTarget: string | Element, - onTestFinished: TestContext["onTestFinished"], -) { - const owner = crypto.randomUUID(); - let started = false; - let finished = false; - - function cancel() { - return runMouse([{ type: "cancel", owner }]); - } - - // Bind to this attempt before any await. If it ends while we are still - // finding the handle, do not acquire the page's native button afterward. - onTestFinished(async () => { - finished = true; - if (started) { - await cancel(); - } - }); - - const target = - typeof dragTarget === "string" - ? await waitForSelector(dragTarget) - : dragTarget; - await moveMouseOverElement(target); - - const handle = await waitForDragHandle(target); - const handleCenter = center(handle.getBoundingClientRect()); - const previousPreview = document.querySelector(".bn-drag-preview"); - - async function cancelAfterFailure() { - try { - await cancel(); - } catch { - // The browser may have disconnected. Report the original drag failure. - } - } - - if (finished) { - throw new Error("The test ended before the drag acquired the mouse."); - } - started = true; - try { - await runMouse([ - { type: "move", x: handleCenter.x, y: handleCenter.y, steps: 5 }, - { type: "down", owner }, - { - type: "move", - x: handleCenter.x + 10, - y: handleCenter.y + 10, - steps: 5, - }, - ]); - // BlockNote creates this on native dragstart, not on mouse down. - await expect - .poll(() => { - const preview = document.querySelector(".bn-drag-preview"); - return preview !== null && preview !== previousPreview; - }) - .toBe(true); - } catch (error) { - await cancelAfterFailure(); - throw error; - } - - /** Drops on the target's left edge (`dropAbove`) or right edge. */ - async function drop(dropTarget: string | Element, dropAbove: boolean) { - try { - const dropRect = getRect(dropTarget); - const x = dropAbove ? dropRect.left + 1 : dropRect.right - 1; - const y = dropRect.top + dropRect.height / 2; - await runMouse([ - { type: "move", x, y, steps: 5, owner }, - { type: "up", owner }, - ]); - } catch (error) { - await cancelAfterFailure(); - throw error; - } - } - - return { drop }; -} - -const BLOCK_ID_SELECTOR = "[data-node-type][data-id]"; -const BLOCK_OUTER_SELECTOR = '[data-node-type="blockOuter"]'; -const BLOCK_ROOT_SELECTOR = `${BLOCK_ID_SELECTOR}:not(${BLOCK_OUTER_SELECTOR})`; - -/** Waits for the hovered block's own handle to be positioned on its row. */ -export async function waitForDragHandle(target: Element) { - const targetBlock = target.closest(BLOCK_ID_SELECTOR); - const blockId = targetBlock?.getAttribute("data-id"); - const container = target.closest(".bn-container"); - if (!targetBlock || !blockId || !container) { - throw new Error("The drag handle target must belong to an editor block."); - } - - const idSelector = `[data-id="${CSS.escape(blockId)}"]`; - const handleSelector = `${DRAG_HANDLE_SELECTOR}[data-side-menu-block-id="${CSS.escape(blockId)}"]`; - const block = targetBlock.matches(BLOCK_OUTER_SELECTOR) - ? targetBlock.querySelector(`${BLOCK_ROOT_SELECTOR}${idSelector}`) - : targetBlock; - if (!block || block.closest(".bn-container") !== container) { - throw new Error( - `Could not resolve the drag handle target block ${blockId}.`, - ); - } - - function findHandle(block: Element, container: Element) { - // A regular block's box includes its children. Find its own content row, - // even when a toggle or another frame wraps that row. Layout blocks have - // no content row of their own; the handle's block ID disambiguates them. - const row = block.matches('[data-node-type="blockContainer"]') - ? [...block.querySelectorAll(".bn-block-content")].find( - (content) => - content.closest(BLOCK_ROOT_SELECTOR) === block && - content.closest(".bn-container") === container, - ) - : block; - if (!row) { - return undefined; - } - const { top, bottom } = row.getBoundingClientRect(); - return [...container.querySelectorAll(handleSelector)].find((handle) => { - if (handle.closest(".bn-container") !== container) { - return false; - } - const { x, y } = center(handle.getBoundingClientRect()); - const button = handle.closest("button") ?? handle; - return ( - y >= top && - y <= bottom && - button.contains(document.elementFromPoint(x, y)) - ); - }); - } - - let handle: Element | undefined; - await expect - .poll(() => (handle = findHandle(block, container))) - .toBeDefined(); - return handle!; -} - -/** - * Drags a block onto another via its drag handle. Hovers the drag target to - * reveal the handle, presses on the handle, then drops on the left edge - * (`dropAbove`) or right edge of the drop target. Uses the current test's - * finish hook by default; pass the bound hook if calling from a shared fixture. - */ -export async function dragAndDropBlock( - dragTarget: string | Element, - dropTarget: string | Element, - dropAbove: boolean, - onTestFinished: TestContext["onTestFinished"] = finishCurrentTest, -) { - const drag = await startBlockDrag(dragTarget, onTestFinished); - await drag.drop(dropTarget, dropAbove); -} +export { + clickAt, + dragAndDropBlock, + getRect, + mouseSequence, + moveMouseOverElement, + startBlockDrag, + waitForDragHandle, +} from "../commands/browser/blockDrag.js"; diff --git a/tests/tsconfig.browser.json b/tests/tsconfig.browser.json index 22158adb04..8939e89b11 100644 --- a/tests/tsconfig.browser.json +++ b/tests/tsconfig.browser.json @@ -21,7 +21,6 @@ } }, "include": [ - "src/examples.d.ts", "src/utils/**/*.ts", "src/utils/**/*.tsx", "src/fixtures/**/*.tsx",