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

PullRequestCommentForm.tsx

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