Open History to see the last commit
1import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
2import { T, useGT, useMessages } from "gt-react";
3import { reviewCommentRangeText } from "~/lib/composerContextRecords";
4import { MessageCircle, Trash2 } from "lucide-react";
5import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
6
7import { Button } from "~/components/ui/button";
8import {
9 PullRequestMarkdownTextarea,
10 type PullRequestCompletionScope,
11} from "~/components/pullRequest/PullRequestMarkdownTextarea";
12import {
13 SpeechTextField,
14 TextFieldSpeechControls,
15 type TextFieldSpeech,
16} from "~/speech/useTextFieldSpeech";
17import { textDirection } from "~/textDirection";
18
19import { isCommentSubmitShortcut } from "./commentSubmitShortcut";
20
21interface DiffCommentSecondaryAction {
22 readonly label: string;
23 readonly icon?: ReactNode;
24 readonly allowEmpty?: boolean;
25 readonly onAction: (text: string) => void;
26}
27
28interface DiffCommentAnnotationProps {
29 /** With an environment, the draft can be dictated; its project supplies vocabulary. */
30 environmentId?: EnvironmentId | undefined;
31 projectId?: ProjectId | null | undefined;
32 ownerKey?: string;
33 kind: "draft" | "comment";
34 rangeLabel: string;
35 text: string;
36 onTextChange?: (text: string) => void;
37 onCancel: () => void;
38 onComment: (text: string) => void;
39 onDelete?: () => void;
40 placeholder?: string;
41 submitLabel?: string;
42 pending?: boolean;
43 secondaryAction?: DiffCommentSecondaryAction;
44 focusOnMount?: boolean;
45 /** Set only for pull request comments, where `@` completes the repository's users. */
46 completionScope?: PullRequestCompletionScope | null;
47}
48
49export function DiffCommentAnnotation({
50 environmentId,
51 projectId,
52 ownerKey,
53 kind,
54 rangeLabel,
55 text,
56 onTextChange,
57 onCancel,
58 onComment,
59 onDelete,
60 placeholder,
61 submitLabel,
62 pending = false,
63 secondaryAction,
64 focusOnMount = true,
65 completionScope = null,
66}: DiffCommentAnnotationProps) {
67 const gt = useGT();
68 const messages = useMessages();
69 const [localDraftText, setLocalDraftText] = useState("");
70 const displayedText = kind === "draft" && !onTextChange ? localDraftText : text;
71 const trimmedText = displayedText.trim();
72 const textareaRef = useRef<HTMLTextAreaElement | null>(null);
73
74 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses the draft textarea on the next animation frame after mount
75 useLayoutEffect(() => {
76 if (kind !== "draft" || !focusOnMount) return;
77 const frame = window.requestAnimationFrame(() => {
78 textareaRef.current?.focus({ preventScroll: true });
79 });
80 return () => window.cancelAnimationFrame(frame);
81 }, [focusOnMount, kind]);
82
83 if (kind === "comment") {
84 return (
85 <div
86 data-diff-comment-annotation
87 className="group/comment flex min-w-0 items-start gap-2.5 border-s-2 border-primary/55 bg-primary/[0.045] px-3 py-2.5 font-sans text-foreground selection:bg-primary selection:text-primary-foreground"
88 contentEditable={false}
89 onPointerDown={(event) => event.stopPropagation()}
90 >
91 <MessageCircle className="size-3.5 h-5 shrink-0 text-primary/70" aria-hidden="true" />
92 <p
93 className="min-w-0 flex-1 whitespace-pre-wrap text-sm leading-5"
94 dir={textDirection(displayedText)}
95 >
96 {displayedText}
97 </p>
98 {onDelete ? (
99 <span className="-my-1 -mr-1 flex shrink-0 opacity-0 transition-opacity group-hover/comment:opacity-100 focus-within:opacity-100 max-sm:opacity-100">
100 <Button
101 variant="ghost-muted"
102 size="icon-xs"
103 aria-label={gt("Delete comment")}
104 onClick={onDelete}
105 >
106 <Trash2 className="size-3" />
107 </Button>
108 </span>
109 ) : null}
110 </div>
111 );
112 }
113
114 const submit = (
115 speech: TextFieldSpeech | undefined,
116 action: (text: string) => void,
117 allowEmpty = false,
118 ) => {
119 const finish = (value: string) => {
120 if (!pending && (allowEmpty || value.trim())) action(value.trim());
121 };
122 if (speech) speech.submitAfterDictation(finish);
123 else finish(displayedText);
124 };
125
126 // Pierre hides native carets and selection; textarea comments need their own visible feedback.
127 const renderDraft = (speech?: TextFieldSpeech) => (
128 <div
129 data-diff-comment-annotation
130 className="px-3 py-2 font-sans text-foreground caret-foreground selection:bg-primary selection:text-primary-foreground"
131 contentEditable={false}
132 onPointerDown={(event) => event.stopPropagation()}
133 >
134 <PullRequestMarkdownTextarea
135 ref={textareaRef}
136 completionScope={completionScope}
137 readOnly={speech?.freezesEditor}
138 autoFocus={focusOnMount}
139 size="sm"
140 value={displayedText}
141 dir={textDirection(displayedText)}
142 placeholder={placeholder ?? gt("Add a comment…")}
143 aria-label={gt("Comment on lines {rangeLabel}", {
144 rangeLabel: reviewCommentRangeText(rangeLabel, messages),
145 })}
146 onValueChange={onTextChange ?? setLocalDraftText}
147 onFocus={(event) => {
148 const end = event.currentTarget.value.length;
149 event.currentTarget.setSelectionRange(end, end);
150 }}
151 onKeyDown={(event) => {
152 // Unclaimed, an IME Escape would close the right panel sheet or leave the pull requests page.
153 if (event.nativeEvent.isComposing || event.keyCode === 229) {
154 event.stopPropagation();
155 return;
156 }
157 if (event.key === "Escape") {
158 event.preventDefault();
159 if (speech && speech.state.phase !== "idle") speech.cancel();
160 else onCancel();
161 }
162 if (isCommentSubmitShortcut(event, trimmedText, pending, speech?.blocksSubmission)) {
163 event.preventDefault();
164 submit(speech, onComment);
165 }
166 }}
167 />
168 <div className="mt-1.5 flex flex-wrap items-center gap-1">
169 <span className="mr-auto text-3xs text-muted-foreground/70">
170 <T>⌘/Ctrl Enter to send</T>
171 </span>
172 {speech ? <TextFieldSpeechControls speech={speech} disabled={pending} /> : null}
173 <Button variant="ghost-muted" size="xs" onClick={onCancel}>
174 <T>Cancel</T>
175 </Button>
176 {secondaryAction ? (
177 <Button
178 size="xs"
179 variant="outline"
180 disabled={
181 speech?.preparing ||
182 pending ||
183 (!speech?.blocksSubmission && !secondaryAction.allowEmpty && !trimmedText)
184 }
185 onClick={() => submit(speech, secondaryAction.onAction, secondaryAction.allowEmpty)}
186 >
187 {secondaryAction.icon}
188 {secondaryAction.label}
189 </Button>
190 ) : null}
191 <Button
192 size="xs"
193 disabled={speech?.preparing || pending || (!speech?.blocksSubmission && !trimmedText)}
194 onClick={() => submit(speech, onComment)}
195 >
196 {submitLabel ?? gt("Comment", { $context: "verb, submit button" })}
197 </Button>
198 </div>
199 </div>
200 );
201
202 return environmentId ? (
203 <SpeechTextField
204 environmentId={environmentId}
205 projectId={projectId}
206 ownerKey={ownerKey ?? rangeLabel}
207 text={displayedText}
208 textareaRef={textareaRef}
209 onTextChange={onTextChange ?? setLocalDraftText}
210 disabled={pending}
211 >
212 {renderDraft}
213 </SpeechTextField>
214 ) : (
215 renderDraft()
216 );
217}