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

ThreadGitControls.tsx

425 lines13.8 KB

1import { msg, useGT, useMessages } from "gt-react-native";
2​
3import * as Dialog from "../../components/ui/Dialog";
4import { useOpenPullRequest } from "../../native/useOpenPullRequest";
5import type { AppBarMenu } from "../../components/ui/AppBar.types";
6import {
7 AuthSourceControlWriteScope,
8 EnvironmentId,
9 type GitRunStackedActionResult,
10 type ProjectScript,
11 ThreadId,
12 type VcsStatusResult,
13} from "@t3tools/contracts";
14import {
15 type GitActionRequestInput,
16 requiresDefaultBranchConfirmation,
17 resolveQuickAction,
18} from "@t3tools/client-runtime/state/vcs";
19import { useNavigation } from "@react-navigation/native";
20import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
21import { changeRequestTermKind } from "../../lib/changeRequestTerm";
22​
23import { m, type MessageResolver } from "../../i18n/messages";
24import { useEnvironmentScope } from "../../state/session";
25import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
26import {
27 basename,
28 getTerminalStatusLabel,
29 projectScriptMenuIcon,
30 type TerminalMenuSession,
31} from "../terminal/terminalMenu";
32import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy";
33import { compactMenuBranchLabel } from "./ThreadGitControls.logic";
34​
35function compactMenuStatus(gitStatus: VcsStatusResult | null, resolve: MessageResolver): string {
36 if (!gitStatus) {
37 return resolve(msg("Checking status"));
38 }
39 if (!gitStatus.isRepo) {
40 return resolve(msg("Not a repo"));
41 }
42​
43 const parts: string[] = [];
44 if (gitStatus.hasWorkingTreeChanges) {
45 parts.push(
46 resolve(
47 msg("{count, plural, one {{count} changed} other {{count} changed}}", {
48 count: gitStatus.workingTree.files.length,
49 }),
50 ),
51 );
52 } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
53 parts.push(resolve(msg("Clean", { $context: "git working tree has no changes" })));
54 }
55 if (gitStatus.aheadCount > 0) {
56 parts.push(
57 resolve(
58 msg("{count, plural, one {{count} ahead} other {{count} ahead}}", {
59 count: gitStatus.aheadCount,
60 }),
61 ),
62 );
63 }
64 if (gitStatus.behindCount > 0) {
65 parts.push(
66 resolve(
67 msg("{count, plural, one {{count} behind} other {{count} behind}}", {
68 count: gitStatus.behindCount,
69 }),
70 ),
71 );
72 }
73 if (gitStatus.pr?.state === "open") {
74 const { shortLabel } = sourceControlClients.get(
75 gitStatus.sourceControlProvider?.kind,
76 ).changeRequest;
77 parts.push(`${shortLabel} #${gitStatus.pr.number}`);
78 }
79​
80 return parts.join(" · ");
82​
83type QuickActionIcon =
84 | "arrow.down.circle"
85 | "arrow.up.right.circle"
86 | "checkmark.circle"
87 | "arrow.up.circle";
88​
89export type ThreadGitMenuProps = {
90 readonly environmentId: EnvironmentId | string;
91 readonly threadId: ThreadId | string;
92 readonly currentBranch: string | null;
93 readonly hasThread?: boolean;
94 /** The project tracks repositories besides its folder, which then need not be one itself. */
95 readonly tracksRepositories?: boolean;
96 readonly gitStatus: VcsStatusResult | null;
97 readonly gitOperationLabel: string | null;
98 readonly onOpenFilesInspector?: () => void;
99 readonly onOpenGitInspector?: () => void;
100 readonly onMergeBack?: () => void;
101 readonly onPull: () => Promise<void>;
102 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
103};
104​
105export type ThreadGitControlsProps = ThreadGitMenuProps & {
106 readonly canOpenTerminal: boolean;
107 readonly canOperateTerminal: boolean;
108 readonly canOpenFiles: boolean;
109 readonly projectScripts: ReadonlyArray<ProjectScript>;
110 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
111 readonly onOpenTerminal: (terminalId?: string | null) => void;
112 readonly onOpenNewTerminal: () => void;
113 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
114};
115​
116function useThreadGitControlModel(props: ThreadGitMenuProps) {
117 const navigation = useNavigation();
118 const gt = useGT();
119 const messages = useMessages();
120 const openPullRequest = useOpenPullRequest();
121 const environmentId = props.environmentId;
122 const canWriteSourceControl = useEnvironmentScope(
123 environmentId ? EnvironmentId.make(String(environmentId)) : null,
124 AuthSourceControlWriteScope,
125 );
126 const threadId = props.threadId;
127 const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
128​
129 const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? gt("Detached HEAD");
130 const busy = gitOperationLabel !== null;
131 const isRepo = gitStatus?.isRepo ?? true;
132 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
133 const isDefaultRef = gitStatus?.isDefaultRef ?? false;
134​
135 const quickAction = (() => {
136 if (!isRepo) {
137 return {
138 label: gt("Git unavailable"),
139 disabled: true,
140 kind: "show_hint" as const,
141 hint: gt("This workspace is not a git repository."),
142 };
143 }
144 const action = resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote, messages);
145 return !canWriteSourceControl && (action.kind === "run_pull" || action.kind === "run_action")
146 ? {
147 ...action,
148 disabled: true,
149 hint: gt("This connection cannot change source control."),
150 }
151 : action;
152 })();
153​
154 const quickActionHint = quickAction.disabled
155 ? (quickAction.hint ?? gt("This action is unavailable."))
156 : null;
157​
158 const quickActionIcon: QuickActionIcon = (() => {
159 if (quickAction.kind === "run_pull") return "arrow.down.circle";
160 if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
161 if (quickAction.kind === "run_action") {
162 if (quickAction.action === "commit") return "checkmark.circle";
163 if (quickAction.action === "push" || quickAction.action === "commit_push")
164 return "arrow.up.circle";
165 }
166 return "arrow.up.right.circle";
167 })();
168​
169 const openExistingPr = async () => {
170 const term = changeRequestTermKind(
171 sourceControlClients.get(gitStatus?.sourceControlProvider?.kind).changeRequest,
172 );
173 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
174 if (!prUrl) {
175 Dialog.alert(
176 gt("{term, select, mr {No open MR} cr {No open change request} other {No open PR}}", {
177 term,
178 }),
179 gt(
180 "{term, select, mr {This branch does not have an open merge request.} cr {This branch does not have an open change request.} other {This branch does not have an open pull request.}}",
181 { term },
182 ),
183 );
184 return;
185 }
186 if (!(await openPullRequest(prUrl))) {
187 Dialog.alert(
188 gt(
189 "{term, select, mr {Unable to open MR} cr {Unable to open change request} other {Unable to open PR}}",
190 { term },
191 ),
192 gt(
193 "{term, select, mr {The merge request could not be opened.} cr {The change request could not be opened.} other {The pull request could not be opened.}}",
194 { term },
195 ),
196 );
197 }
198 };
199​
200 const runActionWithPrompt = async (input: GitActionRequestInput) => {
201 if (!canWriteSourceControl) return;
202 const confirmableAction =
203 input.action === "push" ||
204 input.action === "create_pr" ||
205 input.action === "commit_push" ||
206 input.action === "commit_push_pr"
207 ? input.action
208 : null;
209 const branchName = gitStatus?.refName;
210 if (
211 branchName &&
212 confirmableAction &&
213 !input.featureBranch &&
214 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
215 ) {
216 if (props.hasThread === false) {
217 Dialog.alert(
218 gt("Choose a feature branch"),
219 gt("Switch branches before publishing changes from this draft."),
220 );
221 return;
222 }
223 navigation.navigate("GitConfirm", {
224 environmentId: String(environmentId),
225 threadId: String(threadId),
226 confirmAction: confirmableAction,
227 });
228 return;
229 }
230​
231 await onRunAction(input);
232 };
233​
234 const runQuickAction = async () => {
235 if (quickAction.disabled) return;
236 if (quickAction.kind === "open_pr") {
237 await openExistingPr();
238 return;
239 }
240 if (quickAction.kind === "run_pull") {
241 await onPull();
242 return;
243 }
244 if (quickAction.kind === "run_action" && quickAction.action) {
245 await runActionWithPrompt({ action: quickAction.action });
246 }
247 };
248​
249 const openReview = () => {
250 navigation.navigate("ThreadReview", {
251 environmentId: EnvironmentId.make(String(environmentId)),
252 threadId: ThreadId.make(String(threadId)),
253 });
254 };
255​
256 const openGitInspector = () => {
257 if (props.onOpenGitInspector) {
258 props.onOpenGitInspector();
259 return;
260 }
261 navigation.navigate("GitOverview", {
262 environmentId: String(environmentId),
263 threadId: String(threadId),
264 });
265 };
266​
267 return {
268 currentBranchLabel,
269 isRepo,
270 openGitInspector,
271 openReview,
272 quickAction,
273 quickActionHint,
274 quickActionIcon,
275 runQuickAction,
276 };
278​
279export function threadTerminalMenu(
280 props: ThreadGitControlsProps,
281 resolve: MessageResolver = m,
282): AppBarMenu | null {
283 if (!props.canOpenTerminal) return null;
284 return {
285 title: resolve(msg("Terminal")),
286 icon: "terminal",
287 separateBackground: false,
288 items: [
289 ...(props.projectScripts.length > 0
290 ? props.projectScripts.map((script) => ({
291 id: `script-${script.id}`,
292 title: projectScriptMenuLabel(script, resolve),
293 icon: projectScriptMenuIcon(script.icon),
294 subtitle: script.command,
295 disabled: !props.canOperateTerminal,
296 onPress: () => void props.onRunProjectScript(script),
297 }))
298 : [
299 {
300 id: "script-none",
301 title: resolve(msg("No project scripts")),
302 icon: "play",
303 subtitle: resolve(msg("This project has no saved scripts yet")),
304 disabled: true,
305 onPress: () => {},
306 },
307 ]),
308 ...props.terminalSessions.map((session) => ({
309 id: `terminal-${session.terminalId}`,
310 title: session.displayLabel,
311 icon: "terminal",
312 subtitle: [
313 getTerminalStatusLabel(
314 {
315 status: session.status,
316 hasRunningSubprocess: session.hasRunningSubprocess,
317 },
318 resolve,
319 ),
320 basename(session.cwd),
321 ]
322 .filter(Boolean)
323 .join(" · "),
324 onPress: () => props.onOpenTerminal(session.terminalId),
325 })),
326 {
327 id: "terminal-new",
328 title: resolve(msg("Open new terminal")),
329 icon: "plus",
330 subtitle: resolve(msg("Start another shell for this thread")),
331 disabled: !props.canOperateTerminal,
332 onPress: props.onOpenNewTerminal,
333 },
334 ],
335 };
337​
338/** The thread's git menu, shared by the thread bar and Review. */
339export function useThreadGitMenuDefinition(props: ThreadGitMenuProps): AppBarMenu | null {
340 const model = useThreadGitControlModel(props);
341 const gt = useGT();
342 const messages = useMessages();
343 // A plain folder that tracks repositories has no branch of its own; its turns still have diffs.
344 const repositoriesOnly = !model.isRepo && props.tracksRepositories === true;
345 return {
346 title: gt("Git controls"),
347 icon: "point.topleft.down.curvedto.point.bottomright.up",
348 separateBackground: false,
349 items: [
350 ...(repositoriesOnly
351 ? // A worktree thread of such a folder still has a branch: its repositories are on it.
352 props.currentBranch === null
353 ? []
354 : [
355 {
356 id: "git-status",
357 title: compactMenuBranchLabel(props.currentBranch),
358 icon: "point.topleft.down.curvedto.point.bottomright.up",
359 disabled: true,
360 subtitle: gt("Repository worktrees"),
361 onPress: () => {},
362 },
363 ]
364 : [
365 {
366 id: "git-status",
367 title: compactMenuBranchLabel(model.currentBranchLabel),
368 icon: "point.topleft.down.curvedto.point.bottomright.up",
369 disabled: true,
370 subtitle: compactMenuStatus(props.gitStatus, messages),
371 onPress: () => {},
372 },
373 {
374 id: "git-quick-action",
375 title: model.quickAction.label,
376 icon: model.quickActionIcon,
377 disabled: model.quickAction.disabled,
378 subtitle: model.quickActionHint ?? undefined,
379 onPress: () => {
380 void model.runQuickAction();
381 },
382 },
383 ]),
384 {
385 id: "git-review",
386 title: gt("Review changes"),
387 icon: "text.bubble",
388 disabled: !(model.isRepo || repositoriesOnly) || props.hasThread === false,
389 subtitle:
390 props.hasThread === false
391 ? gt("Available after the first message")
392 : repositoriesOnly
393 ? gt("Turn diffs")
394 : gt("Turn diffs and worktree changes"),
395 onPress: model.openReview,
396 },
397 ...(props.onMergeBack
398 ? [
399 {
400 id: "git-merge-back",
401 title: gt("Merge back to source"),
402 icon: PullRequestGlyph.merged,
403 subtitle: gt("Bring this thread's latest turn into its source"),
404 onPress: props.onMergeBack,
405 },
406 ]
407 : []),
408 {
409 id: "git-more",
410 title: gt("More", { $context: "menu item that opens more git actions" }),
411 icon: "ellipsis",
412 disabled: props.hasThread === false,
413 subtitle:
414 props.hasThread === false
415 ? gt("Available after the first message")
416 : repositoriesOnly
417 ? gt("Repositories")
418 : props.tracksRepositories === true
419 ? gt("Commit, branches, repositories")
420 : gt("Commit, files, branches"),
421 onPress: model.openGitInspector,
422 },
423 ],
424 };