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

ThreadGitControls.tsx

573 lines18.9 KB

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