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

SourceFileSurface.tsx

405 lines14.8 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 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;
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 };
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;
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 };
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 );
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 // 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
253 useLayoutEffect(() => {
254 if (targetIndex === null) {
255 return;
256 }
257 lineScroll.scrollToLine(listRef.current, targetIndex);
258 return lineScroll.cancel;
259 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index scrolls the new file to it.
260 }, [lineScroll, props.path, targetIndex]);
261​
262 const renderLine = ({ item, index }: { item: string; index: number }) => (
263 <HighlightedSourceLine
264 codeSurface={codeSurface}
265 index={index}
266 line={item}
267 tokens={tokens?.[index] ?? null}
268 highlighted={index === targetIndex}
269 wordBreak={codeWordBreak}
270 />
271 );
272​
273 // One native text view permits document-wide selection; virtualized rows cannot.
274 const selectableBlock = props.selectable ? (
275 <SourceText
276 selectable
277 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
278 style={{
279 color: foreground,
280 fontFamily: REVIEW_MONO_FONT_FAMILY,
281 fontSize: codeSurface.fontSize,
282 lineHeight: codeSurface.rowHeight,
283 }}
284 >
285 {selectableTokens
286 ? lines.map(
287 (
288 line,
289 index,
290 ) => /* oxlint-disable react/no-array-index-key -- Source lines and highlight tokens are stateless positions within the loaded file. */ {
291 const lineTokens = selectableTokens[index] ?? null;
292 const body =
293 lineTokens && lineTokens.length > 0
294 ? lineTokens.map((token, tokenIndex) => (
295 <SourceText
296 key={`${index}:${tokenIndex}`}
297 style={{
298 color: token.color ?? foreground,
299 fontWeight:
300 token.fontStyle !== null && (token.fontStyle & 2) === 2
301 ? "700"
302 : "400",
303 fontStyle:
304 token.fontStyle !== null && (token.fontStyle & 1) === 1
305 ? "italic"
306 : "normal",
307 }}
308 >
309 {token.content}
310 </SourceText>
311 ))
312 : line;
313 return (
314 <SourceText key={index}>
315 {body}
316 {index < lines.length - 1 ? "\n" : ""}
317 </SourceText>
318 );
319 } /* oxlint-enable react/no-array-index-key */,
320 )
321 : normalizedContents}
322 </SourceText>
323 ) : null;
324​
325 const list = (
326 <FlatList
327 ref={listRef}
328 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
329 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
330 refreshControl={refreshControl}
331 data={lines}
332 keyExtractor={(_line, index) => String(index)}
333 initialNumToRender={80}
334 maxToRenderPerBatch={80}
335 windowSize={12}
336 {...(codeWordBreak
337 ? {}
338 : {
339 getItemLayout: (_data, index) => ({
340 length: codeSurface.rowHeight,
341 offset: codeSurface.rowHeight * index,
342 index,
343 }),
344 })}
345 contentContainerStyle={{
346 minWidth: codeWordBreak ? undefined : "100%",
347 paddingBottom: codeSurface.rowHeight,
348 paddingTop: 8,
349 }}
350 renderItem={renderLine}
351 onScrollToIndexFailed={lineScroll.onScrollToIndexFailed}
352 onScrollBeginDrag={lineScroll.cancel}
353 />
354 );
355​
356 const usesLineList = !props.selectable;
357 const padded = (
358 <ScrollView
359 refreshControl={refreshControl}
360 className="flex-1"
361 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
362 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
363 contentContainerStyle={{
364 paddingBottom: codeSurface.rowHeight,
365 paddingHorizontal: 12,
366 paddingTop: 8,
367 }}
368 >
369 {selectableBlock}
370 </ScrollView>
371 );
372​
373 return (
374 <View className="relative flex-1 bg-sheet">
375 <SourceHighlightStatusView status={status} />
376 {usesLineList ? (
377 codeWordBreak ? (
378 list
379 ) : (
380 <ScrollView horizontal bounces={false} className="flex-1">
381 {list}
382 </ScrollView>
383 )
384 ) : codeWordBreak ? (
385 padded
386 ) : (
387 <ScrollView horizontal bounces={false} className="flex-1">
388 {padded}
389 </ScrollView>
390 )}
391 </View>
392 );
394​
395export function SourceFileSurface(props: SourceFileSurfaceProps) {
396 const NativeView = resolveNativeReviewDiffView();
397 const { codeWordBreak } = useAppearanceCodeSurface();
398 const surface =
399 NativeView && !codeWordBreak && !props.selectable ? (
400 <NativeSourceFileSurface {...props} NativeView={NativeView} />
401 ) : (
402 <JavaScriptSourceFileSurface {...props} />
403 );
404 return surface;