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