Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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",
]);
});
});
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -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.
Expand Down
22 changes: 20 additions & 2 deletions tests/src/end-to-end/customblocks/customblocks.test.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<void>;
};
beforeAll(() => imageCommands.mockCustomBlockImages("install"));
afterAll(() => imageCommands.mockCustomBlockImages("remove"));

async function waitForImage() {
await expect
.poll(
() =>
document.querySelector<HTMLImageElement>("img.simple-image")
?.naturalWidth ?? 0,
)
.toBeGreaterThan(0);
}

test("Should be able to interactively update vanilla custom blocks", async () => {
await render(<VanillaCustomBlocksApp />);
await waitForSelector(EDITOR_SELECTOR);
Expand All @@ -20,6 +36,7 @@ describe("Check custom block functionality", () => {
await sleep(500);

await compareDocToSnapshot("vanillaInteractivity");
await waitForImage();
await expectElement(document.body).toMatchScreenshot(
"vanilla-interactivity",
);
Expand All @@ -33,6 +50,7 @@ describe("Check custom block functionality", () => {
await sleep(500);

await compareDocToSnapshot("reactInteractivity");
await waitForImage();
await expectElement(document.body).toMatchScreenshot("react-interactivity");
});
});
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions tests/src/utils/mockCustomBlockImages.ts
Original file line number Diff line number Diff line change
@@ -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 }));
}
}
}
8 changes: 7 additions & 1 deletion tests/vite.config.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
Loading