Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HighlightedCodeBlock.tsx

140 lines4.6 KB

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