Repository navigation
Expand file tree
/
Copy pathPullRequestThreadLinks.tsx
More file actions
269 lines (262 loc) · 9.83 KB
/
Copy pathPullRequestThreadLinks.tsx
File metadata and controls
269 lines (262 loc) · 9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
import { useAtomValue } from "@effect/atom-react";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestRef, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { CheckIcon, MessageSquareIcon } from "lucide-react";
import { useState } from "react";
import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
import { usePullRequestLinking } from "~/hooks/usePullRequestLinking";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
import {
useAnyEnvironmentHiding,
useEnvironmentThreadRefs,
useProjects,
useServerConfigs,
useThreadShell,
useVisibleThreadShells,
} from "~/state/entities";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { environmentThreadShells } from "~/state/threads";
import { useEnvironmentQuery } from "~/state/query";
import { useThreadSearch } from "~/state/queries";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { openCommandPalette } from "~/commandPaletteBus";
import { Button } from "../ui/button";
import { Command, CommandInput, CommandItem, CommandList } from "../ui/command";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { MenuItem } from "../ui/menu";
import { toastManager } from "../ui/toast";
import { PullRequestGlyph } from "./pullRequestIcons";
interface PullRequestThreadLinksProps {
environmentId: EnvironmentId;
reference: PullRequestRef;
url: string;
threadRef: ScopedThreadRef | null;
display: "count" | "menu-item" | "picker";
onPickerOpenChange?: (open: boolean) => void;
}
export function PullRequestThreadLinks(props: PullRequestThreadLinksProps) {
const configs = useServerConfigs();
if (
threadPullRequestLinkMode(configs.get(props.environmentId)?.environment.capabilities) ===
"unsupported"
) {
return null;
}
return <EnabledPullRequestThreadLinks key={`${props.environmentId}:${props.url}`} {...props} />;
}
function EnabledPullRequestThreadLinks({
environmentId,
reference,
url,
threadRef,
display,
onPickerOpenChange,
}: PullRequestThreadLinksProps) {
const parsedUrl = sourceControlClients.parseChangeRequestUrl(url);
const parsed = parsedUrl?.link ?? null;
const term = (parsedUrl?.definition ?? sourceControlClients.get(undefined)).changeRequest
.singular;
const thread = useThreadShell(threadRef?.environmentId === environmentId ? threadRef : null);
const currentThreadRef = thread === null ? null : threadRef;
const linking = usePullRequestLinking(environmentId);
const linkedHere = linking.isLinked(thread, url);
const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom);
const hidingAnywhere = useAnyEnvironmentHiding();
const loadedThreadRefs = useEnvironmentThreadRefs(environmentId);
const relations = useEnvironmentQuery(
linking.mode === "multiple" && display !== "menu-item"
? pullRequestEnvironment.linkedThreads({
environmentId,
input:
parsed === null
? reference
: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
})
: null,
);
// Retain the last count while refresh temporarily clears query data.
const [lastRelations, setLastRelations] = useState(relations.data);
if (relations.data !== null && relations.data !== lastRelations) {
setLastRelations(relations.data);
}
const [pending, setPending] = useState(false);
const changeLink = async (threadId: ThreadId, remove: boolean) => {
if (parsed === null || pending) return;
setPending(true);
const result = await settlePromise(() =>
linking.changeLink(scopeThreadRef(environmentId, threadId), url, !remove),
);
setPending(false);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
title: remove ? `Could not unlink the ${term}` : `Could not link the ${term}`,
description: error instanceof Error ? error.message : String(error),
});
return;
}
if (linking.mode === "multiple") {
appAtomRegistry.refresh(
pullRequestEnvironment.linkedThreads({
environmentId,
input: { ...reference, ...normalizeThreadPullRequestKey(parsed) },
}),
);
}
onPickerOpenChange?.(false);
};
if (parsed === null || (!linkedHere && !linking.canLink(url))) return null;
const linkedThreads = visibleLinkedThreads(
linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [],
environmentId,
loadedThreadRefs,
hiddenKeys,
hidingAnywhere,
);
const linkedThreadsLabel =
linkedThreads.length > 0
? `Linked from ${linkedThreads.length} ${linkedThreads.length === 1 ? "thread" : "threads"}`
: "Linked threads";
return (
<>
{display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? (
<Tooltip>
<TooltipTrigger
render={
<Button
size="xs"
variant="ghost"
aria-label={linkedThreadsLabel}
onClick={() =>
openCommandPalette({
query: url,
...((relations.data ?? lastRelations) === null
? {}
: { linkedThreads: { environmentId, threads: linkedThreads } }),
})
}
>
<MessageSquareIcon aria-hidden className="size-3.5" />
<span aria-hidden>{linkedThreads.length || "?"}</span>
</Button>
}
/>
<TooltipPopup>{linkedThreadsLabel}. Search in the command palette.</TooltipPopup>
</Tooltip>
) : null}
{display === "menu-item" ? (
<MenuItem
disabled={pending}
onClick={() => {
if (currentThreadRef !== null) {
void changeLink(currentThreadRef.threadId, linkedHere);
} else {
onPickerOpenChange?.(true);
}
}}
>
{linkedHere ? (
<PullRequestGlyph.unlink aria-hidden className="size-3.5" />
) : (
<PullRequestGlyph.link aria-hidden className="size-3.5" />
)}
{linkedHere
? "Unlink from this thread"
: currentThreadRef
? "Link to this thread"
: "Link to thread"}
</MenuItem>
) : null}
{display === "picker" ? (
<Dialog open onOpenChange={onPickerOpenChange}>
<DialogPopup className="max-w-md" showCloseButton={false}>
<DialogTitle className="sr-only">Link {term} to a thread</DialogTitle>
<ThreadPicker
environmentId={environmentId}
url={url}
pending={pending}
onSelect={(threadId) => void changeLink(threadId, false)}
/>
</DialogPopup>
</Dialog>
) : null}
</>
);
}
function ThreadPicker({
environmentId,
url,
pending,
onSelect,
}: {
environmentId: EnvironmentId;
url: string;
pending: boolean;
onSelect: (threadId: ThreadId) => void;
}) {
const threads = useVisibleThreadShells();
const linking = usePullRequestLinking(environmentId);
const projects = useProjects();
const [query, setQuery] = useState("");
// Mounts older settled threads matching the query, which shells may leave out.
useThreadSearch([environmentId], query, { titlesOnly: true });
const projectNames = new Map(
projects
.filter((project) => project.environmentId === environmentId)
.map((project) => [project.id, project.title]),
);
const search = query.trim().toLocaleLowerCase();
const candidates = threads
.filter(
(thread) =>
thread.environmentId === environmentId &&
thread.archivedAt === null &&
`${thread.title} ${projectNames.get(thread.projectId) ?? ""}`
.toLocaleLowerCase()
.includes(search),
)
.toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt));
return (
<Command mode="none" value={query} onValueChange={setQuery} aria-label="Choose a thread">
<CommandInput placeholder="Search threads or projects..." disabled={pending} />
<CommandList className="max-h-80 overflow-y-auto">
{candidates.length === 0 ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
No active threads found.
</div>
) : (
candidates.map((thread) => {
const linked = linking.isLinked(thread, url);
return (
<CommandItem
key={thread.id}
value={thread.id}
disabled={pending || linked}
onClick={() => onSelect(thread.id)}
>
<MessageSquareIcon aria-hidden className="size-4 shrink-0" />
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">{thread.title || "Untitled thread"}</span>
<span className="truncate text-xs text-muted-foreground">
{projectNames.get(thread.projectId)}
</span>
</span>
{linked ? (
<>
<CheckIcon aria-hidden className="size-3.5" />
<span className="text-xs text-muted-foreground">Linked</span>
</>
) : null}
</CommandItem>
);
})
)}
</CommandList>
</Command>
);
}