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

IssueCommentComposer.tsx

194 lines8.1 KB

1import { RegistryContext, useAtomValue } from "@effect/atom-react";
2import {
3 beginIssueCommentPost,
4 editIssueCommentDraft,
5 finishIssueCommentPost,
6 issueCommentDraftAtom,
7} from "@t3tools/client-runtime/state/issues";
8import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9import type { EnvironmentId, IssueCommentAudience, IssueRef } from "@t3tools/contracts";
10import { msg, useGT } from "gt-react";
11import { ArrowUpIcon, ChevronDownIcon } from "lucide-react";
12import { useContext, useRef } from "react";
13import { flushSync } from "react-dom";
14​
15import { m } from "~/i18n/messages";
16import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFieldSpeech";
17import { cn } from "~/lib/utils";
18import { issueEnvironment } from "~/state/issues";
19import { useAtomCommand } from "~/state/use-atom-command";
20​
21import { ComposerSurface } from "../chat/ComposerSurface";
22import { readableFailure } from "../pullRequest/pullRequestDetail.logic";
23import { Button } from "../ui/button";
24import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu";
25import { Spinner } from "../ui/spinner";
26import { toastManager } from "../ui/toast";
27​
28/** The thread composer's card, floating over the issue's timeline, with a comment as its message. */
29export function IssueCommentComposer({
30 environmentId,
31 reference,
32 issueUrl,
33 blocked,
34 audiences,
35}: {
36 environmentId: EnvironmentId;
37 reference: IssueRef;
38 issueUrl: string;
39 /** Why the viewer cannot comment here; null when they can. */
40 blocked: string | null;
41 /** Each comment is an internal note unless the viewer picks a reply to the customer. */
42 audiences: boolean;
43}) {
44 const gt = useGT();
45 const registry = useContext(RegistryContext);
46 const draftAtom = issueCommentDraftAtom(environmentId, issueUrl);
47 const { audience, body, posting: submitting } = useAtomValue(draftAtom);
48 const setBody = (body: string) => editIssueCommentDraft(registry, draftAtom, { body });
49 const textareaRef = useRef<HTMLTextAreaElement>(null);
50 const comment = useAtomCommand(issueEnvironment.comment, { reportFailure: false });
51 const locked = blocked !== null || submitting;
52 const speech = useTextFieldSpeech({
53 environmentId,
54 projectId: reference.projectId,
55 ownerKey: JSON.stringify(["issue-comment", environmentId, reference]),
56 text: body,
57 textareaRef,
58 onTextChange: setBody,
59 disabled: locked,
60 });
61​
62 const submit = async (text: string) => {
63 if (blocked !== null) return;
64 const pending = beginIssueCommentPost(registry, draftAtom, text);
65 if (pending === null) return;
66 const form = textareaRef.current?.form;
67 if (form?.contains(document.activeElement)) form.focus({ preventScroll: true });
68 const result = await comment({
69 environmentId,
70 input: {
71 ...reference,
72 body: pending.body,
73 ...(audiences ? { audience: pending.audience } : {}),
74 },
75 });
76 flushSync(() =>
77 finishIssueCommentPost(registry, draftAtom, pending, result._tag === "Success"),
78 );
79 if (document.activeElement === form) textareaRef.current?.focus({ preventScroll: true });
80 if (result._tag === "Failure") {
81 toastManager.add({
82 type: "error",
83 title: m(msg("The comment could not be posted")),
84 description: readableFailure(
85 squashAtomCommandFailure(result),
86 m(msg("The tracker refused it.")),
87 ),
88 });
89 }
90 };
91 const submitAfterDictation = () => speech.submitAfterDictation((text) => void submit(text));
92 const submitDisabled =
93 speech.preparing || (body.trim().length === 0 && !speech.blocksSubmission) || locked;
94​
95 return (
96 <div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 px-3">
97 <ComposerSurface.Shell className="pointer-events-auto">
98 <ComposerSurface.Host
99 className={audiences && audience === "internal" ? "bg-warning-surface" : undefined}
100 >
101 <form
102 tabIndex={-1}
103 className="relative z-10 flex flex-col outline-none"
104 onSubmit={(event) => {
105 event.preventDefault();
106 submitAfterDictation();
107 }}
108 >
109 <textarea
110 ref={textareaRef}
111 rows={2}
112 className={cn(
113 "field-sizing-content max-h-64 w-full resize-none bg-transparent px-3.5 pt-3 pb-1 text-base text-foreground outline-none wrap-anywhere placeholder:text-muted-foreground/70 disabled:opacity-64 sm:text-sm",
114 // Two full lines above the audience row; the padding counts against min-height.
115 audiences ? "min-h-[calc(2lh+1rem)]" : "min-h-[2lh]",
116 )}
117 aria-label={gt`Add a comment`}
118 placeholder={blocked ?? gt`Leave a comment`}
119 value={body}
120 // Lock while posting because success clears the draft.
121 disabled={locked}
122 readOnly={speech.freezesEditor}
123 onChange={(event) => setBody(event.target.value)}
124 onKeyDown={(event) => {
125 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
126 if (event.key === "Enter" && (event.metaKey || event.ctrlKey) && !event.shiftKey) {
127 event.preventDefault();
128 if (!event.repeat) submitAfterDictation();
129 }
130 }}
131 />
132 <div className="flex flex-wrap items-center justify-end gap-2 px-2.5 pb-2.5">
133 {audiences ? (
134 <Menu>
135 <MenuTrigger
136 render={
137 <Button
138 type="button"
139 size="xs"
140 variant="ghost"
141 className="mr-auto"
142 disabled={locked}
143 />
144 }
145 >
146 {audience === "internal" ? gt`Internal note` : gt`Reply to customer`}
147 <ChevronDownIcon aria-hidden className="size-3" />
148 </MenuTrigger>
149 <MenuPopup align="start">
150 <MenuRadioGroup
151 value={audience}
152 onValueChange={(audience: IssueCommentAudience) =>
153 editIssueCommentDraft(registry, draftAtom, { audience })
154 }
155 >
156 <MenuRadioItem value="internal" closeOnClick>
157 {gt`Internal note`}
158 </MenuRadioItem>
159 <MenuRadioItem value="public" closeOnClick>
160 {gt`Reply to customer`}
161 </MenuRadioItem>
162 </MenuRadioGroup>
163 </MenuPopup>
164 </Menu>
165 ) : null}
166 <TextFieldSpeechControls speech={speech} disabled={locked} />
167 <button
168 type="submit"
169 className="flex size-8 items-center justify-center rounded-full bg-message-action text-message-action-foreground shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:shadow-message-action/24 enabled:inset-shadow-control-highlight hover:scale-105 hover:bg-message-action-hover active:shadow-none active:inset-shadow-control-pressed disabled:pointer-events-none disabled:bg-foreground/12 disabled:text-muted-foreground disabled:shadow-none"
170 disabled={submitDisabled}
171 aria-label={
172 submitting
173 ? gt`Posting comment`
174 : gt({ context: "verb, posts the comment" })`Comment`
175 }
176 >
177 {submitting ? (
178 <Spinner size="sm" aria-hidden />
179 ) : (
180 <ArrowUpIcon aria-hidden className="size-4" />
181 )}
182 </button>
183 </div>
184 </form>
185 </ComposerSurface.Host>
186 </ComposerSurface.Shell>
187 {/* The chat composer's bottom inset, so the two cards line up side by side. */}
188 <div
189 aria-hidden
190 className="h-[calc(env(safe-area-inset-bottom)+1rem)] sm:h-[calc(env(safe-area-inset-bottom)+1.25rem)]"
191 />
192 </div>
193 );