Open History to see the last commit
1import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
2import { T, useGT } from "gt-react-native";
3import { settlePromise } from "@t3tools/client-runtime/state/runtime";
4import { useAtomValue } from "@effect/atom-react";
5import { AsyncResult } from "effect/reactivity";
6import type { ComponentType } from "react";
7import { useLayoutEffect, useRef, useState } from "react";
8import {
9 Platform,
10 Pressable,
11 ScrollView,
12 Text as NativeText,
13 useWindowDimensions,
14 View,
15} from "react-native";
16import { NativeScrollView } from "../../native/NativeScrollViewMarker";
17import { RefreshControl } from "../../components/ui/RefreshControl";
18import { WebView } from "react-native-webview";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20import { AppText as Text } from "../../components/ui/AppText";
21import { LoadingStrip } from "../../components/ui/LoadingStrip";
22import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
23import {
24 type NativeReviewDiffViewProps,
25 resolveNativeReviewDiffView,
26} from "../diffs/nativeReviewDiffSurface";
27import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
28import { renderVisibleWhitespace } from "../review/reviewDiffRendering";
29import type { HighlightedToken } from "../../lib/highlights";
30import { cn } from "../../lib/cn";
31import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
32import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
33import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
34import { useUniwindTheme } from "../../lib/useUniwindTheme";
35import {
36 buildNativeSourceTokens,
37 NATIVE_SOURCE_CONTENT_WIDTH,
38 nativeSourceRowId,
39} from "./nativeSourceFileAdapter";
40import { SourceText } from "@t3tools/mobile-source-text";
41
42import {
43 boundedSelectableSourceTokens,
44 prepareSourceFileDocument,
45 selectableSourceHtml,
46} from "./source-file-document";
47import { sourceHighlightAtom } from "./sourceHighlightingState";
48
49interface SourceFileSurfaceProps {
50 readonly contents: string;
51 readonly path: string;
52 readonly embedded?: boolean;
53 readonly initialLine?: number | null;
54 readonly headerInsetTop?: number;
55 readonly selectable?: boolean;
56 readonly onLongPressLine?: (line: number) => void;
57 readonly onRefresh?: () => Promise<void> | void;
58}
59
60type SourceHighlightStatus = "highlighting" | "ready" | "error";
61
62const HighlightedSourceLine = function HighlightedSourceLine(props: {
63 readonly codeSurface: ResolvedMobileCodeSurface;
64 readonly index: number;
65 readonly line: string;
66 readonly tokens: ReadonlyArray<HighlightedToken> | null;
67 readonly highlighted: boolean;
68 readonly wordBreak: boolean;
69 readonly onLongPress?: () => void;
70}) {
71 const gt = useGT();
72 const selectable = props.onLongPress === undefined;
73 const row = (
74 <View
75 className={cn("flex-row", props.highlighted && "bg-primary/10")}
76 style={{ minHeight: props.codeSurface.rowHeight }}
77 >
78 <NativeText
79 className="select-none pr-3 text-right font-mono text-foreground-tertiary"
80 style={{
81 width: props.codeSurface.gutterWidth,
82 fontSize: props.codeSurface.lineNumberFontSize,
83 lineHeight: props.codeSurface.rowHeight,
84 }}
85 >
86 {props.index + 1}
87 </NativeText>
88 <NativeText
89 selectable={selectable}
90 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
91 numberOfLines={props.wordBreak ? undefined : 1}
92 className="flex-1 font-mono font-normal text-foreground"
93 style={{
94 fontSize: props.codeSurface.fontSize,
95 lineHeight: props.codeSurface.rowHeight,
96 minWidth: props.wordBreak ? undefined : 320,
97 }}
98 >
99 {props.tokens && props.tokens.length > 0
100 ? (() => {
101 let offset = 0;
102 return props.tokens.map((token) => {
103 const start = offset;
104 offset += token.content.length;
105
106 const fontWeight =
107 token.fontStyle !== null && (token.fontStyle & 2) === 2
108 ? ("700" as const)
109 : ("400" as const);
110 const fontStyle =
111 token.fontStyle !== null && (token.fontStyle & 1) === 1
112 ? ("italic" as const)
113 : ("normal" as const);
114
115 return (
116 <NativeText
117 key={`${start}:${token.content.length}:${token.color ?? ""}`}
118 selectable={selectable}
119 selectionColorClassName={
120 Platform.OS === "android" ? "accent-focus/32" : undefined
121 }
122 style={{
123 color: token.color ?? undefined,
124 fontWeight,
125 fontStyle,
126 }}
127 >
128 {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
129 </NativeText>
130 );
131 });
132 })()
133 : renderVisibleWhitespace(props.line || " ")}
134 </NativeText>
135 </View>
136 );
137 const onLongPress = props.onLongPress;
138 return onLongPress ? (
139 <Pressable
140 onLongPress={onLongPress}
141 accessibilityActions={[{ name: "longpress", label: gt`Select text` }]}
142 onAccessibilityAction={(event) => {
143 if (event.nativeEvent.actionName === "longpress") onLongPress();
144 }}
145 >
146 {row}
147 </Pressable>
148 ) : (
149 row
150 );
151};
152
153function useSourceFileModel(props: SourceFileSurfaceProps) {
154 const { themeAppearance: theme } = useAppearancePreferences();
155 const document = prepareSourceFileDocument(props.contents);
156 const { contents: normalizedContents, lines, rowsJson } = document;
157 const targetIndex =
158 props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
159 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
160 : null;
161 const highlightAtom = sourceHighlightAtom({
162 path: props.path,
163 contents: normalizedContents,
164 theme,
165 });
166 const highlightResult = useAtomValue(highlightAtom);
167 const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
168 const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
169 ? "error"
170 : AsyncResult.isSuccess(highlightResult)
171 ? "ready"
172 : "highlighting";
173
174 return { normalizedContents, lines, rowsJson, status, targetIndex, theme, tokens };
175}
176
177function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
178 if (props.status === "highlighting") {
179 return <LoadingStrip />;
180 }
181 if (props.status === "error") {
182 return (
183 <View className="border-b border-border bg-card px-4 py-2">
184 <Text className="text-2xs font-t3-medium uppercase text-foreground-muted">
185 <T>Plain text</T>
186 </Text>
187 </View>
188 );
189 }
190 return null;
191}
192
193function useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {
194 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
195 const handlePullToRefresh = async () => {
196 if (!onRefresh) {
197 return;
198 }
199 setIsPullRefreshing(true);
200 // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
201 await settlePromise(async () => onRefresh());
202 setIsPullRefreshing(false);
203 };
204 return { isPullRefreshing, handlePullToRefresh };
205}
206
207function NativeSourceFileSurface(
208 props: SourceFileSurfaceProps & {
209 readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
210 },
211) {
212 const { NativeView, onLongPressLine, onRefresh } = props;
213 const insets = useSafeAreaInsets();
214 const columnMetrics = useNativeColumnLayoutMetrics();
215 const safeArea = columnMetrics?.safeArea ?? insets;
216 const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
217 const { themeAppearance, themeId } = useAppearancePreferences();
218 const appTheme = useUniwindTheme();
219 const { width: viewportWidth } = useWindowDimensions();
220 const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
221 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(onRefresh);
222 const tokensJson = JSON.stringify(buildNativeSourceTokens(tokens));
223 const selectedRowIdsJson = JSON.stringify(
224 targetIndex === null ? [] : [nativeSourceRowId(targetIndex)],
225 );
226 const themeJson = JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme));
227 const styleJson = JSON.stringify(nativeSourceStyle);
228 const contentWidth = codeWordBreak
229 ? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
230 : NATIVE_SOURCE_CONTENT_WIDTH;
231
232 return (
233 <View className="relative flex-1 bg-sheet">
234 <SourceHighlightStatusView status={status} />
235 <NativeView
236 collapsable={false}
237 testID="source-native-code-view"
238 style={{ flex: 1 }}
239 appearanceScheme={themeAppearance}
240 contentResetKey={props.path}
241 contentWidth={contentWidth}
242 contentInsetTop={props.embedded ? 0 : (props.headerInsetTop ?? safeArea.top)}
243 contentInsetBottom={props.embedded ? 0 : safeArea.bottom + 8}
244 initialRowIndex={targetIndex ?? -1}
245 rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
246 rowsJson={rowsJson}
247 selectedRowIdsJson={selectedRowIdsJson}
248 styleJson={styleJson}
249 themeJson={themeJson}
250 tokensJson={tokensJson}
251 onPressLine={({ nativeEvent }) => {
252 if (nativeEvent.gesture === "longPress" && nativeEvent.newLineNumber !== undefined) {
253 onLongPressLine?.(nativeEvent.newLineNumber);
254 }
255 }}
256 {...(onRefresh
257 ? {
258 refreshing: isPullRefreshing,
259 onPullToRefresh: () => void handlePullToRefresh(),
260 }
261 : {})}
262 />
263 </View>
264 );
265}
266
267function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
268 const usesAutomaticInsets = Platform.OS === "ios" && !props.embedded;
269 const appTheme = useUniwindTheme();
270 const foreground = appTheme["--color-foreground"];
271 const { codeSurface, codeWordBreak, monoFontFamily } = useAppearanceCodeSurface();
272 const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
273 const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;
274 const listRef = useRef<LegendListRef>(null);
275 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
276 const refreshControl = props.onRefresh ? (
277 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
278 ) : undefined;
279
280 const usesLineList = !props.selectable;
281 // Android lays out a full selectable TextView on the UI thread, which can stall large files.
282 const usesWebSelection = props.selectable === true && Platform.OS === "android";
283 const usesTextSelection = props.selectable === true && !usesWebSelection;
284
285 // Layout effect so a pending jump is cancelled in the commit that swaps the file.
286 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the list to the target line and cancels a pending jump when the file changes
287 useLayoutEffect(() => {
288 if (targetIndex === null || !usesLineList) {
289 return;
290 }
291 const frame = requestAnimationFrame(() => {
292 void listRef.current?.scrollToIndex({
293 index: targetIndex,
294 animated: false,
295 viewPosition: 0.3,
296 });
297 });
298 return () => cancelAnimationFrame(frame);
299 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index, or leaving selection mode, scrolls the remounted list to it.
300 }, [props.path, targetIndex, usesLineList]);
301
302 const { onLongPressLine } = props;
303 const renderLine = ({ item, index }: { item: string; index: number }) => (
304 <HighlightedSourceLine
305 codeSurface={codeSurface}
306 index={index}
307 line={item}
308 tokens={tokens?.[index] ?? null}
309 highlighted={index === targetIndex}
310 wordBreak={codeWordBreak}
311 onLongPress={onLongPressLine ? () => onLongPressLine(index + 1) : undefined}
312 />
313 );
314
315 // One native text view permits document-wide selection; virtualized rows cannot.
316 const selectableBlock = usesTextSelection ? (
317 <SourceText
318 selectable
319 style={{
320 color: foreground,
321 fontFamily: monoFontFamily,
322 fontSize: codeSurface.fontSize,
323 lineHeight: codeSurface.rowHeight,
324 }}
325 >
326 {selectableTokens
327 ? lines.map(
328 (
329 line,
330 index,
331 ) => /* oxlint-disable react/no-array-index-key -- Source lines and highlight tokens are stateless positions within the loaded file. */ {
332 const lineTokens = selectableTokens[index] ?? null;
333 const body =
334 lineTokens && lineTokens.length > 0
335 ? lineTokens.map((token, tokenIndex) => (
336 <SourceText
337 key={`${index}:${tokenIndex}`}
338 style={{
339 color: token.color ?? foreground,
340 fontWeight:
341 token.fontStyle !== null && (token.fontStyle & 2) === 2
342 ? "700"
343 : "400",
344 fontStyle:
345 token.fontStyle !== null && (token.fontStyle & 1) === 1
346 ? "italic"
347 : "normal",
348 }}
349 >
350 {token.content}
351 </SourceText>
352 ))
353 : line;
354 return (
355 <SourceText key={index}>
356 {body}
357 {index < lines.length - 1 ? "\n" : ""}
358 </SourceText>
359 );
360 } /* oxlint-enable react/no-array-index-key */,
361 )
362 : normalizedContents}
363 </SourceText>
364 ) : null;
365
366 const webSelection = usesWebSelection ? (
367 <WebView
368 source={{
369 html: selectableSourceHtml(normalizedContents, {
370 foreground,
371 selection: appTheme["--color-focus"],
372 fontSize: codeSurface.fontSize,
373 rowHeight: codeSurface.rowHeight,
374 wordBreak: codeWordBreak,
375 }),
376 }}
377 originWhitelist={["*"]}
378 // Android pastes copied HTML as styled text with collapsed whitespace, so copy plain text.
379 // Wrapped text reflows once the WebView reaches its final width, so scroll again then.
380 injectedJavaScript={`addEventListener("copy",(event)=>{event.clipboardData.setData("text/plain",getSelection().toString());event.preventDefault();});${
381 targetIndex === null
382 ? ""
383 : `const line=document.getElementById("L${targetIndex + 1}");const reveal=()=>line?.scrollIntoView({block:"center"});reveal();addEventListener("resize",reveal,{once:true});`
384 }true;`}
385 domStorageEnabled={false}
386 cacheEnabled={false}
387 setSupportMultipleWindows={false}
388 onShouldStartLoadWithRequest={(request) => request.url === "about:blank"}
389 style={{ flex: 1, backgroundColor: "transparent" }}
390 />
391 ) : null;
392
393 const list = (
394 <LegendList
395 ref={listRef}
396 // An embedded viewer sits inside another screen's scroll surface.
397 renderScrollComponent={props.embedded ? undefined : NativeScrollView}
398 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
399 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
400 refreshControl={refreshControl}
401 data={lines}
402 keyExtractor={(_line, index) => String(index)}
403 extraData={{ tokens, targetIndex, codeSurface, codeWordBreak, onLongPressLine }}
404 estimatedItemSize={codeSurface.rowHeight}
405 getFixedItemSize={codeWordBreak ? undefined : () => codeSurface.rowHeight}
406 drawDistance={codeSurface.rowHeight * 40}
407 recycleItems
408 contentContainerStyle={{
409 minWidth: codeWordBreak ? undefined : "100%",
410 paddingBottom: codeSurface.rowHeight,
411 paddingTop: 8,
412 }}
413 renderItem={renderLine}
414 />
415 );
416
417 const padded = (
418 <ScrollView
419 refreshControl={refreshControl}
420 className="flex-1"
421 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
422 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
423 contentContainerStyle={{
424 paddingBottom: codeSurface.rowHeight,
425 paddingHorizontal: 12,
426 paddingTop: 8,
427 }}
428 >
429 {selectableBlock}
430 </ScrollView>
431 );
432
433 return (
434 <View className="relative flex-1 bg-sheet">
435 {usesWebSelection ? null : <SourceHighlightStatusView status={status} />}
436 {usesLineList ? (
437 codeWordBreak ? (
438 list
439 ) : (
440 <ScrollView horizontal bounces={false} className="flex-1">
441 {list}
442 </ScrollView>
443 )
444 ) : usesWebSelection ? (
445 webSelection
446 ) : codeWordBreak ? (
447 padded
448 ) : (
449 <ScrollView horizontal bounces={false} className="flex-1">
450 {padded}
451 </ScrollView>
452 )}
453 </View>
454 );
455}
456
457export function SourceFileSurface(props: SourceFileSurfaceProps) {
458 const NativeView = resolveNativeReviewDiffView();
459 const { codeWordBreak } = useAppearanceCodeSurface();
460 const surface =
461 NativeView && !codeWordBreak && !props.selectable ? (
462 <NativeSourceFileSurface {...props} NativeView={NativeView} />
463 ) : (
464 <JavaScriptSourceFileSurface {...props} />
465 );
466 return surface;
467}