Open History to see the last commit
1import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
2import * as Dialog from "../../components/ui/Dialog";
3import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
4import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import type { PullRequestDetail, PullRequestMergeMethod } from "@t3tools/contracts";
6import { AsyncResult } from "effect/reactivity";
7import { useRef, useState } from "react";
8import { Platform, Pressable, View } from "react-native";
9import { AppText as Text } from "../../components/ui/AppText";
10import { SymbolView } from "../../components/ui/AppSymbol";
11import { Menu } from "../../components/ui/Menu";
12import { Button } from "../../components/ui/Button";
13import { IconButton } from "../../components/ui/IconButton";
14import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
15import { composerPullRequests } from "../../state/pull-requests";
16import { useAtomCommand } from "../../state/use-atom-command";
17import {
18 allowedMergeMethods,
19 canPerformPullRequestAction,
20 mergeUnavailableReason,
21 MERGE_CONFLICT_REASON,
22 MERGE_METHODS,
23} from "./pullRequestActions";
24import { pullRequestStackMerge, singlePullRequestMergeAllowed } from "./pullRequestStack";
25import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
26import { usePullRequestPermissions } from "./usePullRequestPermissions";
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 target = pullRequestTarget(props.params);
36 const permissions = usePullRequestPermissions(props.params, pr);
37 const preferences = useAtomValue(mobilePreferencesAtom);
38 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
39 const runAction = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
40 const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
41 const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
42 const [selectedMethod, setSelectedMethod] = useState<PullRequestMergeMethod | null>(null);
43 const [busy, setBusy] = useState(false);
44 const pending = useRef(false);
45 const methods = allowedMergeMethods(pr);
46 const preferred =
47 selectedMethod ??
48 (AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined) ??
49 "squash";
50 const method = methods.includes(preferred)
51 ? preferred
52 : methods.includes("squash")
53 ? "squash"
54 : methods[0];
55 const scope = stack.stack ? pullRequestStackMerge(stack.stack, pr.number) : null;
56 const canMergeSingle = singlePullRequestMergeAllowed({
57 supportsStackActions: stack.supportsStackActions,
58 hasStack: stack.stack !== null,
59 isFresh: stack.isFresh,
60 });
61 const checkingStack =
62 permissions.connected && stack.supportsStackActions && !stack.isFresh && !stack.error;
63 const reason =
64 (!permissions.connected
65 ? "Reconnect to merge."
66 : mergeUnavailableReason(pr, permissions.canWrite)) ??
67 (stack.stack
68 ? !stack.supportsStackActions
69 ? "This environment can display stacks but cannot merge them."
70 : !stack.isFresh
71 ? "Refresh the stack before merging."
72 : scope?.reason
73 : !canMergeSingle
74 ? stack.error
75 ? "Couldn't check stack membership. Refresh before merging."
76 : "Checking stack membership…"
77 : null);
78 const canMerge = !busy && method !== undefined && !reason;
79 const label = method
80 ? scope && scope.layers.length > 1
81 ? `${MERGE_METHODS[method].title} stack (${scope.layers.length})`
82 : MERGE_METHODS[method].title
83 : "Merge unavailable";
84 const autoAction = pr.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge";
85 const canAutoMerge =
86 !busy &&
87 (autoAction === "disable-auto-merge" || (!stack.stack && canMergeSingle)) &&
88 permissions.canWrite &&
89 canPerformPullRequestAction(pr, autoAction);
90
91 const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
92 if (
93 pending.current ||
94 (action !== "disable-auto-merge" && !method) ||
95 (action === "merge" ? !canMerge : !canAutoMerge)
96 )
97 return;
98 pending.current = true;
99 setBusy(true);
100 try {
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 pull request changed. Refresh before merging.");
120 return method;
121 },
122 }
123 : action === "enable-auto-merge" && method
124 ? { mergeMethod: method }
125 : {}),
126 },
127 });
128 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
129 } catch (cause) {
130 Dialog.alert(
131 "Couldn't complete the merge action",
132 cause instanceof Error ? cause.message : "Try again.",
133 );
134 } finally {
135 // A stack can partly merge before the provider reports a failure.
136 refreshDetail();
137 refreshActivity();
138 stack.refresh();
139 pending.current = false;
140 setBusy(false);
141 }
142 };
143 const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
144 const title =
145 action === "merge"
146 ? scope && scope.layers.length > 1
147 ? `Merge ${scope.layers.length} stack layers?`
148 : "Merge pull request?"
149 : action === "enable-auto-merge"
150 ? "Enable auto-merge?"
151 : "Disable auto-merge?";
152 const message =
153 action === "merge" && scope
154 ? `Merge ${scope.layers.map((layer) => `#${layer.number}`).join(" → ")} into ${stack.stack?.base} using ${method}. Layers above #${pr.number} stay open.`
155 : action === "enable-auto-merge"
156 ? `Merge #${pr.number} using ${method} when its requirements are met. This may happen immediately.`
157 : action === "disable-auto-merge"
158 ? "Stop the provider from automatically merging this pull request."
159 : `Merge #${pr.number} into ${pr.baseBranch} using ${method}.`;
160 Dialog.alert(title, message, [
161 { text: "Cancel", style: "cancel" },
162 {
163 text: action === "merge" ? label : title.replace("?", ""),
164 onPress: () => void perform(action),
165 },
166 ]);
167 };
168 return (
169 <View className="gap-2 border-t border-border-subtle p-3">
170 <View
171 className={
172 Platform.OS === "android"
173 ? "flex-row items-center gap-2"
174 : `flex-row overflow-hidden rounded-xl border-continuous ${canMerge ? "bg-prominent-action" : "bg-subtle-strong"}`
175 }
176 >
177 {Platform.OS === "android" ? (
178 <View className="min-w-0 flex-1">
179 <Button
180 label={busy ? "Working…" : !permissions.connected ? "Reconnect to merge" : label}
181 tone="primary"
182 fullWidth
183 disabled={!canMerge}
184 loading={busy || checkingStack}
185 onPress={() => confirm("merge")}
186 />
187 </View>
188 ) : (
189 <Pressable
190 accessibilityRole="button"
191 accessibilityLabel={
192 scope ? `${label}, ${scope.layers.length} stack layers through #${pr.number}` : label
193 }
194 accessibilityState={{ disabled: !canMerge, busy: busy || checkingStack }}
195 disabled={!canMerge}
196 onPress={() => confirm("merge")}
197 className="min-h-11 min-w-0 flex-1 flex-row items-center justify-center gap-2 px-3 py-2 active:opacity-70"
198 >
199 {busy || checkingStack ? (
200 <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
201 ) : (
202 <SymbolView
203 name="arrow.triangle.merge"
204 size={16}
205 tintColorClassName={
206 canMerge ? "accent-prominent-action-foreground" : "accent-icon-muted"
207 }
208 />
209 )}
210 <Text
211 className={`shrink text-center text-sm font-t3-semibold ${canMerge ? "text-prominent-action-foreground" : "text-foreground-muted"}`}
212 >
213 {busy ? "Working…" : !permissions.connected ? "Reconnect to merge" : label}
214 </Text>
215 </Pressable>
216 )}
217 {methods.length > 0 || canAutoMerge ? (
218 <Menu
219 title="Merge options"
220 actions={[
221 ...methods.map((id) => ({
222 id,
223 title: MERGE_METHODS[id].title,
224 state: id === method ? ("on" as const) : ("off" as const),
225 attributes: { disabled: busy },
226 })),
227 ...(canAutoMerge
228 ? [
229 {
230 id: autoAction,
231 title: pr.autoMergeEnabled ? "Disable auto-merge" : "Enable auto-merge",
232 image: "clock",
233 },
234 ]
235 : []),
236 ]}
237 onPressAction={({ nativeEvent }) => {
238 const selected = methods.find((id) => id === nativeEvent.event);
239 if (selected) {
240 setSelectedMethod(selected);
241 savePreferences({ pullRequestMergeMethod: selected });
242 } else if (nativeEvent.event === autoAction && canAutoMerge) confirm(autoAction);
243 }}
244 >
245 {Platform.OS === "android" ? (
246 <View pointerEvents="none">
247 <IconButton
248 accessibilityLabel="Merge options"
249 icon="chevron.down"
250 variant="tonal"
251 />
252 </View>
253 ) : (
254 <Pressable
255 accessibilityRole="button"
256 accessibilityLabel="Merge options"
257 className="min-h-11 w-11 items-center justify-center border-l border-border-subtle"
258 >
259 <SymbolView
260 name="chevron.down"
261 size={13}
262 tintColorClassName={
263 canMerge ? "accent-prominent-action-foreground" : "accent-icon-muted"
264 }
265 />
266 </Pressable>
267 )}
268 </Menu>
269 ) : null}
270 </View>
271 {permissions.connected &&
272 reason &&
273 reason !== MERGE_CONFLICT_REASON &&
274 reason !== "Checking stack membership…" &&
275 !(checkingStack && reason === "Refresh the stack before merging.") ? (
276 <Text className="px-1 text-xs text-foreground-muted">{reason}</Text>
277 ) : null}
278 {pr.autoMergeEnabled ? (
279 <Text className="px-1 text-xs text-foreground-muted">
280 Auto-merge is enabled{pr.autoMergeMethod ? ` · ${pr.autoMergeMethod}` : ""}
281 </Text>
282 ) : null}
283 {stack.error && stack.supportsStackActions ? (
284 <Pressable
285 accessibilityRole="button"
286 onPress={stack.refresh}
287 className="min-h-11 justify-center px-1"
288 >
289 <Text className="text-sm text-primary-text">Retry stack lookup</Text>
290 </Pressable>
291 ) : null}
292 </View>
293 );
294}