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