AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(editor): retain file drop position during upload (#709)
tianma-if56770274d13b
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex a7393779..54b0c6b8 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -71,6 +71,7 @@ import {ImageUploadPlaceholderExtension,addImageUploadPlaceholder,createResourceUploadPlaceholder,+ getImageUploadPlaceholderPosition,removeImageUploadPlaceholder,waitForImageSourceReady,updateImageUploadPlaceholder,@@ -1050,7 +1051,7 @@ const RichEditorPane = ({}}, [repository, t]);- const insertResourceFiles = useCallback((files: File[]) => {+ const insertResourceFiles = useCallback((files: File[], dropPosition?: number) => {const currentMemo = memoRef.current;const currentEditor = editorRef.current;@@ -1067,7 +1068,7 @@ const RichEditorPane = ({memoRef.current?.id,);const interactionVersionAtRequest = editorCanvasInteractionVersionRef.current;- const placeholderPosition = currentEditor.state.selection.from;+ const placeholderPosition = dropPosition ?? currentEditor.state.selection.from;const placeholderByFile = new Map(files.map((file) => [file,createResourceUploadPlaceholder(file, {imagePreparing: t("editor.uploadState.imagePreparing"),@@ -1095,7 +1096,7 @@ const RichEditorPane = ({// Read the selection only after earlier resource insertions complete.// Rapid consecutive pastes otherwise race with the same stale cursor.- const insertionTarget = getResourceInsertionTarget(insertionEditor.state.selection);+ const insertionTarget = dropPosition ?? getResourceInsertionTarget(insertionEditor.state.selection);setImageUploadState("uploading");const imageReadiness: Promise<void>[] = [];@@ -1182,8 +1183,16 @@ const RichEditorPane = ({});if (content.length > 0) {+ // Drop anchors follow every document transaction, including edits made+ // while this upload was queued. Never fall back to an unrelated caret+ // if the user deleted the drop location or reset the document.+ const mappedDropPosition = dropPosition === undefined ? undefined+ : getImageUploadPlaceholderPosition(activeEditor.state, placeholders[0]!.id);+ if (mappedDropPosition === null) {+ throw new Error("The attachment drop location no longer exists");+ }const safeInsertionTarget = clampResourceInsertionTarget(- insertionTarget,+ mappedDropPosition ?? insertionTarget,activeEditor.state.doc.content.size,);const updateSelection = shouldSelectInsertedResources(@@ -1424,7 +1433,12 @@ const RichEditorPane = ({}event.preventDefault();- insertResourceFiles(getResourceFilesFromDataTransfer(event.dataTransfer));+ // Use the same coordinate lookup as ProseMirror's external drop cursor.+ // A drop inserts at a point; it must never replace the old text selection.+ const dropPosition = view.posAtCoords({ left: event.clientX, top: event.clientY });+ if (dropPosition) {+ insertResourceFiles(getResourceFilesFromDataTransfer(event.dataTransfer), dropPosition.pos);+ }return true;},},diff --git a/apps/web/src/components/editor/image-upload-placeholder.test.mjs b/apps/web/src/components/editor/image-upload-placeholder.test.mjsindex ab6ab7df..6907869e 100644--- a/apps/web/src/components/editor/image-upload-placeholder.test.mjs+++ b/apps/web/src/components/editor/image-upload-placeholder.test.mjs@@ -7,6 +7,7 @@ import {createFileUploadPlaceholder,createImageUploadPlaceholderPlugin,createResourceUploadPlaceholder,+ getImageUploadPlaceholderPosition,removeImageUploadPlaceholder,updateImageUploadPlaceholder,} from "./image-upload-placeholder.ts";@@ -128,6 +129,7 @@ describe("resource upload placeholder", () => {?.find(undefined, undefined, (spec) => spec.id === placeholder.id) ?? [];expect(initialDecorations).toHaveLength(1);expect(initialDecorations[0]?.from).toBe(1);+ expect(getImageUploadPlaceholderPosition(editor.state, placeholder.id)).toBe(1);editor.view.dispatch(editor.state.tr.insertText("A", 1));const mappedDecorations = IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY@@ -135,8 +137,48 @@ describe("resource upload placeholder", () => {?.find(undefined, undefined, (spec) => spec.id === placeholder.id) ?? [];expect(mappedDecorations).toHaveLength(1);expect(mappedDecorations[0]?.from).toBe(2);+ expect(getImageUploadPlaceholderPosition(editor.state, placeholder.id)).toBe(2);removeImageUploadPlaceholder(editor, placeholder);expect(IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY.getState(editor.state)?.find()).toHaveLength(0);+ expect(getImageUploadPlaceholderPosition(editor.state, placeholder.id)).toBeNull();+ });+});++// #709: dropped files use a mapped point, never the previous replacement selection.+describe("drop upload anchors", () => {+ const makeEditor = () => {+ const schema = new Schema({ nodes: {+ doc: { content: "block+" },+ paragraph: { content: "inline*", group: "block" },+ text: { group: "inline" },+ } });+ const editor = {+ state: EditorState.create({ schema,+ doc: schema.node("doc", null, [schema.node("paragraph", null, schema.text("before after"))]),+ plugins: [createImageUploadPlaceholderPlugin()],+ }),+ view: { dispatch(tr) { editor.state = editor.state.apply(tr); } },+ };+ return editor;+ };++ test("retains distinct queued drop points through edits before and between them", () => {+ const editor = makeEditor();+ addImageUploadPlaceholder(editor, { ...placeholder, id: "first" }, 5);+ addImageUploadPlaceholder(editor, { ...placeholder, id: "second" }, 10);+ editor.view.dispatch(editor.state.tr.insertText("ABC", 1));+ expect(getImageUploadPlaceholderPosition(editor.state, "first")).toBe(8);+ expect(getImageUploadPlaceholderPosition(editor.state, "second")).toBe(13);+ editor.view.dispatch(editor.state.tr.insertText("XY", 9));+ expect(getImageUploadPlaceholderPosition(editor.state, "first")).toBe(8);+ expect(getImageUploadPlaceholderPosition(editor.state, "second")).toBe(15);+ });++ test("does not revive an anchor whose containing content was deleted", () => {+ const editor = makeEditor();+ addImageUploadPlaceholder(editor, placeholder, 5);+ editor.view.dispatch(editor.state.tr.delete(2, 8));+ expect(getImageUploadPlaceholderPosition(editor.state, placeholder.id)).toBeNull();});});diff --git a/apps/web/src/components/editor/image-upload-placeholder.ts b/apps/web/src/components/editor/image-upload-placeholder.tsindex b069eb16..595a0647 100644--- a/apps/web/src/components/editor/image-upload-placeholder.ts+++ b/apps/web/src/components/editor/image-upload-placeholder.ts@@ -1,5 +1,5 @@import { Extension, type Editor } from "@tiptap/core";-import { Plugin, PluginKey } from "@tiptap/pm/state";+import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";import { Decoration, DecorationSet } from "@tiptap/pm/view";import { SUPPORTED_PASTE_IMAGE_TYPES } from "./editor-pane-helpers";@@ -223,3 +223,8 @@ export const waitForImageSourceReady = async (source: string, timeoutMs = 4_000)if (image.complete) finish();});};++/** Resolve an upload anchor after all edits made since the file was dropped. */+export const getImageUploadPlaceholderPosition = (state: EditorState, id: string): number | null =>+ IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY.getState(state)+ ?.find(undefined, undefined, (spec) => spec.id === id)[0]?.from ?? null;diff --git a/tests/e2e/markdown-image-paste.spec.ts b/tests/e2e/markdown-image-paste.spec.tsindex 41a2c085..b820f6a8 100644--- a/tests/e2e/markdown-image-paste.spec.ts+++ b/tests/e2e/markdown-image-paste.spec.ts@@ -65,7 +65,8 @@ test("converts a pasted Markdown image line in the main Web editor", async ({ paconst image = editor.locator(`img[src="${source}"]`);await expect(image).toHaveCount(1);await expect(image).toHaveAttribute("alt", "图片");- await expect(image).toHaveAttribute("title", "Issue 229");+ // Filenames/titles stay in the document model, not native hover tooltips.+ await expect(image).not.toHaveAttribute("title");await expect(editor).not.toContainText(markdown);const imageNode = editor.locator(".edgeever-image-node");@@ -90,6 +91,8 @@ test("converts a pasted Markdown image line in the main Web editor", async ({ paconst body = await response.json() as { memo: { contentJson: unknown } };return JSON.stringify(body.memo.contentJson);}, { timeout: 20_000 }).toContain(source);+ const saved = await (await page.request.get(`/api/v1/memos/${memo.id}`)).json();+ expect(JSON.stringify(saved.memo.contentJson)).toContain('"title":"Issue 229"');} finally {await deleteMemo(page, memo.id);}diff --git a/tests/e2e/resource-file-drop.spec.ts b/tests/e2e/resource-file-drop.spec.tsnew file mode 100644index 00000000..5dcf6898--- /dev/null+++ b/tests/e2e/resource-file-drop.spec.ts@@ -0,0 +1,94 @@+import { expect, test } from "@playwright/test";++// #709: exercise the real EditorPane drop handler, coordinates, and async upload.+// Synthetic DragEvents cannot verify Finder's native drag transport.+for (const kind of ["image", "attachment"]) {+ test(`drops an uploaded ${kind} at the indicated point and maps it through edits during upload`, async ({ page }) => {+ const title = `Drop position ${kind} ${Date.now()}`;+ const notebooks = await (await page.request.get("/api/v1/notebooks")).json();+ const created = await page.request.post("/api/v1/memos", {+ data: { notebookId: notebooks.notebooks[0].id, title,+ contentMarkdown: "FIRST paragraph\n\nMIDDLE paragraph\n\nLAST paragraph" },+ });+ expect(created.status()).toBe(201);+ const { memo } = await created.json();+ let releaseUpload = () => {};+ const gate = new Promise<void>((resolve) => { releaseUpload = resolve; });+ try {+ await page.route("**/api/v1/memos/*/resources", async (route) => {+ await gate;+ await route.continue();+ });+ await page.goto("/");+ // A prior browser session may have left focus mode on.+ const exitFocus = page.getByRole("button", { name: "退出专注模式", exact: true });+ if (await exitFocus.isVisible()) await exitFocus.click();+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();+ await page.getByPlaceholder("搜索笔记").fill(title);+ await page.locator(`[data-memo-id="${memo.id}"]`).locator("button").first().click();+ const editor = page.locator(".ProseMirror[contenteditable='true']");+ await expect(editor).toContainText("LAST paragraph");+ await editor.click();+ await editor.press(process.platform === "darwin" ? "Meta+ArrowUp" : "Control+Home");+ // A drop must not replace the old selected text.+ if (kind === "attachment") await editor.press("Shift+ArrowRight");+ await expect.poll(() => editor.evaluate(() => {+ const selection = window.getSelection();+ return selection?.anchorNode?.parentElement?.closest("p")?.textContent;+ })).toBe("FIRST paragraph");+ expect(await editor.evaluate(() => window.getSelection()?.toString()))+ .toBe(kind === "attachment" ? "F" : "");++ await editor.evaluate((element, fileKind) => {+ const paragraphs = element.querySelectorAll("p");+ const target = paragraphs[fileKind === "image" ? 2 : 1]!;+ const range = document.createRange();+ const text = target.firstChild!;+ range.setStart(text, text.textContent!.length);+ range.collapse(true);+ const rect = range.getBoundingClientRect();+ const dataTransfer = new DataTransfer();+ const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";+ dataTransfer.items.add(fileKind === "image"+ ? new File([Uint8Array.from(atob(png), (c) => c.charCodeAt(0))], "drop.png", { type: "image/png" })+ : new File(["dropped attachment"], "drop.txt", { type: "text/plain" }));+ for (const type of ["dragover", "drop"]) {+ const event = new DragEvent(type, { bubbles: true, cancelable: true,+ clientX: rect.right, clientY: (rect.top + rect.bottom) / 2, dataTransfer });+ target.dispatchEvent(event);+ }+ }, kind);+ const placeholder = editor.locator("[data-placeholder-id]");+ await expect(placeholder).toHaveCount(1);+ const followingParagraph = placeholder.locator("xpath=following::p[1]");+ if (kind === "attachment") await expect(followingParagraph).toContainText("LAST paragraph");++ // Shift the document while the upload is blocked. A saved integer would+ // now insert inside the wrong paragraph; a mapped anchor stays at its end.+ await editor.press(process.platform === "darwin" ? "Meta+ArrowUp" : "Control+Home");+ await page.keyboard.insertText("INSERTED DURING UPLOAD ");+ releaseUpload();+ await expect(placeholder).toHaveCount(0);+ if (kind === "image") {+ const image = editor.locator(".edgeever-image-node");+ await expect(image).toBeVisible();+ await expect.poll(() => editor.evaluate((element) => {+ const imageBlock = Array.from(element.children).find((child) => child.querySelector("img"));+ return imageBlock?.previousElementSibling?.textContent;+ })).toBe("LAST paragraph");+ } else {+ const attachment = editor.locator("a").filter({ hasText: "drop.txt" }).first();+ await expect(attachment).toBeVisible();+ await expect(attachment.locator("xpath=ancestor::p[1]/following-sibling::p[1]"))+ .toHaveText("LAST paragraph");+ }+ await expect(editor).toContainText("INSERTED DURING UPLOAD FIRST paragraph");+ await expect(editor).toContainText("MIDDLE paragraph");+ await expect(editor).toContainText("LAST paragraph");+ } finally {+ releaseUpload();+ await page.request.delete(`/api/v1/memos/${memo.id}`);+ await page.request.delete(`/api/v1/memos/${memo.id}?permanent=1`);+ }+ });+}