Skip to content

Commit bf38c10

Browse files
feat(mobile): tap a Mermaid diagram to open it full screen
The image viewer draws bitmaps, so a tap exports the diagram as a PNG with the code block colour behind it and opens it there, with zoom, save and share, as web does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 497bb8a commit bf38c10

3 files changed

Lines changed: 117 additions & 9 deletions

File tree

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { render } from "pele";
22
import { describe, expect, it } from "vite-plus/test";
33

4-
import { mermaidSvgForNative } from "./mermaidSvg";
4+
import { mermaidSvgForNative, withDiagramBackground } from "./mermaidSvg";
55

66
describe("mermaidSvgForNative", () => {
77
it("turns Pele's CSS variables and styles into attributes react-native-svg draws", () => {
@@ -24,5 +24,9 @@ describe("mermaidSvgForNative", () => {
2424
// Colors the theme leaves out keep Pele's fallback, and the corner radius becomes geometry.
2525
expect(native).toContain('fill="#f3f3f3"');
2626
expect(native).toMatch(/<rect[^>]* rx="4"/);
27+
// The exported image fills the viewBox before anything else draws.
28+
expect(withDiagramBackground(native, "#fafafa")).toMatch(
29+
/^<svg[^>]*><rect x="0" y="0" width="\d+(\.\d+)?" height="\d+(\.\d+)?" fill="#fafafa"\/>/,
30+
);
2731
});
2832
});

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ export function mermaidSvgForNative(svg: string, theme: Readonly<Record<string,
3232
return root + resolve(body);
3333
}
3434

35+
/** Fills the diagram's viewBox, so an exported image reads on any background. */
36+
export function withDiagramBackground(svg: string, color: string): string {
37+
const rootTag = /^<svg\b[^>]*>/.exec(svg)?.[0];
38+
const box = /\sviewBox="([^"]*)"/
39+
.exec(rootTag ?? "")?.[1]
40+
?.trim()
41+
.split(/[\s,]+/);
42+
if (!rootTag || box?.length !== 4) return svg;
43+
const [x, y, width, height] = box;
44+
return `${rootTag}<rect x="${x}" y="${y}" width="${width}" height="${height}" fill="${color}"/>${svg.slice(rootTag.length)}`;
45+
}
46+
3547
function styleDeclarations(style: string): Map<string, string> {
3648
const declarations = new Map<string, string>();
3749
for (const declaration of style.split(";")) {

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

Lines changed: 100 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1+
import * as Hash from "effect/Hash";
2+
import { File, Paths } from "expo-file-system";
3+
import * as Haptics from "expo-haptics";
14
import type { DiagramType } from "pele/lazy";
2-
import { Suspense, use, useState } from "react";
3-
import { Platform, Pressable, StyleSheet, Text, View } from "react-native";
4-
import { SvgXml } from "react-native-svg";
5+
import { Suspense, use, useRef, useState } from "react";
6+
import { PixelRatio, Platform, Pressable, StyleSheet, Text, View } from "react-native";
7+
import { parse, Svg, SvgXml } from "react-native-svg";
58

9+
import { MediaImagePreview } from "../components/MediaImagePreview";
610
import { SymbolView, type AppSymbolName } from "../components/ui/AppSymbol";
711
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
8-
import { mermaidSvgForNative } from "../lib/mermaidSvg";
12+
import { mermaidSvgForNative, withDiagramBackground } from "../lib/mermaidSvg";
913
import { themeColorWithAlpha } from "../lib/mobileTheme";
1014
import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
1115

@@ -90,6 +94,22 @@ async function renderDiagram(source: string): Promise<Diagram> {
9094
}
9195
}
9296

97+
// The image viewer zooms a bitmap: about twice a phone's screen leaves room to zoom while
98+
// bounding the memory one image takes.
99+
const EXPORT_LONGEST_SIDE = 3072;
100+
101+
/** Named by content, so a theme change never shows a stale image cached under the same URI. */
102+
async function writeDiagramImage(xml: string, base64: string): Promise<string> {
103+
const file = new File(Paths.cache, "t3-diagrams", `${(Hash.string(xml) >>> 0).toString(36)}.png`);
104+
file.create({ intermediates: true, overwrite: true });
105+
await file.write(base64, { encoding: "base64" });
106+
return file.uri;
107+
}
108+
109+
type Expansion =
110+
| { readonly status: "exporting" }
111+
| { readonly status: "open"; readonly uri: string };
112+
93113
type MermaidCodeBlockProps = {
94114
readonly code: string;
95115
readonly textStyle: NativeMarkdownTextStyle;
@@ -111,6 +131,8 @@ function RenderedMermaidBlock(props: MermaidCodeBlockProps) {
111131
function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram | null }) {
112132
const { code, textStyle, diagram } = props;
113133
const [showCode, setShowCode] = useState(false);
134+
const [expansion, setExpansion] = useState<Expansion | null>(null);
135+
const exportSvg = useRef<Svg>(null);
114136
const secondaryColor = themeColorWithAlpha(textStyle.codeColor, 0.6);
115137
const codeFontSize = textStyle.fontSize * 0.9;
116138
const svg =
@@ -128,6 +150,41 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram
128150
"--pele-font-mono": MONOSPACE,
129151
})
130152
: null;
153+
const exportXml =
154+
expansion?.status === "exporting" && svg
155+
? withDiagramBackground(svg, textStyle.codeBlockBackgroundColor)
156+
: null;
157+
const exportTree = exportXml ? parse(exportXml) : null;
158+
const exportScale =
159+
diagram?.status === "ready" ? EXPORT_LONGEST_SIDE / Math.max(diagram.width, diagram.height) : 0;
160+
// In points. iOS draws the copy at its own size and the screen scale, Android at the
161+
// requested pixels, so the copy is laid out at the export size for both.
162+
const exportSize =
163+
diagram?.status === "ready"
164+
? {
165+
width: (diagram.width * exportScale) / PixelRatio.get(),
166+
height: (diagram.height * exportScale) / PixelRatio.get(),
167+
}
168+
: null;
169+
170+
// Runs once the hidden export copy has laid out.
171+
const exportDiagram = () => {
172+
if (!exportSvg.current || !exportXml || !exportSize) return;
173+
const pixels = Platform.OS === "ios" ? 1 : PixelRatio.get();
174+
exportSvg.current.toDataURL(
175+
(base64) => {
176+
// iOS wraps the encoding in line feeds.
177+
writeDiagramImage(exportXml, base64.replace(/\s/g, "")).then(
178+
(uri) => setExpansion({ status: "open", uri }),
179+
() => setExpansion(null),
180+
);
181+
},
182+
{
183+
width: Math.round(exportSize.width * pixels),
184+
height: Math.round(exportSize.height * pixels),
185+
},
186+
);
187+
};
131188

132189
// The header copies the native code block's, which this block replaces once the fence closes.
133190
return (
@@ -176,18 +233,23 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram
176233
// In a row the width resolves first, so the height follows the shrunk width;
177234
// a column with maxWidth would size the height from the full width.
178235
<View style={styles.diagramRow}>
179-
<View
180-
accessible
181-
accessibilityRole="image"
236+
<Pressable
237+
accessibilityRole="imagebutton"
182238
accessibilityLabel="Mermaid diagram"
239+
accessibilityHint="Opens the diagram full screen"
240+
onPress={() => {
241+
if (expansion) return;
242+
void Haptics.selectionAsync();
243+
setExpansion({ status: "exporting" });
244+
}}
183245
style={{
184246
flexBasis: diagram.width,
185247
flexShrink: 1,
186248
aspectRatio: diagram.width / diagram.height,
187249
}}
188250
>
189251
<SvgXml xml={svg} width="100%" height="100%" />
190-
</View>
252+
</Pressable>
191253
</View>
192254
) : (
193255
<Text
@@ -203,6 +265,35 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram
203265
</Text>
204266
)}
205267
</View>
268+
{expansion?.status === "exporting" && exportTree && exportSize ? (
269+
<View pointerEvents="none" style={[styles.exportCopy, exportSize]} onLayout={exportDiagram}>
270+
<Svg ref={exportSvg} {...exportTree.props} width="100%" height="100%">
271+
{exportTree.children}
272+
</Svg>
273+
</View>
274+
) : null}
275+
{expansion?.status === "open" ? (
276+
<MediaImagePreview
277+
source={{
278+
kind: "image",
279+
selectedIndex: 0,
280+
images: [
281+
{
282+
kind: "image",
283+
uri: expansion.uri,
284+
name: "Mermaid diagram",
285+
mimeType: "image/png",
286+
actionsSource: {
287+
uri: expansion.uri,
288+
name: "Mermaid diagram.png",
289+
mimeType: "image/png",
290+
},
291+
},
292+
],
293+
}}
294+
onRequestClose={() => setExpansion(null)}
295+
/>
296+
) : null}
206297
</View>
207298
);
208299
}
@@ -245,4 +336,5 @@ const styles = StyleSheet.create({
245336
content: { padding: 12 },
246337
diagramRow: { flexDirection: "row", justifyContent: "center" },
247338
error: { marginBottom: 8 },
339+
exportCopy: { position: "absolute", opacity: 0 },
248340
});

0 commit comments

Comments
 (0)