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