@devries-cameron20 / t3code-1 / commits / 7e45dcdd61
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): chat code blocks colour diff, kotlin, sql and other languages again (#33680)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 10, 2026 at 22:50 UTC 7e45dcdd61942973b4f026d01ca89b4128d438c8
9 files changed +442 -89
apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx
+19 -20
@@ -6,7 +6,10 @@ import { Pressable, ScrollView, View } from "react-native";
6 import { useKeyboardState } from "react-native-keyboard-controller";
7
8 import { useHardwareBack } from "../../lib/backHandler";
9 -import { deriveMenuHorizontalPlacement } from "../../lib/menu-placement";
9 +import {
10 + deriveMenuHorizontalPlacement,
11 + deriveMenuVerticalPlacement,
12 +} from "../../lib/menu-placement";
13 import { WindowHingeContext } from "../../native/window-hinge-context";
14 import { OverlayPortal } from "./OverlayPortal";
15 import { useAndroidControlSizing } from "./useAndroidControlSizing";
@@ -41,10 +44,9 @@ export type AndroidAnchoredMenuProps = {
44 };
45
46 export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
44 - const { scale, menuWidth: desiredMenuWidth } = useAndroidControlSizing();
47 + const { scale, menuWidth: desiredMenuWidth, menuItemHeight } = useAndroidControlSizing();
48 const [anchor, setAnchor] = useState<AnchorSnapshot | null>(null);
49 const [path, setPath] = useState<readonly MenuAction[]>([]);
47 - const [rootHeight, setRootHeight] = useState<number | null>(null);
50 const [overlay, setOverlay] = useState<OverlayFrame | null>(null);
51 const windowHinge = use(WindowHingeContext);
52 // State, not a ref: `open` reaches render-prop children, and the compiler
@@ -58,7 +60,6 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
60 setAnchor(null);
61 setPath([]);
62 setOverlay(null);
61 - setRootHeight(null);
63 };
64
65 const open = () => {
@@ -70,7 +71,6 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
71 const measureOverlay = () => {
72 overlayRef.current?.measureInWindow((x, y, width, height) => {
73 setOverlay({ x, y, width, height });
73 - setRootHeight(height);
74 });
75 };
76
@@ -110,17 +110,19 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
110 margin: SCREEN_MARGIN,
111 hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width },
112 });
113 - // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable.
114 - const usableBottom =
115 - overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0);
116 - const spaceBelow =
113 + const verticalPlacement =
114 local === null || overlay === null
118 - ? 0
119 - : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN;
120 - const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN;
121 - const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
122 - const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
123 - const placeable = local !== null && rootHeight !== null;
115 + ? null
116 + : deriveMenuVerticalPlacement({
117 + anchorY: local.y,
118 + anchorHeight: local.height,
119 + overlayHeight: overlay.height,
120 + // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable.
121 + keyboardInset: keyboardVisible ? keyboardHeight : 0,
122 + gap: ANCHOR_GAP,
123 + margin: SCREEN_MARGIN,
124 + minHeight: 2 * menuItemHeight + 14 * scale,
125 + });
126
127 const onPressItem = (action: MenuAction) => {
128 if ((action.subactions?.length ?? 0) > 0) {
@@ -167,7 +169,7 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
169 onLayout={measureOverlay}
170 >
171 <Pressable accessible={false} className="absolute inset-0" onPress={close} />
170 - {!placeable || local === null ? null : !anchor.keyboardWasVisible ? (
172 + {local === null ? null : !anchor.keyboardWasVisible ? (
173 <MenuPopup
174 // Compose aligns to the trigger's start if it fits; hinge-safe triggers keep menus on their side.
175 anchor={windowHinge ? { ...local, x: left, width: menuWidth } : local}
@@ -185,12 +187,9 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) {
187 className="absolute overflow-hidden bg-card-alt shadow-md"
188 style={{
189 left,
188 - maxHeight,
190 width: menuWidth,
191 borderRadius: 4 * scale,
191 - ...(opensDown
192 - ? { top: local.y + local.height + ANCHOR_GAP }
193 - : { bottom: (rootHeight ?? 0) - local.y + ANCHOR_GAP }),
192 + ...verticalPlacement,
193 }}
194 >
195 {/* Compose DropdownMenu takes focus; in-window editor menus preserve the keyboard. */}
apps/mobile/src/lib/menu-placement.test.ts new
+27
@@ -0,0 +1,27 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { deriveMenuVerticalPlacement } from "./menu-placement";
4 +
5 +const base = { gap: 6, margin: 12, minHeight: 110 };
6 +
7 +describe("deriveMenuVerticalPlacement", () => {
8 + it.each([
9 + {
10 + name: "anchor taller than the keyboard-free area stays on screen",
11 + input: { anchorY: -100, anchorHeight: 1000, overlayHeight: 800, keyboardInset: 300 },
12 + expected: { maxHeight: 476, top: 12 },
13 + },
14 + {
15 + name: "room below opens down",
16 + input: { anchorY: 100, anchorHeight: 40, overlayHeight: 800, keyboardInset: 300 },
17 + expected: { maxHeight: 342, top: 146 },
18 + },
19 + {
20 + name: "room above opens up",
21 + input: { anchorY: 400, anchorHeight: 40, overlayHeight: 800, keyboardInset: 300 },
22 + expected: { maxHeight: 382, bottom: 406 },
23 + },
24 + ])("$name", ({ input, expected }) => {
25 + expect(deriveMenuVerticalPlacement({ ...base, ...input })).toEqual(expected);
26 + });
27 +});
apps/mobile/src/lib/menu-placement.ts
+28
@@ -23,3 +23,31 @@ export function deriveMenuHorizontalPlacement(input: {
23 const left = Math.min(Math.max(preferredLeft, start + input.margin), end - width - input.margin);
24 return { left, width };
25 }
26 +
27 +/** In the overlay's coordinates; `bottom` is measured up from the overlay's bottom edge. */
28 +export function deriveMenuVerticalPlacement(input: {
29 + readonly anchorY: number;
30 + readonly anchorHeight: number;
31 + readonly overlayHeight: number;
32 + readonly keyboardInset: number;
33 + readonly gap: number;
34 + readonly margin: number;
35 + readonly minHeight: number;
36 +}) {
37 + const usableBottom = input.overlayHeight - input.keyboardInset;
38 + const spaceBelow = usableBottom - (input.anchorY + input.anchorHeight) - input.gap - input.margin;
39 + const spaceAbove = input.anchorY - input.gap - input.margin;
40 + const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove;
41 + const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480);
42 + if (maxHeight < input.minHeight) {
43 + // Neither side fits (e.g. a code block taller than the screen): overlap the anchor instead.
44 + const top = Math.max(
45 + input.margin,
46 + Math.min(input.anchorY, usableBottom - input.margin - input.minHeight),
47 + );
48 + return { maxHeight: Math.min(usableBottom - input.margin - top, 480), top };
49 + }
50 + return opensDown
51 + ? { maxHeight, top: input.anchorY + input.anchorHeight + input.gap }
52 + : { maxHeight, bottom: input.overlayHeight - input.anchorY + input.gap };
53 +}
apps/mobile/src/native/CodeBlockFrame.tsx new
+98
@@ -0,0 +1,98 @@
1 +import type { ReactNode } from "react";
2 +import { Pressable, StyleSheet, Text, View } from "react-native";
3 +
4 +import { SymbolView, type AppSymbolName } from "../components/ui/AppSymbol";
5 +import { themeColorWithAlpha } from "../lib/mobileTheme";
6 +import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
7 +
8 +/**
9 + * The native code block's border and header, for a fence drawn in React once it closes.
10 + * The block slot already applies the code block's outer margins.
11 + */
12 +export function CodeBlockFrame(props: {
13 + readonly label: string;
14 + readonly textStyle: NativeMarkdownTextStyle;
15 + readonly actions: ReactNode;
16 + readonly children: ReactNode;
17 +}) {
18 + const { textStyle } = props;
19 + return (
20 + <View
21 + style={[
22 + styles.block,
23 + {
24 + backgroundColor: textStyle.codeBlockBackgroundColor,
25 + borderColor: textStyle.dividerColor,
26 + },
27 + ]}
28 + >
29 + <View
30 + style={[
31 + styles.header,
32 + { borderBottomColor: themeColorWithAlpha(textStyle.codeColor, 0.2) },
33 + ]}
34 + >
35 + <Text
36 + style={[
37 + styles.label,
38 + {
39 + color: themeColorWithAlpha(textStyle.codeColor, 0.6),
40 + fontSize: textStyle.fontSize * 0.9 * 0.85,
41 + },
42 + ]}
43 + >
44 + {props.label}
45 + </Text>
46 + <View style={styles.actions}>{props.actions}</View>
47 + </View>
48 + {props.children}
49 + </View>
50 + );
51 +}
52 +
53 +/** A header icon; `active` draws it at full strength, as the native wrap toggle when on. */
54 +export function CodeBlockHeaderButton(props: {
55 + readonly icon: AppSymbolName;
56 + readonly label: string;
57 + readonly textStyle: NativeMarkdownTextStyle;
58 + readonly active?: boolean;
59 + readonly onPress: () => void;
60 +}) {
61 + return (
62 + <Pressable
63 + accessibilityRole="button"
64 + accessibilityLabel={props.label}
65 + hitSlop={10}
66 + onPress={props.onPress}
67 + >
68 + <SymbolView
69 + name={props.icon}
70 + size={14}
71 + tintColor={
72 + props.active
73 + ? props.textStyle.codeColor
74 + : themeColorWithAlpha(props.textStyle.codeColor, 0.6)
75 + }
76 + type="monochrome"
77 + />
78 + </Pressable>
79 + );
80 +}
81 +
82 +const styles = StyleSheet.create({
83 + block: {
84 + borderRadius: 8,
85 + borderWidth: StyleSheet.hairlineWidth,
86 + overflow: "hidden",
87 + },
88 + header: {
89 + minHeight: 32,
90 + paddingHorizontal: 12,
91 + flexDirection: "row",
92 + alignItems: "center",
93 + justifyContent: "space-between",
94 + borderBottomWidth: StyleSheet.hairlineWidth,
95 + },
96 + label: { fontWeight: "500" },
97 + actions: { flexDirection: "row", alignItems: "center", gap: 14 },
98 +});
apps/mobile/src/native/EnrichedMarkdownText.tsx
+35 -7
@@ -20,6 +20,8 @@ import {
20 type MarkdownLinkOccurrence,
21 type MarkdownStyle,
22 } from "react-native-enriched-markdown";
23 +import { codeFenceRenderer } from "./codeBlockMarkdown";
24 +import { HighlightedCodeBlock } from "./HighlightedCodeBlock";
25 import { MermaidCodeBlock } from "./MermaidCodeBlock";
26 import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types";
27
@@ -29,6 +31,7 @@ import { useEnrichedLinkVariants } from "./useEnrichedLinkVariants";
31 import { useRetryingImageSource } from "./useRetryingImageSource";
32 import * as Dialog from "../components/ui/Dialog";
33 import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
34 +import type { HighlightScheme } from "../lib/highlights";
35 import {
36 ENRICHED_INLINE_FILE_LINK_REGEX,
37 enrichedTextLinkRegex,
@@ -166,19 +169,25 @@ function enrichedStyle(
169 };
170 }
171
169 -/** Diagram and math fences, as web draws them. A fence streams as native code until it closes. */
172 +/**
173 + * Diagram and math fences, as web draws them, and code enriched-markdown cannot colour.
174 + * Diagrams and math stay native until the library reports them complete; fallback code keeps one block throughout.
175 + */
176 function codeBlockElement(
177 block: MarkdownCodeBlock,
178 textStyle: SelectableMarkdownTextProps["textStyle"],
179 markdownStyle: MarkdownStyle,
180 mathRenderingEnabled: boolean,
181 + scheme: HighlightScheme,
182 ): ReactElement | undefined {
176 - if (!block.isComplete) return undefined;
177 - if (block.language === "mermaid") {
178 - return <MermaidCodeBlock code={block.code} textStyle={textStyle} />;
183 + const renderer = codeFenceRenderer(block.language, mathRenderingEnabled);
184 + if (renderer.kind === "mermaid") {
185 + return block.isComplete ? (
186 + <MermaidCodeBlock code={block.code} textStyle={textStyle} />
187 + ) : undefined;
188 }
180 - if (block.language === "math" && mathRenderingEnabled) {
181 - return (
189 + if (renderer.kind === "math") {
190 + return block.isComplete ? (
191 <EnrichedMarkdownText
192 // A blank line would end the paragraph, and so the math, early.
193 markdown={`$$\n${block.code.replace(/\n\s*\n/g, "\n").trim()}\n$$`}
@@ -190,6 +199,19 @@ function codeBlockElement(
199 selectionColor={textStyle.selectionColor}
200 selectionHandleColor={textStyle.selectionHandleColor}
201 />
202 + ) : undefined;
203 + }
204 + if (renderer.kind === "highlight" && markdownStyle.codeBlock) {
205 + return (
206 + <HighlightedCodeBlock
207 + code={block.code}
208 + fence={block.language}
209 + language={renderer.language}
210 + complete={block.isComplete}
211 + scheme={scheme}
212 + textStyle={textStyle}
213 + codeStyle={markdownStyle.codeBlock}
214 + />
215 );
216 }
217 return undefined;
@@ -347,7 +369,13 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
369 }
370 : undefined,
371 code: (block: MarkdownCodeBlock) =>
350 - codeBlockElement(block, props.textStyle, baseMarkdownStyle, mathRenderingEnabled),
372 + codeBlockElement(
373 + block,
374 + props.textStyle,
375 + baseMarkdownStyle,
376 + mathRenderingEnabled,
377 + themeAppearance,
378 + ),
379 };
380 const resolveNativeImageSource = useRetryingImageSource(resolveImageSource);
381 const renderMarkdown = (openAndroidMenu?: () => void) => {
apps/mobile/src/native/HighlightedCodeBlock.tsx new
+137
@@ -0,0 +1,137 @@
1 +import { useState } from "react";
2 +import { Pressable, ScrollView, Text } from "react-native";
3 +import type { MarkdownStyle } from "react-native-enriched-markdown";
4 +
5 +import { Menu } from "../components/ui/Menu";
6 +import { useMarkdownCodeHighlight } from "../features/threads/markdownCodeHighlightState";
7 +import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
8 +import type { HighlightScheme } from "../lib/highlights";
9 +import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame";
10 +import { fencedCodeMarkdown } from "./codeBlockMarkdown";
11 +import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
12 +
13 +// Header names from enriched-markdown's CodeBlockLanguages.cpp that are not the fence capitalized.
14 +const FENCE_DISPLAY_NAMES: Readonly<Record<string, string>> = {
15 + cc: "C++",
16 + cpp: "C++",
17 + cxx: "C++",
18 + cs: "C#",
19 + csharp: "C#",
20 + graphql: "GraphQL",
21 + objc: "Objective-C",
22 + objectivec: "Objective-C",
23 + php: "PHP",
24 + rb: "Ruby",
25 + scss: "SCSS",
26 + sql: "SQL",
27 + toml: "TOML",
28 + xml: "XML",
29 +};
30 +
31 +// The native block's long-press menu, with its labels and iOS symbols.
32 +const CODE_MENU_ACTIONS = [
33 + { id: "copy-code", title: "Copy", image: "doc.on.doc" },
34 + { id: "copy-markdown", title: "Copy as Markdown", image: "doc.text" },
35 +];
36 +
37 +/** A fence in a language enriched-markdown cannot colour, drawn like its native block. */
38 +export function HighlightedCodeBlock(props: {
39 + readonly code: string;
40 + readonly fence: string;
41 + readonly language: string;
42 + /** False only while the library withholds an unclosed fence (`streamingAnimation`, which T3 never enables, so always true today); highlighting waits for it. */
43 + readonly complete: boolean;
44 + readonly scheme: HighlightScheme;
45 + readonly textStyle: NativeMarkdownTextStyle;
46 + readonly codeStyle: NonNullable<MarkdownStyle["codeBlock"]>;
47 +}) {
48 + const { code, codeStyle, textStyle } = props;
49 + const [wrapped, setWrapped] = useState(false);
50 + const lines = useMarkdownCodeHighlight({
51 + code,
52 + language: props.language,
53 + theme: props.scheme,
54 + enabled: props.complete,
55 + });
56 + const fence = props.fence.toLowerCase();
57 + let offset = 0;
58 + const text = (
59 + // Not selectable: as in the native block, a long-press opens the copy menu instead.
60 + <Text
61 + style={{
62 + color: codeStyle.color,
63 + fontFamily: codeStyle.fontFamily,
64 + fontSize: codeStyle.fontSize,
65 + lineHeight: codeStyle.lineHeight,
66 + }}
67 + >
68 + {lines?.flatMap((line, lineIndex) => {
69 + const separator = lineIndex > 0 ? "\n" : "";
70 + offset += separator.length;
71 + return [
72 + separator,
73 + ...line.map((token) => {
74 + const start = offset;
75 + offset += token.content.length;
76 + return (
77 + <Text key={start} style={token.color ? { color: token.color } : undefined}>
78 + {token.content}
79 + </Text>
80 + );
81 + }),
82 + ];
83 + }) ?? code}
84 + </Text>
85 + );
86 + // Inside the scroller: on iOS an ancestor JS responder disables a ScrollView's panning.
87 + const content = (
88 + <Menu
89 + shouldOpenOnLongPress
90 + actions={CODE_MENU_ACTIONS}
91 + style={{ flexGrow: 1 }}
92 + onPressAction={({ nativeEvent }) => {
93 + copyTextWithHaptic(
94 + nativeEvent.event === "copy-markdown" ? fencedCodeMarkdown(code, props.fence) : code,
95 + );
96 + }}
97 + >
98 + <Pressable style={{ padding: codeStyle.padding }}>{text}</Pressable>
99 + </Menu>
100 + );
101 + return (
102 + <CodeBlockFrame
103 + label={FENCE_DISPLAY_NAMES[fence] ?? fence.charAt(0).toUpperCase() + fence.slice(1)}
104 + textStyle={textStyle}
105 + actions={
106 + <>
107 + <CodeBlockHeaderButton
108 + icon="text.alignleft"
109 + label={wrapped ? "Disable line wrap" : "Wrap lines"}
110 + textStyle={textStyle}
111 + active={wrapped}
112 + onPress={() => setWrapped((value) => !value)}
113 + />
114 + <CodeBlockHeaderButton
115 + icon="doc.on.doc"
116 + label="Copy code"
117 + textStyle={textStyle}
118 + onPress={() => copyTextWithHaptic(code)}
119 + />
120 + </>
121 + }
122 + >
123 + {wrapped ? (
124 + content
125 + ) : (
126 + <ScrollView
127 + horizontal
128 + // As in the thread feed: with the keyboard open, the first long-press reaches the copy menu.
129 + keyboardShouldPersistTaps="always"
130 + contentContainerStyle={{ flexGrow: 1 }}
131 + >
132 + {content}
133 + </ScrollView>
134 + )}
135 + </CodeBlockFrame>
136 + );
137 +}
apps/mobile/src/native/MermaidCodeBlock.tsx
+14 -62
@@ -7,10 +7,10 @@ import { PixelRatio, Platform, Pressable, StyleSheet, Text, View } from "react-n
7 import { parse, Svg, SvgXml } from "react-native-svg";
8
9 import { FilePreviewModal } from "../components/ui/FilePreviewModal";
10 -import { SymbolView, type AppSymbolName } from "../components/ui/AppSymbol";
10 import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
11 import { mermaidSvgForNative, withDiagramBackground } from "../lib/mermaidSvg";
12 import { themeColorWithAlpha } from "../lib/mobileTheme";
13 +import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame";
14 import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
15
16 type Pele = typeof import("pele/lazy");
@@ -191,43 +191,29 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram
191 );
192 };
193
194 - // The header copies the native code block's, which this block replaces once the fence closes.
194 return (
196 - <View
197 - style={[
198 - styles.block,
199 - {
200 - backgroundColor: textStyle.codeBlockBackgroundColor,
201 - borderColor: textStyle.dividerColor,
202 - },
203 - ]}
204 - >
205 - <View
206 - style={[
207 - styles.header,
208 - { borderBottomColor: themeColorWithAlpha(textStyle.codeColor, 0.2) },
209 - ]}
210 - >
211 - <Text style={[styles.language, { color: secondaryColor, fontSize: codeFontSize * 0.85 }]}>
212 - Mermaid
213 - </Text>
214 - <View style={styles.actions}>
195 + <CodeBlockFrame
196 + label="Mermaid"
197 + textStyle={textStyle}
198 + actions={
199 + <>
200 {svg ? (
216 - <HeaderButton
201 + <CodeBlockHeaderButton
202 icon={showCode ? "flowchart" : "chevron.left.forwardslash.chevron.right"}
203 label={showCode ? "Show diagram" : "Show code"}
219 - color={secondaryColor}
204 + textStyle={textStyle}
205 onPress={() => setShowCode((value) => !value)}
206 />
207 ) : null}
223 - <HeaderButton
208 + <CodeBlockHeaderButton
209 icon="doc.on.doc"
210 label="Copy code"
226 - color={secondaryColor}
211 + textStyle={textStyle}
212 onPress={() => copyTextWithHaptic(code)}
213 />
229 - </View>
230 - </View>
214 + </>
215 + }
216 + >
217 <View style={styles.content}>
218 {diagram?.status === "error" ? (
219 <Text style={[styles.error, { color: secondaryColor, fontSize: codeFontSize * 0.85 }]}>
@@ -296,45 +282,11 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram
282 onRequestClose={() => setExpansion(null)}
283 />
284 ) : null}
299 - </View>
300 - );
301 -}
302 -
303 -function HeaderButton(props: {
304 - readonly icon: AppSymbolName;
305 - readonly label: string;
306 - readonly color: string;
307 - readonly onPress: () => void;
308 -}) {
309 - return (
310 - <Pressable
311 - accessibilityRole="button"
312 - accessibilityLabel={props.label}
313 - hitSlop={10}
314 - onPress={props.onPress}
315 - >
316 - <SymbolView name={props.icon} size={14} tintColor={props.color} type="monochrome" />
317 - </Pressable>
285 + </CodeBlockFrame>
286 );
287 }
288
321 -// The block slot already applies the code block's outer margins.
289 const styles = StyleSheet.create({
323 - block: {
324 - borderRadius: 8,
325 - borderWidth: StyleSheet.hairlineWidth,
326 - overflow: "hidden",
327 - },
328 - header: {
329 - height: 32,
330 - paddingHorizontal: 12,
331 - flexDirection: "row",
332 - alignItems: "center",
333 - justifyContent: "space-between",
334 - borderBottomWidth: StyleSheet.hairlineWidth,
335 - },
336 - language: { fontWeight: "500" },
337 - actions: { flexDirection: "row", alignItems: "center", gap: 14 },
290 content: { padding: 12 },
291 diagramRow: { flexDirection: "row", justifyContent: "center" },
292 error: { marginBottom: 8 },
apps/mobile/src/native/codeBlockMarkdown.test.ts new
+30
@@ -0,0 +1,30 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { codeFenceRenderer, fencedCodeMarkdown } from "./codeBlockMarkdown";
4 +
5 +describe("fencedCodeMarkdown", () => {
6 + it.each([
7 + ["a plain fence", "fun main() {}", "kotlin", "```kotlin\nfun main() {}\n```"],
8 + ["a longer fence than the code's", "```\nx\n```", "md", "````md\n```\nx\n```\n````"],
9 + ["no language", "x", "", "```\nx\n```"],
10 + ])("writes %s", (_, code, language, expected) => {
11 + expect(fencedCodeMarkdown(code, language)).toBe(expected);
12 + });
13 +});
14 +
15 +describe("codeFenceRenderer", () => {
16 + it.each([
17 + ["mermaid", true, { kind: "mermaid" }],
18 + ["math", true, { kind: "math" }],
19 + ["math", false, { kind: "native" }],
20 + ["kotlin", true, { kind: "highlight", language: "kotlin" }],
21 + ["KOTLIN", true, { kind: "highlight", language: "kotlin" }],
22 + ["diff", true, { kind: "highlight", language: "diff" }],
23 + ["ts", true, { kind: "native" }],
24 + ["python", true, { kind: "native" }],
25 + ["", true, { kind: "native" }],
26 + ["text", true, { kind: "native" }],
27 + ])("draws %j with math rendering %s as %j", (fence, mathRenderingEnabled, expected) => {
28 + expect(codeFenceRenderer(fence, mathRenderingEnabled)).toEqual(expected);
29 + });
30 +});
apps/mobile/src/native/codeBlockMarkdown.ts new
+54
@@ -0,0 +1,54 @@
1 +import { resolveHighlightLanguage } from "../lib/highlightLanguage";
2 +
3 +// Fences enriched-markdown colours itself: cpp/highlight/CodeBlockLanguages.cpp entries with a default grammar.
4 +const NATIVE_HIGHLIGHT_FENCES = new Set([
5 + "bash",
6 + "c",
7 + "css",
8 + "go",
9 + "golang",
10 + "html",
11 + "java",
12 + "javascript",
13 + "js",
14 + "json",
15 + "jsx",
16 + "markdown",
17 + "md",
18 + "py",
19 + "python",
20 + "rs",
21 + "rust",
22 + "sh",
23 + "shell",
24 + "ts",
25 + "tsx",
26 + "typescript",
27 + "yaml",
28 + "yml",
29 + "zsh",
30 +]);
31 +
32 +/** A fenced code block for `code`, with a backtick fence longer than any backtick run inside it. */
33 +export function fencedCodeMarkdown(code: string, language: string): string {
34 + let longestRun = 0;
35 + for (const [run] of code.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length);
36 + const fence = "`".repeat(Math.max(3, longestRun + 1));
37 + return `${fence}${language}\n${code}\n${fence}`;
38 +}
39 +
40 +type CodeFenceRenderer =
41 + | { readonly kind: "mermaid" }
42 + | { readonly kind: "math" }
43 + | { readonly kind: "highlight"; readonly language: string }
44 + | { readonly kind: "native" };
45 +
46 +/** Mermaid and math fences first: highlights knows `mermaid` too, and would claim it as code. */
47 +export function codeFenceRenderer(fence: string, mathRenderingEnabled: boolean): CodeFenceRenderer {
48 + if (fence === "mermaid") return { kind: "mermaid" };
49 + if (fence === "math" && mathRenderingEnabled) return { kind: "math" };
50 + const name = fence.toLowerCase();
51 + if (NATIVE_HIGHLIGHT_FENCES.has(name)) return { kind: "native" };
52 + const language = resolveHighlightLanguage({ language: name });
53 + return language === "text" ? { kind: "native" } : { kind: "highlight", language };
54 +}