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