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

PullRequestReviewForm.tsx

225 lines8.2 KB

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