Open History to see the last commit
1import { useAtomCommand } from "~/state/use-atom-command";
2import type {
3 EnvironmentId,
4 PullRequestRef,
5 PullRequestReviewerCandidate,
6} from "@t3tools/contracts";
7import {
8 hostReviewerQuery,
9 reviewerCandidateView,
10 type ReviewerTruncation,
11} from "@t3tools/client-runtime/pull-request-reviewers";
12import {
13 emptySelection,
14 isSelected,
15 changeBatches,
16 selectionChanges,
17 toggleSelection,
18} from "@t3tools/client-runtime/pull-request-selection";
19import { CheckIcon, UserPlusIcon } from "lucide-react";
20import { msg, useGT, useMessages } from "gt-react";
21import { useState } from "react";
22
23import { m, type MessageResolver } from "~/i18n/messages";
24
25import { pullRequestEnvironment } from "~/state/pullRequests";
26import { useEnvironmentQuery } from "~/state/query";
27import { useDebouncedValue } from "~/state/queries";
28import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
29
30import { toastManager } from "../ui/toast";
31import { PullRequestCandidatePicker } from "./PullRequestCandidatePicker";
32import { PullRequestActorLabel } from "./pullRequestPresentation";
33import { readableFailure } from "./pullRequestDetail.logic";
34
35const TRUNCATED_LABELS: Record<
36 ReviewerTruncation,
37 (error: string | null, resolve: MessageResolver) => string
38> = {
39 unsearchable: (_error, resolve) =>
40 resolve(
41 msg(
42 "This repository has more people with access than are listed here. Ask for the rest on the host.",
43 ),
44 ),
45 searchable: (_error, resolve) =>
46 resolve(
47 msg("This repository has more people with access than are listed here. Search to find them."),
48 ),
49 "search-failed": (error, resolve) =>
50 resolve(
51 msg`Only the people already listed are matched: the host search failed. ${{ error: error ?? "" }}`,
52 ),
53 "search-truncated": (_error, resolve) =>
54 resolve(msg("More people match than the host returned. Keep typing to narrow it down.")),
55};
56
57export function PullRequestReviewerPicker({
58 environmentId,
59 reference,
60 allowed,
61 searchable,
62}: {
63 environmentId: EnvironmentId;
64 reference: PullRequestRef;
65 allowed: boolean;
66 searchable: boolean;
67}) {
68 const gt = useGT();
69 const resolve = useMessages();
70 const [open, setOpen] = useState(false);
71 const [query, setQuery] = useState("");
72 const [draft, setDraft] = useState(emptySelection<PullRequestReviewerCandidate>);
73
74 const candidatesQuery = useEnvironmentQuery(
75 open ? pullRequestEnvironment.reviewerCandidates({ environmentId, input: reference }) : null,
76 resolve,
77 );
78 // Past the first page the host is asked, since what was loaded cannot answer for the rest.
79 const debouncedQuery = useDebouncedValue(query.trim(), 250);
80 const searchInput = { loaded: candidatesQuery.data, searchable, query, debouncedQuery };
81 const hostQuery = hostReviewerQuery(searchInput);
82 const searchResult = useEnvironmentQuery(
83 open && hostQuery !== null
84 ? pullRequestEnvironment.reviewerSearch({
85 environmentId,
86 input: { ...reference, query: hostQuery },
87 })
88 : null,
89 );
90 const requestReviewers = useAtomCommand(pullRequestEnvironment.requestReviewers, {
91 reportFailure: false,
92 });
93
94 const { candidates, searchPending, searchError, truncation } = reviewerCandidateView({
95 ...searchInput,
96 search: searchResult,
97 });
98
99 const send = async (people: ReadonlyArray<PullRequestReviewerCandidate>, requested: boolean) => {
100 for (const batch of changeBatches(people)) await sendBatch(batch, requested);
101 };
102 const sendBatch = async (
103 people: ReadonlyArray<PullRequestReviewerCandidate>,
104 requested: boolean,
105 ) => {
106 const result = await requestReviewers({
107 environmentId,
108 input: {
109 ...reference,
110 reviewers: people.map(({ id, kind }) => ({ id, kind })),
111 requested,
112 },
113 });
114 if (result._tag === "Success") return;
115 const logins = people.map((person) => person.login).join(", ");
116 toastManager.add({
117 type: "error",
118 title: requested
119 ? m(msg`Could not ask ${{ logins }} for a review`)
120 : m(msg`Could not take back the review request to ${{ logins }}`),
121 description: readableFailure(
122 squashAtomCommandFailure(result),
123 m(
124 msg(
125 "The host refused it. Check that you have write access on this repository, and that they still have access to it.",
126 ),
127 ),
128 ),
129 });
130 };
131
132 const onOpenChange = (nextOpen: boolean) => {
133 setOpen(nextOpen);
134 if (nextOpen) return;
135 // Loaded rows first: they carry the request state mutations update.
136 const latest = [
137 ...(candidatesQuery.data?.candidates ?? []),
138 ...(searchResult.data?.candidates ?? []),
139 ];
140 const { add, remove } = selectionChanges(
141 draft,
142 (key, person) =>
143 latest.find((entry) => `${entry.kind}:${entry.id}` === key)?.isRequested ??
144 person.isRequested,
145 );
146 setDraft(emptySelection());
147 // A search result is keyed by what was typed, so the writes do not reach it on their own.
148 const refreshSearch =
149 hostQuery !== null && add.length + remove.length > 0 ? searchResult.refresh : null;
150 // Removing first lets a host that keeps one reviewer take the new one.
151 void send(remove, false)
152 .then(() => send(add, true))
153 .then(() => refreshSearch?.());
154 };
155
156 return (
157 <PullRequestCandidatePicker
158 icon={<UserPlusIcon className="size-3.5" />}
159 label={gt`Request a review`}
160 allowed={allowed}
161 disabledReason={gt`Asking someone to review needs write access on this repository`}
162 open={open}
163 onOpenChange={onOpenChange}
164 query={query}
165 onQueryChange={setQuery}
166 searchLabel={gt`Search people with access`}
167 isPending={(candidatesQuery.isPending && candidatesQuery.data === null) || searchPending}
168 error={
169 candidatesQuery.data === null
170 ? candidatesQuery.error
171 : candidates.length === 0
172 ? searchError
173 : null
174 }
175 candidates={candidates}
176 emptyLabel={gt`Nobody else has access to this repository.`}
177 noMatchLabel={gt`Nobody with access matches that.`}
178 errorLabel={gt`The people with access could not be read.`}
179 truncated={truncation !== null}
180 truncatedLabel={truncation === null ? "" : TRUNCATED_LABELS[truncation](searchError, resolve)}
181 candidateKey={(candidate) => `${candidate.kind}:${candidate.id}`}
182 onSelect={(candidate) =>
183 setDraft((current) =>
184 toggleSelection(
185 current,
186 `${candidate.kind}:${candidate.id}`,
187 candidate,
188 candidate.isRequested,
189 ),
190 )
191 }
192 >
193 {(candidate) => (
194 <>
195 <PullRequestActorLabel actor={candidate} className="flex-1" />
196 {candidate.kind === "team" ? (
197 <span className="shrink-0 text-muted-foreground">team</span>
198 ) : null}
199 {isSelected(draft, `${candidate.kind}:${candidate.id}`, candidate.isRequested) ? (
200 <CheckIcon aria-label={gt`Already asked`} className="size-3.5 shrink-0" />
201 ) : null}
202 </>
203 )}
204 </PullRequestCandidatePicker>
205 );
206}