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