Open History to see the last commit
1import * as Hash from "effect/Hash";
2import { File, Paths } from "expo-file-system";
3import * as Haptics from "expo-haptics";
4import type { DiagramType } from "pele/lazy";
5import { Suspense, use, useRef, useState } from "react";
6import { PixelRatio, Platform, Pressable, StyleSheet, Text, View } from "react-native";
7import { parse, Svg, SvgXml } from "react-native-svg";
8
9import { FilePreviewModal } from "../components/ui/FilePreviewModal";
10import { SymbolView, type AppSymbolName } from "../components/ui/AppSymbol";
11import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
12import { mermaidSvgForNative, withDiagramBackground } from "../lib/mermaidSvg";
13import { themeColorWithAlpha } from "../lib/mobileTheme";
14import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
15
16type Pele = typeof import("pele/lazy");
17type Diagram =
18 | {
19 readonly status: "ready";
20 readonly svg: string;
21 readonly width: number;
22 readonly height: number;
23 }
24 | { readonly status: "error"; readonly message: string };
25
26let peleLoad: Promise<Pele | null> | null = null;
27// Each diagram type is its own chunk, so a thread with one flowchart only
28// evaluates the flowchart parser and layout.
29const typeLoads = new Map<DiagramType, Promise<boolean>>();
30// A message scrolled back into view reuses its settled promise, which `use`
31// reads without suspending, instead of flashing the source.
32const diagramLoads = new Map<string, Promise<Diagram>>();
33const DIAGRAM_CACHE_LIMIT = 64;
34
35function loadDiagram(source: string): Promise<Diagram> {
36 let load = diagramLoads.get(source);
37 if (!load) {
38 if (diagramLoads.size >= DIAGRAM_CACHE_LIMIT) {
39 diagramLoads.delete(diagramLoads.keys().next().value!);
40 }
41 load = renderDiagram(source);
42 diagramLoads.set(source, load);
43 }
44 return load;
45}
46
47const MONOSPACE = Platform.OS === "ios" ? "Menlo" : "monospace";
48// Pele measures labels with metrics close to Helvetica when no canvas is available.
49const DIAGRAM_FONT = Platform.OS === "ios" ? "Helvetica" : "sans-serif";
50
51async function renderDiagram(source: string): Promise<Diagram> {
52 peleLoad ??= import("pele/lazy").catch(() => null);
53 const pele = await peleLoad;
54 if (!pele) {
55 // Not cached, so the next mount tries again.
56 peleLoad = null;
57 diagramLoads.delete(source);
58 return { status: "error", message: "The diagram renderer failed to load." };
59 }
60 let type: DiagramType | null = null;
61 try {
62 type = pele.detectType(source);
63 } catch {
64 // An unknown type falls through to render, which reports why.
65 }
66 if (type) {
67 let load = typeLoads.get(type);
68 if (!load) {
69 load = pele.load(type).then(
70 () => true,
71 () => false,
72 );
73 typeLoads.set(type, load);
74 }
75 if (!(await load)) {
76 typeLoads.delete(type);
77 diagramLoads.delete(source);
78 return { status: "error", message: "The diagram renderer failed to load." };
79 }
80 }
81 try {
82 const { svg, width, height } = pele.render(source, {
83 links: false,
84 images: false,
85 // Keep the author's direction; a wide diagram scales down to fit instead of turning vertical.
86 autoDirection: false,
87 });
88 return { status: "ready", svg, width, height };
89 } catch (error) {
90 return {
91 status: "error",
92 message: error instanceof Error ? error.message : "The diagram could not be rendered.",
93 };
94 }
95}
96
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.
99const EXPORT_LONGEST_SIDE = 3072;
100
101/** Named by content, so a theme change never shows a stale image cached under the same URI. */
102async 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
109type Expansion =
110 | { readonly status: "exporting" }
111 | { readonly status: "open"; readonly uri: string };
112
113type MermaidCodeBlockProps = {
114 readonly code: string;
115 readonly textStyle: NativeMarkdownTextStyle;
116};
117
118/** A complete ```mermaid fence, drawn as its diagram with a toggle back to the source. */
119export function MermaidCodeBlock(props: MermaidCodeBlockProps) {
120 return (
121 <Suspense fallback={<MermaidBlock {...props} diagram={null} />}>
122 <RenderedMermaidBlock {...props} />
123 </Suspense>
124 );
125}
126
127function RenderedMermaidBlock(props: MermaidCodeBlockProps) {
128 return <MermaidBlock {...props} diagram={use(loadDiagram(props.code.trim()))} />;
129}
130
131function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram | null }) {
132 const { code, textStyle, diagram } = props;
133 const [showCode, setShowCode] = useState(false);
134 const [expansion, setExpansion] = useState<Expansion | null>(null);
135 const exportSvg = useRef<Svg>(null);
136 const secondaryColor = themeColorWithAlpha(textStyle.codeColor, 0.6);
137 const codeFontSize = textStyle.fontSize * 0.9;
138 const svg =
139 diagram?.status === "ready"
140 ? mermaidSvgForNative(diagram.svg, {
141 "--pele-bg": textStyle.codeBlockBackgroundColor,
142 "--pele-fg": textStyle.color,
143 "--pele-muted": themeColorWithAlpha(textStyle.color, 0.65),
144 "--pele-line": themeColorWithAlpha(textStyle.color, 0.55),
145 "--pele-surface": themeColorWithAlpha(textStyle.color, 0.06),
146 "--pele-surface-alt": themeColorWithAlpha(textStyle.color, 0.12),
147 "--pele-border": themeColorWithAlpha(textStyle.color, 0.28),
148 "--pele-accent": textStyle.linkColor,
149 "--pele-font": DIAGRAM_FONT,
150 "--pele-font-mono": MONOSPACE,
151 })
152 : 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 // A failed capture calls back with nothing; let the next tap try again.
177 if (!base64) {
178 setExpansion(null);
179 return;
180 }
181 // iOS wraps the encoding in line feeds.
182 writeDiagramImage(exportXml, base64.replace(/\s/g, "")).then(
183 (uri) => setExpansion({ status: "open", uri }),
184 () => setExpansion(null),
185 );
186 },
187 {
188 width: Math.round(exportSize.width * pixels),
189 height: Math.round(exportSize.height * pixels),
190 },
191 );
192 };
193
194 // The header copies the native code block's, which this block replaces once the fence closes.
195 return (
196 <View
197 style={[
198 styles.block,
199 {
200 backgroundColor: textStyle.codeBlockBackgroundColor,
201 borderColor: textStyle.dividerColor,
202 },
203 ]}
204 >
205 <View
206 style={[
207 styles.header,
208 { borderBottomColor: themeColorWithAlpha(textStyle.codeColor, 0.2) },
209 ]}
210 >
211 <Text style={[styles.language, { color: secondaryColor, fontSize: codeFontSize * 0.85 }]}>
212 Mermaid
213 </Text>
214 <View style={styles.actions}>
215 {svg ? (
216 <HeaderButton
217 icon={showCode ? "flowchart" : "chevron.left.forwardslash.chevron.right"}
218 label={showCode ? "Show diagram" : "Show code"}
219 color={secondaryColor}
220 onPress={() => setShowCode((value) => !value)}
221 />
222 ) : null}
223 <HeaderButton
224 icon="doc.on.doc"
225 label="Copy code"
226 color={secondaryColor}
227 onPress={() => copyTextWithHaptic(code)}
228 />
229 </View>
230 </View>
231 <View style={styles.content}>
232 {diagram?.status === "error" ? (
233 <Text style={[styles.error, { color: secondaryColor, fontSize: codeFontSize * 0.85 }]}>
234 Unable to render diagram: {diagram.message}
235 </Text>
236 ) : null}
237 {svg && diagram?.status === "ready" && !showCode ? (
238 // In a row the width resolves first, so the height follows the shrunk width;
239 // a column with maxWidth would size the height from the full width.
240 <View style={styles.diagramRow}>
241 <Pressable
242 accessibilityRole="imagebutton"
243 accessibilityLabel="Mermaid diagram"
244 accessibilityHint="Opens the diagram full screen"
245 onPress={() => {
246 if (expansion) return;
247 void Haptics.selectionAsync();
248 setExpansion({ status: "exporting" });
249 }}
250 style={{
251 flexBasis: diagram.width,
252 flexShrink: 1,
253 aspectRatio: diagram.width / diagram.height,
254 }}
255 >
256 <SvgXml xml={svg} width="100%" height="100%" />
257 </Pressable>
258 </View>
259 ) : (
260 <Text
261 selectable
262 style={{
263 color: textStyle.codeColor,
264 fontFamily: MONOSPACE,
265 fontSize: codeFontSize,
266 lineHeight: codeFontSize * 1.45,
267 }}
268 >
269 {code}
270 </Text>
271 )}
272 </View>
273 {expansion?.status === "exporting" && exportTree && exportSize ? (
274 <View pointerEvents="none" style={[styles.exportCopy, exportSize]} onLayout={exportDiagram}>
275 <Svg ref={exportSvg} {...exportTree.props} width="100%" height="100%">
276 {exportTree.children}
277 </Svg>
278 </View>
279 ) : null}
280 {expansion?.status === "open" ? (
281 <FilePreviewModal
282 source={{
283 kind: "image",
284 uri: expansion.uri,
285 // The viewer titles an image by a name with an extension.
286 name: "Mermaid diagram.png",
287 mimeType: "image/png",
288 // Alone, as on web, rather than paged with the thread's images.
289 gallery: [],
290 actionsSource: {
291 uri: expansion.uri,
292 name: "Mermaid diagram.png",
293 mimeType: "image/png",
294 },
295 }}
296 onRequestClose={() => setExpansion(null)}
297 />
298 ) : null}
299 </View>
300 );
301}
302
303function HeaderButton(props: {
304 readonly icon: AppSymbolName;
305 readonly label: string;
306 readonly color: string;
307 readonly onPress: () => void;
308}) {
309 return (
310 <Pressable
311 accessibilityRole="button"
312 accessibilityLabel={props.label}
313 hitSlop={10}
314 onPress={props.onPress}
315 >
316 <SymbolView name={props.icon} size={14} tintColor={props.color} type="monochrome" />
317 </Pressable>
318 );
319}
320
321// The block slot already applies the code block's outer margins.
322const styles = StyleSheet.create({
323 block: {
324 borderRadius: 8,
325 borderWidth: StyleSheet.hairlineWidth,
326 overflow: "hidden",
327 },
328 header: {
329 height: 32,
330 paddingHorizontal: 12,
331 flexDirection: "row",
332 alignItems: "center",
333 justifyContent: "space-between",
334 borderBottomWidth: StyleSheet.hairlineWidth,
335 },
336 language: { fontWeight: "500" },
337 actions: { flexDirection: "row", alignItems: "center", gap: 14 },
338 content: { padding: 12 },
339 diagramRow: { flexDirection: "row", justifyContent: "center" },
340 error: { marginBottom: 8 },
341 exportCopy: { position: "absolute", opacity: 0 },
342});