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

usePullRequestAction.ts

58 lines2.4 KB

1import { AsyncResult } from "effect/reactivity";
2import * as Dialog from "../../components/ui/Dialog";
3import { useAtomRefresh } from "@effect/atom-react";
4import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import type {
6 PullRequestAction,
7 PullRequestDetail,
8 PullRequestUpdateMethod,
9} from "@t3tools/contracts";
10import { useRef, useState } from "react";
11import { composerPullRequests } from "../../state/pull-requests";
12import { useAtomCommand } from "../../state/use-atom-command";
13import { canPerformPullRequestAction } from "./pullRequestActions";
14import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
15import { usePullRequestPermissions } from "./usePullRequestPermissions";
16​
17export function usePullRequestAction(params: PullRequestParams, pr: PullRequestDetail | null) {
18 const target = pullRequestTarget(params);
19 const permissions = usePullRequestPermissions(params, pr);
20 const run = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
21 const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
22 const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
23 const pending = useRef(false);
24 const [busy, setBusy] = useState(false);
25 const available = (action: PullRequestAction) =>
26 pr !== null && !busy && permissions.canWrite && canPerformPullRequestAction(pr, action);
27 const perform = async (action: PullRequestAction, updateMethod?: PullRequestUpdateMethod) => {
28 if (pending.current || !available(action)) return;
29 pending.current = true;
30 setBusy(true);
31 const response = await run({
32 ...target,
33 input: { ...target.input, action, ...(updateMethod ? { updateMethod } : {}) },
34 });
35 pending.current = false;
36 setBusy(false);
37 if (AsyncResult.isFailure(response)) {
38 const cause = squashAtomCommandFailure(response);
39 Dialog.alert(
40 "Couldn't update this pull request",
41 cause instanceof Error ? cause.message : "Try again.",
42 );
43 return;
44 }
45 refreshDetail();
46 refreshActivity();
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 };