Skip to content
Merged
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,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);
},
);
});
40 changes: 13 additions & 27 deletions packages/core/src/extensions/SideMenu/blockDropHandling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: <DesktopFormattingToolbarController />,
});
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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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 }) => (
<section style={{ border: "1px solid gray", padding: 8 }}>
<div className="panel-label" contentEditable={false}>
React panel
</div>
<div ref={slotRef} />
</section>
),
},
);

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 ({
Expand Down Expand Up @@ -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);
},
);
});
});
});
Loading
Loading