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

SourceFileSurface.tsx

407 lines14.5 KB

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