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

nativeReviewDiffSurface.ts

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