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