Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(views): keep HTML <img> images in the preview sequence (MUL-8971) (#10308)

Jiayuan Zhang07f4e0bcb171
diff --git a/packages/core/attachments/image-sequence.test.ts b/packages/core/attachments/image-sequence.test.ts
index 75af261531..5452a05b01 100644
--- a/packages/core/attachments/image-sequence.test.ts
+++ b/packages/core/attachments/image-sequence.test.ts
@@ -224,6 +224,23 @@ describe("collectImageSequence", () => {
]);
});
+ it.each([
+ ["named reference", '<img src="/a.png?a=1&amp;b=2" alt="A &amp; B">', "/a.png?a=1&b=2", "A & B"],
+ ["numeric reference", "<img alt='A' src='/a&#46;png'>", "/a.png", "A"],
+ ["unquoted value", "<IMG SRC=/a&amp;b.png ALT=A/>", "/a&b.png", "A/"],
+ ["legacy reference before =", '<img src="/a.png?x=1&copy=2" alt="A">', "/a.png?x=1&copy=2", "A"],
+ ["src-like text in another attribute", '<img alt="no src=/b.png" src="/a.png">', "/a.png", "no src=/b.png"],
+ ["repeated attribute", '<img src="/a.png" src="/b.png" alt="A">', "/a.png", "A"],
+ ])("reads <img> attributes as the HTML parser does: %s", (_name, html, url, filename) => {
+ expect(collectImageSequence([{ content: html }]).map(({ key, filename }) => ({ key, filename })))
+ .toEqual([{ key: url, filename }]);
+ });
+
+ it("skips <img> tags with no src or no closing bracket", () => {
+ const content = '<img alt="none">\n\n<img src="/open.png';
+ expect(collectImageSequence([{ content }])).toEqual([]);
+ });
+
it.each([
["full reference", "![A][shot]", "[shot]: /a.png", "/a.png"],
["collapsed reference", "![shot][]", "[shot]: /a.png", "/a.png"],
diff --git a/packages/core/attachments/image-sequence.ts b/packages/core/attachments/image-sequence.ts
index 7dfc34b97a..d803609a9f 100644
--- a/packages/core/attachments/image-sequence.ts
+++ b/packages/core/attachments/image-sequence.ts
@@ -18,6 +18,7 @@
* apps/mobile/CLAUDE.md: pure functions from @multica/core are importable).
*/
+import { decodeHTMLAttribute } from "entities/decode";
import { fromMarkdown } from "mdast-util-from-markdown";
import { normalizeUri } from "micromark-util-sanitize-uri";
import type { Attachment } from "../types/attachment";
@@ -199,10 +200,55 @@ const INLINE_REF_CACHE_LIMIT = 500;
// Timeline updates can then resolve current metadata without reparsing old bodies.
const inlineRefCache = new Map<string, ReadonlyArray<InlineRef>>();
-// Raw `<img src=...>` — reachable because the readonly renderer runs
-// rehypeRaw + rehypeSanitize, and the sanitize schema keeps img.
-const HTML_IMAGE_RE =
- /<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s">']+))[^>]*>/gi;
+// Raw `<img>` — reachable because the readonly renderer runs rehypeRaw +
+// rehypeSanitize, and the sanitize schema keeps img. The renderer receives
+// `src` and `alt` after parse5 has tokenized the tag and decoded its character
+// references, so the attributes are read the same way.
+const HTML_IMAGE_START_RE = /<img(?=[\t\n\f\r />])/gi;
+const HTML_SPACE_RE = /[\t\n\f\r ]/;
+
+/**
+ * Attributes of the start tag whose name ends at `from`, keyed by lowercase
+ * name with the first occurrence winning, or null when the tag never closes.
+ */
+function readTagAttributes(html: string, from: number): Map<string, string> | null {
+ const attributes = new Map<string, string>();
+ const skipSpace = (i: number) => {
+ while (i < html.length && HTML_SPACE_RE.test(html[i]!)) i++;
+ return i;
+ };
+ let i = from;
+ while (i < html.length) {
+ const c = html[i]!;
+ if (c === ">") return attributes;
+ if (c === "/" || HTML_SPACE_RE.test(c)) {
+ i++;
+ continue;
+ }
+ const nameStart = i;
+ i++;
+ while (i < html.length && !/[\t\n\f\r />=]/.test(html[i]!)) i++;
+ const name = html.slice(nameStart, i).toLowerCase();
+ i = skipSpace(i);
+ let value = "";
+ if (html[i] === "=") {
+ i = skipSpace(i + 1);
+ const quote = html[i];
+ if (quote === '"' || quote === "'") {
+ const end = html.indexOf(quote, i + 1);
+ if (end < 0) return null;
+ value = html.slice(i + 1, end);
+ i = end + 1;
+ } else {
+ const valueStart = i;
+ while (i < html.length && html[i] !== ">" && !HTML_SPACE_RE.test(html[i]!)) i++;
+ value = html.slice(valueStart, i);
+ }
+ }
+ if (!attributes.has(name)) attributes.set(name, decodeHTMLAttribute(value));
+ }
+ return null;
+}
// `!file[name](url)` on its own line — `preprocessFileCards` turns it into a
// fileCard div, which the renderer hands to <Attachment>: an image filename
@@ -270,10 +316,16 @@ function extractInlineRefs(rawContent: string): ReadonlyArray<InlineRef> {
});
}
} else if (node.type === "html") {
- for (const m of node.value.matchAll(HTML_IMAGE_RE)) {
- const url = (m[1] ?? m[2] ?? m[3] ?? "").trim();
+ for (const m of node.value.matchAll(HTML_IMAGE_START_RE)) {
+ const attributes = readTagAttributes(node.value, m.index + m[0].length);
+ const url = attributes?.get("src");
if (url) {
- refs.push({ index: index + m.index, url, filename: "", isFileCard: false });
+ refs.push({
+ index: index + m.index,
+ url,
+ filename: attributes?.get("alt") ?? "",
+ isFileCard: false,
+ });
}
}
} else if (node.type === "code" || node.type === "inlineCode") {
@@ -320,7 +372,7 @@ export interface ImageSequenceItem {
/**
* Identity used to open the sequence at the clicked attachment. The
* attachment id when the reference resolves to a record, otherwise the URL
- * passed to the image/card renderer after Markdown decoding/normalization.
+ * passed to the image/card renderer after Markdown or HTML decoding.
*/
key: string;
/** Best-known URL. Callers holding `attachment` should prefer re-resolving. */
diff --git a/packages/core/package.json b/packages/core/package.json
index bc87a74961..f48a99179b 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -202,6 +202,7 @@
"dependencies": {
"@formatjs/intl-localematcher": "catalog:",
"@tanstack/react-query": "catalog:",
+ "entities": "catalog:",
"i18next": "catalog:",
"mdast-util-from-markdown": "catalog:",
"micromark-util-sanitize-uri": "catalog:",
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index d48f5fff13..f47f71ea42 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -328,8 +328,8 @@ export function Attachment({
const shareUrl = isObjectURL(mediaUrl) ? state.url : mediaUrl;
// Identity this attachment has in the surrounding surface's sequence: the
- // attachment id once the URL resolves to a record, otherwise the URL exactly
- // as written in the body — the same pair `collectAttachmentSequence` keys on.
+ // attachment id once the URL resolves to a record, otherwise the URL as the
+ // renderer received it — the same pair `collectAttachmentSequence` keys on.
const sequenceKey =
state.attachmentId ?? (attachment.kind === "url" ? attachment.url : "");
diff --git a/packages/views/rich-content/image-preview-sequence.test.tsx b/packages/views/rich-content/image-preview-sequence.test.tsx
index 7caf91b5a3..a062f169d4 100644
--- a/packages/views/rich-content/image-preview-sequence.test.tsx
+++ b/packages/views/rich-content/image-preview-sequence.test.tsx
@@ -96,6 +96,8 @@ describe("RichContent image preview sequence", () => {
["angle destination", "![Reference](</chart v2.png>)", "", [], "/chart%20v2.png", "Reference"],
["escaped destination", String.raw`![Reference](/chart\(v2\).png)`, "", [], "/chart(v2).png", "Reference"],
["parenthesized URL", "![Reference](/chart(v2).png)", "", [], "/chart(v2).png", "Reference"],
+ ["HTML image", '<img src="https://cdn.example/a.png" alt="Reference">', "", [], "https://cdn.example/a.png", "Reference"],
+ ["HTML image with a character reference", '<img src="https://cdn.example/a.png?a=1&amp;b=2" alt="Reference">', "", [], "https://cdn.example/a.png?a=1&b=2", "Reference"],
] as const)("opens the %s in the shared viewer and pages through rendered images", (_name, image, definition, attachments, expectedSrc, imageAlt) => {
const content = [
"![First](/first.png)",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1880f989b9..45cfae75d2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -69,6 +69,9 @@ catalogs:
cmdk:
specifier: ^1.1.1
version: 1.1.1
+ entities:
+ specifier: ^6.0.1
+ version: 6.0.1
eslint-plugin-i18next:
specifier: ^6.1.4
version: 6.1.4
@@ -735,6 +738,9 @@ importers:
'@tanstack/react-query':
specifier: 'catalog:'
version: 5.96.2([email protected])
+ entities:
+ specifier: 'catalog:'
+ version: 6.0.1
i18next:
specifier: 'catalog:'
version: 26.0.8(@typescript/[email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 88fea290a2..5b58119985 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -26,6 +26,7 @@ catalog:
class-variance-authority: ^0.7.1
clsx: ^2.1.1
cmdk: ^1.1.1
+ entities: ^6.0.1
eslint-plugin-i18next: ^6.1.4
fumadocs-core: ^16.17.8
fumadocs-mdx: ^15.4.10