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

nativeReviewDiffSurface.ts

501 lines16.9 KB

1import {
2 createElement,
3 useCallback,
4 useEffect,
5 useImperativeHandle,
6 useRef,
7 useState,
8 type ComponentType,
9 type ReactNode,
10 type Ref,
11} from "react";
12import { StyleSheet, View, type NativeSyntheticEvent, type ViewProps } from "react-native";
13import { requireNativeView } from "expo";
14import { msg, useMessages } from "gt-react-native";
15​
16import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
17import { EmptyState } from "../../components/ui/EmptyState";
18import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
19​
20const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
21const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60;
22​
23interface ExpoGlobalWithViewConfig {
24 readonly expo?: {
25 getViewConfig?: (moduleName: string, viewName?: string) => unknown;
26 };
28​
29export interface NativeReviewDiffRow {
30 readonly kind: "file" | "hunk" | "line" | "notice" | "comment";
31 readonly id: string;
32 readonly fileId?: string;
33 readonly filePath?: string;
34 readonly previousPath?: string | null;
35 readonly changeType?:
36 | "modified"
37 | "new"
38 | "deleted"
39 | "renamed"
40 | "rename-pure"
41 | "rename-changed";
42 readonly additions?: number;
43 readonly deletions?: number;
44 readonly text?: string;
45 readonly content?: string;
46 readonly change?: "context" | "add" | "delete";
47 readonly oldLineNumber?: number | null;
48 readonly newLineNumber?: number | null;
49 readonly wordDiffRanges?: ReadonlyArray<NativeReviewDiffWordDiffRange>;
50 readonly commentText?: string;
51 readonly commentRangeLabel?: string;
52 readonly commentSectionTitle?: string;
53 /** A notice drawn in the warning colors. */
54 readonly tone?: "warning";
55 /** A notice that reports taps through `onPressNotice`. */
56 readonly actionable?: boolean;
57 /** Where a cut line's note starts in `content`. */
58 readonly noteStart?: number;
60​
61export interface NativeReviewDiffWordDiffRange {
62 readonly start: number;
63 readonly end: number;
65​
66export interface NativeReviewDiffToken {
67 readonly content: string;
68 readonly color: string | null;
69 readonly fontStyle: number | null;
71​
72export interface NativeReviewDiffTheme {
73 readonly background: string;
74 readonly text: string;
75 readonly mutedText: string;
76 readonly headerBackground: string;
77 readonly border: string;
78 readonly hunkBackground: string;
79 readonly hunkText: string;
80 readonly addBackground: string;
81 readonly deleteBackground: string;
82 readonly addBar: string;
83 readonly deleteBar: string;
84 readonly addText: string;
85 readonly deleteText: string;
86 readonly warningText: string;
87 readonly warningBackground: string;
89​
90export interface NativeReviewDiffStyle {
91 readonly rowHeight?: number;
92 readonly contentWidth?: number;
93 readonly changeBarWidth?: number;
94 readonly gutterWidth?: number;
95 readonly codePadding?: number;
96 readonly textVerticalInset?: number;
97 readonly fileHeaderHeight?: number;
98 readonly fileHeaderHorizontalMargin?: number;
99 readonly fileHeaderVerticalMargin?: number;
100 readonly fileHeaderCornerRadius?: number;
101 readonly fileHeaderHorizontalPadding?: number;
102 readonly fileHeaderPathRightPadding?: number;
103 readonly fileHeaderCountColumnWidth?: number;
104 readonly fileHeaderCountGap?: number;
105 /** Family names as React Native takes them; a system family name selects the platform font. */
106 readonly codeFontFamily?: string;
107 readonly uiFontFamily?: string;
108 /** Android only: bundled families register one file per name, so bold needs its own. */
109 readonly uiBoldFontFamily?: string;
110 readonly codeFontSize?: number;
111 readonly codeFontWeight?: string;
112 readonly lineNumberFontSize?: number;
113 readonly lineNumberFontWeight?: string;
114 readonly hunkFontSize?: number;
115 readonly hunkFontWeight?: string;
116 readonly fileHeaderFontSize?: number;
117 readonly fileHeaderFontWeight?: string;
118 readonly fileHeaderMetaFontSize?: number;
119 readonly fileHeaderMetaFontWeight?: string;
120 readonly fileHeaderSubtextFontSize?: number;
121 readonly fileHeaderSubtextFontWeight?: string;
122 readonly fileHeaderStatusFontSize?: number;
123 readonly fileHeaderStatusFontWeight?: string;
125​
126export interface NativeReviewDiffViewProps extends ViewProps {
127 readonly contentInsetTop?: number;
128 readonly contentInsetBottom?: number;
129 readonly rowsJson: string;
130 readonly tokensJson?: string;
131 readonly tokensPatchJson?: string;
132 readonly tokensResetKey?: string;
133 readonly contentResetKey?: string;
134 readonly collapsedFileIdsJson?: string;
135 readonly viewedFileIdsJson?: string;
136 readonly selectedRowIdsJson?: string;
137 readonly collapsedCommentIdsJson?: string;
138 readonly appearanceScheme: "light" | "dark";
139 readonly themeJson: string;
140 readonly styleJson?: string;
141 readonly rowHeight: number;
142 /** Android ignores this and measures the widest row. */
143 readonly contentWidth: number;
144 readonly initialRowIndex?: number;
145 readonly initialFileId?: string;
146 readonly scrollEnabled?: boolean;
147 readonly bounces?: boolean;
148 readonly refreshing?: boolean;
149 readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
150 /** Shown over the blank surface until rows for `contentResetKey` are drawn; defaults to a spinner. */
151 readonly loadingFallback?: ReactNode;
152 readonly onPullToRefresh?: (event: NativeSyntheticEvent<Record<string, never>>) => void;
153 readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
154 readonly onVisibleFileChange?: (
155 event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
156 ) => void;
157 readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
158 readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
159 readonly onPressLine?: (
160 event: NativeSyntheticEvent<{
161 readonly rowId?: string;
162 readonly fileId?: string;
163 readonly gesture?: "tap" | "longPress";
164 readonly oldLineNumber?: number;
165 readonly newLineNumber?: number;
166 readonly change?: "context" | "add" | "delete";
167 }>,
168 ) => void;
169 readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
170 readonly onPressNotice?: (
171 event: NativeSyntheticEvent<{ readonly rowId?: string; readonly fileId?: string }>,
172 ) => void;
174​
175export interface NativeReviewDiffViewHandle {
176 readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
177 readonly scrollToTop: (animated?: boolean) => Promise<void>;
179​
180export function isNativeReviewDiffDrawEvent(payload: Readonly<Record<string, unknown>>): boolean {
181 return payload.message === "draw-metrics" || payload.message === "visible-range";
183​
184interface NativeReviewDiffViewRef {
185 readonly setRowsJson: (rowsJson: string, contentResetKey: string) => Promise<void>;
186 readonly setTokensJson: (tokensJson: string) => Promise<void>;
187 readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<boolean>;
188 readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
189 readonly scrollToTop: (animated: boolean) => Promise<void>;
191​
192type NativeReviewDiffRawViewProps = Omit<
193 NativeReviewDiffViewProps,
194 "nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
195> & {
196 readonly refreshEnabled: boolean;
197 readonly ref?: Ref<NativeReviewDiffViewRef>;
198};
199​
200let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
201let nativeReviewDiffViewResolutionFailed = false;
202​
203type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
204​
205export function isPendingNativeViewRegistration(error: unknown): boolean {
206 if (!(error instanceof Error)) return false;
207 return (
208 error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`) ||
209 (error.message.includes("Unable to find the class") &&
210 error.message.includes("T3ReviewDiffView view with tag"))
211 );
213​
214function useNativeReviewDiffPayload(
215 nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
216 method: NativeReviewDiffPayloadMethod,
217 payload: string | undefined,
218 resetKey?: string,
219 onFailure?: () => void,
220 onDelivered?: (payload: string) => void,
221) {
222 // 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
223 useEffect(() => {
224 if (payload === undefined) {
225 return;
226 }
227​
228 let cancelled = false;
229 let frame: number | null = null;
230 let attempts = 0;
231​
232 const dispatch = () => {
233 if (cancelled) {
234 return;
235 }
236​
237 const view = nativeRef.current;
238 if (!view?.[method]) {
239 if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
240 attempts += 1;
241 frame = requestAnimationFrame(dispatch);
242 } else {
243 console.error(`[native-review-diff] ${method} unavailable`);
244 onFailure?.();
245 }
246 return;
247 }
248​
249 void Promise.resolve()
250 .then((): Promise<void | boolean> | undefined => {
251 if (cancelled) return;
252 // Fabric can apply the contentResetKey prop after this call, so rows carry the key.
253 return method === "setRowsJson"
254 ? view.setRowsJson(payload, resetKey ?? "")
255 : view[method](payload);
256 })
257 .then((accepted) => {
258 if (cancelled) return;
259 // This promise resolves after native decode, reset validation, and merge.
260 if (method === "setTokensPatchJson" && accepted !== true) {
261 throw new Error("Native token patch was not accepted");
262 }
263 onDelivered?.(payload);
264 })
265 .catch((error: unknown) => {
266 if (cancelled) return;
267 if (
268 attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
269 isPendingNativeViewRegistration(error)
270 ) {
271 attempts += 1;
272 frame = requestAnimationFrame(dispatch);
273 return;
274 }
275 console.error(`[native-review-diff] ${method} failed`, error);
276 onFailure?.();
277 });
278 };
279​
280 // Expo registers native tags after Fabric attaches refs; dispatch next frame.
281 frame = requestAnimationFrame(dispatch);
282​
283 return () => {
284 cancelled = true;
285 if (frame !== null) {
286 cancelAnimationFrame(frame);
287 }
288 };
289 }, [method, nativeRef, payload, resetKey, onFailure, onDelivered]);
291​
292function getExpoViewConfig(moduleName: string) {
293 return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
294 moduleName,
295 );
297​
298function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
299 const messages = useMessages();
300 const [failedRowsJson, setFailedRowsJson] = useState<string | null>(null);
301 const onRowsFailure = useCallback(() => setFailedRowsJson(props.rowsJson), [props.rowsJson]);
302 if (failedRowsJson !== null && failedRowsJson !== props.rowsJson) setFailedRowsJson(null);
303 if (failedRowsJson === props.rowsJson) {
304 return createElement(
305 View,
306 {
307 style: [
308 props.style,
309 {
310 flex: 1,
311 justifyContent: "center",
312 paddingTop: props.contentInsetTop,
313 paddingBottom: props.contentInsetBottom,
314 },
315 ],
316 },
317 createElement(EmptyState, {
318 title: messages(msg("Could not display diff")),
319 detail: messages(msg("Try loading the diff view again.")),
320 variant: "plain",
321 actionLabel: messages(msg("Retry diff")),
322 onAction: () => {
323 props.onDebug?.({
324 nativeEvent: { message: "surface-retry" },
325 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
326 setFailedRowsJson(null);
327 },
328 }),
329 );
330 }
331 return createElement(NativeReviewDiffContent, { ...props, onRowsFailure });
333​
334function NativeReviewDiffContent(
335 props: NativeReviewDiffViewProps & { readonly onRowsFailure: () => void },
336) {
337 const {
338 nativeViewRef,
339 rowsJson,
340 tokensJson,
341 tokensPatchJson,
342 onRowsFailure,
343 onDebug,
344 loadingFallback,
345 ...nativeProps
346 } = props;
347 const nativeRef = useRef<NativeReviewDiffViewRef>(null);
348 const contentResetKey = props.contentResetKey ?? "";
349 // Native clears its rows on every key change, so each change waits for its own rows-decoded.
350 const [readiness, setReadiness] = useState({ key: contentResetKey, ready: false });
351 if (readiness.key !== contentResetKey) setReadiness({ key: contentResetKey, ready: false });
352 useNativeReviewDiffPayload(
353 nativeRef,
354 "setRowsJson",
355 rowsJson,
356 props.contentResetKey,
357 onRowsFailure,
358 );
359 useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
360 const onDebugRef = useRef(onDebug);
361 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the latest onDebug for callbacks the native diff view fires outside render
362 useEffect(() => {
363 onDebugRef.current = onDebug;
364 }, [onDebug]);
365 const reportedMountRef = useRef(false);
366 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the native surface mount to the debug callback once per mount
367 useEffect(() => {
368 // Effect replay keeps the same native content; only a new mount loses tokens.
369 if (reportedMountRef.current) return;
370 reportedMountRef.current = true;
371 onDebugRef.current?.({
372 nativeEvent: { message: "surface-content-mounted" },
373 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
374 }, []);
375 const reportTokenDelivery = useCallback((json: string, message: string) => {
376 const patch = JSON.parse(json) as { resetKey?: string; chunkIndex?: number };
377 if (patch.chunkIndex === undefined) return;
378 onDebugRef.current?.({
379 nativeEvent: {
380 message,
381 resetKey: patch.resetKey,
382 chunkIndex: patch.chunkIndex,
383 },
384 } as unknown as NativeSyntheticEvent<Record<string, unknown>>);
385 }, []);
386 const onTokensDelivered = useCallback(
387 (json: string) => {
388 reportTokenDelivery(json, "tokens-patch-delivered");
389 },
390 [reportTokenDelivery],
391 );
392 const onTokensFailure = useCallback(() => {
393 if (tokensPatchJson !== undefined) reportTokenDelivery(tokensPatchJson, "tokens-patch-failed");
394 }, [reportTokenDelivery, tokensPatchJson]);
395 useNativeReviewDiffPayload(
396 nativeRef,
397 "setTokensPatchJson",
398 tokensPatchJson,
399 undefined,
400 onTokensFailure,
401 onTokensDelivered,
402 );
403 useImperativeHandle(
404 nativeViewRef,
405 () => ({
406 scrollToFile: async (fileId, animated = true) => {
407 await nativeRef.current?.scrollToFile(fileId, animated);
408 },
409 scrollToTop: async (animated = true) => {
410 await nativeRef.current?.scrollToTop(animated);
411 },
412 }),
413 [],
414 );
415​
416 const RawNativeView = cachedNativeReviewDiffRawView;
417 if (!RawNativeView) {
418 return null;
419 }
420​
421 /* oxlint-disable react/refs -- The native view receives this ref; only event callbacks access its current value. */
422 const nativeView = createElement(RawNativeView, {
423 ...nativeProps,
424 style: StyleSheet.absoluteFill,
425 refreshEnabled: props.onPullToRefresh !== undefined,
426 onDebug: (event) => {
427 const { message } = event.nativeEvent;
428 if (message === "rows-decode-failed") {
429 console.error("[native-review-diff] rows decode failed", event.nativeEvent.error);
430 onRowsFailure();
431 }
432 if (message === "rows-decoded") {
433 // Builds that predate the key in this event still need the loading state cleared.
434 const decodedKey = event.nativeEvent.contentResetKey;
435 setReadiness((current) =>
436 typeof decodedKey !== "string" || current.key === decodedKey
437 ? { key: current.key, ready: true }
438 : current,
439 );
440 }
441 onDebug?.(event);
442 },
443 ref: nativeRef,
444 });
445 /* oxlint-enable react/refs */
446 // Always wrapped, so a caller toggling `loadingFallback` never remounts the native view.
447 return createElement(
448 View,
449 { style: props.style },
450 nativeView,
451 readiness.ready
452 ? null
453 : createElement(
454 View,
455 {
456 pointerEvents: "none",
457 style: [
458 StyleSheet.absoluteFill,
459 { paddingTop: props.contentInsetTop, paddingBottom: props.contentInsetBottom },
460 ],
461 },
462 loadingFallback ??
463 createElement(
464 View,
465 { style: { flex: 1, alignItems: "center", justifyContent: "center" } },
466 createElement(AppActivityIndicator, { size: "small" }),
467 ),
468 ),
469 );
471​
472export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
473 if (cachedNativeReviewDiffRawView) {
474 return NativeReviewDiffView;
475 }
476​
477 if (nativeReviewDiffViewResolutionFailed) {
478 return null;
479 }
480​
481 if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
482 return null;
483 }
484​
485 try {
486 cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
487 NATIVE_REVIEW_DIFF_MODULE_NAME,
488 );
489 } catch (cause) {
490 nativeReviewDiffViewResolutionFailed = true;
491 console.error(
492 new NativeViewResolutionError({
493 nativeModuleName: NATIVE_REVIEW_DIFF_MODULE_NAME,
494 cause,
495 }),
496 );
497 return null;
498 }
499​
500 return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;