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_METHODS,
20 PR_ACTION_ICONS,
21 pullRequestActionLabel,
22} from "./pullRequestActions";
23import { pullRequestStackMerge, singlePullRequestMergeAllowed } from "./pullRequestStack";
24import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
25import { usePullRequestAction } from "./usePullRequestAction";
26import { usePullRequestPermissions } from "./usePullRequestPermissions";
27import { PullRequestGlyph } from "./pullRequestGlyphs";
28import type { AppSymbolName } from "../../components/ui/AppSymbol";
29import type { PullRequestStackState } from "./usePullRequestStack";
30
31export function PullRequestMergeControls(props: {
32 readonly pr: PullRequestDetail;
33 readonly params: PullRequestParams;
34 readonly stack: PullRequestStackState;
35}) {
36 const { pr, stack } = props;
37 const terminology = sourceControlClients.get(pr.provider).changeRequest;
38 const target = pullRequestTarget(props.params);
39 const permissions = usePullRequestPermissions(props.params, pr);
40 const stateAction = usePullRequestAction(props.params, pr);
41 const preferences = useAtomValue(mobilePreferencesAtom);
42 const savePreferences = useAtomSet(updateMobilePreferencesAtom);
43 const runAction = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
44 const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
45 const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
46 const [selectedMethod, setSelectedMethod] = useState<PullRequestMergeMethod | null>(null);
47 const [busy, setBusy] = useState(false);
48 const pending = useRef(false);
49 const methods = allowedMergeMethods(pr);
50 const preferred =
51 selectedMethod ??
52 (AsyncResult.isSuccess(preferences) ? preferences.value.pullRequestMergeMethod : undefined) ??
53 "squash";
54 const method = methods.includes(preferred)
55 ? preferred
56 : methods.includes("squash")
57 ? "squash"
58 : methods[0];
59 const scope = stack.stack ? pullRequestStackMerge(stack.stack, pr.number, terminology) : null;
60 const canMergeSingle = singlePullRequestMergeAllowed({
61 supportsStackActions: stack.supportsStackActions,
62 hasStack: stack.stack !== null,
63 isFresh: stack.isFresh,
64 });
65 const checkingStack =
66 permissions.connected && stack.supportsStackActions && !stack.isFresh && !stack.error;
67 const reason =
68 (!permissions.connected
69 ? "Reconnect to merge."
70 : mergeUnavailableReason(pr, permissions.canWrite, terminology)) ??
71 (stack.stack
72 ? !stack.supportsStackActions
73 ? "This environment can display stacks but cannot merge them."
74 : !stack.isFresh
75 ? "Refresh the stack before merging."
76 : scope?.reason
77 : !canMergeSingle
78 ? stack.error
79 ? "Couldn't check stack membership. Refresh before merging."
80 : "Checking stack membership…"
81 : null);
82 const canMerge = !busy && method !== undefined && !reason;
83 const label = method
84 ? scope && scope.layers.length > 1
85 ? `${MERGE_METHODS[method].title} stack (${scope.layers.length})`
86 : MERGE_METHODS[method].title
87 : "Merge unavailable";
88 const nextAction =
89 pr.state === "closed" ? "reopen" : pr.state === "open" && pr.isDraft ? "ready" : null;
90 // States the button itself names, instead of a reason line under it. Draft and
91 // closed offer their way forward when the viewer can take it.
92 const status: {
93 label: string;
94 icon: AppSymbolName;
95 final?: boolean;
96 action?: "ready" | "reopen";
97 } | null =
98 nextAction && stateAction.available(nextAction)
99 ? {
100 label: pullRequestActionLabel(nextAction, terminology),
101 icon: PR_ACTION_ICONS[nextAction],
102 final: nextAction === "reopen",
103 action: nextAction,
104 }
105 : pr.state === "merged"
106 ? { label: "Merged", icon: PullRequestGlyph.merged, final: true }
107 : pr.state === "closed"
108 ? { label: "Closed", icon: PullRequestGlyph.closed, final: true }
109 : pr.isDraft
110 ? { label: "Draft", icon: PullRequestGlyph.draft }
111 : pr.mergeability === "conflicting"
112 ? { label: "Resolve conflicts to merge", icon: PullRequestGlyph.conflicting }
113 : pr.autoMergeEnabled
114 ? {
115 label: `Auto-merge pending${pr.autoMergeMethod ? ` (${pr.autoMergeMethod})` : ""}`,
116 icon: "clock",
117 }
118 : checkingStack && !busy
119 ? { label: "Checking stack…", icon: PullRequestGlyph.merged }
120 : null;
121 const autoAction = pr.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge";
122 const canAutoMerge =
123 !busy &&
124 (autoAction === "disable-auto-merge" || (!stack.stack && canMergeSingle)) &&
125 permissions.canWrite &&
126 canPerformPullRequestAction(pr, autoAction);
127
128 const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
129 if (
130 pending.current ||
131 (action !== "disable-auto-merge" && !method) ||
132 (action === "merge" ? !canMerge : !canAutoMerge)
133 )
134 return;
135 pending.current = true;
136 setBusy(true);
137 const response = await runAction({
138 ...target,
139 input: {
140 ...target.input,
141 action,
142 ...(action === "merge" && method && stack.stack && scope
143 ? {
144 stackNumber: stack.stack.number,
145 expectedStackHeads: scope.heads,
146 mergeMethod: method,
147 }
148 : action === "merge" && method
149 ? {
150 resolveMergeMethod: (fresh) => {
151 if (
152 !canPerformPullRequestAction(fresh, "merge") ||
153 !allowedMergeMethods(fresh).includes(method)
154 )
155 throw new Error(`The ${terminology.singular} changed. Refresh before merging.`);
156 return method;
157 },
158 }
159 : action === "enable-auto-merge" && method
160 ? { mergeMethod: method }
161 : {}),
162 },
163 });
164 // A stack can partly merge before the provider reports a failure.
165 if (!AsyncResult.isSuccess(response)) refreshDetail();
166 refreshActivity();
167 stack.refresh();
168 pending.current = false;
169 setBusy(false);
170 if (AsyncResult.isFailure(response)) {
171 const cause = squashAtomCommandFailure(response);
172 Dialog.alert(
173 "Couldn't complete the merge action",
174 cause instanceof Error ? cause.message : "Try again.",
175 );
176 }
177 };
178 const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
179 const title =
180 action === "merge"
181 ? scope && scope.layers.length > 1
182 ? `Merge ${scope.layers.length} stack layers?`
183 : `${pullRequestActionLabel("merge", terminology)}?`
184 : action === "enable-auto-merge"
185 ? "Enable auto-merge?"
186 : "Disable auto-merge?";
187 const message =
188 action === "merge" && scope
189 ? `Merge ${scope.layers.map((layer) => `#${layer.number}`).join(" → ")} into ${stack.stack?.base} using ${method}. Layers above #${pr.number} stay open.`
190 : action === "enable-auto-merge"
191 ? `Merge #${pr.number} using ${method} when its requirements are met. This may happen immediately.`
192 : action === "disable-auto-merge"
193 ? `Stop the provider from automatically merging this ${terminology.singular}.`
194 : `Merge #${pr.number} into ${pr.baseBranch} using ${method}.`;
195 Dialog.alert(title, message, [
196 { text: "Cancel", style: "cancel" },
197 {
198 text: action === "merge" ? label : title.replace("?", ""),
199 onPress: () => void perform(action),
200 },
201 ]);
202 };
203 return (
204 <View className="gap-2 border-t border-border-subtle p-3">
205 <SplitButton
206 label={
207 busy || stateAction.busy
208 ? "Working…"
209 : !permissions.connected
210 ? "Reconnect to merge"
211 : (status?.label ?? label)
212 }
213 accessibilityLabel={
214 status
215 ? status.label
216 : scope
217 ? `${label}, ${scope.layers.length} stack layers through #${pr.number}`
218 : label
219 }
220 icon={status?.icon ?? PullRequestGlyph.merged}
221 disabled={status?.action ? stateAction.busy : !canMerge || status !== null}
222 loading={busy || stateAction.busy || (!status?.action && checkingStack)}
223 onPress={() =>
224 status?.action ? void stateAction.perform(status.action) : confirm("merge")
225 }
226 menuTitle="Merge options"
227 actions={
228 status?.final
229 ? []
230 : [
231 ...methods.map((id) => ({
232 id,
233 title: MERGE_METHODS[id].title,
234 state: id === method ? ("on" as const) : ("off" as const),
235 attributes: { disabled: !canMerge && !canAutoMerge },
236 })),
237 ...(canAutoMerge
238 ? [
239 {
240 id: autoAction,
241 title: pr.autoMergeEnabled ? "Disable auto-merge" : "Enable auto-merge",
242 image: "clock",
243 },
244 ]
245 : []),
246 ]
247 }
248 onPressAction={(id) => {
249 const selected = methods.find((method) => method === id);
250 if (selected) {
251 setSelectedMethod(selected);
252 savePreferences({ pullRequestMergeMethod: selected });
253 } else if (id === autoAction && canAutoMerge) confirm(autoAction);
254 }}
255 />
256 {permissions.connected && !status && reason ? (
257 <Text className="px-1 text-xs text-foreground-muted">{reason}</Text>
258 ) : null}
259 {stack.error && stack.supportsStackActions ? (
260 <Button label="Retry stack lookup" tone="text" onPress={stack.refresh} />
261 ) : null}
262 </View>
263 );
264}