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): match WeChat paste to the light editor
tianma-if78c22375a7c9
diff --git a/apps/web/src/lib/publish-layout.test.mjs b/apps/web/src/lib/publish-layout.test.mjsindex 01eaad0a..29161cff 100644--- a/apps/web/src/lib/publish-layout.test.mjs+++ b/apps/web/src/lib/publish-layout.test.mjs@@ -218,8 +218,17 @@ describe("copy pipeline wiring", () => {expect(source).toContain("export const preparePublishArticle");expect(source).not.toContain("applyPublishLayout");expect(source).toContain("applyLegacyWeChatStyles");- expect(source).toContain("const bold = colors ? `font-weight: 700; color: ${accent};` : \"font-weight: 700;\"");+ expect(source).toContain("const bold = colors ? `font-weight: 800; color: ${accent};` : \"font-weight: 800;\"");expect(source).toContain("accentOnly");+ expect(source).toContain("#27272a");+ expect(source).toContain("#3d4450");+ expect(source).toContain("#f3f5f7");+ expect(source).toContain("data-ee-math");+ expect(source).toContain("katex.renderToString");+ expect(source).toContain("rasterizeMathForWeChat");+ expect(source).not.toContain("#be123c");+ expect(source).not.toContain("#10b981");+ expect(source).not.toContain("#f0fdf4");expect(source).toContain('palette !== "native"');expect(source).not.toContain('palette !== "custom"');expect(preview).toContain("preparePublishArticle(editor.getHTML(), editor.view.dom)");diff --git a/apps/web/src/lib/wechat-copy.test.mjs b/apps/web/src/lib/wechat-copy.test.mjsnew file mode 100644index 00000000..e4ec1297--- /dev/null+++ b/apps/web/src/lib/wechat-copy.test.mjs@@ -0,0 +1,129 @@+import { beforeAll, describe, expect, test } from "bun:test";+import { parseHTML } from "../../../../node_modules/.bun/[email protected]/node_modules/linkedom/esm/index.js";++const window = parseHTML("<!DOCTYPE html><html><body></body></html>");+try {+ Object.defineProperty(window.document, "compatMode", { value: "CSS1Compat" });+} catch {+ // linkedom may already expose a read-only quirks flag. KaTeX still renders.+}+globalThis.document = window.document;+globalThis.Node = window.Node;+globalThis.HTMLElement = window.HTMLElement;+globalThis.getComputedStyle = typeof window.getComputedStyle === "function"+ ? window.getComputedStyle.bind(window)+ : () => ({ getPropertyValue: () => "" });++const css = (element) => (element?.style.cssText ?? "").replace(/:\s+/g, ":");++let preparePublishArticle;+let prepareMarkdownPublishArticle;++beforeAll(async () => {+ const module = await import("./wechat-copy.ts");+ preparePublishArticle = module.preparePublishArticle;+ prepareMarkdownPublishArticle = module.prepareMarkdownPublishArticle;+});++const MARKDOWN = `+> **EdgeEver** 把笔记留在你自己的账号里。++正文里的行内代码是 \`#memo=<笔记ID>\`,起步价($10+/月)。++| 成本 | 商业订阅高昂($10+/月) | 官方云同步收费($5+/月) |+| --- | --- | --- |++- **行内公式**:例如质能方程 $E = mc^2$。+- **多行独立公式块**:+$$+\oint_{\\partial \\Omega} \\mathbf{E} \\cdot d\\mathbf{S} = \\frac{1}{\\varepsilon_0} \\iiint_{\\Omega} \\rho \\, dV+$$++- [x] 已完成的待办+- [ ] 未完成的待办++\`\`\`sh+# 官方 GHCR 镜像+curl -fsSL https://edgeever.org/install.sh | bash+\`\`\`+`;++describe("preparePublishArticle", () => {+ test("matches the light editor instead of the old rose-and-green paste", () => {+ const root = preparePublishArticle([+ "<blockquote><p>引用</p></blockquote>",+ "<p>正文 <strong>重点</strong> <code>token</code></p>",+ "<h2>标题</h2>",+ "<hr>",+ "<hr data-edgeever-merge-divider>",+ "<pre><code class=\"language-sh\"># 官方 GHCR 镜像\\ncurl</code></pre>",+ "<ul data-type=\"taskList\"><li data-checked=\"true\"><label><input type=\"checkbox\" checked></label><div><p>已完成</p></div></li></ul>",+ "<span data-type=\"inline-math\" data-latex=\"E = mc^2\"></span>",+ "<p>#memo 话题</p>",+ ].join(""));++ const quote = root.querySelector("blockquote");+ expect(css(quote)).toContain("background:#f3f5f7");+ expect(css(quote)).toContain("color:#3d4450");+ expect(css(quote)).toContain("border:0");+ expect(css(quote)).not.toContain("10b981");+ expect(css(quote.querySelector("p"))).toContain("color:#3d4450");+ expect(css(quote.querySelector("p"))).not.toContain("#27272a");+ const body = root.querySelector("blockquote").nextElementSibling;+ expect(css(body)).toContain("color:#27272a");+ expect(css(root.querySelector("strong"))).toContain("font-weight:800");+ const inlineCode = body.querySelector("code");+ expect(css(inlineCode)).toContain("color:#3d4450");+ expect(css(inlineCode)).toContain("background:#f3f5f7");+ expect(css(root.querySelector("h2"))).toContain("font-weight:600");+ expect(css(root.querySelector("h2"))).toContain("color:#27272a");+ const [rule, merge] = root.querySelectorAll("hr");+ expect(css(rule)).toContain("1px solid #1a1d21");+ expect(css(merge)).toContain("2px solid #1a1d21");++ const math = root.querySelector("[data-ee-math='inline']");+ expect(math?.querySelector(".katex")).toBeTruthy();+ expect(math?.textContent).not.toContain("$E");+ expect(root.querySelector("input")).toBeNull();+ expect(root.querySelector("[data-ee-task='checked']")?.textContent).toBe("☑ ");+ expect(root.textContent).toContain("已完成");+ const checked = root.querySelector("[data-ee-task='checked']")?.parentElement;+ expect(css(checked)).toContain("color:#737373");+ expect(css(checked)).toContain("line-through");++ const highlighted = root.querySelector("pre code");+ expect(highlighted?.querySelector("span[style*='color']")).toBeTruthy();+ expect(highlighted?.textContent).toContain("# 官方");+ expect(highlighted?.textContent).not.toContain("#\u200b官方");+ expect(root.textContent).toContain("#\u200bmemo");+ expect(root.innerHTML).not.toContain("#be123c");+ expect(root.innerHTML).not.toContain("#10b981");+ });+});++describe("prepareMarkdownPublishArticle", () => {+ test("renders formulas, keeps currency, and colors the shell snippet", () => {+ const root = prepareMarkdownPublishArticle(MARKDOWN);+ const html = root.innerHTML;++ expect(root.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(2);+ expect(root.querySelector("[data-ee-math='block'] .katex")).toBeTruthy();+ expect(root.querySelector(".katex-error")).toBeNull();+ const taskList = root.querySelector("[data-ee-task]")?.closest("ul");+ expect(css(taskList)).not.toContain("list-style-type");+ expect(css(taskList)).toContain("list-style:none");+ expect(html).toContain("$10+/月");+ expect(html).toContain("$5+/月");+ expect(html).not.toContain("$E = mc^2$");+ expect(root.querySelector("input[type='checkbox']")).toBeNull();+ expect(root.textContent).toContain("☑ ");+ expect(root.textContent).toContain("☐ ");+ expect(root.textContent).toContain("#\u200bmemo");+ const code = root.querySelector("pre code");+ expect(code?.textContent).toContain("# 官方 GHCR 镜像");+ expect(code?.textContent).not.toContain("#\u200b");+ expect(code?.querySelector("span[style*='#6a737d']")).toBeTruthy();+ expect(css(root.querySelector("blockquote"))).toContain("background:#f3f5f7");+ expect(css(root.querySelector("blockquote p"))).toContain("color:#3d4450");+ });+});diff --git a/apps/web/src/lib/wechat-copy.ts b/apps/web/src/lib/wechat-copy.tsindex df6f6c9e..18f26958 100644--- a/apps/web/src/lib/wechat-copy.ts+++ b/apps/web/src/lib/wechat-copy.ts@@ -9,20 +9,32 @@ import {parseNoteProseLineHeight,type NoteProsePaletteColors,} from "@edgeever/shared";+import katex from "katex";+import { common, createLowlight } from "lowlight";+import { toCanvas } from "html-to-image";import { marked } from "marked";import { MERMAID_THEME_PALETTES } from "@/components/ThemeProvider";import { copyHtmlToClipboard } from "@/lib/clipboard";import { parseCustomCssToStyles } from "@/lib/css-sandbox";const PARAGRAPH_SPACING = `${NOTE_PROSE_PARAGRAPH_SPACING_PX}px`;+const PUBLISH_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', sans-serif";+const PUBLISH_MONO = "'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace";+const BODY_COLOR = "#27272a";+const QUOTE_COLOR = "#3d4450";+const CODE_COLOR = "#3d4450";+const CODE_BACKGROUND = "#f3f5f7";+const CODE_BORDER = "#e1e5ea";+const LINK_COLOR = "#404040";+const CHECKED_TASK_COLOR = "#737373";const HEADING_LAYOUT = {- h1: { margin: "1.2em 0 0.6em", lineHeight: 1.35 },- h2: { margin: "1.1em 0 0.55em", lineHeight: 1.4 },- h3: { margin: "1em 0 0.5em", lineHeight: 1.45 },- h4: { margin: "0.95em 0 0.45em", lineHeight: 1.5 },- h5: { margin: "0.9em 0 0.4em", lineHeight: 1.5 },- h6: { margin: "0.85em 0 0.35em", lineHeight: 1.5 },+ h1: { margin: "0 0 14px", lineHeight: 1.28, weight: 650, tracking: "-0.02em", color: "#1a1d21" },+ h2: { margin: "22px 0 10px", lineHeight: 1.32, weight: 600, tracking: "-0.015em", color: "#27272a" },+ h3: { margin: "18px 0 8px", lineHeight: 1.38, weight: 600, tracking: "-0.01em", color: "#27272a" },+ h4: { margin: "17px 0 7px", lineHeight: 1.4, weight: 600, tracking: "-0.006em", color: "#1e293b" },+ h5: { margin: "15px 0 6px", lineHeight: 1.42, weight: 600, tracking: "-0.005em", color: "#334155" },+ h6: { margin: "14px 0 6px", lineHeight: 1.45, weight: 600, tracking: "-0.005em", color: "#334155" },} as const;type WeChatMetrics = {@@ -30,87 +42,74 @@ type WeChatMetrics = {lineHeight: number;};-const headingStyle = (tag: keyof typeof HEADING_LAYOUT, metrics: WeChatMetrics, color: string) => {+const headingStyle = (tag: keyof typeof HEADING_LAYOUT, metrics: WeChatMetrics) => {const layout = HEADING_LAYOUT[tag];const size = Math.round(metrics.fontSize * NOTE_PROSE_HEADING_SCALE[tag]);- return `margin: ${layout.margin}; font-size: ${size}px; line-height: ${layout.lineHeight}; font-weight: 700; color: ${color};`;+ return `margin: ${layout.margin}; padding: 0; font-family: ${PUBLISH_FONT}; font-size: ${size}px; line-height: ${layout.lineHeight}; font-weight: ${layout.weight}; letter-spacing: ${layout.tracking}; color: ${layout.color};`;};const applyLegacyWeChatStyles = (root: HTMLElement,metrics: WeChatMetrics,colors: NoteProsePaletteColors | null,- accentOnly = false,+ _accentOnly = false,) => {const fontSize = `${metrics.fontSize}px`;const lineHeight = String(metrics.lineHeight);const codeSize = `${noteProseCodeFontSize(metrics.fontSize)}px`;- // Named hues move link, inline-code, and bold ink. The rest stays on the WeChat defaults.- const painted = accentOnly ? null : colors;- const text = painted?.text ?? "#333";- const headingColor = painted?.text ?? "#1f2937";- const background = painted?.background ?? "#ffffff";- const accent = colors?.accent ?? "#059669";- const quoteBorder = painted?.accent ?? "#10b981";- const quoteBackground = painted?.surface ?? "#f0fdf4";- const quoteColor = painted?.muted ?? "#4b5563";- const link = colors?.link ?? "#059669";- const inlineCodeBackground = painted?.codeBackground ?? "#f3f4f6";- const inlineCodeColor = (accentOnly ? colors?.codeText : painted?.codeText) ?? "#be123c";- const preBackground = painted?.codeBackground ?? "#f6f8fa";- const preColor = painted?.codeText ?? "#24292f";- const ruleColor = painted?.divider ?? "#e5e7eb";- const cellBorder = painted?.divider ?? "#d1d5db";- const headBackground = painted?.surface ?? "#f3f4f6";- const cellColor = painted ? ` color: ${text};` : "";- const bold = colors ? `font-weight: 700; color: ${accent};` : "font-weight: 700;";+ // A named hue only recolors links, inline code, and bold, matching the editor.+ const link = colors?.link ?? LINK_COLOR;+ const inlineCodeColor = colors?.codeText ?? CODE_COLOR;+ const accent = colors?.accent ?? BODY_COLOR;+ const bold = colors ? `font-weight: 800; color: ${accent};` : "font-weight: 800;";+ const textStyle = `font-family: ${PUBLISH_FONT}; font-size: ${fontSize}; line-height: ${lineHeight}; letter-spacing: -0.005em; color: ${BODY_COLOR};`;const styles: Record<string, string> = {- p: `margin: 0 0 ${PARAGRAPH_SPACING}; padding: 0; line-height: ${lineHeight}; font-size: ${fontSize}; color: ${text};`,- h1: headingStyle("h1", metrics, headingColor),- h2: headingStyle("h2", metrics, headingColor),- h3: headingStyle("h3", metrics, headingColor),- h4: headingStyle("h4", metrics, headingColor),- h5: headingStyle("h5", metrics, headingColor),- h6: headingStyle("h6", metrics, headingColor),- blockquote: `margin: 1em 0; padding: 0.6em 1em; border-left: 4px solid ${quoteBorder}; background: ${quoteBackground}; color: ${quoteColor}; line-height: ${lineHeight};`,- ul: `margin: 0 0 1em; padding-left: 1.6em; line-height: ${lineHeight};`,- ol: `margin: 0 0 1em; padding-left: 1.6em; line-height: ${lineHeight};`,- li: `margin: 0.25em 0; line-height: ${lineHeight};`,- a: `color: ${link}; text-decoration: underline;`,+ p: `margin: 0 0 ${PARAGRAPH_SPACING}; padding: 0; ${textStyle}`,+ h1: headingStyle("h1", metrics),+ h2: headingStyle("h2", metrics),+ h3: headingStyle("h3", metrics),+ h4: headingStyle("h4", metrics),+ h5: headingStyle("h5", metrics),+ h6: headingStyle("h6", metrics),+ blockquote: `margin: 0 0 16px; padding: 12px 16px; border: 0; border-radius: 8px; background: #f3f5f7; color: ${QUOTE_COLOR}; font-family: ${PUBLISH_FONT}; line-height: ${lineHeight};`,+ ul: `margin: 0 0 16px; padding-left: 24px; line-height: ${lineHeight}; list-style-type: disc;`,+ ol: `margin: 0 0 16px; padding-left: 24px; line-height: ${lineHeight}; list-style-type: decimal;`,+ li: `margin: 4px 0; line-height: ${lineHeight}; ${textStyle}`,+ a: `color: ${link}; font-weight: 500; text-decoration: underline; text-underline-offset: 2px;`,strong: bold,b: bold,em: "font-style: italic;",del: "text-decoration: line-through;",- code: `padding: 0.15em 0.35em; border-radius: 3px; background: ${inlineCodeBackground}; color: ${inlineCodeColor}; font-family: Menlo, Consolas, monospace; font-size: ${codeSize};`,- pre: `margin: 1em 0; padding: 12px 14px; overflow: hidden; border-radius: 6px; background: ${preBackground}; color: ${preColor}; line-height: 1.6; text-align: left;`,- hr: `margin: 1.5em 0; border: 0; border-top: 1px solid ${ruleColor};`,- table: `width: 100%; margin: 1em 0; border-collapse: collapse; font-size: ${fontSize}; line-height: 1.6;`,- th: `padding: 8px; border: 1px solid ${cellBorder}; background: ${headBackground}; font-weight: 700; text-align: left;${cellColor}`,- td: `padding: 8px; border: 1px solid ${cellBorder}; text-align: left;${cellColor}`,- img: "display: block; max-width: 100%; height: auto; margin: 1em auto;",+ code: `padding: 2px 6px; border: 1px solid ${CODE_BORDER}; border-radius: 4px; background: ${CODE_BACKGROUND}; color: ${inlineCodeColor}; font-family: ${PUBLISH_MONO}; font-size: ${codeSize}; font-weight: 550;`,+ pre: `margin: 0 0 16px; padding: 14px 16px; overflow: hidden; border: 1px solid #e4e4e4; border-radius: 8px; background: #fafafa; color: #0f172a; font-family: ${PUBLISH_MONO}; font-size: ${codeSize}; line-height: 1.6; text-align: left; white-space: pre-wrap;`,+ hr: "margin: 24px 0; border: 0; border-top: 1px solid #1a1d21;",+ table: `width: 100%; margin: 20px 0; border-collapse: collapse; font-size: ${fontSize}; line-height: 1.45;`,+ th: "padding: 8px 13px; border: 1px solid #e5e5e5; background: #f5f5f5; color: #0f172a; font-weight: 600; font-size: 13px; text-align: left;",+ td: `padding: 8px 13px; border: 1px solid #e5e5e5; color: ${BODY_COLOR}; text-align: left;`,+ img: "display: block; max-width: 100%; height: auto; margin: 16px 0; border: 1px solid #b8dfd0; border-radius: 8px;",};- root.style.cssText = `font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: ${fontSize}; line-height: ${lineHeight}; color: ${text}; background-color: ${background}; word-break: break-word;`;+ root.style.cssText = `${textStyle} background-color: #ffffff; word-break: break-word;`;root.querySelectorAll<HTMLElement>("*").forEach((element) => {+ if (element.closest("[data-ee-math]")) return;const tagName = element.tagName.toLowerCase();const isMergeDivider =tagName === "hr" && element.matches("[data-edgeever-merge-divider], .edgeever-merge-divider");+ const quoted = (tagName === "p" || tagName === "li") && element.closest("blockquote");+ const baseStyle = styles[tagName] || "";+ // One color declaration. A second `color` later in the attribute is easy for WeChat to drop.const style = isMergeDivider- ? `margin: 1.75em 0; border: 0; border-top: 2px solid ${accent};`- : styles[tagName] || "";+ ? "margin: 24px 0; border: 0; border-top: 2px solid #1a1d21;"+ : quoted+ ? baseStyle.replace(/(^|;)\s*color:\s*[^;]+/i, `$1 color: ${QUOTE_COLOR}`)+ : baseStyle;if (style) element.style.cssText = `${style}${element.style.cssText}`;});root.querySelectorAll<HTMLElement>("pre code").forEach((element) => {- element.style.cssText = `padding: 0; background: transparent; color: inherit; font-family: Menlo, Consolas, monospace; font-size: ${codeSize}; white-space: pre-wrap;`;+ element.style.cssText = `padding: 0; border: 0; background: transparent; color: inherit; font-family: ${PUBLISH_MONO}; font-size: ${codeSize}; font-weight: 400; white-space: pre-wrap;`;});-- if (colors?.accent) {- root.querySelectorAll<HTMLElement>('ul[data-type="taskList"] li[data-checked] > label input').forEach((element) => {- element.style.accentColor = colors.accent;- });- }};const applyInlineStyles = (@@ -127,6 +126,7 @@ const applyInlineStyles = (root.querySelectorAll<HTMLElement>("*").forEach((element) => {if (element.getAttribute("data-ee-publish-chrome") === "true") return;+ if (element.closest("[data-ee-math]")) return;const extra = customStyles[element.tagName.toLowerCase()];if (extra) element.style.cssText = `${element.style.cssText}; ${extra}`;});@@ -475,6 +475,519 @@ const convertImageGalleriesForWeChat = (root: HTMLElement) => {});};+const publishLowlight = createLowlight(common);+for (const [language, aliases] of [+ ["bash", ["sh", "zsh"]],+ ["yaml", ["yml"]],+] as const) {+ const missing = aliases.filter((alias) => !publishLowlight.registered(alias));+ if (missing.length > 0) publishLowlight.registerAlias({ [language]: missing });+}++const HLJS_COLORS: Record<string, string> = {+ "hljs-doctag": "#d73a49",+ "hljs-keyword": "#d73a49",+ "hljs-template-tag": "#d73a49",+ "hljs-template-variable": "#d73a49",+ "hljs-type": "#d73a49",+ "hljs-title": "#6f42c1",+ "hljs-attr": "#005cc5",+ "hljs-attribute": "#005cc5",+ "hljs-literal": "#005cc5",+ "hljs-meta": "#005cc5",+ "hljs-number": "#005cc5",+ "hljs-operator": "#005cc5",+ "hljs-variable": "#005cc5",+ "hljs-selector-attr": "#005cc5",+ "hljs-selector-class": "#005cc5",+ "hljs-selector-id": "#005cc5",+ "hljs-regexp": "#032f62",+ "hljs-string": "#032f62",+ "hljs-built_in": "#e36209",+ "hljs-symbol": "#e36209",+ "hljs-comment": "#6a737d",+ "hljs-code": "#6a737d",+ "hljs-formula": "#6a737d",+ "hljs-name": "#22863a",+ "hljs-quote": "#22863a",+ "hljs-selector-tag": "#22863a",+ "hljs-selector-pseudo": "#22863a",+ "hljs-subst": "#24292e",+ "hljs-section": "#005cc5",+ "hljs-bullet": "#735c0f",+ "hljs-emphasis": "#24292e",+ "hljs-strong": "#24292e",+ "hljs-addition": "#22863a",+ "hljs-deletion": "#b31d28",+};++type HastNode = {+ type: string;+ value?: string;+ tagName?: string;+ properties?: { className?: string | string[] };+ children?: HastNode[];+};++const isEscaped = (source: string, index: number) => {+ let backslashCount = 0;+ for (let cursor = index - 1; cursor >= 0 && source[cursor] === "\\"; cursor -= 1) {+ backslashCount += 1;+ }+ return backslashCount % 2 === 1;+};++const findClosingDelimiter = (source: string, delimiter: "$" | "$$", from: number) => {+ for (let index = from; index <= source.length - delimiter.length; index += 1) {+ if (source.startsWith(delimiter, index) && !isEscaped(source, index)) return index;+ }+ return -1;+};++const escapeHtmlAttribute = (value: string) => value+ .replace(/&/g, "&")+ .replace(/"/g, """)+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/\r?\n/g, " ");++const inlineMathHtml = (latex: string) =>+ `<span data-type="inline-math" data-latex="${escapeHtmlAttribute(latex)}"></span>`;++const blockMathHtml = (latex: string) =>+ `\n\n<div data-type="block-math" data-latex="${escapeHtmlAttribute(latex)}"></div>\n\n`;++/** Inline `$...$` only. A later `$` in another table cell must not close an unclosed price. */+const embedInlineMath = (source: string) => {+ let output = "";+ let index = 0;+ while (index < source.length) {+ if (source[index] === "`") {+ let ticks = 0;+ while (source[index + ticks] === "`") ticks += 1;+ const token = "`".repeat(ticks);+ const close = source.indexOf(token, index + ticks);+ if (close < 0) return output + source.slice(index);+ const end = close + ticks;+ output += source.slice(index, end);+ index = end;+ continue;+ }+ if (source[index] === "$" && !source.startsWith("$$", index) && !isEscaped(source, index)) {+ const close = findClosingDelimiter(source, "$", index + 1);+ if (close > index && source[close + 1] !== "$") {+ const latex = source.slice(index + 1, close).trim();+ if (latex && !latex.includes("\n") && !isPureCurrency(latex)) {+ output += inlineMathHtml(latex);+ index = close + 1;+ continue;+ }+ if (latex && isPureCurrency(latex)) {+ output += source.slice(index, close + 1);+ index = close + 1;+ continue;+ }+ }+ }+ output += source[index];+ index += 1;+ }+ return output;+};++const isPureCurrency = (latex: string) => /^\d+(?:[.,]\d+)?$/u.test(latex);++/** Turn `$...$` / `$$...$$` into math nodes before Markdown parsing. Fences and inline code stay literal. */+const embedMarkdownMath = (markdown: string) => {+ let output = "";+ let index = 0;+ while (index < markdown.length) {+ const atLineStart = index === 0 || markdown[index - 1] === "\n";+ if (atLineStart) {+ const lineBreak = markdown.indexOf("\n", index);+ const lineEnd = lineBreak < 0 ? markdown.length : lineBreak;+ const line = markdown.slice(index, lineEnd);+ // Scan each cell on its own so `$10+/月` in one cell cannot close on `$5+/月` in the next.+ if (/^\s*\|.*\|\s*$/u.test(line) && !line.includes("$$")) {+ output += line.split("|").map((cell) => embedInlineMath(cell)).join("|");+ if (lineBreak >= 0) output += "\n";+ index = lineBreak < 0 ? markdown.length : lineBreak + 1;+ continue;+ }+ }+ if (atLineStart && (markdown.startsWith("```", index) || markdown.startsWith("~~~", index))) {+ const fenceChar = markdown[index];+ let fenceLength = 0;+ while (markdown[index + fenceLength] === fenceChar) fenceLength += 1;+ const fence = markdown.slice(index, index + fenceLength);+ let cursor = markdown.indexOf("\n", index);+ cursor = cursor < 0 ? markdown.length : cursor + 1;+ let close = -1;+ while (cursor <= markdown.length) {+ const next = markdown.indexOf("\n", cursor);+ const lineEnd = next < 0 ? markdown.length : next;+ const line = markdown.slice(cursor, lineEnd).trim();+ const fenceOnly = line.length >= fenceLength && [...line].every((char) => char === fenceChar);+ if (fenceOnly && line.startsWith(fence)) {+ close = next < 0 ? markdown.length : next + 1;+ break;+ }+ if (next < 0) break;+ cursor = next + 1;+ }+ const end = close < 0 ? markdown.length : close;+ output += markdown.slice(index, end);+ index = end;+ continue;+ }++ if (markdown[index] === "`") {+ let ticks = 0;+ while (markdown[index + ticks] === "`") ticks += 1;+ const token = "`".repeat(ticks);+ const close = markdown.indexOf(token, index + ticks);+ if (close < 0) {+ output += markdown.slice(index);+ break;+ }+ const end = close + ticks;+ output += markdown.slice(index, end);+ index = end;+ continue;+ }++ if (atLineStart && markdown.startsWith("$$", index) && !isEscaped(markdown, index)) {+ const lineBreak = markdown.indexOf("\n", index);+ const lineEnd = lineBreak < 0 ? markdown.length : lineBreak;+ const line = markdown.slice(index, lineEnd).trim();+ const sameLine = /^\$\$([\s\S]*?)\$\$$/u.exec(line);+ if (sameLine?.[1]?.trim()) {+ output += blockMathHtml(sameLine[1].trim());+ index = lineBreak < 0 ? markdown.length : lineBreak + 1;+ continue;+ }+ if (line === "$$") {+ const close = findClosingDelimiter(markdown, "$$", lineEnd + 1);+ const latex = close >= 0 ? markdown.slice(lineEnd + 1, close).trim() : "";+ const after = close + 2;+ const nextBreak = close >= 0 ? markdown.indexOf("\n", after) : -1;+ const restOfLine = close >= 0+ ? markdown.slice(after, nextBreak < 0 ? markdown.length : nextBreak).trim()+ : "kept";+ if (latex && restOfLine === "") {+ output += blockMathHtml(latex);+ index = nextBreak < 0 ? markdown.length : nextBreak + 1;+ continue;+ }+ }+ }++ if (markdown[index] === "$" && !markdown.startsWith("$$", index) && !isEscaped(markdown, index)) {+ const close = findClosingDelimiter(markdown, "$", index + 1);+ if (close > index && markdown[close + 1] !== "$") {+ const latex = markdown.slice(index + 1, close).trim();+ if (latex && !latex.includes("\n") && !isPureCurrency(latex)) {+ output += inlineMathHtml(latex);+ index = close + 1;+ continue;+ }+ if (latex && isPureCurrency(latex)) {+ output += markdown.slice(index, close + 1);+ index = close + 1;+ continue;+ }+ }+ }++ output += markdown[index];+ index += 1;+ }+ return output;+};++const renderKatexHtml = (latex: string, displayMode: boolean) => {+ const trimmed = latex.trim();+ if (!trimmed) return "";+ try {+ return katex.renderToString(trimmed, {+ displayMode,+ throwOnError: false,+ strict: "warn",+ trust: false,+ output: "html",+ });+ } catch {+ return "";+ }+};++const mountMath = (latex: string, kind: "inline" | "block", metrics: WeChatMetrics) => {+ const host = document.createElement("span");+ host.setAttribute("data-ee-math", kind);+ host.setAttribute("data-latex", latex.trim());+ const codeSize = `${noteProseCodeFontSize(metrics.fontSize)}px`;+ const html = renderKatexHtml(latex, kind === "block");+ host.style.cssText = kind === "block"+ ? `display: block; margin: 16px 0; text-align: center; font-size: ${codeSize}; color: ${BODY_COLOR};`+ : `font-size: ${codeSize}; color: ${BODY_COLOR};`;+ if (html) host.innerHTML = html;+ else host.textContent = latex.trim();+ return host;+};++const collectTextNodes = (root: Node) => {+ const nodes: Text[] = [];+ const visit = (node: Node) => {+ node.childNodes.forEach((child) => {+ if (child.nodeType === Node.TEXT_NODE) nodes.push(child as Text);+ else visit(child);+ });+ };+ visit(root);+ return nodes;+};++type MathPiece = string | { kind: "inline" | "block"; latex: string };++const splitMathText = (source: string): MathPiece[] => {+ const parts: MathPiece[] = [];+ let cursor = 0;+ let plainStart = 0;+ const pushPlain = (end: number) => {+ if (end > plainStart) parts.push(source.slice(plainStart, end));+ };+ while (cursor < source.length) {+ if (source[cursor] !== "$" || isEscaped(source, cursor)) {+ cursor += 1;+ continue;+ }+ if (source.startsWith("$$", cursor)) {+ const close = findClosingDelimiter(source, "$$", cursor + 2);+ const latex = close >= 0 ? source.slice(cursor + 2, close).trim() : "";+ if (!latex) {+ cursor += 2;+ continue;+ }+ pushPlain(cursor);+ parts.push({ kind: "block", latex });+ cursor = close + 2;+ plainStart = cursor;+ continue;+ }+ const close = findClosingDelimiter(source, "$", cursor + 1);+ if (close < 0 || source[close + 1] === "$") {+ cursor += 1;+ continue;+ }+ const latex = source.slice(cursor + 1, close).trim();+ if (!latex || latex.includes("\n") || isPureCurrency(latex)) {+ if (latex && isPureCurrency(latex)) {+ cursor = close + 1;+ continue;+ }+ cursor += 1;+ continue;+ }+ pushPlain(cursor);+ parts.push({ kind: "inline", latex });+ cursor = close + 1;+ plainStart = cursor;+ }+ pushPlain(source.length);+ return parts;+};++const replaceMathNodes = (root: HTMLElement, metrics: WeChatMetrics) => {+ root.querySelectorAll<HTMLElement>('[data-type="inline-math"], [data-type="block-math"]').forEach((node) => {+ const latex = node.getAttribute("data-latex") ?? "";+ if (!latex.trim()) return;+ const kind = node.getAttribute("data-type") === "block-math" ? "block" : "inline";+ node.replaceWith(mountMath(latex, kind, metrics));+ });++ for (const node of collectTextNodes(root)) {+ const parent = node.parentElement;+ if (!parent || parent.closest("pre, code, [data-ee-math], .katex")) continue;+ if (!node.data.includes("$")) continue;+ const parts = splitMathText(node.data);+ if (parts.length === 1 && typeof parts[0] === "string") continue;+ const fragment = document.createDocumentFragment();+ for (const part of parts) {+ if (typeof part === "string") fragment.append(document.createTextNode(part));+ else fragment.append(mountMath(part.latex, part.kind, metrics));+ }+ node.replaceWith(fragment);+ }+};++const convertTaskLists = (root: HTMLElement, accent: string | null) => {+ const markerColor = accent || "#1a1d21";+ const items = new Set<HTMLElement>();+ root.querySelectorAll<HTMLElement>('li[data-checked], li[data-type="taskItem"]').forEach((item) => items.add(item));+ root.querySelectorAll<HTMLInputElement>('input[type="checkbox"]').forEach((input) => {+ const item = input.closest("li");+ if (item) items.add(item);+ });++ items.forEach((item) => {+ const input = item.querySelector<HTMLInputElement>('input[type="checkbox"]');+ const flag = item.getAttribute("data-checked");+ const checked = flag === "true" || (flag !== "false" && Boolean(input?.hasAttribute("checked") || input?.checked));+ item.querySelectorAll('input[type="checkbox"]').forEach((box) => box.remove());+ item.querySelectorAll("label").forEach((label) => {+ if (!label.textContent?.trim()) label.remove();+ });+ const marker = document.createElement("span");+ marker.setAttribute("data-ee-task", checked ? "checked" : "open");+ marker.textContent = checked ? "☑ " : "☐ ";+ marker.style.cssText = `color: ${markerColor}; text-decoration: none; font-weight: 400;`;+ const paragraph = item.querySelector("p");+ const target = paragraph ?? item;+ target.insertBefore(marker, target.firstChild);+ if (checked) {+ target.style.color = CHECKED_TASK_COLOR;+ target.style.textDecoration = "line-through";+ }+ item.style.listStyle = "none";+ const list = item.parentElement;+ if (list && (list.tagName === "UL" || list.tagName === "OL")) {+ const kept = list.style.cssText+ .split(";")+ .map((part) => part.trim())+ .filter((part) => part && !/^(list-style|padding-left)\b/i.test(part));+ list.style.cssText = `${kept.join("; ")}; list-style: none; padding-left: 0;`;+ }+ });+};++const classNamesOf = (properties?: { className?: string | string[] }) => {+ const value = properties?.className;+ if (!value) return [];+ return Array.isArray(value) ? value : [value];+};++const tokenStyle = (classNames: string[]) => {+ if (classNames.includes("hljs-variable") && classNames.includes("language_")) return "color: #d73a49;";+ let color = "";+ for (const name of classNames) {+ const next = HLJS_COLORS[name];+ if (next) color = next;+ }+ if (!color) return "";+ let style = `color: ${color};`;+ if (classNames.includes("hljs-section") || classNames.includes("hljs-strong")) style += " font-weight: 700;";+ if (classNames.includes("hljs-emphasis")) style += " font-style: italic;";+ if (classNames.includes("hljs-addition")) style += " background-color: #f0fff4;";+ if (classNames.includes("hljs-deletion")) style += " background-color: #ffeef0;";+ return style;+};++const appendHast = (parent: Node, node: HastNode) => {+ if (node.type === "text") {+ parent.appendChild(document.createTextNode(node.value ?? ""));+ return;+ }+ if (node.type === "root") {+ node.children?.forEach((child) => appendHast(parent, child));+ return;+ }+ if (node.type !== "element") return;+ const element = document.createElement(node.tagName || "span");+ const style = tokenStyle(classNamesOf(node.properties));+ if (style) element.setAttribute("style", style);+ node.children?.forEach((child) => appendHast(element, child));+ parent.appendChild(element);+};++const languageOf = (code: HTMLElement) => {+ const named = code.className.split(/\s+/u).find((item) => item.startsWith("language-"));+ if (!named) return null;+ const raw = named.slice("language-".length).toLowerCase();+ if (!raw || raw === "mermaid" || raw === "plaintext" || raw === "text" || raw === "none") return null;+ if (raw === "sh" || raw === "zsh") return "bash";+ if (raw === "yml") return "yaml";+ return raw;+};++const highlightCodeForWeChat = (root: HTMLElement) => {+ root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {+ const language = languageOf(code);+ if (!language || !publishLowlight.registered(language)) return;+ const source = code.textContent ?? "";+ if (!source.trim()) return;+ try {+ const tree = publishLowlight.highlight(language, source) as HastNode;+ code.replaceChildren();+ appendHast(code, tree);+ code.style.color = "#24292e";+ } catch {+ // Leave the source readable when the grammar rejects it.+ }+ });+};++const neutralizeWeChatTopics = (root: HTMLElement) => {+ for (const node of collectTextNodes(root)) {+ const parent = node.parentElement;+ if (!parent || parent.closest("[data-ee-math], .katex")) continue;+ if (!node.data.includes("#")) continue;+ node.data = node.data.replace(/#(?=[\p{L}\p{N}_])/gu, "#\u200b");+ }+};++const WECHAT_CONTENT_WIDTH = 677;++const rasterizeMathForWeChat = async (root: HTMLElement) => {+ const hosts = Array.from(root.querySelectorAll<HTMLElement>("[data-ee-math]"));+ if (hosts.length === 0) return;+ await document.fonts?.ready;+ for (const host of hosts) {+ const kind = host.getAttribute("data-ee-math") === "block" ? "block" : "inline";+ const latex = host.getAttribute("data-latex") || host.textContent || "";+ if (!host.querySelector(".katex")) continue;+ const mount = host.cloneNode(true) as HTMLElement;+ mount.style.position = "fixed";+ mount.style.left = "-10000px";+ mount.style.top = "0";+ mount.style.zIndex = "-1";+ mount.style.margin = "0";+ mount.style.background = "transparent";+ mount.style.display = "inline-block";+ mount.style.width = "max-content";+ mount.style.maxWidth = kind === "block" ? `${WECHAT_CONTENT_WIDTH}px` : "none";+ document.body.appendChild(mount);+ try {+ const canvas = await toCanvas(mount, {+ backgroundColor: "transparent",+ cacheBust: false,+ pixelRatio: 2,+ });+ if (canvas.width < 2 || canvas.height < 2) continue;+ const cssWidth = Math.max(1, Math.round(canvas.width / 2));+ const cssHeight = Math.max(1, Math.round(canvas.height / 2));+ const image = document.createElement("img");+ image.alt = latex.trim();+ image.src = canvas.toDataURL("image/png");+ if (kind === "block") {+ const width = Math.min(cssWidth, WECHAT_CONTENT_WIDTH);+ const height = Math.max(1, Math.round(cssHeight * (width / cssWidth)));+ image.width = width;+ image.height = height;+ image.style.cssText = `display: block; max-width: 100%; width: ${width}px; height: auto; margin: 16px auto; border: 0; border-radius: 0;`;+ } else {+ image.width = cssWidth;+ image.height = cssHeight;+ image.style.cssText = `display: inline-block; width: ${cssWidth}px; height: ${cssHeight}px; margin: 0; border: 0; border-radius: 0; vertical-align: -0.15em;`;+ }+ host.replaceWith(image);+ } catch {+ // Keep the KaTeX HTML so a failed snapshot never drops the formula.+ } finally {+ mount.remove();+ }+ }+};+const readCssNumber = (value: string | undefined, fallback: number) => {const parsed = Number.parseFloat(value ?? "");return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;@@ -525,21 +1038,35 @@ export const preparePublishArticle = () => {const root = document.createElement("div");root.innerHTML = html;+ flattenDetailsForLinearHtml(root);const context = readEditorCopyContext(from);+ const metrics = { fontSize: context.fontSize, lineHeight: context.lineHeight };applyInlineStyles(root,- { fontSize: context.fontSize, lineHeight: context.lineHeight },+ metrics,context.colors,context.customCss,context.accentOnly,);- flattenDetailsForLinearHtml(root);+ replaceMathNodes(root, metrics);+ convertTaskLists(root, context.colors?.accent ?? null);+ highlightCodeForWeChat(root);+ neutralizeWeChatTopics(root);convertImageGalleriesForWeChat(root);return root;};+export const prepareMarkdownPublishArticle = (markdown: string, from?: HTMLElement | null) => {+ const html = marked.parse(embedMarkdownMath(markdown), { async: false, gfm: true, breaks: false });+ if (typeof html !== "string") {+ throw new Error("Markdown parser returned a promise");+ }+ return preparePublishArticle(html, from);+};+export const buildWeChatClipboardHtml = async (editor: Editor) => {const container = preparePublishArticle(editor.getHTML(), editor.view.dom);+ await rasterizeMathForWeChat(container);await embedMermaidForWeChat(container, editor);const originalImages = Array.from(editor.view.dom.querySelectorAll<HTMLImageElement>("img")).filter(isContentImage);await embedImagesForWeChat(container, originalImages);@@ -551,9 +1078,8 @@ export const copyEditorToWeChat = async (editor: Editor) =>copyHtmlToClipboard(await buildWeChatClipboardHtml(editor), editor.getText({ blockSeparator: "\n" }));export const copyMarkdownToWeChat = async (markdown: string) => {- const container = preparePublishArticle(- marked.parse(markdown, { async: false, gfm: true, breaks: false }),- );+ const container = prepareMarkdownPublishArticle(markdown);+ await rasterizeMathForWeChat(container);await embedMermaidForWeChat(container);await embedImagesForWeChat(container);await rasterizePublishOrnamentsForWeChat(container);