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

PullRequestReviewersScreen.tsx

330 lines13.1 KB

1import { Toolbar } from "../../components/ui/Toolbar";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import { usePullRequestConnected } from "./usePullRequestConnected";
4import { useAtomValue } from "@effect/atom-react";
5import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
6import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
7import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
8import { useEffect, useMemo, useRef, useState } from "react";
9import {
10 FlatList,
11 Platform,
12 Pressable,
13 ScrollView,
14 View,
15 type ScrollViewProps,
16} from "react-native";
17import { useSafeAreaInsets } from "react-native-safe-area-context";
18import { ScrollViewMarker } from "react-native-screens";
19import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
20import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
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 );
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 = useMemo(() => {
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 }, [result.data, query]);
92 useEffect(() => {
93 if (candidates.length === 0) return;
94 // Filtering must reveal the first match below the translucent native header.
95 listRef.current?.scrollToOffset({
96 offset: Platform.OS === "ios" ? -insets.top : 0,
97 animated: false,
98 });
99 }, [candidates, insets.top]);
100 const update = async (
101 candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
102 ) => {
103 if (!allowed || inFlight.current) return;
104 inFlight.current = true;
105 setPending(`${candidate.kind}:${candidate.id}`);
106 setError(null);
107 try {
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 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
117 if (!pr?.capabilities.reviewers.listCandidates) {
118 setQuery("");
119 detail.refresh();
120 }
121 } catch (cause) {
122 setError(
123 cause instanceof Error ? cause.message : "Couldn't update this review request. Try again.",
124 );
125 } finally {
126 inFlight.current = false;
127 setPending(null);
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 <Toolbar placement="left">
145 <Toolbar.Button
146 icon="xmark"
147 accessibilityLabel="Close request review"
148 onPress={() => navigation.goBack()}
149 />
150 </Toolbar>
151 <NativeStackScreenOptions
152 options={{
153 title: "Request review",
154 unstable_headerSubtitle: `#${route.params.number} · ${route.params.repository}`,
155 headerSearchBarOptions: listCandidates ? searchOptions : undefined,
156 unstable_headerToolbarItems: () =>
157 listCandidates && integratedSearch
158 ? [
159 createNativeMailSearchToolbarItem({
160 placeholder: "Search reviewers",
161 onSearchTextChange: setQuery,
162 showsSearchDismissButton: true,
163 searchTextChangeId: "pr-reviewer-search",
164 }),
165 ]
166 : [],
167 }}
168 />
169 {Platform.OS === "android" ? (
170 <AndroidScreenHeader title="Request review" onBack={() => navigation.goBack()} />
171 ) : null}
172 {listCandidates ? (
173 <FlatList
174 ref={listRef}
175 data={candidates}
176 keyExtractor={(candidate) => `${candidate.kind}:${candidate.id}`}
177 renderScrollComponent={
178 Platform.OS === "ios" ? (props) => <ReviewerScrollView {...props} /> : undefined
179 }
180 contentInsetAdjustmentBehavior="never"
181 automaticallyAdjustKeyboardInsets
182 keyboardDismissMode="on-drag"
183 keyboardShouldPersistTaps="handled"
184 contentContainerStyle={{ paddingBottom: 24 }}
185 ListHeaderComponent={
186 <View className="gap-3 px-4 py-4">
187 <Text className="text-xs text-foreground-muted">
188 Tap someone to request a review. Tap a requested reviewer to remove the request.
189 </Text>
190 {Platform.OS === "android" ? (
191 <TextInput
192 accessibilityLabel="Search reviewers"
193 placeholder="Search reviewers"
194 placeholderTextColorClassName="accent-foreground-muted"
195 value={query}
196 onChangeText={setQuery}
197 autoCapitalize="none"
198 className="min-h-11 rounded-xl bg-grouped-card px-3 text-sm"
199 />
200 ) : null}
201 {!allowed ? (
202 <Text className="text-xs text-foreground-muted">
203 Requesting reviews requires write access and an open pull request.
204 </Text>
205 ) : null}
206 {error ? (
207 <Text selectable className="text-sm text-danger-foreground">
208 {error}
209 </Text>
210 ) : null}
211 </View>
212 }
213 renderItem={({ item }) => {
214 const id = `${item.kind}:${item.id}`;
215 return (
216 <Pressable
217 accessibilityRole="button"
218 accessibilityLabel={`${item.isRequested ? "Remove review request from" : "Request review from"} ${item.login}${item.kind === "team" ? " team" : ""}`}
219 accessibilityState={{ disabled: !allowed || pending !== null }}
220 disabled={!allowed || pending !== null}
221 onPress={() => void update(item)}
222 className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70"
223 >
224 <PullRequestAvatar actor={item} size={32} />
225 <View className="min-w-0 flex-1 gap-0.5">
226 <Text className="text-sm font-t3-medium" numberOfLines={1}>
227 {item.name || item.login}
228 </Text>
229 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
230 {item.login}
231 {item.kind === "team" ? " · Team" : ""}
232 </Text>
233 </View>
234 {pending === id ? (
235 <AppActivityIndicator />
236 ) : item.isRequested ? (
237 <View className="flex-row items-center gap-1.5">
238 <Text className="text-xs text-foreground-muted">Requested</Text>
239 <SymbolView name="checkmark" size={14} tintColorClassName="accent-icon" />
240 </View>
241 ) : (
242 <SymbolView name="plus" size={16} tintColorClassName="accent-icon-muted" />
243 )}
244 </Pressable>
245 );
246 }}
247 ListEmptyComponent={
248 result.isPending && !result.data ? (
249 <AppActivityIndicator className="my-8" />
250 ) : (
251 <View className="px-4 py-6">
252 <EmptyState
253 title={
254 result.error
255 ? "Couldn't load reviewers"
256 : query.trim()
257 ? "No matching reviewers"
258 : "No reviewers available"
259 }
260 detail={result.error ?? "Search people and teams with access to this repository."}
261 variant="plain"
262 />
263 {result.error ? <Button label="Retry" onPress={result.refresh} /> : null}
264 </View>
265 )
266 }
267 ListFooterComponent={
268 result.data?.truncated ? (
269 <Text className="px-4 py-4 text-xs text-foreground-muted">
270 The provider has more reviewers than it returned. Find additional reviewers on the
271 provider.
272 </Text>
273 ) : undefined
274 }
275 />
276 ) : (
277 <ScrollView
278 contentInsetAdjustmentBehavior="automatic"
279 automaticallyAdjustKeyboardInsets
280 keyboardShouldPersistTaps="handled"
281 contentContainerStyle={{ padding: 16, gap: 16 }}
282 >
283 {!pr ? (
284 detail.isPending ? (
285 <AppActivityIndicator />
286 ) : (
287 <Text className="text-danger-foreground">
288 {detail.error ?? "Couldn't load this pull request."}
289 </Text>
290 )
291 ) : (
292 <>
293 <Text className="text-sm text-foreground-muted">
294 This provider accepts a reviewer ID but cannot list candidates.
295 </Text>
296 <TextInput
297 accessibilityLabel="Reviewer ID"
298 placeholder="Reviewer login or ID"
299 placeholderTextColorClassName="accent-foreground-muted"
300 value={query}
301 onChangeText={setQuery}
302 autoCapitalize="none"
303 autoCorrect={false}
304 className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
305 />
306 <Button
307 label="Request review"
308 fullWidth
309 disabled={!allowed || !query.trim() || pending !== null}
310 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: false })}
311 />
312 <Button
313 label="Remove review request"
314 fullWidth
315 tone="text"
316 disabled={!allowed || !query.trim() || pending !== null}
317 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: true })}
318 />
319 {error ? (
320 <Text selectable className="text-danger-foreground">
321 {error}
322 </Text>
323 ) : null}
324 </>
325 )}
326 </ScrollView>
327 )}
328 </View>
329 );