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

PullRequestReviewersScreen.tsx

315 lines12.5 KB

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