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

DiffCommentAnnotation.tsx

227 lines7.7 KB

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