Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
4import { AuthOrchestrationOperateScope, threadIssueKeysEqual } from "@t3tools/contracts";
5import type {
6 EnvironmentId,
7 IssueDetail,
8 IssueRef,
9 ScopedThreadRef,
10 ThreadId,
11} from "@t3tools/contracts";
12import { Link2Icon, Link2OffIcon, MessageSquareIcon } from "lucide-react";
13import { msg, T, useGT, plural, part } from "gt-react";
14import { useRef, useState } from "react";
15
16import { openCommandPalette } from "~/commandPaletteBus";
17import { m } from "~/i18n/messages";
18import { appAtomRegistry } from "~/rpc/atomRegistry";
19import {
20 useAnyEnvironmentHiding,
21 useEnvironmentThreadRefs,
22 useServerConfigs,
23 useThreadShell,
24} from "~/state/entities";
25import { issueEnvironment } from "~/state/issues";
26import { useEnvironmentQuery } from "~/state/query";
27import { useEnvironmentScope } from "~/state/session";
28import { environmentThreadShells, threadEnvironment } from "~/state/threads";
29import { useAtomCommand } from "~/state/use-atom-command";
30
31import { readableFailure } from "../pullRequest/pullRequestDetail.logic";
32import { ThreadLinkPicker } from "../ThreadLinkPicker";
33import { Button } from "../ui/button";
34import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
35import { toastManager } from "../ui/toast";
36import { SharedTooltipTrigger } from "../ui/shared-tooltip";
37
38/**
39 * The threads an issue is linked to, and the control that links it to one more: the thread it is
40 * shown beside, or one picked from the environment when it is shown on its own.
41 */
42export function IssueThreadLinks({
43 environmentId,
44 reference,
45 issue,
46 threadRef,
47}: {
48 environmentId: EnvironmentId;
49 reference: IssueRef & { readonly host: string };
50 issue: Pick<IssueDetail, "url" | "displayKey" | "title">;
51 threadRef: ScopedThreadRef | null;
52}) {
53 const gt = useGT();
54 const thread = useThreadShell(threadRef?.environmentId === environmentId ? threadRef : null);
55 const canOperate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
56 const listsThreads =
57 useServerConfigs().get(environmentId)?.environment.capabilities.issueLinkedThreads === true;
58 const link = useAtomCommand(threadEnvironment.linkIssue, { reportFailure: false });
59 const unlink = useAtomCommand(threadEnvironment.unlinkIssue, { reportFailure: false });
60 const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
61 const hidingAnywhere = useAnyEnvironmentHiding();
62 const loadedThreadRefs = useEnvironmentThreadRefs(environmentId);
63 const key = {
64 tracker: reference.tracker,
65 host: reference.host,
66 scope: reference.scope,
67 key: reference.key,
68 };
69 const relationsAtom = issueEnvironment.linkedThreads({ environmentId, input: key });
70 const relations = useEnvironmentQuery(listsThreads ? relationsAtom : null);
71 // Retain the last count while refresh temporarily clears query data.
72 const [lastRelations, setLastRelations] = useState(relations.data);
73 if (relations.data !== null && relations.data !== lastRelations) {
74 setLastRelations(relations.data);
75 }
76 const [pending, setPending] = useState(false);
77 const [pickerOpen, setPickerOpen] = useState(false);
78 const triggerRef = useRef<HTMLButtonElement>(null);
79
80 const linkedHere = (thread?.issues ?? []).some((existing) => threadIssueKeysEqual(existing, key));
81 const changeLink = async (threadId: ThreadId, remove: boolean) => {
82 if (pending) return;
83 setPending(true);
84 const result = await (remove
85 ? unlink({ environmentId, input: { threadId, ...key } })
86 : link({
87 environmentId,
88 input: {
89 threadId,
90 ...key,
91 projectId: reference.projectId,
92 url: issue.url,
93 displayKey: issue.displayKey,
94 title: issue.title,
95 source: "manual",
96 },
97 }));
98 setPending(false);
99 if (result._tag === "Failure") {
100 toastManager.add({
101 type: "error",
102 title: remove ? m(msg("Could not unlink the issue")) : m(msg("Could not link the issue")),
103 description: readableFailure(
104 squashAtomCommandFailure(result),
105 m(msg("The server refused it.")),
106 ),
107 });
108 return;
109 }
110 if (listsThreads) appAtomRegistry.refresh(relationsAtom);
111 setPickerOpen(false);
112 };
113
114 const linkedThreads = visibleLinkedThreads(
115 (relations.data ?? lastRelations)?.threads ?? [],
116 environmentId,
117 loadedThreadRefs,
118 hiddenKeys,
119 hidingAnywhere,
120 );
121 const linkedThreadsLabel =
122 linkedThreads.length > 0
123 ? gt`${plural(
124 { count: linkedThreads.length },
125 {
126 one: part`Linked from ${{ count: linkedThreads.length }} thread`,
127 other: part`Linked from ${{ count: linkedThreads.length }} threads`,
128 },
129 )}`
130 : gt`Linked threads`;
131 // A failed read shows "?" and falls back to searching threads for the issue's link.
132 const relationsKnown = (relations.data ?? lastRelations) !== null;
133 return (
134 <>
135 {linkedThreads.length > 0 || (!relationsKnown && relations.error !== null) ? (
136 <SharedTooltipTrigger
137 render={
138 <Button
139 size="xs"
140 variant="ghost"
141 aria-label={linkedThreadsLabel}
142 onClick={() =>
143 openCommandPalette({
144 query: issue.url,
145 ...(relationsKnown
146 ? { linkedThreads: { environmentId, threads: linkedThreads } }
147 : {}),
148 })
149 }
150 >
151 <MessageSquareIcon aria-hidden className="size-3.5" />
152 <span aria-hidden>{linkedThreads.length || "?"}</span>
153 </Button>
154 }
155 label={gt`${{ label: linkedThreadsLabel }}. Search in the command palette.`}
156 />
157 ) : null}
158 {canOperate ? (
159 <SharedTooltipTrigger
160 render={
161 <Button
162 ref={triggerRef}
163 size="icon-xs"
164 variant="ghost"
165 aria-label={linkedHere ? gt`Unlink from thread` : gt`Link to thread`}
166 aria-pressed={thread === null ? undefined : linkedHere}
167 disabled={pending}
168 onClick={() => {
169 if (thread === null) setPickerOpen(true);
170 else void changeLink(thread.id, linkedHere);
171 }}
172 />
173 }
174 label={
175 linkedHere ? (
176 <T>Unlink from this thread</T>
177 ) : thread === null ? (
178 gt`Link to thread`
179 ) : (
180 <T>Link to this thread</T>
181 )
182 }
183 >
184 {linkedHere ? (
185 <Link2OffIcon aria-hidden className="size-3.5" />
186 ) : (
187 <Link2Icon aria-hidden className="size-3.5" />
188 )}
189 </SharedTooltipTrigger>
190 ) : null}
191 {pickerOpen ? (
192 <Dialog open onOpenChange={setPickerOpen}>
193 <DialogPopup className="max-w-md" finalFocus={triggerRef} showCloseButton={false}>
194 <DialogTitle className="sr-only">
195 <T>Link issue to a thread</T>
196 </DialogTitle>
197 <ThreadLinkPicker
198 environmentId={environmentId}
199 pending={pending}
200 isLinked={(candidate) =>
201 (candidate.issues ?? []).some((existing) => threadIssueKeysEqual(existing, key))
202 }
203 onSelect={(threadId) => void changeLink(threadId, false)}
204 />
205 </DialogPopup>
206 </Dialog>
207 ) : null}
208 </>
209 );
210}