Open History to see the last commit
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 { useEffect, 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";
40
41interface SourceFileSurfaceProps {
42 readonly contents: string;
43 readonly path: string;
44 readonly embedded?: boolean;
45 readonly initialLine?: number | null;
46 readonly headerInsetTop?: number;
47 readonly selectable?: boolean;
48 readonly onRefresh?: () => Promise<void> | void;
49}
50
51type SourceHighlightStatus = "highlighting" | "ready" | "error";
52
53const HighlightedSourceLine = function HighlightedSourceLine(props: {
54 readonly codeSurface: ResolvedMobileCodeSurface;
55 readonly index: number;
56 readonly line: string;
57 readonly tokens: ReadonlyArray<HighlightedToken> | null;
58 readonly highlighted: boolean;
59 readonly wordBreak: boolean;
60}) {
61 return (
62 <View
63 className={cn("flex-row", props.highlighted && "bg-primary/10")}
64 style={{ minHeight: props.codeSurface.rowHeight }}
65 >
66 <NativeText
67 className="select-none pr-3 text-right text-foreground-tertiary"
68 style={{
69 width: props.codeSurface.gutterWidth,
70 fontFamily: REVIEW_MONO_FONT_FAMILY,
71 fontSize: props.codeSurface.lineNumberFontSize,
72 lineHeight: props.codeSurface.rowHeight,
73 }}
74 >
75 {props.index + 1}
76 </NativeText>
77 <NativeText
78 selectable
79 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
80 numberOfLines={props.wordBreak ? undefined : 1}
81 className="flex-1 font-normal text-foreground"
82 style={{
83 fontFamily: REVIEW_MONO_FONT_FAMILY,
84 fontSize: props.codeSurface.fontSize,
85 lineHeight: props.codeSurface.rowHeight,
86 minWidth: props.wordBreak ? undefined : 320,
87 }}
88 >
89 {props.tokens && props.tokens.length > 0
90 ? (() => {
91 let offset = 0;
92 return props.tokens.map((token) => {
93 const start = offset;
94 offset += token.content.length;
95
96 const fontWeight =
97 token.fontStyle !== null && (token.fontStyle & 2) === 2
98 ? ("700" as const)
99 : ("400" as const);
100 const fontStyle =
101 token.fontStyle !== null && (token.fontStyle & 1) === 1
102 ? ("italic" as const)
103 : ("normal" as const);
104
105 return (
106 <NativeText
107 key={`${start}:${token.content.length}:${token.color ?? ""}`}
108 selectable
109 selectionColorClassName={
110 Platform.OS === "android" ? "accent-focus/32" : undefined
111 }
112 style={{
113 color: token.color ?? undefined,
114 fontFamily: REVIEW_MONO_FONT_FAMILY,
115 fontWeight,
116 fontStyle,
117 }}
118 >
119 {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
120 </NativeText>
121 );
122 });
123 })()
124 : renderVisibleWhitespace(props.line || " ")}
125 </NativeText>
126 </View>
127 );
128};
129
130function useSourceFileModel(props: SourceFileSurfaceProps) {
131 const { themeAppearance: theme } = useAppearancePreferences();
132 const document = prepareSourceFileDocument(props.contents);
133 const { contents: normalizedContents, lines, rowsJson } = document;
134 const targetIndex =
135 props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
136 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
137 : null;
138 const highlightAtom = sourceHighlightAtom({
139 path: props.path,
140 contents: normalizedContents,
141 theme,
142 });
143 const highlightResult = useAtomValue(highlightAtom);
144 const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
145 const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
146 ? "error"
147 : AsyncResult.isSuccess(highlightResult)
148 ? "ready"
149 : "highlighting";
150
151 return { normalizedContents, lines, rowsJson, status, targetIndex, theme, tokens };
152}
153
154function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
155 if (props.status === "highlighting") {
156 return <LoadingStrip />;
157 }
158 if (props.status === "error") {
159 return (
160 <View className="border-b border-border bg-card px-4 py-2">
161 <Text className="text-2xs font-t3-medium uppercase text-foreground-muted">Plain text</Text>
162 </View>
163 );
164 }
165 return null;
166}
167
168function useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {
169 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
170 const handlePullToRefresh = async () => {
171 if (!onRefresh) {
172 return;
173 }
174 setIsPullRefreshing(true);
175 // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
176 await settlePromise(async () => onRefresh());
177 setIsPullRefreshing(false);
178 };
179 return { isPullRefreshing, handlePullToRefresh };
180}
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 = JSON.stringify(buildNativeSourceTokens(tokens));
198 const selectedRowIdsJson = JSON.stringify(
199 targetIndex === null ? [] : [nativeSourceRowId(targetIndex)],
200 );
201 const themeJson = JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme));
202 const styleJson = JSON.stringify(nativeSourceStyle);
203 const contentWidth = codeWordBreak
204 ? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
205 : NATIVE_SOURCE_CONTENT_WIDTH;
206
207 return (
208 <View className="relative flex-1 bg-sheet">
209 <SourceHighlightStatusView status={status} />
210 <NativeView
211 collapsable={false}
212 testID="source-native-code-view"
213 style={{ flex: 1 }}
214 appearanceScheme={themeAppearance}
215 contentResetKey={props.path}
216 contentWidth={contentWidth}
217 contentInsetTop={props.embedded ? 0 : (props.headerInsetTop ?? safeArea.top)}
218 contentInsetBottom={props.embedded ? 0 : safeArea.bottom + 8}
219 initialRowIndex={targetIndex ?? -1}
220 rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
221 rowsJson={rowsJson}
222 selectedRowIdsJson={selectedRowIdsJson}
223 styleJson={styleJson}
224 themeJson={themeJson}
225 tokensJson={tokensJson}
226 {...(onRefresh
227 ? {
228 refreshing: isPullRefreshing,
229 onPullToRefresh: () => void handlePullToRefresh(),
230 }
231 : {})}
232 />
233 </View>
234 );
235}
236
237function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
238 const usesAutomaticInsets = Platform.OS === "ios" && !props.embedded;
239 const foreground = useUniwindTheme()["--color-foreground"];
240 const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
241 const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
242 const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;
243 const listRef = useRef<FlatList<string>>(null);
244 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
245 const refreshControl = props.onRefresh ? (
246 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
247 ) : undefined;
248
249 useEffect(() => {
250 if (targetIndex === null) {
251 return;
252 }
253 const frame = requestAnimationFrame(() => {
254 listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
255 });
256 return () => cancelAnimationFrame(frame);
257 }, [props.path, targetIndex]);
258
259 const renderLine = ({ item, index }: { item: string; index: number }) => (
260 <HighlightedSourceLine
261 codeSurface={codeSurface}
262 index={index}
263 line={item}
264 tokens={tokens?.[index] ?? null}
265 highlighted={index === targetIndex}
266 wordBreak={codeWordBreak}
267 />
268 );
269
270 // One native text view permits document-wide selection; virtualized rows cannot.
271 const selectableBlock = props.selectable ? (
272 <SourceText
273 selectable
274 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
275 style={{
276 color: foreground,
277 fontFamily: REVIEW_MONO_FONT_FAMILY,
278 fontSize: codeSurface.fontSize,
279 lineHeight: codeSurface.rowHeight,
280 }}
281 >
282 {selectableTokens
283 ? lines.map((line, index) => {
284 const lineTokens = selectableTokens[index] ?? null;
285 const body =
286 lineTokens && lineTokens.length > 0
287 ? lineTokens.map((token, tokenIndex) => (
288 <SourceText
289 key={`${index}:${tokenIndex}`}
290 style={{
291 color: token.color ?? foreground,
292 fontWeight:
293 token.fontStyle !== null && (token.fontStyle & 2) === 2 ? "700" : "400",
294 fontStyle:
295 token.fontStyle !== null && (token.fontStyle & 1) === 1
296 ? "italic"
297 : "normal",
298 }}
299 >
300 {token.content}
301 </SourceText>
302 ))
303 : line;
304 return (
305 <SourceText key={index}>
306 {body}
307 {index < lines.length - 1 ? "\n" : ""}
308 </SourceText>
309 );
310 })
311 : normalizedContents}
312 </SourceText>
313 ) : null;
314
315 const list = (
316 <FlatList
317 ref={listRef}
318 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
319 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
320 refreshControl={refreshControl}
321 data={lines}
322 keyExtractor={(_line, index) => String(index)}
323 initialNumToRender={80}
324 maxToRenderPerBatch={80}
325 windowSize={12}
326 {...(codeWordBreak
327 ? {}
328 : {
329 getItemLayout: (_data, index) => ({
330 length: codeSurface.rowHeight,
331 offset: codeSurface.rowHeight * index,
332 index,
333 }),
334 })}
335 contentContainerStyle={{
336 minWidth: codeWordBreak ? undefined : "100%",
337 paddingBottom: codeSurface.rowHeight,
338 paddingTop: 8,
339 }}
340 renderItem={renderLine}
341 />
342 );
343
344 const usesLineList = !props.selectable;
345 const padded = (
346 <ScrollView
347 refreshControl={refreshControl}
348 className="flex-1"
349 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
350 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
351 contentContainerStyle={{
352 paddingBottom: codeSurface.rowHeight,
353 paddingHorizontal: 12,
354 paddingTop: 8,
355 }}
356 >
357 {selectableBlock}
358 </ScrollView>
359 );
360
361 return (
362 <View className="relative flex-1 bg-sheet">
363 <SourceHighlightStatusView status={status} />
364 {usesLineList ? (
365 codeWordBreak ? (
366 list
367 ) : (
368 <ScrollView horizontal bounces={false} className="flex-1">
369 {list}
370 </ScrollView>
371 )
372 ) : codeWordBreak ? (
373 padded
374 ) : (
375 <ScrollView horizontal bounces={false} className="flex-1">
376 {padded}
377 </ScrollView>
378 )}
379 </View>
380 );
381}
382
383export function SourceFileSurface(props: SourceFileSurfaceProps) {
384 const NativeView = resolveNativeReviewDiffView();
385 const { codeWordBreak } = useAppearanceCodeSurface();
386 const surface =
387 NativeView && !codeWordBreak && !props.selectable ? (
388 <NativeSourceFileSurface {...props} NativeView={NativeView} />
389 ) : (
390 <JavaScriptSourceFileSurface {...props} />
391 );
392 return surface;
393}