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

PullRequestMarkdownTextarea.tsx

339 lines11.9 KB

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