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