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

useLinkedPullRequestActions.ts

260 lines8.9 KB

1import {
2 pullRequestLinkProject,
3 resolveLinkPullRequestInput,
4} from "@t3tools/client-runtime/pull-request-link-input";
5import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
6import type {
7 EnvironmentProject,
8 EnvironmentThreadShell,
9} from "@t3tools/client-runtime/state/shell";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13 type AtomCommandResult,
14} from "@t3tools/client-runtime/state/runtime";
15import {
16 canStartThreadPullRequestWatch,
17 planThreadPullRequestMutation,
18} from "@t3tools/client-runtime/thread-pull-request-compatibility";
19import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
20import { changeRequestTermKind } from "../../lib/changeRequestTerm";
21import { AuthOrchestrationOperateScope, type ThreadPullRequestLink } from "@t3tools/contracts";
22import * as Clipboard from "expo-clipboard";
23import { useGT, select } from "gt-react-native";
24​
25import * as Dialog from "../../components/ui/Dialog";
26import { m } from "../../i18n/messages";
27import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
28import type { MenuProps } from "../../components/ui/Menu.types";
29import type { EnvironmentRuntimeState } from "../../state/remote-runtime-types";
30import { useEnvironmentScope } from "../../state/session";
31import { threadEnvironment } from "../../state/threads";
32import { useAtomCommand } from "../../state/use-atom-command";
33​
34type MenuAction = MenuProps["actions"][number];
35​
36export function useLinkedPullRequestActions(input: {
37 readonly thread: EnvironmentThreadShell | null;
38 readonly project: EnvironmentProject | null;
39 readonly runtime: EnvironmentRuntimeState | null;
40}) {
41 const gt = useGT();
42 const { thread, project, runtime } = input;
43 const terminology = sourceControlClients.get(project?.repositoryIdentity?.provider).changeRequest;
44 const capabilities = runtime?.serverConfig?.environment.capabilities;
45 const canOperate = useEnvironmentScope(
46 thread?.environmentId ?? null,
47 AuthOrchestrationOperateScope,
48 );
49 const canEdit = canOperate && capabilities !== undefined;
50 const canWatch = canOperate && capabilities?.threadPullRequestWatch === true;
51 const canStartWatch = canWatch && thread !== null && canStartThreadPullRequestWatch(thread);
52 const link = useAtomCommand(threadEnvironment.linkPullRequest, { reportFailure: false });
53 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: false });
54 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: false });
55​
56 const run = async (
57 failureTitle: string,
58 pending: Promise<AtomCommandResult<unknown, unknown>>,
59 ) => {
60 const result = await pending;
61 if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
62 const cause = squashAtomCommandFailure(result);
63 Dialog.alert(failureTitle, errorDisplayMessage(cause, m) ?? gt`Try again.`);
64 };
65​
66 const setLinked = (
67 reference: { host: string; repository: string; number: number; url: string },
68 linked: boolean,
69 ) => {
70 if (thread === null) return;
71 const mutation = planThreadPullRequestMutation({
72 capabilities,
73 threadId: thread.id,
74 reference,
75 linked,
76 });
77 if (mutation === null) return;
78 const environmentId = thread.environmentId;
79 void run(
80 linked
81 ? gt`${select(
82 { term: changeRequestTermKind(terminology) },
83 {
84 mr: "Couldn't link this merge request",
85 cr: "Couldn't link this change request",
86 other: "Couldn't link this pull request",
87 },
88 )}`
89 : gt`${select(
90 { term: changeRequestTermKind(terminology) },
91 {
92 mr: "Couldn't unlink this merge request",
93 cr: "Couldn't unlink this change request",
94 other: "Couldn't unlink this pull request",
95 },
96 )}`,
97 mutation.type === "thread.pull-request.link"
98 ? link({ environmentId, input: mutation.input })
99 : unlink({ environmentId, input: mutation.input }),
100 );
101 };
102​
103 const promptLink = () => {
104 const term = changeRequestTermKind(terminology);
105 Dialog.prompt({
106 title: gt`${select(
107 { term },
108 {
109 mr: "Link merge request",
110 cr: "Link change request",
111 other: "Link pull request",
112 },
113 )}`,
114 message: gt`${select(
115 { term },
116 {
117 mr: "Paste a merge request URL, or enter 123 / #123 for this thread's repository.",
118 cr: "Paste a change request URL, or enter 123 / #123 for this thread's repository.",
119 other: "Paste a pull request URL, or enter 123 / #123 for this thread's repository.",
120 },
121 )}`,
122 placeholder: gt`${select(
123 { term },
124 {
125 mr: "Merge request URL or #42",
126 cr: "Change request URL or #42",
127 other: "Pull request URL or #42",
128 },
129 )}`,
130 initialValue: "",
131 confirmText: gt({ context: "verb, confirms linking a pull request" })`Link`,
132 onConfirm: (reference) => {
133 const resolved = resolveLinkPullRequestInput(
134 {
135 reference,
136 project: pullRequestLinkProject(project?.repositoryIdentity),
137 hasProject: () => true,
138 },
139 m,
140 );
141 if (resolved === null) {
142 Dialog.alert(
143 gt`${select(
144 { term },
145 {
146 mr: "Couldn't link this merge request",
147 cr: "Couldn't link this change request",
148 other: "Couldn't link this pull request",
149 },
150 )}`,
151 gt`${select(
152 { term },
153 {
154 mr: "Use a merge request URL, 123, or #123.",
155 cr: "Use a change request URL, 123, or #123.",
156 other: "Use a pull request URL, 123, or #123.",
157 },
158 )}`,
159 );
160 return;
161 }
162 if ("error" in resolved) {
163 Dialog.alert(
164 gt`${select(
165 { term },
166 {
167 mr: "Couldn't link this merge request",
168 cr: "Couldn't link this change request",
169 other: "Couldn't link this pull request",
170 },
171 )}`,
172 resolved.error,
173 );
174 return;
175 }
176 setLinked(resolved.link, true);
177 },
178 });
179 };
180​
181 const menuActions = (link: ThreadPullRequestLink): MenuAction[] => {
182 const open = link.snapshot === null || link.snapshot.state === "open";
183 const watching = link.watch !== undefined;
184 return [
185 { id: "copy", title: gt`Copy link`, image: "link" },
186 { id: "browser", title: gt`Open in browser`, image: "safari" },
187 ...((watching ? canWatch : canStartWatch) && open
188 ? [
189 {
190 id: "watch",
191 title: watching ? gt`Stop watching` : gt`Watch for changes`,
192 image: watching ? "eye.slash" : "eye",
193 },
194 ]
195 : []),
196 ...(canEdit
197 ? [
198 {
199 id: "unlink",
200 title: link.source === "stack" ? gt`Dismiss from thread` : gt`Unlink from thread`,
201 image: "xmark",
202 attributes: { destructive: true },
203 },
204 ]
205 : []),
206 ];
207 };
208​
209 const onMenuAction = (link: ThreadPullRequestLink, action: string) => {
210 if (action === "copy") void Clipboard.setStringAsync(link.url);
211 else if (action === "browser")
212 void tryOpenExternalUrl(link.url, "pull-request").then((opened) => {
213 if (!opened) {
214 const term = changeRequestTermKind(
215 (
216 sourceControlClients.findByChangeRequestUrl(link.url) ??
217 sourceControlClients.get(undefined)
218 ).changeRequest,
219 );
220 Dialog.alert(
221 gt`${select(
222 { term },
223 {
224 mr: "Unable to open MR",
225 cr: "Unable to open change request",
226 other: "Unable to open PR",
227 },
228 )}`,
229 gt`${select(
230 { term },
231 {
232 mr: "The merge request could not be opened.",
233 cr: "The change request could not be opened.",
234 other: "The pull request could not be opened.",
235 },
236 )}`,
237 );
238 }
239 });
240 else if (action === "watch" && thread !== null)
241 void run(
242 gt`Couldn't change watching`,
243 watch({
244 environmentId: thread.environmentId,
245 input: {
246 threadId: thread.id,
247 host: link.host,
248 repository: link.repository,
249 number: link.number,
250 watching: link.watch === undefined,
251 },
252 }),
253 );
254 else if (action === "unlink") setLinked(link, false);
255 };
256​
257 return { canLink: canEdit, terminology, promptLink, menuActions, onMenuAction };
259​
260export type LinkedPullRequestActions = ReturnType<typeof useLinkedPullRequestActions>;