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 { T, useGT, Var } from "gt-react-native";
5import type { DiagramType } from "pele/lazy";
6import { Suspense, use, useRef, useState } from "react";
7import { PixelRatio, Platform, Pressable, StyleSheet, Text, View } from "react-native";
8import { parse, Svg, SvgXml } from "react-native-svg";
9
10import { FilePreviewModal } from "../components/ui/FilePreviewModal";
11import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
12import { mermaidSvgForNative, withDiagramBackground } from "../lib/mermaidSvg";
13import { themeColorWithAlpha } from "../lib/mobileTheme";
14import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame";
15import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
16
17type Pele = typeof import("pele/lazy");
18type Diagram =
19 | {
20 readonly status: "ready";
21 readonly svg: string;
22 readonly width: number;
23 readonly height: number;
24 }
25 | { readonly status: "error"; readonly reason: "load" }
26 | { readonly status: "error"; readonly reason: "render"; readonly message: string | null };
27
28let peleLoad: Promise<Pele | null> | null = null;
29// Each diagram type is its own chunk, so a thread with one flowchart only
30// evaluates the flowchart parser and layout.
31const typeLoads = new Map<DiagramType, Promise<boolean>>();
32// A message scrolled back into view reuses its settled promise, which `use`
33// reads without suspending, instead of flashing the source.
34const diagramLoads = new Map<string, Promise<Diagram>>();
35const DIAGRAM_CACHE_LIMIT = 64;
36
37function loadDiagram(source: string): Promise<Diagram> {
38 let load = diagramLoads.get(source);
39 if (!load) {
40 if (diagramLoads.size >= DIAGRAM_CACHE_LIMIT) {
41 diagramLoads.delete(diagramLoads.keys().next().value!);
42 }
43 load = renderDiagram(source);
44 diagramLoads.set(source, load);
45 }
46 return load;
47}
48
49// Pele measures labels with metrics close to Helvetica when no canvas is available.
50const DIAGRAM_FONT = Platform.OS === "ios" ? "Helvetica" : "sans-serif";
51
52async function renderDiagram(source: string): Promise<Diagram> {
53 peleLoad ??= import("pele/lazy").catch(() => null);
54 const pele = await peleLoad;
55 if (!pele) {
56 // Not cached, so the next mount tries again.
57 peleLoad = null;
58 diagramLoads.delete(source);
59 return { status: "error", reason: "load" };
60 }
61 let type: DiagramType | null = null;
62 try {
63 type = pele.detectType(source);
64 } catch {
65 // An unknown type falls through to render, which reports why.
66 }
67 if (type) {
68 let load = typeLoads.get(type);
69 if (!load) {
70 load = pele.load(type).then(
71 () => true,
72 () => false,
73 );
74 typeLoads.set(type, load);
75 }
76 if (!(await load)) {
77 typeLoads.delete(type);
78 diagramLoads.delete(source);
79 return { status: "error", reason: "load" };
80 }
81 }
82 try {
83 const { svg, width, height } = pele.render(source, {
84 links: false,
85 images: false,
86 // Keep the author's direction; a wide diagram scales down to fit instead of turning vertical.
87 autoDirection: false,
88 });
89 return { status: "ready", svg, width, height };
90 } catch (error) {
91 return {
92 status: "error",
93 reason: "render",
94 message: error instanceof Error ? error.message : null,
95 };
96 }
97}
98
99// The image viewer zooms a bitmap: about twice a phone's screen leaves room to zoom while
100// bounding the memory one image takes.
101const EXPORT_LONGEST_SIDE = 3072;
102
103/** Named by content, so a theme change never shows a stale image cached under the same URI. */
104async function writeDiagramImage(xml: string, base64: string): Promise<string> {
105 const file = new File(Paths.cache, "t3-diagrams", `${(Hash.string(xml) >>> 0).toString(36)}.png`);
106 file.create({ intermediates: true, overwrite: true });
107 await file.write(base64, { encoding: "base64" });
108 return file.uri;
109}
110
111type Expansion =
112 | { readonly status: "exporting" }
113 | { readonly status: "open"; readonly uri: string };
114
115type MermaidCodeBlockProps = {
116 readonly code: string;
117 readonly textStyle: NativeMarkdownTextStyle;
118};
119
120/** A complete ```mermaid fence, drawn as its diagram with a toggle back to the source. */
121export function MermaidCodeBlock(props: MermaidCodeBlockProps) {
122 return (
123 <Suspense fallback={<MermaidBlock {...props} diagram={null} />}>
124 <RenderedMermaidBlock {...props} />
125 </Suspense>
126 );
127}
128
129function RenderedMermaidBlock(props: MermaidCodeBlockProps) {
130 return <MermaidBlock {...props} diagram={use(loadDiagram(props.code.trim()))} />;
131}
132
133function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram | null }) {
134 const { code, textStyle, diagram } = props;
135 const gt = useGT();
136 const [showCode, setShowCode] = useState(false);
137 const [expansion, setExpansion] = useState<Expansion | null>(null);
138 const exportSvg = useRef<Svg>(null);
139 const secondaryColor = themeColorWithAlpha(textStyle.codeColor, 0.6);
140 const codeFontSize = textStyle.fontSize * 0.9;
141 const diagramError =
142 diagram?.status !== "error"
143 ? null
144 : diagram.reason === "load"
145 ? gt`The diagram renderer failed to load.`
146 : (diagram.message ?? gt`The diagram could not be rendered.`);
147 const svg =
148 diagram?.status === "ready"
149 ? mermaidSvgForNative(diagram.svg, {
150 "--pele-bg": textStyle.codeBlockBackgroundColor,
151 "--pele-fg": textStyle.color,
152 "--pele-muted": themeColorWithAlpha(textStyle.color, 0.65),
153 "--pele-line": themeColorWithAlpha(textStyle.color, 0.55),
154 "--pele-surface": themeColorWithAlpha(textStyle.color, 0.06),
155 "--pele-surface-alt": themeColorWithAlpha(textStyle.color, 0.12),
156 "--pele-border": themeColorWithAlpha(textStyle.color, 0.28),
157 "--pele-accent": textStyle.linkColor,
158 "--pele-font": DIAGRAM_FONT,
159 "--pele-font-mono": textStyle.monoFontFamily,
160 })
161 : null;
162 const exportXml =
163 expansion?.status === "exporting" && svg
164 ? withDiagramBackground(svg, textStyle.codeBlockBackgroundColor)
165 : null;
166 const exportTree = exportXml ? parse(exportXml) : null;
167 const exportScale =
168 diagram?.status === "ready" ? EXPORT_LONGEST_SIDE / Math.max(diagram.width, diagram.height) : 0;
169 // In points. iOS draws the copy at its own size and the screen scale, Android at the
170 // requested pixels, so the copy is laid out at the export size for both.
171 const exportSize =
172 diagram?.status === "ready"
173 ? {
174 width: (diagram.width * exportScale) / PixelRatio.get(),
175 height: (diagram.height * exportScale) / PixelRatio.get(),
176 }
177 : null;
178
179 // Runs once the hidden export copy has laid out.
180 const exportDiagram = () => {
181 if (!exportSvg.current || !exportXml || !exportSize) return;
182 const pixels = Platform.OS === "ios" ? 1 : PixelRatio.get();
183 exportSvg.current.toDataURL(
184 (base64) => {
185 // A failed capture calls back with nothing; let the next tap try again.
186 if (!base64) {
187 setExpansion(null);
188 return;
189 }
190 // iOS wraps the encoding in line feeds.
191 writeDiagramImage(exportXml, base64.replace(/\s/g, "")).then(
192 (uri) => setExpansion({ status: "open", uri }),
193 () => setExpansion(null),
194 );
195 },
196 {
197 width: Math.round(exportSize.width * pixels),
198 height: Math.round(exportSize.height * pixels),
199 },
200 );
201 };
202
203 return (
204 <CodeBlockFrame
205 label="Mermaid"
206 textStyle={textStyle}
207 actions={
208 <>
209 {svg ? (
210 <CodeBlockHeaderButton
211 icon={showCode ? "flowchart" : "chevron.left.forwardslash.chevron.right"}
212 label={showCode ? gt`Show diagram` : gt`Show code`}
213 textStyle={textStyle}
214 onPress={() => setShowCode((value) => !value)}
215 />
216 ) : null}
217 <CodeBlockHeaderButton
218 icon="doc.on.doc"
219 label={gt`Copy code`}
220 textStyle={textStyle}
221 onPress={() => copyTextWithHaptic(code)}
222 />
223 </>
224 }
225 >
226 <View style={styles.content}>
227 {diagram?.status === "error" ? (
228 <Text style={[styles.error, { color: secondaryColor, fontSize: codeFontSize * 0.85 }]}>
229 <T>
230 Unable to render diagram: <Var>{diagramError}</Var>
231 </T>
232 </Text>
233 ) : null}
234 {svg && diagram?.status === "ready" && !showCode ? (
235 // In a row the width resolves first, so the height follows the shrunk width;
236 // a column with maxWidth would size the height from the full width.
237 <View style={styles.diagramRow}>
238 <Pressable
239 accessibilityRole="imagebutton"
240 accessibilityLabel={gt`${{ name: "Mermaid" }} diagram`}
241 accessibilityHint={gt`Opens the diagram full screen`}
242 onPress={() => {
243 if (expansion) return;
244 void Haptics.selectionAsync();
245 setExpansion({ status: "exporting" });
246 }}
247 style={{
248 flexBasis: diagram.width,
249 flexShrink: 1,
250 aspectRatio: diagram.width / diagram.height,
251 }}
252 >
253 <SvgXml xml={svg} width="100%" height="100%" />
254 </Pressable>
255 </View>
256 ) : (
257 <Text
258 selectable
259 style={{
260 color: textStyle.codeColor,
261 fontFamily: textStyle.monoFontFamily,
262 fontSize: codeFontSize,
263 lineHeight: codeFontSize * 1.45,
264 }}
265 >
266 {code}
267 </Text>
268 )}
269 </View>
270 {expansion?.status === "exporting" && exportTree && exportSize ? (
271 <View pointerEvents="none" style={[styles.exportCopy, exportSize]} onLayout={exportDiagram}>
272 <Svg ref={exportSvg} {...exportTree.props} width="100%" height="100%">
273 {exportTree.children}
274 </Svg>
275 </View>
276 ) : null}
277 {expansion?.status === "open" ? (
278 <FilePreviewModal
279 source={{
280 kind: "image",
281 uri: expansion.uri,
282 // The viewer titles an image by a name with an extension.
283 name: "Mermaid diagram.png",
284 mimeType: "image/png",
285 // Alone, as on web, rather than paged with the thread's images.
286 gallery: [],
287 actionsSource: {
288 uri: expansion.uri,
289 name: "Mermaid diagram.png",
290 mimeType: "image/png",
291 },
292 }}
293 onRequestClose={() => setExpansion(null)}
294 />
295 ) : null}
296 </CodeBlockFrame>
297 );
298}
299
300const styles = StyleSheet.create({
301 content: { padding: 12 },
302 diagramRow: { flexDirection: "row", justifyContent: "center" },
303 error: { marginBottom: 8 },
304 exportCopy: { position: "absolute", opacity: 0 },
305});