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

PullRequestReviewSheet.tsx

254 lines10.3 KB

1import { AsyncResult } from "effect/reactivity";
2import { useAtomRefresh } from "@effect/atom-react";
3import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
4import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6import type { PullRequestReviewVerdict } from "@t3tools/contracts";
7import { useRef, useState } from "react";
8import { useFocusEffect } from "@react-navigation/native";
9import { Platform, Pressable, View } from "react-native";
10import { clearSubmittedReview } from "./pullRequestReviewDrafts";
11import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft";
12import { reviewPositionLabel } from "./pullRequestDiffComments";
13import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
14import { Button } from "../../components/ui/Button";
15import { SegmentedControl } from "../../components/ui/SegmentedControl";
16import { composerPullRequests } from "../../state/pull-requests";
17import { useEnvironmentQuery } from "../../state/query";
18import { useAtomCommand } from "../../state/use-atom-command";
19import { PullRequestSheetContent as SheetContent } from "./PullRequestSheetContent";
20import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
21import { usePullRequestPermissions } from "./usePullRequestPermissions";
22​
23function useActionSubmission(params: PullRequestParams) {
24 const navigation = useNavigation();
25 const refreshDetail = useAtomRefresh(composerPullRequests.detail(pullRequestTarget(params)));
26 const refreshActivity = useAtomRefresh(composerPullRequests.activity(pullRequestTarget(params)));
27 const pending = useRef(false);
28 const [busy, setBusy] = useState(false);
29 const [error, setError] = useState<string | null>(null);
30 const submit = async (operation: () => Promise<void>) => {
31 if (pending.current) return;
32 pending.current = true;
33 setBusy(true);
34 setError(null);
35 const result = await settlePromise(async () => {
36 await operation();
37 refreshDetail();
38 refreshActivity();
39 navigation.goBack();
40 });
41 pending.current = false;
42 setBusy(false);
43 if (AsyncResult.isFailure(result)) {
44 const cause = squashAtomCommandFailure(result);
45 setError(
46 cause instanceof Error
47 ? cause.message
48 : "The provider could not complete this action. Try again.",
49 );
50 }
51 };
52 return { busy, error, submit };
54​
55const VERDICTS = [
56 { value: "comment", title: "Comment" },
57 { value: "approve", title: "Approve" },
58 {
59 value: "request-changes",
60 title: "Request changes",
61 },
62] as const;
63​
64export function PullRequestReviewSheet({
65 route,
66}: StaticScreenProps<PullRequestParams & { readonly mode: "review" | "comment" }>) {
67 const params = route.params;
68 const target = pullRequestTarget(params);
69 const result = useEnvironmentQuery(composerPullRequests.detail(target));
70 const { refresh: refreshDetail } = result;
71 useFocusEffect(() => refreshDetail());
72 const permissions = usePullRequestPermissions(params, result.data);
73 const submission = useActionSubmission(params);
74 const review = useAtomCommand(composerPullRequests.submitReview, { reportFailure: false });
75 const comment = useAtomCommand(composerPullRequests.comment, { reportFailure: false });
76 const navigation = useNavigation();
77 const store = usePullRequestReviewDraft(params);
78 const body = params.mode === "review" ? store.draft.summary : store.draft.comment;
79 const setBody = (body: string) =>
80 store.update((draft) => ({
81 ...draft,
82 ...(params.mode === "review" ? { summary: body } : { comment: body }),
83 }));
84 const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha);
85 const [requestedVerdict, setRequestedVerdict] = useState<PullRequestReviewVerdict>("comment");
86 const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value));
87 const verdict = offered.find((option) => option.value === requestedVerdict) ?? offered[0];
88 const reviewing = params.mode === "review";
89 const canSubmitComments = !store.draft.comments.length || permissions.canInlineComment;
90 // Forgejo requires a summary when requesting changes, even with inline comments.
91 const summaryRequired =
92 verdict !== undefined && result.data
93 ? sourceControlClients.get(result.data.provider).reviewSummaryRequired(verdict.value)
94 : false;
95 const canSubmit =
96 store.ready &&
97 (!reviewing || (!stale && canSubmitComments)) &&
98 (reviewing
99 ? verdict !== undefined &&
100 (summaryRequired
101 ? body.trim().length > 0
102 : verdict.value === "approve" ||
103 body.trim().length > 0 ||
104 store.draft.comments.length > 0)
105 : permissions.canComment && body.trim().length > 0);
106 const perform = () =>
107 submission.submit(async () => {
108 if (!canSubmit)
109 throw new Error("Add your feedback and check your permissions before submitting.");
110 const submitted = store.draft;
111 const response =
112 reviewing && verdict
113 ? await review({
114 ...target,
115 input: {
116 ...target.input,
117 verdict: verdict.value,
118 body,
119 comments: submitted.comments.map(
120 ({ id: _id, headSha: _sha, code: _code, ...comment }) => comment,
121 ),
122 },
123 })
124 : await comment({ ...target, input: { ...target.input, body } });
125 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
126 store.update((current) =>
127 reviewing
128 ? clearSubmittedReview(current, submitted)
129 : { ...current, comment: current.comment === submitted.comment ? "" : current.comment },
130 );
131 await store.flush();
132 });
133 return (
134 <SheetContent
135 title={reviewing ? "Submit review" : "Add comment"}
136 subtitle={`#${params.number}${reviewing && result.data?.headSha ? ` · reviewing ${result.data.headSha.slice(0, 7)}` : ` · ${params.repository}`}`}
137 busy={submission.busy}
138 footer={
139 <Button
140 label={
141 submission.busy
142 ? "Submitting…"
143 : reviewing
144 ? verdict?.value === "approve"
145 ? "Approve"
146 : verdict?.value === "request-changes"
147 ? "Request changes"
148 : "Submit review"
149 : "Post comment"
150 }
151 fullWidth
152 tone={Platform.OS === "android" ? "primary" : "contrast"}
153 loading={submission.busy}
154 disabled={!canSubmit || result.isPending || result.error !== null}
155 onPress={() => void perform()}
156 />
157 }
158 >
159 {reviewing && offered.length > 1 ? (
160 <SegmentedControl
161 options={offered.map((option) => ({ value: option.value, label: option.title }))}
162 selected={verdict?.value ?? "comment"}
163 onSelect={(value) => {
164 if (!submission.busy) setRequestedVerdict(value);
165 }}
166 size="compact"
167 />
168 ) : null}
169 <Text className="px-4 text-xs text-foreground-muted">
170 {reviewing ? "Summary" : "Comment"}
171 </Text>
172 <TextInput
173 multiline
174 accessibilityLabel={reviewing ? "Review summary" : "Comment"}
175 placeholder={
176 reviewing
177 ? summaryRequired
178 ? "Summary required to request changes…"
179 : "Summarize your review…"
180 : "Write a comment…"
181 }
182 placeholderTextColorClassName="accent-foreground-muted"
183 editable={store.ready && !submission.busy}
184 value={body}
185 maxLength={65536}
186 onChangeText={setBody}
187 className="min-h-36 rounded-[20px] bg-grouped-card p-4 text-base text-foreground"
188 style={{ textAlignVertical: "top" }}
189 />
190 {reviewing && store.draft.comments.length ? (
191 <View className="gap-2">
192 <Text className="text-sm font-t3-medium">
193 {store.draft.comments.length} pending line{" "}
194 {store.draft.comments.length === 1 ? "comment" : "comments"}
195 </Text>
196 {store.draft.comments.map((draft) => (
197 <Pressable
198 key={draft.id}
199 accessibilityRole="button"
200 disabled={submission.busy}
201 onPress={() => {
202 const outdated = draft.headSha !== result.data?.headSha;
203 if (outdated)
204 navigation.dispatch(
205 StackActions.replace("PullRequestFile", {
206 ...params,
207 path: draft.path,
208 replacingDraftId: draft.id,
209 }),
210 );
211 else
212 navigation.dispatch(
213 StackActions.replace("PullRequestInlineComment", {
214 ...params,
215 ...draft,
216 draftId: draft.id,
217 }),
218 );
219 }}
220 className="gap-1 rounded-[20px] bg-grouped-card p-4"
221 >
222 <Text className="font-mono text-xs text-foreground-muted">
223 {draft.path} · {reviewPositionLabel(draft.position)}
224 </Text>
225 <Text numberOfLines={3} className="text-sm">
226 {draft.body}
227 </Text>
228 <Text className="text-2xs text-foreground-muted">
229 {draft.headSha !== result.data?.headSha
230 ? "Branch changed · Tap to choose a new line"
231 : "Tap to edit"}
232 </Text>
233 </Pressable>
234 ))}
235 </View>
236 ) : null}
237 {reviewing && stale ? (
238 <Text className="text-sm text-danger-foreground">
239 The branch changed since you wrote a comment. Choose its current line before submitting.
240 </Text>
241 ) : null}
242 {reviewing && !canSubmitComments ? (
243 <Text className="text-sm text-danger-foreground">
244 You can no longer submit line comments on this pull request. Your drafts are kept here.
245 </Text>
246 ) : null}
247 {submission.error || result.error || store.error ? (
248 <Text selectable className="text-sm text-danger-foreground">
249 {submission.error ?? result.error ?? store.error}
250 </Text>
251 ) : null}
252 </SheetContent>
253 );