The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 470 lines 17.6 KB
Raw
1 import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
2 import { T, useGT } from "gt-react-native";
3 import { settlePromise } from "@t3tools/client-runtime/state/runtime";
4 import { useAtomValue } from "@effect/atom-react";
5 import { AsyncResult } from "effect/reactivity";
6 import type { ComponentType } from "react";
7 import { useLayoutEffect, useRef, useState } from "react";
8 import {
9 Platform,
10 Pressable,
11 ScrollView,
12 Text as NativeText,
13 useWindowDimensions,
14 View,
15 } from "react-native";
16 import { NativeScrollView } from "../../native/NativeScrollViewMarker";
17 import { RefreshControl } from "../../components/ui/RefreshControl";
18 import { WebView } from "react-native-webview";
19 import { useSafeAreaInsets } from "react-native-safe-area-context";
20 import { AppText as Text } from "../../components/ui/AppText";
21 import { LoadingStrip } from "../../components/ui/LoadingStrip";
22 import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
23 import {
24 type NativeReviewDiffViewProps,
25 resolveNativeReviewDiffView,
26 } from "../diffs/nativeReviewDiffSurface";
27 import { createNativeReviewDiffTheme } from "../review/nativeReviewDiffAdapter";
28 import { REVIEW_MONO_FONT_FAMILY, renderVisibleWhitespace } from "../review/reviewDiffRendering";
29 import type { HighlightedToken } from "../../lib/highlights";
30 import { cn } from "../../lib/cn";
31 import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
32 import { useAppearanceCodeSurface } from "../settings/appearance/useAppearanceCodeSurface";
33 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
34 import { useUniwindTheme } from "../../lib/useUniwindTheme";
35 import {
36 buildNativeSourceTokens,
37 NATIVE_SOURCE_CONTENT_WIDTH,
38 nativeSourceRowId,
39 } from "./nativeSourceFileAdapter";
40 import { SourceText } from "@t3tools/mobile-source-text";
41
42 import {
43 boundedSelectableSourceTokens,
44 prepareSourceFileDocument,
45 selectableSourceHtml,
46 } from "./source-file-document";
47 import { sourceHighlightAtom } from "./sourceHighlightingState";
48
49 interface SourceFileSurfaceProps {
50 readonly contents: string;
51 readonly path: string;
52 readonly embedded?: boolean;
53 readonly initialLine?: number | null;
54 readonly headerInsetTop?: number;
55 readonly selectable?: boolean;
56 readonly onLongPressLine?: (line: number) => void;
57 readonly onRefresh?: () => Promise<void> | void;
58 }
59
60 type SourceHighlightStatus = "highlighting" | "ready" | "error";
61
62 const HighlightedSourceLine = function HighlightedSourceLine(props: {
63 readonly codeSurface: ResolvedMobileCodeSurface;
64 readonly index: number;
65 readonly line: string;
66 readonly tokens: ReadonlyArray<HighlightedToken> | null;
67 readonly highlighted: boolean;
68 readonly wordBreak: boolean;
69 readonly onLongPress?: () => void;
70 }) {
71 const gt = useGT();
72 const selectable = props.onLongPress === undefined;
73 const row = (
74 <View
75 className={cn("flex-row", props.highlighted && "bg-primary/10")}
76 style={{ minHeight: props.codeSurface.rowHeight }}
77 >
78 <NativeText
79 className="select-none pr-3 text-right text-foreground-tertiary"
80 style={{
81 width: props.codeSurface.gutterWidth,
82 fontFamily: REVIEW_MONO_FONT_FAMILY,
83 fontSize: props.codeSurface.lineNumberFontSize,
84 lineHeight: props.codeSurface.rowHeight,
85 }}
86 >
87 {props.index + 1}
88 </NativeText>
89 <NativeText
90 selectable={selectable}
91 selectionColorClassName={Platform.OS === "android" ? "accent-focus/32" : undefined}
92 numberOfLines={props.wordBreak ? undefined : 1}
93 className="flex-1 font-normal text-foreground"
94 style={{
95 fontFamily: REVIEW_MONO_FONT_FAMILY,
96 fontSize: props.codeSurface.fontSize,
97 lineHeight: props.codeSurface.rowHeight,
98 minWidth: props.wordBreak ? undefined : 320,
99 }}
100 >
101 {props.tokens && props.tokens.length > 0
102 ? (() => {
103 let offset = 0;
104 return props.tokens.map((token) => {
105 const start = offset;
106 offset += token.content.length;
107
108 const fontWeight =
109 token.fontStyle !== null && (token.fontStyle & 2) === 2
110 ? ("700" as const)
111 : ("400" as const);
112 const fontStyle =
113 token.fontStyle !== null && (token.fontStyle & 1) === 1
114 ? ("italic" as const)
115 : ("normal" as const);
116
117 return (
118 <NativeText
119 key={`${start}:${token.content.length}:${token.color ?? ""}`}
120 selectable={selectable}
121 selectionColorClassName={
122 Platform.OS === "android" ? "accent-focus/32" : undefined
123 }
124 style={{
125 color: token.color ?? undefined,
126 fontFamily: REVIEW_MONO_FONT_FAMILY,
127 fontWeight,
128 fontStyle,
129 }}
130 >
131 {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
132 </NativeText>
133 );
134 });
135 })()
136 : renderVisibleWhitespace(props.line || " ")}
137 </NativeText>
138 </View>
139 );
140 const onLongPress = props.onLongPress;
141 return onLongPress ? (
142 <Pressable
143 onLongPress={onLongPress}
144 accessibilityActions={[{ name: "longpress", label: gt("Select text") }]}
145 onAccessibilityAction={(event) => {
146 if (event.nativeEvent.actionName === "longpress") onLongPress();
147 }}
148 >
149 {row}
150 </Pressable>
151 ) : (
152 row
153 );
154 };
155
156 function useSourceFileModel(props: SourceFileSurfaceProps) {
157 const { themeAppearance: theme } = useAppearancePreferences();
158 const document = prepareSourceFileDocument(props.contents);
159 const { contents: normalizedContents, lines, rowsJson } = document;
160 const targetIndex =
161 props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
162 ? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
163 : null;
164 const highlightAtom = sourceHighlightAtom({
165 path: props.path,
166 contents: normalizedContents,
167 theme,
168 });
169 const highlightResult = useAtomValue(highlightAtom);
170 const tokens = AsyncResult.isSuccess(highlightResult) ? highlightResult.value : null;
171 const status: SourceHighlightStatus = AsyncResult.isFailure(highlightResult)
172 ? "error"
173 : AsyncResult.isSuccess(highlightResult)
174 ? "ready"
175 : "highlighting";
176
177 return { normalizedContents, lines, rowsJson, status, targetIndex, theme, tokens };
178 }
179
180 function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
181 if (props.status === "highlighting") {
182 return <LoadingStrip />;
183 }
184 if (props.status === "error") {
185 return (
186 <View className="border-b border-border bg-card px-4 py-2">
187 <Text className="text-2xs font-t3-medium uppercase text-foreground-muted">
188 <T>Plain text</T>
189 </Text>
190 </View>
191 );
192 }
193 return null;
194 }
195
196 function useSourceFileRefresh(onRefresh: SourceFileSurfaceProps["onRefresh"]) {
197 const [isPullRefreshing, setIsPullRefreshing] = useState(false);
198 const handlePullToRefresh = async () => {
199 if (!onRefresh) {
200 return;
201 }
202 setIsPullRefreshing(true);
203 // RefreshControl only needs the spinner cleared; the caller surfaces its own errors.
204 await settlePromise(async () => onRefresh());
205 setIsPullRefreshing(false);
206 };
207 return { isPullRefreshing, handlePullToRefresh };
208 }
209
210 function NativeSourceFileSurface(
211 props: SourceFileSurfaceProps & {
212 readonly NativeView: ComponentType<NativeReviewDiffViewProps>;
213 },
214 ) {
215 const { NativeView, onLongPressLine, onRefresh } = props;
216 const insets = useSafeAreaInsets();
217 const columnMetrics = useNativeColumnLayoutMetrics();
218 const safeArea = columnMetrics?.safeArea ?? insets;
219 const { codeSurface, codeWordBreak, nativeSourceStyle } = useAppearanceCodeSurface();
220 const { themeAppearance, themeId } = useAppearancePreferences();
221 const appTheme = useUniwindTheme();
222 const { width: viewportWidth } = useWindowDimensions();
223 const { rowsJson, status, targetIndex, tokens } = useSourceFileModel(props);
224 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(onRefresh);
225 const tokensJson = JSON.stringify(buildNativeSourceTokens(tokens));
226 const selectedRowIdsJson = JSON.stringify(
227 targetIndex === null ? [] : [nativeSourceRowId(targetIndex)],
228 );
229 const themeJson = JSON.stringify(createNativeReviewDiffTheme(themeAppearance, themeId, appTheme));
230 const styleJson = JSON.stringify(nativeSourceStyle);
231 const contentWidth = codeWordBreak
232 ? Math.max(240, viewportWidth - codeSurface.gutterWidth - 24)
233 : NATIVE_SOURCE_CONTENT_WIDTH;
234
235 return (
236 <View className="relative flex-1 bg-sheet">
237 <SourceHighlightStatusView status={status} />
238 <NativeView
239 collapsable={false}
240 testID="source-native-code-view"
241 style={{ flex: 1 }}
242 appearanceScheme={themeAppearance}
243 contentResetKey={props.path}
244 contentWidth={contentWidth}
245 contentInsetTop={props.embedded ? 0 : (props.headerInsetTop ?? safeArea.top)}
246 contentInsetBottom={props.embedded ? 0 : safeArea.bottom + 8}
247 initialRowIndex={targetIndex ?? -1}
248 rowHeight={nativeSourceStyle.rowHeight ?? codeSurface.rowHeight}
249 rowsJson={rowsJson}
250 selectedRowIdsJson={selectedRowIdsJson}
251 styleJson={styleJson}
252 themeJson={themeJson}
253 tokensJson={tokensJson}
254 onPressLine={({ nativeEvent }) => {
255 if (nativeEvent.gesture === "longPress" && nativeEvent.newLineNumber !== undefined) {
256 onLongPressLine?.(nativeEvent.newLineNumber);
257 }
258 }}
259 {...(onRefresh
260 ? {
261 refreshing: isPullRefreshing,
262 onPullToRefresh: () => void handlePullToRefresh(),
263 }
264 : {})}
265 />
266 </View>
267 );
268 }
269
270 function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
271 const usesAutomaticInsets = Platform.OS === "ios" && !props.embedded;
272 const appTheme = useUniwindTheme();
273 const foreground = appTheme["--color-foreground"];
274 const { codeSurface, codeWordBreak } = useAppearanceCodeSurface();
275 const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
276 const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;
277 const listRef = useRef<LegendListRef>(null);
278 const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
279 const refreshControl = props.onRefresh ? (
280 <RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
281 ) : undefined;
282
283 const usesLineList = !props.selectable;
284 // Android lays out a full selectable TextView on the UI thread, which can stall large files.
285 const usesWebSelection = props.selectable === true && Platform.OS === "android";
286 const usesTextSelection = props.selectable === true && !usesWebSelection;
287
288 // Layout effect so a pending jump is cancelled in the commit that swaps the file.
289 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the list to the target line and cancels a pending jump when the file changes
290 useLayoutEffect(() => {
291 if (targetIndex === null || !usesLineList) {
292 return;
293 }
294 const frame = requestAnimationFrame(() => {
295 void listRef.current?.scrollToIndex({
296 index: targetIndex,
297 animated: false,
298 viewPosition: 0.3,
299 });
300 });
301 return () => cancelAnimationFrame(frame);
302 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index, or leaving selection mode, scrolls the remounted list to it.
303 }, [props.path, targetIndex, usesLineList]);
304
305 const { onLongPressLine } = props;
306 const renderLine = ({ item, index }: { item: string; index: number }) => (
307 <HighlightedSourceLine
308 codeSurface={codeSurface}
309 index={index}
310 line={item}
311 tokens={tokens?.[index] ?? null}
312 highlighted={index === targetIndex}
313 wordBreak={codeWordBreak}
314 onLongPress={onLongPressLine ? () => onLongPressLine(index + 1) : undefined}
315 />
316 );
317
318 // One native text view permits document-wide selection; virtualized rows cannot.
319 const selectableBlock = usesTextSelection ? (
320 <SourceText
321 selectable
322 style={{
323 color: foreground,
324 fontFamily: REVIEW_MONO_FONT_FAMILY,
325 fontSize: codeSurface.fontSize,
326 lineHeight: codeSurface.rowHeight,
327 }}
328 >
329 {selectableTokens
330 ? lines.map(
331 (
332 line,
333 index,
334 ) => /* oxlint-disable react/no-array-index-key -- Source lines and highlight tokens are stateless positions within the loaded file. */ {
335 const lineTokens = selectableTokens[index] ?? null;
336 const body =
337 lineTokens && lineTokens.length > 0
338 ? lineTokens.map((token, tokenIndex) => (
339 <SourceText
340 key={`${index}:${tokenIndex}`}
341 style={{
342 color: token.color ?? foreground,
343 fontWeight:
344 token.fontStyle !== null && (token.fontStyle & 2) === 2
345 ? "700"
346 : "400",
347 fontStyle:
348 token.fontStyle !== null && (token.fontStyle & 1) === 1
349 ? "italic"
350 : "normal",
351 }}
352 >
353 {token.content}
354 </SourceText>
355 ))
356 : line;
357 return (
358 <SourceText key={index}>
359 {body}
360 {index < lines.length - 1 ? "\n" : ""}
361 </SourceText>
362 );
363 } /* oxlint-enable react/no-array-index-key */,
364 )
365 : normalizedContents}
366 </SourceText>
367 ) : null;
368
369 const webSelection = usesWebSelection ? (
370 <WebView
371 source={{
372 html: selectableSourceHtml(normalizedContents, {
373 foreground,
374 selection: appTheme["--color-focus"],
375 fontSize: codeSurface.fontSize,
376 rowHeight: codeSurface.rowHeight,
377 wordBreak: codeWordBreak,
378 }),
379 }}
380 originWhitelist={["*"]}
381 // Android pastes copied HTML as styled text with collapsed whitespace, so copy plain text.
382 // Wrapped text reflows once the WebView reaches its final width, so scroll again then.
383 injectedJavaScript={`addEventListener("copy",(event)=>{event.clipboardData.setData("text/plain",getSelection().toString());event.preventDefault();});${
384 targetIndex === null
385 ? ""
386 : `const line=document.getElementById("L${targetIndex + 1}");const reveal=()=>line?.scrollIntoView({block:"center"});reveal();addEventListener("resize",reveal,{once:true});`
387 }true;`}
388 domStorageEnabled={false}
389 cacheEnabled={false}
390 setSupportMultipleWindows={false}
391 onShouldStartLoadWithRequest={(request) => request.url === "about:blank"}
392 style={{ flex: 1, backgroundColor: "transparent" }}
393 />
394 ) : null;
395
396 const list = (
397 <LegendList
398 ref={listRef}
399 // An embedded viewer sits inside another screen's scroll surface.
400 renderScrollComponent={props.embedded ? undefined : NativeScrollView}
401 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
402 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
403 refreshControl={refreshControl}
404 data={lines}
405 keyExtractor={(_line, index) => String(index)}
406 extraData={{ tokens, targetIndex, codeSurface, codeWordBreak, onLongPressLine }}
407 estimatedItemSize={codeSurface.rowHeight}
408 getFixedItemSize={codeWordBreak ? undefined : () => codeSurface.rowHeight}
409 drawDistance={codeSurface.rowHeight * 40}
410 recycleItems
411 contentContainerStyle={{
412 minWidth: codeWordBreak ? undefined : "100%",
413 paddingBottom: codeSurface.rowHeight,
414 paddingTop: 8,
415 }}
416 renderItem={renderLine}
417 />
418 );
419
420 const padded = (
421 <ScrollView
422 refreshControl={refreshControl}
423 className="flex-1"
424 contentInsetAdjustmentBehavior={usesAutomaticInsets ? "automatic" : "never"}
425 automaticallyAdjustsScrollIndicatorInsets={usesAutomaticInsets}
426 contentContainerStyle={{
427 paddingBottom: codeSurface.rowHeight,
428 paddingHorizontal: 12,
429 paddingTop: 8,
430 }}
431 >
432 {selectableBlock}
433 </ScrollView>
434 );
435
436 return (
437 <View className="relative flex-1 bg-sheet">
438 {usesWebSelection ? null : <SourceHighlightStatusView status={status} />}
439 {usesLineList ? (
440 codeWordBreak ? (
441 list
442 ) : (
443 <ScrollView horizontal bounces={false} className="flex-1">
444 {list}
445 </ScrollView>
446 )
447 ) : usesWebSelection ? (
448 webSelection
449 ) : codeWordBreak ? (
450 padded
451 ) : (
452 <ScrollView horizontal bounces={false} className="flex-1">
453 {padded}
454 </ScrollView>
455 )}
456 </View>
457 );
458 }
459
460 export function SourceFileSurface(props: SourceFileSurfaceProps) {
461 const NativeView = resolveNativeReviewDiffView();
462 const { codeWordBreak } = useAppearanceCodeSurface();
463 const surface =
464 NativeView && !codeWordBreak && !props.selectable ? (
465 <NativeSourceFileSurface {...props} NativeView={NativeView} />
466 ) : (
467 <JavaScriptSourceFileSurface {...props} />
468 );
469 return surface;
470 }