Open History to see the last commit
1import { useAtomCommand } from "~/state/use-atom-command";
2import type { EnvironmentId, PullRequestRef, PullRequestReviewVerdict } from "@t3tools/contracts";
3import { CheckIcon, MessageSquareIcon, XCircleIcon } from "lucide-react";
4import { msg, useGT, useMessages } from "gt-react";
5import { useEffect, useState, type ReactNode, type RefObject } from "react";
6
7import { m } from "~/i18n/messages";
8
9import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFieldSpeech";
10import { pullRequestEnvironment } from "~/state/pullRequests";
11import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
12
13import { isCommentSubmitShortcut } from "../diffs/commentSubmitShortcut";
14import { Button } from "../ui/button";
15import { Select, SelectItem, SelectPopup, SelectTrigger } from "../ui/select";
16import { toastManager } from "../ui/toast";
17import { readableFailure } from "./pullRequestDetail.logic";
18import {
19 pullRequestReviewKey,
20 usePendingReviewComments,
21 usePullRequestReviewStore,
22} from "./pullRequestReviewStore";
23import {
24 PullRequestMarkdownTextarea,
25 type PullRequestCompletionScope,
26} from "./PullRequestMarkdownTextarea";
27
28import type { ChangeRequestTermKind } from "./changeRequestTerm";
29
30const VERDICTS: ReadonlyArray<{
31 readonly value: PullRequestReviewVerdict;
32 readonly label: string;
33 readonly sent: (term: ChangeRequestTermKind) => string;
34 readonly icon: ReactNode;
35}> = [
36 {
37 value: "comment",
38 label: msg("Comment", { $context: "review verdict" }),
39 sent: () => m(msg("Review submitted")),
40 icon: <MessageSquareIcon className="size-3" />,
41 },
42 {
43 value: "approve",
44 label: msg("Approve", { $context: "review verdict" }),
45 sent: (term) =>
46 m(
47 msg(
48 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} approved",
49 { term },
50 ),
51 ),
52 icon: <CheckIcon className="size-3" />,
53 },
54 {
55 value: "request-changes",
56 label: msg("Request changes"),
57 sent: () => m(msg("Changes requested")),
58 icon: <XCircleIcon className="size-3" />,
59 },
60];
61
62export function PullRequestReviewForm({
63 environmentId,
64 active,
65 reference,
66 headSha,
67 completionScope,
68 term,
69 verdicts,
70 requestChangesSummaryRequired,
71 textareaRef,
72 pending,
73 onPendingChange,
74 onSubmitted,
75 onRefused,
76}: {
77 environmentId: EnvironmentId;
78 /** False while the form stays mounted but hidden; dictation is cancelled then. */
79 active: boolean;
80 reference: PullRequestRef;
81 /** The head on screen, which the review is pinned to. */
82 headSha: string | undefined;
83 completionScope: PullRequestCompletionScope | null;
84 term: ChangeRequestTermKind;
85 verdicts: ReadonlyArray<PullRequestReviewVerdict>;
86 requestChangesSummaryRequired: boolean;
87 textareaRef: RefObject<HTMLTextAreaElement | null>;
88 pending: boolean;
89 onPendingChange: (pending: boolean) => void;
90 onSubmitted: () => void;
91 onRefused: () => void;
92}) {
93 const gt = useGT();
94 const resolve = useMessages();
95 const [requestedVerdict, setRequestedVerdict] = useState<PullRequestReviewVerdict>("comment");
96 const comments = usePendingReviewComments(reference);
97 const reviewKey = pullRequestReviewKey(reference);
98 const body = usePullRequestReviewStore((store) => store.summaries[reviewKey] ?? "");
99 const removeComments = usePullRequestReviewStore((store) => store.removeComments);
100 const setSummary = usePullRequestReviewStore((store) => store.setSummary);
101 const speech = useTextFieldSpeech({
102 environmentId,
103 projectId: reference.projectId,
104 ownerKey: JSON.stringify(["pr-review", environmentId, reviewKey]),
105 text: body,
106 textareaRef,
107 onTextChange: (text) => setSummary(reviewKey, text),
108 disabled: !active || pending,
109 });
110 const { cancel } = speech;
111 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- discards a recording when the hidden form can no longer be submitted
112 useEffect(() => {
113 if (!active) cancel();
114 }, [active, cancel]);
115 const clearSummary = usePullRequestReviewStore((store) => store.clearSummary);
116 const submitReview = useAtomCommand(pullRequestEnvironment.submitReview, {
117 reportFailure: false,
118 });
119
120 const offered = VERDICTS.filter((verdict) => verdicts.includes(verdict.value));
121 const selectedVerdict =
122 offered.find((verdict) => verdict.value === requestedVerdict) ?? offered[0];
123
124 const submit = async (verdict: (typeof VERDICTS)[number], text: string) => {
125 const submittedComments = usePullRequestReviewStore.getState().drafts[reviewKey] ?? [];
126 if (pending || !canSubmit(verdict.value, text, submittedComments.length)) return;
127 const submittedBody = text;
128 onPendingChange(true);
129 const result = await submitReview({
130 environmentId,
131 input: {
132 ...reference,
133 ...(headSha === undefined ? {} : { expectedHeadSha: headSha }),
134 verdict: verdict.value,
135 body: submittedBody,
136 comments: submittedComments,
137 },
138 });
139 onPendingChange(false);
140 if (result._tag === "Failure") {
141 toastManager.add({
142 type: "error",
143 title: m(msg("The review could not be submitted")),
144 description: readableFailure(
145 squashAtomCommandFailure(result),
146 m(msg("The host refused the review. Your draft is still here to try again.")),
147 ),
148 });
149 onRefused();
150 return;
151 }
152 // Preserve comments and summary edits made during submission.
153 removeComments(
154 reviewKey,
155 submittedComments.map((comment) => comment.id),
156 );
157 clearSummary(reviewKey, submittedBody);
158 toastManager.add({ type: "success", title: verdict.sent(term) });
159 onSubmitted();
160 };
161
162 // Forgejo requires a summary when requesting changes, even with inline comments.
163 const canSubmit = (verdict: PullRequestReviewVerdict, summary: string, commentCount: number) =>
164 verdict === "request-changes" && requestChangesSummaryRequired
165 ? summary.trim().length > 0
166 : verdict === "approve" || summary.trim().length > 0 || commentCount > 0;
167 const placeholder =
168 selectedVerdict === undefined || canSubmit(selectedVerdict.value, "", comments.length)
169 ? gt("Summarize your review (optional)")
170 : selectedVerdict.value === "request-changes" && requestChangesSummaryRequired
171 ? gt("Summarize your review (required to request changes)")
172 : gt("Summarize your review or add line comments");
173
174 return (
175 <>
176 <PullRequestMarkdownTextarea
177 ref={textareaRef}
178 completionScope={completionScope}
179 rows={3}
180 readOnly={speech.freezesEditor}
181 value={body}
182 placeholder={placeholder}
183 aria-label={gt("Review summary")}
184 onValueChange={(next) => setSummary(reviewKey, next)}
185 onKeyDown={(event) => {
186 if (event.nativeEvent.isComposing || event.keyCode === 229 || event.repeat) return;
187 if (
188 selectedVerdict !== undefined &&
189 isCommentSubmitShortcut(event, body, pending || speech.preparing, true)
190 ) {
191 event.preventDefault();
192 event.stopPropagation();
193 speech.submitAfterDictation((text) => void submit(selectedVerdict, text));
194 }
195 }}
196 />
197 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
198 <TextFieldSpeechControls speech={speech} disabled={pending} />
199 {offered.length > 1 ? (
200 <Select
201 value={selectedVerdict?.value ?? null}
202 disabled={pending}
203 onValueChange={(value) => {
204 if (value !== null) setRequestedVerdict(value);
205 }}
206 >
207 <SelectTrigger size="xs" className="w-auto min-w-0" aria-label={gt("Review verdict")}>
208 <span className="flex items-center gap-1.5">
209 {selectedVerdict?.icon}
210 {selectedVerdict ? resolve(selectedVerdict.label) : null}
211 </span>
212 </SelectTrigger>
213 <SelectPopup side="top" alignItemWithTrigger={false}>
214 {offered.map((verdict) => (
215 <SelectItem key={verdict.value} value={verdict.value}>
216 <span className="flex items-center gap-1.5">
217 {verdict.icon}
218 {resolve(verdict.label)}
219 </span>
220 </SelectItem>
221 ))}
222 </SelectPopup>
223 </Select>
224 ) : null}
225 <Button
226 size="xs"
227 disabled={
228 speech.preparing ||
229 pending ||
230 selectedVerdict === undefined ||
231 (!canSubmit(selectedVerdict.value, body, comments.length) && !speech.blocksSubmission)
232 }
233 onClick={() => {
234 if (selectedVerdict !== undefined)
235 speech.submitAfterDictation((text) => void submit(selectedVerdict, text));
236 }}
237 >
238 {pending ? gt("Submitting...") : gt("Submit review")}
239 </Button>
240 </div>
241 </>
242 );
243}