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