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