@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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