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