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

PullRequestMergeControls.tsx

290 lines11.7 KB

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 { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
6import type { PullRequestDetail, PullRequestMergeMethod } from "@t3tools/contracts";
7import { AsyncResult } from "effect/reactivity";
8import { useRef, useState } from "react";
9import { Platform, Pressable, View } from "react-native";
10import { AppText as Text } from "../../components/ui/AppText";
11import { SymbolView } from "../../components/ui/AppSymbol";
12import { Menu } from "../../components/ui/Menu";
13import { Button } from "../../components/ui/Button";
14import { IconButton } from "../../components/ui/IconButton";
15import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
16import { composerPullRequests } from "../../state/pull-requests";
17import { useAtomCommand } from "../../state/use-atom-command";
18import {
19 allowedMergeMethods,
20 canPerformPullRequestAction,
21 mergeUnavailableReason,
22 MERGE_CONFLICT_REASON,
23 MERGE_METHODS,
24 pullRequestActionLabel,
25} from "./pullRequestActions";
26import { pullRequestStackMerge, singlePullRequestMergeAllowed } from "./pullRequestStack";
27import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
28import { usePullRequestPermissions } from "./usePullRequestPermissions";
29import type { PullRequestStackState } from "./usePullRequestStack";
30import { PullRequestGlyph } from "./pullRequestGlyphs";
31​
32export function PullRequestMergeControls(props: {
33 readonly pr: PullRequestDetail;
34 readonly params: PullRequestParams;
35 readonly stack: PullRequestStackState;
36}) {
37 const { pr, stack } = props;
38 const terminology = sourceControlClients.get(pr.provider).changeRequest;
39 const target = pullRequestTarget(props.params);
40 const permissions = usePullRequestPermissions(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 autoAction = pr.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge";
89 const canAutoMerge =
90 !busy &&
91 (autoAction === "disable-auto-merge" || (!stack.stack && canMergeSingle)) &&
92 permissions.canWrite &&
93 canPerformPullRequestAction(pr, autoAction);
94​
95 const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
96 if (
97 pending.current ||
98 (action !== "disable-auto-merge" && !method) ||
99 (action === "merge" ? !canMerge : !canAutoMerge)
100 )
101 return;
102 pending.current = true;
103 setBusy(true);
104 const response = await runAction({
105 ...target,
106 input: {
107 ...target.input,
108 action,
109 ...(action === "merge" && method && stack.stack && scope
110 ? {
111 stackNumber: stack.stack.number,
112 expectedStackHeads: scope.heads,
113 mergeMethod: method,
114 }
115 : action === "merge" && method
116 ? {
117 resolveMergeMethod: (fresh) => {
118 if (
119 !canPerformPullRequestAction(fresh, "merge") ||
120 !allowedMergeMethods(fresh).includes(method)
121 )
122 throw new Error(`The ${terminology.singular} changed. Refresh before merging.`);
123 return method;
124 },
125 }
126 : action === "enable-auto-merge" && method
127 ? { mergeMethod: method }
128 : {}),
129 },
130 });
131 // A stack can partly merge before the provider reports a failure.
132 refreshDetail();
133 refreshActivity();
134 stack.refresh();
135 pending.current = false;
136 setBusy(false);
137 if (AsyncResult.isFailure(response)) {
138 const cause = squashAtomCommandFailure(response);
139 Dialog.alert(
140 "Couldn't complete the merge action",
141 cause instanceof Error ? cause.message : "Try again.",
142 );
143 }
144 };
145 const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => {
146 const title =
147 action === "merge"
148 ? scope && scope.layers.length > 1
149 ? `Merge ${scope.layers.length} stack layers?`
150 : `${pullRequestActionLabel("merge", terminology)}?`
151 : action === "enable-auto-merge"
152 ? "Enable auto-merge?"
153 : "Disable auto-merge?";
154 const message =
155 action === "merge" && scope
156 ? `Merge ${scope.layers.map((layer) => `#${layer.number}`).join(" → ")} into ${stack.stack?.base} using ${method}. Layers above #${pr.number} stay open.`
157 : action === "enable-auto-merge"
158 ? `Merge #${pr.number} using ${method} when its requirements are met. This may happen immediately.`
159 : action === "disable-auto-merge"
160 ? `Stop the provider from automatically merging this ${terminology.singular}.`
161 : `Merge #${pr.number} into ${pr.baseBranch} using ${method}.`;
162 Dialog.alert(title, message, [
163 { text: "Cancel", style: "cancel" },
164 {
165 text: action === "merge" ? label : title.replace("?", ""),
166 onPress: () => void perform(action),
167 },
168 ]);
169 };
170 return (
171 <View className="gap-2 border-t border-border-subtle p-3">
172 <View
173 className={
174 Platform.OS === "android"
175 ? "flex-row items-center gap-2"
176 : `flex-row overflow-hidden rounded-xl border-continuous ${canMerge ? "bg-prominent-action" : "bg-subtle-strong"}`
177 }
178 >
179 {Platform.OS === "android" ? (
180 <View className="min-w-0 flex-1">
181 <Button
182 label={busy ? "Working…" : !permissions.connected ? "Reconnect to merge" : label}
183 tone="primary"
184 fullWidth
185 disabled={!canMerge}
186 loading={busy || checkingStack}
187 onPress={() => confirm("merge")}
188 />
189 </View>
190 ) : (
191 <Pressable
192 accessibilityRole="button"
193 accessibilityLabel={
194 scope ? `${label}, ${scope.layers.length} stack layers through #${pr.number}` : label
195 }
196 accessibilityState={{ disabled: !canMerge, busy: busy || checkingStack }}
197 disabled={!canMerge}
198 onPress={() => confirm("merge")}
199 className="min-h-11 min-w-0 flex-1 flex-row items-center justify-center gap-2 px-3 py-2 active:opacity-70"
200 >
201 {busy || checkingStack ? (
202 <AppActivityIndicator size="small" colorClassName="accent-icon-muted" />
203 ) : (
204 <SymbolView
205 name={PullRequestGlyph.merged}
206 size={16}
207 tintColorClassName={
208 canMerge ? "accent-prominent-action-foreground" : "accent-icon-muted"
209 }
210 />
211 )}
212 <Text
213 className={`shrink text-center text-sm font-t3-semibold ${canMerge ? "text-prominent-action-foreground" : "text-foreground-muted"}`}
214 >
215 {busy ? "Working…" : !permissions.connected ? "Reconnect to merge" : label}
216 </Text>
217 </Pressable>
218 )}
219 {methods.length > 0 || canAutoMerge ? (
220 <Menu
221 title="Merge options"
222 actions={[
223 ...methods.map((id) => ({
224 id,
225 title: MERGE_METHODS[id].title,
226 state: id === method ? ("on" as const) : ("off" as const),
227 attributes: { disabled: busy },
228 })),
229 ...(canAutoMerge
230 ? [
231 {
232 id: autoAction,
233 title: pr.autoMergeEnabled ? "Disable auto-merge" : "Enable auto-merge",
234 image: "clock",
235 },
236 ]
237 : []),
238 ]}
239 onPressAction={({ nativeEvent }) => {
240 const selected = methods.find((id) => id === nativeEvent.event);
241 if (selected) {
242 setSelectedMethod(selected);
243 savePreferences({ pullRequestMergeMethod: selected });
244 } else if (nativeEvent.event === autoAction && canAutoMerge) confirm(autoAction);
245 }}
246 >
247 {Platform.OS === "android" ? (
248 <View pointerEvents="none">
249 <IconButton
250 accessibilityLabel="Merge options"
251 icon="chevron.down"
252 variant="tonal"
253 />
254 </View>
255 ) : (
256 <Pressable
257 accessibilityRole="button"
258 accessibilityLabel="Merge options"
259 className="min-h-11 w-11 items-center justify-center border-l border-border-subtle"
260 >
261 <SymbolView
262 name="chevron.down"
263 size={13}
264 tintColorClassName={
265 canMerge ? "accent-prominent-action-foreground" : "accent-icon-muted"
266 }
267 />
268 </Pressable>
269 )}
270 </Menu>
271 ) : null}
272 </View>
273 {permissions.connected &&
274 reason &&
275 reason !== MERGE_CONFLICT_REASON &&
276 reason !== "Checking stack membership…" &&
277 !(checkingStack && reason === "Refresh the stack before merging.") ? (
278 <Text className="px-1 text-xs text-foreground-muted">{reason}</Text>
279 ) : null}
280 {pr.autoMergeEnabled ? (
281 <Text className="px-1 text-xs text-foreground-muted">
282 Auto-merge is enabled{pr.autoMergeMethod ? ` · ${pr.autoMergeMethod}` : ""}
283 </Text>
284 ) : null}
285 {stack.error && stack.supportsStackActions ? (
286 <Button label="Retry stack lookup" tone="text" onPress={stack.refresh} />
287 ) : null}
288 </View>
289 );