Open History to see the last commit
1import {
2 pullRequestLinkProject,
3 resolveLinkPullRequestInput,
4} from "@t3tools/client-runtime/pull-request-link-input";
5import type {
6 EnvironmentProject,
7 EnvironmentThreadShell,
8} from "@t3tools/client-runtime/state/shell";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12 type AtomCommandResult,
13} from "@t3tools/client-runtime/state/runtime";
14import { planThreadPullRequestMutation } from "@t3tools/client-runtime/thread-pull-request-compatibility";
15import {
16 capitalizeTerm,
17 sourceControlClients,
18} from "@t3tools/client-runtime/source-control-clients";
19import { AuthOrchestrationOperateScope, type ThreadPullRequestLink } from "@t3tools/contracts";
20import * as Clipboard from "expo-clipboard";
21
22import * as Dialog from "../../components/ui/Dialog";
23import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
24import type { MenuProps } from "../../components/ui/Menu.types";
25import type { EnvironmentRuntimeState } from "../../state/remote-runtime-types";
26import { useEnvironmentScope } from "../../state/session";
27import { threadEnvironment } from "../../state/threads";
28import { useAtomCommand } from "../../state/use-atom-command";
29
30type MenuAction = MenuProps["actions"][number];
31
32export function useLinkedPullRequestActions(input: {
33 readonly thread: EnvironmentThreadShell | null;
34 readonly project: EnvironmentProject | null;
35 readonly runtime: EnvironmentRuntimeState | null;
36}) {
37 const { thread, project, runtime } = input;
38 const terminology = sourceControlClients.get(project?.repositoryIdentity?.provider).changeRequest;
39 const capabilities = runtime?.serverConfig?.environment.capabilities;
40 const canOperate = useEnvironmentScope(
41 thread?.environmentId ?? null,
42 AuthOrchestrationOperateScope,
43 );
44 const canEdit = canOperate && capabilities !== undefined;
45 const canWatch = canOperate && capabilities?.threadPullRequestWatch === true;
46 const canStartWatch =
47 canWatch &&
48 thread !== null &&
49 thread.archivedAt === null &&
50 thread.settledAt === null &&
51 thread.settledOverride !== "settled" &&
52 thread.lineage.relationshipToParent !== "subagent";
53 const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
54 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
55 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: false });
56
57 const run = async (
58 failureTitle: string,
59 pending: Promise<AtomCommandResult<unknown, unknown>>,
60 ) => {
61 const result = await pending;
62 if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
63 const cause = squashAtomCommandFailure(result);
64 Dialog.alert(failureTitle, cause instanceof Error ? cause.message : "Try again.");
65 };
66
67 const setLinked = (
68 reference: { host: string; repository: string; number: number; url: string },
69 linked: boolean,
70 ) => {
71 if (thread === null) return;
72 const mutation = planThreadPullRequestMutation({
73 capabilities,
74 threadId: thread.id,
75 reference,
76 linked,
77 });
78 if (mutation === null) return;
79 const environmentId = thread.environmentId;
80 void run(
81 linked
82 ? `Couldn't link this ${terminology.singular}`
83 : `Couldn't unlink this ${terminology.singular}`,
84 mutation.type === "thread.pull-request.link"
85 ? link({ environmentId, input: mutation.input })
86 : unlink({ environmentId, input: mutation.input }),
87 );
88 };
89
90 const promptLink = () => {
91 const { singular } = terminology;
92 Dialog.prompt({
93 title: `Link ${singular}`,
94 message: `Paste a ${singular} URL, or enter 123 / #123 for this thread's repository.`,
95 placeholder: `${capitalizeTerm(singular)} URL or #42`,
96 initialValue: "",
97 confirmText: "Link",
98 onConfirm: (reference) => {
99 const resolved = resolveLinkPullRequestInput({
100 reference,
101 project: pullRequestLinkProject(project?.repositoryIdentity),
102 hasProject: () => true,
103 });
104 if (resolved === null) {
105 Dialog.alert(`Couldn't link this ${singular}`, `Use a ${singular} URL, 123, or #123.`);
106 return;
107 }
108 if ("error" in resolved) {
109 Dialog.alert(`Couldn't link this ${singular}`, resolved.error);
110 return;
111 }
112 setLinked(resolved.link, true);
113 },
114 });
115 };
116
117 const menuActions = (link: ThreadPullRequestLink): MenuAction[] => {
118 const open = link.snapshot === null || link.snapshot.state === "open";
119 const watching = link.watch !== undefined;
120 return [
121 { id: "copy", title: "Copy link", image: "link" },
122 { id: "browser", title: "Open in browser", image: "safari" },
123 ...((watching ? canWatch : canStartWatch) && open
124 ? [
125 {
126 id: "watch",
127 title: watching ? "Stop watching" : "Watch for changes",
128 image: watching ? "eye.slash" : "eye",
129 },
130 ]
131 : []),
132 ...(canEdit
133 ? [
134 {
135 id: "unlink",
136 title: link.source === "stack" ? "Dismiss from thread" : "Unlink from thread",
137 image: "xmark",
138 attributes: { destructive: true },
139 },
140 ]
141 : []),
142 ];
143 };
144
145 const onMenuAction = (link: ThreadPullRequestLink, action: string) => {
146 if (action === "copy") void Clipboard.setStringAsync(link.url);
147 else if (action === "browser")
148 void tryOpenExternalUrl(link.url, "pull-request").then((opened) => {
149 if (!opened) {
150 const { shortLabel, singular } = (
151 sourceControlClients.findByChangeRequestUrl(link.url) ??
152 sourceControlClients.get(undefined)
153 ).changeRequest;
154 Dialog.alert(`Unable to open ${shortLabel}`, `The ${singular} could not be opened.`);
155 }
156 });
157 else if (action === "watch" && thread !== null)
158 void run(
159 "Couldn't change watching",
160 watch({
161 environmentId: thread.environmentId,
162 input: {
163 threadId: thread.id,
164 host: link.host,
165 repository: link.repository,
166 number: link.number,
167 watching: link.watch === undefined,
168 },
169 }),
170 );
171 else if (action === "unlink") setLinked(link, false);
172 };
173
174 return { canLink: canEdit, terminology, promptLink, menuActions, onMenuAction };
175}
176
177export type LinkedPullRequestActions = ReturnType<typeof useLinkedPullRequestActions>;