Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
3import { AppBar, type AppBarSearch } from "../../components/ui/AppBar";
4import { AsyncResult } from "effect/reactivity";
5import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6import { usePullRequestConnected } from "./usePullRequestConnected";
7import { useAtomValue } from "@effect/atom-react";
8import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
9import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
11import { changeRequestTermKind } from "../../lib/changeRequestTerm";
12import {
13 hostReviewerQuery,
14 reviewerCandidateView,
15 type ReviewerTruncation,
16} from "@t3tools/client-runtime/pull-request-reviewers";
17import {
18 emptySelection,
19 isSelected,
20 changeBatches,
21 selectionChanges,
22 toggleSelection,
23} from "@t3tools/client-runtime/pull-request-selection";
24import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
25import { msg, T, useGT, useMessages, select } from "gt-react-native";
26import { useEffect, useRef, useState } from "react";
27import { Pressable, ScrollView, View } from "react-native";
28import { NativeScrollView } from "../../native/NativeScrollViewMarker";
29import { useContentTopInset, useSearchToolbarInset } from "../../components/ui/useBarInset";
30import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
31import { EmptyState } from "../../components/ui/EmptyState";
32import { Button } from "../../components/ui/Button";
33import * as Dialog from "../../components/ui/Dialog";
34import { SymbolView } from "../../components/ui/AppSymbol";
35import { composerPullRequests } from "../../state/pull-requests";
36import { useEnvironmentQuery } from "../../state/query";
37import { useDebouncedValue } from "../../state/queries";
38import { useAtomCommand } from "../../state/use-atom-command";
39import { PullRequestAvatar } from "./PullRequestPresentation";
40import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
41import type { MessageResolver } from "../../i18n/messages";
42import { m as resolveMessage } from "../../i18n/messages";
43
44const TRUNCATED_LABELS: Record<
45 ReviewerTruncation,
46 (error: string | null, resolve: MessageResolver) => string
47> = {
48 unsearchable: (_error, resolve) =>
49 resolve(
50 msg(
51 "The provider has more reviewers than it returned. Find additional reviewers on the provider.",
52 ),
53 ),
54 searchable: (_error, resolve) =>
55 resolve(msg("The provider has more reviewers than are listed here. Search to find them.")),
56 "search-failed": (error, resolve) =>
57 resolve(
58 msg`Only listed reviewers are matched: the provider search failed. ${{ error: error ?? "" }}`,
59 ),
60 "search-truncated": (_error, resolve) =>
61 resolve(msg("More reviewers match than the provider returned. Keep typing to narrow it down.")),
62};
63
64export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequestParams>) {
65 const navigation = useNavigation();
66 const gt = useGT();
67 const m = useMessages();
68 const contentTopInset = useContentTopInset();
69 const listRef = useRef<LegendListRef>(null);
70 const target = pullRequestTarget(route.params);
71 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
72 const pr = detail.data;
73 const term = changeRequestTermKind(
74 sourceControlClients.get((pr ?? route.params.initialSummary)?.provider).changeRequest,
75 );
76 const canWrite = useAtomValue(
77 composerPullRequests.requestReviewers.permissionAtom(target.environmentId),
78 );
79 const connected = usePullRequestConnected(route.params.environmentId);
80 const allowed =
81 connected &&
82 canWrite &&
83 pr?.state === "open" &&
84 pr.capabilities.reviewers.request &&
85 pr.viewerPermissions.requestReviewers;
86 const result = useEnvironmentQuery(
87 pr?.capabilities.reviewers.listCandidates
88 ? composerPullRequests.reviewerCandidates(target)
89 : null,
90 );
91 const request = useAtomCommand(composerPullRequests.requestReviewers, { reportFailure: false });
92 const [query, setQuery] = useState("");
93 const [pending, setPending] = useState<string | null>(null);
94 const [error, setError] = useState<string | null>(null);
95 const inFlight = useRef(false);
96 const [draft, setDraft] = useState(emptySelection<PullRequestReviewerCandidate>);
97 const debouncedQuery = useDebouncedValue(query.trim(), 250);
98 const searchInput = {
99 loaded: result.data,
100 searchable: pr?.capabilities.reviewers.searchCandidates === true,
101 query,
102 debouncedQuery,
103 };
104 const hostQuery = hostReviewerQuery(searchInput);
105 const searchResult = useEnvironmentQuery(
106 hostQuery !== null
107 ? composerPullRequests.reviewerSearch({
108 ...target,
109 input: { ...target.input, query: hostQuery },
110 })
111 : null,
112 );
113 const view = reviewerCandidateView({
114 ...searchInput,
115 search: searchResult,
116 });
117 const candidates = [...view.candidates].sort(
118 (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),
119 );
120 const queryError = result.error ?? view.searchError;
121 // A new search shows its best matches from the top.
122 const search = (next: string) => {
123 setQuery(next);
124 listRef.current?.scrollToOffset({
125 offset: -contentTopInset,
126 animated: false,
127 });
128 };
129 // Hosts that cannot list candidates take one typed id at a time.
130 const update = async (
131 candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
132 ) => {
133 if (!allowed || inFlight.current) return;
134 inFlight.current = true;
135 setPending(`${candidate.kind}:${candidate.id}`);
136 setError(null);
137 const response = await request({
138 ...target,
139 input: {
140 ...target.input,
141 reviewers: [{ id: candidate.id, kind: candidate.kind }],
142 requested: !candidate.isRequested,
143 },
144 });
145 inFlight.current = false;
146 setPending(null);
147 if (AsyncResult.isFailure(response)) {
148 const cause = squashAtomCommandFailure(response);
149 setError(
150 cause instanceof Error
151 ? (errorDisplayMessage(cause, resolveMessage) ?? cause.message)
152 : gt`Couldn't update this review request. Try again.`,
153 );
154 return;
155 }
156 search("");
157 detail.refresh();
158 };
159 const listCandidates = pr?.capabilities.reviewers.listCandidates === true;
160 // Loaded rows first: they carry the request state mutations update.
161 const latest = [...(result.data?.candidates ?? []), ...(searchResult.data?.candidates ?? [])];
162 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed
163 useEffect(
164 () =>
165 navigation.addListener("beforeRemove", () => {
166 const { add, remove } = selectionChanges(
167 draft,
168 (key, person) =>
169 latest.find((entry) => `${entry.kind}:${entry.id}` === key)?.isRequested ??
170 person.isRequested,
171 );
172 const sendBatch = async (
173 people: ReadonlyArray<PullRequestReviewerCandidate>,
174 requested: boolean,
175 ) => {
176 const response = await request({
177 ...target,
178 input: {
179 ...target.input,
180 reviewers: people.map(({ id, kind }) => ({ id, kind })),
181 requested,
182 },
183 });
184 if (!AsyncResult.isFailure(response)) return;
185 const cause = squashAtomCommandFailure(response);
186 const logins = people.map((person) => person.login).join(", ");
187 Dialog.alert(
188 requested
189 ? gt`Couldn't request a review from ${{ logins }}`
190 : gt`Couldn't remove the review request from ${{ logins }}`,
191 cause instanceof Error
192 ? (errorDisplayMessage(cause, resolveMessage) ?? cause.message)
193 : gt`The provider refused the change.`,
194 );
195 };
196 const send = async (
197 people: ReadonlyArray<PullRequestReviewerCandidate>,
198 requested: boolean,
199 ) => {
200 for (const batch of changeBatches(people)) await sendBatch(batch, requested);
201 };
202 // A search result is keyed by what was typed, so the writes do not reach it on their own.
203 const refreshSearch =
204 hostQuery !== null && add.length + remove.length > 0 ? searchResult.refresh : null;
205 // Removing first lets a host that keeps one reviewer take the new one.
206 void send(remove, false)
207 .then(() => send(add, true))
208 .then(() => refreshSearch?.());
209 }),
210 [navigation, draft, latest, request, target, hostQuery, searchResult.refresh, gt],
211 );
212 const reviewerSearch: AppBarSearch | undefined = listCandidates
213 ? {
214 mode: "inline",
215 compactToolbar: true,
216 value: query,
217 onChangeText: search,
218 placeholder: gt`Search reviewers`,
219 }
220 : undefined;
221 const searchToolbarInset = useSearchToolbarInset(reviewerSearch);
222 return (
223 <View className="flex-1 bg-sheet">
224 <AppBar
225 title={gt`Request review`}
226 subtitle={`#${route.params.number} · ${route.params.repository}`}
227 onClose={() => navigation.goBack()}
228 closeAccessibilityLabel={gt`Close request review`}
229 search={reviewerSearch}
230 />
231 {listCandidates ? (
232 <LegendList
233 ref={listRef}
234 data={candidates}
235 keyExtractor={(candidate) => `${candidate.kind}:${candidate.id}`}
236 extraData={{ allowed, draft }}
237 estimatedItemSize={64}
238 recycleItems
239 renderScrollComponent={NativeScrollView}
240 contentInsetAdjustmentBehavior="automatic"
241 automaticallyAdjustKeyboardInsets
242 keyboardDismissMode="on-drag"
243 keyboardShouldPersistTaps="handled"
244 contentContainerStyle={{ paddingBottom: 24 + searchToolbarInset }}
245 ListHeaderComponent={
246 <View className="gap-3 px-4 py-4">
247 <Text className="text-xs text-foreground-muted">
248 <T>
249 Tap someone to request a review. Tap a requested reviewer to remove the request.
250 Changes are sent when you close this sheet.
251 </T>
252 </Text>
253 {!allowed ? (
254 <Text className="text-xs text-foreground-muted">
255 {gt`Requesting reviews requires write access and an open ${select(
256 { term },
257 {
258 mr: "merge request",
259 cr: "change request",
260 other: "pull request",
261 },
262 )}.`}
263 </Text>
264 ) : null}
265 </View>
266 }
267 renderItem={({ item }) => {
268 const id = `${item.kind}:${item.id}`;
269 const requested = isSelected(draft, id, item.isRequested);
270 return (
271 <Pressable
272 accessibilityRole="button"
273 accessibilityLabel={
274 item.kind === "team"
275 ? requested
276 ? gt`Remove review request from ${{ login: item.login }} team`
277 : gt`Request review from ${{ login: item.login }} team`
278 : requested
279 ? gt`Remove review request from ${{ login: item.login }}`
280 : gt`Request review from ${{ login: item.login }}`
281 }
282 accessibilityState={{ disabled: !allowed }}
283 disabled={!allowed}
284 onPress={() =>
285 setDraft((current) => toggleSelection(current, id, item, item.isRequested))
286 }
287 className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70"
288 >
289 <PullRequestAvatar actor={item} size={32} />
290 <View className="min-w-0 flex-1 gap-0.5">
291 <Text className="text-sm font-t3-medium" numberOfLines={1}>
292 {item.name || item.login}
293 </Text>
294 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
295 {item.login}
296 {item.kind === "team" ? ` · ${gt({ context: "reviewer kind" })`Team`}` : ""}
297 </Text>
298 </View>
299 {requested ? (
300 <View className="flex-row items-center gap-1.5">
301 <Text className="text-xs text-foreground-muted">
302 <T context="reviewer state">Requested</T>
303 </Text>
304 <SymbolView name="checkmark" size={14} tintColorClassName="accent-icon" />
305 </View>
306 ) : (
307 <SymbolView name="plus" size={16} tintColorClassName="accent-icon-muted" />
308 )}
309 </Pressable>
310 );
311 }}
312 ListEmptyComponent={
313 (result.isPending && !result.data) || view.searchPending ? (
314 <AppActivityIndicator className="my-8" />
315 ) : (
316 <View className="px-4 py-6">
317 <EmptyState
318 title={
319 queryError
320 ? gt`Couldn't load reviewers`
321 : query.trim()
322 ? gt`No matching reviewers`
323 : gt`No reviewers available`
324 }
325 detail={queryError ?? gt`Search people and teams with access to this repository.`}
326 variant="plain"
327 />
328 {queryError ? (
329 <Button
330 label={gt`Retry`}
331 onPress={result.error ? result.refresh : searchResult.refresh}
332 />
333 ) : null}
334 </View>
335 )
336 }
337 ListFooterComponent={
338 view.truncation ? (
339 <Text className="px-4 py-4 text-xs text-foreground-muted">
340 {TRUNCATED_LABELS[view.truncation](view.searchError, m)}
341 </Text>
342 ) : undefined
343 }
344 />
345 ) : (
346 <ScrollView
347 contentInsetAdjustmentBehavior="automatic"
348 automaticallyAdjustKeyboardInsets
349 keyboardShouldPersistTaps="handled"
350 contentContainerStyle={{ padding: 16, gap: 16 }}
351 >
352 {!pr ? (
353 detail.isPending ? (
354 <AppActivityIndicator />
355 ) : (
356 <Text className="text-danger-foreground">
357 {detail.error ??
358 gt`Couldn't load this ${select(
359 { term },
360 {
361 mr: "merge request",
362 cr: "change request",
363 other: "pull request",
364 },
365 )}.`}
366 </Text>
367 )
368 ) : (
369 <>
370 <Text className="text-sm text-foreground-muted">
371 <T>This provider accepts a reviewer ID but cannot list candidates.</T>
372 </Text>
373 <TextInput
374 accessibilityLabel={gt`Reviewer ID`}
375 placeholder={gt`Reviewer login or ID`}
376 placeholderTextColorClassName="accent-foreground-muted"
377 value={query}
378 onChangeText={search}
379 autoCapitalize="none"
380 autoCorrect={false}
381 className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
382 />
383 <Button
384 label={gt`Request review`}
385 fullWidth
386 disabled={!allowed || !query.trim() || pending !== null}
387 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: false })}
388 />
389 <Button
390 label={gt`Remove review request`}
391 fullWidth
392 tone="text"
393 disabled={!allowed || !query.trim() || pending !== null}
394 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: true })}
395 />
396 {error ? (
397 <Text selectable className="text-danger-foreground">
398 {error}
399 </Text>
400 ) : null}
401 </>
402 )}
403 </ScrollView>
404 )}
405 </View>
406 );
407}