Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(mobile): render HTML <img> images in Markdown (MUL-8965) (#10302)
Jiayuan Zhangfa089093fd91
diff --git a/apps/mobile/lib/markdown/image-sequence.test.ts b/apps/mobile/lib/markdown/image-sequence.test.tsindex 224ac4092e..84a3498c7b 100644--- a/apps/mobile/lib/markdown/image-sequence.test.ts+++ b/apps/mobile/lib/markdown/image-sequence.test.ts@@ -78,6 +78,10 @@ describe("mobile Markdown image sequence wiring", () => {["nested entity", "", "https://cdn.example/a.png?a=1&b=2", []],["reference", "![middle][shot]\n\n[shot]: https://cdn.example/图.png", "https://cdn.example/%E5%9B%BE.png", []],["attachment", ``, attachment.download_url!, [attachment]],+ ["HTML", '<img src="https://cdn.example/a.png" width="400" />', "https://cdn.example/a.png", []],+ ["HTML named entity", '<img src="https://cdn.example/a.png?a=1&b=2">', "https://cdn.example/a.png?a=1&b=2", []],+ ["HTML Unicode", '<img src="https://cdn.example/图.png">', "https://cdn.example/%E5%9B%BE.png", []],+ ["HTML block", '<p align="center">\n<img src="https://cdn.example/图.png">\n</p>', "https://cdn.example/%E5%9B%BE.png", []],] as const)("keeps the %s image inside the screen sequence", (_name, middle, expectedUri, attachments) => {const content = `\n\n${middle}\n\n`;const segments = splitMarkdown(preprocessMobileMarkdown(content)).filter((segment) => segment.type === "image");@@ -99,4 +103,13 @@ describe("mobile Markdown image sequence wiring", () => {});expect(renderedUri).toBe(expectedUri);});++ it("does not count an HTML image shown literally in code", () => {+ const content = '\n\n`<img src="https://cdn.example/a.png">`\n\n';+ const provider = ImageSequenceProvider({ blocks: [{ content }], children: null });+ expect(provider.props.value).toEqual([+ "https://cdn.example/first.png",+ "https://cdn.example/last.png",+ ]);+ });});diff --git a/apps/mobile/lib/markdown/image-sequence.tsx b/apps/mobile/lib/markdown/image-sequence.tsxindex fcd063204c..3a6434cd31 100644--- a/apps/mobile/lib/markdown/image-sequence.tsx+++ b/apps/mobile/lib/markdown/image-sequence.tsx@@ -16,7 +16,9 @@** The URIs are resolved the same way `MarkdownImage` resolves the one it* renders — same attachment match, same `resolveAttachmentUrl` pass — so the- * URI a tap reports is the one the sequence holds.+ * URI a tap reports is the one the sequence holds. Bodies go through the+ * renderer's HTML pass first: mobile shows `<img>` as a Markdown image, whose+ * URL is entity-decoded and normalized, and drops the tags around it.*/import { createContext, use, useMemo, type ReactNode } from "react";import {@@ -24,6 +26,7 @@ import {type ImageSequenceBlock,} from "@multica/core/attachments/image-sequence";import { resolveAttachmentUrl } from "@/lib/attachment-url";+import { stripHtml } from "./preprocess";const ImageSequenceContext = createContext<readonly string[]>([]);@@ -44,7 +47,11 @@ export function ImageSequenceProvider({}) {const uris = useMemo(() =>- collectImageSequence(blocks).map(+ collectImageSequence(+ blocks.map((block) =>+ block?.content ? { ...block, content: stripHtml(block.content) } : block,+ ),+ ).map((item) => resolveAttachmentUrl(item.url) ?? item.url,),[blocks],diff --git a/apps/mobile/lib/markdown/preprocess.test.ts b/apps/mobile/lib/markdown/preprocess.test.tsindex 80a4e54fe9..d51746f19a 100644--- a/apps/mobile/lib/markdown/preprocess.test.ts+++ b/apps/mobile/lib/markdown/preprocess.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import { preprocessMobileMarkdown } from "./preprocess";+import { splitMarkdown } from "./split-markdown";const UUID = "019f49e2-5b07-7970-beef-c0d537fb8c1d";const ABS_URL = `https://multica-app.copilothub.ai/api/attachments/${UUID}/download`;@@ -76,3 +77,51 @@ describe("preprocessMobileMarkdown — angle-bracket image destinations", () =>.toBe("A \nB");});});++describe("preprocessMobileMarkdown — HTML images", () => {+ it("renders an HTML <img> as an image segment", () => {+ const out = preprocessMobileMarkdown(+ 'Text\n\n<img src="https://host/a.png" width="400" />\n\nEnd',+ );+ expect(out).toBe("Text\n\n\n\nEnd");+ expect(splitMarkdown(out)).toEqual([+ { type: "prose", content: "Text" },+ { type: "image", uri: "https://host/a.png", alt: "" },+ { type: "prose", content: "End" },+ ]);+ });++ it.each([+ ['<img alt="a [b]" src=\'https://host/a.png\'>', "![a \\[b\\]](https://host/a.png)"],+ ["<IMG SRC=https://host/a.png ALT=chart>", ""],+ ['<img\n src="https://host/a.png"\n alt="multi\nline"\n/>', ""],+ ['<img src="https://host/a(1).png">', ".png>)"],+ ['<p align="center"><a href="https://host/a.png"><img src="https://host/a.png"></a></p>', ""],+ ])("rewrites %j", (input, expected) => {+ expect(preprocessMobileMarkdown(input)).toBe(expected);+ });++ it.each([+ '<img src="javascript:alert(1)">',+ '<img src="data:image/png;base64,AAAA">',+ '<img src="/uploads/a.png">',+ '<img alt="no source">',+ ])("drops %j without an http(s) source", (input) => {+ expect(preprocessMobileMarkdown(input)).toBe("");+ });++ it.each([+ 'Use `<img src="https://host/a.png">` here',+ '```html\n<img src="https://host/a.png" width="400" />\n<br>\n```',+ '- item\n\n ~~~\n <img src="https://host/a.png">\n ~~~',+ ' <img src="https://host/a.png">',+ ])("keeps HTML inside code literal: %j", (input) => {+ expect(preprocessMobileMarkdown(input)).toBe(input);+ });++ it("rewrites images around code without touching the code", () => {+ const input = '<img src="https://host/a.png">\n\n`<img src="https://host/b.png">` <b>x</b>';+ expect(preprocessMobileMarkdown(input))+ .toBe('\n\n`<img src="https://host/b.png">` x');+ });+});diff --git a/apps/mobile/lib/markdown/preprocess.ts b/apps/mobile/lib/markdown/preprocess.tsindex 8c9455ef5e..384b0fb300 100644--- a/apps/mobile/lib/markdown/preprocess.ts+++ b/apps/mobile/lib/markdown/preprocess.ts@@ -22,6 +22,7 @@* hyperlinks — same tap behavior, just no 📎 prefix. Acceptable degradation.*/import { preprocessMentionShortcodes } from "@multica/core/markdown";+import { fromMarkdown } from "mdast-util-from-markdown";// File-card line matcher, kept in sync with web's parser in// `packages/ui/markdown/file-cards.ts` (NEW_FILE_CARD_RE + FILE_CARD_URL_PATTERN):@@ -94,6 +95,68 @@ function preprocessTaskListStrikethrough(input: string): string {});}+// CommonMark raw-HTML attribute, kept in sync with web's `findHtmlTagRanges`+// in `packages/ui/markdown/linkify.ts`. Unquoted values exclude whitespace, so+// attribute boundaries are unambiguous and matching stays linear.+const HTML_ATTRIBUTE = String.raw`\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\x60]+|'[^']*'|"[^"]*"))?`;+const HTML_ATTRIBUTE_RE =+ /\s+([A-Za-z_:][\w.:-]*)(?:\s*=\s*(?:([^\s"'=<>\x60]+)|'([^']*)'|"([^"]*)"))?/g;+const HTML_RE = new RegExp(+ [+ String.raw`<!--[\s\S]*?-->`,+ String.raw`<br\s*\/?>`,+ String.raw`<img(?:${HTML_ATTRIBUTE})*\s*\/?>`,+ // Angle-bracket URL destinations are not HTML tags. Closing tags have+ // no attributes, so </chart v2.png> must also survive for the lexer.+ String.raw`<(?:\/[a-z][a-z\d:-]*\s*|[a-z][a-z\d:-]*(?:\s[^>]*|\/?))>`,+ ].join("|"),+ "gi",+);++function htmlImageToMarkdown(tag: string): string {+ const attrs = new Map<string, string>();+ for (const m of tag.matchAll(HTML_ATTRIBUTE_RE)) {+ const name = m[1]!.toLowerCase();+ if (!attrs.has(name)) attrs.set(name, m[2] ?? m[3] ?? m[4] ?? "");+ }+ const src = attrs.get("src")?.trim() ?? "";+ if (!/^https?:\/\/[^\s<>]+$/i.test(src)) return "";+ const alt = (attrs.get("alt") ?? "").replace(/\s+/g, " ").trim();+ // A bare destination breaks on unbalanced parens; the angle form doesn't.+ const destination = /[()]/.test(src) ? `<${src}>` : src;+ return ``;+}++function stripHtmlOutsideCode(input: string): string {+ return input.replace(HTML_RE, (tag) => {+ if (tag.startsWith("<!--")) return "";+ if (/^<br[\s/>]/i.test(tag)) return " \n";+ if (/^<img[\s/>]/i.test(tag)) return htmlImageToMarkdown(tag);+ return "";+ });+}++// Code ranges come from the same CommonMark parser split-markdown uses, so a+// backtick inside raw HTML or an HTML block is not mistaken for a code span.+function findCodeRanges(input: string): [number, number][] {+ if (!/`|~{3}| {4}|\t/.test(input)) return [];+ const tree = fromMarkdown(input);+ type Node = typeof tree | (typeof tree.children)[number];+ const pending: Node[] = [tree];+ const ranges: [number, number][] = [];+ while (pending.length) {+ const node = pending.pop()!;+ if (node.type === "code" || node.type === "inlineCode") {+ const start = node.position?.start.offset;+ const end = node.position?.end.offset;+ if (start !== undefined && end !== undefined) ranges.push([start, end]);+ } else if ("children" in node) {+ for (const child of node.children) pending.push(child);+ }+ }+ return ranges.sort((a, b) => a[0] - b[0]);+}+/*** Strip embedded HTML before marked sees it. Mobile cannot do what web does* (rehype-raw + sanitize → render real <br> / <sub> / <details>) — RN has@@ -104,21 +167,28 @@ function preprocessTaskListStrikethrough(input: string): string {* the canonical CommonMark hard-break syntax). md4c respects it as a* hard line break inside a paragraph; bare `\n` would be treated as a* space (CommonMark default), losing intentional `<br>` semantics.+ * - `<img src="http(s)://…" alt="…">` → ``, so agent- and+ * GitHub-authored images render like Markdown images. Any other `src`+ * (missing, relative, `data:`, `javascript:`) is dropped.* - HTML comments `<!-- ... -->` → removed entirely.* - Every other tag → strip the tag, keep the inner text. So* `<sub>2</sub>` becomes `2`. Loses formatting but keeps content; far* better than showing raw HTML.*- * Does not parse — pure regex. Cannot handle nested tags with attributes- * containing `>`, but those don't appear in our editor output.+ * Code spans and code blocks are left literal. Does not parse HTML — pure+ * regex. Cannot handle nested tags with attributes containing `>`, but those+ * don't appear in our editor output.*/-function stripHtml(input: string): string {- return input- .replace(/<!--[\s\S]*?-->/g, "")- .replace(/<br\s*\/?>/gi, " \n")- // Angle-bracket URL destinations are not HTML tags. Closing tags have- // no attributes, so </chart v2.png> must also survive for the lexer.- .replace(/<(?:\/[a-z][a-z\d:-]*\s*|[a-z][a-z\d:-]*(?:\s[^>]*|\/?))>/gi, "");+export function stripHtml(input: string): string {+ if (!input.includes("<")) return input;+ let out = "";+ let cursor = 0;+ for (const [start, end] of findCodeRanges(input)) {+ if (start < cursor) continue;+ out += stripHtmlOutsideCode(input.slice(cursor, start)) + input.slice(start, end);+ cursor = end;+ }+ return out + stripHtmlOutsideCode(input.slice(cursor));}export function preprocessMobileMarkdown(input: string): string {