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

PullRequestLabelsScreen.tsx

157 lines6.8 KB

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 query={query}
79 onQueryChange={setQuery}
80 >
81 {({ paddingBottom }) => (
82 <FlatList
83 data={candidates}
84 keyExtractor={(candidate) => candidate.name}
85 className="flex-1"
86 contentInsetAdjustmentBehavior="automatic"
87 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
88 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
89 keyboardShouldPersistTaps="handled"
90 showsVerticalScrollIndicator={false}
91 contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }}
92 ListHeaderComponent={
93 readOnlyReason || error ? (
94 <View className="gap-2 pb-3">
95 {readOnlyReason ? (
96 <Text className="text-xs text-foreground-muted">{readOnlyReason}</Text>
97 ) : null}
98 {error ? (
99 <Text selectable className="text-sm text-danger-foreground">
100 {error}
101 </Text>
102 ) : null}
103 </View>
104 ) : undefined
105 }
106 renderItem={({ item, index }) => (
107 <SelectionRow
108 title={item.name}
109 {...(item.description ? { subtitle: item.description } : {})}
110 role="checkbox"
111 // The change shows as soon as it is tapped; a failure puts the host's answer back.
112 selected={pending?.name === item.name ? pending.applied : item.isApplied}
113 disabled={!allowed}
114 isFirst={index === 0}
115 isLast={index === candidates.length - 1}
116 leading={<PullRequestLabelDot color={pullRequestLabelColor(item.color)} />}
117 onPress={() => void toggle(item)}
118 />
119 )}
120 ListEmptyComponent={
121 result.isPending && !result.data ? (
122 <AppActivityIndicator className="my-8" />
123 ) : (
124 <View>
125 <EmptyState
126 title={
127 result.error
128 ? "Couldn't load labels"
129 : needle
130 ? "No matching labels"
131 : "This repository has no labels"
132 }
133 detail={
134 result.error ??
135 (needle
136 ? "Try another name."
137 : "Create labels on the provider to use them here.")
138 }
139 variant="plain"
140 />
141 {result.error ? <Button label="Retry" onPress={result.refresh} /> : null}
142 </View>
143 )
144 }
145 ListFooterComponent={
146 result.data?.truncated ? (
147 <Text className="py-4 text-xs text-foreground-muted">
148 This repository has more labels than are listed here. Apply the rest on the
149 provider.
150 </Text>
151 ) : undefined
152 }
153 />
154 )}
155 </PullRequestSearchSheet>
156 );