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

nativeReviewDiffSurface.ts

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