Skip to content

Commit 150ef00

Browse files
committed
fix(mobile): address diagram review findings
Escape < in the WebView payload so diagram text cannot break out of the inline script. Skip non-mermaid fences and accept longer fence runs. Reset the error banner on reload and let tall diagrams scroll instead of clipping. Share link reference definitions with segments after a fence and key segments by position so streaming appends do not remount them.
1 parent 435a370 commit 150ef00

3 files changed

Lines changed: 111 additions & 27 deletions

File tree

‎apps/mobile/src/lib/mermaidBlocks.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,44 @@ describe("splitMarkdownWithMermaid", () => {
4040
expect(first[0].id).toBe(second[0].id);
4141
}
4242
});
43+
44+
it("accepts fences longer than three backticks", () => {
45+
const segments = splitMarkdownWithMermaid(
46+
["````mermaid", "flowchart TD", " A --> B", "````"].join("\n"),
47+
);
48+
expect(segments).toMatchObject([{ kind: "mermaid", source: "flowchart TD\n A --> B" }]);
49+
});
50+
51+
it("keeps a mermaid example inside a non-mermaid fence whole", () => {
52+
const markdown = ["```md", "```mermaid", "A --> B", "```", "```"].join("\n");
53+
const segments = splitMarkdownWithMermaid(markdown);
54+
expect(segments.map((segment) => segment.kind)).toEqual(["markdown"]);
55+
expect(segments[0]).toMatchObject({ kind: "markdown", markdown });
56+
});
57+
58+
it("uses position keys that survive content appends", () => {
59+
const before = splitMarkdownWithMermaid("```mermaid\nA --> B\n```\n\nHello");
60+
const after = splitMarkdownWithMermaid("```mermaid\nA --> B\n```\n\nHello world");
61+
expect(before.map((segment) => segment.key)).toEqual(after.map((segment) => segment.key));
62+
});
63+
64+
it("shares link reference definitions with segments after a fence", () => {
65+
const segments = splitMarkdownWithMermaid(
66+
[
67+
"[guide]: https://example.com",
68+
"",
69+
"```mermaid",
70+
"A --> B",
71+
"```",
72+
"",
73+
"[Open][guide]",
74+
].join("\n"),
75+
);
76+
const tail = segments[segments.length - 1];
77+
expect(tail).toMatchObject({ kind: "markdown" });
78+
if (tail?.kind === "markdown") {
79+
expect(tail.markdown).toContain("[guide]: https://example.com");
80+
expect(tail.markdown).toContain("[Open][guide]");
81+
}
82+
});
4383
});

‎apps/mobile/src/lib/mermaidBlocks.ts‎

Lines changed: 62 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ export type MermaidMarkdownSegment =
99
readonly key: string;
1010
};
1111

12-
const FENCE_RE = /^ {0,3}(```|~~~)[ \t]*([^\n]*)\n?/;
12+
const FENCE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*([^\n]*)\n?/;
13+
const DEFINITION_RE = /^ {0,3}\[[^\]\n]+\]:[ \t]*\S.*$/;
1314

1415
function fenceLanguage(info: string): string {
1516
return info.trim().split(/\s+/, 1)[0]?.toLowerCase() ?? "";
@@ -23,55 +24,93 @@ function fenceHash(source: string): string {
2324
return `m${(hash >>> 0).toString(36)}`;
2425
}
2526

27+
function closerIndex(lines: readonly string[], from: number, fence: string): number {
28+
const char = fence[0] === "`" ? "`" : "~";
29+
const closeRe = new RegExp(`^ {0,3}${char}{${fence.length},}[ \\t]*$`);
30+
for (let scan = from; scan < lines.length; scan += 1) {
31+
if (closeRe.test(lines[scan] ?? "")) return scan;
32+
}
33+
return -1;
34+
}
35+
2636
export function splitMarkdownWithMermaid(markdown: string): MermaidMarkdownSegment[] {
27-
const segments: MermaidMarkdownSegment[] = [];
37+
const raw: Array<
38+
| { readonly kind: "markdown"; readonly markdown: string; readonly start: number }
39+
| {
40+
readonly kind: "mermaid";
41+
readonly source: string;
42+
readonly id: string;
43+
readonly start: number;
44+
}
45+
> = [];
2846
const lines = markdown.split("\n");
2947
let markdownStart = 0;
3048
let index = 0;
3149

3250
const pushMarkdown = (end: number) => {
3351
if (end > markdownStart) {
34-
const markdown = lines.slice(markdownStart, end).join("\n");
35-
segments.push({
52+
raw.push({
3653
kind: "markdown",
37-
markdown,
38-
key: `md-${markdownStart}-${fenceHash(markdown)}`,
54+
markdown: lines.slice(markdownStart, end).join("\n"),
55+
start: markdownStart,
3956
});
4057
}
4158
};
4259

4360
while (index < lines.length) {
4461
const line = lines[index] ?? "";
4562
const open = FENCE_RE.exec(line);
46-
if (!open || fenceLanguage(open[2] ?? "") !== "mermaid") {
63+
if (!open) {
4764
index += 1;
4865
continue;
4966
}
5067
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).
68+
const close = closerIndex(lines, index + 1, fence);
6069
if (close === -1) {
6170
index += 1;
6271
continue;
6372
}
73+
// A non-mermaid fence may document a mermaid example; keep it whole.
74+
if (fenceLanguage(open[2] ?? "") !== "mermaid") {
75+
index = close + 1;
76+
continue;
77+
}
6478
pushMarkdown(index);
6579
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-
});
80+
raw.push({ kind: "mermaid", source, id: fenceHash(source), start: index });
7281
index = close + 1;
7382
markdownStart = index;
7483
}
7584
pushMarkdown(lines.length);
76-
return segments.filter((segment) => segment.kind === "mermaid" || segment.markdown.length > 0);
85+
86+
// Link reference definitions resolve per parser instance, so share them
87+
// with every Markdown segment instead of stranding uses after a fence.
88+
const definitions = [
89+
...new Set(
90+
raw.flatMap((segment) =>
91+
segment.kind === "markdown"
92+
? segment.markdown.split("\n").filter((entry) => DEFINITION_RE.test(entry))
93+
: [],
94+
),
95+
),
96+
];
97+
const prefix = definitions.length > 0 ? `${definitions.join("\n")}\n` : "";
98+
99+
return raw
100+
.map((segment): MermaidMarkdownSegment => {
101+
if (segment.kind === "mermaid") {
102+
return {
103+
kind: "mermaid",
104+
source: segment.source,
105+
id: segment.id,
106+
key: `mmd-${segment.start}`,
107+
};
108+
}
109+
const needsPrefix =
110+
prefix.length > 0 &&
111+
!definitions.every((definition) => segment.markdown.includes(definition));
112+
const text = needsPrefix ? `${prefix}${segment.markdown}` : segment.markdown;
113+
return { kind: "markdown", markdown: text, key: `md-${segment.start}` };
114+
})
115+
.filter((segment) => segment.kind === "mermaid" || segment.markdown.length > 0);
77116
}

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import { AppText } from "../components/ui/AppText";
66
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
77

88
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 });
9+
// Source travels as JSON inside script. Escape `<` so a `</script>` in the
10+
// diagram text cannot close the script tag and run as HTML.
11+
const payload = JSON.stringify({ source, dark }).replace(/</g, "\\u003c");
1112
return `<!doctype html>
1213
<html>
1314
<head>
@@ -67,6 +68,7 @@ function isHeightMessage(message: HeightMessage | ErrorMessage): message is Heig
6768

6869
export function MobileMermaidDiagram(props: { readonly source: string; readonly dark: boolean }) {
6970
const [height, setHeight] = useState(220);
71+
const [tall, setTall] = useState(false);
7072
const [failed, setFailed] = useState<string | null>(null);
7173
const [showCode, setShowCode] = useState(false);
7274
const html = useMemo(() => buildHtml(props.source, props.dark), [props.source, props.dark]);
@@ -76,7 +78,9 @@ export function MobileMermaidDiagram(props: { readonly source: string; readonly
7678
if (!message) return;
7779
if (isHeightMessage(message)) {
7880
if (Number.isFinite(message.height)) {
79-
setHeight(Math.min(Math.max(Math.ceil(message.height) + 16, 120), 800));
81+
const next = Math.ceil(message.height) + 16;
82+
setTall(next > 800);
83+
setHeight(Math.min(Math.max(next, 120), 800));
8084
}
8185
return;
8286
}
@@ -119,7 +123,8 @@ export function MobileMermaidDiagram(props: { readonly source: string; readonly
119123
javaScriptEnabled
120124
domStorageEnabled={false}
121125
allowFileAccess={false}
122-
scrollEnabled={false}
126+
scrollEnabled={tall}
127+
onLoadStart={() => setFailed(null)}
123128
style={{ height }}
124129
onMessage={onMessage}
125130
/>

0 commit comments

Comments
 (0)