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