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

ThreadGitControls.tsx

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