Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MermaidCodeBlock.tsx

294 lines10.5 KB

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 { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
11import { mermaidSvgForNative, withDiagramBackground } from "../lib/mermaidSvg";
12import { themeColorWithAlpha } from "../lib/mobileTheme";
13import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame";
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;
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 }
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;
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 );
126​
127function RenderedMermaidBlock(props: MermaidCodeBlockProps) {
128 return <MermaidBlock {...props} diagram={use(loadDiagram(props.code.trim()))} />;
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 return (
195 <CodeBlockFrame
196 label="Mermaid"
197 textStyle={textStyle}
198 actions={
199 <>
200 {svg ? (
201 <CodeBlockHeaderButton
202 icon={showCode ? "flowchart" : "chevron.left.forwardslash.chevron.right"}
203 label={showCode ? "Show diagram" : "Show code"}
204 textStyle={textStyle}
205 onPress={() => setShowCode((value) => !value)}
206 />
207 ) : null}
208 <CodeBlockHeaderButton
209 icon="doc.on.doc"
210 label="Copy code"
211 textStyle={textStyle}
212 onPress={() => copyTextWithHaptic(code)}
213 />
214 </>
215 }
216 >
217 <View style={styles.content}>
218 {diagram?.status === "error" ? (
219 <Text style={[styles.error, { color: secondaryColor, fontSize: codeFontSize * 0.85 }]}>
220 Unable to render diagram: {diagram.message}
221 </Text>
222 ) : null}
223 {svg && diagram?.status === "ready" && !showCode ? (
224 // In a row the width resolves first, so the height follows the shrunk width;
225 // a column with maxWidth would size the height from the full width.
226 <View style={styles.diagramRow}>
227 <Pressable
228 accessibilityRole="imagebutton"
229 accessibilityLabel="Mermaid diagram"
230 accessibilityHint="Opens the diagram full screen"
231 onPress={() => {
232 if (expansion) return;
233 void Haptics.selectionAsync();
234 setExpansion({ status: "exporting" });
235 }}
236 style={{
237 flexBasis: diagram.width,
238 flexShrink: 1,
239 aspectRatio: diagram.width / diagram.height,
240 }}
241 >
242 <SvgXml xml={svg} width="100%" height="100%" />
243 </Pressable>
244 </View>
245 ) : (
246 <Text
247 selectable
248 style={{
249 color: textStyle.codeColor,
250 fontFamily: MONOSPACE,
251 fontSize: codeFontSize,
252 lineHeight: codeFontSize * 1.45,
253 }}
254 >
255 {code}
256 </Text>
257 )}
258 </View>
259 {expansion?.status === "exporting" && exportTree && exportSize ? (
260 <View pointerEvents="none" style={[styles.exportCopy, exportSize]} onLayout={exportDiagram}>
261 <Svg ref={exportSvg} {...exportTree.props} width="100%" height="100%">
262 {exportTree.children}
263 </Svg>
264 </View>
265 ) : null}
266 {expansion?.status === "open" ? (
267 <FilePreviewModal
268 source={{
269 kind: "image",
270 uri: expansion.uri,
271 // The viewer titles an image by a name with an extension.
272 name: "Mermaid diagram.png",
273 mimeType: "image/png",
274 // Alone, as on web, rather than paged with the thread's images.
275 gallery: [],
276 actionsSource: {
277 uri: expansion.uri,
278 name: "Mermaid diagram.png",
279 mimeType: "image/png",
280 },
281 }}
282 onRequestClose={() => setExpansion(null)}
283 />
284 ) : null}
285 </CodeBlockFrame>
286 );
288​
289const styles = StyleSheet.create({
290 content: { padding: 12 },
291 diagramRow: { flexDirection: "row", justifyContent: "center" },
292 error: { marginBottom: 8 },
293 exportCopy: { position: "absolute", opacity: 0 },
294});