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 { 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 // A new search shows its best matches from the top.
90 const search = (next: string) => {
91 setQuery(next);
92 listRef.current?.scrollToOffset({
93 offset: Platform.OS === "ios" ? -insets.top : 0,
94 animated: false,
95 });
96 };
97 const update = async (
98 candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
99 ) => {
100 if (!allowed || inFlight.current) return;
101 inFlight.current = true;
102 setPending(`${candidate.kind}:${candidate.id}`);
103 setError(null);
104 const response = await request({
105 ...target,
106 input: {
107 ...target.input,
108 reviewers: [{ id: candidate.id, kind: candidate.kind }],
109 requested: !candidate.isRequested,
110 },
111 });
112 inFlight.current = false;
113 setPending(null);
114 if (AsyncResult.isFailure(response)) {
115 const cause = squashAtomCommandFailure(response);
116 setError(
117 cause instanceof Error ? cause.message : "Couldn't update this review request. Try again.",
118 );
119 return;
120 }
121 if (!pr?.capabilities.reviewers.listCandidates) {
122 search("");
123 detail.refresh();
124 }
125 };
126 const listCandidates = pr?.capabilities.reviewers.listCandidates === true;
127 const searchOptions = {
128 placeholder: "Search reviewers",
129 autoCapitalize: "none" as const,
130 onChangeText: (event: { nativeEvent: { text: string } }) => search(event.nativeEvent.text),
131 onCancelButtonPress: () => search(""),
132 hideNavigationBar: false,
133 hideWhenScrolling: false,
134 obscureBackground: false,
135 allowToolbarIntegration: integratedSearch,
136 placement: integratedSearch ? ("automatic" as const) : ("stacked" as const),
137 };
138 return (
139 <View className="flex-1 bg-sheet">
140 <SheetHeader
141 title="Request review"
142 subtitle={`#${route.params.number} · ${route.params.repository}`}
143 onClose={() => navigation.goBack()}
144 accessibilityLabel="Close request review"
145 />
146 <NativeStackScreenOptions
147 options={{
148 headerSearchBarOptions: listCandidates ? searchOptions : undefined,
149 unstable_headerToolbarItems: () =>
150 listCandidates && integratedSearch
151 ? [
152 createNativeMailSearchToolbarItem({
153 placeholder: "Search reviewers",
154 onSearchTextChange: search,
155 showsSearchDismissButton: true,
156 searchTextChangeId: "pr-reviewer-search",
157 }),
158 ]
159 : [],
160 }}
161 />
162 {listCandidates ? (
163 <FlatList
164 ref={listRef}
165 data={candidates}
166 keyExtractor={(candidate) => `${candidate.kind}:${candidate.id}`}
167 renderScrollComponent={
168 Platform.OS === "ios" ? (props) => <ReviewerScrollView {...props} /> : undefined
169 }
170 contentInsetAdjustmentBehavior="never"
171 automaticallyAdjustKeyboardInsets
172 keyboardDismissMode="on-drag"
173 keyboardShouldPersistTaps="handled"
174 contentContainerStyle={{ paddingBottom: 24 }}
175 ListHeaderComponent={
176 <View className="gap-3 px-4 py-4">
177 <Text className="text-xs text-foreground-muted">
178 Tap someone to request a review. Tap a requested reviewer to remove the request.
179 </Text>
180 {Platform.OS === "android" ? (
181 <TextInput
182 accessibilityLabel="Search reviewers"
183 placeholder="Search reviewers"
184 placeholderTextColorClassName="accent-foreground-muted"
185 value={query}
186 onChangeText={search}
187 autoCapitalize="none"
188 className="min-h-11 rounded-xl bg-grouped-card px-3 text-sm"
189 />
190 ) : null}
191 {!allowed ? (
192 <Text className="text-xs text-foreground-muted">
193 Requesting reviews requires write access and an open {singular}.
194 </Text>
195 ) : null}
196 {error ? (
197 <Text selectable className="text-sm text-danger-foreground">
198 {error}
199 </Text>
200 ) : null}
201 </View>
202 }
203 renderItem={({ item }) => {
204 const id = `${item.kind}:${item.id}`;
205 return (
206 <Pressable
207 accessibilityRole="button"
208 accessibilityLabel={`${item.isRequested ? "Remove review request from" : "Request review from"} ${item.login}${item.kind === "team" ? " team" : ""}`}
209 accessibilityState={{ disabled: !allowed || pending !== null }}
210 disabled={!allowed || pending !== null}
211 onPress={() => void update(item)}
212 className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70"
213 >
214 <PullRequestAvatar actor={item} size={32} />
215 <View className="min-w-0 flex-1 gap-0.5">
216 <Text className="text-sm font-t3-medium" numberOfLines={1}>
217 {item.name || item.login}
218 </Text>
219 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
220 {item.login}
221 {item.kind === "team" ? " · Team" : ""}
222 </Text>
223 </View>
224 {pending === id ? (
225 <AppActivityIndicator />
226 ) : item.isRequested ? (
227 <View className="flex-row items-center gap-1.5">
228 <Text className="text-xs text-foreground-muted">Requested</Text>
229 <SymbolView name="checkmark" size={14} tintColorClassName="accent-icon" />
230 </View>
231 ) : (
232 <SymbolView name="plus" size={16} tintColorClassName="accent-icon-muted" />
233 )}
234 </Pressable>
235 );
236 }}
237 ListEmptyComponent={
238 result.isPending && !result.data ? (
239 <AppActivityIndicator className="my-8" />
240 ) : (
241 <View className="px-4 py-6">
242 <EmptyState
243 title={
244 result.error
245 ? "Couldn't load reviewers"
246 : query.trim()
247 ? "No matching reviewers"
248 : "No reviewers available"
249 }
250 detail={result.error ?? "Search people and teams with access to this repository."}
251 variant="plain"
252 />
253 {result.error ? <Button label="Retry" onPress={result.refresh} /> : null}
254 </View>
255 )
256 }
257 ListFooterComponent={
258 result.data?.truncated ? (
259 <Text className="px-4 py-4 text-xs text-foreground-muted">
260 The provider has more reviewers than it returned. Find additional reviewers on the
261 provider.
262 </Text>
263 ) : undefined
264 }
265 />
266 ) : (
267 <ScrollView
268 contentInsetAdjustmentBehavior="automatic"
269 automaticallyAdjustKeyboardInsets
270 keyboardShouldPersistTaps="handled"
271 contentContainerStyle={{ padding: 16, gap: 16 }}
272 >
273 {!pr ? (
274 detail.isPending ? (
275 <AppActivityIndicator />
276 ) : (
277 <Text className="text-danger-foreground">
278 {detail.error ?? `Couldn't load this ${singular}.`}
279 </Text>
280 )
281 ) : (
282 <>
283 <Text className="text-sm text-foreground-muted">
284 This provider accepts a reviewer ID but cannot list candidates.
285 </Text>
286 <TextInput
287 accessibilityLabel="Reviewer ID"
288 placeholder="Reviewer login or ID"
289 placeholderTextColorClassName="accent-foreground-muted"
290 value={query}
291 onChangeText={search}
292 autoCapitalize="none"
293 autoCorrect={false}
294 className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
295 />
296 <Button
297 label="Request review"
298 fullWidth
299 disabled={!allowed || !query.trim() || pending !== null}
300 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: false })}
301 />
302 <Button
303 label="Remove review request"
304 fullWidth
305 tone="text"
306 disabled={!allowed || !query.trim() || pending !== null}
307 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: true })}
308 />
309 {error ? (
310 <Text selectable className="text-danger-foreground">
311 {error}
312 </Text>
313 ) : null}
314 </>
315 )}
316 </ScrollView>
317 )}
318 </View>
319 );
320}