Skip to content

Commit 73731a9

Browse files
feat(mobile): Mermaid and math fences render like they do on web
Mobile showed ```mermaid and ```math fences as plain code, while web draws the diagram and the formula. Enriched Markdown's new code block renderers let the mobile app replace those two fences once they close: Mermaid goes through Pele, the renderer web uses, drawn with react-native-svg after its CSS variables are resolved; math goes through the library's own display math. Other code blocks stay native. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 47eea48 commit 73731a9

9 files changed

Lines changed: 372 additions & 9 deletions

File tree

‎apps/mobile/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@
118118
"expo-video": "58.0.11",
119119
"expo-web-browser": "~58.0.6",
120120
"expo-widgets": "58.0.20",
121+
"pele": "catalog:",
121122
"react": "catalog:",
122123
"react-dom": "catalog:",
123124
"react-native": "0.88.0",

‎apps/mobile/src/components/ui/AppSymbol.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ import IconTool from "@tabler/icons-react-native/IconTool";
124124
import IconTrash from "@tabler/icons-react-native/IconTrash";
125125
import IconTypography from "@tabler/icons-react-native/IconTypography";
126126
import IconDownload from "@tabler/icons-react-native/IconDownload";
127+
import IconSitemap from "@tabler/icons-react-native/IconSitemap";
127128
import IconUpload from "@tabler/icons-react-native/IconUpload";
128129
import IconUserCircle from "@tabler/icons-react-native/IconUserCircle";
129130
import IconUserCheck from "@tabler/icons-react-native/IconUserCheck";
@@ -248,6 +249,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
248249
"slash.circle": IconBan,
249250
"qrcode.viewfinder": IconQrcode,
250251
"point.3.connected.trianglepath.dotted": IconNetwork,
252+
flowchart: IconSitemap,
251253
"point.topleft.down.curvedto.point.bottomright.up": IconGitMerge,
252254
safari: IconExternalLink,
253255
"server.rack": IconServer,
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { render } from "pele";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { mermaidSvgForNative } from "./mermaidSvg";
5+
6+
describe("mermaidSvgForNative", () => {
7+
it("turns Pele's CSS variables and styles into attributes react-native-svg draws", () => {
8+
const { svg } = render("flowchart LR\n A[Client] -->|ws| B(Server)", {
9+
links: false,
10+
images: false,
11+
});
12+
13+
const native = mermaidSvgForNative(svg, {
14+
"--pele-fg": "#111111",
15+
"--pele-line": "#222222",
16+
"--pele-font": "Helvetica",
17+
});
18+
19+
expect(native).not.toMatch(/var\(|style=/);
20+
expect(native).toMatch(
21+
/^<svg[^>]* fill="#111111"[^>]* font-family="Helvetica" font-size="16">/,
22+
);
23+
expect(native).toContain('stroke="#222222"');
24+
// Colors the theme leaves out keep Pele's fallback, and the corner radius becomes geometry.
25+
expect(native).toContain('fill="#f3f3f3"');
26+
expect(native).toMatch(/<rect[^>]* rx="4"/);
27+
});
28+
});

‎apps/mobile/src/lib/mermaidSvg.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* react-native-svg applies neither the CSS custom properties Pele colors with
3+
* nor CSS-only geometry such as `rx` in a style, so both become attributes.
4+
* `theme` sets `--pele-*` values; the rest keep Pele's fallbacks.
5+
*/
6+
export function mermaidSvgForNative(svg: string, theme: Readonly<Record<string, string>>): string {
7+
const rootTag = /^<svg\b[^>]*>/.exec(svg)?.[0];
8+
if (!rootTag) return svg;
9+
const declared = styleDeclarations(/\sstyle="([^"]*)"/.exec(rootTag)?.[1] ?? "");
10+
const resolve = (value: string, depth = 0): string =>
11+
depth > 8
12+
? value
13+
: value.replace(
14+
/var\((--[\w-]+)(?:,\s*((?:[^()]|\([^()]*\))*))?\)/g,
15+
(_match, name: string, fallback: string | undefined) =>
16+
resolve(theme[name] ?? declared.get(name) ?? fallback ?? "", depth + 1),
17+
);
18+
19+
const fontSize = /(\d+(?:\.\d+)?)px/.exec(declared.get("font") ?? "")?.[1] ?? "16";
20+
const fontFamily = resolve(declared.get("font-family") ?? "sans-serif").replaceAll('"', "'");
21+
const root = resolve(rootTag.replace(/\sstyle="[^"]*"/, "")).replace(
22+
/>$/,
23+
` font-family="${fontFamily}" font-size="${fontSize}">`,
24+
);
25+
const body = svg
26+
.slice(rootTag.length)
27+
.replace(/\sstyle="([^"]*)"/g, (_match, style: string) =>
28+
[...styleDeclarations(style)]
29+
.map(([name, value]) => ` ${name}="${resolve(value).replace(/^(-?[\d.]+)px$/, "$1")}"`)
30+
.join(""),
31+
);
32+
return root + resolve(body);
33+
}
34+
35+
function styleDeclarations(style: string): Map<string, string> {
36+
const declarations = new Map<string, string>();
37+
for (const declaration of style.split(";")) {
38+
const colon = declaration.indexOf(":");
39+
if (colon > 0) {
40+
declarations.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).trim());
41+
}
42+
}
43+
return declarations;
44+
}

‎apps/mobile/src/native/EnrichedMarkdownText.tsx‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,16 @@ import {
1111
markdownWithInlineFileLinks,
1212
markdownWithTableBreaks,
1313
} from "../lib/markdownDocument";
14-
import { isValidElement, useMemo, useState, type ReactNode } from "react";
14+
import { isValidElement, useMemo, useState, type ReactElement, type ReactNode } from "react";
1515
import { Platform, Share, StyleSheet, useWindowDimensions, View } from "react-native";
1616
import {
1717
EnrichedMarkdownText,
18+
type MarkdownCodeBlock,
1819
type MarkdownImageBlock,
1920
type MarkdownLinkOccurrence,
2021
type MarkdownStyle,
2122
} from "react-native-enriched-markdown";
23+
import { MermaidCodeBlock } from "./MermaidCodeBlock";
2224
import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types";
2325

2426
import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
@@ -161,6 +163,35 @@ function enrichedStyle(
161163
};
162164
}
163165

166+
/** Diagram and math fences, as web draws them. A fence streams as native code until it closes. */
167+
function codeBlockElement(
168+
block: MarkdownCodeBlock,
169+
textStyle: SelectableMarkdownTextProps["textStyle"],
170+
markdownStyle: MarkdownStyle,
171+
mathRenderingEnabled: boolean,
172+
): ReactElement | undefined {
173+
if (!block.isComplete) return undefined;
174+
if (block.language === "mermaid") {
175+
return <MermaidCodeBlock code={block.code} textStyle={textStyle} />;
176+
}
177+
if (block.language === "math" && mathRenderingEnabled) {
178+
return (
179+
<EnrichedMarkdownText
180+
// A blank line would end the paragraph, and so the math, early.
181+
markdown={`$$\n${block.code.replace(/\n\s*\n/g, "\n").trim()}\n$$`}
182+
markdownStyle={markdownStyle}
183+
md4cFlags={{ latexMath: true }}
184+
containerStyle={{ flexShrink: 1, minWidth: 0 }}
185+
flavor="github"
186+
selectable
187+
selectionColor={textStyle.selectionColor}
188+
selectionHandleColor={textStyle.selectionHandleColor}
189+
/>
190+
);
191+
}
192+
return undefined;
193+
}
194+
164195
export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
165196
const { renderImage, resolveImageSource, fileEmbedLabel } = props;
166197
const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences();
@@ -274,18 +305,20 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
274305
linkVariants,
275306
};
276307
}, [props.textStyle, props.textAlign, themeAppearance, fontScale, linkVariants]);
277-
const renderers = renderImage
278-
? {
279-
image: (block: MarkdownImageBlock) => {
308+
const renderers = {
309+
image: renderImage
310+
? (block: MarkdownImageBlock) => {
280311
const element = renderImage({
281312
href: block.url,
282313
alt: block.altText || null,
283314
title: block.title || null,
284315
});
285316
return isValidElement(element) ? element : undefined;
286-
},
287-
}
288-
: undefined;
317+
}
318+
: undefined,
319+
code: (block: MarkdownCodeBlock) =>
320+
codeBlockElement(block, props.textStyle, markdownStyle, mathRenderingEnabled),
321+
};
289322
const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
290323
const renderMarkdown = (openAndroidMenu?: () => void) => {
291324
const onLinkLongPress =

0 commit comments

Comments
 (0)