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

ThreadGitControls.tsx

542 lines17.9 KB

1import {
2 EnvironmentId,
3 type GitRunStackedActionResult,
4 type ProjectScript,
5 ThreadId,
6 type VcsStatusResult,
7} from "@t3tools/contracts";
8import {
9 type GitActionRequestInput,
10 requiresDefaultBranchConfirmation,
11 resolveQuickAction,
12} from "@t3tools/client-runtime/state/vcs";
13import { useNavigation } from "@react-navigation/native";
14import { NativeHeaderToolbar } from "../../native/StackHeader";
15import { useCallback, useMemo } from "react";
16import { Alert } from "react-native";
17import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
18import {
19 basename,
20 getTerminalStatusLabel,
21 projectScriptMenuIcon,
22 projectScriptMenuLabel,
23 type TerminalMenuSession,
24} from "../terminal/terminalMenu";
25​
26function truncateMiddle(value: string, maxLength: number): string {
27 if (value.length <= maxLength) {
28 return value;
29 }
30​
31 const headLength = Math.ceil((maxLength - 1) / 2);
32 const tailLength = Math.floor((maxLength - 1) / 2);
33 return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`;
35​
36function compactMenuBranchLabel(branch: string): string {
37 return truncateMiddle(branch, 24);
39​
40function compactMenuStatus(gitStatus: VcsStatusResult | null): string {
41 if (!gitStatus) {
42 return "Checking status";
43 }
44 if (!gitStatus.isRepo) {
45 return "Not a repo";
46 }
47​
48 const parts: string[] = [];
49 if (gitStatus.hasWorkingTreeChanges) {
50 parts.push(`${gitStatus.workingTree.files.length} changed`);
51 } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
52 parts.push("Clean");
53 }
54 if (gitStatus.aheadCount > 0) {
55 parts.push(`${gitStatus.aheadCount} ahead`);
56 }
57 if (gitStatus.behindCount > 0) {
58 parts.push(`${gitStatus.behindCount} behind`);
59 }
60 if (gitStatus.pr?.state === "open") {
61 parts.push(`PR #${gitStatus.pr.number}`);
62 }
63​
64 return parts.join(" · ");
66​
67type HeaderItem = Record<string, unknown>;
68type HeaderItems = HeaderItem[];
69type ThreadGitHeaderActionItems = {
70 readonly terminal: HeaderItem;
71 readonly files: HeaderItem;
72 readonly git: HeaderItem;
73};
74type QuickActionIcon =
75 | "arrow.down.circle"
76 | "arrow.up.right.circle"
77 | "checkmark.circle"
78 | "arrow.up.circle";
79​
80/** The subset of git-control wiring the standalone git menu needs. */
81export type ThreadGitMenuProps = {
82 readonly environmentId: EnvironmentId | string;
83 readonly threadId: ThreadId | string;
84 readonly currentBranch: string | null;
85 readonly gitStatus: VcsStatusResult | null;
86 readonly gitOperationLabel: string | null;
87 readonly onOpenFilesInspector?: () => void;
88 readonly onOpenGitInspector?: () => void;
89 readonly onPull: () => Promise<void>;
90 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
91};
92​
93type ThreadGitControlsProps = ThreadGitMenuProps & {
94 readonly auxiliaryPaneControl?: {
95 readonly accessibilityLabel: string;
96 readonly onPress: () => void;
97 };
98 readonly canOpenTerminal: boolean;
99 readonly canOpenFiles: boolean;
100 readonly projectScripts: ReadonlyArray<ProjectScript>;
101 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
102 readonly showActionControls?: boolean;
103 readonly showDirectFileControl?: boolean;
104 readonly onOpenTerminal: (terminalId?: string | null) => void;
105 readonly onOpenNewTerminal: () => void;
106 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
107};
108​
109function useThreadGitControlModel(props: ThreadGitMenuProps) {
110 const navigation = useNavigation();
111 const environmentId = props.environmentId;
112 const threadId = props.threadId;
113 const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
114​
115 const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD";
116 const busy = gitOperationLabel !== null;
117 const isRepo = gitStatus?.isRepo ?? true;
118 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
119 const isDefaultRef = gitStatus?.isDefaultRef ?? false;
120​
121 const quickAction = useMemo(
122 () =>
123 isRepo
124 ? resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote)
125 : {
126 label: "Git unavailable",
127 disabled: true,
128 kind: "show_hint" as const,
129 hint: "This workspace is not a git repository.",
130 },
131 [busy, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo],
132 );
133​
134 const quickActionHint = quickAction.disabled
135 ? (quickAction.hint ?? "This action is unavailable.")
136 : null;
137​
138 const quickActionIcon: QuickActionIcon = (() => {
139 if (quickAction.kind === "run_pull") return "arrow.down.circle";
140 if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
141 if (quickAction.kind === "run_action") {
142 if (quickAction.action === "commit") return "checkmark.circle";
143 if (quickAction.action === "push" || quickAction.action === "commit_push")
144 return "arrow.up.circle";
145 }
146 return "arrow.up.right.circle";
147 })();
148​
149 const openExistingPr = useCallback(async () => {
150 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
151 if (!prUrl) {
152 Alert.alert("No open PR", "This branch does not have an open pull request.");
153 return;
154 }
155 if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
156 Alert.alert("Unable to open PR", "The pull request could not be opened.");
157 }
158 }, [gitStatus]);
159​
160 const runActionWithPrompt = useCallback(
161 async (input: GitActionRequestInput) => {
162 const confirmableAction =
163 input.action === "push" ||
164 input.action === "create_pr" ||
165 input.action === "commit_push" ||
166 input.action === "commit_push_pr"
167 ? input.action
168 : null;
169 const branchName = gitStatus?.refName;
170 if (
171 branchName &&
172 confirmableAction &&
173 !input.featureBranch &&
174 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
175 ) {
176 navigation.navigate("GitConfirm", {
177 environmentId: String(environmentId),
178 threadId: String(threadId),
179 confirmAction: confirmableAction,
180 branchName,
181 includesCommit: String(
182 input.action === "commit_push" || input.action === "commit_push_pr",
183 ),
184 });
185 return;
186 }
187​
188 await onRunAction(input);
189 },
190 [environmentId, gitStatus, isDefaultRef, onRunAction, navigation, threadId],
191 );
192​
193 const runQuickAction = useCallback(async () => {
194 if (quickAction.kind === "open_pr") {
195 await openExistingPr();
196 return;
197 }
198 if (quickAction.kind === "run_pull") {
199 await onPull();
200 return;
201 }
202 if (quickAction.kind === "run_action" && quickAction.action) {
203 await runActionWithPrompt({ action: quickAction.action });
204 }
205 }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
206​
207 const openFiles = useCallback(() => {
208 if (props.onOpenFilesInspector) {
209 props.onOpenFilesInspector();
210 return;
211 }
212 navigation.navigate("ThreadFiles", {
213 environmentId: String(environmentId),
214 threadId: String(threadId),
215 });
216 }, [environmentId, props.onOpenFilesInspector, navigation, threadId]);
217​
218 const openReview = useCallback(() => {
219 navigation.navigate("ThreadReview", {
220 environmentId: EnvironmentId.make(String(environmentId)),
221 threadId: ThreadId.make(String(threadId)),
222 });
223 }, [environmentId, navigation, threadId]);
224​
225 const openGitInspector = useCallback(() => {
226 if (props.onOpenGitInspector) {
227 props.onOpenGitInspector();
228 return;
229 }
230 navigation.navigate("GitOverview", {
231 environmentId: String(environmentId),
232 threadId: String(threadId),
233 });
234 }, [environmentId, props.onOpenGitInspector, navigation, threadId]);
235​
236 return {
237 currentBranchLabel,
238 isRepo,
239 openFiles,
240 openGitInspector,
241 openReview,
242 quickAction,
243 quickActionHint,
244 quickActionIcon,
245 runQuickAction,
246 };
248​
249function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems {
250 const model = useThreadGitControlModel(props);
251​
252 return useMemo(
253 () => ({
254 terminal: {
255 accessibilityLabel: "Open terminal",
256 disabled: !props.canOpenTerminal,
257 icon: { name: "terminal", type: "sfSymbol" },
258 identifier: "thread-right-terminal",
259 label: "Terminal",
260 menu: {
261 items: [
262 ...props.projectScripts.map((script) => ({
263 description: script.command,
264 icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
265 label: projectScriptMenuLabel(script),
266 onPress: () => void props.onRunProjectScript(script),
267 type: "action" as const,
268 })),
269 ...(props.projectScripts.length === 0
270 ? [
271 {
272 description: "This project has no saved scripts yet",
273 disabled: true,
274 icon: { name: "play", type: "sfSymbol" as const },
275 label: "No project scripts",
276 onPress: () => {},
277 type: "action" as const,
278 },
279 ]
280 : []),
281 ...props.terminalSessions.map((session) => ({
282 description: [
283 getTerminalStatusLabel({
284 status: session.status,
285 hasRunningSubprocess: session.hasRunningSubprocess,
286 }),
287 basename(session.cwd),
288 ]
289 .filter(Boolean)
290 .join(" · "),
291 icon: { name: "terminal", type: "sfSymbol" as const },
292 label: session.displayLabel,
293 onPress: () => props.onOpenTerminal(session.terminalId),
294 type: "action" as const,
295 })),
296 {
297 description: "Start another shell for this thread",
298 icon: { name: "plus", type: "sfSymbol" },
299 label: "Open new terminal",
300 onPress: props.onOpenNewTerminal,
301 type: "action",
302 },
303 ],
304 title: "Terminal",
305 },
306 sharesBackground: true,
307 type: "menu",
308 variant: "plain",
309 },
310 files: {
311 accessibilityLabel: "Open files",
312 disabled: !props.canOpenFiles,
313 icon: { name: "folder", type: "sfSymbol" },
314 identifier: "thread-right-files",
315 label: "Files",
316 onPress: model.openFiles,
317 sharesBackground: true,
318 type: "button",
319 variant: "plain",
320 },
321 git: {
322 accessibilityLabel: "Git actions",
323 icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
324 identifier: "thread-right-git",
325 label: "Git",
326 menu: {
327 items: [
328 {
329 description: compactMenuStatus(props.gitStatus),
330 disabled: true,
331 icon: {
332 name: "point.topleft.down.curvedto.point.bottomright.up",
333 type: "sfSymbol",
334 },
335 label: compactMenuBranchLabel(model.currentBranchLabel),
336 onPress: (): void => {},
337 type: "action",
338 },
339 {
340 description: model.quickActionHint ?? undefined,
341 disabled: model.quickAction.disabled,
342 icon: { name: model.quickActionIcon, type: "sfSymbol" },
343 label: model.quickAction.label,
344 onPress: (): void => void model.runQuickAction(),
345 type: "action",
346 },
347 {
348 description: "Turn diffs and worktree changes",
349 disabled: !model.isRepo,
350 icon: { name: "text.bubble", type: "sfSymbol" },
351 label: "Review changes",
352 onPress: model.openReview,
353 type: "action",
354 },
355 {
356 description: "Commit, files, branches",
357 icon: { name: "ellipsis", type: "sfSymbol" },
358 label: "More",
359 onPress: model.openGitInspector,
360 type: "action",
361 },
362 ],
363 title: "Git",
364 },
365 sharesBackground: true,
366 type: "menu",
367 variant: "plain",
368 },
369 }),
370 [
371 model.currentBranchLabel,
372 model.isRepo,
373 model.openFiles,
374 model.openGitInspector,
375 model.openReview,
376 model.quickAction.disabled,
377 model.quickAction.label,
378 model.quickActionHint,
379 model.quickActionIcon,
380 model.runQuickAction,
381 props.canOpenFiles,
382 props.canOpenTerminal,
383 props.gitStatus,
384 props.onOpenNewTerminal,
385 props.onOpenTerminal,
386 props.onRunProjectScript,
387 props.projectScripts,
388 props.terminalSessions,
389 ],
390 );
392​
393export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems {
394 const actionItems = useThreadGitHeaderActionItems(props);
395 return useMemo(
396 () => [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems,
397 [actionItems],
398 );
400​
401export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems {
402 const actionItems = useThreadGitHeaderActionItems(props);
403 return useMemo(
404 () => [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems,
405 [actionItems],
406 );
408​
409export function ThreadGitControls(props: ThreadGitControlsProps) {
410 const model = useThreadGitControlModel(props);
411 const showActionControls = props.showActionControls ?? true;
412​
413 if (!showActionControls) {
414 return null;
415 }
416​
417 return (
418 <NativeHeaderToolbar placement="right">
419 {showActionControls && props.auxiliaryPaneControl ? (
420 <NativeHeaderToolbar.Button
421 accessibilityLabel={props.auxiliaryPaneControl.accessibilityLabel}
422 icon="sidebar.right"
423 onPress={props.auxiliaryPaneControl.onPress}
424 separateBackground
425 />
426 ) : null}
427 {showActionControls ? (
428 <NativeHeaderToolbar.Menu
429 icon="terminal"
430 disabled={!props.canOpenTerminal}
431 separateBackground
432 >
433 {props.projectScripts.length > 0 ? (
434 props.projectScripts.map((script) => (
435 <NativeHeaderToolbar.MenuAction
436 key={script.id}
437 icon={projectScriptMenuIcon(script.icon)}
438 onPress={() => void props.onRunProjectScript(script)}
439 subtitle={script.command}
440 >
441 <NativeHeaderToolbar.Label>
442 {projectScriptMenuLabel(script)}
443 </NativeHeaderToolbar.Label>
444 </NativeHeaderToolbar.MenuAction>
445 ))
446 ) : (
447 <NativeHeaderToolbar.MenuAction
448 icon="play"
449 disabled
450 onPress={() => {}}
451 subtitle="This project has no saved scripts yet"
452 >
453 <NativeHeaderToolbar.Label>No project scripts</NativeHeaderToolbar.Label>
454 </NativeHeaderToolbar.MenuAction>
455 )}
456 {props.terminalSessions.map((session) => (
457 <NativeHeaderToolbar.MenuAction
458 key={session.terminalId}
459 icon="terminal"
460 onPress={() => props.onOpenTerminal(session.terminalId)}
461 subtitle={[
462 getTerminalStatusLabel({
463 status: session.status,
464 hasRunningSubprocess: session.hasRunningSubprocess,
465 }),
466 basename(session.cwd),
467 ]
468 .filter(Boolean)
469 .join(" · ")}
470 >
471 <NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
472 </NativeHeaderToolbar.MenuAction>
473 ))}
474 <NativeHeaderToolbar.MenuAction
475 icon="plus"
476 onPress={props.onOpenNewTerminal}
477 subtitle="Start another shell for this thread"
478 >
479 <NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
480 </NativeHeaderToolbar.MenuAction>
481 </NativeHeaderToolbar.Menu>
482 ) : null}
483 {showActionControls && props.showDirectFileControl ? (
484 <NativeHeaderToolbar.Button
485 accessibilityLabel="Open files"
486 disabled={!props.canOpenFiles}
487 icon="folder"
488 onPress={model.openFiles}
489 separateBackground
490 />
491 ) : null}
492 {showActionControls ? <ThreadGitMenu {...props} /> : null}
493 </NativeHeaderToolbar>
494 );
496​
497/**
498 * The standalone git actions menu (branch status, quick commit/push action,
499 * review, more). Rendered inside a NativeHeaderToolbar by both the thread
500 * chat header and the review screen's toolbar.
501 */
502export function ThreadGitMenu(props: ThreadGitMenuProps) {
503 const model = useThreadGitControlModel(props);
504​
505 return (
506 <NativeHeaderToolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
507 <NativeHeaderToolbar.MenuAction
508 icon="point.topleft.down.curvedto.point.bottomright.up"
509 disabled
510 onPress={() => {}}
511 subtitle={compactMenuStatus(props.gitStatus)}
512 >
513 <NativeHeaderToolbar.Label>
514 {compactMenuBranchLabel(model.currentBranchLabel)}
515 </NativeHeaderToolbar.Label>
516 </NativeHeaderToolbar.MenuAction>
517 <NativeHeaderToolbar.MenuAction
518 icon={model.quickActionIcon}
519 disabled={model.quickAction.disabled}
520 onPress={() => void model.runQuickAction()}
521 subtitle={model.quickActionHint ?? undefined}
522 >
523 <NativeHeaderToolbar.Label>{model.quickAction.label}</NativeHeaderToolbar.Label>
524 </NativeHeaderToolbar.MenuAction>
525 <NativeHeaderToolbar.MenuAction
526 icon="text.bubble"
527 disabled={!model.isRepo}
528 onPress={model.openReview}
529 subtitle="Turn diffs and worktree changes"
530 >
531 <NativeHeaderToolbar.Label>Review changes</NativeHeaderToolbar.Label>
532 </NativeHeaderToolbar.MenuAction>
533 <NativeHeaderToolbar.MenuAction
534 icon="ellipsis"
535 onPress={model.openGitInspector}
536 subtitle="Commit, files, branches"
537 >
538 <NativeHeaderToolbar.Label>More</NativeHeaderToolbar.Label>
539 </NativeHeaderToolbar.MenuAction>
540 </NativeHeaderToolbar.Menu>
541 );