Skip to content

Commit 7974c8f

Browse files
committed
fix(mobile): render mermaid fenced blocks as diagrams
Mobile chat showed mermaid fences as plain code text while web rendered diagrams. Split mermaid fences out of the native markdown flow and render each through a WebView diagram with show-code and copy controls. Unclosed fences stay as code so streaming is unchanged.
1 parent 80a2351 commit 7974c8f

4 files changed

Lines changed: 312 additions & 34 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { splitMarkdownWithMermaid } from "./mermaidBlocks";
4+
5+
describe("splitMarkdownWithMermaid", () => {
6+
it("returns plain markdown untouched", () => {
7+
expect(splitMarkdownWithMermaid("# Hi\n\nSome text")).toMatchObject([
8+
{ kind: "markdown", markdown: "# Hi\n\nSome text" },
9+
]);
10+
});
11+
12+
it("splits a single mermaid block", () => {
13+
const segments = splitMarkdownWithMermaid(
14+
["Before", "", "```mermaid", "flowchart TD", " A --> B", "```", "", "After"].join("\n"),
15+
);
16+
expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "mermaid", "markdown"]);
17+
expect(segments[1]).toMatchObject({ kind: "mermaid", source: "flowchart TD\n A --> B" });
18+
});
19+
20+
it("leaves unclosed fences as markdown for streaming", () => {
21+
const markdown = "Before\n\n```mermaid\nflowchart TD\n A --> B";
22+
expect(splitMarkdownWithMermaid(markdown)).toMatchObject([{ kind: "markdown", markdown }]);
23+
});
24+
25+
it("supports tilde fences and ignores non-mermaid fences", () => {
26+
const segments = splitMarkdownWithMermaid(
27+
["~~~mermaid", "flowchart TD", " A --> B", "~~~", "", "```ts", "const x = 1;", "```"].join(
28+
"\n",
29+
),
30+
);
31+
expect(segments.map((segment) => segment.kind)).toEqual(["mermaid", "markdown"]);
32+
});
33+
34+
it("matches mermaid case-insensitively and keeps source stable ids", () => {
35+
const first = splitMarkdownWithMermaid("```MERMAID\nA --> B\n```");
36+
const second = splitMarkdownWithMermaid("```mermaid\nA --> B\n```");
37+
expect(first[0]).toMatchObject({ kind: "mermaid" });
38+
expect(second[0]).toMatchObject({ kind: "mermaid" });
39+
if (first[0]?.kind === "mermaid" && second[0]?.kind === "mermaid") {
40+
expect(first[0].id).toBe(second[0].id);
41+
}
42+
});
43+
});
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/** Split ```mermaid fences out so mobile renders diagrams, not code text. */
2+
3+
export type MermaidMarkdownSegment =
4+
| { readonly kind: "markdown"; readonly markdown: string; readonly key: string }
5+
| {
6+
readonly kind: "mermaid";
7+
readonly source: string;
8+
readonly id: string;
9+
readonly key: string;
10+
};
11+
12+
const FENCE_RE = /^ {0,3}(```|~~~)[ \t]*([^\n]*)\n?/;
13+
14+
function fenceLanguage(info: string): string {
15+
return info.trim().split(/\s+/, 1)[0]?.toLowerCase() ?? "";
16+
}
17+
18+
function fenceHash(source: string): string {
19+
let hash = 5381;
20+
for (let index = 0; index < source.length; index += 1) {
21+
hash = ((hash << 5) + hash + source.charCodeAt(index)) | 0;
22+
}
23+
return `m${(hash >>> 0).toString(36)}`;
24+
}
25+
26+
export function splitMarkdownWithMermaid(markdown: string): MermaidMarkdownSegment[] {
27+
const segments: MermaidMarkdownSegment[] = [];
28+
const lines = markdown.split("\n");
29+
let markdownStart = 0;
30+
let index = 0;
31+
32+
const pushMarkdown = (end: number) => {
33+
if (end > markdownStart) {
34+
const markdown = lines.slice(markdownStart, end).join("\n");
35+
segments.push({
36+
kind: "markdown",
37+
markdown,
38+
key: `md-${markdownStart}-${fenceHash(markdown)}`,
39+
});
40+
}
41+
};
42+
43+
while (index < lines.length) {
44+
const line = lines[index] ?? "";
45+
const open = FENCE_RE.exec(line);
46+
if (!open || fenceLanguage(open[2] ?? "") !== "mermaid") {
47+
index += 1;
48+
continue;
49+
}
50+
const fence = open[1] ?? "```";
51+
const closeRe = new RegExp(`^ {0,3}${fence === "```" ? "```" : "~~~"}[ \\t]*$`);
52+
let close = -1;
53+
for (let scan = index + 1; scan < lines.length; scan += 1) {
54+
if (closeRe.test(lines[scan] ?? "")) {
55+
close = scan;
56+
break;
57+
}
58+
}
59+
// Unclosed fence: leave it as Markdown (streaming or authored that way).
60+
if (close === -1) {
61+
index += 1;
62+
continue;
63+
}
64+
pushMarkdown(index);
65+
const source = lines.slice(index + 1, close).join("\n");
66+
segments.push({
67+
kind: "mermaid",
68+
source,
69+
id: fenceHash(source),
70+
key: `mmd-${index}-${fenceHash(source)}`,
71+
});
72+
index = close + 1;
73+
markdownStart = index;
74+
}
75+
pushMarkdown(lines.length);
76+
return segments.filter((segment) => segment.kind === "mermaid" || segment.markdown.length > 0);
77+
}

‎apps/mobile/src/native/EnrichedMarkdownText.tsx‎

Lines changed: 70 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types
2323

2424
import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
2525
import { Menu } from "../components/ui/Menu";
26+
import { MobileMermaidDiagram } from "./MobileMermaidDiagram";
27+
import { splitMarkdownWithMermaid } from "../lib/mermaidBlocks";
2628
import { useEnrichedLinkVariants } from "./useEnrichedLinkVariants";
2729
import { useRetryingImageSource } from "./useRetryingImageSource";
2830
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
@@ -284,6 +286,61 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
284286
}
285287
: undefined;
286288
const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
289+
const segments = useMemo(() => splitMarkdownWithMermaid(markdown), [markdown]);
290+
const hasMermaid = segments.some((segment) => segment.kind === "mermaid");
291+
const dark = themeAppearance === "dark";
292+
const onSegmentLinksChange = (links: MarkdownLinkOccurrence[]) => {
293+
if (links.length === 0) return;
294+
const urls = [...new Set(links.map((link) => link.url))];
295+
setParsedLinkUrls((previous) => {
296+
const next = [...previous];
297+
for (const url of urls) {
298+
if (!next.includes(url)) next.push(url);
299+
}
300+
return next.length === previous.length ? previous : next;
301+
});
302+
};
303+
const renderMarkdownSegment = (
304+
segmentMarkdown: string,
305+
key: string,
306+
onLinkLongPress?: ({ url }: { url: string }) => void,
307+
) => (
308+
<EnrichedMarkdownText
309+
key={key}
310+
markdown={segmentMarkdown}
311+
markdownStyle={markdownStyle}
312+
onLinksChange={hasMermaid ? onSegmentLinksChange : onLinksChange}
313+
renderers={renderers}
314+
resolveImageSource={resolveNativeImageSource}
315+
onImagePress={
316+
props.onImagePress || props.onLinkPress
317+
? ({ url }) => (props.onImagePress ?? props.onLinkPress)?.(url)
318+
: undefined
319+
}
320+
linkRecognition={linkRecognition}
321+
containerStyle={{ flexShrink: 1, minWidth: 0 }}
322+
flavor="github"
323+
selectable
324+
selectionClipboard={selectionClipboard}
325+
selectionColor={props.textStyle.selectionColor}
326+
selectionHandleColor={props.textStyle.selectionHandleColor}
327+
md4cFlags={{
328+
latexMath: mathRenderingEnabled,
329+
hardSoftBreaks: props.preserveSoftBreaks ?? false,
330+
admonitions: true,
331+
preserveWindowsPaths: true,
332+
}}
333+
enableTaskListItemToggle={false}
334+
enableCodeBlockWrapToggle
335+
spoilerOverlay="solid"
336+
onLinkPress={
337+
props.onLinkPress || props.onImagePress ? ({ url }) => onLinkPress(url) : undefined
338+
}
339+
onLinkLongPress={onLinkLongPress}
340+
linkContextMenuItems={linkContextMenuItems}
341+
linkPillContent={linkPillContent}
342+
/>
343+
);
287344
const renderMarkdown = (openAndroidMenu?: () => void) => {
288345
const onLinkLongPress =
289346
Platform.OS === "android" && props.fileContextMenu
@@ -309,40 +366,19 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
309366
marginBottom: props.marginBottom,
310367
}}
311368
>
312-
<EnrichedMarkdownText
313-
markdown={markdown}
314-
markdownStyle={markdownStyle}
315-
onLinksChange={onLinksChange}
316-
renderers={renderers}
317-
resolveImageSource={resolveNativeImageSource}
318-
onImagePress={
319-
props.onImagePress || props.onLinkPress
320-
? ({ url }) => (props.onImagePress ?? props.onLinkPress)?.(url)
321-
: undefined
322-
}
323-
linkRecognition={linkRecognition}
324-
containerStyle={{ flexShrink: 1, minWidth: 0 }}
325-
flavor="github"
326-
selectable
327-
selectionClipboard={selectionClipboard}
328-
selectionColor={props.textStyle.selectionColor}
329-
selectionHandleColor={props.textStyle.selectionHandleColor}
330-
md4cFlags={{
331-
latexMath: mathRenderingEnabled,
332-
hardSoftBreaks: props.preserveSoftBreaks ?? false,
333-
admonitions: true,
334-
preserveWindowsPaths: true,
335-
}}
336-
enableTaskListItemToggle={false}
337-
enableCodeBlockWrapToggle
338-
spoilerOverlay="solid"
339-
onLinkPress={
340-
props.onLinkPress || props.onImagePress ? ({ url }) => onLinkPress(url) : undefined
341-
}
342-
onLinkLongPress={onLinkLongPress}
343-
linkContextMenuItems={linkContextMenuItems}
344-
linkPillContent={linkPillContent}
345-
/>
369+
{hasMermaid ? (
370+
<View style={{ flexShrink: 1, minWidth: 0, gap: 8 }}>
371+
{segments.map((segment) =>
372+
segment.kind === "mermaid" ? (
373+
<MobileMermaidDiagram key={segment.key} source={segment.source} dark={dark} />
374+
) : (
375+
renderMarkdownSegment(segment.markdown, segment.key, onLinkLongPress)
376+
),
377+
)}
378+
</View>
379+
) : (
380+
renderMarkdownSegment(markdown, "markdown", onLinkLongPress)
381+
)}
346382
</View>
347383
);
348384
};
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import { useMemo, useState } from "react";
2+
import { Pressable, View } from "react-native";
3+
import { WebView, type WebViewMessageEvent } from "react-native-webview";
4+
5+
import { AppText } from "../components/ui/AppText";
6+
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
7+
8+
function buildHtml(source: string, dark: boolean): string {
9+
// Source travels as JSON inside script, never as raw HTML.
10+
const payload = JSON.stringify({ source, dark });
11+
return `<!doctype html>
12+
<html>
13+
<head>
14+
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
15+
<style>
16+
html,body{margin:0;padding:8px;background:${dark ? "#1f1f1f" : "#ffffff"};}
17+
svg{max-width:100%;height:auto;}
18+
.error{font-family:monospace;font-size:12px;color:${dark ? "#ff9d9d" : "#b3261e"};white-space:pre-wrap;}
19+
</style>
20+
</head>
21+
<body>
22+
<div id="root"></div>
23+
<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
24+
<script>
25+
(function(){
26+
var data = ${payload};
27+
var root = document.getElementById("root");
28+
function post(message){ window.ReactNativeWebView.postMessage(JSON.stringify(message)); }
29+
function reportHeight(){ post({ type: "height", height: document.body.scrollHeight }); }
30+
try {
31+
mermaid.initialize({ startOnLoad: false, theme: data.dark ? "dark" : "default" });
32+
mermaid.render("diagram", data.source).then(function(result) {
33+
root.innerHTML = result.svg;
34+
reportHeight();
35+
}).catch(function(error) {
36+
root.innerHTML = "";
37+
var div = document.createElement("div");
38+
div.className = "error";
39+
div.textContent = String((error && error.message) || error);
40+
root.appendChild(div);
41+
post({ type: "error", message: div.textContent });
42+
});
43+
} catch (error) {
44+
post({ type: "error", message: String((error && error.message) || error) });
45+
}
46+
new ResizeObserver(reportHeight).observe(document.body);
47+
})();
48+
</script>
49+
</body>
50+
</html>`;
51+
}
52+
53+
type HeightMessage = { readonly type: "height"; readonly height: number };
54+
type ErrorMessage = { readonly type: "error"; readonly message: string };
55+
56+
export function MobileMermaidDiagram(props: { readonly source: string; readonly dark: boolean }) {
57+
const [height, setHeight] = useState(220);
58+
const [failed, setFailed] = useState<string | null>(null);
59+
const [showCode, setShowCode] = useState(false);
60+
const html = useMemo(() => buildHtml(props.source, props.dark), [props.source, props.dark]);
61+
62+
const onMessage = (event: WebViewMessageEvent) => {
63+
try {
64+
const message = JSON.parse(event.nativeEvent.data) as HeightMessage | ErrorMessage;
65+
if (message.type === "height" && Number.isFinite(message.height)) {
66+
setHeight(Math.min(Math.max(Math.ceil(message.height) + 16, 120), 800));
67+
} else if (message.type === "error") {
68+
setFailed(message.message);
69+
}
70+
} catch {
71+
// Ignore malformed WebView messages.
72+
}
73+
};
74+
75+
return (
76+
<View className="mb-3 overflow-hidden rounded-lg border border-divider bg-card">
77+
<View className="flex-row items-center justify-between px-3 py-2">
78+
<AppText className="text-xs text-muted">Mermaid</AppText>
79+
<View className="flex-row gap-2">
80+
<Pressable
81+
accessibilityRole="button"
82+
accessibilityLabel={showCode ? "Show diagram" : "Show code"}
83+
onPress={() => setShowCode((value) => !value)}
84+
>
85+
<AppText className="text-xs text-link">
86+
{showCode ? "Show diagram" : "Show code"}
87+
</AppText>
88+
</Pressable>
89+
<Pressable
90+
accessibilityRole="button"
91+
accessibilityLabel="Copy diagram source"
92+
onPress={() => void copyTextWithHaptic(props.source)}
93+
>
94+
<AppText className="text-xs text-link">Copy</AppText>
95+
</Pressable>
96+
</View>
97+
</View>
98+
{showCode ? (
99+
<View className="px-3 pb-3">
100+
<AppText selectable className="font-mono text-xs text-code">
101+
{props.source}
102+
</AppText>
103+
</View>
104+
) : (
105+
<WebView
106+
originWhitelist={["*"]}
107+
source={{ html }}
108+
javaScriptEnabled
109+
domStorageEnabled={false}
110+
scrollEnabled={false}
111+
style={{ height }}
112+
onMessage={onMessage}
113+
/>
114+
)}
115+
{failed && !showCode ? (
116+
<View className="px-3 pb-3">
117+
<AppText className="text-xs text-muted">Diagram failed to render. See code.</AppText>
118+
</View>
119+
) : null}
120+
</View>
121+
);
122+
}

0 commit comments

Comments
 (0)