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

ThreadGitControls.tsx

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