:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mobilehog): render mermaid diagrams (#109532)
Dylan Martin27518b6a1cb9
diff --git a/products/desktop/apps/mobilehog/metro.config.js b/products/desktop/apps/mobilehog/metro.config.jsindex d6073f0cf514..855936210279 100644--- a/products/desktop/apps/mobilehog/metro.config.js+++ b/products/desktop/apps/mobilehog/metro.config.js@@ -6,6 +6,10 @@ const monorepoRoot = path.resolve(projectRoot, "../..");const config = getDefaultConfig(projectRoot);+config.transformer.babelTransformerPath = require.resolve(+ "./metro.transformer.js",+);+config.watchFolders = [monorepoRoot];config.resolver.nodeModulesPaths = [path.resolve(projectRoot, "node_modules"),diff --git a/products/desktop/apps/mobilehog/metro.transformer.js b/products/desktop/apps/mobilehog/metro.transformer.jsnew file mode 100644index 000000000000..e04bef64a1c5--- /dev/null+++ b/products/desktop/apps/mobilehog/metro.transformer.js@@ -0,0 +1,25 @@+const path = require("node:path");++const upstream = require(+ require.resolve("@expo/metro-config/babel-transformer", {+ paths: [path.dirname(require.resolve("expo/package.json"))],+ }),+);++// The WebView gets mermaid's browser bundle as text. Exporting it as a string+// keeps Hermes from running a DOM library and keeps it out of startup until a+// diagram requires it.+const RAW_MODULES = [path.join("mermaid", "dist", "mermaid.min.js")];++module.exports = {+ ...upstream,+ transform(props) {+ if (RAW_MODULES.some((suffix) => props.filename.endsWith(suffix))) {+ return upstream.transform({+ ...props,+ src: `module.exports = ${JSON.stringify(props.src)};`,+ });+ }+ return upstream.transform(props);+ },+};diff --git a/products/desktop/apps/mobilehog/package.json b/products/desktop/apps/mobilehog/package.jsonindex fc479875ab34..b45e5a764e4d 100644--- a/products/desktop/apps/mobilehog/package.json+++ b/products/desktop/apps/mobilehog/package.json@@ -64,6 +64,7 @@"expo-updates": "~57.0.22","expo-web-browser": "~57.0.2","marked": "16.4.2",+ "mermaid": "^11.17.0","react": "catalog:","react-dom": "catalog:","react-native": "0.86.0",diff --git a/products/desktop/apps/mobilehog/src/components/Markdown.tsx b/products/desktop/apps/mobilehog/src/components/Markdown.tsxindex 1216c1529283..8405a91e64e4 100644--- a/products/desktop/apps/mobilehog/src/components/Markdown.tsx+++ b/products/desktop/apps/mobilehog/src/components/Markdown.tsx@@ -11,7 +11,9 @@ import {Text,View,} from "react-native";+import { MermaidDiagram } from "@/components/MermaidDiagram";import { splitImageRuns } from "@/lib/markdown";+import { isClosedFence, isMermaidLang } from "@/lib/mermaid";import { colors, fonts } from "@/lib/theme";interface MarkdownProps {@@ -220,6 +222,17 @@ function Paragraph({ tokens, color }: { tokens: Token[]; color: ColorValue }) {);}+function CodeBlock({ token }: { token: Tokens.Code }) {+ return (+ <View style={styles.codeBlock}>+ {token.lang ? <Text style={styles.codeLang}>{token.lang}</Text> : null}+ <Text style={styles.codeText} selectable>+ {token.text}+ </Text>+ </View>+ );+}+function renderBlocks(tokens: Token[] | undefined,color: ColorValue,@@ -229,15 +242,14 @@ function renderBlocks(const key = `${index}-${token.type}`;switch (token.type) {case "code":- return (- <View key={key} style={styles.codeBlock}>- {token.lang ? (- <Text style={styles.codeLang}>{token.lang}</Text>- ) : null}- <Text style={styles.codeText} selectable>- {token.text}- </Text>- </View>+ return isMermaidLang(token.lang) && isClosedFence(token.raw) ? (+ <MermaidDiagram+ key={key}+ code={token.text}+ fallback={<CodeBlock token={token} />}+ />+ ) : (+ <CodeBlock key={key} token={token} />);case "heading":return (diff --git a/products/desktop/apps/mobilehog/src/components/MermaidDiagram.tsx b/products/desktop/apps/mobilehog/src/components/MermaidDiagram.tsxnew file mode 100644index 000000000000..fe70a58768fd--- /dev/null+++ b/products/desktop/apps/mobilehog/src/components/MermaidDiagram.tsx@@ -0,0 +1,150 @@+import { type ReactNode, useMemo, useState } from "react";+import {+ ActivityIndicator,+ ScrollView,+ StyleSheet,+ useColorScheme,+ View,+} from "react-native";+import WebView from "react-native-webview";+import {+ type DiagramSize,+ hasRemoteImageNode,+ inlineScriptSource,+ mermaidHtml,+ parseMermaidMessage,+ rememberSize,+} from "@/lib/mermaid";+import { colors } from "@/lib/theme";++const PADDING = 12;+const PENDING_HEIGHT = 120;+const SIZE_CACHE_LIMIT = 50;++let bundle: string | null = null;++// Metro exports the prebuilt browser bundle as a string (see metro.transformer.js).+function mermaidBundle(): string {+ bundle ??= inlineScriptSource(+ require("mermaid/dist/mermaid.min.js") as string,+ );+ return bundle;+}++// Remounted rows keep their height instead of jumping while the WebView loads.+const sizes = new Map<string, DiagramSize>();++interface MermaidDiagramProps {+ code: string;+ fallback: ReactNode;+}++// Keyed by theme and code, so a new diagram starts without the old failure or size.+export function MermaidDiagram(props: MermaidDiagramProps): ReactNode {+ const dark = useColorScheme() === "dark";+ const key = `${dark ? "dark" : "light"}\n${props.code}`;+ return <DiagramView key={key} cacheKey={key} dark={dark} {...props} />;+}++interface DiagramViewProps extends MermaidDiagramProps {+ cacheKey: string;+ dark: boolean;+}++function DiagramView({+ code,+ fallback,+ cacheKey,+ dark,+}: DiagramViewProps): ReactNode {+ const html = useMemo(+ () => mermaidHtml(code, dark, mermaidBundle()),+ [code, dark],+ );+ const [width, setWidth] = useState(0);+ const [size, setSize] = useState(() => sizes.get(cacheKey) ?? null);+ const [failed, setFailed] = useState(false);++ if (failed || hasRemoteImageNode(code)) return fallback;++ const fail = () => setFailed(true);+ const onMessage = (data: string) => {+ const message = parseMermaidMessage(data);+ if (message?.type === "size") {+ const next = { width: message.width, height: message.height };+ rememberSize(sizes, cacheKey, next, SIZE_CACHE_LIMIT);+ setSize(next);+ } else if (message?.type === "error") {+ fail();+ }+ };++ return (+ <View+ style={styles.frame}+ onLayout={(event) =>+ setWidth(event.nativeEvent.layout.width - PADDING * 2)+ }+ >+ <ScrollView+ horizontal+ showsHorizontalScrollIndicator={false}+ contentContainerStyle={styles.content}+ >+ {width > 0 ? (+ <WebView+ source={{ html }}+ originWhitelist={["*"]}+ onShouldStartLoadWithRequest={(request) =>+ request.url.startsWith("about:")+ }+ onMessage={(event) => onMessage(event.nativeEvent.data)}+ onError={fail}+ onContentProcessDidTerminate={fail}+ onRenderProcessGone={fail}+ javaScriptEnabled+ scrollEnabled={false}+ bounces={false}+ setSupportMultipleWindows={false}+ showsHorizontalScrollIndicator={false}+ showsVerticalScrollIndicator={false}+ style={[+ styles.webview,+ size ?? { width, height: PENDING_HEIGHT, opacity: 0 },+ ]}+ />+ ) : (+ <View style={{ height: PENDING_HEIGHT }} />+ )}+ </ScrollView>+ {size ? null : (+ <View pointerEvents="none" style={styles.spinner}>+ <ActivityIndicator color={colors.inkMute} />+ </View>+ )}+ </View>+ );+}++const styles = StyleSheet.create({+ frame: {+ backgroundColor: colors.code,+ borderRadius: 12,+ overflow: "hidden",+ },+ content: {+ flexGrow: 1,+ justifyContent: "center",+ padding: PADDING,+ },+ webview: { backgroundColor: "transparent" },+ spinner: {+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ alignItems: "center",+ justifyContent: "center",+ },+});diff --git a/products/desktop/apps/mobilehog/src/lib/mermaid.test.ts b/products/desktop/apps/mobilehog/src/lib/mermaid.test.tsnew file mode 100644index 000000000000..b7528d2ca9b6--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/mermaid.test.ts@@ -0,0 +1,145 @@+import { readFileSync } from "node:fs";+import { createRequire } from "node:module";+import { runInNewContext } from "node:vm";+import { describe, expect, it } from "vitest";+import {+ type DiagramSize,+ hasRemoteImageNode,+ inlineScriptSource,+ isClosedFence,+ isMermaidLang,+ mermaidHtml,+ parseMermaidMessage,+ rememberSize,+} from "./mermaid";++describe("isMermaidLang", () => {+ it.each([+ ["mermaid", true],+ ["Mermaid", true],+ ["mermaid title", true],+ ["mermaidjs", false],+ ["ts", false],+ [undefined, false],+ ])("%s -> %s", (lang, expected) => {+ expect(isMermaidLang(lang)).toBe(expected);+ });+});++describe("isClosedFence", () => {+ it.each([+ ["```mermaid\ngraph TD\n```", true],+ ["```mermaid\ngraph TD\n```\n\n", true],+ ["~~~mermaid\ngraph TD\n~~~", true],+ ["````mermaid\ngraph TD\n````", true],+ ["```mermaid\ngraph TD\n A-->B", false],+ ["```mermaid\ngraph TD\n~~~", false],+ ["````mermaid\ngraph TD\n```", false],+ ["```mermaid", false],+ ])("%j -> %s", (raw, expected) => {+ expect(isClosedFence(raw)).toBe(expected);+ });+});++describe("hasRemoteImageNode", () => {+ it.each([+ ['flowchart TD\n A@{ img: "https://example.com/a.png" }', true],+ ["flowchart TD\n A@{ IMG: 'https://example.com/a.png' }", true],+ ["flowchart TD\n A@{ label: x, img: //example.com/a.png }", true],+ ['flowchart TD\n A@{ img: "data:image/png;base64,AAAA" }', false],+ ["flowchart TD\n A[img] --> B", false],+ ])("%j -> %s", (code, expected) => {+ expect(hasRemoteImageNode(code)).toBe(expected);+ });+});++describe("parseMermaidMessage", () => {+ it.each([+ [+ '{"type":"size","width":120,"height":80}',+ { type: "size", width: 120, height: 80 },+ ],+ ['{"type":"error"}', { type: "error" }],+ ['{"type":"size","width":0,"height":80}', null],+ ['{"type":"size","width":"120","height":80}', null],+ ["not json", null],+ ["null", null],+ ])("%s", (data, expected) => {+ expect(parseMermaidMessage(data)).toEqual(expected);+ });+});++describe("mermaidHtml", () => {+ it("keeps diagram text from closing the script tag", () => {+ const html = mermaidHtml(+ 'graph TD\n A["</script><img src=x>"]',+ false,+ "",+ );+ expect(html.match(/<\/script>/g)).toHaveLength(2);+ expect(html).toContain("\\u003c/script>\\u003cimg src=x>");+ });++ it("uses strict security and follows the color scheme", () => {+ expect(mermaidHtml("graph TD", true, "")).toContain('"theme":"dark"');+ expect(mermaidHtml("graph TD", false, "")).toContain('"theme":"default"');+ expect(mermaidHtml("graph TD", false, "")).toContain(+ '"securityLevel":"strict"',+ );+ });++ it("blocks every network fetch", () => {+ expect(mermaidHtml("graph TD", false, "")).toContain("default-src 'none'");+ });++ it("loads the bundle in a page script before the render script", () => {+ const html = mermaidHtml("graph TD", false, "window.mermaid = {};");+ expect(html).toContain("<script>window.mermaid = {};</script>");+ expect(html.indexOf("window.mermaid = {};")).toBeLessThan(+ html.indexOf("mermaid.initialize"),+ );+ });+});++describe("inlineScriptSource", () => {+ it("escapes sequences that end or nest a script tag", () => {+ const source = 'a="</script>";b=/<!--/;c="<SCRIPT>";d="a<b"';+ const escaped = inlineScriptSource(source);+ expect(escaped).not.toMatch(/<\/?script|<!--/i);+ expect(escaped).toContain('d="a<b"');+ const context = runInNewContext(+ `${escaped};({ a, b: b.test("<!--"), c, d })`,+ );+ expect(context).toEqual({+ a: "</script>",+ b: true,+ c: "<SCRIPT>",+ d: "a<b",+ });+ });++ it("keeps the real bundle runnable as a page script", () => {+ const path = createRequire(import.meta.url).resolve(+ "mermaid/dist/mermaid.min.js",+ );+ const source = inlineScriptSource(readFileSync(path, "utf8"));+ expect(source).not.toMatch(/<\/script/i);+ const context: Record<string, unknown> = {};+ runInNewContext(source, context);+ expect(context.mermaid).toBeDefined();+ });+});++describe("rememberSize", () => {+ const size = (width: number): DiagramSize => ({ width, height: 10 });++ it("drops the least recently stored entries over the limit", () => {+ const cache = new Map<string, DiagramSize>();+ rememberSize(cache, "a", size(1), 2);+ rememberSize(cache, "b", size(2), 2);+ rememberSize(cache, "a", size(3), 2);+ rememberSize(cache, "c", size(4), 2);+ expect([...cache.keys()]).toEqual(["a", "c"]);+ expect(cache.get("a")).toEqual(size(3));+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/mermaid.ts b/products/desktop/apps/mobilehog/src/lib/mermaid.tsnew file mode 100644index 000000000000..8ac6b745544f--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/mermaid.ts@@ -0,0 +1,154 @@+const MERMAID_LANGUAGE = "mermaid";++export function isMermaidLang(lang: string | undefined): boolean {+ return lang?.trim().split(/\s+/)[0].toLowerCase() === MERMAID_LANGUAGE;+}++// A fence without its closing line is still streaming; rendering each partial+// diagram would reload the WebView on every token.+export function isClosedFence(raw: string): boolean {+ const open = /^ {0,3}(`{3,}|~{3,})/.exec(raw);+ if (!open) return false;+ const fence = open[1];+ const lines = raw.trimEnd().split("\n");+ if (lines.length < 2) return false;+ const last = lines[lines.length - 1].trim();+ return (+ last.length >= fence.length &&+ /^(`+|~+)$/.test(last) &&+ last[0] === fence[0]+ );+}++// The `img` key of a shape metadata block, as in `A@{ img: "…" }`. Mermaid reads the key+// case sensitively today, but matching either case keeps the guard off that detail.+const IMAGE_NODE =+ /(?:^|[,{\s])["']?img["']?\s*:\s*(?<url>"[^"]*"|'[^']*'|[^,}\n]*)/gi;++// Mermaid loads an image node through `new Image()` while it builds the SVG, before+// DOMPurify ever sees the output. Diagrams reach us from agent output, so a remote+// image node would let their author make the app fetch any URL.+export function hasRemoteImageNode(code: string): boolean {+ for (const node of code.matchAll(IMAGE_NODE)) {+ const url = node.groups?.url?.trim() ?? "";+ if (!/^["']?data:/i.test(url)) return true;+ }+ return false;+}++export interface DiagramSize {+ width: number;+ height: number;+}++export type MermaidMessage =+ | ({ type: "size" } & DiagramSize)+ | { type: "error" };++export function parseMermaidMessage(data: string): MermaidMessage | null {+ let message: unknown;+ try {+ message = JSON.parse(data);+ } catch {+ return null;+ }+ if (typeof message !== "object" || message === null) return null;+ const { type, width, height } = message as Record<string, unknown>;+ if (type === "error") return { type };+ if (+ type === "size" &&+ typeof width === "number" &&+ typeof height === "number" &&+ width > 0 &&+ height > 0+ ) {+ return { type, width, height };+ }+ return null;+}++export function rememberSize(+ cache: Map<string, DiagramSize>,+ key: string,+ size: DiagramSize,+ limit: number,+): void {+ cache.delete(key);+ cache.set(key, size);+ for (const oldest of cache.keys()) {+ if (cache.size <= limit) break;+ cache.delete(oldest);+ }+}++// Embeds a value in an inline script without letting it close the tag.+function scriptLiteral(value: unknown): string {+ return JSON.stringify(value).replace(/</g, "\\u003c");+}++// Keeps a script source from ending its tag early. The escape only appears in+// strings, regexes and comments, where it still reads as "<".+export function inlineScriptSource(source: string): string {+ return source.replace(/<(?=!--|\/?script)/gi, "\\x3C");+}++// The bundle loads in its own script tag before the render script. Injected+// JavaScript runs inside a function on Android, where the bundle's top-level+// `var` does not become a global, and it may run after the page scripts. The+// policy blocks every network fetch, so the SVG can only use what it carries.+export function mermaidHtml(+ code: string,+ dark: boolean,+ bundle: string,+): string {+ const config = {+ startOnLoad: false,+ theme: dark ? "dark" : "default",+ securityLevel: "strict",+ suppressErrorRendering: true,+ fontFamily: "-apple-system, system-ui, sans-serif",+ };+ return `<!DOCTYPE html>+<html>+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:">+<style>html, body { margin: 0; padding: 0; background: transparent; overflow: hidden; } svg { display: block; }</style>+</head>+<body>+<div id="root"></div>+<script>${bundle}</script>+<script>+(function () {+ function post(message) {+ window.ReactNativeWebView.postMessage(JSON.stringify(message));+ }+ function fail() {+ post({ type: "error" });+ }+ if (!window.mermaid) return fail();+ try {+ mermaid.initialize(${scriptLiteral(config)});+ mermaid.render("diagram", ${scriptLiteral(code)}).then(function (result) {+ var root = document.getElementById("root");+ root.innerHTML = result.svg;+ var svg = root.querySelector("svg");+ if (!svg) return fail();+ var box = svg.viewBox && svg.viewBox.baseVal;+ var rect = svg.getBoundingClientRect();+ var width = Math.ceil(box && box.width ? box.width : rect.width);+ var height = Math.ceil(box && box.height ? box.height : rect.height);+ svg.style.maxWidth = "none";+ svg.setAttribute("width", String(width));+ svg.setAttribute("height", String(height));+ post({ type: "size", width: width, height: height });+ }, fail);+ } catch (error) {+ fail();+ }+})();+</script>+</body>+</html>`;+}diff --git a/products/desktop/pnpm-lock.yaml b/products/desktop/pnpm-lock.yamlindex 700d26c5f5d6..f22df152ce1c 100644--- a/products/desktop/pnpm-lock.yaml+++ b/products/desktop/pnpm-lock.yaml@@ -731,6 +731,9 @@ importers:marked:specifier: 16.4.2version: 16.4.2+ mermaid:+ specifier: ^11.17.0+ version: 11.17.0react:specifier: 19.2.6version: 19.2.6