diff --git a/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.gapCursor.node.test.ts b/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.gapCursor.node.test.ts new file mode 100644 index 0000000000..754c1de68f --- /dev/null +++ b/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.gapCursor.node.test.ts @@ -0,0 +1,141 @@ +// @vitest-environment node +import { GapCursor } from "@tiptap/pm/gapcursor"; +import { NodeSelection, TextSelection } from "prosemirror-state"; +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { getNodeById } from "../../../api/nodeUtil.js"; +import { type PartialBlock } from "../../../blocks/defaultBlocks.js"; +import { BlockNoteEditor } from "../../../editor/BlockNoteEditor.js"; + +const editors: BlockNoteEditor[] = []; + +afterEach(() => { + for (const editor of editors.splice(0)) { + editor._tiptapEditor.destroy(); + } +}); + +function createEditor(initialContent: PartialBlock[]) { + const editor = BlockNoteEditor.create({ + initialContent, + trailingBlock: false, + }); + editors.push(editor); + const view = editor.prosemirrorView; + view.updateState( + view.state.reconfigure({ + plugins: editor._tiptapEditor.extensionManager.plugins, + }), + ); + return editor; +} + +function pressEnter(editor: BlockNoteEditor) { + // The real keymaps only read these fields; no DOM or layout is needed. + const event = { key: "Enter", keyCode: 13 } as KeyboardEvent; + const view = editor.prosemirrorView; + expect( + view.state.plugins.some((plugin) => + plugin.props.handleKeyDown?.call(plugin, view, event), + ), + ).toBe(true); + view.state.doc.check(); + expect(view.state.selection).toBeInstanceOf(TextSelection); + expect(view.state.selection.$from.parent.type.name).toBe("paragraph"); +} + +describe("Enter at a gap cursor", () => { + // Manual ArrowUp navigation produces the inner gap at position 2, before the + // image content inside its blockContainer, not before the wrapper itself. + // These node tests pin Enter's response, not browser arrow-key geometry. + it.each(["image", "file", "video", "audio"] as const)( + "inserts above the first %s without moving its children", + (type) => { + const editor = createEditor([ + { id: "media", type, children: [{ id: "child", content: "Child" }] }, + { id: "following", content: "Following" }, + ]); + editor.transact((tr) => { + tr.setSelection(new GapCursor(tr.doc.resolve(2))); + }); + const original = editor.document; + + pressEnter(editor); + + expect(editor.document.map((block) => block.type)).toEqual([ + "paragraph", + type, + "paragraph", + ]); + expect(editor.document.slice(1)).toEqual(original); + expect(editor.getTextCursorPosition().block.id).toBe( + editor.document[0].id, + ); + }, + ); + + it.each([ + [1, 0], // Before the first wrapper. + [2, 0], // Before the first image, inside its wrapper (the reported case). + [3, 1], // After the image, inside its wrapper. + [4, 1], // Between the wrappers. + [5, 1], // Before the file, inside its wrapper. + [6, 2], // After the final file, inside its wrapper. + ])("inserts at gap %s as block %s", (pos, insertionIndex) => { + const editor = createEditor([ + { id: "image", type: "image" }, + { id: "file", type: "file" }, + ]); + editor.transact((tr) => { + tr.setSelection(new GapCursor(tr.doc.resolve(pos))); + }); + + pressEnter(editor); + + const expected = ["image", "file"]; + expected.splice(insertionIndex, 0, "paragraph"); + expect(editor.document.map((block) => block.type)).toEqual(expected); + expect(editor.getTextCursorPosition().block.id).toBe( + editor.document[insertionIndex].id, + ); + }); + + it("inserts before a nested image without outdenting it", () => { + const editor = createEditor([ + { + id: "parent", + content: "Parent", + children: [{ id: "image", type: "image" }], + }, + ]); + const image = getNodeById("image", editor.prosemirrorState.doc)!; + editor.transact((tr) => { + tr.setSelection(new GapCursor(tr.doc.resolve(image.posBeforeNode + 1))); + }); + + pressEnter(editor); + + expect(editor.document).toHaveLength(1); + expect(editor.document[0].children.map((block) => block.type)).toEqual([ + "paragraph", + "image", + ]); + expect(editor.getTextCursorPosition().block.id).toBe( + editor.document[0].children[0].id, + ); + }); + + it("still inserts below a node-selected image", () => { + const editor = createEditor([{ id: "image", type: "image" }]); + editor.transact((tr) => { + tr.setSelection(NodeSelection.create(tr.doc, 2)); + }); + + pressEnter(editor); + + expect(editor.document.map((block) => block.type)).toEqual([ + "image", + "paragraph", + ]); + }); +}); diff --git a/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts b/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts index 505eb72df0..c63876aec8 100644 --- a/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +++ b/packages/core/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts @@ -1,4 +1,5 @@ import { type ChainedCommands, Extension } from "@tiptap/core"; +import { GapCursor } from "@tiptap/pm/gapcursor"; import { Fragment, type Node } from "prosemirror-model"; import { NodeSelection, @@ -17,6 +18,7 @@ import { unnestBlock, } from "../../../api/blockManipulation/commands/nestBlock/nestBlock.js"; import { fixLayoutBlocksById } from "../../../api/blockManipulation/layoutBlocks/fixLayoutBlock.js"; +import { blockToNode } from "../../../api/nodeConversions/blockToNode.js"; import { nodeToBlock } from "../../../api/nodeConversions/nodeToBlock.js"; import { isLayoutNode } from "../../../schema/blocks/children.js"; import { splitBlockCommand } from "../../../api/blockManipulation/commands/splitBlock/splitBlock.js"; @@ -640,6 +642,35 @@ export const KeyboardShortcutsExtension = Extension.create<{ const handleEnter = (withShift = false) => { return this.editor.commands.first(({ commands, tr }) => [ + // A gap is between blocks, not inside the nearest empty block. Arrow + // navigation can place it just inside a blockContainer, before its + // content node; insert outside that wrapper without moving its children. + () => + commands.command(({ state, tr, dispatch }) => { + if (!(state.selection instanceof GapCursor)) { + return false; + } + let $pos = state.selection.$from; + if ($pos.parent.type.name === "blockContainer") { + if ($pos.parentOffset === 0) { + $pos = state.doc.resolve($pos.before()); + } else if ($pos.parentOffset === $pos.parent.content.size) { + $pos = state.doc.resolve($pos.after()); + } + } + const blockType = state.schema.nodes["blockContainer"]; + const index = $pos.index(); + if (!$pos.parent.canReplaceWith(index, index, blockType)) { + return false; + } + if (dispatch) { + const block = blockToNode({ type: "paragraph" }, state.schema); + tr.insert($pos.pos, block) + .setSelection(TextSelection.create(tr.doc, $pos.pos + 2)) + .scrollIntoView(); + } + return true; + }), // Resets an empty block (`keyboard.resetsTo`) if it resets on Enter // (`keyboard.emptyEnterResets`), e.g. an empty list item turns into a // paragraph. Its children stay. diff --git a/tests/src/end-to-end/customblocks/customblocks.test.tsx b/tests/src/end-to-end/customblocks/customblocks.test.tsx index 42c89c12b3..9d50f52fbf 100644 --- a/tests/src/end-to-end/customblocks/customblocks.test.tsx +++ b/tests/src/end-to-end/customblocks/customblocks.test.tsx @@ -1,8 +1,8 @@ import ReactCustomBlocksApp from "@examples/06-custom-schema/react-custom-blocks/src/App"; import VanillaCustomBlocksApp from "@examples/vanilla-js/react-vanilla-custom-blocks/src/App"; -import { describe, test } from "vite-plus/test"; +import { afterAll, beforeAll, describe, expect, test } from "vite-plus/test"; import { render } from "vitest-browser-react"; -import { userEvent } from "../../utils/context.js"; +import { commands, userEvent } from "../../utils/context.js"; import { EDITOR_SELECTOR } from "../../utils/const.js"; import { compareDocToSnapshot, @@ -12,6 +12,22 @@ import { } from "../../utils/editor.js"; describe("Check custom block functionality", () => { + const imageCommands = commands as unknown as { + mockCustomBlockImages(action: "install" | "remove"): Promise; + }; + beforeAll(() => imageCommands.mockCustomBlockImages("install")); + afterAll(() => imageCommands.mockCustomBlockImages("remove")); + + async function waitForImage() { + await expect + .poll( + () => + document.querySelector("img.simple-image") + ?.naturalWidth ?? 0, + ) + .toBeGreaterThan(0); + } + test("Should be able to interactively update vanilla custom blocks", async () => { await render(); await waitForSelector(EDITOR_SELECTOR); @@ -20,6 +36,7 @@ describe("Check custom block functionality", () => { await sleep(500); await compareDocToSnapshot("vanillaInteractivity"); + await waitForImage(); await expectElement(document.body).toMatchScreenshot( "vanilla-interactivity", ); @@ -33,6 +50,7 @@ describe("Check custom block functionality", () => { await sleep(500); await compareDocToSnapshot("reactInteractivity"); + await waitForImage(); await expectElement(document.body).toMatchScreenshot("react-interactivity"); }); }); diff --git a/tests/src/end-to-end/customblocks/fixtures/332x322.jpg b/tests/src/end-to-end/customblocks/fixtures/332x322.jpg new file mode 100644 index 0000000000..8287e0bd94 Binary files /dev/null and b/tests/src/end-to-end/customblocks/fixtures/332x322.jpg differ diff --git a/tests/src/end-to-end/customblocks/fixtures/800x540.png b/tests/src/end-to-end/customblocks/fixtures/800x540.png new file mode 100644 index 0000000000..7f989ad001 Binary files /dev/null and b/tests/src/end-to-end/customblocks/fixtures/800x540.png differ diff --git a/tests/src/utils/mockCustomBlockImages.ts b/tests/src/utils/mockCustomBlockImages.ts new file mode 100644 index 0000000000..0ee7740bd8 --- /dev/null +++ b/tests/src/utils/mockCustomBlockImages.ts @@ -0,0 +1,24 @@ +import { fileURLToPath } from "node:url"; +import type { BrowserCommandContext } from "vite-plus/test/node"; + +// Preserve the examples' URLs/document snapshots, but serve the exact image +// bytes locally: a screenshot must not depend on placehold.co being available. +export async function mockCustomBlockImages( + { context }: BrowserCommandContext, + action: "install" | "remove", +) { + for (const filename of ["800x540.png", "332x322.jpg"]) { + const url = `https://placehold.co/${filename}`; + if (action === "remove") { + await context.unroute(url); + } else { + const path = fileURLToPath( + new URL( + `../end-to-end/customblocks/fixtures/${filename}`, + import.meta.url, + ), + ); + await context.route(url, (route) => route.fulfill({ path })); + } + } +} diff --git a/tests/vite.config.browser.ts b/tests/vite.config.browser.ts index ac2b636bd7..6fe9023fd1 100644 --- a/tests/vite.config.browser.ts +++ b/tests/vite.config.browser.ts @@ -5,6 +5,7 @@ import { configDefaults, defineConfig, type UserConfig } from "vite-plus"; import { playwright } from "vite-plus/test/browser/providers/playwright"; import { positionalMouse } from "./src/utils/positionalMouse.js"; import { imeComposition } from "./src/utils/imeComposition.js"; +import { mockCustomBlockImages } from "./src/utils/mockCustomBlockImages.js"; // For the desktop instances: end-to-end/mobile runs only in the "android" // instance. An instance-level `exclude` replaces the resolved base exclude @@ -165,7 +166,12 @@ export default defineConfig( // still show in the HTML report (errors + stack traces don't depend // on these shots), so disable them. See `e2e:report` to view. screenshotFailures: false, - commands: { positionalMouse, imeComposition, restoreTouchEmulation }, + commands: { + positionalMouse, + imeComposition, + restoreTouchEmulation, + mockCustomBlockImages, + }, instances: [ { browser: "chromium",