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