Open History to see the last commit
1import {
2 createElement,
3 useEffect,
4 useImperativeHandle,
5 useRef,
6 type ComponentType,
7 type Ref,
8} from "react";
9import type { NativeSyntheticEvent, ViewProps } from "react-native";
10import { requireNativeView } from "expo";
11
12import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
13
14const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
15const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60;
16
17interface ExpoGlobalWithViewConfig {
18 readonly expo?: {
19 getViewConfig?: (moduleName: string, viewName?: string) => unknown;
20 };
21}
22
23export interface NativeReviewDiffRow {
24 readonly kind: "file" | "hunk" | "line" | "notice" | "comment";
25 readonly id: string;
26 readonly fileId?: string;
27 readonly filePath?: string;
28 readonly previousPath?: string | null;
29 readonly changeType?:
30 | "modified"
31 | "new"
32 | "deleted"
33 | "renamed"
34 | "rename-pure"
35 | "rename-changed";
36 readonly additions?: number;
37 readonly deletions?: number;
38 readonly text?: string;
39 readonly content?: string;
40 readonly change?: "context" | "add" | "delete";
41 readonly oldLineNumber?: number | null;
42 readonly newLineNumber?: number | null;
43 readonly wordDiffRanges?: ReadonlyArray<NativeReviewDiffWordDiffRange>;
44 readonly commentText?: string;
45 readonly commentRangeLabel?: string;
46 readonly commentSectionTitle?: string;
47}
48
49export interface NativeReviewDiffWordDiffRange {
50 readonly start: number;
51 readonly end: number;
52}
53
54export interface NativeReviewDiffToken {
55 readonly content: string;
56 readonly color: string | null;
57 readonly fontStyle: number | null;
58}
59
60export interface NativeReviewDiffTheme {
61 readonly background: string;
62 readonly text: string;
63 readonly mutedText: string;
64 readonly headerBackground: string;
65 readonly border: string;
66 readonly hunkBackground: string;
67 readonly hunkText: string;
68 readonly addBackground: string;
69 readonly deleteBackground: string;
70 readonly addBar: string;
71 readonly deleteBar: string;
72 readonly addText: string;
73 readonly deleteText: string;
74}
75
76export interface NativeReviewDiffStyle {
77 readonly rowHeight?: number;
78 readonly contentWidth?: number;
79 readonly changeBarWidth?: number;
80 readonly gutterWidth?: number;
81 readonly codePadding?: number;
82 readonly textVerticalInset?: number;
83 readonly fileHeaderHeight?: number;
84 readonly fileHeaderHorizontalMargin?: number;
85 readonly fileHeaderVerticalMargin?: number;
86 readonly fileHeaderCornerRadius?: number;
87 readonly fileHeaderHorizontalPadding?: number;
88 readonly fileHeaderPathRightPadding?: number;
89 readonly fileHeaderCountColumnWidth?: number;
90 readonly fileHeaderCountGap?: number;
91 readonly codeFontSize?: number;
92 readonly codeFontWeight?: string;
93 readonly lineNumberFontSize?: number;
94 readonly lineNumberFontWeight?: string;
95 readonly hunkFontSize?: number;
96 readonly hunkFontWeight?: string;
97 readonly fileHeaderFontSize?: number;
98 readonly fileHeaderFontWeight?: string;
99 readonly fileHeaderMetaFontSize?: number;
100 readonly fileHeaderMetaFontWeight?: string;
101 readonly fileHeaderSubtextFontSize?: number;
102 readonly fileHeaderSubtextFontWeight?: string;
103 readonly fileHeaderStatusFontSize?: number;
104 readonly fileHeaderStatusFontWeight?: string;
105 readonly emptyStateFontSize?: number;
106 readonly emptyStateFontWeight?: string;
107}
108
109export interface NativeReviewDiffViewProps extends ViewProps {
110 readonly rowsJson: string;
111 readonly tokensJson?: string;
112 readonly tokensPatchJson?: string;
113 readonly tokensResetKey?: string;
114 readonly contentResetKey?: string;
115 readonly collapsedFileIdsJson?: string;
116 readonly viewedFileIdsJson?: string;
117 readonly selectedRowIdsJson?: string;
118 readonly collapsedCommentIdsJson?: string;
119 readonly appearanceScheme: "light" | "dark";
120 readonly themeJson: string;
121 readonly styleJson?: string;
122 readonly rowHeight: number;
123 readonly contentWidth: number;
124 readonly contentInsetTop?: number;
125 readonly contentInsetBottom?: number;
126 readonly initialRowIndex?: number;
127 readonly refreshing?: boolean;
128 readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
129 readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
130 readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
131 readonly onVisibleFileChange?: (
132 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
133 ) => void;
134 readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
135 readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
136 readonly onPressLine?: (
137 event: NativeSyntheticEvent<{
138 readonly rowId?: string;
139 readonly fileId?: string;
140 readonly gesture?: "tap" | "longPress";
141 readonly oldLineNumber?: number;
142 readonly newLineNumber?: number;
143 readonly change?: "context" | "add" | "delete";
144 }>,
145 ) => void;
146 readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
147}
148
149export interface NativeReviewDiffViewHandle {
150 readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
151 readonly scrollToTop: (animated?: boolean) => Promise<void>;
152}
153
154export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
155 return payload.message === "draw-metrics" || payload.message === "visible-range";
156}
157
158interface NativeReviewDiffViewRef {
159 readonly setRowsJson: (rowsJson: string) => Promise<void>;
160 readonly setTokensJson: (tokensJson: string) => Promise<void>;
161 readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;
162 readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
163 readonly scrollToTop: (animated: boolean) => Promise<void>;
164}
165
166type NativeReviewDiffRawViewProps = Omit<
167 NativeReviewDiffViewProps,
168 "nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
169> & {
170 readonly ref?: Ref<NativeReviewDiffViewRef>;
171};
172
173let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
174let nativeReviewDiffViewResolutionFailed = false;
175
176type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
177
178export function isPendingNativeViewRegistration(error: unknown): boolean {
179 if (!(error instanceof Error)) return false;
180 return (
181 error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
182 (error.message.includes("Unable to find the class") &&
183 error.message.includes("T3ReviewDiffView view with tag"))
184 );
185}
186
187function useNativeReviewDiffPayload(
188 nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
189 method: NativeReviewDiffPayloadMethod,
190 payload: string | undefined,
191) {
192 useEffect(() => {
193 if (payload === undefined) {
194 return;
195 }
196
197 let cancelled = false;
198 let frame: number | null = null;
199 let attempts = 0;
200
201 const dispatch = () => {
202 if (cancelled) {
203 return;
204 }
205
206 const view = nativeRef.current;
207 const command = view?.[method];
208 if (!view || !command) {
209 if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
210 attempts += 1;
211 frame = requestAnimationFrame(dispatch);
212 }
213 return;
214 }
215
216 void command.call(view, payload).catch((error: unknown) => {
217 if (
218 !cancelled &&
219 attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
220 isPendingNativeViewRegistration(error)
221 ) {
222 attempts += 1;
223 frame = requestAnimationFrame(dispatch);
224 return;
225 }
226 console.error(`[native-review-diff] ${method} failed`, error);
227 });
228 };
229
230 // Fabric attaches the React ref before Expo registers the native tag used by
231 // view functions. Starting on the next frame avoids racing that registration.
232 frame = requestAnimationFrame(dispatch);
233
234 return () => {
235 cancelled = true;
236 if (frame !== null) {
237 cancelAnimationFrame(frame);
238 }
239 };
240 }, [method, nativeRef, payload]);
241}
242
243function getExpoViewConfig(moduleName: string) {
244 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
245 moduleName,
246 );
247}
248
249function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
250 const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;
251 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
252 useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);
253 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
254 useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);
255 useImperativeHandle(
256 nativeViewRef,
257 () => ({
258 scrollToFile: async (fileId, animated = true) => {
259 await nativeRef.current?.scrollToFile(fileId, animated);
260 },
261 scrollToTop: async (animated = true) => {
262 await nativeRef.current?.scrollToTop(animated);
263 },
264 }),
265 [],
266 );
267
268 const RawNativeView = cachedNativeReviewDiffRawView;
269 if (!RawNativeView) {
270 return null;
271 }
272
273 return createElement(RawNativeView, { ...nativeProps, ref: nativeRef });
274}
275
276export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
277 if (cachedNativeReviewDiffRawView) {
278 return NativeReviewDiffView;
279 }
280
281 if (nativeReviewDiffViewResolutionFailed) {
282 return null;
283 }
284
285 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
286 return null;
287 }
288
289 try {
290 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
291 NATIVE_REVIEW_DIFF_MODULE_NAME,
292 );
293 } catch (cause) {
294 nativeReviewDiffViewResolutionFailed = true;
295 console.error(
296 new NativeViewResolutionError({
297 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
298 cause,
299 }),
300 );
301 return null;
302 }
303
304 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
305}