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

PullRequestActionsMenu.tsx

569 lines20.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 canEditPullRequestMaintainerEdits,
4 maintainerEditsChoiceInForce,
5 type MaintainerEditsChoice,
6} from "@t3tools/client-runtime/pull-request-editing";
7import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
8import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9import type {
10 EnvironmentId,
11 PullRequestAction,
12 PullRequestDetail,
13 PullRequestMergeMethod,
14 PullRequestRef,
15 ScopedThreadRef,
16} from "@t3tools/contracts";
17import {
18 ArrowUpRightIcon,
19 BookOpenIcon,
20 CopyIcon,
21 HammerIcon,
22 LinkIcon,
23 MessageCircleQuestionIcon,
24 MoreHorizontalIcon,
25 RotateCcwIcon,
26 ScrollTextIcon,
27 Trash2Icon,
28} from "lucide-react";
29import { Branch, msg, T, useGT, useMessages } from "gt-react";
30import { useId, useState } from "react";
31​
32import { m } from "~/i18n/messages";
33​
34import { shortcutLabelForCommand } from "~/keybindings";
35import { readLocalApi } from "~/localApi";
36import { pullRequestEnvironment } from "~/state/pullRequests";
37import { primaryServerKeybindingsAtom } from "~/state/server";
38import { useAtomCommand } from "~/state/use-atom-command";
39import { Button } from "../ui/button";
40import {
41 Menu,
42 MenuCheckboxItem,
43 MenuItem,
44 MenuPopup,
45 MenuRadioGroup,
46 MenuRadioItem,
47 MenuSeparator,
48 MenuShortcut,
49 MenuTrigger,
50} from "../ui/menu";
51import { RefreshIcon } from "../ui/refresh-icon";
52import { toastManager } from "../ui/toast";
53import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
54import { ActOnEnvironmentPicker, type PerformPullRequestAction } from "./PullRequestDetailActions";
55import {
56 PULL_REQUEST_MERGE_METHOD_LABELS,
57 pullRequestActionMenuHasGroup,
58 readableFailure,
59} from "./pullRequestDetail.logic";
60import { PullRequestGlyph } from "./pullRequestIcons";
61import type { PickableEnvironment } from "./pullRequestProjectAssignment.logic";
62import { PullRequestThreadLinks } from "./PullRequestThreadLinks";
63import { useInlineActionConfirm } from "./useInlineActionConfirm";
64​
65import { changeRequestTermKind } from "./changeRequestTerm";
66​
67/** Everything else the reader can do with the pull request, behind the header's overflow button. */
68export function PullRequestActionsMenu({
69 environmentId,
70 reference,
71 pullRequestKey,
72 detail,
73 terminology,
74 linkThreadRef,
75 onThreadPickerOpenChange,
76 refreshing,
77 refreshFromHost,
78 handoff,
79 attachesToComposer,
80 askAboutPullRequest,
81 explainPullRequest,
82 canFixFindings,
83 startFixFindings,
84 handoffLabels,
85 canWriteGuide,
86 guideRunning,
87 guideWritten,
88 writeGuide,
89 pickableEnvironments,
90 actingEnvironmentId,
91 onActingEnvironmentChange,
92 can,
93 autoMergeArmed,
94 showsDraftToggle,
95 showsMergeNow,
96 showsAutoMerge,
97 showsMergeMethods,
98 allowedMergeMethods,
99 selectedMergeMethod,
100 onSelectMergeMethod,
101 showsDeleteBranch,
102 environmentConnected,
103 canWriteSourceControl,
104 onMaintainerEditsSaved,
105 confirmDeleteBranch,
106 pendingAction,
107 perform,
108 openOnHostText,
109 copyReference,
110}: {
111 environmentId: EnvironmentId;
112 reference: PullRequestRef;
113 pullRequestKey: string;
114 detail: Pick<
115 PullRequestDetail,
116 | "url"
117 | "state"
118 | "isDraft"
119 | "headBranch"
120 | "capabilities"
121 | "viewerPermissions"
122 | "maintainerCanModify"
123 | "observedAt"
124 >;
125 terminology: ChangeRequestTerminology;
126 linkThreadRef: ScopedThreadRef | null;
127 onThreadPickerOpenChange: (open: boolean) => void;
128 refreshing: boolean;
129 refreshFromHost: () => Promise<void>;
130 handoff: string | null;
131 attachesToComposer: boolean;
132 askAboutPullRequest: () => void;
133 explainPullRequest: () => void;
134 canFixFindings: boolean;
135 startFixFindings: () => void;
136 handoffLabels: { readonly fixFindings: string };
137 canWriteGuide: boolean;
138 guideRunning: boolean;
139 guideWritten: boolean;
140 writeGuide: () => void;
141 pickableEnvironments: ReadonlyArray<PickableEnvironment>;
142 actingEnvironmentId: EnvironmentId;
143 onActingEnvironmentChange: (environmentId: EnvironmentId) => void;
144 can: (action: PullRequestAction) => boolean;
145 autoMergeArmed: boolean;
146 showsDraftToggle: boolean;
147 showsMergeNow: boolean;
148 showsAutoMerge: boolean;
149 showsMergeMethods: boolean;
150 allowedMergeMethods: ReadonlyArray<PullRequestMergeMethod>;
151 selectedMergeMethod: PullRequestMergeMethod;
152 onSelectMergeMethod: (method: PullRequestMergeMethod) => void;
153 showsDeleteBranch: boolean;
154 environmentConnected: boolean;
155 canWriteSourceControl: boolean;
156 onMaintainerEditsSaved: () => void;
157 confirmDeleteBranch: () => Promise<void>;
158 pendingAction: PullRequestAction | null;
159 perform: PerformPullRequestAction;
160 openOnHostText: string;
161 copyReference: (value: string, failureTitle: string) => void;
162}) {
163 const gt = useGT();
164 const resolve = useMessages();
165 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
166 const inlineConfirm = useInlineActionConfirm(pullRequestKey);
167 const actionPending = pendingAction !== null;
168 const maintainerEditsHintId = useId();
169 const updatePullRequest = useAtomCommand(pullRequestEnvironment.update, {
170 reportFailure: false,
171 });
172 const [maintainerEditsChoice, setMaintainerEditsChoice] = useState<MaintainerEditsChoice | null>(
173 null,
174 );
175 const [maintainerEditsSaving, setMaintainerEditsSaving] = useState(false);
176 const maintainerEditsChoiceKept = maintainerEditsChoiceInForce(
177 maintainerEditsChoice,
178 pullRequestKey,
179 detail.observedAt,
180 maintainerEditsSaving,
181 );
182 if (maintainerEditsChoiceKept !== maintainerEditsChoice) {
183 setMaintainerEditsChoice(maintainerEditsChoiceKept);
184 }
185 const maintainerCanModify = maintainerEditsChoiceKept?.value ?? detail.maintainerCanModify;
186 const canSaveMaintainerEdits =
187 canWriteSourceControl && environmentConnected && !maintainerEditsSaving;
188 const saveMaintainerEdits = async (value: boolean) => {
189 if (!canSaveMaintainerEdits) return;
190 const previousChoice = maintainerEditsChoice;
191 setMaintainerEditsChoice({ key: pullRequestKey, observedAt: detail.observedAt, value });
192 setMaintainerEditsSaving(true);
193 const result = await updatePullRequest({
194 environmentId,
195 input: { ...reference, maintainerCanModify: value },
196 });
197 setMaintainerEditsSaving(false);
198 if (result._tag === "Failure") {
199 setMaintainerEditsChoice(previousChoice);
200 toastManager.add({
201 type: "error",
202 title: m(msg("Could not save maintainer access")),
203 description: readableFailure(squashAtomCommandFailure(result), m(msg("Try again."))),
204 });
205 return;
206 }
207 onMaintainerEditsSaved();
208 };
209 return (
210 <Menu>
211 <Tooltip>
212 <TooltipTrigger
213 render={
214 <MenuTrigger
215 render={
216 <Button
217 aria-label={
218 refreshing
219 ? gt(
220 "Refreshing {term, select, mr {merge request} cr {change request} other {pull request}}",
221 { term: changeRequestTermKind(terminology) },
222 )
223 : gt(
224 "More {term, select, mr {merge request} cr {change request} other {pull request}} actions",
225 { term: changeRequestTermKind(terminology) },
226 )
227 }
228 size="icon-xs"
229 variant="ghost-muted"
230 />
231 }
232 >
233 {refreshing ? (
234 <RefreshIcon refreshing size="md" />
235 ) : (
236 <MoreHorizontalIcon className="size-4" />
237 )}
238 </MenuTrigger>
239 }
240 />
241 <TooltipPopup>
242 {refreshing
243 ? gt(
244 "Refreshing {term, select, mr {merge request} cr {change request} other {pull request}}",
245 { term: changeRequestTermKind(terminology) },
246 )
247 : gt(
248 "More {term, select, mr {merge request} cr {change request} other {pull request}} actions",
249 { term: changeRequestTermKind(terminology) },
250 )}
251 </TooltipPopup>
252 </Tooltip>
253 <MenuPopup align="end" side="bottom">
254 <PullRequestThreadLinks
255 display="menu-item"
256 environmentId={environmentId}
257 reference={reference}
258 url={detail.url}
259 threadRef={linkThreadRef}
260 onPickerOpenChange={onThreadPickerOpenChange}
261 />
262 <MenuItem disabled={refreshing} onClick={() => void refreshFromHost()}>
263 <RefreshIcon size="sm" refreshing={refreshing} />
264 <T context="verb, menu item">Refresh</T>
265 </MenuItem>
266 <MenuItem disabled={handoff !== null} onClick={askAboutPullRequest}>
267 <MessageCircleQuestionIcon className="mt-1 size-3.5 shrink-0 self-start" />
268 <span className="flex min-w-0 flex-col">
269 <span>{handoff === "ask" ? gt("Opening...") : gt("Ask a question")}</span>
270 <span className="text-xs text-muted-foreground">
271 {attachesToComposer
272 ? gt(
273 "Adds the {term, select, mr {merge request} cr {change request} other {pull request}} to this thread's composer.",
274 { term: changeRequestTermKind(terminology) },
275 )
276 : gt(
277 "Opens a thread that knows which {term, select, mr {merge request} cr {change request} other {pull request}} you mean.",
278 {
279 term: changeRequestTermKind(terminology),
280 },
281 )}
282 </span>
283 </span>
284 </MenuItem>
285 <MenuItem disabled={handoff !== null} onClick={explainPullRequest}>
286 <BookOpenIcon className="mt-1 size-3.5 shrink-0 self-start" />
287 <span className="flex min-w-0 flex-col">
288 <span>
289 {handoff === "explain"
290 ? gt("Opening...")
291 : gt("Explain this {term, select, mr {MR} cr {change request} other {PR}}", {
292 term: changeRequestTermKind(terminology),
293 })}
294 </span>
295 <span className="text-xs text-muted-foreground">
296 <T>A walk through the diff and what to read closely.</T>
297 </span>
298 </span>
299 </MenuItem>
300 <MenuItem disabled={handoff !== null || !canFixFindings} onClick={startFixFindings}>
301 <HammerIcon className="size-3.5" />
302 {handoff === "findings" ? gt("Preparing...") : handoffLabels.fixFindings}
303 </MenuItem>
304 {canWriteGuide ? (
305 <MenuItem disabled={guideRunning} onClick={writeGuide}>
306 <ScrollTextIcon className="size-3.5" />
307 {guideRunning
308 ? gt("Writing guide...")
309 : !guideWritten
310 ? gt("Write guide")
311 : gt("Rewrite guide")}
312 </MenuItem>
313 ) : null}
314 {pickableEnvironments.length > 0 ? (
315 <ActOnEnvironmentPicker
316 environments={pickableEnvironments}
317 value={actingEnvironmentId}
318 onChange={onActingEnvironmentChange}
319 disabled={handoff !== null}
320 />
321 ) : null}
322 <MenuSeparator />
323 {canEditPullRequestMaintainerEdits(detail) ? (
324 <>
325 <MenuCheckboxItem
326 variant="icon"
327 checked={maintainerCanModify === true}
328 disabled={!canSaveMaintainerEdits}
329 closeOnClick={false}
330 aria-label={gt("Allow edits from maintainers")}
331 aria-describedby={maintainerEditsHintId}
332 onCheckedChange={(value) => void saveMaintainerEdits(value)}
333 >
334 <span className="flex max-w-xs flex-col gap-0.5">
335 <span>
336 <T>Allow edits from maintainers</T>
337 </span>
338 <span id={maintainerEditsHintId} className="text-xs text-muted-foreground">
339 <T>
340 Maintainers can push to this branch. If your fork has workflows, this can also
341 give access to its secrets.
342 </T>
343 </span>
344 {maintainerEditsSaving ? (
345 <span role="status" className="text-xs text-muted-foreground">
346 <T>Saving…</T>
347 </span>
348 ) : null}
349 </span>
350 </MenuCheckboxItem>
351 <MenuSeparator />
352 </>
353 ) : null}
354 {detail.state === "open" ? (
355 <>
356 {showsDraftToggle ? (
357 <MenuItem
358 disabled={actionPending}
359 onClick={() => void perform(detail.isDraft ? "ready" : "draft")}
360 >
361 {detail.isDraft ? (
362 <PullRequestGlyph.pullRequest className="size-3.5" />
363 ) : (
364 <PullRequestGlyph.draft className="size-3.5" />
365 )}
366 {detail.isDraft ? gt("Ready for review") : gt("Convert to draft")}
367 </MenuItem>
368 ) : null}
369 {showsMergeNow ? (
370 <MenuItem
371 closeOnClick={inlineConfirm.isArmed("merge")}
372 aria-label={inlineConfirm.isArmed("merge") ? gt("Confirm merge?") : gt("Merge now")}
373 disabled={actionPending}
374 {...inlineConfirm.props("merge", () => void perform("merge", selectedMergeMethod))}
375 >
376 <PullRequestGlyph.merged className="size-3.5" />
377 {inlineConfirm.isArmed("merge") ? gt("Confirm merge?") : gt("Merge now")}
378 </MenuItem>
379 ) : null}
380 {autoMergeArmed && can("disable-auto-merge") ? (
381 <MenuItem disabled={actionPending} onClick={() => void perform("disable-auto-merge")}>
382 <PullRequestGlyph.merged className="size-3.5" />
383 <T>Disable auto-merge</T>
384 </MenuItem>
385 ) : showsAutoMerge ? (
386 <MenuItem
387 closeOnClick={inlineConfirm.isArmed("enable-auto-merge")}
388 aria-label={
389 inlineConfirm.isArmed("enable-auto-merge")
390 ? gt("Confirm auto-merge?")
391 : gt("Enable auto-merge")
392 }
393 disabled={actionPending}
394 {...inlineConfirm.props(
395 "enable-auto-merge",
396 () => void perform("enable-auto-merge", selectedMergeMethod),
397 )}
398 >
399 <PullRequestGlyph.merged className="size-3.5" />
400 {inlineConfirm.isArmed("enable-auto-merge")
401 ? gt("Confirm auto-merge?")
402 : gt("Enable auto-merge")}
403 </MenuItem>
404 ) : null}
405 {showsMergeMethods ? (
406 <>
407 {showsDraftToggle || showsMergeNow || showsAutoMerge ? <MenuSeparator /> : null}
408 <MenuRadioGroup
409 value={selectedMergeMethod}
410 onValueChange={(method) => onSelectMergeMethod(method as PullRequestMergeMethod)}
411 >
412 {allowedMergeMethods.map((method) => (
413 <MenuRadioItem
414 key={method}
415 value={method}
416 disabled={actionPending}
417 closeOnClick
418 >
419 <span className="flex min-w-0 items-center gap-2">
420 <PullRequestGlyph.merged className="size-3.5" />
421 <span>{resolve(PULL_REQUEST_MERGE_METHOD_LABELS[method])}</span>
422 </span>
423 </MenuRadioItem>
424 ))}
425 </MenuRadioGroup>
426 </>
427 ) : null}
428 {pullRequestActionMenuHasGroup(
429 showsDraftToggle,
430 showsAutoMerge || showsMergeNow,
431 showsMergeMethods,
432 ) ? (
433 <MenuSeparator />
434 ) : null}
435 </>
436 ) : null}
437 <MenuItem onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}>
438 <ArrowUpRightIcon className="size-3.5" />
439 {openOnHostText}
440 </MenuItem>
441 <MenuItem
442 onClick={() =>
443 copyReference(
444 detail.url,
445 resolve(
446 msg("Failed to copy {term, select, mr {MR} cr {change request} other {PR}} link", {
447 term: changeRequestTermKind(terminology),
448 }),
449 ),
450 )
451 }
452 >
453 <LinkIcon className="size-3.5" />
454 <T>Copy link</T>
455 <MenuShortcut>
456 {shortcutLabelForCommand(keybindings, "thread.copyReference")}
457 </MenuShortcut>
458 </MenuItem>
459 <MenuItem
460 onClick={() =>
461 copyReference(
462 `#${reference.number}`,
463 resolve(
464 msg(
465 "Failed to copy {term, select, mr {MR} cr {change request} other {PR}} number",
466 { term: changeRequestTermKind(terminology) },
467 ),
468 ),
469 )
470 }
471 >
472 <CopyIcon className="size-3.5" />
473 <T>
474 Copy{" "}
475 <Branch branch={changeRequestTermKind(terminology)} mr="MR" cr="change request">
476 PR
477 </Branch>{" "}
478 number
479 </T>
480 <MenuShortcut>
481 {shortcutLabelForCommand(keybindings, "pullRequest.copyNumber")}
482 </MenuShortcut>
483 </MenuItem>
484 {detail.state === "open" && can("close") ? (
485 <>
486 <MenuSeparator />
487 <MenuItem
488 closeOnClick={inlineConfirm.isArmed("close")}
489 aria-label={
490 inlineConfirm.isArmed("close")
491 ? gt("Confirm close?")
492 : gt(
493 "Close {term, select, mr {merge request} cr {change request} other {pull request}}",
494 { term: changeRequestTermKind(terminology) },
495 )
496 }
497 variant="destructive"
498 disabled={actionPending}
499 {...inlineConfirm.props("close", () => void perform("close"))}
500 >
501 <PullRequestGlyph.closed className="size-3.5" />
502 {inlineConfirm.isArmed("close")
503 ? gt("Confirm close?")
504 : gt(
505 "Close {term, select, mr {merge request} cr {change request} other {pull request}}",
506 { term: changeRequestTermKind(terminology) },
507 )}
508 </MenuItem>
509 </>
510 ) : detail.state === "closed" && can("reopen") ? (
511 <>
512 <MenuSeparator />
513 <MenuItem disabled={actionPending} onClick={() => void perform("reopen")}>
514 <PullRequestGlyph.reopen className="size-3.5" />
515 <T>
516 Reopen{" "}
517 <Branch
518 branch={changeRequestTermKind(terminology)}
519 mr="merge request"
520 cr="change request"
521 >
522 pull request
523 </Branch>
524 </T>
525 </MenuItem>
526 </>
527 ) : detail.state === "merged" && can("revert") ? (
528 <>
529 <MenuSeparator />
530 <MenuItem
531 closeOnClick={inlineConfirm.isArmed("revert")}
532 aria-label={
533 inlineConfirm.isArmed("revert") ? gt("Confirm revert?") : gt("Revert changes")
534 }
535 variant={inlineConfirm.isArmed("revert") ? "destructive" : "default"}
536 disabled={actionPending}
537 {...inlineConfirm.props("revert", () => void perform("revert"))}
538 >
539 <RotateCcwIcon className="size-3.5" />
540 {inlineConfirm.isArmed("revert") ? gt("Confirm revert?") : gt("Revert changes")}
541 </MenuItem>
542 </>
543 ) : null}
544 {showsDeleteBranch ? (
545 <>
546 <MenuSeparator />
547 <MenuItem
548 variant="destructive"
549 disabled={actionPending || !environmentConnected}
550 onClick={() => void confirmDeleteBranch()}
551 >
552 <Trash2Icon className="mt-1 size-3.5 shrink-0 self-start" />
553 <span className="flex min-w-0 flex-col">
554 <span>
555 {pendingAction === "delete-branch"
556 ? gt("Deleting branch...")
557 : gt("Delete branch")}
558 </span>
559 <span className="truncate text-xs text-muted-foreground">
560 {environmentConnected ? detail.headBranch : gt("Reconnect to delete this branch")}
561 </span>
562 </span>
563 </MenuItem>
564 </>
565 ) : null}
566 </MenuPopup>
567 </Menu>
568 );