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
feat(web): support pasted Markdown images (#229)
tianma-ifb2fc6f1e8c25
diff --git a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx b/apps/web/src/components/MobileStandaloneTiptapEditor.tsxindex cf18b0aa..de72d116 100644--- a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx+++ b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx@@ -42,9 +42,13 @@ import {} from "@/lib/mobile-editor-standalone";import { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate, shouldQueueMemoSaveError } from "@/lib/sync-queue";import { EdgeEverCodeBlock, codeBlockLowlight } from "@/lib/code-block";+import { createMarkdownImagePasteRule } from "@/lib/markdown-image-paste";import { ThemeBlock } from "./ThemeBlock";const ProtectedExternalImage = Image.extend({+ addPasteRules() {+ return [createMarkdownImagePasteRule(this.type)];+ },renderHTML({ HTMLAttributes }) {const referrerPolicy = getImageReferrerPolicy(HTMLAttributes.src);return [diff --git a/apps/web/src/components/editor/ResizableImage.tsx b/apps/web/src/components/editor/ResizableImage.tsxindex 3f4c52c1..b3447add 100644--- a/apps/web/src/components/editor/ResizableImage.tsx+++ b/apps/web/src/components/editor/ResizableImage.tsx@@ -11,6 +11,7 @@ import {parseImageWidth,} from "@edgeever/shared/image-display";import { getAttachmentResourceId } from "@/lib/attachment-links";+import { createMarkdownImagePasteRule } from "@/lib/markdown-image-paste";import { cn } from "@/lib/utils";export type ImageMenuRequestDetail = {@@ -151,6 +152,9 @@ const ResizableImageNodeView = ({};export const ResizableImage = Image.extend({+ addPasteRules() {+ return [createMarkdownImagePasteRule(this.type)];+ },addAttributes() {return {...this.parent?.(),diff --git a/apps/web/src/lib/markdown-image-paste.test.mjs b/apps/web/src/lib/markdown-image-paste.test.mjsnew file mode 100644index 00000000..43c2ebb2--- /dev/null+++ b/apps/web/src/lib/markdown-image-paste.test.mjs@@ -0,0 +1,46 @@+import { describe, expect, test } from "bun:test";+import { findMarkdownImagePasteMatches } from "./markdown-image-paste.ts";++describe("findMarkdownImagePasteMatches", () => {+ test("maps a pasted Markdown image to Tiptap node attributes", () => {+ const markdown = "";++ expect(findMarkdownImagePasteMatches(markdown, markdown)).toEqual([{+ index: 0,+ text: markdown,+ data: {+ src: "https://example.com/image.webp",+ alt: "图片",+ title: "预览图",+ },+ }]);+ });++ test("finds each image when pasted as separate lines", () => {+ const first = "";+ const second = "";+ const clipboard = `${first}\n${second}`;++ expect(findMarkdownImagePasteMatches(first, clipboard)).toHaveLength(1);+ expect(findMarkdownImagePasteMatches(second, clipboard)).toEqual([{+ index: 0,+ text: second,+ data: {+ src: "https://example.com/second.png",+ alt: "second",+ title: null,+ },+ }]);+ });++ test("does not match mixed text or unsafe image sources", () => {+ expect(findMarkdownImagePasteMatches(+ "Before ",+ "Before ",+ )).toEqual([]);+ expect(findMarkdownImagePasteMatches(+ ")",+ ")",+ )).toEqual([]);+ });+});diff --git a/apps/web/src/lib/markdown-image-paste.ts b/apps/web/src/lib/markdown-image-paste.tsnew file mode 100644index 00000000..1914abdf--- /dev/null+++ b/apps/web/src/lib/markdown-image-paste.ts@@ -0,0 +1,52 @@+import {+ nodePasteRule,+ type PasteRuleMatch,+} from "@tiptap/core";+import type { NodeType } from "@tiptap/pm/model";+import {+ parseMarkdownImagePaste,+ type MarkdownImageAttributes,+} from "@edgeever/shared";++export const findMarkdownImagePasteMatches = (+ textToMatch: string,+ clipboardText: string,+): PasteRuleMatch[] => {+ const images = parseMarkdownImagePaste(clipboardText);+ if (!images) {+ return [];+ }++ const matches: PasteRuleMatch[] = [];+ let searchFrom = 0;+ for (const image of images) {+ const index = textToMatch.indexOf(image.markdown, searchFrom);+ if (index === -1) {+ continue;+ }++ matches.push({+ index,+ text: image.markdown,+ data: image.attributes,+ });+ searchFrom = index + image.markdown.length;+ }++ return matches;+};++export const createMarkdownImagePasteRule = (type: NodeType) => nodePasteRule({+ type,+ find: (text, event) => {+ if (!event?.clipboardData) {+ return [];+ }++ return findMarkdownImagePasteMatches(+ text,+ event.clipboardData.getData("text/plain"),+ );+ },+ getAttributes: (match) => match.data as MarkdownImageAttributes,+});diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 39b76fc0..edbea12e 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -6,6 +6,7 @@ export * from "./backup";export * from "./github-feedback";export * from "./image-display";export * from "./image-referrer";+export * from "./markdown-image";export * from "./memo-safety";export * from "./memo-conflict";export * from "./memo-content-style";diff --git a/packages/shared/src/markdown-image.test.mjs b/packages/shared/src/markdown-image.test.mjsnew file mode 100644index 00000000..73de6b17--- /dev/null+++ b/packages/shared/src/markdown-image.test.mjs@@ -0,0 +1,73 @@+import { describe, expect, test } from "bun:test";+import {+ isSupportedMarkdownImageSource,+ parseMarkdownImagePaste,+} from "./markdown-image.ts";++describe("parseMarkdownImagePaste", () => {+ test("parses the Markdown image syntax from Issue #229", () => {+ expect(parseMarkdownImagePaste(+ "",+ )).toEqual([{+ markdown: "",+ attributes: {+ src: "https://picui.ogmua.cn/s1/2026/08/12/6a7c64323d0a8.webp",+ alt: "图片",+ title: null,+ },+ }]);+ });++ test("preserves optional titles and parses multiple image lines", () => {+ expect(parseMarkdownImagePaste([+ "  ",+ "",+ "",+ ].join("\r\n"))).toEqual([+ {+ markdown: "",+ attributes: {+ src: "https://example.com/first.png",+ alt: "First",+ title: "First title",+ },+ },+ {+ markdown: "",+ attributes: {+ src: "http://example.com/second.jpg",+ alt: "Second",+ title: null,+ },+ },+ ]);+ });++ test("leaves prose, ordinary URLs, and malformed syntax unchanged", () => {+ expect(parseMarkdownImagePaste("Before  after")).toBeNull();+ expect(parseMarkdownImagePaste("https://example.com/image.png")).toBeNull();+ expect(parseMarkdownImagePaste("\nordinary text")).toBeNull();+ expect(parseMarkdownImagePaste(" \n")).toBeNull();+ });++ test("rejects executable, embedded, local-file, and relative sources", () => {+ for (const source of [+ "javascript:alert(1)",+ "data:image/png;base64,AAAA",+ "file:///tmp/image.png",+ "./image.png",+ ]) {+ expect(parseMarkdownImagePaste(``)).toBeNull();+ }+ });+});++describe("isSupportedMarkdownImageSource", () => {+ test("allows remote and EdgeEver-managed image sources", () => {+ expect(isSupportedMarkdownImageSource("https://example.com/image.png")).toBe(true);+ expect(isSupportedMarkdownImageSource("http://example.com/image.png")).toBe(true);+ expect(isSupportedMarkdownImageSource("/api/v1/resources/res_1/blob")).toBe(true);+ expect(isSupportedMarkdownImageSource("edgeever-resource://resource/res_1")).toBe(true);+ expect(isSupportedMarkdownImageSource("edgeever-staged://stage_1")).toBe(true);+ });+});diff --git a/packages/shared/src/markdown-image.ts b/packages/shared/src/markdown-image.tsnew file mode 100644index 00000000..1015b00d--- /dev/null+++ b/packages/shared/src/markdown-image.ts@@ -0,0 +1,81 @@+import { markdownToDoc } from "./content";++export type MarkdownImageAttributes = {+ src: string;+ alt: string | null;+ title: string | null;+};++export type MarkdownImagePasteItem = {+ markdown: string;+ attributes: MarkdownImageAttributes;+};++const INTERNAL_IMAGE_SOURCE_PREFIXES = [+ "/api/v1/resources/",+ "edgeever-resource://",+ "edgeever-staged://",+];++export const isSupportedMarkdownImageSource = (source: string): boolean => {+ const trimmed = source.trim();+ if (!trimmed) {+ return false;+ }++ if (INTERNAL_IMAGE_SOURCE_PREFIXES.some((prefix) => trimmed.startsWith(prefix))) {+ return true;+ }++ try {+ const parsed = new URL(trimmed);+ return parsed.protocol === "http:" || parsed.protocol === "https:";+ } catch {+ return false;+ }+};++const stringAttribute = (value: unknown): string | null =>+ typeof value === "string" ? value : null;++/**+ * Parses clipboard text only when every non-empty line is a standalone+ * Markdown image. This strict boundary prevents ordinary prose containing an+ * image-like fragment from being rewritten by a rich-text paste rule.+ */+export const parseMarkdownImagePaste = (clipboardText: string): MarkdownImagePasteItem[] | null => {+ const lines = clipboardText+ .replace(/\r\n?/g, "\n")+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);++ if (lines.length === 0) {+ return null;+ }++ const items: MarkdownImagePasteItem[] = [];+ for (const markdown of lines) {+ const doc = markdownToDoc(markdown);+ if (doc.content.length !== 1 || doc.content[0]?.type !== "image") {+ return null;+ }++ const attributes = doc.content[0].attrs;+ const src = stringAttribute(attributes?.src);+ if (!src || !isSupportedMarkdownImageSource(src)) {+ return null;+ }++ items.push({+ markdown,+ attributes: {+ src,+ alt: stringAttribute(attributes?.alt),+ title: stringAttribute(attributes?.title),+ },+ });+ }++ return items;+};diff --git a/tests/e2e/markdown-image-paste.spec.ts b/tests/e2e/markdown-image-paste.spec.tsnew file mode 100644index 00000000..fd6553b2--- /dev/null+++ b/tests/e2e/markdown-image-paste.spec.ts@@ -0,0 +1,92 @@+import { expect, test, type Locator, type Page } from "@playwright/test";++const createMemo = async (page: Page, title: string) => {+ const notebooksResponse = await page.request.get("/api/v1/notebooks");+ expect(notebooksResponse.ok()).toBe(true);+ const notebooks = await notebooksResponse.json() as { notebooks: Array<{ id: string }> };+ const notebookId = notebooks.notebooks[0]?.id;+ expect(notebookId).toBeTruthy();++ const createResponse = await page.request.post("/api/v1/memos", {+ data: { notebookId, title, contentMarkdown: "" },+ });+ expect(createResponse.status()).toBe(201);+ return (await createResponse.json() as { memo: { id: string } }).memo;+};++const deleteMemo = async (page: Page, memoId: string) => {+ await page.request.delete(`/api/v1/memos/${memoId}`);+ await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);+};++const dispatchPlainTextPaste = async (editor: Locator, text: string) => {+ await editor.click();+ await editor.evaluate((element, clipboardText) => {+ const clipboardData = new DataTransfer();+ clipboardData.setData("text/plain", clipboardText);+ element.dispatchEvent(new ClipboardEvent("paste", {+ bubbles: true,+ cancelable: true,+ clipboardData,+ }));+ }, text);+};++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);+ const source = "https://picui.ogmua.cn/s1/2026/08/12/6a7c64323d0a8.webp";+ const markdown = ``;++ try {+ 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 dispatchPlainTextPaste(editor, markdown);++ const image = editor.locator(`img[src="${source}"]`);+ await expect(image).toHaveCount(1);+ await expect(image).toHaveAttribute("alt", "图片");+ await expect(image).toHaveAttribute("title", "Issue 229");+ await expect(editor).not.toContainText(markdown);++ await expect.poll(async () => {+ const response = await page.request.get(`/api/v1/memos/${memo.id}`);+ const body = await response.json() as { memo: { contentJson: unknown } };+ return JSON.stringify(body.memo.contentJson);+ }, { timeout: 20_000 }).toContain(source);+ } finally {+ await deleteMemo(page, memo.id);+ }+});++test("converts a pasted Markdown image line in the standalone mobile Web editor", async ({ page }) => {+ const title = `Mobile Markdown image paste ${Date.now()}`;+ const memo = await createMemo(page, title);+ const source = "https://example.com/mobile-image.png";+ const secondSource = "https://example.com/second-mobile-image.png";+ const markdown = [+ ``,+ ``,+ ].join("\n");++ try {+ await page.setViewportSize({ width: 390, height: 844 });+ await page.goto(`/mobile-edit.html#memoId=${encodeURIComponent(memo.id)}&returnTo=%2F`);++ const editor = page.locator(".edgeever-mobile-tiptap-content[contenteditable='true']");+ await expect(editor).toBeEditable();+ await dispatchPlainTextPaste(editor, markdown);++ await expect(editor.locator("img")).toHaveCount(2);+ await expect(editor.locator(`img[src="${source}"]`)).toHaveAttribute("alt", "Mobile image");+ await expect(editor.locator(`img[src="${secondSource}"]`)).toHaveAttribute("alt", "Second mobile image");+ await expect(editor).not.toContainText(markdown);+ } finally {+ await deleteMemo(page, memo.id);+ }+});