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

nativeReviewDiffSurface.ts

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