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

nativeReviewDiffSurface.ts

312 lines9.9 KB

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