Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5import type { PullRequestDetail, PullRequestMergeMethod } from "@t3tools/contracts";
6import { AsyncResult } from "effect/reactivity";
7import { useRef, useState } from "react";
8import { View } from "react-native";
9import { AppText as Text } from "../../components/ui/AppText";
10import { Button } from "../../components/ui/Button";
11import { SplitButton } from "../../components/ui/SplitButton";
12import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
13import { composerPullRequests } from "../../state/pull-requests";
14import { useAtomCommand } from "../../state/use-atom-command";
15import {
16 allowedMergeMethods,
17 canPerformPullRequestAction,
18 mergeUnavailableReason,
19 MERGE_CONFLICT_REASON,
20 MERGE_METHODS,
21 pullRequestActionLabel,
22} from "./pullRequestActions";
23import { pullRequestStackMerge, singlePullRequestMergeAllowed } from "./pullRequestStack";
24import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
25import { usePullRequestPermissions } from "./usePullRequestPermissions";
26import { PullRequestGlyph } from "./pullRequestGlyphs";
27import type { PullRequestStackState } from "./usePullRequestStack";
28
29export function PullRequestMergeControls(props: {
30 readonly pr: PullRequestDetail;
31 readonly params: PullRequestParams;
32 readonly stack: PullRequestStackState;
33}) {
34 const { pr, stack } = props;
35 const terminology = sourceControlClients.get(pr.provider).changeRequest;
36 const target = pullRequestTarget(props.params);
37 const permissions = usePullRequestPermissions(props.params, pr);
38 const preferences = useAtomValue(mobilePreferencesAtom);
39 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
40 const runAction = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
41 const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
42 const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
43 const [selectedMethod, setSelectedMethod] = useState<PullRequestMergeMethod | null>(null);
44 const [busy, setBusy] = useState(false);
45 const pending = useRef(false);
46 const methods = allowedMergeMethods(pr);
47 const preferred =
48 selectedMethod ??
49 (AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined) ??
50 "squash";
51 const method = methods.includes(preferred)
52 ? preferred
53 : methods.includes("squash")
54 ? "squash"
55 : methods[0];
56 const scope = stack.stack ? pullRequestStackMerge(stack.stack, pr.number, terminology) : null;
57 const canMergeSingle = singlePullRequestMergeAllowed({
58 supportsStackActions: stack.supportsStackActions,
59 hasStack: stack.stack !== null,
60 isFresh: stack.isFresh,
61 });
62 const checkingStack =
63 permissions.connected && stack.supportsStackActions && !stack.isFresh && !stack.error;
64 const reason =
65 (!permissions.connected
66 ? "Reconnect to merge."
67 : mergeUnavailableReason(pr, permissions.canWrite, terminology)) ??
68 (stack.stack
69 ? !stack.supportsStackActions
70 ? "This environment can display stacks but cannot merge them."
71 : !stack.isFresh
72 ? "Refresh the stack before merging."
73 : scope?.reason
74 : !canMergeSingle
75 ? stack.error
76 ? "Couldn't check stack membership. Refresh before merging."
77 : "Checking stack membership…"
78 : null);
79 const canMerge = !busy && method !== undefined && !reason;
80 const label = method
81 ? scope && scope.layers.length > 1
82 ? `${MERGE_METHODS[method].title} stack (${scope.layers.length})`
83 : MERGE_METHODS[method].title
84 : "Merge unavailable";
85 const autoAction = pr.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge";
86 const canAutoMerge =
87 !busy &&
88 (autoAction === "disable-auto-merge" || (!stack.stack && canMergeSingle)) &&
89 permissions.canWrite &&
90 canPerformPullRequestAction(pr, autoAction);
91
92 const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
93 if (
94 pending.current ||
95 (action !== "disable-auto-merge" && !method) ||
96 (action === "merge" ? !canMerge : !canAutoMerge)
97 )
98 return;
99 pending.current = true;
100 setBusy(true);
101 const response = await runAction({
102 ...target,
103 input: {
104 ...target.input,
105 action,
106 ...(action === "merge" && method && stack.stack && scope
107 ? {
108 stackNumber: stack.stack.number,
109 expectedStackHeads: scope.heads,
110 mergeMethod: method,
111 }
112 : action === "merge" && method
113 ? {
114 resolveMergeMethod: (fresh) => {
115 if (
116 !canPerformPullRequestAction(fresh, "merge") ||
117 !allowedMergeMethods(fresh).includes(method)
118 )
119 throw new Error(`The ${terminology.singular} changed. Refresh before merging.`);
120 return method;
121 },
122 }
123 : action === "enable-auto-merge" && method
124 ? { mergeMethod: method }
125 : {}),
126 },
127 });
128 // A stack can partly merge before the provider reports a failure.
129 refreshDetail();
130 refreshActivity();
131 stack.refresh();
132 pending.current = false;
133 setBusy(false);
134 if (AsyncResult.isFailure(response)) {
135 const cause = squashAtomCommandFailure(response);
136 Dialog.alert(
137 "Couldn't complete the merge action",
138 cause instanceof Error ? cause.message : "Try again.",
139 );
140 }
141 };
142 const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
143 const title =
144 action === "merge"
145 ? scope && scope.layers.length > 1
146 ? `Merge ${scope.layers.length} stack layers?`
147 : `${pullRequestActionLabel("merge", terminology)}?`
148 : action === "enable-auto-merge"
149 ? "Enable auto-merge?"
150 : "Disable auto-merge?";
151 const message =
152 action === "merge" && scope
153 ? `Merge ${scope.layers.map((layer) => `#${layer.number}`).join(" → ")} into ${stack.stack?.base} using ${method}. Layers above #${pr.number} stay open.`
154 : action === "enable-auto-merge"
155 ? `Merge #${pr.number} using ${method} when its requirements are met. This may happen immediately.`
156 : action === "disable-auto-merge"
157 ? `Stop the provider from automatically merging this ${terminology.singular}.`
158 : `Merge #${pr.number} into ${pr.baseBranch} using ${method}.`;
159 Dialog.alert(title, message, [
160 { text: "Cancel", style: "cancel" },
161 {
162 text: action === "merge" ? label : title.replace("?", ""),
163 onPress: () => void perform(action),
164 },
165 ]);
166 };
167 return (
168 <View className="gap-2 border-t border-border-subtle p-3">
169 <SplitButton
170 label={busy ? "Working…" : !permissions.connected ? "Reconnect to merge" : label}
171 accessibilityLabel={
172 scope ? `${label}, ${scope.layers.length} stack layers through #${pr.number}` : label
173 }
174 icon={PullRequestGlyph.merged}
175 disabled={!canMerge}
176 loading={busy || checkingStack}
177 onPress={() => confirm("merge")}
178 menuTitle="Merge options"
179 actions={[
180 ...methods.map((id) => ({
181 id,
182 title: MERGE_METHODS[id].title,
183 state: id === method ? ("on" as const) : ("off" as const),
184 attributes: { disabled: !canMerge && !canAutoMerge },
185 })),
186 ...(canAutoMerge
187 ? [
188 {
189 id: autoAction,
190 title: pr.autoMergeEnabled ? "Disable auto-merge" : "Enable auto-merge",
191 image: "clock",
192 },
193 ]
194 : []),
195 ]}
196 onPressAction={(id) => {
197 const selected = methods.find((method) => method === id);
198 if (selected) {
199 setSelectedMethod(selected);
200 savePreferences({ pullRequestMergeMethod: selected });
201 } else if (id === autoAction && canAutoMerge) confirm(autoAction);
202 }}
203 />
204 {permissions.connected &&
205 reason &&
206 reason !== MERGE_CONFLICT_REASON &&
207 reason !== "Checking stack membership…" &&
208 !(checkingStack && reason === "Refresh the stack before merging.") ? (
209 <Text className="px-1 text-xs text-foreground-muted">{reason}</Text>
210 ) : null}
211 {pr.autoMergeEnabled ? (
212 <Text className="px-1 text-xs text-foreground-muted">
213 Auto-merge is enabled{pr.autoMergeMethod ? ` · ${pr.autoMergeMethod}` : ""}
214 </Text>
215 ) : null}
216 {stack.error && stack.supportsStackActions ? (
217 <Button label="Retry stack lookup" tone="text" onPress={stack.refresh} />
218 ) : null}
219 </View>
220 );
221}