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

nativeReviewDiffSurface.ts

441 lines14.4 KB

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