Open History to see the last commit
1import { msg, useGT, useMessages } from "gt-react-native";
2import { useState } from "react";
3import { Pressable, ScrollView, Text } from "react-native";
4import type { MarkdownStyle } from "react-native-enriched-markdown";
5
6import { Menu } from "../components/ui/Menu";
7import { CopyTextButton } from "../features/threads/CopyTextButton";
8import { useMarkdownCodeHighlight } from "../features/threads/markdownCodeHighlightState";
9import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
10import { type HighlightScheme, withTokenStarts } from "../lib/highlights";
11import { themeColorWithAlpha } from "../lib/mobileTheme";
12import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame";
13import { fencedCodeMarkdown } from "./codeBlockMarkdown";
14import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types";
15
16// Header names from enriched-markdown's CodeBlockLanguages.cpp that are not the fence capitalized.
17const FENCE_DISPLAY_NAMES: Readonly<Record<string, string>> = {
18 cc: "C++",
19 cpp: "C++",
20 cxx: "C++",
21 cs: "C#",
22 csharp: "C#",
23 graphql: "GraphQL",
24 objc: "Objective-C",
25 objectivec: "Objective-C",
26 php: "PHP",
27 rb: "Ruby",
28 scss: "SCSS",
29 sql: "SQL",
30 toml: "TOML",
31 xml: "XML",
32};
33
34// The native block's long-press menu, with its labels and iOS symbols.
35const CODE_MENU_ACTIONS = [
36 {
37 id: "copy-code",
38 title: msg({ context: "verb, copies the code" })`Copy`,
39 image: "doc.on.doc",
40 },
41 { id: "copy-markdown", title: msg("Copy as Markdown"), image: "doc.text" },
42];
43
44/** A fence in a language enriched-markdown cannot colour, drawn like its native block. */
45export function HighlightedCodeBlock(props: {
46 readonly code: string;
47 readonly fence: string;
48 readonly language: string;
49 /** False only while the library withholds an unclosed fence (`streamingAnimation`, which T3 never enables, so always true today); highlighting waits for it. */
50 readonly complete: boolean;
51 readonly scheme: HighlightScheme;
52 readonly textStyle: NativeMarkdownTextStyle;
53 readonly codeStyle: NonNullable<MarkdownStyle["codeBlock"]>;
54}) {
55 const { code, codeStyle, textStyle } = props;
56 const gt = useGT();
57 const resolve = useMessages();
58 const [wrapped, setWrapped] = useState(false);
59 const lines = useMarkdownCodeHighlight({
60 code,
61 language: props.language,
62 theme: props.scheme,
63 enabled: props.complete,
64 });
65 const fence = props.fence.toLowerCase();
66 const text = (
67 // Not selectable: as in the native block, a long-press opens the copy menu instead.
68 <Text
69 style={{
70 color: codeStyle.color,
71 fontFamily: codeStyle.fontFamily,
72 fontSize: codeStyle.fontSize,
73 lineHeight: codeStyle.lineHeight,
74 }}
75 >
76 {(lines ? withTokenStarts(lines) : undefined)?.flatMap((line, lineIndex) => {
77 const separator = lineIndex > 0 ? "\n" : "";
78 return [
79 separator,
80 ...line.map(({ token, start }) => {
81 return (
82 <Text key={start} style={token.color ? { color: token.color } : undefined}>
83 {token.content}
84 </Text>
85 );
86 }),
87 ];
88 }) ?? code}
89 </Text>
90 );
91 // Inside the scroller: on iOS an ancestor JS responder disables a ScrollView's panning.
92 const content = (
93 <Menu
94 shouldOpenOnLongPress
95 actions={CODE_MENU_ACTIONS.map((action) => ({ ...action, title: resolve(action.title) }))}
96 style={{ flexGrow: 1 }}
97 onPressAction={({ nativeEvent }) => {
98 copyTextWithHaptic(
99 nativeEvent.event === "copy-markdown" ? fencedCodeMarkdown(code, props.fence) : code,
100 );
101 }}
102 >
103 <Pressable style={{ padding: codeStyle.padding }}>{text}</Pressable>
104 </Menu>
105 );
106 return (
107 <CodeBlockFrame
108 label={FENCE_DISPLAY_NAMES[fence] ?? fence.charAt(0).toUpperCase() + fence.slice(1)}
109 textStyle={textStyle}
110 actions={
111 <>
112 <CodeBlockHeaderButton
113 icon="text.alignleft"
114 label={wrapped ? gt`Disable line wrap` : gt`Wrap lines`}
115 textStyle={textStyle}
116 active={wrapped}
117 onPress={() => setWrapped((value) => !value)}
118 />
119 <CopyTextButton
120 accessibilityLabel={gt`Copy code`}
121 text={code}
122 buttonSize={18}
123 iconSize={14}
124 tintColor={themeColorWithAlpha(textStyle.codeColor, 0.6)}
125 copiedTintColor={textStyle.codeColor}
126 />
127 </>
128 }
129 >
130 {wrapped ? (
131 content
132 ) : (
133 <ScrollView
134 horizontal
135 // As in the thread feed: with the keyboard open, the first long-press reaches the copy menu.
136 keyboardShouldPersistTaps="always"
137 contentContainerStyle={{ flexGrow: 1 }}
138 >
139 {content}
140 </ScrollView>
141 )}
142 </CodeBlockFrame>
143 );
144}