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

ThreadGitControls.tsx

282 lines9.6 KB

1import type {
2 EnvironmentId,
3 GitRunStackedActionResult,
4 ProjectScript,
5 ThreadId,
6 VcsStatusResult,
7} from "@t3tools/contracts";
8import {
9 type GitActionRequestInput,
10 requiresDefaultBranchConfirmation,
11 resolveQuickAction,
12} from "@t3tools/client-runtime/state/vcs";
13import { useLocalSearchParams, useRouter } from "expo-router";
14import Stack from "expo-router/stack";
15import { useCallback, useMemo } from "react";
16import { Alert } from "react-native";
17import { buildThreadFilesNavigation, buildThreadReviewRoutePath } from "../../lib/routes";
18import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
19import {
20 basename,
21 getTerminalStatusLabel,
22 projectScriptMenuIcon,
23 projectScriptMenuLabel,
24 type TerminalMenuSession,
25} from "../terminal/terminalMenu";
26​
27function truncateMiddle(value: string, maxLength: number): string {
28 if (value.length <= maxLength) {
29 return value;
30 }
31​
32 const headLength = Math.ceil((maxLength - 1) / 2);
33 const tailLength = Math.floor((maxLength - 1) / 2);
34 return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`;
36​
37function compactMenuBranchLabel(branch: string): string {
38 return truncateMiddle(branch, 24);
40​
41function compactMenuStatus(gitStatus: VcsStatusResult | null): string {
42 if (!gitStatus) {
43 return "Checking status";
44 }
45 if (!gitStatus.isRepo) {
46 return "Not a repo";
47 }
48​
49 const parts: string[] = [];
50 if (gitStatus.hasWorkingTreeChanges) {
51 parts.push(`${gitStatus.workingTree.files.length} changed`);
52 } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
53 parts.push("Clean");
54 }
55 if (gitStatus.aheadCount > 0) {
56 parts.push(`${gitStatus.aheadCount} ahead`);
57 }
58 if (gitStatus.behindCount > 0) {
59 parts.push(`${gitStatus.behindCount} behind`);
60 }
61 if (gitStatus.pr?.state === "open") {
62 parts.push(`PR #${gitStatus.pr.number}`);
63 }
64​
65 return parts.join(" · ");
67​
68export function ThreadGitControls(props: {
69 readonly currentBranch: string | null;
70 readonly gitStatus: VcsStatusResult | null;
71 readonly gitOperationLabel: string | null;
72 readonly canOpenTerminal: boolean;
73 readonly canOpenFiles: boolean;
74 readonly projectScripts: ReadonlyArray<ProjectScript>;
75 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
76 readonly onOpenTerminal: (terminalId?: string | null) => void;
77 readonly onOpenNewTerminal: () => void;
78 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
79 readonly onPull: () => Promise<void>;
80 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
81}) {
82 const router = useRouter();
83 const { environmentId, threadId } = useLocalSearchParams<{
84 environmentId: EnvironmentId;
85 threadId: ThreadId;
86 }>();
87 const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
88​
89 const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD";
90 const busy = gitOperationLabel !== null;
91 const isRepo = gitStatus?.isRepo ?? true;
92 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
93 const isDefaultRef = gitStatus?.isDefaultRef ?? false;
94​
95 const quickAction = useMemo(
96 () =>
97 isRepo
98 ? resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote)
99 : {
100 label: "Git unavailable",
101 disabled: true,
102 kind: "show_hint" as const,
103 hint: "This workspace is not a git repository.",
104 },
105 [busy, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo],
106 );
107​
108 const quickActionHint = quickAction.disabled
109 ? (quickAction.hint ?? "This action is unavailable.")
110 : null;
111​
112 const quickActionIcon = (() => {
113 if (quickAction.kind === "run_pull") return "arrow.down.circle";
114 if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
115 if (quickAction.kind === "run_action") {
116 if (quickAction.action === "commit") return "checkmark.circle";
117 if (quickAction.action === "push" || quickAction.action === "commit_push")
118 return "arrow.up.circle";
119 }
120 return "arrow.up.right.circle";
121 })();
122​
123 const openExistingPr = useCallback(async () => {
124 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
125 if (!prUrl) {
126 Alert.alert("No open PR", "This branch does not have an open pull request.");
127 return;
128 }
129 if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
130 Alert.alert("Unable to open PR", "The pull request could not be opened.");
131 }
132 }, [gitStatus]);
133​
134 const runActionWithPrompt = useCallback(
135 async (input: GitActionRequestInput) => {
136 const confirmableAction =
137 input.action === "push" ||
138 input.action === "create_pr" ||
139 input.action === "commit_push" ||
140 input.action === "commit_push_pr"
141 ? input.action
142 : null;
143 const branchName = gitStatus?.refName;
144 if (
145 branchName &&
146 confirmableAction &&
147 !input.featureBranch &&
148 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
149 ) {
150 router.push({
151 pathname: "/threads/[environmentId]/[threadId]/git-confirm",
152 params: {
153 environmentId,
154 threadId,
155 confirmAction: confirmableAction,
156 branchName,
157 includesCommit: String(
158 input.action === "commit_push" || input.action === "commit_push_pr",
159 ),
160 },
161 });
162 return;
163 }
164​
165 await onRunAction(input);
166 },
167 [environmentId, gitStatus, isDefaultRef, onRunAction, router, threadId],
168 );
169​
170 const runQuickAction = useCallback(async () => {
171 if (quickAction.kind === "open_pr") {
172 await openExistingPr();
173 return;
174 }
175 if (quickAction.kind === "run_pull") {
176 await onPull();
177 return;
178 }
179 if (quickAction.kind === "run_action" && quickAction.action) {
180 await runActionWithPrompt({ action: quickAction.action });
181 }
182 }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
183​
184 return (
185 <Stack.Toolbar placement="right">
186 <Stack.Toolbar.Menu icon="terminal" disabled={!props.canOpenTerminal} separateBackground>
187 {props.projectScripts.length > 0 ? (
188 props.projectScripts.map((script) => (
189 <Stack.Toolbar.MenuAction
190 key={script.id}
191 icon={projectScriptMenuIcon(script.icon)}
192 onPress={() => void props.onRunProjectScript(script)}
193 subtitle={script.command}
194 >
195 <Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
196 </Stack.Toolbar.MenuAction>
197 ))
198 ) : (
199 <Stack.Toolbar.MenuAction
200 icon="play"
201 disabled
202 onPress={() => {}}
203 subtitle="This project has no saved scripts yet"
204 >
205 <Stack.Toolbar.Label>No project scripts</Stack.Toolbar.Label>
206 </Stack.Toolbar.MenuAction>
207 )}
208 {props.terminalSessions.map((session) => (
209 <Stack.Toolbar.MenuAction
210 key={session.terminalId}
211 icon="terminal"
212 onPress={() => props.onOpenTerminal(session.terminalId)}
213 subtitle={[
214 getTerminalStatusLabel({
215 status: session.status,
216 hasRunningSubprocess: session.hasRunningSubprocess,
217 }),
218 basename(session.cwd),
219 ]
220 .filter(Boolean)
221 .join(" · ")}
222 >
223 <Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
224 </Stack.Toolbar.MenuAction>
225 ))}
226 <Stack.Toolbar.MenuAction
227 icon="plus"
228 onPress={props.onOpenNewTerminal}
229 subtitle="Start another shell for this thread"
230 >
231 <Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
232 </Stack.Toolbar.MenuAction>
233 </Stack.Toolbar.Menu>
234 <Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
235 <Stack.Toolbar.MenuAction
236 icon="point.topleft.down.curvedto.point.bottomright.up"
237 disabled
238 onPress={() => {}}
239 subtitle={compactMenuStatus(gitStatus)}
240 >
241 <Stack.Toolbar.Label>{compactMenuBranchLabel(currentBranchLabel)}</Stack.Toolbar.Label>
242 </Stack.Toolbar.MenuAction>
243 <Stack.Toolbar.MenuAction
244 icon={quickActionIcon}
245 disabled={quickAction.disabled}
246 onPress={() => void runQuickAction()}
247 subtitle={quickActionHint ?? undefined}
248 >
249 <Stack.Toolbar.Label>{quickAction.label}</Stack.Toolbar.Label>
250 </Stack.Toolbar.MenuAction>
251 <Stack.Toolbar.MenuAction
252 icon="text.bubble"
253 disabled={!isRepo}
254 onPress={() => router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
255 subtitle="Turn diffs and worktree changes"
256 >
257 <Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
258 </Stack.Toolbar.MenuAction>
259 <Stack.Toolbar.MenuAction
260 icon="folder"
261 disabled={!props.canOpenFiles}
262 onPress={() => router.push(buildThreadFilesNavigation({ environmentId, threadId }))}
263 subtitle="Browse this workspace"
264 >
265 <Stack.Toolbar.Label>Files</Stack.Toolbar.Label>
266 </Stack.Toolbar.MenuAction>
267 <Stack.Toolbar.MenuAction
268 icon="ellipsis.circle"
269 onPress={() =>
270 router.push({
271 pathname: "/threads/[environmentId]/[threadId]/git",
272 params: { environmentId, threadId },
273 })
274 }
275 subtitle="Commit, files, branches"
276 >
277 <Stack.Toolbar.Label>More</Stack.Toolbar.Label>
278 </Stack.Toolbar.MenuAction>
279 </Stack.Toolbar.Menu>
280 </Stack.Toolbar>
281 );