GeezerVison is showing github.com — feat(mobile): Mermaid and math fences render like they do on web (#32… · adampeterhiggins/t3code@d0807b7
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/mobile/package.json +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 118 | 118 | "expo-video": "58.0.11", | 119 | 119 | "expo-web-browser": "~58.0.6", | 120 | 120 | "expo-widgets": "58.0.20", | | 121 | + "pele": "catalog:", | 121 | 122 | "react": "catalog:", | 122 | 123 | "react-dom": "catalog:", | 123 | 124 | "react-native": "0.88.0", | |
Collapse file Copy file name to clipboardExpand all lines: apps/mobile/src/components/ui/AppSymbol.tsx +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -124,6 +124,7 @@ import IconTool from "@tabler/icons-react-native/IconTool"; | 124 | 124 | import IconTrash from "@tabler/icons-react-native/IconTrash"; | 125 | 125 | import IconTypography from "@tabler/icons-react-native/IconTypography"; | 126 | 126 | import IconDownload from "@tabler/icons-react-native/IconDownload"; | | 127 | +import IconSitemap from "@tabler/icons-react-native/IconSitemap"; | 127 | 128 | import IconUpload from "@tabler/icons-react-native/IconUpload"; | 128 | 129 | import IconUserCircle from "@tabler/icons-react-native/IconUserCircle"; | 129 | 130 | import IconUserCheck from "@tabler/icons-react-native/IconUserCheck"; | @@ -248,6 +249,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { | 248 | 249 | "slash.circle": IconBan, | 249 | 250 | "qrcode.viewfinder": IconQrcode, | 250 | 251 | "point.3.connected.trianglepath.dotted": IconNetwork, | | 252 | + flowchart: IconSitemap, | 251 | 253 | "point.topleft.down.curvedto.point.bottomright.up": IconGitMerge, | 252 | 254 | safari: IconExternalLink, | 253 | 255 | "server.rack": IconServer, | |
Collapse file Copy file name to clipboard +37Lines changed: 37 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 Copy file name to clipboard +63Lines changed: 63 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 Copy file name to clipboardExpand all lines: apps/mobile/src/native/EnrichedMarkdownText.tsx +48-10Lines changed: 48 additions & 10 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -11,14 +11,16 @@ import { | 11 | 11 | markdownWithInlineFileLinks, | 12 | 12 | markdownWithTableBreaks, | 13 | 13 | } from "../lib/markdownDocument"; | 14 | | -import { isValidElement, useMemo, useState, type ReactNode } from "react"; | | 14 | +import { isValidElement, useMemo, useState, type ReactElement, type ReactNode } from "react"; | 15 | 15 | import { Platform, Share, StyleSheet, useWindowDimensions, View } from "react-native"; | 16 | 16 | import { | 17 | 17 | EnrichedMarkdownText, | | 18 | + type MarkdownCodeBlock, | 18 | 19 | type MarkdownImageBlock, | 19 | 20 | type MarkdownLinkOccurrence, | 20 | 21 | type MarkdownStyle, | 21 | 22 | } from "react-native-enriched-markdown"; | | 23 | +import { MermaidCodeBlock } from "./MermaidCodeBlock"; | 22 | 24 | import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types"; | 23 | 25 |
| 24 | 26 | import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider"; | @@ -161,6 +163,35 @@ function enrichedStyle( | 161 | 163 | }; | 162 | 164 | } | 163 | 165 |
| | 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 | + | 164 | 195 | export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { | 165 | 196 | const { renderImage, resolveImageSource, fileEmbedLabel } = props; | 166 | 197 | const { themeAppearance, mathRenderingEnabled } = useAppearancePreferences(); | @@ -264,28 +295,35 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { | 264 | 295 | }; | 265 | 296 | }, [props.contextClipboardFragment, props.markdown]); | 266 | 297 | const { fontScale } = useWindowDimensions(); | 267 | | - const markdownStyle = useMemo(() => { | | 298 | + const baseMarkdownStyle = useMemo(() => { | 268 | 299 | const style = enrichedStyle(props.textStyle, themeAppearance === "dark", fontScale); | 269 | 300 | return { | 270 | 301 | ...style, | 271 | 302 | paragraph: props.textAlign | 272 | 303 | ? { ...style.paragraph, textAlign: props.textAlign } | 273 | 304 | : style.paragraph, | 274 | | - linkVariants, | 275 | 305 | }; | 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) => { | 280 | 316 | const element = renderImage({ | 281 | 317 | href: block.url, | 282 | 318 | alt: block.altText || null, | 283 | 319 | title: block.title || null, | 284 | 320 | }); | 285 | 321 | return isValidElement(element) ? element : undefined; | 286 | | - }, | 287 | | - } | 288 | | - : undefined; | | 322 | + } | | 323 | + : undefined, | | 324 | + code: (block: MarkdownCodeBlock) => | | 325 | + codeBlockElement(block, props.textStyle, baseMarkdownStyle, mathRenderingEnabled), | | 326 | + }; | 289 | 327 | const resolveNativeImageSource = useRetryingImageSource(resolveImageSource); | 290 | 328 | const renderMarkdown = (openAndroidMenu?: () => void) => { | 291 | 329 | const onLinkLongPress = | |
|