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

PullRequestActionsMenu.tsx

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