Skip to content
TypeScript

perf(mobile): pull request screens compile with the React Compiler (#21136)

Julius Marminge001111c360d3
diff --git a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
index 541ae735ed1..6ee6c572625 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestDiscussionScreen.tsx
@@ -2,7 +2,11 @@ import { Toolbar } from "../../components/ui/Toolbar";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { useAtomRefresh } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import {
+ type AtomCommandResult,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import type { PullRequestThreadComment } from "@t3tools/contracts";
import { useRef, useState } from "react";
import { Platform, ScrollView, View } from "react-native";
@@ -59,57 +63,58 @@ function Discussion({ params }: { params: PullRequestParams & { readonly discuss
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [composerHeight, setComposerHeight] = useState(64);
- const operation = async (run: () => Promise<void>) => {
+ const operation = async (run: () => Promise<AtomCommandResult<unknown, unknown> | undefined>) => {
if (pending.current) return;
pending.current = true;
setBusy(true);
setError(null);
setNotice(null);
- try {
- await run();
- } catch (cause) {
+ const result = await run();
+ pending.current = false;
+ setBusy(false);
+ if (result && AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
setError(
cause instanceof Error ? cause.message : "The provider could not complete this action.",
);
- } finally {
- pending.current = false;
- setBusy(false);
}
};
const post = () =>
operation(async () => {
- if (!permissions.canReply || !body.trim() || !thread) return;
+ if (!permissions.canReply || !body.trim() || !thread) return undefined;
const submitted = body;
const response = await reply({
...target,
input: { ...target.input, threadId: thread.id, body: submitted },
});
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
+ if (AsyncResult.isFailure(response)) return response;
setBody((current) => (current === submitted ? "" : current));
setNotice("Reply posted.");
refresh();
+ return response;
});
const toggleResolved = () =>
operation(async () => {
- if (!thread || !permissions.canResolve) return;
+ if (!thread || !permissions.canResolve) return undefined;
const response = await resolve({
...target,
input: { ...target.input, threadId: thread.id, resolved: !thread.isResolved },
});
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
- refresh();
+ if (AsyncResult.isSuccess(response)) refresh();
+ return response;
});
const nextCursor = cursor === undefined ? thread?.nextCommentsCursor : cursor;
const more = () =>
operation(async () => {
- if (!thread || !nextCursor) return;
+ if (!thread || !nextCursor) return undefined;
const response = await loadMore({
...target,
input: { ...target.input, threadId: thread.id, cursor: nextCursor },
});
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
+ if (AsyncResult.isFailure(response)) return response;
setExtra((comments) => [...comments, ...response.value.comments]);
setCursor(response.value.nextCursor);
+ return response;
});
const comments = [
...new Map(
diff --git a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
index 9d2decadf53..7a8152e01dc 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestInlineCommentScreen.tsx
@@ -1,6 +1,8 @@
+import { settlePromise } from "@t3tools/client-runtime/state/runtime";
+import { AsyncResult } from "effect/reactivity";
import * as Dialog from "../../components/ui/Dialog";
import { useFocusEffect, useNavigation, type StaticScreenProps } from "@react-navigation/native";
-import { useCallback, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { View } from "react-native";
import type { PullRequestReviewPosition } from "@t3tools/contracts";
import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
@@ -31,7 +33,7 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
const body = editedBody ?? saved?.body ?? "";
const detail = useEnvironmentQuery(composerPullRequests.detail(pullRequestTarget(params)));
const { refresh: refreshDetail } = detail;
- useFocusEffect(useCallback(() => refreshDetail(), [refreshDetail]));
+ useFocusEffect(() => refreshDetail());
const permissions = usePullRequestPermissions(params, detail.data);
const stale = detail.data && detail.data.headSha !== params.headSha;
const pending = useRef(false);
@@ -64,13 +66,11 @@ export function PullRequestInlineCommentScreen({ route }: StaticScreenProps<Inli
},
],
}));
- try {
- await store.flush();
- navigation.goBack();
- } finally {
- pending.current = false;
- setBusy(false);
- }
+ // flush reports write failures through the draft store's error field.
+ const result = await settlePromise(() => store.flush());
+ pending.current = false;
+ setBusy(false);
+ if (AsyncResult.isSuccess(result)) navigation.goBack();
};
return (
<PullRequestSheetContent
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
index c479ad24082..97ff786fa86 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
@@ -98,47 +98,45 @@ export function PullRequestMergeControls(props: {
return;
pending.current = true;
setBusy(true);
- try {
- const response = await runAction({
- ...target,
- input: {
- ...target.input,
- action,
- ...(action === "merge" && method && stack.stack && scope
+ const response = await runAction({
+ ...target,
+ input: {
+ ...target.input,
+ action,
+ ...(action === "merge" && method && stack.stack && scope
+ ? {
+ stackNumber: stack.stack.number,
+ expectedStackHeads: scope.heads,
+ mergeMethod: method,
+ }
+ : action === "merge" && method
? {
- stackNumber: stack.stack.number,
- expectedStackHeads: scope.heads,
- mergeMethod: method,
+ resolveMergeMethod: (fresh) => {
+ if (
+ !canPerformPullRequestAction(fresh, "merge") ||
+ !allowedMergeMethods(fresh).includes(method)
+ )
+ throw new Error("The pull request changed. Refresh before merging.");
+ return method;
+ },
}
- : action === "merge" && method
- ? {
- resolveMergeMethod: (fresh) => {
- if (
- !canPerformPullRequestAction(fresh, "merge") ||
- !allowedMergeMethods(fresh).includes(method)
- )
- throw new Error("The pull request changed. Refresh before merging.");
- return method;
- },
- }
- : action === "enable-auto-merge" && method
- ? { mergeMethod: method }
- : {}),
- },
- });
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
- } catch (cause) {
+ : action === "enable-auto-merge" && method
+ ? { mergeMethod: method }
+ : {}),
+ },
+ });
+ // A stack can partly merge before the provider reports a failure.
+ refreshDetail();
+ refreshActivity();
+ stack.refresh();
+ pending.current = false;
+ setBusy(false);
+ if (AsyncResult.isFailure(response)) {
+ const cause = squashAtomCommandFailure(response);
Dialog.alert(
"Couldn't complete the merge action",
cause instanceof Error ? cause.message : "Try again.",
);
- } finally {
- // A stack can partly merge before the provider reports a failure.
- refreshDetail();
- refreshActivity();
- stack.refresh();
- pending.current = false;
- setBusy(false);
}
};
const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
index c60e2e1d3d3..1758c8f57f5 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx
@@ -1,9 +1,10 @@
+import { AsyncResult } from "effect/reactivity";
import { useAtomRefresh } from "@effect/atom-react";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
-import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { PullRequestReviewVerdict } from "@t3tools/contracts";
-import { useCallback, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { useFocusEffect } from "@react-navigation/native";
import { Platform, Pressable, View } from "react-native";
import { clearSubmittedReview } from "./pullRequestReviewDrafts";
@@ -31,20 +32,21 @@ function useActionSubmission(params: PullRequestParams) {
pending.current = true;
setBusy(true);
setError(null);
- try {
+ const result = await settlePromise(async () => {
await operation();
refreshDetail();
refreshActivity();
navigation.goBack();
- } catch (cause) {
+ });
+ pending.current = false;
+ setBusy(false);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
setError(
cause instanceof Error
? cause.message
: "The provider could not complete this action. Try again.",
);
- } finally {
- pending.current = false;
- setBusy(false);
}
};
return { busy, error, submit };
@@ -66,7 +68,7 @@ export function PullRequestReviewSheet({
const target = pullRequestTarget(params);
const result = useEnvironmentQuery(composerPullRequests.detail(target));
const { refresh: refreshDetail } = result;
- useFocusEffect(useCallback(() => refreshDetail(), [refreshDetail]));
+ useFocusEffect(() => refreshDetail());
const permissions = usePullRequestPermissions(params, result.data);
const submission = useActionSubmission(params);
const review = useAtomCommand(composerPullRequests.submitReview, { reportFailure: false });
diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
index 3a4323b030e..3caa8957dfe 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
@@ -1,3 +1,4 @@
+import { AsyncResult } from "effect/reactivity";
import { Toolbar } from "../../components/ui/Toolbar";
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { usePullRequestConnected } from "./usePullRequestConnected";
@@ -5,7 +6,7 @@ import { useAtomValue } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import {
FlatList,
Platform,
@@ -79,7 +80,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
const [pending, setPending] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const inFlight = useRef(false);
- const candidates = useMemo(() => {
+ const candidates = (() => {
const needle = query.trim().toLowerCase();
return [...(result.data?.candidates ?? [])]
.filter((candidate) =>
@@ -88,7 +89,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
.sort(
(a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),
);
- }, [result.data, query]);
+ })();
useEffect(() => {
if (candidates.length === 0) return;
listRef.current?.scrollToOffset({
@@ -103,27 +104,26 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
inFlight.current = true;
setPending(`${candidate.kind}:${candidate.id}`);
setError(null);
- try {
- const response = await request({
- ...target,
- input: {
- ...target.input,
- reviewers: [{ id: candidate.id, kind: candidate.kind }],
- requested: !candidate.isRequested,
- },
- });
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
- if (!pr?.capabilities.reviewers.listCandidates) {
- setQuery("");
- detail.refresh();
- }
- } catch (cause) {
+ const response = await request({
+ ...target,
+ input: {
+ ...target.input,
+ reviewers: [{ id: candidate.id, kind: candidate.kind }],
+ requested: !candidate.isRequested,
+ },
+ });
+ inFlight.current = false;
+ setPending(null);
+ if (AsyncResult.isFailure(response)) {
+ const cause = squashAtomCommandFailure(response);
setError(
cause instanceof Error ? cause.message : "Couldn't update this review request. Try again.",
);
- } finally {
- inFlight.current = false;
- setPending(null);
+ return;
+ }
+ if (!pr?.capabilities.reviewers.listCandidates) {
+ setQuery("");
+ detail.refresh();
}
};
const listCandidates = pr?.capabilities.reviewers.listCandidates === true;
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index bbb6087e6c0..9ff0d0b1868 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
@@ -50,7 +50,7 @@ import { type PullRequestDetail, type PullRequestListEntry } from "@t3tools/cont
import { PullRequestOverviewLoading } from "./PullRequestOverviewLoading";
import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";
import { pullRequestStatus } from "./pullRequestStatus";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import {
Linking,
Platform,
@@ -139,11 +139,8 @@ function PullRequestTabScrollView(props: ScrollViewProps) {
function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityFilter) {
const navigation = useNavigation();
const result = useEnvironmentQuery(composerPullRequests.activity(requestTarget(params)));
- const filtered = useMemo(
- () => (result.data ? filterPullRequestActivity(result.data, filter) : null),
- [result.data, filter],
- );
- const rows = useMemo(() => {
+ const filtered = result.data ? filterPullRequestActivity(result.data, filter) : null;
+ const rows = (() => {
if (!filtered) return [];
const rows = pullRequestTimelineRows(filtered.activity, params, navigation);
if (filter.newestFirst) {
@@ -162,7 +159,7 @@ function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityF
),
});
return rows;
- }, [filtered, filter.newestFirst, params, navigation]);
+ })();
return {
rows,
hiddenCount: filtered?.hiddenCount ?? 0,
@@ -340,7 +337,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
const result = useEnvironmentQuery(detailAtom);
const pullRefresh = usePullToRefresh(detailAtom);
const { refresh: refreshDetail } = result;
- useFocusEffect(useCallback(() => refreshDetail(), [refreshDetail]));
+ useFocusEffect(() => refreshDetail());
const pr = result.data;
const summary = params.initialSummary;
const identity = pr ?? summary;
@@ -791,7 +788,7 @@ export function PullRequestFileRouteScreen({
);
const detail = useEnvironmentQuery(composerPullRequests.detail(requestTarget(route.params)));
const { refresh: refreshDetail } = detail;
- useFocusEffect(useCallback(() => refreshDetail(), [refreshDetail]));
+ useFocusEffect(() => refreshDetail());
const { loadMore } = result;
const parsed = filter.parsed;
const reviewDraft = usePullRequestReviewDraft(route.params);
@@ -813,16 +810,12 @@ export function PullRequestFileRouteScreen({
!result.isPending &&
!result.error;
const activity = useEnvironmentQuery(composerPullRequests.activity(requestTarget(route.params)));
- const baseData = useMemo(() => buildNativeReviewDiffData(parsed), [parsed]);
- const data = useMemo(
- () =>
- annotatePullRequestDiff(
- baseData,
- staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
- commit ? [] : reviewDraft.draft.comments,
- diffHead.sha ?? undefined,
- ),
- [baseData, activity.data, reviewDraft.draft.comments, diffHead.sha, staleDiff, commit],
+ const baseData = buildNativeReviewDiffData(parsed);
+ const data = annotatePullRequestDiff(
+ baseData,
+ staleDiff || commit ? [] : (activity.data?.reviewThreads ?? []),
+ commit ? [] : reviewDraft.draft.comments,
+ diffHead.sha ?? undefined,
);
const viewedIds = data.files
.filter((file) => (commit ? commitViewedPaths.has(file.path) : viewed.isViewed(file.path)))
@@ -916,49 +909,43 @@ export function PullRequestFileRouteScreen({
if (!targetFile) loadMore();
}, [targetFile, loadMore]);
const { onDebug: updateVisibleRange } = bridge;
- const onDebug = useCallback<NonNullable<NativeReviewDiffViewProps["onDebug"]>>(
- (event) => {
- const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);
- const decoded =
- event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === data.rows.length;
- if (!drawn && !decoded) return;
- // Filtering replaces the native row payload asynchronously. Old draw events
- // must not consume the file jump or highlight the new payload's row indices.
- if (
- typeof event.nativeEvent.totalRows === "number" &&
- event.nativeEvent.totalRows !== data.rows.length
- )
- return;
- if (drawn) updateVisibleRange(event);
- if (
- targetFile &&
- !jumpStarted.current &&
- nativeView.current &&
- (Platform.OS !== "ios" || decoded)
- ) {
- jumpStarted.current = true;
- if (focusIndex >= 0) return;
- void nativeView.current.scrollToFile(targetFile.id, false).catch(() => {
- jumpStarted.current = false;
- });
- return;
- }
- if (!drawn) return;
- const lastRow = event.nativeEvent.lastRowIndex;
- if (typeof lastRow === "number" && lastRow >= data.rows.length - 40) loadMore();
- },
- [updateVisibleRange, data.rows.length, loadMore, targetFile, focusIndex],
- );
- const onToggleFile = useCallback<NonNullable<NativeReviewDiffViewProps["onToggleFile"]>>(
- (event) => {
- const id = event.nativeEvent.fileId;
- if (!id) return;
- setCollapsedIds((ids) =>
- ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id],
- );
- },
- [],
- );
+ const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) => {
+ const drawn = isNativeReviewDiffDrawEvent(event.nativeEvent);
+ const decoded =
+ event.nativeEvent.message === "rows-decoded" && event.nativeEvent.rows === data.rows.length;
+ if (!drawn && !decoded) return;
+ // Filtering replaces the native row payload asynchronously. Old draw events
+ // must not consume the file jump or highlight the new payload's row indices.
+ if (
+ typeof event.nativeEvent.totalRows === "number" &&
+ event.nativeEvent.totalRows !== data.rows.length
+ )
+ return;
+ if (drawn) updateVisibleRange(event);
+ if (
+ targetFile &&
+ !jumpStarted.current &&
+ nativeView.current &&
+ (Platform.OS !== "ios" || decoded)
+ ) {
+ jumpStarted.current = true;
+ if (focusIndex >= 0) return;
+ void nativeView.current.scrollToFile(targetFile.id, false).catch(() => {
+ jumpStarted.current = false;
+ });
+ return;
+ }
+ if (!drawn) return;
+ const lastRow = event.nativeEvent.lastRowIndex;
+ if (typeof lastRow === "number" && lastRow >= data.rows.length - 40) loadMore();
+ };
+ const onToggleFile: NonNullable<NativeReviewDiffViewProps["onToggleFile"]> = (event) => {
+ const id = event.nativeEvent.fileId;
+ if (!id) return;
+ setCollapsedIds((ids) =>
+ ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id],
+ );
+ };
const visibleFile = data.files.find((file) => file.id === visibleFileId) ?? targetFile;
const toggleTestFiles = () => {
setJumpPath(visibleFile?.path ?? route.params.path);
diff --git a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
index f45be6cf2ec..cfc18131873 100644
--- a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx
@@ -2,7 +2,7 @@ import { Toolbar } from "../../../components/ui/Toolbar";
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { FileDiffMetadata } from "@pierre/diffs";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
-import { useEffect, useMemo } from "react";
+import { useEffect } from "react";
import { Platform, Pressable, View } from "react-native";
import { AndroidScreenHeader } from "../../../components/ui/AndroidScreenHeader";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -102,19 +102,8 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps<GuideSto
const position = Math.max(0, Math.min(route.params.position, (guide?.stops.length ?? 1) - 1));
const stop = guide?.stops[Math.max(0, position)];
const diff = usePullRequestDiff(route.params);
- const excerptFiles = useMemo(() => {
- const files = new Map<string, FileDiffMetadata>();
- try {
- for (const patch of parsePatchFiles(diff.patch)) {
- for (const file of patch.files) {
- files.set(file.name, file);
- if (file.prevName) files.set(file.prevName, file);
- }
- }
- } catch {}
- return files;
- }, [diff.patch]);
- const wanted = useMemo(() => (stop ? stopFilePaths(stop) : []), [stop]);
+ const excerptFiles = diffFilesByPath(diff.patch);
+ const wanted = stop ? stopFilePaths(stop) : [];
const loadedPaths = new Set(
diff.parsed.kind === "files" ? diff.parsed.files.map((file) => file.path) : [],
);
@@ -332,3 +321,16 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps<GuideSto
</View>
);
}
+
+function diffFilesByPath(patchText: string): Map<string, FileDiffMetadata> {
+ const files = new Map<string, FileDiffMetadata>();
+ try {
+ for (const patch of parsePatchFiles(patchText)) {
+ for (const file of patch.files) {
+ files.set(file.name, file);
+ if (file.prevName) files.set(file.prevName, file);
+ }
+ }
+ } catch {}
+ return files;
+}
diff --git a/apps/mobile/src/features/pull-requests/guide/ReviewGuideExcerpt.tsx b/apps/mobile/src/features/pull-requests/guide/ReviewGuideExcerpt.tsx
index bff0affaab0..aa5f9e8d87f 100644
--- a/apps/mobile/src/features/pull-requests/guide/ReviewGuideExcerpt.tsx
+++ b/apps/mobile/src/features/pull-requests/guide/ReviewGuideExcerpt.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { Pressable, View } from "react-native";
import type { FileDiffMetadata } from "@pierre/diffs";
import type { PullRequestReviewGuideExcerpt } from "@t3tools/contracts";
@@ -28,19 +28,8 @@ export function ReviewGuideExcerpt({
}) {
const { nativeReviewDiffStyle, codeWordBreak } = useAppearanceCodeSurface();
const { themeAppearance } = useAppearancePreferences();
- const slice = useMemo(() => {
- try {
- if (!file) return "";
- return rowsToPatch(
- excerpt.path,
- file.prevName ?? excerpt.path,
- excerptRows(fileDiffRows(file), excerpt),
- );
- } catch {
- return "";
- }
- }, [file, excerpt]);
- const data = useMemo(() => {
+ const slice = excerptPatch(file, excerpt);
+ const data = (() => {
const parsed = buildNativeReviewDiffData(
buildReviewParsedDiff(slice, `guide:${excerpt.path}:${excerpt.start}`),
);
@@ -48,7 +37,7 @@ export function ReviewGuideExcerpt({
...parsed,
rows: parsed.rows.filter((row) => row.kind !== "file" && row.kind !== "hunk"),
};
- }, [slice, excerpt.path, excerpt.start]);
+ })();
const bridge = useNativeReviewDiffBridge({
threadKey: null,
sectionId: `guide:${excerpt.path}:${excerpt.start}`,
@@ -132,3 +121,19 @@ export function ReviewGuideExcerpt({
</View>
);
}
+
+function excerptPatch(
+ file: FileDiffMetadata | undefined,
+ excerpt: PullRequestReviewGuideExcerpt,
+): string {
+ if (!file) return "";
+ try {
+ return rowsToPatch(
+ excerpt.path,
+ file.prevName ?? excerpt.path,
+ excerptRows(fileDiffRows(file), excerpt),
+ );
+ } catch {
+ return "";
+ }
+}
diff --git a/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts b/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts
index e915804c651..5dad083e761 100644
--- a/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts
+++ b/apps/mobile/src/features/pull-requests/guide/useReviewGuide.ts
@@ -1,7 +1,8 @@
import { useAtomValue } from "@effect/atom-react";
import { useFocusEffect } from "@react-navigation/native";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
-import { useCallback, useRef, useState } from "react";
+import { AsyncResult } from "effect/reactivity";
+import { useRef, useState } from "react";
import { usePullRequestConnected } from "../usePullRequestConnected";
import { composerPullRequests } from "../../../state/pull-requests";
import { useEnvironmentQuery } from "../../../state/query";
@@ -33,29 +34,24 @@ export function useReviewGuide(params: PullRequestParams) {
const pending = useRef(false);
const running = starting || query.data?.run?._tag === "Running";
const refresh = query.refresh;
- useFocusEffect(
- useCallback(() => {
- if (!enabled) return;
- refresh();
- if (!running) return;
- const timer = setInterval(refresh, 5_000);
- return () => clearInterval(timer);
- }, [enabled, refresh, running]),
- );
+ useFocusEffect(() => {
+ if (!enabled) return;
+ refresh();
+ if (!running) return;
+ const timer = setInterval(refresh, 5_000);
+ return () => clearInterval(timer);
+ });
const write = async () => {
if (!enabled || !canWrite || running || pending.current) return;
pending.current = true;
setStarting(true);
setError(null);
- try {
- const result = await generate(target);
- if (result._tag === "Failure") {
- const cause = squashAtomCommandFailure(result);
- setError(cause instanceof Error ? cause.message : "Could not start the review guide.");
- }
- } finally {
- pending.current = false;
- setStarting(false);
+ const result = await generate(target);
+ pending.current = false;
+ setStarting(false);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
+ setError(cause instanceof Error ? cause.message : "Could not start the review guide.");
}
};
return { ...query, enabled, canWrite, running, write, startError: error };
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestAction.ts b/apps/mobile/src/features/pull-requests/usePullRequestAction.ts
index 017d02e9f26..68f7879546d 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestAction.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestAction.ts
@@ -1,3 +1,4 @@
+import { AsyncResult } from "effect/reactivity";
import * as Dialog from "../../components/ui/Dialog";
import { useAtomRefresh } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
@@ -27,23 +28,22 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD
if (pending.current || !available(action)) return;
pending.current = true;
setBusy(true);
- try {
- const response = await run({
- ...target,
- input: { ...target.input, action, ...(updateMethod ? { updateMethod } : {}) },
- });
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
- refreshDetail();
- refreshActivity();
- } catch (cause) {
+ const response = await run({
+ ...target,
+ input: { ...target.input, action, ...(updateMethod ? { updateMethod } : {}) },
+ });
+ pending.current = false;
+ setBusy(false);
+ if (AsyncResult.isFailure(response)) {
+ const cause = squashAtomCommandFailure(response);
Dialog.alert(
"Couldn't update this pull request",
cause instanceof Error ? cause.message : "Try again.",
);
- } finally {
- pending.current = false;
- setBusy(false);
+ return;
}
+ refreshDetail();
+ refreshActivity();
};
const confirm = (action: PullRequestAction, title: string, message: string) =>
Dialog.alert(title, message, [
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts b/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
index 473202c28a0..db7dda5ba7a 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
@@ -1,10 +1,14 @@
import * as Dialog from "../../components/ui/Dialog";
import { RegistryContext, useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
-import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import {
+ executeAtomQuery,
+ settlePromise,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestAction } from "@t3tools/contracts";
-import { Atom } from "effect/reactivity";
-import { use, useCallback, useMemo, useRef, useState } from "react";
+import { Atom, AsyncResult } from "effect/reactivity";
+import { use, useRef, useState } from "react";
import { Linking, Platform } from "react-native";
import type { MenuProps } from "../../components/ui/Menu.types";
import { composerPullRequests } from "../../state/pull-requests";
@@ -30,172 +34,161 @@ export function usePullRequestListActions(
const navigation = useNavigation();
const selectAndroidWorkspace = useAndroidWorkspaceSelection();
const permissionKey = JSON.stringify(environmentIds);
- const permissionAtom = useMemo(() => {
+ const permissionAtom = (() => {
const ids: readonly EnvironmentId[] = JSON.parse(permissionKey);
return Atom.make(
(get) => new Set(ids.filter((id) => get(composerPullRequests.runAction.permissionAtom(id)))),
);
- }, [permissionKey]);
+ })();
const writableEnvironments = useAtomValue(permissionAtom);
const run = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
const pending = useRef(false);
const [busyKey, setBusyKey] = useState<string | null>(null);
- const params = useCallback(
- (entry: EnvironmentPullRequestListEntry) => ({
- environmentId: String(entry.environmentId),
- projectId: String(entry.projectId),
- host: entry.host,
- repository: entry.repository,
- number: entry.number,
- initialSummary: entry,
- }),
- [],
- );
- const perform = useCallback(
- async (
- entry: EnvironmentPullRequestListEntry,
- action: PullRequestAction | "request-review",
- ) => {
- const { environmentId } = entry;
- if (pending.current) return;
- pending.current = true;
- setBusyKey(scopedPullRequestListKey(entry));
- try {
- const target = pullRequestTarget(params(entry));
- // List rows do not subscribe to expensive detail reads.
- const response = await executeAtomQuery(registry, composerPullRequests.detail(target), {
- refresh: true,
- reportFailure: false,
- });
- if (response._tag === "Failure") throw squashAtomCommandFailure(response);
- const pr = response.value;
- if (action === "request-review") {
- if (
- !registry.get(composerPullRequests.requestReviewers.permissionAtom(environmentId)) ||
- pr.state !== "open" ||
- !pr.capabilities.reviewers.request ||
- !pr.viewerPermissions.requestReviewers
- )
- throw new Error("Review requests aren't available for this pull request.");
- if (Platform.OS === "android") {
- selectAndroidWorkspace({ name: "PullRequest", params: params(entry) }, params(entry));
- } else navigation.navigate("PullRequestReviewers", params(entry));
- return;
- }
+ const params = (entry: EnvironmentPullRequestListEntry) => ({
+ environmentId: String(entry.environmentId),
+ projectId: String(entry.projectId),
+ host: entry.host,
+ repository: entry.repository,
+ number: entry.number,
+ initialSummary: entry,
+ });
+ const perform = async (
+ entry: EnvironmentPullRequestListEntry,
+ action: PullRequestAction | "request-review",
+ ) => {
+ const { environmentId } = entry;
+ if (pending.current) return;
+ pending.current = true;
+ setBusyKey(scopedPullRequestListKey(entry));
+ const result = await settlePromise(async () => {
+ const target = pullRequestTarget(params(entry));
+ // List rows do not subscribe to expensive detail reads.
+ const response = await executeAtomQuery(registry, composerPullRequests.detail(target), {
+ refresh: true,
+ reportFailure: false,
+ });
+ if (response._tag === "Failure") throw squashAtomCommandFailure(response);
+ const pr = response.value;
+ if (action === "request-review") {
if (
- !registry.get(composerPullRequests.runAction.permissionAtom(environmentId)) ||
- !canPerformPullRequestAction(pr, action)
+ !registry.get(composerPullRequests.requestReviewers.permissionAtom(environmentId)) ||
+ pr.state !== "open" ||
+ !pr.capabilities.reviewers.request ||
+ !pr.viewerPermissions.requestReviewers
)
- throw new Error("This action isn't available for this pull request.");
- const result = await run({ ...target, input: { ...target.input, action } });
- if (result._tag === "Failure") throw squashAtomCommandFailure(result);
- onChanged(
- entry,
- action === "close"
- ? { state: "closed" }
- : action === "reopen"
- ? { state: "open" }
- : { isDraft: action === "draft" },
- );
- } catch (cause) {
- Dialog.alert(
- "Couldn't update this pull request",
- cause instanceof Error ? cause.message : "Try again.",
- );
- } finally {
- pending.current = false;
- setBusyKey(null);
- }
- },
- [registry, navigation, params, run, onChanged, selectAndroidWorkspace],
- );
- const select = useCallback(
- (entry: EnvironmentPullRequestListEntry, action: string) => {
- if (action === "open") {
- if (Platform.OS === "android")
- selectAndroidWorkspace({ name: "PullRequest", params: params(entry) });
- else navigation.navigate("PullRequest", params(entry));
- return;
- }
- if (action === "request-review") {
- void perform(entry, action);
- return;
- }
- if (action === "copy") {
- copyPullRequestLink(entry);
- return;
- }
- if (action === "provider") {
- void Linking.openURL(entry.url);
- return;
- }
- if (action === "share") {
- sharePullRequestLink(entry);
+ throw new Error("Review requests aren't available for this pull request.");
+ if (Platform.OS === "android") {
+ selectAndroidWorkspace({ name: "PullRequest", params: params(entry) }, params(entry));
+ } else navigation.navigate("PullRequestReviewers", params(entry));
return;
}
- const supported = (["close", "reopen", "ready", "draft"] as const).find(
- (value) => value === action,
+ if (
+ !registry.get(composerPullRequests.runAction.permissionAtom(environmentId)) ||
+ !canPerformPullRequestAction(pr, action)
+ )
+ throw new Error("This action isn't available for this pull request.");
+ const result = await run({ ...target, input: { ...target.input, action } });
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ onChanged(
+ entry,
+ action === "close"
+ ? { state: "closed" }
+ : action === "reopen"
+ ? { state: "open" }
+ : { isDraft: action === "draft" },
);
- if (!supported) return;
- Dialog.alert(`${PR_ACTION_LABELS[supported]}?`, `#${entry.number} · ${entry.title}`, [
- { text: "Cancel", style: "cancel" },
- {
- text: PR_ACTION_LABELS[supported],
- style: supported === "close" ? "destructive" : "default",
- onPress: () => void perform(entry, supported),
- },
- ]);
- },
- [navigation, params, perform, selectAndroidWorkspace],
- );
- const actions = useCallback(
- (entry: EnvironmentPullRequestListEntry): MenuProps["actions"] => [
+ });
+ pending.current = false;
+ setBusyKey(null);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
+ Dialog.alert(
+ "Couldn't update this pull request",
+ cause instanceof Error ? cause.message : "Try again.",
+ );
+ }
+ };
+ const select = (entry: EnvironmentPullRequestListEntry, action: string) => {
+ if (action === "open") {
+ if (Platform.OS === "android")
+ selectAndroidWorkspace({ name: "PullRequest", params: params(entry) });
+ else navigation.navigate("PullRequest", params(entry));
+ return;
+ }
+ if (action === "request-review") {
+ void perform(entry, action);
+ return;
+ }
+ if (action === "copy") {
+ copyPullRequestLink(entry);
+ return;
+ }
+ if (action === "provider") {
+ void Linking.openURL(entry.url);
+ return;
+ }
+ if (action === "share") {
+ sharePullRequestLink(entry);
+ return;
+ }
+ const supported = (["close", "reopen", "ready", "draft"] as const).find(
+ (value) => value === action,
+ );
+ if (!supported) return;
+ Dialog.alert(`${PR_ACTION_LABELS[supported]}?`, `#${entry.number} · ${entry.title}`, [
+ { text: "Cancel", style: "cancel" },
{
- id: "open",
- title: "Open pull request",
- image: Platform.OS === "ios" ? "arrow.up.right" : "open_in_new",
+ text: PR_ACTION_LABELS[supported],
+ style: supported === "close" ? "destructive" : "default",
+ onPress: () => void perform(entry, supported),
},
- ...(writableEnvironments.has(entry.environmentId) && entry.state === "open"
+ ]);
+ };
+ const actions = (entry: EnvironmentPullRequestListEntry): MenuProps["actions"] => [
+ {
+ id: "open",
+ title: "Open pull request",
+ image: Platform.OS === "ios" ? "arrow.up.right" : "open_in_new",
+ },
+ ...(writableEnvironments.has(entry.environmentId) && entry.state === "open"
+ ? [
+ {
+ id: "request-review",
+ title: "Request review",
+ image: Platform.OS === "ios" ? "person.badge.plus" : "person_add",
+ },
+ {
+ id: entry.isDraft ? "ready" : "draft",
+ title: entry.isDraft ? "Mark ready for review" : "Convert to draft",
+ image: Platform.OS === "ios" ? "pencil" : "edit",
+ },
+ {
+ id: "close",
+ title: "Close pull request",
+ image: Platform.OS === "ios" ? "xmark" : "close",
+ attributes: { destructive: true },
+ },
+ ]
+ : writableEnvironments.has(entry.environmentId) && entry.state === "closed"
? [
{
- id: "request-review",
- title: "Request review",
- image: Platform.OS === "ios" ? "person.badge.plus" : "person_add",
- },
- {
- id: entry.isDraft ? "ready" : "draft",
- title: entry.isDraft ? "Mark ready for review" : "Convert to draft",
- image: Platform.OS === "ios" ? "pencil" : "edit",
- },
- {
- id: "close",
- title: "Close pull request",
- image: Platform.OS === "ios" ? "xmark" : "close",
- attributes: { destructive: true },
+ id: "reopen",
+ title: "Reopen pull request",
+ image: Platform.OS === "ios" ? "arrow.clockwise" : "refresh",
},
]
- : writableEnvironments.has(entry.environmentId) && entry.state === "closed"
- ? [
- {
- id: "reopen",
- title: "Reopen pull request",
- image: Platform.OS === "ios" ? "arrow.clockwise" : "refresh",
- },
- ]
- : []),
- {
- id: "share",
- title: "Share…",
- image: Platform.OS === "ios" ? "square.and.arrow.up" : "share",
- },
- { id: "copy", title: "Copy link", image: Platform.OS === "ios" ? "link" : "link" },
- {
- id: "provider",
- title: openOnProviderLabel(entry.provider),
- image: Platform.OS === "ios" ? "safari" : "open_in_browser",
- },
- ],
- [writableEnvironments],
- );
+ : []),
+ {
+ id: "share",
+ title: "Share…",
+ image: Platform.OS === "ios" ? "square.and.arrow.up" : "share",
+ },
+ { id: "copy", title: "Copy link", image: Platform.OS === "ios" ? "link" : "link" },
+ {
+ id: "provider",
+ title: openOnProviderLabel(entry.provider),
+ image: Platform.OS === "ios" ? "safari" : "open_in_browser",
+ },
+ ];
return { actions, select, busyKey };
}
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts b/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts
index c2ad4bd5cc6..6b97390908a 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts
@@ -1,6 +1,5 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/reactivity";
-import { useCallback } from "react";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList";
@@ -12,36 +11,37 @@ export function usePullRequestListControls() {
? preferences.value.pullRequestListFilters
: undefined;
const environmentId = saved?.environmentId ?? null;
- const controlsFor = useCallback(
- (environment: string | null) => saved?.controls[environment ?? ""] ?? DEFAULT_PR_LIST_CONTROLS,
- [saved],
- );
- const setEnvironmentId = useCallback(
- (next: string | null) =>
- savePreferences({
- transform: (current) => ({
- pullRequestListFilters: {
- controls: current.pullRequestListFilters?.controls ?? {},
- environmentId: next,
- },
- }),
+ const controlsFor = (environment: string | null) =>
+ saved?.controls[environment ?? ""] ?? DEFAULT_PR_LIST_CONTROLS;
+ const setEnvironmentId = (next: string | null) =>
+ savePreferences({
+ transform: (current) => ({
+ pullRequestListFilters: {
+ controls: current.pullRequestListFilters?.controls ?? {},
+ environmentId: next,
+ },
}),
- [savePreferences],
- );
- const setControls = useCallback(
- (environment: string | null, controls: PullRequestListControls) =>
- savePreferences({
- transform: (current) => ({
- pullRequestListFilters: {
- environmentId: current.pullRequestListFilters?.environmentId ?? null,
- controls: {
- ...current.pullRequestListFilters?.controls,
- [environment ?? ""]: controls,
- },
- },
- }),
+ });
+ const setControls = (environment: string | null, controls: PullRequestListControls) =>
+ savePreferences({
+ transform: (current) => ({
+ pullRequestListFilters: {
+ environmentId: current.pullRequestListFilters?.environmentId ?? null,
+ controls: withEnvironmentControls(
+ current.pullRequestListFilters?.controls,
+ environment ?? "",
+ controls,
+ ),
+ },
}),
- [savePreferences],
- );
+ });
return { environmentId, controlsFor, setEnvironmentId, setControls } as const;
}
+
+function withEnvironmentControls(
+ saved: Readonly<Record<string, PullRequestListControls>> | undefined,
+ environment: string,
+ controls: PullRequestListControls,
+): Record<string, PullRequestListControls> {
+ return { ...saved, [environment]: controls };
+}
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
index f4690968a32..225db014749 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
@@ -1,3 +1,5 @@
+import { AsyncResult } from "effect/reactivity";
+import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Dialog from "../../components/ui/Dialog";
import { useNavigation, useNavigationState, useRoute } from "@react-navigation/native";
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
@@ -83,7 +85,7 @@ export function usePullRequestThreads(
if (!pr || !canAsk || pending.current) return;
pending.current = true;
setBusy(true);
- try {
+ const result = await settlePromise(async () => {
if (connected && !thread && !canCheckout)
throw new Error("Starting work from this PR requires source control write access.");
await waitForComposerDraftsLoaded();
@@ -148,11 +150,12 @@ export function usePullRequestThreads(
screen: "NewTaskDraft",
params: { draftId: draftKey, title: `Ask about #${pr.number}` },
});
- } catch (cause) {
+ });
+ pending.current = false;
+ setBusy(false);
+ if (AsyncResult.isFailure(result)) {
+ const cause = squashAtomCommandFailure(result);
Dialog.alert("Couldn't open a thread", cause instanceof Error ? cause.message : "Try again.");
- } finally {
- pending.current = false;
- setBusy(false);
}
};
return {
diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts
index 7d47342f70c..2e50626ac36 100644
--- a/apps/mobile/src/reactCompilerCoverage.test.ts
+++ b/apps/mobile/src/reactCompilerCoverage.test.ts
@@ -28,19 +28,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {
"src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
"src/features/home/thread-swipe-actions.tsx": "ref read during render",
"src/features/projects/AddProjectScreen.tsx": "try without catch",
- "src/features/pull-requests/PullRequestDiscussionScreen.tsx": "try/finally",
- "src/features/pull-requests/PullRequestInlineCommentScreen.tsx": "try without catch",
- "src/features/pull-requests/PullRequestMergeControls.tsx": "throw inside try, try/finally",
- "src/features/pull-requests/PullRequestReviewSheet.tsx": "try/finally",
- "src/features/pull-requests/PullRequestReviewersScreen.tsx": "throw inside try, try/finally",
- "src/features/pull-requests/PullRequestRouteScreen.tsx": "manual memo not preserved",
- "src/features/pull-requests/guide/PullRequestGuideScreen.tsx": "conditional inside try",
- "src/features/pull-requests/guide/ReviewGuideExcerpt.tsx": "conditional inside try",
- "src/features/pull-requests/guide/useReviewGuide.ts": "try without catch",
- "src/features/pull-requests/usePullRequestAction.ts": "throw inside try, try/finally",
- "src/features/pull-requests/usePullRequestListActions.ts": "throw inside try, try/finally",
- "src/features/pull-requests/usePullRequestListControls.ts": "unsupported syntax",
- "src/features/pull-requests/usePullRequestThreads.ts": "throw inside try, try/finally",
"src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
"src/features/threads/NewTaskContextPickerScreens.tsx":
"manual memo not preserved, try without catch",