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

useLinkedPullRequestActions.ts

191 lines7.0 KB

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