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

SourceFileSurface.tsx

288 lines9.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import { AsyncResult } from "effect/unstable/reactivity";
3import type { ComponentType } from "react";
4import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
5import { FlatList, ScrollView, Text as NativeText, useWindowDimensions, View } from "react-native";
6​
7import { AppText as Text } from "../../components/AppText";
8import { LoadingStrip } from "../../components/LoadingStrip";
9import {
10 type NativeReviewDiffViewProps,
11 resolveNativeReviewDiffView,
12} from "../diffs/nativeReviewDiffSurface";
13import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
14import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering";
15import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
16import { cn } from "../../lib/cn";
17import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
18import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
19import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
20import {
21 buildNativeSourceTokens,
22 NATIVE_SOURCE_CONTENT_WIDTH,
23 nativeSourceRowId,
24} from "./nativeSourceFileAdapter";
25import { prepareSourceFileDocument } from "./source-file-document";
26import { sourceHighlightAtom } from "./sourceHighlightingState";
27​
28interface SourceFileSurfaceProps {
29 readonly contents: string;
30 readonly path: string;
31 readonly initialLine?: number | null;
32 /** Enables native pull-to-refresh on the source surface. */
33 readonly onRefresh?: () => Promise<void> | void;
35​
36type SourceHighlightStatus = "highlighting" | "ready" | "error";
37​
38const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
39 readonly codeSurface: ResolvedMobileCodeSurface;
40 readonly index: number;
41 readonly line: string;
42 readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
43 readonly highlighted: boolean;
44 readonly wordBreak: boolean;
45}) {
46 return (
47 <View
48 className={cn("flex-row", props.highlighted && "bg-primary/10")}
49 style={{ minHeight: props.codeSurface.rowHeight }}
50 >
51 <NativeText
52 className="select-none pr-3 text-right text-foreground-tertiary"
53 style={{
54 width: props.codeSurface.gutterWidth,
55 fontFamily: REVIEW_MONO_FONT_FAMILY,
56 fontSize: props.codeSurface.lineNumberFontSize,
57 lineHeight: props.codeSurface.rowHeight,
58 }}
59 >
60 {props.index + 1}
61 </NativeText>
62 <NativeText
63 selectable
64 numberOfLines={props.wordBreak ? undefined : 1}
65 className="flex-1 font-normal text-foreground"
66 style={{
67 fontFamily: REVIEW_MONO_FONT_FAMILY,
68 fontSize: props.codeSurface.fontSize,
69 lineHeight: props.codeSurface.rowHeight,
70 minWidth: props.wordBreak ? undefined : 320,
71 }}
72 >
73 {props.tokens && props.tokens.length > 0
74 ? (() => {
75 let offset = 0;
76 return props.tokens.map((token) => {
77 const start = offset;
78 offset += token.content.length;
79​
80 const fontWeight =
81 token.fontStyle !== null && (token.fontStyle & 2) === 2
82 ? ("700" as const)
83 : ("400" as const);
84 const fontStyle =
85 token.fontStyle !== null && (token.fontStyle & 1) === 1
86 ? ("italic" as const)
87 : ("normal" as const);
88​
89 return (
90 <NativeText
91 key={`${start}:${token.content.length}:${token.color ?? ""}`}
92 selectable
93 style={{
94 color: token.color ?? undefined,
95 fontFamily: REVIEW_MONO_FONT_FAMILY,
96 fontWeight,
97 fontStyle,
98 }}
99 >
100 {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
101 </NativeText>
102 );
103 });
104 })()
105 : renderVisibleWhitespace(props.line || " ")}
106 </NativeText>
107 </View>
108 );
109});
110​
111function useSourceFileModel(props: SourceFileSurfaceProps) {
112 const { themeAppearance: theme } = useAppearancePreferences();
113 const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]);
114 const { contents: normalizedContents, lines, rowsJson } = document;
115 const targetIndex =
116 props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
117 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
118 : null;
119 const highlightAtom = useMemo(
120 () => sourceHighlightAtom({ path: props.path, contents: normalizedContents, theme }),
121 [normalizedContents, props.path, theme],
122 );
123 const highlightResult = useAtomValue(highlightAtom);
124 const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
125 const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
126 ? "error"
127 : AsyncResult.isSuccess(highlightResult)
128 ? "ready"
129 : "highlighting";
130​
131 return { lines, rowsJson, status, targetIndex, theme, tokens };
133​
134function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
135 if (props.status === "highlighting") {
136 return <LoadingStrip />;
137 }
138 if (props.status === "error") {
139 return (
140 <View className="border-b border-border bg-card px-4 py-2">
141 <Text className="text-2xs font-t3-medium uppercase text-foreground-muted">Plain text</Text>
142 </View>
143 );
144 }
145 return null;
147​
148function NativeSourceFileSurface(
149 props: SourceFileSurfaceProps & {
150 readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
151 },
152) {
153 const { NativeView, onRefresh } = props;
154 const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
155 const { themeAppearance, themeId } = useAppearancePreferences();
156 const { width: viewportWidth } = useWindowDimensions();
157 const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
158 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
159 const handlePullToRefresh = useCallback(async () => {
160 if (!onRefresh) {
161 return;
162 }
163 setIsPullRefreshing(true);
164 try {
165 await onRefresh();
166 } finally {
167 setIsPullRefreshing(false);
168 }
169 }, [onRefresh]);
170 const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
171 const selectedRowIdsJson = useMemo(
172 () => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
173 [targetIndex],
174 );
175 const themeJson = useMemo(
176 () => JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId)),
177 [themeAppearance, themeId],
178 );
179 const styleJson = useMemo(() => JSON.stringify(nativeSourceStyle), [nativeSourceStyle]);
180 const contentWidth = codeWordBreak
181 ? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
182 : NATIVE_SOURCE_CONTENT_WIDTH;
183​
184 return (
185 <View className="relative flex-1 bg-sheet">
186 <SourceHighlightStatusView status={status} />
187 <NativeView
188 collapsable={false}
189 testID="source-native-code-view"
190 style={{ flex: 1 }}
191 appearanceScheme={themeAppearance}
192 contentResetKey={props.path}
193 contentWidth={contentWidth}
194 initialRowIndex={targetIndex ?? -1}
195 rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
196 rowsJson={rowsJson}
197 selectedRowIdsJson={selectedRowIdsJson}
198 styleJson={styleJson}
199 themeJson={themeJson}
200 tokensJson={tokensJson}
201 {...(onRefresh
202 ? {
203 refreshing: isPullRefreshing,
204 onPullToRefresh: () => void handlePullToRefresh(),
205 }
206 : {})}
207 />
208 </View>
209 );
211​
212function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
213 const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
214 const { lines, status, targetIndex, tokens } = useSourceFileModel(props);
215 const listRef = useRef<FlatList<string>>(null);
216​
217 useEffect(() => {
218 if (targetIndex === null) {
219 return;
220 }
221 const frame = requestAnimationFrame(() => {
222 listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
223 });
224 return () => cancelAnimationFrame(frame);
225 }, [props.path, targetIndex]);
226​
227 const renderLine = useCallback(
228 ({ item, index }: { item: string; index: number }) => (
229 <HighlightedSourceLine
230 codeSurface={codeSurface}
231 index={index}
232 line={item}
233 tokens={tokens?.[index] ?? null}
234 highlighted={index === targetIndex}
235 wordBreak={codeWordBreak}
236 />
237 ),
238 [codeSurface, codeWordBreak, targetIndex, tokens],
239 );
240​
241 const list = (
242 <FlatList
243 ref={listRef}
244 data={lines}
245 keyExtractor={(_line, index) => String(index)}
246 initialNumToRender={80}
247 maxToRenderPerBatch={80}
248 windowSize={12}
249 {...(codeWordBreak
250 ? {}
251 : {
252 getItemLayout: (_data, index) => ({
253 length: codeSurface.rowHeight,
254 offset: codeSurface.rowHeight * index,
255 index,
256 }),
257 })}
258 contentContainerStyle={{
259 minWidth: codeWordBreak ? undefined : "100%",
260 paddingBottom: codeSurface.rowHeight,
261 paddingTop: 8,
262 }}
263 renderItem={renderLine}
264 />
265 );
266​
267 return (
268 <View className="relative flex-1 bg-sheet">
269 <SourceHighlightStatusView status={status} />
270 {codeWordBreak ? (
271 list
272 ) : (
273 <ScrollView horizontal bounces={false} className="flex-1">
274 {list}
275 </ScrollView>
276 )}
277 </View>
278 );
280​
281export function SourceFileSurface(props: SourceFileSurfaceProps) {
282 const NativeView = resolveNativeReviewDiffView();
283 return NativeView ? (
284 <NativeSourceFileSurface {...props} NativeView={NativeView} />
285 ) : (
286 <JavaScriptSourceFileSurface {...props} />
287 );