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

SourceFileSurface.tsx

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