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

PullRequestReviewForm.tsx

247 lines8.8 KB

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