Skip to content

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

Go

fix(mobile): render image file cards inline in the lightbox sequence (MUL-8972) (#10309)

Jiayuan Zhang305c895bc553
diff --git a/apps/mobile/docs/markdown-rendering-adr.md b/apps/mobile/docs/markdown-rendering-adr.md
index 26e474c62c..d7a556fb39 100644
--- a/apps/mobile/docs/markdown-rendering-adr.md
+++ b/apps/mobile/docs/markdown-rendering-adr.md
@@ -52,7 +52,8 @@ token's specific platform trap.
content (string)
↓ preprocessMobileMarkdown
legacy mention shortcode → [@name](mention://type/id)
- legacy file-card lines → [📎 name](url)
+ image file-card lines → ![name](url)
+ other file-card lines → [📎 name](url)
HTML <br> → CommonMark " \n" hard break
↓ splitMarkdown (marked@18 lexer; we use the AST only)
code fence → { type:'code', lang, code }
diff --git a/apps/mobile/lib/markdown/image-sequence.test.ts b/apps/mobile/lib/markdown/image-sequence.test.ts
index 84a3498c7b..e2953010ce 100644
--- a/apps/mobile/lib/markdown/image-sequence.test.ts
+++ b/apps/mobile/lib/markdown/image-sequence.test.ts
@@ -104,6 +104,47 @@ describe("mobile Markdown image sequence wiring", () => {
expect(renderedUri).toBe(expectedUri);
});
+ it.each([
+ ["image name", "!file[photo.png](https://cdn.example/photo.png)", "https://cdn.example/photo.png", []],
+ ["image record", `!file[screenshot](/api/attachments/${ID}/download)`, attachment.download_url!, [attachment]],
+ ["Unicode URL", "!file[photo.png](https://cdn.example/图.png)", "https://cdn.example/%E5%9B%BE.png", []],
+ ["entity-like URL", "!file[photo.png](https://cdn.example/a.png?a=1&amp;b=2)", "https://cdn.example/a.png?a=1&amp;b=2", []],
+ ["backslash and brackets in URL", String.raw`!file[photo.png](https://cdn.example/a\b<c(d>.png)`, "https://cdn.example/a%5Cb%3Cc(d%3E.png", []],
+ ] as const)("renders an image file card (%s) inline at its sequence position", (_name, card, expectedUri, attachments) => {
+ const content = `![first](https://cdn.example/first.png)\n\n${card}\n\n![last](https://cdn.example/last.png)`;
+ const segments = splitMarkdown(preprocessMobileMarkdown(content, attachments));
+ expect(segments.map((segment) => segment.type)).toEqual(["image", "image", "image"]);
+ const lightbox = LightboxProvider({ children: null });
+ state.contexts.set(lightbox.type, lightbox.props.value);
+ const provider = ImageSequenceProvider({ blocks: [{ content, attachments }], children: null });
+ state.contexts.set(provider.type, provider.props.value);
+ const image = MarkdownImage({ uri: (segments[1] as { uri: string }).uri, attachments: [...attachments] });
+ image.props.onPress();
+ expect(state.setters[0]).toHaveBeenCalledExactlyOnceWith({
+ images: [
+ { uri: "https://cdn.example/first.png" },
+ { uri: expectedUri },
+ { uri: "https://cdn.example/last.png" },
+ ],
+ index: 1,
+ });
+ });
+
+ it.each([
+ ["non-image name", "!file[report.pdf](https://cdn.example/report.pdf)", []],
+ ["non-image record", `!file[photo.png](/api/attachments/${ID}/download)`, [{ ...attachment, filename: "report.pdf", content_type: "application/pdf" }]],
+ ] as const)("keeps a %s file card as a link outside the sequence", (_name, card, attachments) => {
+ const content = `![first](https://cdn.example/first.png)\n\n${card}\n\n![last](https://cdn.example/last.png)`;
+ const segments = splitMarkdown(preprocessMobileMarkdown(content, attachments));
+ expect(segments.map((segment) => segment.type)).toEqual(["image", "prose", "image"]);
+ expect((segments[1] as { content: string }).content).toMatch(/^\[📎 /);
+ const provider = ImageSequenceProvider({ blocks: [{ content, attachments }], children: null });
+ expect(provider.props.value).toEqual([
+ "https://cdn.example/first.png",
+ "https://cdn.example/last.png",
+ ]);
+ });
+
it("does not count an HTML image shown literally in code", () => {
const content = '![first](https://cdn.example/first.png)\n\n`<img src="https://cdn.example/a.png">`\n\n![last](https://cdn.example/last.png)';
const provider = ImageSequenceProvider({ blocks: [{ content }], children: null });
diff --git a/apps/mobile/lib/markdown/image-sequence.tsx b/apps/mobile/lib/markdown/image-sequence.tsx
index 3a6434cd31..d0e053e40a 100644
--- a/apps/mobile/lib/markdown/image-sequence.tsx
+++ b/apps/mobile/lib/markdown/image-sequence.tsx
@@ -18,9 +18,12 @@
* renders — same attachment match, same `resolveAttachmentUrl` pass — so the
* 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.
+ * URL is entity-decoded and normalized, and drops the tags around it. Image
+ * file cards are decided by the same rule on both sides (see
+ * `preprocessFileCards`), so a card shown as a link is never counted.
*/
import { createContext, use, useMemo, type ReactNode } from "react";
+import { normalizeUri } from "micromark-util-sanitize-uri";
import {
collectImageSequence,
type ImageSequenceBlock,
@@ -51,9 +54,14 @@ export function ImageSequenceProvider({
blocks.map((block) =>
block?.content ? { ...block, content: stripHtml(block.content) } : block,
),
- ).map(
- (item) => resolveAttachmentUrl(item.url) ?? item.url,
- ),
+ ).map((item) => {
+ // An unmatched image file card renders as a Markdown image, whose
+ // destination is normalized like any other.
+ const url = !item.imageByConstruction && !item.attachment
+ ? normalizeUri(item.url)
+ : item.url;
+ return resolveAttachmentUrl(url) ?? url;
+ }),
[blocks],
);
return (
diff --git a/apps/mobile/lib/markdown/markdown.tsx b/apps/mobile/lib/markdown/markdown.tsx
index 258febdf91..16db1b96e8 100644
--- a/apps/mobile/lib/markdown/markdown.tsx
+++ b/apps/mobile/lib/markdown/markdown.tsx
@@ -129,9 +129,9 @@ export function Markdown({
);
const segments = useMemo(() => {
- const processed = preprocessMobileMarkdown(content);
+ const processed = preprocessMobileMarkdown(content, attachments);
return splitMarkdown(processed);
- }, [content]);
+ }, [content, attachments]);
const onLinkPress = useCallback(
({ url }: { url: string }) => {
diff --git a/apps/mobile/lib/markdown/preprocess.ts b/apps/mobile/lib/markdown/preprocess.ts
index 384b0fb300..dc48925ac3 100644
--- a/apps/mobile/lib/markdown/preprocess.ts
+++ b/apps/mobile/lib/markdown/preprocess.ts
@@ -14,7 +14,9 @@
* turns it into HTML, which mobile can't render natively. Rewriting
* to a normal link with a 📎 emoji makes it a tappable link that
* `Linking.openURL` opens in the system viewer (Safari for PDFs,
- * QuickLook for docs, share sheet for arbitrary files).
+ * QuickLook for docs, share sheet for arbitrary files). An image card
+ * becomes `![name](url)` instead, as web renders it inline, so it is
+ * tappable and part of the screen's lightbox sequence.
*
* NOTE: Web's preprocess also has a third pass that detects bare CDN
* URLs as legacy file links. We skip that because mobile doesn't bootstrap
@@ -22,6 +24,11 @@
* hyperlinks — same tap behavior, just no 📎 prefix. Acceptable degradation.
*/
import { preprocessMentionShortcodes } from "@multica/core/markdown";
+import {
+ isImageAttachment,
+ matchAttachmentByURL,
+} from "@multica/core/attachments/image-sequence";
+import type { Attachment } from "@multica/core/types";
import { fromMarkdown } from "mdast-util-from-markdown";
// File-card line matcher, kept in sync with web's parser in
@@ -58,13 +65,36 @@ function escapeLinkLabel(name: string): string {
return name.replace(/([\\[\]])/g, "\\$1");
}
-function preprocessFileCards(input: string): string {
+// Same candidate `collectImageSequence` builds for an inline file card, so the
+// lightbox counts exactly the cards this renders as images. Core only reads
+// cards whose URL has no whitespace.
+function isImageFileCard(
+ name: string,
+ url: string,
+ attachments: readonly Attachment[] | undefined,
+): boolean {
+ if (/\s/.test(url)) return false;
+ const record = matchAttachmentByURL(url, attachments);
+ return isImageAttachment(record?.content_type ?? "", record?.filename || name || url);
+}
+
+// An angle-bracket destination with every metacharacter escaped decodes back
+// to the card's raw URL, which is what the sequence matches against.
+function imageDestination(url: string): string {
+ return `<${url.replace(/[\\<>&]/g, "\\$&")}>`;
+}
+
+function preprocessFileCards(input: string, attachments: readonly Attachment[] | undefined): string {
return input
.split("\n")
.map((line) => {
const m = line.trim().match(FILE_LINE_RE);
if (!m) return line;
- const label = escapeLinkLabel(unescapeFileLabel(m[1]!));
+ const name = unescapeFileLabel(m[1]!);
+ const label = escapeLinkLabel(name);
+ if (isImageFileCard(name, m[2]!, attachments)) {
+ return `![${label}](${imageDestination(m[2]!)})`;
+ }
return `[📎 ${label}](${m[2]})`;
})
.join("\n");
@@ -191,9 +221,12 @@ export function stripHtml(input: string): string {
return out + stripHtmlOutsideCode(input.slice(cursor));
}
-export function preprocessMobileMarkdown(input: string): string {
+export function preprocessMobileMarkdown(
+ input: string,
+ attachments?: readonly Attachment[],
+): string {
if (!input) return "";
return preprocessTaskListStrikethrough(
- preprocessFileCards(preprocessMentionShortcodes(stripHtml(input))),
+ preprocessFileCards(preprocessMentionShortcodes(stripHtml(input)), attachments),
);
}