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(web): share WeChat article HTML with phone preview
tianma-if7ab391c094fe
diff --git a/apps/web/src/components/EditorPhonePreview.tsx b/apps/web/src/components/EditorPhonePreview.tsxindex 1ad76044..54f0806f 100644--- a/apps/web/src/components/EditorPhonePreview.tsx+++ b/apps/web/src/components/EditorPhonePreview.tsx@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";import { useEditorTheme, useMermaidTheme } from "@/components/ThemeProvider";import { embedMermaidForPreview } from "@/lib/phone-preview-mermaid";import { Switch } from "@/components/ui/switch";-import { buildPhonePreviewHtml } from "@/lib/publish-layout";+import { preparePublishArticle } from "@/lib/wechat-copy";import {readEditorPhonePreviewFollowPreference,writeEditorPhonePreviewFollowPreference,@@ -30,9 +30,9 @@ type EditorPhonePreviewProps = {const BLOCK_SELECTOR ="p, h1, h2, h3, li, blockquote, pre, img, table, hr, figure, [data-edgeever-theme-block]";-export const collectPhonePreviewBlocks = (root: Element, skipTitle = "") => {- const blocks = [...root.querySelectorAll<HTMLElement>(BLOCK_SELECTOR)].filter((element) => {- if (element.matches("[data-ee-publish-chrome]") || element.closest("[data-ee-publish-chrome]")) {+export const collectPhonePreviewBlocks = (root: Element) =>+ [...root.querySelectorAll<HTMLElement>(BLOCK_SELECTOR)].filter((element) => {+ if (element.matches("[data-ee-publish-chrome], .edgeever-phone-shell-title") || element.closest("[data-ee-publish-chrome]")) {return false;}const parentBlock = element.parentElement?.closest(BLOCK_SELECTOR);@@ -42,13 +42,6 @@ export const collectPhonePreviewBlocks = (root: Element, skipTitle = "") => {return true;});- const trimmedTitle = skipTitle.trim();- if (trimmedTitle && blocks[0]?.tagName === "H1" && blocks[0].textContent?.trim() === trimmedTitle) {- return blocks.slice(1);- }- return blocks;-};-const fingerprint = (element: HTMLElement) =>`${element.tagName}:${(element.innerText || element.getAttribute("src") || "").replace(/\s+/g, " ").trim().slice(0, 48)}`;@@ -73,28 +66,26 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }const { editorTheme } = useEditorTheme();const { mermaidTheme } = useMermaidTheme();const previewSyncGeneration = useRef(0);- const [markup, setMarkup] = useState({ html: "", style: "", paper: false });+ const [markup, setMarkup] = useState({ html: "", style: "" });const [follow, setFollow] = useState(readEditorPhonePreviewFollowPreference);const previewRef = useRef<HTMLDivElement | null>(null);const syncingRef = useRef(false);useEffect(() => {if (!editor || editor.isDestroyed) {- setMarkup({ html: "", style: "", paper: false });+ setMarkup({ html: "", style: "" });return;}const sync = () => {if (editor.isDestroyed) return;const generation = ++previewSyncGeneration.current;- const nextMarkup = buildPhonePreviewHtml(editor.getHTML(), title ?? "", editorTheme);- const holder = document.createElement("div");- holder.innerHTML = nextMarkup.html;- void embedMermaidForPreview(holder, editor, mermaidTheme).then(() => {+ const root = preparePublishArticle(editor.getHTML(), editor.view.dom);+ void embedMermaidForPreview(root, editor, mermaidTheme).then(() => {if (generation !== previewSyncGeneration.current) return;setMarkup({- ...nextMarkup,- html: holder.innerHTML,+ html: root.innerHTML,+ style: root.getAttribute("style") ?? "",});});};@@ -106,7 +97,7 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }editor.off("update", sync);editor.off("create", sync);};- }, [editor, editorTheme, mermaidTheme, title]);+ }, [editor, editorTheme, mermaidTheme]);const handleFollowChange = (enabled: boolean) => {setFollow(enabled);@@ -120,7 +111,7 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }if (!preview || !scrollContainer) return;const editorBlocks = collectPhonePreviewBlocks(editorRoot);- const previewBlocks = collectPhonePreviewBlocks(preview, title);+ const previewBlocks = collectPhonePreviewBlocks(preview);if (editorBlocks.length === 0 || previewBlocks.length === 0) return;const source = blockAtReadLine(editorBlocks, scrollContainer.getBoundingClientRect().top + 72);@@ -133,7 +124,7 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }window.requestAnimationFrame(() => {syncingRef.current = false;});- }, [editor, follow, scrollContainer, title]);+ }, [editor, follow, scrollContainer]);const syncFromPreview = useCallback(() => {if (!follow || syncingRef.current || !editor || editor.isDestroyed) return;@@ -142,7 +133,7 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }if (!preview || !scrollContainer) return;const editorBlocks = collectPhonePreviewBlocks(editorRoot);- const previewBlocks = collectPhonePreviewBlocks(preview, title);+ const previewBlocks = collectPhonePreviewBlocks(preview);if (editorBlocks.length === 0 || previewBlocks.length === 0) return;const source = blockAtReadLine(previewBlocks, preview.getBoundingClientRect().top + 52);@@ -155,7 +146,7 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }window.requestAnimationFrame(() => {syncingRef.current = false;});- }, [editor, follow, scrollContainer, title]);+ }, [editor, follow, scrollContainer]);useEffect(() => {if (!follow) return;@@ -208,17 +199,15 @@ export const EditorPhonePreview = ({ editor, title, scrollContainer, className }<span className="edgeever-phone-device__lens" /></div><div- className={cn("edgeever-phone-preview", markup.paper ? "edgeever-phone-preview--article" : "edgeever-phone-preview--editor")}+ className="edgeever-phone-preview"ref={(node) => {previewRef.current = node;if (node) node.setAttribute("style", markup.style);}}>+ {title?.trim() ? <p className="edgeever-phone-shell-title">{title.trim()}</p> : null}{markup.html ? (- <div- className={markup.paper ? "edgeever-phone-article" : "ProseMirror"}- dangerouslySetInnerHTML={{ __html: markup.html }}- />+ <div className="edgeever-phone-article" dangerouslySetInnerHTML={{ __html: markup.html }} />) : (<p className="pt-10 text-center text-sm text-slate-400">{t("editor.phonePreviewEmpty")}</p>)}diff --git a/apps/web/src/lib/markdown-theme.test.mjs b/apps/web/src/lib/markdown-theme.test.mjsindex 6a4bf844..d70b65f3 100644--- a/apps/web/src/lib/markdown-theme.test.mjs+++ b/apps/web/src/lib/markdown-theme.test.mjs@@ -87,11 +87,13 @@ describe("markdown theme contracts", () => {expect(preview).toContain("edgeever-phone-device__top");expect(preview).toContain("edgeever-phone-device__home");expect(preview).not.toContain("edgeever-phone-device__status");- expect(preview).toContain("buildPhonePreviewHtml");+ expect(preview).toContain("preparePublishArticle");expect(preview).toContain("embedMermaidForPreview");expect(preview).toContain("phonePreviewFollow");expect(preview).toContain("scrollContainer");expect(preview).not.toContain("edgeever-phone-device__wifi");+ expect(preview).toContain("edgeever-phone-shell-title");+ expect(preview).not.toContain("ProseMirror");expect(editorPane).toContain("scrollContainer={editorScrollContainer}");});});diff --git a/apps/web/src/lib/publish-layout.test.mjs b/apps/web/src/lib/publish-layout.test.mjsindex 4ba43ed9..4d0c3165 100644--- a/apps/web/src/lib/publish-layout.test.mjs+++ b/apps/web/src/lib/publish-layout.test.mjs@@ -106,6 +106,13 @@ describe("copy pipeline wiring", () => {expect(source).toContain("applyPublishLayout");expect(source).toContain('"phone"');expect(source).toContain("MEMO_CONTENT_STYLE");+ expect(source).toContain("preparePublishArticle");+ expect(source).toContain("ProseMirror-separator");+ expect(source).toContain("findOriginalImage");+ expect(source).toContain("svgToWeChatImage");+ expect(source).toContain('fillStyle = "#ffffff"');+ expect(source).toContain("image/jpeg");+ expect(source).toContain("text-align: center");expect(preferenceCard).not.toContain('t("settings.publishLayoutTitle")');expect(preferenceCard).toContain('t("settings.editorThemes.letter")');});@@ -132,8 +139,8 @@ describe("copy pipeline wiring", () => {});test("phone preview markup applies the paper layout instead of raw editor chrome", () => {- const source = readFileSync(new URL("./publish-layout.ts", import.meta.url), "utf8");- expect(source).toContain("export const buildPhonePreviewHtml");- expect(source).toContain('applyPublishLayout(root, paper.layout, paper.palette, "phone")');+ const source = readFileSync(new URL("./wechat-copy.ts", import.meta.url), "utf8");+ expect(source).toContain("export const preparePublishArticle");+ expect(source).toContain('applyPublishLayout(root, paperTheme.layout, paperTheme.palette, "phone")');});});diff --git a/apps/web/src/lib/publish-layout.ts b/apps/web/src/lib/publish-layout.tsindex f79cefd7..37a6b7be 100644--- a/apps/web/src/lib/publish-layout.ts+++ b/apps/web/src/lib/publish-layout.ts@@ -767,24 +767,3 @@ export const applyPublishLayout = (applyThemeBlocks(root, layout, palette, surface);};-export const buildPhonePreviewHtml = (html: string, title = "", editorTheme?: string | null) => {- const root = document.createElement("div");- const trimmedTitle = title.trim();- if (trimmedTitle && !/^\s*<h1[\s>]/i.test(html)) {- const heading = document.createElement("h1");- heading.textContent = trimmedTitle;- root.appendChild(heading);- }- root.insertAdjacentHTML("beforeend", html);-- const paper = resolvePaperEditorTheme(editorTheme);- if (paper) {- applyPublishLayout(root, paper.layout, paper.palette, "phone");- }-- return {- html: root.innerHTML,- style: root.getAttribute("style") ?? "",- paper: Boolean(paper),- };-};diff --git a/apps/web/src/lib/wechat-copy.ts b/apps/web/src/lib/wechat-copy.tsindex f25a005d..4129900e 100644--- a/apps/web/src/lib/wechat-copy.ts+++ b/apps/web/src/lib/wechat-copy.ts@@ -208,16 +208,56 @@ const getSvgSize = (svg: string) => {};};-const svgToPng = async (svg: string) => {- const size = getSvgSize(svg);- const objectUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));+const WECHAT_MERMAID_MAX_EDGE = 1280;++const prepareSvgMarkup = (svg: string) => {+ const markup = svg.trim();+ if (/<svg\b[^>]*\sxmlns=/.test(markup)) return markup;+ return markup.replace(/<svg\b/, '<svg xmlns="http://www.w3.org/2000/svg"');+};++const canvasToJpeg = (canvas: HTMLCanvasElement, quality = 0.86) =>+ new Promise<Blob>((resolve, reject) => {+ canvas.toBlob(+ (jpeg) => {+ if (jpeg) {+ resolve(jpeg);+ return;+ }+ reject(new Error("Could not convert image to JPEG"));+ },+ "image/jpeg",+ quality,+ );+ });++const svgToWeChatImage = async (svg: string) => {+ const markup = prepareSvgMarkup(svg);+ const size = getSvgSize(markup);+ const objectUrl = URL.createObjectURL(new Blob([markup], { type: "image/svg+xml;charset=utf-8" }));try {const image = new Image();image.src = objectUrl;await image.decode();+ const naturalWidth = image.naturalWidth || size.width;+ const naturalHeight = image.naturalHeight || size.height;+ const scale = Math.min(2, WECHAT_MERMAID_MAX_EDGE / Math.max(naturalWidth, naturalHeight, 1));+ const canvas = document.createElement("canvas");+ canvas.width = Math.max(1, Math.round(naturalWidth * scale));+ canvas.height = Math.max(1, Math.round(naturalHeight * scale));+ const context = canvas.getContext("2d");+ if (!context) {+ throw new Error("Could not create image canvas");+ }+ context.fillStyle = "#ffffff";+ context.fillRect(0, 0, canvas.width, canvas.height);+ context.drawImage(image, 0, 0, canvas.width, canvas.height);+ const displayWidth = Math.min(size.width || naturalWidth, 677);+ const displayHeight = displayWidth * (naturalHeight / Math.max(naturalWidth, 1));return {- blob: await rasterizeImageElement(image, 2),- ...size,+ blob: await canvasToJpeg(canvas),+ width: displayWidth,+ height: displayHeight,};} finally {URL.revokeObjectURL(objectUrl);@@ -252,16 +292,25 @@ const embedMermaidForWeChat = async (root: HTMLElement, editor?: Editor) => {}try {- const renderedSvg = renderedBlocks[index]?.querySelector("svg")?.outerHTML;- const svg = renderedSvg || await renderMermaidSvg(source);+ let svg = "";+ try {+ svg = await renderMermaidSvg(source);+ } catch {+ svg = renderedBlocks[index]?.querySelector("svg")?.outerHTML || "";+ }+ if (!svg) return;++ const { blob, width, height } = await svgToWeChatImage(svg);+ const paragraph = document.createElement("p");+ paragraph.style.cssText = "text-align: center; margin: 1em 0;";const image = document.createElement("img");- const { blob, width, height } = await svgToPng(svg);image.src = await blobToDataUrl(blob);image.width = Math.round(width);image.height = Math.round(height);image.alt = "Mermaid diagram";- image.style.cssText = "display: block; width: auto; max-width: 100%; height: auto; max-height: 30rem; object-fit: contain; margin: 1em auto;";- pre.replaceWith(image);+ image.style.cssText = "display: inline-block; max-width: 100%; height: auto;";+ paragraph.appendChild(image);+ pre.replaceWith(paragraph);} catch {// Preserve the Mermaid source as a readable fallback when rendering fails.}@@ -276,16 +325,31 @@ const isSameOrigin = (source: string) => {}};+const isContentImage = (image: HTMLImageElement) =>+ Boolean(image.getAttribute("src")?.trim()) && !image.classList.contains("ProseMirror-separator");++const findOriginalImage = (source: string, originals: HTMLImageElement[]) => {+ const match = originals.find((image) => image.getAttribute("src") === source || image.currentSrc === source);+ if (match) return match;+ try {+ const resolved = new URL(source, window.location.href).href;+ return originals.find((image) => image.src === resolved) ?? null;+ } catch {+ return null;+ }+};+const embedImagesForWeChat = async (root: HTMLElement, originalImages: HTMLImageElement[] = []) => {- const images = Array.from(root.querySelectorAll<HTMLImageElement>("img"));- await Promise.all(images.map(async (image, index) => {+ const images = Array.from(root.querySelectorAll<HTMLImageElement>("img")).filter(isContentImage);+ const originals = originalImages.filter(isContentImage);+ await Promise.all(images.map(async (image) => {const source = image.getAttribute("src")?.trim();if (!source || source.startsWith("data:")) {return;}try {- const originalImage = originalImages[index];+ const originalImage = findOriginalImage(source, originals);if (originalImage) {image.setAttribute("src", await blobToDataUrl(await rasterizeImageElement(originalImage)));image.removeAttribute("srcset");@@ -298,12 +362,12 @@ const embedImagesForWeChat = async (root: HTMLElement, originalImages: HTMLImage}image.setAttribute("src", await blobToDataUrl(await convertImageToPng(await response.blob())));image.removeAttribute("srcset");- } catch (error) {+ } catch {// Never put a private same-origin URL into the clipboard: WeChat cannot access it.if (isSameOrigin(source)) {- throw error;+ image.removeAttribute("src");+ image.removeAttribute("srcset");}- // External images may still be reachable by the WeChat editor.}}));};@@ -343,7 +407,7 @@ const convertImageGalleriesForWeChat = (root: HTMLElement) => {});};-const readEditorCopyContext = (from?: HTMLElement | null) => {+export const readEditorCopyContext = (from?: HTMLElement | null) => {const closestContainer = from?.closest<HTMLElement>("[data-editor-theme]")?? document.querySelector<HTMLElement>("[data-editor-theme]");const editorTheme = closestContainer?.dataset.editorTheme;@@ -367,15 +431,19 @@ const readEditorCopyContext = (from?: HTMLElement | null) => {};};-export const buildWeChatClipboardHtml = async (editor: Editor) => {- const container = document.createElement("div");- container.innerHTML = editor.getHTML();- const { editorTheme, customColors, customCss } = readEditorCopyContext(editor.view.dom);+export const preparePublishArticle = (html: string, from?: HTMLElement | null) => {+ const root = document.createElement("div");+ root.innerHTML = html;+ const { editorTheme, customColors, customCss } = readEditorCopyContext(from);+ applyInlineStyles(root, editorTheme, customColors, customCss);+ convertImageGalleriesForWeChat(root);+ return root;+};- applyInlineStyles(container, editorTheme, customColors, customCss);- convertImageGalleriesForWeChat(container);+export const buildWeChatClipboardHtml = async (editor: Editor) => {+ const container = preparePublishArticle(editor.getHTML(), editor.view.dom);await embedMermaidForWeChat(container, editor);- const originalImages = Array.from(editor.view.dom.querySelectorAll<HTMLImageElement>("img"));+ const originalImages = Array.from(editor.view.dom.querySelectorAll<HTMLImageElement>("img")).filter(isContentImage);await embedImagesForWeChat(container, originalImages);return container.outerHTML;};@@ -384,11 +452,9 @@ export const copyEditorToWeChat = async (editor: Editor) =>copyHtmlToClipboard(await buildWeChatClipboardHtml(editor), editor.getText({ blockSeparator: "\n" }));export const copyMarkdownToWeChat = async (markdown: string) => {- const container = document.createElement("div");- container.innerHTML = marked.parse(markdown, { async: false, gfm: true, breaks: false });- const { editorTheme, customColors, customCss } = readEditorCopyContext();-- applyInlineStyles(container, editorTheme, customColors, customCss);+ const container = preparePublishArticle(+ marked.parse(markdown, { async: false, gfm: true, breaks: false }),+ );await embedMermaidForWeChat(container);await embedImagesForWeChat(container);await copyHtmlToClipboard(container.outerHTML, container.textContent ?? "");diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.cssindex bf3b38cd..aaf0c8ba 100644--- a/apps/web/src/styles/globals.css+++ b/apps/web/src/styles/globals.css@@ -753,6 +753,7 @@ textarea {overflow: hidden;border-radius: 40px;background: #fff;+ container-type: size;}:root.dark .edgeever-phone-device__screen {@@ -812,26 +813,28 @@ textarea {}.edgeever-phone-preview {- height: 100%;+ box-sizing: border-box;+ width: 390px;+ height: calc(100cqh * 390px / 100cqw);overflow-y: auto;overscroll-behavior: contain;padding: 48px 16px 26px;background: var(--publish-bg, #fff);+ zoom: calc(100cqw / 390px);-webkit-overflow-scrolling: touch;}-.edgeever-phone-preview .ProseMirror,.edgeever-phone-article {min-height: 0;padding: 0 0 20px;}-.edgeever-phone-preview h1 {- font-size: 24px !important;- font-weight: 800 !important;- line-height: 1.4 !important;- letter-spacing: normal !important;- margin: 0 0 12px !important;+.edgeever-phone-shell-title {+ margin: 0 0 12px;+ font-size: 17px;+ font-weight: 650;+ line-height: 1.35;+ color: #111;}.edgeever-phone-preview .edgeever-phone-mermaid {