Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useAtomRefresh } from "@effect/atom-react";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import type {
5 PullRequestAction,
6 PullRequestDetail,
7 PullRequestUpdateMethod,
8} from "@t3tools/contracts";
9import { useRef, useState } from "react";
10import { composerPullRequests } from "../../state/pull-requests";
11import { useAtomCommand } from "../../state/use-atom-command";
12import { canPerformPullRequestAction } from "./pullRequestActions";
13import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
14import { usePullRequestPermissions } from "./usePullRequestPermissions";
15
16export function usePullRequestAction(params: PullRequestParams, pr: PullRequestDetail | null) {
17 const target = pullRequestTarget(params);
18 const permissions = usePullRequestPermissions(params, pr);
19 const run = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
20 const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
21 const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
22 const pending = useRef(false);
23 const [busy, setBusy] = useState(false);
24 const available = (action: PullRequestAction) =>
25 pr !== null && !busy && permissions.canWrite && canPerformPullRequestAction(pr, action);
26 const perform = async (action: PullRequestAction, updateMethod?: PullRequestUpdateMethod) => {
27 if (pending.current || !available(action)) return;
28 pending.current = true;
29 setBusy(true);
30 try {
31 const response = await run({
32 ...target,
33 input: { ...target.input, action, ...(updateMethod ? { updateMethod } : {}) },
34 });
35 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
36 refreshDetail();
37 refreshActivity();
38 } catch (cause) {
39 Dialog.alert(
40 "Couldn't update this pull request",
41 cause instanceof Error ? cause.message : "Try again.",
42 );
43 } finally {
44 pending.current = false;
45 setBusy(false);
46 }
47 };
48 const confirm = (action: PullRequestAction, title: string, message: string) =>
49 Dialog.alert(title, message, [
50 { text: "Cancel", style: "cancel" },
51 {
52 text: title,
53 style: action === "close" || action === "delete-branch" ? "destructive" : "default",
54 onPress: () => void perform(action),
55 },
56 ]);
57 return { available, perform, confirm, busy };
58}