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

SourceFileSurface.tsx

258 lines8.7 KB

1import { useAtomValue } from "@effect/atom-react";
2import { AsyncResult } from "effect/unstable/reactivity";
3import type { ComponentType } from "react";
4import { memo, useCallback, useEffect, useMemo, useRef } from "react";
5import { FlatList, ScrollView, Text as NativeText, useColorScheme, View } from "react-native";
6​
7import { AppText as Text } from "../../components/AppText";
8import { LoadingStrip } from "../../components/LoadingStrip";
9import {
10 type NativeReviewDiffViewProps,
11 resolveNativeReviewDiffView,
12} from "../diffs/nativeReviewDiffSurface";
13import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
14import {
15 REVIEW_DIFF_LINE_HEIGHT,
16 REVIEW_MONO_FONT_FAMILY,
17 renderVisibleWhitespace,
18} from "../review/reviewDiffRendering";
19import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
20import { cn } from "../../lib/cn";
21import { MOBILE_CODE_SURFACE } from "../../lib/typography";
22import {
23 buildNativeSourceRows,
24 buildNativeSourceTokens,
25 NATIVE_SOURCE_CONTENT_WIDTH,
26 NATIVE_SOURCE_ROW_HEIGHT,
27 NATIVE_SOURCE_STYLE,
28 nativeSourceRowId,
29} from "./nativeSourceFileAdapter";
30import { sourceHighlightAtom } from "./sourceHighlightingState";
31​
32const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
33const SOURCE_LINE_NUMBER_WIDTH = MOBILE_CODE_SURFACE.gutterWidth;
34const NATIVE_SOURCE_STYLE_JSON = JSON.stringify(NATIVE_SOURCE_STYLE);
35​
36interface SourceFileSurfaceProps {
37 readonly contents: string;
38 readonly path: string;
39 readonly initialLine?: number | null;
41​
42type SourceHighlightStatus = "highlighting" | "ready" | "error";
43​
44function splitSourceLines(contents: string): ReadonlyArray<string> {
45 return contents.replace(/\r\n?/g, "\n").split("\n");
47​
48const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
49 readonly index: number;
50 readonly line: string;
51 readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
52 readonly highlighted: boolean;
53}) {
54 return (
55 <View
56 className={cn("flex-row", props.highlighted && "bg-primary/10")}
57 style={{ minHeight: SOURCE_LINE_HEIGHT }}
58 >
59 <NativeText
60 className="select-none pr-3 text-right text-foreground-tertiary"
61 style={{
62 width: SOURCE_LINE_NUMBER_WIDTH,
63 fontFamily: REVIEW_MONO_FONT_FAMILY,
64 fontSize: MOBILE_CODE_SURFACE.lineNumberFontSize,
65 lineHeight: MOBILE_CODE_SURFACE.rowHeight,
66 }}
67 >
68 {props.index + 1}
69 </NativeText>
70 <NativeText
71 selectable
72 numberOfLines={1}
73 className="font-normal text-foreground"
74 style={{
75 fontFamily: REVIEW_MONO_FONT_FAMILY,
76 fontSize: MOBILE_CODE_SURFACE.fontSize,
77 lineHeight: MOBILE_CODE_SURFACE.rowHeight,
78 minWidth: 320,
79 }}
80 >
81 {props.tokens && props.tokens.length > 0
82 ? (() => {
83 let offset = 0;
84 return props.tokens.map((token) => {
85 const start = offset;
86 offset += token.content.length;
87​
88 const fontWeight =
89 token.fontStyle !== null && (token.fontStyle & 2) === 2
90 ? ("700" as const)
91 : ("400" as const);
92 const fontStyle =
93 token.fontStyle !== null && (token.fontStyle & 1) === 1
94 ? ("italic" as const)
95 : ("normal" as const);
96​
97 return (
98 <NativeText
99 key={`${start}:${token.content.length}:${token.color ?? ""}`}
100 selectable
101 style={{
102 color: token.color ?? undefined,
103 fontFamily: REVIEW_MONO_FONT_FAMILY,
104 fontWeight,
105 fontStyle,
106 }}
107 >
108 {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
109 </NativeText>
110 );
111 });
112 })()
113 : renderVisibleWhitespace(props.line || " ")}
114 </NativeText>
115 </View>
116 );
117});
118​
119function useSourceFileModel(props: SourceFileSurfaceProps) {
120 const colorScheme = useColorScheme();
121 const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
122 const normalizedContents = useMemo(
123 () => props.contents.replace(/\r\n?/g, "\n"),
124 [props.contents],
125 );
126 const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
127 const targetIndex =
128 props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
129 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
130 : null;
131 const highlightAtom = useMemo(
132 () => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
133 [normalizedContents, props.path, theme],
134 );
135 const highlightResult = useAtomValue(highlightAtom);
136 const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
137 const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
138 ? "error"
139 : AsyncResult.isSuccess(highlightResult)
140 ? "ready"
141 : "highlighting";
142​
143 return { lines, status, targetIndex, theme, tokens };
145​
146function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
147 if (props.status === "highlighting") {
148 return <LoadingStrip />;
149 }
150 if (props.status === "error") {
151 return (
152 <View className="border-b border-border bg-card px-4 py-2">
153 <Text className="text-2xs font-t3-medium uppercase text-foreground-muted">Plain text</Text>
154 </View>
155 );
156 }
157 return null;
159​
160function NativeSourceFileSurface(
161 props: SourceFileSurfaceProps & {
162 readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
163 },
164) {
165 const { NativeView } = props;
166 const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
167 const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
168 const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
169 const selectedRowIdsJson = useMemo(
170 () => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
171 [targetIndex],
172 );
173 const themeJson = useMemo(() => JSON.stringify(createNativeReviewDiffTheme(theme)), [theme]);
174​
175 return (
176 <View className="relative flex-1 bg-card">
177 <SourceHighlightStatusView status={status} />
178 <NativeView
179 key={props.path}
180 collapsable={false}
181 testID="source-native-code-view"
182 style={{ flex: 1 }}
183 appearanceScheme={theme}
184 contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
185 initialRowIndex={targetIndex ?? -1}
186 rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
187 rowsJson={rowsJson}
188 selectedRowIdsJson={selectedRowIdsJson}
189 styleJson={NATIVE_SOURCE_STYLE_JSON}
190 themeJson={themeJson}
191 tokensJson={tokensJson}
192 />
193 </View>
194 );
196​
197function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
198 const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
199 const listRef = useRef<FlatList<string>>(null);
200​
201 useEffect(() => {
202 if (targetIndex === null) {
203 return;
204 }
205 const frame = requestAnimationFrame(() => {
206 listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
207 });
208 return () => cancelAnimationFrame(frame);
209 }, [props.path, targetIndex]);
210​
211 const renderLine = useCallback(
212 ({ item, index }: { item: string; index: number }) => (
213 <HighlightedSourceLine
214 index={index}
215 line={item}
216 tokens={tokens?.[index] ?? null}
217 highlighted={index === targetIndex}
218 />
219 ),
220 [targetIndex, tokens],
221 );
222​
223 return (
224 <View className="relative flex-1 bg-card">
225 <SourceHighlightStatusView status={status} />
226 <ScrollView horizontal bounces={false} className="flex-1">
227 <FlatList
228 ref={listRef}
229 data={lines}
230 keyExtractor={(_line, index) => String(index)}
231 initialNumToRender={80}
232 maxToRenderPerBatch={80}
233 windowSize={12}
234 getItemLayout={(_data, index) => ({
235 length: SOURCE_LINE_HEIGHT,
236 offset: SOURCE_LINE_HEIGHT * index,
237 index,
238 })}
239 contentContainerStyle={{
240 minWidth: "100%",
241 paddingBottom: REVIEW_DIFF_LINE_HEIGHT,
242 paddingTop: 8,
243 }}
244 renderItem={renderLine}
245 />
246 </ScrollView>
247 </View>
248 );
250​
251export function SourceFileSurface(props: SourceFileSurfaceProps) {
252 const NativeView = resolveNativeReviewDiffView();
253 return NativeView ? (
254 <NativeSourceFileSurface {...props} NativeView={NativeView} />
255 ) : (
256 <JavaScriptSourceFileSurface {...props} />
257 );