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

PullRequestCommentForm.tsx

188 lines6.6 KB

1import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2import { useAtomCommand } from "~/state/use-atom-command";
3import type { EnvironmentId, PullRequestDetailView, PullRequestRef } from "@t3tools/contracts";
4import { SendIcon } from "lucide-react";
5import { useEffect, useState, type RefObject } from "react";
6​
7import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFieldSpeech";
8import { pullRequestEnvironment } from "~/state/pullRequests";
9​
10import { Button } from "../ui/button";
11import { toastManager } from "../ui/toast";
12import { PullRequestGlyph } from "./pullRequestIcons";
13import {
14 PullRequestMarkdownTextarea,
15 pullRequestCompletionScope,
16} from "./PullRequestMarkdownTextarea";
17import { pullRequestReviewKey } from "./pullRequestReviewStore";
18import { useInlineActionConfirm } from "./useInlineActionConfirm";
19​
20export function PullRequestCommentForm({
21 environmentId,
22 active,
23 reference,
24 detail,
25 actionPending,
26 textareaRef,
27 onCommentAction,
28 onCommented,
29 onClose,
30}: {
31 environmentId: EnvironmentId;
32 /** False while the form stays mounted but hidden; dictation is cancelled then. */
33 active: boolean;
34 reference: PullRequestRef;
35 detail: PullRequestDetailView;
36 actionPending: boolean;
37 textareaRef: RefObject<HTMLTextAreaElement | null>;
38 onCommentAction: (
39 body: string,
40 action: "close" | "reopen",
41 ) => Promise<{ readonly commentPosted: boolean }>;
42 onCommented: () => void;
43 onClose: () => void;
44}) {
45 const [body, setBody] = useState("");
46 const [submitting, setSubmitting] = useState<"comment" | "close" | "reopen" | null>(null);
47 const locked = submitting !== null || actionPending;
48 const speech = useTextFieldSpeech({
49 environmentId,
50 projectId: reference.projectId,
51 ownerKey: JSON.stringify(["pr-comment", environmentId, reference]),
52 text: body,
53 textareaRef,
54 onTextChange: setBody,
55 disabled: !active || locked,
56 });
57 const { cancel } = speech;
58 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- discards a recording when the hidden form can no longer be submitted
59 useEffect(() => {
60 if (!active) cancel();
61 }, [active, cancel]);
62 const postComment = useAtomCommand(pullRequestEnvironment.comment, {
63 reportFailure: false,
64 });
65 const inlineConfirm = useInlineActionConfirm(pullRequestReviewKey(reference));
66 const followUpAction =
67 detail.state === "open" &&
68 detail.capabilities.actions.includes("close") &&
69 detail.viewerPermissions.actions.includes("close")
70 ? ("close" as const)
71 : detail.state === "closed" &&
72 detail.capabilities.actions.includes("reopen") &&
73 detail.viewerPermissions.actions.includes("reopen")
74 ? ("reopen" as const)
75 : null;
76​
77 const submit = async (action: "comment" | "close" | "reopen", text: string) => {
78 const trimmed = text.trim();
79 if (trimmed.length === 0 || submitting !== null || actionPending) return;
80 setSubmitting(action);
81 if (action !== "comment") {
82 const result = await onCommentAction(trimmed, action);
83 if (result.commentPosted) {
84 setBody("");
85 onClose();
86 }
87 setSubmitting(null);
88 return;
89 }
90 const result = await postComment({
91 environmentId,
92 input: {
93 ...reference,
94 body: trimmed,
95 },
96 });
97 if (result._tag === "Failure") {
98 setSubmitting(null);
99 toastManager.add({ type: "error", title: "Could not post the comment" });
100 return;
101 }
102 setBody("");
103 setSubmitting(null);
104 onClose();
105 onCommented();
106 };
107 const submitAfterDictation = (action: "comment" | "close" | "reopen") =>
108 speech.submitAfterDictation((text) => void submit(action, text));
109 const submitDisabled =
110 speech.preparing || (body.trim().length === 0 && !speech.blocksSubmission) || locked;
111​
112 return (
113 <div className="space-y-2">
114 <PullRequestMarkdownTextarea
115 ref={textareaRef}
116 completionScope={pullRequestCompletionScope(detail, environmentId, reference)}
117 // Lock while posting because success clears the draft.
118 disabled={locked}
119 readOnly={speech.freezesEditor}
120 value={body}
121 rows={3}
122 placeholder="Leave a comment"
123 aria-label={`Comment on this ${sourceControlClients.get(detail.provider).changeRequest.singular}`}
124 onValueChange={setBody}
125 onKeyDown={(event) => {
126 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
127 if (
128 event.key === "Enter" &&
129 (event.metaKey || event.ctrlKey) &&
130 !event.shiftKey &&
131 !event.altKey
132 ) {
133 event.preventDefault();
134 event.stopPropagation();
135 if (!event.repeat) submitAfterDictation("comment");
136 }
137 }}
138 />
139 <div className="flex flex-wrap items-center justify-end gap-2">
140 <TextFieldSpeechControls speech={speech} disabled={locked} />
141 {followUpAction === null ? null : (
142 <Button
143 size="xs"
144 variant={followUpAction === "close" ? "destructive-outline" : "outline"}
145 disabled={submitDisabled}
146 {...(followUpAction === "close"
147 ? inlineConfirm.props("close", () => submitAfterDictation("close"))
148 : { onClick: () => submitAfterDictation("reopen") })}
149 >
150 {followUpAction === "close" ? (
151 <PullRequestGlyph.closed className="size-3.5" />
152 ) : (
153 <PullRequestGlyph.reopen className="size-3.5" />
154 )}
155 {followUpAction === "close" ? (
156 // The longest label holds the width, so the confirming click lands on the button.
157 <span className="inline-grid">
158 <span aria-hidden className="invisible col-start-1 row-start-1">
159 Close with comment
160 </span>
161 <span className="col-start-1 row-start-1">
162 {submitting === "close"
163 ? "Closing..."
164 : inlineConfirm.isArmed("close")
165 ? "Confirm close?"
166 : "Close with comment"}
167 </span>
168 </span>
169 ) : submitting === "reopen" ? (
170 "Reopening..."
171 ) : (
172 "Reopen with comment"
173 )}
174 </Button>
175 )}
176 <Button
177 size="xs"
178 variant="outline"
179 disabled={submitDisabled}
180 onClick={() => submitAfterDictation("comment")}
181 >
182 <SendIcon className="size-3.5" />
183 {submitting === "comment" ? "Posting..." : "Comment"}
184 </Button>
185 </div>
186 </div>
187 );