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