Open History to see the last commit
1import { settlePromise } from "@t3tools/client-runtime/state/runtime";
2import { useAtomValue } from "@effect/atom-react";
3import { AsyncResult } from "effect/reactivity";
4import type { ComponentType } from "react";
5import { useLayoutEffect, useRef, useState } from "react";
6import {
7 FlatList,
8 Platform,
9 RefreshControl,
10 ScrollView,
11 Text as NativeText,
12 useWindowDimensions,
13 View,
14} from "react-native";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16import { AppText as Text } from "../../components/ui/AppText";
17import { LoadingStrip } from "../../components/ui/LoadingStrip";
18import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
19import {
20 type NativeReviewDiffViewProps,
21 resolveNativeReviewDiffView,
22} from "../diffs/nativeReviewDiffSurface";
23import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
24import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering";
25import type { HighlightedToken } from "../../lib/highlights";
26import { cn } from "../../lib/cn";
27import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
28import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
29import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
30import { useUniwindTheme } from "../../lib/useUniwindTheme";
31import {
32 buildNativeSourceTokens,
33 NATIVE_SOURCE_CONTENT_WIDTH,
34 nativeSourceRowId,
35} from "./nativeSourceFileAdapter";
36import { SourceText } from "@t3tools/mobile-source-text";
37
38import { boundedSelectableSourceTokens, prepareSourceFileDocument } from "./source-file-document";
39import { sourceHighlightAtom } from "./sourceHighlightingState";
40import { createSourceLineScroll } from "./source-file-scroll";
41
42interface SourceFileSurfaceProps {
43 readonly contents: string;
44 readonly path: string;
45 readonly embedded?: boolean;
46 readonly initialLine?: number | null;
47 readonly headerInsetTop?: number;
48 readonly selectable?: boolean;
49 readonly onRefresh?: () => Promise<void> | void;
50}
51
52type SourceHighlightStatus = "highlighting" | "ready" | "error";
53
54const HighlightedSourceLine = function HighlightedSourceLine(props: {
55 readonly codeSurface: ResolvedMobileCodeSurface;
56 readonly index: number;
57 readonly line: string;
58 readonly tokens: ReadonlyArray<HighlightedToken> | null;
59 readonly highlighted: boolean;
60 readonly wordBreak: boolean;
61}) {
62 return (
63 <View
64 className={cn("flex-row", props.highlighted && "bg-primary/10")}
65 style={{ minHeight: props.codeSurface.rowHeight }}
66 >
67 <NativeText
68 className="select-none pr-3 text-right text-foreground-tertiary"
69 style={{
70 width: props.codeSurface.gutterWidth,
71 fontFamily: REVIEW_MONO_FONT_FAMILY,
72 fontSize: props.codeSurface.lineNumberFontSize,
73 lineHeight: props.codeSurface.rowHeight,
74 }}
75 >
76 {props.index + 1}
77 </NativeText>
78 <NativeText
79 selectable
80 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
81 numberOfLines={props.wordBreak ? undefined : 1}
82 className="flex-1 font-normal text-foreground"
83 style={{
84 fontFamily: REVIEW_MONO_FONT_FAMILY,
85 fontSize: props.codeSurface.fontSize,
86 lineHeight: props.codeSurface.rowHeight,
87 minWidth: props.wordBreak ? undefined : 320,
88 }}
89 >
90 {props.tokens && props.tokens.length > 0
91 ? (() => {
92 let offset = 0;
93 return props.tokens.map((token) => {
94 const start = offset;
95 offset += token.content.length;
96
97 const fontWeight =
98 token.fontStyle !== null && (token.fontStyle & 2) === 2
99 ? ("700" as const)
100 : ("400" as const);
101 const fontStyle =
102 token.fontStyle !== null && (token.fontStyle & 1) === 1
103 ? ("italic" as const)
104 : ("normal" as const);
105
106 return (
107 <NativeText
108 key={`${start}:${token.content.length}:${token.color ?? ""}`}
109 selectable
110 selectionColorClassName={
111 Platform.OS === "android" ? "accent-focus/32" : undefined
112 }
113 style={{
114 color: token.color ?? undefined,
115 fontFamily: REVIEW_MONO_FONT_FAMILY,
116 fontWeight,
117 fontStyle,
118 }}
119 >
120 {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
121 </NativeText>
122 );
123 });
124 })()
125 : renderVisibleWhitespace(props.line || " ")}
126 </NativeText>
127 </View>
128 );
129};
130
131function useSourceFileModel(props: SourceFileSurfaceProps) {
132 const { themeAppearance: theme } = useAppearancePreferences();
133 const document = prepareSourceFileDocument(props.contents);
134 const { contents: normalizedContents, lines, rowsJson } = document;
135 const targetIndex =
136 props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
137 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
138 : null;
139 const highlightAtom = sourceHighlightAtom({
140 path: props.path,
141 contents: normalizedContents,
142 theme,
143 });
144 const highlightResult = useAtomValue(highlightAtom);
145 const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
146 const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
147 ? "error"
148 : AsyncResult.isSuccess(highlightResult)
149 ? "ready"
150 : "highlighting";
151
152 return { normalizedContents, lines, rowsJson, status, targetIndex, theme, tokens };
153}
154
155function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
156 if (props.status === "highlighting") {
157 return <LoadingStrip />;
158 }
159 if (props.status === "error") {
160 return (
161 <View className="border-b border-border bg-card px-4 py-2">
162 <Text className="text-2xs font-t3-medium uppercase text-foreground-muted">Plain text</Text>
163 </View>
164 );
165 }
166 return null;
167}
168
169function useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {
170 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
171 const handlePullToRefresh = async () => {
172 if (!onRefresh) {
173 return;
174 }
175 setIsPullRefreshing(true);
176 // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
177 await settlePromise(async () => onRefresh());
178 setIsPullRefreshing(false);
179 };
180 return { isPullRefreshing, handlePullToRefresh };
181}
182
183function NativeSourceFileSurface(
184 props: SourceFileSurfaceProps & {
185 readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
186 },
187) {
188 const { NativeView, onRefresh } = props;
189 const insets = useSafeAreaInsets();
190 const columnMetrics = useNativeColumnLayoutMetrics();
191 const safeArea = columnMetrics?.safeArea ?? insets;
192 const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
193 const { themeAppearance, themeId } = useAppearancePreferences();
194 const appTheme = useUniwindTheme();
195 const { width: viewportWidth } = useWindowDimensions();
196 const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
197 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(onRefresh);
198 const tokensJson = JSON.stringify(buildNativeSourceTokens(tokens));
199 const selectedRowIdsJson = JSON.stringify(
200 targetIndex === null ? [] : [nativeSourceRowId(targetIndex)],
201 );
202 const themeJson = JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme));
203 const styleJson = JSON.stringify(nativeSourceStyle);
204 const contentWidth = codeWordBreak
205 ? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
206 : NATIVE_SOURCE_CONTENT_WIDTH;
207
208 return (
209 <View className="relative flex-1 bg-sheet">
210 <SourceHighlightStatusView status={status} />
211 <NativeView
212 collapsable={false}
213 testID="source-native-code-view"
214 style={{ flex: 1 }}
215 appearanceScheme={themeAppearance}
216 contentResetKey={props.path}
217 contentWidth={contentWidth}
218 contentInsetTop={props.embedded ? 0 : (props.headerInsetTop ?? safeArea.top)}
219 contentInsetBottom={props.embedded ? 0 : safeArea.bottom + 8}
220 initialRowIndex={targetIndex ?? -1}
221 rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
222 rowsJson={rowsJson}
223 selectedRowIdsJson={selectedRowIdsJson}
224 styleJson={styleJson}
225 themeJson={themeJson}
226 tokensJson={tokensJson}
227 {...(onRefresh
228 ? {
229 refreshing: isPullRefreshing,
230 onPullToRefresh: () => void handlePullToRefresh(),
231 }
232 : {})}
233 />
234 </View>
235 );
236}
237
238function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
239 const usesAutomaticInsets = Platform.OS === "ios" && !props.embedded;
240 const foreground = useUniwindTheme()["--color-foreground"];
241 const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
242 const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
243 const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;
244 const listRef = useRef<FlatList<string>>(null);
245 const [lineScroll] = useState(createSourceLineScroll);
246 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
247 const refreshControl = props.onRefresh ? (
248 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
249 ) : undefined;
250
251 // Layout effect so a pending jump is cancelled in the commit that swaps the file.
252 useLayoutEffect(() => {
253 if (targetIndex === null) {
254 return;
255 }
256 lineScroll.scrollToLine(listRef.current, targetIndex);
257 return lineScroll.cancel;
258 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index scrolls the new file to it.
259 }, [lineScroll, props.path, targetIndex]);
260
261 const renderLine = ({ item, index }: { item: string; index: number }) => (
262 <HighlightedSourceLine
263 codeSurface={codeSurface}
264 index={index}
265 line={item}
266 tokens={tokens?.[index] ?? null}
267 highlighted={index === targetIndex}
268 wordBreak={codeWordBreak}
269 />
270 );
271
272 // One native text view permits document-wide selection; virtualized rows cannot.
273 const selectableBlock = props.selectable ? (
274 <SourceText
275 selectable
276 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
277 style={{
278 color: foreground,
279 fontFamily: REVIEW_MONO_FONT_FAMILY,
280 fontSize: codeSurface.fontSize,
281 lineHeight: codeSurface.rowHeight,
282 }}
283 >
284 {selectableTokens
285 ? lines.map(
286 (
287 line,
288 index,
289 ) => /* oxlint-disable react/no-array-index-key -- Source lines and highlight tokens are stateless positions within the loaded file. */ {
290 const lineTokens = selectableTokens[index] ?? null;
291 const body =
292 lineTokens && lineTokens.length > 0
293 ? lineTokens.map((token, tokenIndex) => (
294 <SourceText
295 key={`${index}:${tokenIndex}`}
296 style={{
297 color: token.color ?? foreground,
298 fontWeight:
299 token.fontStyle !== null && (token.fontStyle & 2) === 2
300 ? "700"
301 : "400",
302 fontStyle:
303 token.fontStyle !== null && (token.fontStyle & 1) === 1
304 ? "italic"
305 : "normal",
306 }}
307 >
308 {token.content}
309 </SourceText>
310 ))
311 : line;
312 return (
313 <SourceText key={index}>
314 {body}
315 {index < lines.length - 1 ? "\n" : ""}
316 </SourceText>
317 );
318 } /* oxlint-enable react/no-array-index-key */,
319 )
320 : normalizedContents}
321 </SourceText>
322 ) : null;
323
324 const list = (
325 <FlatList
326 ref={listRef}
327 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
328 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
329 refreshControl={refreshControl}
330 data={lines}
331 keyExtractor={(_line, index) => String(index)}
332 initialNumToRender={80}
333 maxToRenderPerBatch={80}
334 windowSize={12}
335 {...(codeWordBreak
336 ? {}
337 : {
338 getItemLayout: (_data, index) => ({
339 length: codeSurface.rowHeight,
340 offset: codeSurface.rowHeight * index,
341 index,
342 }),
343 })}
344 contentContainerStyle={{
345 minWidth: codeWordBreak ? undefined : "100%",
346 paddingBottom: codeSurface.rowHeight,
347 paddingTop: 8,
348 }}
349 renderItem={renderLine}
350 onScrollToIndexFailed={lineScroll.onScrollToIndexFailed}
351 onScrollBeginDrag={lineScroll.cancel}
352 />
353 );
354
355 const usesLineList = !props.selectable;
356 const padded = (
357 <ScrollView
358 refreshControl={refreshControl}
359 className="flex-1"
360 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
361 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
362 contentContainerStyle={{
363 paddingBottom: codeSurface.rowHeight,
364 paddingHorizontal: 12,
365 paddingTop: 8,
366 }}
367 >
368 {selectableBlock}
369 </ScrollView>
370 );
371
372 return (
373 <View className="relative flex-1 bg-sheet">
374 <SourceHighlightStatusView status={status} />
375 {usesLineList ? (
376 codeWordBreak ? (
377 list
378 ) : (
379 <ScrollView horizontal bounces={false} className="flex-1">
380 {list}
381 </ScrollView>
382 )
383 ) : codeWordBreak ? (
384 padded
385 ) : (
386 <ScrollView horizontal bounces={false} className="flex-1">
387 {padded}
388 </ScrollView>
389 )}
390 </View>
391 );
392}
393
394export function SourceFileSurface(props: SourceFileSurfaceProps) {
395 const NativeView = resolveNativeReviewDiffView();
396 const { codeWordBreak } = useAppearanceCodeSurface();
397 const surface =
398 NativeView && !codeWordBreak && !props.selectable ? (
399 <NativeSourceFileSurface {...props} NativeView={NativeView} />
400 ) : (
401 <JavaScriptSourceFileSurface {...props} />
402 );
403 return surface;
404}