Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { StaticScreenProps } from "@react-navigation/native";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import type { PullRequestLabelCandidate } from "@t3tools/contracts";
5import { AsyncResult } from "effect/reactivity";
6import { useRef, useState } from "react";
7import { FlatList, Platform, View } from "react-native";
8import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
9import { AppText as Text } from "../../components/ui/AppText";
10import { Button } from "../../components/ui/Button";
11import { EmptyState } from "../../components/ui/EmptyState";
12import { SelectionRow } from "../../components/ui/SelectionRow";
13import { composerPullRequests } from "../../state/pull-requests";
14import { useEnvironmentQuery } from "../../state/query";
15import { useAtomCommand } from "../../state/use-atom-command";
16import { PullRequestLabelDot } from "./PullRequestLabelDot";
17import { pullRequestLabelColor } from "./pullRequestList";
18import { PullRequestSearchSheet } from "./PullRequestSearchSheet";
19import { usePullRequestConnected } from "./usePullRequestConnected";
20import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
21
22export function PullRequestLabelsScreen({ route }: StaticScreenProps<PullRequestParams>) {
23 const target = pullRequestTarget(route.params);
24 const pr = useEnvironmentQuery(composerPullRequests.detail(target)).data;
25 const canWrite = useAtomValue(
26 composerPullRequests.setLabels.permissionAtom(target.environmentId),
27 );
28 const connected = usePullRequestConnected(route.params.environmentId);
29 const allowed =
30 connected &&
31 canWrite &&
32 pr?.capabilities.labels === true &&
33 pr.viewerPermissions.labels !== false;
34 // Name the first thing in the way, so the notice says what would actually fix it.
35 const readOnlyReason =
36 !pr || allowed
37 ? null
38 : !connected
39 ? "Reconnect to change labels."
40 : !canWrite
41 ? "This device isn't allowed to change source control on this environment."
42 : pr.capabilities.labels !== true
43 ? "This provider doesn't support changing labels."
44 : "Changing labels needs triage access on this repository.";
45 const result = useEnvironmentQuery(composerPullRequests.labelCandidates(target));
46 const setLabels = useAtomCommand(composerPullRequests.setLabels, { reportFailure: false });
47 const [query, setQuery] = useState("");
48 const [pending, setPending] = useState<{ readonly name: string; readonly applied: boolean }>();
49 const [error, setError] = useState<string | null>(null);
50 const inFlight = useRef(false);
51 const needle = query.trim().toLowerCase();
52 // Host order, not applied-first: re-sorting on toggle would move the row out from under a tap.
53 const candidates = (result.data?.candidates ?? []).filter((candidate) =>
54 `${candidate.name} ${candidate.description ?? ""}`.toLowerCase().includes(needle),
55 );
56 const toggle = async (candidate: PullRequestLabelCandidate) => {
57 if (!allowed || inFlight.current) return;
58 inFlight.current = true;
59 setPending({ name: candidate.name, applied: !candidate.isApplied });
60 setError(null);
61 const response = await setLabels({
62 ...target,
63 input: { ...target.input, labels: [candidate.name], applied: !candidate.isApplied },
64 });
65 inFlight.current = false;
66 setPending(undefined);
67 if (AsyncResult.isFailure(response)) {
68 const cause = squashAtomCommandFailure(response);
69 setError(cause instanceof Error ? cause.message : "Couldn't update this label. Try again.");
70 }
71 };
72 return (
73 <PullRequestSearchSheet
74 title="Labels"
75 placeholder="Search labels"
76 closeAccessibilityLabel="Close labels"
77 clearAccessibilityLabel="Clear label search"
78 searchTextChangeId="pr-label-search"
79 query={query}
80 onQueryChange={setQuery}
81 >
82 {({ paddingBottom }) => (
83 <FlatList
84 data={candidates}
85 keyExtractor={(candidate) => candidate.name}
86 className="flex-1"
87 contentInsetAdjustmentBehavior="automatic"
88 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
89 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
90 keyboardShouldPersistTaps="handled"
91 showsVerticalScrollIndicator={false}
92 contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }}
93 ListHeaderComponent={
94 readOnlyReason || error ? (
95 <View className="gap-2 pb-3">
96 {readOnlyReason ? (
97 <Text className="text-xs text-foreground-muted">{readOnlyReason}</Text>
98 ) : null}
99 {error ? (
100 <Text selectable className="text-sm text-danger-foreground">
101 {error}
102 </Text>
103 ) : null}
104 </View>
105 ) : undefined
106 }
107 renderItem={({ item, index }) => (
108 <SelectionRow
109 title={item.name}
110 {...(item.description ? { subtitle: item.description } : {})}
111 role="checkbox"
112 // The change shows as soon as it is tapped; a failure puts the host's answer back.
113 selected={pending?.name === item.name ? pending.applied : item.isApplied}
114 disabled={!allowed}
115 isFirst={index === 0}
116 isLast={index === candidates.length - 1}
117 leading={<PullRequestLabelDot color={pullRequestLabelColor(item.color)} />}
118 onPress={() => void toggle(item)}
119 />
120 )}
121 ListEmptyComponent={
122 result.isPending && !result.data ? (
123 <AppActivityIndicator className="my-8" />
124 ) : (
125 <View>
126 <EmptyState
127 title={
128 result.error
129 ? "Couldn't load labels"
130 : needle
131 ? "No matching labels"
132 : "This repository has no labels"
133 }
134 detail={
135 result.error ??
136 (needle
137 ? "Try another name."
138 : "Create labels on the provider to use them here.")
139 }
140 variant="plain"
141 />
142 {result.error ? <Button label="Retry" onPress={result.refresh} /> : null}
143 </View>
144 )
145 }
146 ListFooterComponent={
147 result.data?.truncated ? (
148 <Text className="py-4 text-xs text-foreground-muted">
149 This repository has more labels than are listed here. Apply the rest on the
150 provider.
151 </Text>
152 ) : undefined
153 }
154 />
155 )}
156 </PullRequestSearchSheet>
157 );
158}