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

nativeReviewDiffSurface.ts

433 lines13.6 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 }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);
268​
269function getExpoViewConfig(moduleName: string) {
270 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
271 moduleName,
272 );
274​
275function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
276 const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);
277 const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);
278 if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);
279 if (failedRowsJson === props.rowsJson) {
280 return createElement(
281 View,
282 {
283 style: [
284 props.style,
285 {
286 flex: 1,
287 justifyContent: "center",
288 paddingTop: props.contentInsetTop,
289 paddingBottom: props.contentInsetBottom,
290 },
291 ],
292 },
293 createElement(EmptyState, {
294 title: "Could not display diff",
295 detail: "Try loading the diff view again.",
296 variant: "plain",
297 actionLabel: "Retry diff",
298 onAction: () => {
299 props.onDebug?.({
300 nativeEvent: { message: "surface-retry" },
301 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
302 setFailedRowsJson(null);
303 },
304 }),
305 );
306 }
307 return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });
309​
310function NativeReviewDiffContent(
311 props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },
312) {
313 const {
314 nativeViewRef,
315 rowsJson,
316 tokensJson,
317 tokensPatchJson,
318 onRowsFailure,
319 onDebug,
320 ...nativeProps
321 } = props;
322 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
323 useNativeReviewDiffPayload(
324 nativeRef,
325 "setRowsJson",
326 rowsJson,
327 props.contentResetKey,
328 onRowsFailure,
329 );
330 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
331 const onDebugRef = useRef(onDebug);
332 useEffect(() => {
333 onDebugRef.current = onDebug;
334 }, [onDebug]);
335 const reportedMountRef = useRef(false);
336 useEffect(() => {
337 // Effect replay keeps the same native content; only a new mount loses tokens.
338 if (reportedMountRef.current) return;
339 reportedMountRef.current = true;
340 onDebugRef.current?.({
341 nativeEvent: { message: "surface-content-mounted" },
342 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
343 }, []);
344 const reportTokenDelivery = useCallback((json: string, message: string) => {
345 const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };
346 if (patch.chunkIndex === undefined) return;
347 onDebugRef.current?.({
348 nativeEvent: {
349 message,
350 resetKey: patch.resetKey,
351 chunkIndex: patch.chunkIndex,
352 },
353 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
354 }, []);
355 const onTokensDelivered = useCallback(
356 (json: string) => {
357 reportTokenDelivery(json, "tokens-patch-delivered");
358 },
359 [reportTokenDelivery],
360 );
361 const onTokensFailure = useCallback(() => {
362 if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");
363 }, [reportTokenDelivery, tokensPatchJson]);
364 useNativeReviewDiffPayload(
365 nativeRef,
366 "setTokensPatchJson",
367 tokensPatchJson,
368 undefined,
369 onTokensFailure,
370 onTokensDelivered,
371 );
372 useImperativeHandle(
373 nativeViewRef,
374 () => ({
375 scrollToFile: async (fileId, animated = true) => {
376 await nativeRef.current?.scrollToFile(fileId, animated);
377 },
378 scrollToTop: async (animated = true) => {
379 await nativeRef.current?.scrollToTop(animated);
380 },
381 }),
382 [],
383 );
384​
385 const RawNativeView = cachedNativeReviewDiffRawView;
386 if (!RawNativeView) {
387 return null;
388 }
389​
390 return createElement(RawNativeView, {
391 ...nativeProps,
392 refreshEnabled: props.onPullToRefresh !== undefined,
393 onDebug: (event) => {
394 if (event.nativeEvent.message === "rows-decode-failed") {
395 console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);
396 onRowsFailure();
397 }
398 onDebug?.(event);
399 },
400 ref: nativeRef,
401 });
403​
404export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
405 if (cachedNativeReviewDiffRawView) {
406 return NativeReviewDiffView;
407 }
408​
409 if (nativeReviewDiffViewResolutionFailed) {
410 return null;
411 }
412​
413 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
414 return null;
415 }
416​
417 try {
418 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
419 NATIVE_REVIEW_DIFF_MODULE_NAME,
420 );
421 } catch (cause) {
422 nativeReviewDiffViewResolutionFailed = true;
423 console.error(
424 new NativeViewResolutionError({
425 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
426 cause,
427 }),
428 );
429 return null;
430 }
431​
432 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;