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

nativeReviewDiffSurface.ts

439 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) => 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 const command: ((payload: string) => Promise<void | boolean>) | undefined = view?.[method];
220 if (!view || !command) {
221 if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
222 attempts += 1;
223 frame = requestAnimationFrame(dispatch);
224 } else {
225 console.error(`[native-review-diff] ${method} unavailable`);
226 onFailure?.();
227 }
228 return;
229 }
230​
231 void Promise.resolve()
232 .then(() => {
233 if (!cancelled) return command.call(view, payload);
234 })
235 .then((accepted) => {
236 if (cancelled) return;
237 // This promise resolves after native decode, reset validation, and merge.
238 if (method === "setTokensPatchJson" && accepted !== true) {
239 throw new Error("Native token patch was not accepted");
240 }
241 onDelivered?.(payload);
242 })
243 .catch((error: unknown) => {
244 if (cancelled) return;
245 if (
246 attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
247 isPendingNativeViewRegistration(error)
248 ) {
249 attempts += 1;
250 frame = requestAnimationFrame(dispatch);
251 return;
252 }
253 console.error(`[native-review-diff] ${method} failed`, error);
254 onFailure?.();
255 });
256 };
257​
258 // Expo registers native tags after Fabric attaches refs; dispatch next frame.
259 frame = requestAnimationFrame(dispatch);
260​
261 return () => {
262 cancelled = true;
263 if (frame !== null) {
264 cancelAnimationFrame(frame);
265 }
266 };
267 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new resetKey redelivers an unchanged payload after the diff surface resets.
268 }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);
270​
271function getExpoViewConfig(moduleName: string) {
272 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
273 moduleName,
274 );
276​
277function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
278 const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);
279 const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);
280 if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);
281 if (failedRowsJson === props.rowsJson) {
282 return createElement(
283 View,
284 {
285 style: [
286 props.style,
287 {
288 flex: 1,
289 justifyContent: "center",
290 paddingTop: props.contentInsetTop,
291 paddingBottom: props.contentInsetBottom,
292 },
293 ],
294 },
295 createElement(EmptyState, {
296 title: "Could not display diff",
297 detail: "Try loading the diff view again.",
298 variant: "plain",
299 actionLabel: "Retry diff",
300 onAction: () => {
301 props.onDebug?.({
302 nativeEvent: { message: "surface-retry" },
303 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
304 setFailedRowsJson(null);
305 },
306 }),
307 );
308 }
309 return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });
311​
312function NativeReviewDiffContent(
313 props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },
314) {
315 const {
316 nativeViewRef,
317 rowsJson,
318 tokensJson,
319 tokensPatchJson,
320 onRowsFailure,
321 onDebug,
322 ...nativeProps
323 } = props;
324 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
325 useNativeReviewDiffPayload(
326 nativeRef,
327 "setRowsJson",
328 rowsJson,
329 props.contentResetKey,
330 onRowsFailure,
331 );
332 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
333 const onDebugRef = useRef(onDebug);
334 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the latest onDebug for callbacks the native diff view fires outside render
335 useEffect(() => {
336 onDebugRef.current = onDebug;
337 }, [onDebug]);
338 const reportedMountRef = useRef(false);
339 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the native surface mount to the debug callback once per mount
340 useEffect(() => {
341 // Effect replay keeps the same native content; only a new mount loses tokens.
342 if (reportedMountRef.current) return;
343 reportedMountRef.current = true;
344 onDebugRef.current?.({
345 nativeEvent: { message: "surface-content-mounted" },
346 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
347 }, []);
348 const reportTokenDelivery = useCallback((json: string, message: string) => {
349 const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };
350 if (patch.chunkIndex === undefined) return;
351 onDebugRef.current?.({
352 nativeEvent: {
353 message,
354 resetKey: patch.resetKey,
355 chunkIndex: patch.chunkIndex,
356 },
357 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
358 }, []);
359 const onTokensDelivered = useCallback(
360 (json: string) => {
361 reportTokenDelivery(json, "tokens-patch-delivered");
362 },
363 [reportTokenDelivery],
364 );
365 const onTokensFailure = useCallback(() => {
366 if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");
367 }, [reportTokenDelivery, tokensPatchJson]);
368 useNativeReviewDiffPayload(
369 nativeRef,
370 "setTokensPatchJson",
371 tokensPatchJson,
372 undefined,
373 onTokensFailure,
374 onTokensDelivered,
375 );
376 useImperativeHandle(
377 nativeViewRef,
378 () => ({
379 scrollToFile: async (fileId, animated = true) => {
380 await nativeRef.current?.scrollToFile(fileId, animated);
381 },
382 scrollToTop: async (animated = true) => {
383 await nativeRef.current?.scrollToTop(animated);
384 },
385 }),
386 [],
387 );
388​
389 const RawNativeView = cachedNativeReviewDiffRawView;
390 if (!RawNativeView) {
391 return null;
392 }
393​
394 /* oxlint-disable react/refs -- The native view receives this ref; only event callbacks access its current value. */
395 return createElement(RawNativeView, {
396 ...nativeProps,
397 refreshEnabled: props.onPullToRefresh !== undefined,
398 onDebug: (event) => {
399 if (event.nativeEvent.message === "rows-decode-failed") {
400 console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);
401 onRowsFailure();
402 }
403 onDebug?.(event);
404 },
405 ref: nativeRef,
406 });
407 /* oxlint-enable react/refs */
409​
410export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
411 if (cachedNativeReviewDiffRawView) {
412 return NativeReviewDiffView;
413 }
414​
415 if (nativeReviewDiffViewResolutionFailed) {
416 return null;
417 }
418​
419 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
420 return null;
421 }
422​
423 try {
424 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
425 NATIVE_REVIEW_DIFF_MODULE_NAME,
426 );
427 } catch (cause) {
428 nativeReviewDiffViewResolutionFailed = true;
429 console.error(
430 new NativeViewResolutionError({
431 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
432 cause,
433 }),
434 );
435 return null;
436 }
437​
438 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;