@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 403 lines 16.2 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
3 import { AppBar, type AppBarSearch } from "../../components/ui/AppBar";
4 import { AsyncResult } from "effect/reactivity";
5 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6 import { usePullRequestConnected } from "./usePullRequestConnected";
7 import { useAtomValue } from "@effect/atom-react";
8 import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
9 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
11 import { changeRequestTermKind } from "../../lib/changeRequestTerm";
12 import {
13 hostReviewerQuery,
14 reviewerCandidateView,
15 type ReviewerTruncation,
16 } from "@t3tools/client-runtime/pull-request-reviewers";
17 import {
18 emptySelection,
19 isSelected,
20 changeBatches,
21 selectionChanges,
22 toggleSelection,
23 } from "@t3tools/client-runtime/pull-request-selection";
24 import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
25 import { msg, T, useGT, useMessages } from "gt-react-native";
26 import { useEffect, useRef, useState } from "react";
27 import { Pressable, ScrollView, View } from "react-native";
28 import { NativeScrollView } from "../../native/NativeScrollViewMarker";
29 import { useContentTopInset, useSearchToolbarInset } from "../../components/ui/useBarInset";
30 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
31 import { EmptyState } from "../../components/ui/EmptyState";
32 import { Button } from "../../components/ui/Button";
33 import * as Dialog from "../../components/ui/Dialog";
34 import { SymbolView } from "../../components/ui/AppSymbol";
35 import { composerPullRequests } from "../../state/pull-requests";
36 import { useEnvironmentQuery } from "../../state/query";
37 import { useDebouncedValue } from "../../state/queries";
38 import { useAtomCommand } from "../../state/use-atom-command";
39 import { PullRequestAvatar } from "./PullRequestPresentation";
40 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
41 import type { MessageResolver } from "../../i18n/messages";
42 import { m as resolveMessage } from "../../i18n/messages";
43
44 const TRUNCATED_LABELS: Record<
45 ReviewerTruncation,
46 (error: string | null, resolve: MessageResolver) => string
47 > = {
48 unsearchable: (_error, resolve) =>
49 resolve(
50 msg(
51 "The provider has more reviewers than it returned. Find additional reviewers on the provider.",
52 ),
53 ),
54 searchable: (_error, resolve) =>
55 resolve(msg("The provider has more reviewers than are listed here. Search to find them.")),
56 "search-failed": (error, resolve) =>
57 resolve(
58 msg("Only listed reviewers are matched: the provider search failed. {error}", {
59 error: error ?? "",
60 }),
61 ),
62 "search-truncated": (_error, resolve) =>
63 resolve(msg("More reviewers match than the provider returned. Keep typing to narrow it down.")),
64 };
65
66 export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequestParams>) {
67 const navigation = useNavigation();
68 const gt = useGT();
69 const m = useMessages();
70 const contentTopInset = useContentTopInset();
71 const listRef = useRef<LegendListRef>(null);
72 const target = pullRequestTarget(route.params);
73 const detail = useEnvironmentQuery(composerPullRequests.detail(target));
74 const pr = detail.data;
75 const term = changeRequestTermKind(
76 sourceControlClients.get((pr ?? route.params.initialSummary)?.provider).changeRequest,
77 );
78 const canWrite = useAtomValue(
79 composerPullRequests.requestReviewers.permissionAtom(target.environmentId),
80 );
81 const connected = usePullRequestConnected(route.params.environmentId);
82 const allowed =
83 connected &&
84 canWrite &&
85 pr?.state === "open" &&
86 pr.capabilities.reviewers.request &&
87 pr.viewerPermissions.requestReviewers;
88 const result = useEnvironmentQuery(
89 pr?.capabilities.reviewers.listCandidates
90 ? composerPullRequests.reviewerCandidates(target)
91 : null,
92 );
93 const request = useAtomCommand(composerPullRequests.requestReviewers, { reportFailure: false });
94 const [query, setQuery] = useState("");
95 const [pending, setPending] = useState<string | null>(null);
96 const [error, setError] = useState<string | null>(null);
97 const inFlight = useRef(false);
98 const [draft, setDraft] = useState(emptySelection<PullRequestReviewerCandidate>);
99 const debouncedQuery = useDebouncedValue(query.trim(), 250);
100 const searchInput = {
101 loaded: result.data,
102 searchable: pr?.capabilities.reviewers.searchCandidates === true,
103 query,
104 debouncedQuery,
105 };
106 const hostQuery = hostReviewerQuery(searchInput);
107 const searchResult = useEnvironmentQuery(
108 hostQuery !== null
109 ? composerPullRequests.reviewerSearch({
110 ...target,
111 input: { ...target.input, query: hostQuery },
112 })
113 : null,
114 );
115 const view = reviewerCandidateView({
116 ...searchInput,
117 search: searchResult,
118 });
119 const candidates = [...view.candidates].sort(
120 (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),
121 );
122 const queryError = result.error ?? view.searchError;
123 // A new search shows its best matches from the top.
124 const search = (next: string) => {
125 setQuery(next);
126 listRef.current?.scrollToOffset({
127 offset: -contentTopInset,
128 animated: false,
129 });
130 };
131 // Hosts that cannot list candidates take one typed id at a time.
132 const update = async (
133 candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
134 ) => {
135 if (!allowed || inFlight.current) return;
136 inFlight.current = true;
137 setPending(`${candidate.kind}:${candidate.id}`);
138 setError(null);
139 const response = await request({
140 ...target,
141 input: {
142 ...target.input,
143 reviewers: [{ id: candidate.id, kind: candidate.kind }],
144 requested: !candidate.isRequested,
145 },
146 });
147 inFlight.current = false;
148 setPending(null);
149 if (AsyncResult.isFailure(response)) {
150 const cause = squashAtomCommandFailure(response);
151 setError(
152 cause instanceof Error
153 ? (errorDisplayMessage(cause, resolveMessage) ?? cause.message)
154 : gt("Couldn't update this review request. Try again."),
155 );
156 return;
157 }
158 search("");
159 detail.refresh();
160 };
161 const listCandidates = pr?.capabilities.reviewers.listCandidates === true;
162 // Loaded rows first: they carry the request state mutations update.
163 const latest = [...(result.data?.candidates ?? []), ...(searchResult.data?.candidates ?? [])];
164 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed
165 useEffect(
166 () =>
167 navigation.addListener("beforeRemove", () => {
168 const { add, remove } = selectionChanges(
169 draft,
170 (key, person) =>
171 latest.find((entry) => `${entry.kind}:${entry.id}` === key)?.isRequested ??
172 person.isRequested,
173 );
174 const sendBatch = async (
175 people: ReadonlyArray<PullRequestReviewerCandidate>,
176 requested: boolean,
177 ) => {
178 const response = await request({
179 ...target,
180 input: {
181 ...target.input,
182 reviewers: people.map(({ id, kind }) => ({ id, kind })),
183 requested,
184 },
185 });
186 if (!AsyncResult.isFailure(response)) return;
187 const cause = squashAtomCommandFailure(response);
188 const logins = people.map((person) => person.login).join(", ");
189 Dialog.alert(
190 requested
191 ? gt("Couldn't request a review from {logins}", { logins })
192 : gt("Couldn't remove the review request from {logins}", { logins }),
193 cause instanceof Error
194 ? (errorDisplayMessage(cause, resolveMessage) ?? cause.message)
195 : gt("The provider refused the change."),
196 );
197 };
198 const send = async (
199 people: ReadonlyArray<PullRequestReviewerCandidate>,
200 requested: boolean,
201 ) => {
202 for (const batch of changeBatches(people)) await sendBatch(batch, requested);
203 };
204 // A search result is keyed by what was typed, so the writes do not reach it on their own.
205 const refreshSearch =
206 hostQuery !== null && add.length + remove.length > 0 ? searchResult.refresh : null;
207 // Removing first lets a host that keeps one reviewer take the new one.
208 void send(remove, false)
209 .then(() => send(add, true))
210 .then(() => refreshSearch?.());
211 }),
212 [navigation, draft, latest, request, target, hostQuery, searchResult.refresh, gt],
213 );
214 const reviewerSearch: AppBarSearch | undefined = listCandidates
215 ? {
216 mode: "inline",
217 compactToolbar: true,
218 value: query,
219 onChangeText: search,
220 placeholder: gt("Search reviewers"),
221 }
222 : undefined;
223 const searchToolbarInset = useSearchToolbarInset(reviewerSearch);
224 return (
225 <View className="flex-1 bg-sheet">
226 <AppBar
227 title={gt("Request review")}
228 subtitle={`#${route.params.number} · ${route.params.repository}`}
229 onClose={() => navigation.goBack()}
230 closeAccessibilityLabel={gt("Close request review")}
231 search={reviewerSearch}
232 />
233 {listCandidates ? (
234 <LegendList
235 ref={listRef}
236 data={candidates}
237 keyExtractor={(candidate) => `${candidate.kind}:${candidate.id}`}
238 extraData={{ allowed, draft }}
239 estimatedItemSize={64}
240 recycleItems
241 renderScrollComponent={NativeScrollView}
242 contentInsetAdjustmentBehavior="automatic"
243 automaticallyAdjustKeyboardInsets
244 keyboardDismissMode="on-drag"
245 keyboardShouldPersistTaps="handled"
246 contentContainerStyle={{ paddingBottom: 24 + searchToolbarInset }}
247 ListHeaderComponent={
248 <View className="gap-3 px-4 py-4">
249 <Text className="text-xs text-foreground-muted">
250 <T>
251 Tap someone to request a review. Tap a requested reviewer to remove the request.
252 Changes are sent when you close this sheet.
253 </T>
254 </Text>
255 {!allowed ? (
256 <Text className="text-xs text-foreground-muted">
257 {gt(
258 "Requesting reviews requires write access and an open {term, select, mr {merge request} cr {change request} other {pull request}}.",
259 { term },
260 )}
261 </Text>
262 ) : null}
263 </View>
264 }
265 renderItem={({ item }) => {
266 const id = `${item.kind}:${item.id}`;
267 const requested = isSelected(draft, id, item.isRequested);
268 return (
269 <Pressable
270 accessibilityRole="button"
271 accessibilityLabel={
272 item.kind === "team"
273 ? requested
274 ? gt("Remove review request from {login} team", { login: item.login })
275 : gt("Request review from {login} team", { login: item.login })
276 : requested
277 ? gt("Remove review request from {login}", { login: item.login })
278 : gt("Request review from {login}", { login: item.login })
279 }
280 accessibilityState={{ disabled: !allowed }}
281 disabled={!allowed}
282 onPress={() =>
283 setDraft((current) => toggleSelection(current, id, item, item.isRequested))
284 }
285 className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70"
286 >
287 <PullRequestAvatar actor={item} size={32} />
288 <View className="min-w-0 flex-1 gap-0.5">
289 <Text className="text-sm font-t3-medium" numberOfLines={1}>
290 {item.name || item.login}
291 </Text>
292 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
293 {item.login}
294 {item.kind === "team" ? ` · ${gt("Team", { $context: "reviewer kind" })}` : ""}
295 </Text>
296 </View>
297 {requested ? (
298 <View className="flex-row items-center gap-1.5">
299 <Text className="text-xs text-foreground-muted">
300 <T context="reviewer state">Requested</T>
301 </Text>
302 <SymbolView name="checkmark" size={14} tintColorClassName="accent-icon" />
303 </View>
304 ) : (
305 <SymbolView name="plus" size={16} tintColorClassName="accent-icon-muted" />
306 )}
307 </Pressable>
308 );
309 }}
310 ListEmptyComponent={
311 (result.isPending && !result.data) || view.searchPending ? (
312 <AppActivityIndicator className="my-8" />
313 ) : (
314 <View className="px-4 py-6">
315 <EmptyState
316 title={
317 queryError
318 ? gt("Couldn't load reviewers")
319 : query.trim()
320 ? gt("No matching reviewers")
321 : gt("No reviewers available")
322 }
323 detail={
324 queryError ?? gt("Search people and teams with access to this repository.")
325 }
326 variant="plain"
327 />
328 {queryError ? (
329 <Button
330 label={gt("Retry")}
331 onPress={result.error ? result.refresh : searchResult.refresh}
332 />
333 ) : null}
334 </View>
335 )
336 }
337 ListFooterComponent={
338 view.truncation ? (
339 <Text className="px-4 py-4 text-xs text-foreground-muted">
340 {TRUNCATED_LABELS[view.truncation](view.searchError, m)}
341 </Text>
342 ) : undefined
343 }
344 />
345 ) : (
346 <ScrollView
347 contentInsetAdjustmentBehavior="automatic"
348 automaticallyAdjustKeyboardInsets
349 keyboardShouldPersistTaps="handled"
350 contentContainerStyle={{ padding: 16, gap: 16 }}
351 >
352 {!pr ? (
353 detail.isPending ? (
354 <AppActivityIndicator />
355 ) : (
356 <Text className="text-danger-foreground">
357 {detail.error ??
358 gt(
359 "Couldn't load this {term, select, mr {merge request} cr {change request} other {pull request}}.",
360 { term },
361 )}
362 </Text>
363 )
364 ) : (
365 <>
366 <Text className="text-sm text-foreground-muted">
367 <T>This provider accepts a reviewer ID but cannot list candidates.</T>
368 </Text>
369 <TextInput
370 accessibilityLabel={gt("Reviewer ID")}
371 placeholder={gt("Reviewer login or ID")}
372 placeholderTextColorClassName="accent-foreground-muted"
373 value={query}
374 onChangeText={search}
375 autoCapitalize="none"
376 autoCorrect={false}
377 className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
378 />
379 <Button
380 label={gt("Request review")}
381 fullWidth
382 disabled={!allowed || !query.trim() || pending !== null}
383 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: false })}
384 />
385 <Button
386 label={gt("Remove review request")}
387 fullWidth
388 tone="text"
389 disabled={!allowed || !query.trim() || pending !== null}
390 onPress={() => void update({ id: query.trim(), kind: "user", isRequested: true })}
391 />
392 {error ? (
393 <Text selectable className="text-danger-foreground">
394 {error}
395 </Text>
396 ) : null}
397 </>
398 )}
399 </ScrollView>
400 )}
401 </View>
402 );
403 }