GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(mobile): Mermaid and math fences render like they do on web (#32… · adampeterhiggins/t3code@d0807b7

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps
    • mobile
      • package.json
      • src
        • components/ui
          • AppSymbol.tsx
        • lib
          • mermaidSvg.test.ts
          • mermaidSvg.ts
        • native
          • EnrichedMarkdownText.tsx
          • MermaidCodeBlock.tsx
    • web
      • package.json
  • pnpm-lock.yaml
  • pnpm-workspace.yaml
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/mobile/package.json‎

Copy file name to clipboardExpand all lines: apps/mobile/package.json
+1Lines 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",
Collapse file

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

Copy file name to clipboardExpand all lines: apps/mobile/src/components/ui/AppSymbol.tsx
+2Lines 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,
Collapse file

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

Copy file name to clipboard
+37Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { render } from "pele";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { mermaidSvgForNative, withDiagramBackground } 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(
9+
'flowchart LR\n A[Client] -->|ws| B(Server)\n B --> C["var(--pele-fg)"]',
10+
{
11+
links: false,
12+
images: false,
13+
},
14+
);
15+
16+
const native = mermaidSvgForNative(svg, {
17+
"--pele-fg": "#111111",
18+
"--pele-line": "#222222",
19+
"--pele-font": "Helvetica",
20+
});
21+
22+
expect(native).not.toMatch(/="[^"]*var\(|style=/);
23+
// A label that reads like a variable keeps its text.
24+
expect(native).toContain(">var(--pele-fg)<");
25+
expect(native).toMatch(
26+
/^<svg[^>]* fill="#111111"[^>]* font-family="Helvetica" font-size="16">/,
27+
);
28+
expect(native).toContain('stroke="#222222"');
29+
// Colors the theme leaves out keep Pele's fallback, and the corner radius becomes geometry.
30+
expect(native).toContain('fill="#f3f3f3"');
31+
expect(native).toMatch(/<rect[^>]* rx="4"/);
32+
// The exported image fills the viewBox before anything else draws.
33+
expect(withDiagramBackground(native, "#fafafa")).toMatch(
34+
/^<svg[^>]*><rect x="0" y="0" width="\d+(\.\d+)?" height="\d+(\.\d+)?" fill="#fafafa"\/>/,
35+
);
36+
});
37+
});
Collapse file

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

Copy file name to clipboard
+63Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
// Attribute values only: a label's text can itself read `var(--…)`.
33+
return (
34+
root +
35+
body.replace(
36+
/(\s[\w:-]+=")([^"]*)"/g,
37+
(_match, prefix: string, value: string) => `${prefix}${resolve(value)}"`,
38+
)
39+
);
40+
}
41+
42+
/** Fills the diagram's viewBox, so an exported image reads on any background. */
43+
export function withDiagramBackground(svg: string, color: string): string {
44+
const rootTag = /^<svg\b[^>]*>/.exec(svg)?.[0];
45+
const box = /\sviewBox="([^"]*)"/
46+
.exec(rootTag ?? "")?.[1]
47+
?.trim()
48+
.split(/[\s,]+/);
49+
if (!rootTag || box?.length !== 4) return svg;
50+
const [x, y, width, height] = box;
51+
return `${rootTag}<rect x="${x}" y="${y}" width="${width}" height="${height}" fill="${color}"/>${svg.slice(rootTag.length)}`;
52+
}
53+
54+
function styleDeclarations(style: string): Map<string, string> {
55+
const declarations = new Map<string, string>();
56+
for (const declaration of style.split(";")) {
57+
const colon = declaration.indexOf(":");
58+
if (colon > 0) {
59+
declarations.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).trim());
60+
}
61+
}
62+
return declarations;
63+
}
Collapse file

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

Copy file name to clipboardExpand all lines: apps/mobile/src/native/EnrichedMarkdownText.tsx
+48-10Lines changed: 48 additions & 10 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();
@@ -264,28 +295,35 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
264295
};
265296
}, [props.contextClipboardFragment, props.markdown]);
266297
const { fontScale } = useWindowDimensions();
267-
const markdownStyle = useMemo(() => {
298+
const baseMarkdownStyle = useMemo(() => {
268299
const style = enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale);
269300
return {
270301
...style,
271302
paragraph: props.textAlign
272303
? { ...style.paragraph, textAlign: props.textAlign }
273304
: style.paragraph,
274-
linkVariants,
275305
};
276-
}, [props.textStyle, props.textAlign, themeAppearance, fontScale, linkVariants]);
277-
const renderers = renderImage
278-
? {
279-
image: (block: MarkdownImageBlock) => {
306+
}, [props.textStyle, props.textAlign, themeAppearance, fontScale]);
307+
// Link variants change as a message streams. The code renderer reads only the base style, so
308+
// it stays the same function and the library keeps its rendered blocks.
309+
const markdownStyle = useMemo(
310+
() => ({ ...baseMarkdownStyle, linkVariants }),
311+
[baseMarkdownStyle, linkVariants],
312+
);
313+
const renderers = {
314+
image: renderImage
315+
? (block: MarkdownImageBlock) => {
280316
const element = renderImage({
281317
href: block.url,
282318
alt: block.altText || null,
283319
title: block.title || null,
284320
});
285321
return isValidElement(element) ? element : undefined;
286-
},
287-
}
288-
: undefined;
322+
}
323+
: undefined,
324+
code: (block: MarkdownCodeBlock) =>
325+
codeBlockElement(block, props.textStyle, baseMarkdownStyle, mathRenderingEnabled),
326+
};
289327
const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
290328
const renderMarkdown = (openAndroidMenu?: () => void) => {
291329
const onLinkLongPress =

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.