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

SourceFileSurface.tsx

468 lines17.3 KB

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