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

nativeReviewDiffSurface.ts

452 lines14.8 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;
50 /** A notice drawn in the warning colors. */
51 readonly tone?: "warning";
52 /** A notice that reports taps through `onPressNotice`. */
53 readonly actionable?: boolean;
54 /** Where a cut line's note starts in `content`. */
55 readonly noteStart?: number;
57​
58export interface NativeReviewDiffWordDiffRange {
59 readonly start: number;
60 readonly end: number;
62​
63export interface NativeReviewDiffToken {
64 readonly content: string;
65 readonly color: string | null;
66 readonly fontStyle: number | null;
68​
69export interface NativeReviewDiffTheme {
70 readonly background: string;
71 readonly text: string;
72 readonly mutedText: string;
73 readonly headerBackground: string;
74 readonly border: string;
75 readonly hunkBackground: string;
76 readonly hunkText: string;
77 readonly addBackground: string;
78 readonly deleteBackground: string;
79 readonly addBar: string;
80 readonly deleteBar: string;
81 readonly addText: string;
82 readonly deleteText: string;
83 readonly warningText: string;
84 readonly warningBackground: string;
86​
87export interface NativeReviewDiffStyle {
88 readonly rowHeight?: number;
89 readonly contentWidth?: number;
90 readonly changeBarWidth?: number;
91 readonly gutterWidth?: number;
92 readonly codePadding?: number;
93 readonly textVerticalInset?: number;
94 readonly fileHeaderHeight?: number;
95 readonly fileHeaderHorizontalMargin?: number;
96 readonly fileHeaderVerticalMargin?: number;
97 readonly fileHeaderCornerRadius?: number;
98 readonly fileHeaderHorizontalPadding?: number;
99 readonly fileHeaderPathRightPadding?: number;
100 readonly fileHeaderCountColumnWidth?: number;
101 readonly fileHeaderCountGap?: number;
102 readonly codeFontSize?: number;
103 readonly codeFontWeight?: string;
104 readonly lineNumberFontSize?: number;
105 readonly lineNumberFontWeight?: string;
106 readonly hunkFontSize?: number;
107 readonly hunkFontWeight?: string;
108 readonly fileHeaderFontSize?: number;
109 readonly fileHeaderFontWeight?: string;
110 readonly fileHeaderMetaFontSize?: number;
111 readonly fileHeaderMetaFontWeight?: string;
112 readonly fileHeaderSubtextFontSize?: number;
113 readonly fileHeaderSubtextFontWeight?: string;
114 readonly fileHeaderStatusFontSize?: number;
115 readonly fileHeaderStatusFontWeight?: string;
116 readonly emptyStateFontSize?: number;
117 readonly emptyStateFontWeight?: string;
119​
120export interface NativeReviewDiffViewProps extends ViewProps {
121 readonly contentInsetTop?: number;
122 readonly contentInsetBottom?: number;
123 readonly rowsJson: string;
124 readonly tokensJson?: string;
125 readonly tokensPatchJson?: string;
126 readonly tokensResetKey?: string;
127 readonly contentResetKey?: string;
128 readonly collapsedFileIdsJson?: string;
129 readonly viewedFileIdsJson?: string;
130 readonly selectedRowIdsJson?: string;
131 readonly collapsedCommentIdsJson?: string;
132 readonly appearanceScheme: "light" | "dark";
133 readonly themeJson: string;
134 readonly styleJson?: string;
135 readonly rowHeight: number;
136 /** Android ignores this and measures the widest row. */
137 readonly contentWidth: number;
138 readonly initialRowIndex?: number;
139 readonly initialFileId?: string;
140 readonly scrollEnabled?: boolean;
141 readonly bounces?: boolean;
142 readonly refreshing?: boolean;
143 readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
144 readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
145 readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
146 readonly onVisibleFileChange?: (
147 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
148 ) => void;
149 readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
150 readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
151 readonly onPressLine?: (
152 event: NativeSyntheticEvent<{
153 readonly rowId?: string;
154 readonly fileId?: string;
155 readonly gesture?: "tap" | "longPress";
156 readonly oldLineNumber?: number;
157 readonly newLineNumber?: number;
158 readonly change?: "context" | "add" | "delete";
159 }>,
160 ) => void;
161 readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
162 readonly onPressNotice?: (
163 event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>,
164 ) => void;
166​
167export interface NativeReviewDiffViewHandle {
168 readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
169 readonly scrollToTop: (animated?: boolean) => Promise<void>;
171​
172export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
173 return payload.message === "draw-metrics" || payload.message === "visible-range";
175​
176interface NativeReviewDiffViewRef {
177 readonly setRowsJson: (rowsJson: string, contentResetKey: string) => Promise<void>;
178 readonly setTokensJson: (tokensJson: string) => Promise<void>;
179 readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<boolean>;
180 readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
181 readonly scrollToTop: (animated: boolean) => Promise<void>;
183​
184type NativeReviewDiffRawViewProps = Omit<
185 NativeReviewDiffViewProps,
186 "nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
187> & {
188 readonly refreshEnabled: boolean;
189 readonly ref?: Ref<NativeReviewDiffViewRef>;
190};
191​
192let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
193let nativeReviewDiffViewResolutionFailed = false;
194​
195type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
196​
197export function isPendingNativeViewRegistration(error: unknown): boolean {
198 if (!(error instanceof Error)) return false;
199 return (
200 error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
201 (error.message.includes("Unable to find the class") &&
202 error.message.includes("T3ReviewDiffView view with tag"))
203 );
205​
206function useNativeReviewDiffPayload(
207 nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
208 method: NativeReviewDiffPayloadMethod,
209 payload: string | undefined,
210 resetKey?: string,
211 onFailure?: () => void,
212 onDelivered?: (payload: string) => void,
213) {
214 // 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
215 useEffect(() => {
216 if (payload === undefined) {
217 return;
218 }
219​
220 let cancelled = false;
221 let frame: number | null = null;
222 let attempts = 0;
223​
224 const dispatch = () => {
225 if (cancelled) {
226 return;
227 }
228​
229 const view = nativeRef.current;
230 if (!view?.[method]) {
231 if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
232 attempts += 1;
233 frame = requestAnimationFrame(dispatch);
234 } else {
235 console.error(`[native-review-diff] ${method} unavailable`);
236 onFailure?.();
237 }
238 return;
239 }
240​
241 void Promise.resolve()
242 .then((): Promise<void | boolean> | undefined => {
243 if (cancelled) return;
244 // Fabric can apply the contentResetKey prop after this call, so rows carry the key.
245 return method === "setRowsJson"
246 ? view.setRowsJson(payload, resetKey ?? "")
247 : view[method](payload);
248 })
249 .then((accepted) => {
250 if (cancelled) return;
251 // This promise resolves after native decode, reset validation, and merge.
252 if (method === "setTokensPatchJson" && accepted !== true) {
253 throw new Error("Native token patch was not accepted");
254 }
255 onDelivered?.(payload);
256 })
257 .catch((error: unknown) => {
258 if (cancelled) return;
259 if (
260 attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
261 isPendingNativeViewRegistration(error)
262 ) {
263 attempts += 1;
264 frame = requestAnimationFrame(dispatch);
265 return;
266 }
267 console.error(`[native-review-diff] ${method} failed`, error);
268 onFailure?.();
269 });
270 };
271​
272 // Expo registers native tags after Fabric attaches refs; dispatch next frame.
273 frame = requestAnimationFrame(dispatch);
274​
275 return () => {
276 cancelled = true;
277 if (frame !== null) {
278 cancelAnimationFrame(frame);
279 }
280 };
281 }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);
283​
284function getExpoViewConfig(moduleName: string) {
285 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
286 moduleName,
287 );
289​
290function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
291 const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);
292 const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);
293 if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);
294 if (failedRowsJson === props.rowsJson) {
295 return createElement(
296 View,
297 {
298 style: [
299 props.style,
300 {
301 flex: 1,
302 justifyContent: "center",
303 paddingTop: props.contentInsetTop,
304 paddingBottom: props.contentInsetBottom,
305 },
306 ],
307 },
308 createElement(EmptyState, {
309 title: "Could not display diff",
310 detail: "Try loading the diff view again.",
311 variant: "plain",
312 actionLabel: "Retry diff",
313 onAction: () => {
314 props.onDebug?.({
315 nativeEvent: { message: "surface-retry" },
316 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
317 setFailedRowsJson(null);
318 },
319 }),
320 );
321 }
322 return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });
324​
325function NativeReviewDiffContent(
326 props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },
327) {
328 const {
329 nativeViewRef,
330 rowsJson,
331 tokensJson,
332 tokensPatchJson,
333 onRowsFailure,
334 onDebug,
335 ...nativeProps
336 } = props;
337 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
338 useNativeReviewDiffPayload(
339 nativeRef,
340 "setRowsJson",
341 rowsJson,
342 props.contentResetKey,
343 onRowsFailure,
344 );
345 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
346 const onDebugRef = useRef(onDebug);
347 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the latest onDebug for callbacks the native diff view fires outside render
348 useEffect(() => {
349 onDebugRef.current = onDebug;
350 }, [onDebug]);
351 const reportedMountRef = useRef(false);
352 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the native surface mount to the debug callback once per mount
353 useEffect(() => {
354 // Effect replay keeps the same native content; only a new mount loses tokens.
355 if (reportedMountRef.current) return;
356 reportedMountRef.current = true;
357 onDebugRef.current?.({
358 nativeEvent: { message: "surface-content-mounted" },
359 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
360 }, []);
361 const reportTokenDelivery = useCallback((json: string, message: string) => {
362 const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };
363 if (patch.chunkIndex === undefined) return;
364 onDebugRef.current?.({
365 nativeEvent: {
366 message,
367 resetKey: patch.resetKey,
368 chunkIndex: patch.chunkIndex,
369 },
370 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
371 }, []);
372 const onTokensDelivered = useCallback(
373 (json: string) => {
374 reportTokenDelivery(json, "tokens-patch-delivered");
375 },
376 [reportTokenDelivery],
377 );
378 const onTokensFailure = useCallback(() => {
379 if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");
380 }, [reportTokenDelivery, tokensPatchJson]);
381 useNativeReviewDiffPayload(
382 nativeRef,
383 "setTokensPatchJson",
384 tokensPatchJson,
385 undefined,
386 onTokensFailure,
387 onTokensDelivered,
388 );
389 useImperativeHandle(
390 nativeViewRef,
391 () => ({
392 scrollToFile: async (fileId, animated = true) => {
393 await nativeRef.current?.scrollToFile(fileId, animated);
394 },
395 scrollToTop: async (animated = true) => {
396 await nativeRef.current?.scrollToTop(animated);
397 },
398 }),
399 [],
400 );
401​
402 const RawNativeView = cachedNativeReviewDiffRawView;
403 if (!RawNativeView) {
404 return null;
405 }
406​
407 /* oxlint-disable react/refs -- The native view receives this ref; only event callbacks access its current value. */
408 return createElement(RawNativeView, {
409 ...nativeProps,
410 refreshEnabled: props.onPullToRefresh !== undefined,
411 onDebug: (event) => {
412 if (event.nativeEvent.message === "rows-decode-failed") {
413 console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);
414 onRowsFailure();
415 }
416 onDebug?.(event);
417 },
418 ref: nativeRef,
419 });
420 /* oxlint-enable react/refs */
422​
423export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
424 if (cachedNativeReviewDiffRawView) {
425 return NativeReviewDiffView;
426 }
427​
428 if (nativeReviewDiffViewResolutionFailed) {
429 return null;
430 }
431​
432 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
433 return null;
434 }
435​
436 try {
437 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
438 NATIVE_REVIEW_DIFF_MODULE_NAME,
439 );
440 } catch (cause) {
441 nativeReviewDiffViewResolutionFailed = true;
442 console.error(
443 new NativeViewResolutionError({
444 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
445 cause,
446 }),
447 );
448 return null;
449 }
450​
451 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;