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

main
ts 454 lines 15 KB
Raw
1 import {
2 createElement,
3 useCallback,
4 useEffect,
5 useImperativeHandle,
6 useRef,
7 useState,
8 type ComponentType,
9 type Ref,
10 } from "react";
11 import { View, type NativeSyntheticEvent, type ViewProps } from "react-native";
12 import { requireNativeView } from "expo";
13 import { msg, useMessages } from "gt-react-native";
14
15 import { EmptyState } from "../../components/ui/EmptyState";
16 import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
17
18 const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
19 const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60;
20
21 interface ExpoGlobalWithViewConfig {
22 readonly expo?: {
23 getViewConfig?: (moduleName: string, viewName?: string) => unknown;
24 };
25 }
26
27 export interface NativeReviewDiffRow {
28 readonly kind: "file" | "hunk" | "line" | "notice" | "comment";
29 readonly id: string;
30 readonly fileId?: string;
31 readonly filePath?: string;
32 readonly previousPath?: string | null;
33 readonly changeType?:
34 | "modified"
35 | "new"
36 | "deleted"
37 | "renamed"
38 | "rename-pure"
39 | "rename-changed";
40 readonly additions?: number;
41 readonly deletions?: number;
42 readonly text?: string;
43 readonly content?: string;
44 readonly change?: "context" | "add" | "delete";
45 readonly oldLineNumber?: number | null;
46 readonly newLineNumber?: number | null;
47 readonly wordDiffRanges?: ReadonlyArray<NativeReviewDiffWordDiffRange>;
48 readonly commentText?: string;
49 readonly commentRangeLabel?: string;
50 readonly commentSectionTitle?: string;
51 /** A notice drawn in the warning colors. */
52 readonly tone?: "warning";
53 /** A notice that reports taps through `onPressNotice`. */
54 readonly actionable?: boolean;
55 /** Where a cut line's note starts in `content`. */
56 readonly noteStart?: number;
57 }
58
59 export interface NativeReviewDiffWordDiffRange {
60 readonly start: number;
61 readonly end: number;
62 }
63
64 export interface NativeReviewDiffToken {
65 readonly content: string;
66 readonly color: string | null;
67 readonly fontStyle: number | null;
68 }
69
70 export interface NativeReviewDiffTheme {
71 readonly background: string;
72 readonly text: string;
73 readonly mutedText: string;
74 readonly headerBackground: string;
75 readonly border: string;
76 readonly hunkBackground: string;
77 readonly hunkText: string;
78 readonly addBackground: string;
79 readonly deleteBackground: string;
80 readonly addBar: string;
81 readonly deleteBar: string;
82 readonly addText: string;
83 readonly deleteText: string;
84 readonly warningText: string;
85 readonly warningBackground: string;
86 }
87
88 export interface NativeReviewDiffStyle {
89 readonly rowHeight?: number;
90 readonly contentWidth?: number;
91 readonly changeBarWidth?: number;
92 readonly gutterWidth?: number;
93 readonly codePadding?: number;
94 readonly textVerticalInset?: number;
95 readonly fileHeaderHeight?: number;
96 readonly fileHeaderHorizontalMargin?: number;
97 readonly fileHeaderVerticalMargin?: number;
98 readonly fileHeaderCornerRadius?: number;
99 readonly fileHeaderHorizontalPadding?: number;
100 readonly fileHeaderPathRightPadding?: number;
101 readonly fileHeaderCountColumnWidth?: number;
102 readonly fileHeaderCountGap?: number;
103 readonly codeFontSize?: number;
104 readonly codeFontWeight?: string;
105 readonly lineNumberFontSize?: number;
106 readonly lineNumberFontWeight?: string;
107 readonly hunkFontSize?: number;
108 readonly hunkFontWeight?: string;
109 readonly fileHeaderFontSize?: number;
110 readonly fileHeaderFontWeight?: string;
111 readonly fileHeaderMetaFontSize?: number;
112 readonly fileHeaderMetaFontWeight?: string;
113 readonly fileHeaderSubtextFontSize?: number;
114 readonly fileHeaderSubtextFontWeight?: string;
115 readonly fileHeaderStatusFontSize?: number;
116 readonly fileHeaderStatusFontWeight?: string;
117 readonly emptyStateFontSize?: number;
118 readonly emptyStateFontWeight?: string;
119 }
120
121 export interface NativeReviewDiffViewProps extends ViewProps {
122 readonly contentInsetTop?: number;
123 readonly contentInsetBottom?: number;
124 readonly rowsJson: string;
125 readonly tokensJson?: string;
126 readonly tokensPatchJson?: string;
127 readonly tokensResetKey?: string;
128 readonly contentResetKey?: string;
129 readonly collapsedFileIdsJson?: string;
130 readonly viewedFileIdsJson?: string;
131 readonly selectedRowIdsJson?: string;
132 readonly collapsedCommentIdsJson?: string;
133 readonly appearanceScheme: "light" | "dark";
134 readonly themeJson: string;
135 readonly styleJson?: string;
136 readonly rowHeight: number;
137 /** Android ignores this and measures the widest row. */
138 readonly contentWidth: number;
139 readonly initialRowIndex?: number;
140 readonly initialFileId?: string;
141 readonly scrollEnabled?: boolean;
142 readonly bounces?: boolean;
143 readonly refreshing?: boolean;
144 readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
145 readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
146 readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
147 readonly onVisibleFileChange?: (
148 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
149 ) => void;
150 readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
151 readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
152 readonly onPressLine?: (
153 event: NativeSyntheticEvent<{
154 readonly rowId?: string;
155 readonly fileId?: string;
156 readonly gesture?: "tap" | "longPress";
157 readonly oldLineNumber?: number;
158 readonly newLineNumber?: number;
159 readonly change?: "context" | "add" | "delete";
160 }>,
161 ) => void;
162 readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
163 readonly onPressNotice?: (
164 event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>,
165 ) => void;
166 }
167
168 export interface NativeReviewDiffViewHandle {
169 readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
170 readonly scrollToTop: (animated?: boolean) => Promise<void>;
171 }
172
173 export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
174 return payload.message === "draw-metrics" || payload.message === "visible-range";
175 }
176
177 interface NativeReviewDiffViewRef {
178 readonly setRowsJson: (rowsJson: string, contentResetKey: string) => Promise<void>;
179 readonly setTokensJson: (tokensJson: string) => Promise<void>;
180 readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<boolean>;
181 readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
182 readonly scrollToTop: (animated: boolean) => Promise<void>;
183 }
184
185 type NativeReviewDiffRawViewProps = Omit<
186 NativeReviewDiffViewProps,
187 "nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
188 > & {
189 readonly refreshEnabled: boolean;
190 readonly ref?: Ref<NativeReviewDiffViewRef>;
191 };
192
193 let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
194 let nativeReviewDiffViewResolutionFailed = false;
195
196 type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
197
198 export function isPendingNativeViewRegistration(error: unknown): boolean {
199 if (!(error instanceof Error)) return false;
200 return (
201 error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
202 (error.message.includes("Unable to find the class") &&
203 error.message.includes("T3ReviewDiffView view with tag"))
204 );
205 }
206
207 function useNativeReviewDiffPayload(
208 nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
209 method: NativeReviewDiffPayloadMethod,
210 payload: string | undefined,
211 resetKey?: string,
212 onFailure?: () => void,
213 onDelivered?: (payload: string) => void,
214 ) {
215 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sends the payload to the native diff view's imperative method, retrying per frame until it mounts
216 useEffect(() => {
217 if (payload === undefined) {
218 return;
219 }
220
221 let cancelled = false;
222 let frame: number | null = null;
223 let attempts = 0;
224
225 const dispatch = () => {
226 if (cancelled) {
227 return;
228 }
229
230 const view = nativeRef.current;
231 if (!view?.[method]) {
232 if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
233 attempts += 1;
234 frame = requestAnimationFrame(dispatch);
235 } else {
236 console.error(`[native-review-diff] ${method} unavailable`);
237 onFailure?.();
238 }
239 return;
240 }
241
242 void Promise.resolve()
243 .then((): Promise<void | boolean> | undefined => {
244 if (cancelled) return;
245 // Fabric can apply the contentResetKey prop after this call, so rows carry the key.
246 return method === "setRowsJson"
247 ? view.setRowsJson(payload, resetKey ?? "")
248 : view[method](payload);
249 })
250 .then((accepted) => {
251 if (cancelled) return;
252 // This promise resolves after native decode, reset validation, and merge.
253 if (method === "setTokensPatchJson" && accepted !== true) {
254 throw new Error("Native token patch was not accepted");
255 }
256 onDelivered?.(payload);
257 })
258 .catch((error: unknown) => {
259 if (cancelled) return;
260 if (
261 attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
262 isPendingNativeViewRegistration(error)
263 ) {
264 attempts += 1;
265 frame = requestAnimationFrame(dispatch);
266 return;
267 }
268 console.error(`[native-review-diff] ${method} failed`, error);
269 onFailure?.();
270 });
271 };
272
273 // Expo registers native tags after Fabric attaches refs; dispatch next frame.
274 frame = requestAnimationFrame(dispatch);
275
276 return () => {
277 cancelled = true;
278 if (frame !== null) {
279 cancelAnimationFrame(frame);
280 }
281 };
282 }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);
283 }
284
285 function getExpoViewConfig(moduleName: string) {
286 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
287 moduleName,
288 );
289 }
290
291 function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
292 const messages = useMessages();
293 const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);
294 const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);
295 if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);
296 if (failedRowsJson === props.rowsJson) {
297 return createElement(
298 View,
299 {
300 style: [
301 props.style,
302 {
303 flex: 1,
304 justifyContent: "center",
305 paddingTop: props.contentInsetTop,
306 paddingBottom: props.contentInsetBottom,
307 },
308 ],
309 },
310 createElement(EmptyState, {
311 title: messages(msg("Could not display diff")),
312 detail: messages(msg("Try loading the diff view again.")),
313 variant: "plain",
314 actionLabel: messages(msg("Retry diff")),
315 onAction: () => {
316 props.onDebug?.({
317 nativeEvent: { message: "surface-retry" },
318 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
319 setFailedRowsJson(null);
320 },
321 }),
322 );
323 }
324 return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });
325 }
326
327 function NativeReviewDiffContent(
328 props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },
329 ) {
330 const {
331 nativeViewRef,
332 rowsJson,
333 tokensJson,
334 tokensPatchJson,
335 onRowsFailure,
336 onDebug,
337 ...nativeProps
338 } = props;
339 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
340 useNativeReviewDiffPayload(
341 nativeRef,
342 "setRowsJson",
343 rowsJson,
344 props.contentResetKey,
345 onRowsFailure,
346 );
347 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
348 const onDebugRef = useRef(onDebug);
349 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the latest onDebug for callbacks the native diff view fires outside render
350 useEffect(() => {
351 onDebugRef.current = onDebug;
352 }, [onDebug]);
353 const reportedMountRef = useRef(false);
354 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the native surface mount to the debug callback once per mount
355 useEffect(() => {
356 // Effect replay keeps the same native content; only a new mount loses tokens.
357 if (reportedMountRef.current) return;
358 reportedMountRef.current = true;
359 onDebugRef.current?.({
360 nativeEvent: { message: "surface-content-mounted" },
361 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
362 }, []);
363 const reportTokenDelivery = useCallback((json: string, message: string) => {
364 const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };
365 if (patch.chunkIndex === undefined) return;
366 onDebugRef.current?.({
367 nativeEvent: {
368 message,
369 resetKey: patch.resetKey,
370 chunkIndex: patch.chunkIndex,
371 },
372 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
373 }, []);
374 const onTokensDelivered = useCallback(
375 (json: string) => {
376 reportTokenDelivery(json, "tokens-patch-delivered");
377 },
378 [reportTokenDelivery],
379 );
380 const onTokensFailure = useCallback(() => {
381 if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");
382 }, [reportTokenDelivery, tokensPatchJson]);
383 useNativeReviewDiffPayload(
384 nativeRef,
385 "setTokensPatchJson",
386 tokensPatchJson,
387 undefined,
388 onTokensFailure,
389 onTokensDelivered,
390 );
391 useImperativeHandle(
392 nativeViewRef,
393 () => ({
394 scrollToFile: async (fileId, animated = true) => {
395 await nativeRef.current?.scrollToFile(fileId, animated);
396 },
397 scrollToTop: async (animated = true) => {
398 await nativeRef.current?.scrollToTop(animated);
399 },
400 }),
401 [],
402 );
403
404 const RawNativeView = cachedNativeReviewDiffRawView;
405 if (!RawNativeView) {
406 return null;
407 }
408
409 /* oxlint-disable react/refs -- The native view receives this ref; only event callbacks access its current value. */
410 return createElement(RawNativeView, {
411 ...nativeProps,
412 refreshEnabled: props.onPullToRefresh !== undefined,
413 onDebug: (event) => {
414 if (event.nativeEvent.message === "rows-decode-failed") {
415 console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);
416 onRowsFailure();
417 }
418 onDebug?.(event);
419 },
420 ref: nativeRef,
421 });
422 /* oxlint-enable react/refs */
423 }
424
425 export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
426 if (cachedNativeReviewDiffRawView) {
427 return NativeReviewDiffView;
428 }
429
430 if (nativeReviewDiffViewResolutionFailed) {
431 return null;
432 }
433
434 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
435 return null;
436 }
437
438 try {
439 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
440 NATIVE_REVIEW_DIFF_MODULE_NAME,
441 );
442 } catch (cause) {
443 nativeReviewDiffViewResolutionFailed = true;
444 console.error(
445 new NativeViewResolutionError({
446 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
447 cause,
448 }),
449 );
450 return null;
451 }
452
453 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
454 }