Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestReviewersScreen.tsx

301 lines12.1 KB

1import { AppBar, type AppBarSearch } from "../../components/ui/AppBar";
2import { AsyncResult } from "effect/reactivity";
3import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
4import { usePullRequestConnected } from "./usePullRequestConnected";
5import { useAtomValue } from "@effect/atom-react";
6import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
9import {
10 hostReviewerQuery,
11 reviewerCandidateView,
12 type ReviewerTruncation,
13} from "@t3tools/client-runtime/pull-request-reviewers";
14import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
15import { useRef, useState } from "react";
16import { FlatList, Pressable, ScrollView, View } from "react-native";
17import { NativeScrollView } from "../../native/NativeScrollViewMarker";
18import { useContentTopInset, useSearchToolbarInset } from "../../components/ui/useBarInset";
19import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
20import { EmptyState } from "../../components/ui/EmptyState";
21import { Button } from "../../components/ui/Button";
22import { SymbolView } from "../../components/ui/AppSymbol";
23import { composerPullRequests } from "../../state/pull-requests";
24import { useEnvironmentQuery } from "../../state/query";
25import { useDebouncedValue } from "../../state/queries";
26import { useAtomCommand } from "../../state/use-atom-command";
27import { PullRequestAvatar } from "./PullRequestPresentation";
28import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
29​
30const TRUNCATED_LABELS: Record<ReviewerTruncation, (error: string | null) => string> = {
31 unsearchable: () =>
32 "The provider has more reviewers than it returned. Find additional reviewers on the provider.",
33 searchable: () => "The provider has more reviewers than are listed here. Search to find them.",
34 "search-failed": (error) =>
35 `Only listed reviewers are matched: the provider search failed. ${error ?? ""}`,
36 "search-truncated": () =>
37 "More reviewers match than the provider returned. Keep typing to narrow it down.",
38};
39​
40export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequestParams>) {
41 const navigation = useNavigation();
42 const contentTopInset = useContentTopInset();
43 const listRef = useRef<FlatList<PullRequestReviewerCandidate>>(null);
44 const target = pullRequestTarget(route.params);
45 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
46 const pr = detail.data;
47 const { singular } = sourceControlClients.get(
48 (pr ?? route.params.initialSummary)?.provider,
49 ).changeRequest;
50 const canWrite = useAtomValue(
51 composerPullRequests.requestReviewers.permissionAtom(target.environmentId),
52 );
53 const connected = usePullRequestConnected(route.params.environmentId);
54 const allowed =
55 connected &&
56 canWrite &&
57 pr?.state === "open" &&
58 pr.capabilities.reviewers.request &&
59 pr.viewerPermissions.requestReviewers;
60 const result = useEnvironmentQuery(
61 pr?.capabilities.reviewers.listCandidates
62 ? composerPullRequests.reviewerCandidates(target)
63 : null,
64 );
65 const request = useAtomCommand(composerPullRequests.requestReviewers, { reportFailure: false });
66 const [query, setQuery] = useState("");
67 const [pending, setPending] = useState<string | null>(null);
68 const [error, setError] = useState<string | null>(null);
69 const inFlight = useRef(false);
70 const debouncedQuery = useDebouncedValue(query.trim(), 250);
71 const searchInput = {
72 loaded: result.data,
73 searchable: pr?.capabilities.reviewers.searchCandidates === true,
74 query,
75 debouncedQuery,
76 };
77 const hostQuery = hostReviewerQuery(searchInput);
78 const searchResult = useEnvironmentQuery(
79 hostQuery !== null
80 ? composerPullRequests.reviewerSearch({
81 ...target,
82 input: { ...target.input, query: hostQuery },
83 })
84 : null,
85 );
86 const view = reviewerCandidateView({
87 ...searchInput,
88 search: searchResult,
89 });
90 const candidates = [...view.candidates].sort(
91 (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),
92 );
93 const queryError = result.error ?? view.searchError;
94 // A new search shows its best matches from the top.
95 const search = (next: string) => {
96 setQuery(next);
97 listRef.current?.scrollToOffset({
98 offset: -contentTopInset,
99 animated: false,
100 });
101 };
102 const update = async (
103 candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
104 ) => {
105 if (!allowed || inFlight.current) return;
106 inFlight.current = true;
107 setPending(`${candidate.kind}:${candidate.id}`);
108 setError(null);
109 const response = await request({
110 ...target,
111 input: {
112 ...target.input,
113 reviewers: [{ id: candidate.id, kind: candidate.kind }],
114 requested: !candidate.isRequested,
115 },
116 });
117 inFlight.current = false;
118 setPending(null);
119 if (AsyncResult.isFailure(response)) {
120 const cause = squashAtomCommandFailure(response);
121 setError(
122 cause instanceof Error ? cause.message : "Couldn't update this review request. Try again.",
123 );
124 return;
125 }
126 if (hostQuery !== null) searchResult.refresh();
127 if (!pr?.capabilities.reviewers.listCandidates) {
128 search("");
129 detail.refresh();
130 }
131 };
132 const listCandidates = pr?.capabilities.reviewers.listCandidates === true;
133 const reviewerSearch: AppBarSearch | undefined = listCandidates
134 ? {
135 mode: "inline",
136 compactToolbar: true,
137 value: query,
138 onChangeText: search,
139 placeholder: "Search reviewers",
140 }
141 : undefined;
142 const searchToolbarInset = useSearchToolbarInset(reviewerSearch);
143 return (
144 <View className="flex-1 bg-sheet">
145 <AppBar
146 title="Request review"
147 subtitle={`#${route.params.number} · ${route.params.repository}`}
148 onClose={() => navigation.goBack()}
149 closeAccessibilityLabel="Close request review"
150 search={reviewerSearch}
151 />
152 {listCandidates ? (
153 <FlatList
154 ref={listRef}
155 data={candidates}
156 keyExtractor={(candidate) => `${candidate.kind}:${candidate.id}`}
157 renderScrollComponent={NativeScrollView}
158 contentInsetAdjustmentBehavior="automatic"
159 automaticallyAdjustKeyboardInsets
160 keyboardDismissMode="on-drag"
161 keyboardShouldPersistTaps="handled"
162 contentContainerStyle={{ paddingBottom: 24 + searchToolbarInset }}
163 ListHeaderComponent={
164 <View className="gap-3 px-4 py-4">
165 <Text className="text-xs text-foreground-muted">
166 Tap someone to request a review. Tap a requested reviewer to remove the request.
167 </Text>
168 {!allowed ? (
169 <Text className="text-xs text-foreground-muted">
170 Requesting reviews requires write access and an open {singular}.
171 </Text>
172 ) : null}
173 {error ? (
174 <Text selectable className="text-sm text-danger-foreground">
175 {error}
176 </Text>
177 ) : null}
178 </View>
179 }
180 renderItem={({ item }) => {
181 const id = `${item.kind}:${item.id}`;
182 return (
183 <Pressable
184 accessibilityRole="button"
185 accessibilityLabel={`${item.isRequested ? "Remove review request from" : "Request review from"} ${item.login}${item.kind === "team" ? " team" : ""}`}
186 accessibilityState={{ disabled: !allowed || pending !== null }}
187 disabled={!allowed || pending !== null}
188 onPress={() => void update(item)}
189 className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70"
190 >
191 <PullRequestAvatar actor={item} size={32} />
192 <View className="min-w-0 flex-1 gap-0.5">
193 <Text className="text-sm font-t3-medium" numberOfLines={1}>
194 {item.name || item.login}
195 </Text>
196 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
197 {item.login}
198 {item.kind === "team" ? " · Team" : ""}
199 </Text>
200 </View>
201 {pending === id ? (
202 <AppActivityIndicator />
203 ) : item.isRequested ? (
204 <View className="flex-row items-center gap-1.5">
205 <Text className="text-xs text-foreground-muted">Requested</Text>
206 <SymbolView name="checkmark" size={14} tintColorClassName="accent-icon" />
207 </View>
208 ) : (
209 <SymbolView name="plus" size={16} tintColorClassName="accent-icon-muted" />
210 )}
211 </Pressable>
212 );
213 }}
214 ListEmptyComponent={
215 (result.isPending && !result.data) || view.searchPending ? (
216 <AppActivityIndicator className="my-8" />
217 ) : (
218 <View className="px-4 py-6">
219 <EmptyState
220 title={
221 queryError
222 ? "Couldn't load reviewers"
223 : query.trim()
224 ? "No matching reviewers"
225 : "No reviewers available"
226 }
227 detail={queryError ?? "Search people and teams with access to this repository."}
228 variant="plain"
229 />
230 {queryError ? (
231 <Button
232 label="Retry"
233 onPress={result.error ? result.refresh : searchResult.refresh}
234 />
235 ) : null}
236 </View>
237 )
238 }
239 ListFooterComponent={
240 view.truncation ? (
241 <Text className="px-4 py-4 text-xs text-foreground-muted">
242 {TRUNCATED_LABELS[view.truncation](view.searchError)}
243 </Text>
244 ) : undefined
245 }
246 />
247 ) : (
248 <ScrollView
249 contentInsetAdjustmentBehavior="automatic"
250 automaticallyAdjustKeyboardInsets
251 keyboardShouldPersistTaps="handled"
252 contentContainerStyle={{ padding: 16, gap: 16 }}
253 >
254 {!pr ? (
255 detail.isPending ? (
256 <AppActivityIndicator />
257 ) : (
258 <Text className="text-danger-foreground">
259 {detail.error ?? `Couldn't load this ${singular}.`}
260 </Text>
261 )
262 ) : (
263 <>
264 <Text className="text-sm text-foreground-muted">
265 This provider accepts a reviewer ID but cannot list candidates.
266 </Text>
267 <TextInput
268 accessibilityLabel="Reviewer ID"
269 placeholder="Reviewer login or ID"
270 placeholderTextColorClassName="accent-foreground-muted"
271 value={query}
272 onChangeText={search}
273 autoCapitalize="none"
274 autoCorrect={false}
275 className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
276 />
277 <Button
278 label="Request review"
279 fullWidth
280 disabled={!allowed || !query.trim() || pending !== null}
281 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: false })}
282 />
283 <Button
284 label="Remove review request"
285 fullWidth
286 tone="text"
287 disabled={!allowed || !query.trim() || pending !== null}
288 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: true })}
289 />
290 {error ? (
291 <Text selectable className="text-danger-foreground">
292 {error}
293 </Text>
294 ) : null}
295 </>
296 )}
297 </ScrollView>
298 )}
299 </View>
300 );