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 initialRowIndex?: number;
125 readonly refreshing?: boolean;
126 readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
127 readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
128 readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
129 readonly onVisibleFileChange?: (
130 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
131 ) => void;
132 readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
133 readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
134 readonly onPressLine?: (
135 event: NativeSyntheticEvent<{
136 readonly rowId?: string;
137 readonly fileId?: string;
138 readonly gesture?: "tap" | "longPress";
139 readonly oldLineNumber?: number;
140 readonly newLineNumber?: number;
141 readonly change?: "context" | "add" | "delete";
142 }>,
143 ) => void;
144 readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
145}
146
147export interface NativeReviewDiffViewHandle {
148 readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
149 readonly scrollToTop: (animated?: boolean) => Promise<void>;
150}
151
152export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
153 return payload.message === "draw-metrics" || payload.message === "visible-range";
154}
155
156interface NativeReviewDiffViewRef {
157 readonly setRowsJson: (rowsJson: string) => Promise<void>;
158 readonly setTokensJson: (tokensJson: string) => Promise<void>;
159 readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;
160 readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
161 readonly scrollToTop: (animated: boolean) => Promise<void>;
162}
163
164type NativeReviewDiffRawViewProps = Omit<
165 NativeReviewDiffViewProps,
166 "nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
167> & {
168 readonly ref?: Ref<NativeReviewDiffViewRef>;
169};
170
171let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
172let nativeReviewDiffViewResolutionFailed = false;
173
174type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
175
176export function isPendingNativeViewRegistration(error: unknown): boolean {
177 if (!(error instanceof Error)) return false;
178 return (
179 error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
180 (error.message.includes("Unable to find the class") &&
181 error.message.includes("T3ReviewDiffView view with tag"))
182 );
183}
184
185function useNativeReviewDiffPayload(
186 nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
187 method: NativeReviewDiffPayloadMethod,
188 payload: string | undefined,
189) {
190 useEffect(() => {
191 if (payload === undefined) {
192 return;
193 }
194
195 let cancelled = false;
196 let frame: number | null = null;
197 let attempts = 0;
198
199 const dispatch = () => {
200 if (cancelled) {
201 return;
202 }
203
204 const view = nativeRef.current;
205 const command = view?.[method];
206 if (!view || !command) {
207 if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
208 attempts += 1;
209 frame = requestAnimationFrame(dispatch);
210 }
211 return;
212 }
213
214 void command.call(view, payload).catch((error: unknown) => {
215 if (
216 !cancelled &&
217 attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
218 isPendingNativeViewRegistration(error)
219 ) {
220 attempts += 1;
221 frame = requestAnimationFrame(dispatch);
222 return;
223 }
224 console.error(`[native-review-diff] ${method} failed`, error);
225 });
226 };
227
228 // Fabric attaches the React ref before Expo registers the native tag used by
229 // view functions. Starting on the next frame avoids racing that registration.
230 frame = requestAnimationFrame(dispatch);
231
232 return () => {
233 cancelled = true;
234 if (frame !== null) {
235 cancelAnimationFrame(frame);
236 }
237 };
238 }, [method, nativeRef, payload]);
239}
240
241function getExpoViewConfig(moduleName: string) {
242 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
243 moduleName,
244 );
245}
246
247function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
248 const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;
249 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
250 useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);
251 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
252 useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);
253 useImperativeHandle(
254 nativeViewRef,
255 () => ({
256 scrollToFile: async (fileId, animated = true) => {
257 await nativeRef.current?.scrollToFile(fileId, animated);
258 },
259 scrollToTop: async (animated = true) => {
260 await nativeRef.current?.scrollToTop(animated);
261 },
262 }),
263 [],
264 );
265
266 const RawNativeView = cachedNativeReviewDiffRawView;
267 if (!RawNativeView) {
268 return null;
269 }
270
271 return createElement(RawNativeView, { ...nativeProps, ref: nativeRef });
272}
273
274export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
275 if (cachedNativeReviewDiffRawView) {
276 return NativeReviewDiffView;
277 }
278
279 if (nativeReviewDiffViewResolutionFailed) {
280 return null;
281 }
282
283 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
284 return null;
285 }
286
287 try {
288 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
289 NATIVE_REVIEW_DIFF_MODULE_NAME,
290 );
291 } catch (cause) {
292 nativeReviewDiffViewResolutionFailed = true;
293 console.error(
294 new NativeViewResolutionError({
295 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
296 cause,
297 }),
298 );
299 return null;
300 }
301
302 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
303}