Open History to see the last commit
1import type {
2 EnvironmentId,
3 ProjectId,
4 PullRequestDetailView,
5 PullRequestRef,
6 PullRequestReferenceCandidate,
7} from "@t3tools/contracts";
8import {
9 debouncedPullRequestCompletionSearch,
10 detectPullRequestComposerTrigger,
11 insertPullRequestCompletion,
12 pullRequestCompletionKey,
13 pullRequestCompletions,
14 type PullRequestCompletion,
15 type PullRequestCompletionSupport,
16 type PullRequestComposerTrigger,
17} from "@t3tools/shared/pullRequestComposerTrigger";
18import { msg, useMessages } from "gt-react";
19import { CircleCheckIcon, CircleDotIcon } from "lucide-react";
20import { useId, useState, type Ref } from "react";
21import { flushSync } from "react-dom";
22
23import { cn } from "~/lib/utils";
24import { usePullRequestFilterOptions } from "~/state/pullRequests";
25import { useDebouncedValue } from "~/state/queries";
26import { markdownProseDirection } from "~/textDirection";
27
28import { Popover, PopoverPopup } from "../ui/popover";
29import { Textarea, type TextareaProps } from "../ui/textarea";
30import { PULL_REQUEST_STATE_PRESENTATION } from "./pullRequestIcons";
31import { PullRequestActorAvatar, resolvePullRequestState } from "./pullRequestPresentation";
32
33/** The repository whose users `@` completes and whose issues and change requests `#` does. */
34export interface PullRequestCompletionScope {
35 readonly environmentId: EnvironmentId;
36 readonly projectId: ProjectId;
37 readonly support: PullRequestCompletionSupport;
38}
39
40/** Null on hosts that complete nothing, so no sigil opens a list that cannot fill. */
41export function pullRequestCompletionScope(
42 detail: Pick<PullRequestDetailView, "capabilities">,
43 environmentId: EnvironmentId,
44 reference: PullRequestRef,
45): PullRequestCompletionScope | null {
46 const { mentions, referenceSigils } = detail.capabilities;
47 return mentions === true || (referenceSigils?.length ?? 0) > 0
48 ? { environmentId, projectId: reference.projectId, support: { mentions, referenceSigils } }
49 : null;
50}
51// About a full list of suggestions. The popup fits itself to the space it opens into, so it never
52// flips once results grow it; the side is picked up front from the room a full list needs.
53const SUGGESTION_LIST_HEIGHT = 320;
54
55function suggestionSide(target: HTMLTextAreaElement): "top" | "bottom" {
56 const rect = target.getBoundingClientRect();
57 const below = window.innerHeight - rect.bottom;
58 return below < SUGGESTION_LIST_HEIGHT && rect.top > below ? "top" : "bottom";
59}
60
61const COMPLETION_SEARCH_DEBOUNCE_MS = 200;
62const COMPLETION_SUGGESTION_LIMIT = 8;
63
64function useCompletions(
65 scope: PullRequestCompletionScope | null,
66 trigger: PullRequestComposerTrigger | null,
67) {
68 const key = pullRequestCompletionKey(trigger);
69 const sentKey = useDebouncedValue(key, COMPLETION_SEARCH_DEBOUNCE_MS);
70 const sent =
71 trigger === null ? undefined : debouncedPullRequestCompletionSearch(trigger, sentKey);
72 const hosted = usePullRequestFilterOptions(
73 scope === null || trigger === null
74 ? []
75 : [
76 {
77 environmentId: scope.environmentId,
78 input:
79 trigger.kind === "mention"
80 ? { kind: "authors", projectId: scope.projectId, ...(sent ? { query: sent } : {}) }
81 : {
82 kind: "references",
83 projectId: scope.projectId,
84 sigil: trigger.sigil,
85 ...(sent ? { query: sent } : {}),
86 },
87 },
88 ],
89 );
90 // Older answers stay useful while the debounced search catches up, narrowed to what is typed now.
91 const completions = pullRequestCompletions(trigger, hosted, COMPLETION_SUGGESTION_LIMIT);
92 return {
93 completions,
94 isPending: hosted.isPending || sentKey !== key,
95 failed: hosted.error !== null,
96 };
97}
98
99function ReferenceStateIcon({ candidate }: { candidate: PullRequestReferenceCandidate }) {
100 const m = useMessages();
101 const presentation =
102 candidate.kind === "change-request"
103 ? resolvePullRequestState({ state: candidate.state, isDraft: false }, m)
104 : candidate.state === "open"
105 ? {
106 label: m(msg("Open issue")),
107 Icon: CircleDotIcon,
108 toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName,
109 }
110 : {
111 label: m(msg("Closed issue")),
112 Icon: CircleCheckIcon,
113 toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName,
114 };
115 return (
116 <presentation.Icon
117 role="img"
118 aria-label={presentation.label}
119 className={cn("size-4 shrink-0", presentation.toneClassName)}
120 />
121 );
122}
123
124function CompletionRow({ completion }: { completion: PullRequestCompletion }) {
125 if (completion.kind === "mention") {
126 const { actor } = completion;
127 return (
128 <>
129 <PullRequestActorAvatar actor={actor} className="size-5" />
130 <span className="truncate font-medium">{actor.login}</span>
131 {actor.name && actor.name !== actor.login ? (
132 <span className="min-w-0 truncate text-muted-foreground">{actor.name}</span>
133 ) : null}
134 </>
135 );
136 }
137 const { candidate } = completion;
138 return (
139 <>
140 <ReferenceStateIcon candidate={candidate} />
141 <span className="shrink-0 font-medium tabular-nums">{candidate.reference}</span>
142 <span className="min-w-0 truncate text-muted-foreground">{candidate.title}</span>
143 </>
144 );
145}
146
147const EMPTY_STATE = {
148 mention: {
149 label: msg("Mention a user"),
150 pending: msg("Searching users..."),
151 failed: msg("Couldn't search users on the host"),
152 none: msg("No matching users"),
153 },
154 reference: {
155 label: msg("Reference an issue or change request"),
156 pending: msg("Searching..."),
157 failed: msg("Couldn't search the host"),
158 none: msg("No matching issues or change requests"),
159 },
160} as const;
161
162function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
163 if (typeof ref === "function") ref(value);
164 else if (ref) ref.current = value;
165}
166
167/** A markdown textarea for pull request text that completes `@login`, `#123` and GitLab `!123`. */
168export function PullRequestMarkdownTextarea({
169 ref,
170 value,
171 onValueChange,
172 completionScope,
173 onKeyDown,
174 onSelect,
175 onFocus,
176 onBlur,
177 ...props
178}: Omit<TextareaProps, "value" | "onChange"> & {
179 readonly value: string;
180 readonly onValueChange: (value: string) => void;
181 readonly completionScope: PullRequestCompletionScope | null;
182}) {
183 const m = useMessages();
184 const listId = useId();
185 const [element, setElement] = useState<HTMLTextAreaElement | null>(null);
186 const [caret, setCaret] = useState<number | null>(null);
187 const [side, setSide] = useState<"top" | "bottom">("bottom");
188 const [dismissedAt, setDismissedAt] = useState<number | null>(null);
189 const [highlight, setHighlight] = useState({ query: "", index: 0 });
190
191 const trigger =
192 completionScope === null || caret === null || props.readOnly
193 ? null
194 : detectPullRequestComposerTrigger(value, caret, completionScope.support);
195 const open = trigger !== null && trigger.rangeStart !== dismissedAt;
196 const {
197 completions: candidates,
198 isPending,
199 failed,
200 } = useCompletions(completionScope, open ? trigger : null);
201 const activeIndex =
202 trigger !== null && highlight.query === trigger.query
203 ? Math.min(highlight.index, Math.max(0, candidates.length - 1))
204 : 0;
205 const active = open ? candidates[activeIndex] : undefined;
206 const optionId = (token: string) => `${listId}-${token}`;
207
208 const syncCaret = (target: HTMLTextAreaElement) => {
209 setSide(suggestionSide(target));
210 setCaret(target.selectionStart === target.selectionEnd ? target.selectionStart : null);
211 };
212
213 const select = (completion: PullRequestCompletion) => {
214 if (trigger === null || element === null) return;
215 const next = insertPullRequestCompletion(value, trigger, completion.token);
216 flushSync(() => onValueChange(next.text));
217 element.setSelectionRange(next.cursor, next.cursor);
218 setCaret(next.cursor);
219 };
220
221 return (
222 <>
223 <Textarea
224 dir={markdownProseDirection(value)}
225 {...props}
226 ref={(node) => {
227 setElement(node);
228 assignRef(ref, node);
229 }}
230 value={value}
231 role={completionScope === null ? undefined : "combobox"}
232 aria-autocomplete={completionScope === null ? undefined : "list"}
233 aria-expanded={completionScope === null ? undefined : open}
234 aria-controls={open && candidates.length > 0 ? listId : undefined}
235 aria-activedescendant={active ? optionId(active.token) : undefined}
236 onChange={(event) => {
237 onValueChange(event.target.value);
238 syncCaret(event.target);
239 setDismissedAt(null);
240 }}
241 onSelect={(event) => {
242 syncCaret(event.currentTarget);
243 onSelect?.(event);
244 }}
245 onFocus={(event) => {
246 syncCaret(event.currentTarget);
247 onFocus?.(event);
248 }}
249 onBlur={(event) => {
250 setCaret(null);
251 onBlur?.(event);
252 }}
253 onKeyDown={(event) => {
254 // Some IMEs confirm a composition with an Enter that reports keyCode 229 but not isComposing.
255 if (open && !event.nativeEvent.isComposing && event.nativeEvent.keyCode !== 229) {
256 const handled = (() => {
257 if (event.key === "Escape") {
258 setDismissedAt(trigger.rangeStart);
259 return true;
260 }
261 if (candidates.length === 0) return false;
262 const plain = !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey;
263 if ((event.key === "ArrowDown" || event.key === "ArrowUp") && plain) {
264 const step = event.key === "ArrowDown" ? 1 : -1;
265 setHighlight({
266 query: trigger.query,
267 index: (activeIndex + step + candidates.length) % candidates.length,
268 });
269 return true;
270 }
271 if ((event.key === "Enter" || event.key === "Tab") && plain && active) {
272 select(active);
273 return true;
274 }
275 return false;
276 })();
277 if (handled) {
278 event.preventDefault();
279 event.stopPropagation();
280 return;
281 }
282 }
283 onKeyDown?.(event);
284 }}
285 />
286 <Popover
287 open={open}
288 modal={false}
289 onOpenChange={(next, details) => {
290 if (next || details.event?.target === element) return;
291 if (trigger !== null) setDismissedAt(trigger.rangeStart);
292 }}
293 >
294 <PopoverPopup
295 anchor={element}
296 side={side}
297 align="start"
298 padding="compact"
299 width={trigger?.kind === "reference" ? "md" : "sm"}
300 initialFocus={false}
301 finalFocus={false}
302 >
303 {candidates.length > 0 ? (
304 <div
305 id={listId}
306 role="listbox"
307 aria-label={m(EMPTY_STATE[trigger?.kind ?? "mention"].label)}
308 className="-mx-1.5"
309 >
310 {candidates.map((completion, index) => (
311 <div
312 key={completion.token}
313 id={optionId(completion.token)}
314 role="option"
315 aria-selected={index === activeIndex}
316 className={cn(
317 "flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm",
318 index === activeIndex && "bg-accent text-accent-foreground",
319 )}
320 onMouseMove={() => {
321 if (index !== activeIndex) setHighlight({ query: trigger?.query ?? "", index });
322 }}
323 // Keeps focus, and the caret, in the textarea.
324 onMouseDown={(event) => event.preventDefault()}
325 onClick={() => select(completion)}
326 >
327 <CompletionRow completion={completion} />
328 </div>
329 ))}
330 </div>
331 ) : (
332 <p className="px-1 text-xs text-muted-foreground">
333 {m(
334 EMPTY_STATE[trigger?.kind ?? "mention"][
335 isPending ? "pending" : failed ? "failed" : "none"
336 ],
337 )}
338 </p>
339 )}
340 </PopoverPopup>
341 </Popover>
342 </>
343 );
344}