Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(editor): show stable image upload preview

tianma-ifa3889ee147c4
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index d22d99af..0b9a4f1b 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -82,6 +82,13 @@ import { EditorToolbar } from "./EditorToolbar";
import { EditorOutline } from "./EditorOutline";
import { EditorTagPicker } from "./EditorTagPicker";
import { useAiBubbleMenu } from "./editor/useAiBubbleMenu";
+import {
+ ImageUploadPlaceholderExtension,
+ addImageUploadPlaceholder,
+ createImageUploadPlaceholder,
+ removeImageUploadPlaceholder,
+ waitForImageSourceReady,
+} from "./editor/image-upload-placeholder";
import {
clampResourceInsertionTarget,
clearNodeSelectionAtDocumentEnd,
@@ -1211,6 +1218,16 @@ const RichEditorPane = ({
const targetMemoId = currentMemo.id;
const interactionVersionAtRequest = editorCanvasInteractionVersionRef.current;
+ const placeholderPosition = currentEditor.state.selection.from;
+ const imagePlaceholders = files
+ .filter((file) => SUPPORTED_PASTE_IMAGE_TYPES.has(file.type))
+ .map((file) => createImageUploadPlaceholder(
+ file,
+ t("editor.uploadState.imagePreparing"),
+ ));
+ imagePlaceholders.forEach((placeholder) => {
+ addImageUploadPlaceholder(currentEditor, placeholder, placeholderPosition);
+ });
void resourceInsertionLimit(async () => {
const insertionEditor = editorRef.current;
@@ -1256,6 +1273,10 @@ const RichEditorPane = ({
void queryClient.invalidateQueries({ queryKey: ["resources"] });
}
+ await Promise.all(successfulResults.map(({ value: resource }) =>
+ resource.kind === "image" ? waitForImageSourceReady(resource.url) : Promise.resolve()
+ ));
+
const activeEditor = editorRef.current;
if (memoRef.current?.id !== targetMemoId || !isEditorReady(activeEditor)) {
setImageUploadState("idle");
@@ -1331,6 +1352,11 @@ const RichEditorPane = ({
} else {
setImageUploadState("idle");
}
+ }).finally(() => {
+ const placeholderEditor = editorRef.current;
+ imagePlaceholders.forEach((placeholder) => {
+ removeImageUploadPlaceholder(placeholderEditor, placeholder);
+ });
});
}, [queryClient, repository, resourceInsertionLimit, t]);
@@ -1351,6 +1377,7 @@ const RichEditorPane = ({
allowBase64: false,
inline: false,
}),
+ ImageUploadPlaceholderExtension,
TableKit.configure({
table: { renderWrapper: true },
}),
diff --git a/apps/web/src/components/editor/image-upload-placeholder.test.mjs b/apps/web/src/components/editor/image-upload-placeholder.test.mjs
new file mode 100644
index 00000000..57ffd528
--- /dev/null
+++ b/apps/web/src/components/editor/image-upload-placeholder.test.mjs
@@ -0,0 +1,60 @@
+import { describe, expect, test } from "bun:test";
+import { Schema } from "@tiptap/pm/model";
+import { EditorState } from "@tiptap/pm/state";
+import {
+ IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY,
+ addImageUploadPlaceholder,
+ createImageUploadPlaceholderPlugin,
+ removeImageUploadPlaceholder,
+} from "./image-upload-placeholder.ts";
+
+const placeholder = {
+ id: "upload-1",
+ filename: "photo.png",
+ previewUrl: null,
+ statusLabel: "Processing image",
+};
+
+describe("image upload placeholder", () => {
+ test("appears immediately, follows document changes, and can be removed", () => {
+ const schema = new Schema({
+ nodes: {
+ doc: { content: "block+" },
+ paragraph: { content: "inline*", group: "block" },
+ text: { group: "inline" },
+ },
+ });
+ const editor = {
+ isDestroyed: false,
+ state: EditorState.create({
+ schema,
+ doc: schema.node("doc", null, [
+ schema.node("paragraph", null, schema.text("hello")),
+ ]),
+ plugins: [createImageUploadPlaceholderPlugin()],
+ }),
+ view: {
+ dispatch(transaction) {
+ editor.state = editor.state.apply(transaction);
+ },
+ },
+ };
+
+ addImageUploadPlaceholder(editor, placeholder);
+ const initialDecorations = IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY
+ .getState(editor.state)
+ ?.find(undefined, undefined, (spec) => spec.id === placeholder.id) ?? [];
+ expect(initialDecorations).toHaveLength(1);
+ expect(initialDecorations[0]?.from).toBe(1);
+
+ editor.view.dispatch(editor.state.tr.insertText("A", 1));
+ const mappedDecorations = IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY
+ .getState(editor.state)
+ ?.find(undefined, undefined, (spec) => spec.id === placeholder.id) ?? [];
+ expect(mappedDecorations).toHaveLength(1);
+ expect(mappedDecorations[0]?.from).toBe(2);
+
+ removeImageUploadPlaceholder(editor, placeholder);
+ expect(IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY.getState(editor.state)?.find()).toHaveLength(0);
+ });
+});
diff --git a/apps/web/src/components/editor/image-upload-placeholder.ts b/apps/web/src/components/editor/image-upload-placeholder.ts
new file mode 100644
index 00000000..1cf048aa
--- /dev/null
+++ b/apps/web/src/components/editor/image-upload-placeholder.ts
@@ -0,0 +1,161 @@
+import { Extension, type Editor } from "@tiptap/core";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
+import { Decoration, DecorationSet } from "@tiptap/pm/view";
+
+export type ImageUploadPlaceholder = {
+ id: string;
+ filename: string;
+ previewUrl: string | null;
+ statusLabel: string;
+};
+
+type ImageUploadPlaceholderAction =
+ | { type: "add"; placeholder: ImageUploadPlaceholder; position: number }
+ | { type: "remove"; id: string };
+
+let nextPlaceholderId = 0;
+
+export const IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY = new PluginKey<DecorationSet>(
+ "edgeever-image-upload-placeholder",
+);
+
+const renderPlaceholder = (placeholder: ImageUploadPlaceholder) => {
+ const element = document.createElement("figure");
+ element.className = "edgeever-image-upload-placeholder";
+ element.contentEditable = "false";
+ element.dataset.placeholderId = placeholder.id;
+ element.setAttribute("role", "status");
+ element.setAttribute("aria-label", `${placeholder.statusLabel}: ${placeholder.filename}`);
+
+ if (placeholder.previewUrl) {
+ const preview = document.createElement("img");
+ preview.className = "edgeever-image-upload-placeholder__preview";
+ preview.src = placeholder.previewUrl;
+ preview.alt = "";
+ preview.setAttribute("aria-hidden", "true");
+ preview.addEventListener("load", () => element.classList.add("is-preview-ready"), { once: true });
+ element.appendChild(preview);
+ }
+
+ const status = document.createElement("figcaption");
+ status.className = "edgeever-image-upload-placeholder__status";
+
+ const spinner = document.createElement("span");
+ spinner.className = "edgeever-image-upload-placeholder__spinner";
+ spinner.setAttribute("aria-hidden", "true");
+
+ const label = document.createElement("span");
+ label.textContent = placeholder.statusLabel;
+ status.appendChild(spinner);
+ status.appendChild(label);
+ element.appendChild(status);
+ return element;
+};
+
+export const createImageUploadPlaceholderPlugin = () => new Plugin<DecorationSet>({
+ key: IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY,
+ state: {
+ init: () => DecorationSet.empty,
+ apply: (transaction, decorations) => {
+ const mappedDecorations = decorations.map(transaction.mapping, transaction.doc);
+ const action = transaction.getMeta(
+ IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY,
+ ) as ImageUploadPlaceholderAction | undefined;
+
+ if (!action) return mappedDecorations;
+ if (action.type === "remove") {
+ return mappedDecorations.remove(
+ mappedDecorations.find(undefined, undefined, (spec) => spec.id === action.id),
+ );
+ }
+
+ const position = Math.max(0, Math.min(action.position, transaction.doc.content.size));
+ return mappedDecorations.add(transaction.doc, [
+ Decoration.widget(
+ position,
+ () => renderPlaceholder(action.placeholder),
+ { id: action.placeholder.id, key: action.placeholder.id, side: 1 },
+ ),
+ ]);
+ },
+ },
+ props: {
+ decorations: (state) => IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY.getState(state) ?? null,
+ },
+});
+
+export const ImageUploadPlaceholderExtension = Extension.create({
+ name: "edgeeverImageUploadPlaceholder",
+ addProseMirrorPlugins() {
+ return [createImageUploadPlaceholderPlugin()];
+ },
+});
+
+export const createImageUploadPlaceholder = (
+ file: File,
+ statusLabel: string,
+): ImageUploadPlaceholder => {
+ nextPlaceholderId += 1;
+ let previewUrl: string | null = null;
+ try {
+ previewUrl = URL.createObjectURL(file);
+ } catch {
+ // The stable skeleton remains useful when a runtime cannot create blob URLs.
+ }
+ return {
+ id: `image-upload-${nextPlaceholderId}`,
+ filename: file.name,
+ previewUrl,
+ statusLabel,
+ };
+};
+
+export const addImageUploadPlaceholder = (
+ editor: Editor,
+ placeholder: ImageUploadPlaceholder,
+ position = editor.state.selection.from,
+) => {
+ editor.view.dispatch(editor.state.tr.setMeta(IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY, {
+ type: "add",
+ placeholder,
+ position,
+ } satisfies ImageUploadPlaceholderAction));
+};
+
+export const removeImageUploadPlaceholder = (
+ editor: Editor | null | undefined,
+ placeholder: ImageUploadPlaceholder,
+) => {
+ if (editor && !editor.isDestroyed) {
+ editor.view.dispatch(editor.state.tr.setMeta(IMAGE_UPLOAD_PLACEHOLDER_PLUGIN_KEY, {
+ type: "remove",
+ id: placeholder.id,
+ } satisfies ImageUploadPlaceholderAction));
+ }
+ if (placeholder.previewUrl) {
+ URL.revokeObjectURL(placeholder.previewUrl);
+ }
+};
+
+/** Keep the local preview visible until the persisted image can paint. */
+export const waitForImageSourceReady = async (source: string, timeoutMs = 4_000) => {
+ if (typeof Image === "undefined") return;
+
+ await new Promise<void>((resolve) => {
+ const image = new Image();
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ window.clearTimeout(timeout);
+ image.onload = null;
+ image.onerror = null;
+ resolve();
+ };
+ const timeout = window.setTimeout(finish, timeoutMs);
+ image.onload = finish;
+ image.onerror = finish;
+ image.src = source;
+ if (image.complete) finish();
+ });
+};
diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.css
index 3957abba..e823ca40 100644
--- a/apps/web/src/styles/globals.css
+++ b/apps/web/src/styles/globals.css
@@ -1094,6 +1094,88 @@ textarea {
outline-offset: 3px;
}
+.ProseMirror .edgeever-image-upload-placeholder {
+ position: relative;
+ display: block;
+ width: 100%;
+ max-width: 48rem;
+ height: clamp(12rem, 42vw, 28rem);
+ overflow: hidden;
+ margin: 1rem 0;
+ border: 1px solid var(--brand-green-border);
+ border-radius: 8px;
+ background:
+ linear-gradient(110deg, transparent 24%, rgb(255 255 255 / 0.72) 42%, transparent 60%) -18rem 0 / 18rem 100% no-repeat,
+ rgb(var(--slate-100-rgb) / 0.82);
+ animation: edgeever-image-placeholder-shimmer 1.35s ease-in-out infinite;
+ line-height: normal;
+}
+
+.ProseMirror .edgeever-image-upload-placeholder__preview {
+ width: 100%;
+ height: 100%;
+ max-height: none;
+ margin: 0;
+ border: 0;
+ border-radius: 0;
+ opacity: 0;
+ object-fit: contain;
+ transition: opacity 160ms ease;
+}
+
+.ProseMirror .edgeever-image-upload-placeholder.is-preview-ready {
+ background: rgb(var(--slate-100-rgb) / 0.82);
+ animation: none;
+}
+
+.ProseMirror .edgeever-image-upload-placeholder.is-preview-ready .edgeever-image-upload-placeholder__preview {
+ opacity: 1;
+}
+
+.ProseMirror .edgeever-image-upload-placeholder__status {
+ position: absolute;
+ left: 50%;
+ bottom: 0.75rem;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ transform: translateX(-50%);
+ border: 1px solid rgb(var(--slate-300-rgb) / 0.8);
+ border-radius: 999px;
+ background: rgb(255 255 255 / 0.92);
+ padding: 0.4rem 0.75rem;
+ color: #475569;
+ box-shadow: 0 4px 16px rgb(15 23 42 / 0.12);
+ font-size: 0.75rem;
+ font-weight: 600;
+ line-height: 1;
+ white-space: nowrap;
+}
+
+.ProseMirror .edgeever-image-upload-placeholder__spinner {
+ width: 0.85rem;
+ height: 0.85rem;
+ border: 2px solid rgb(var(--brand-green-rgb) / 0.2);
+ border-top-color: var(--brand-green);
+ border-radius: 999px;
+ animation: edgeever-image-placeholder-spin 700ms linear infinite;
+}
+
+@keyframes edgeever-image-placeholder-shimmer {
+ to { background-position: calc(100% + 18rem) 0, 0 0; }
+}
+
+@keyframes edgeever-image-placeholder-spin {
+ to { transform: rotate(360deg); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ProseMirror .edgeever-image-upload-placeholder,
+ .ProseMirror .edgeever-image-upload-placeholder__spinner {
+ animation: none;
+ }
+}
+
.ProseMirror .edgeever-image-node {
position: relative;
display: block;
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 8367c487..e33b2270 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -1061,6 +1061,7 @@ export const enUS = {
uploading: "Uploading",
fileFailed: "File upload failed",
imageCompressing: "Compressing image",
+ imagePreparing: "Processing image",
fileUploading: "Uploading file",
},
notebookFallback: "Notebook",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 572d3cbb..42e66ca6 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -1061,6 +1061,7 @@ export const zhCN = {
uploading: "上传中",
fileFailed: "文件上传失败",
imageCompressing: "图片压缩中",
+ imagePreparing: "正在处理图片",
fileUploading: "文件上传中",
},
notebookFallback: "笔记本",
diff --git a/tests/e2e/markdown-image-paste.spec.ts b/tests/e2e/markdown-image-paste.spec.ts
index 61fd17af..becfcf66 100644
--- a/tests/e2e/markdown-image-paste.spec.ts
+++ b/tests/e2e/markdown-image-paste.spec.ts
@@ -32,6 +32,20 @@ const dispatchPlainTextPaste = async (editor: Locator, text: string) => {
}, text);
};
+const dispatchPngFilePaste = async (editor: Locator) => {
+ await editor.evaluate((element) => {
+ const encoded = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";
+ const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));
+ const clipboardData = new DataTransfer();
+ clipboardData.items.add(new File([bytes], "upload-feedback.png", { type: "image/png" }));
+ element.dispatchEvent(new ClipboardEvent("paste", {
+ bubbles: true,
+ cancelable: true,
+ clipboardData,
+ }));
+ });
+};
+
test("converts a pasted Markdown image line in the main Web editor", async ({ page }) => {
const title = `Markdown image paste ${Date.now()}`;
const memo = await createMemo(page, title);
@@ -107,3 +121,48 @@ test("converts a pasted Markdown image line in the standalone mobile Web editor"
await deleteMemo(page, memo.id);
}
});
+
+test("shows a stable local preview while a pasted image is uploading", async ({ page }) => {
+ const title = `Image upload feedback ${Date.now()}`;
+ const memo = await createMemo(page, title);
+ let releaseUpload: () => void = () => undefined;
+ const uploadGate = new Promise<void>((resolve) => {
+ releaseUpload = resolve;
+ });
+ let markUploadStarted: () => void = () => undefined;
+ const uploadStarted = new Promise<void>((resolve) => {
+ markUploadStarted = resolve;
+ });
+
+ try {
+ await page.route("**/api/v1/memos/*/resources", async (route) => {
+ markUploadStarted();
+ await uploadGate;
+ await route.continue();
+ });
+ await page.goto("/");
+ 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).toBeEditable();
+ await dispatchPngFilePaste(editor);
+
+ const placeholder = editor.locator(".edgeever-image-upload-placeholder");
+ await expect(placeholder).toBeVisible();
+ await expect(placeholder).toHaveClass(/is-preview-ready/);
+ expect((await placeholder.boundingBox())?.height ?? 0).toBeGreaterThan(150);
+ await uploadStarted;
+ await expect(placeholder).toBeVisible();
+
+ releaseUpload();
+ const finalImage = editor.locator(".edgeever-image-node img");
+ await expect(finalImage).toBeVisible();
+ await expect(placeholder).toHaveCount(0);
+ expect((await finalImage.boundingBox())?.height ?? 0).toBeGreaterThan(1);
+ } finally {
+ releaseUpload();
+ await deleteMemo(page, memo.id);
+ }
+});