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

IssueTrackerSection.tsx

299 lines11.1 KB

1import {
2 boundIssueTrackerScopes,
3 issueTrackerBindingFor,
4 issueTrackerScopeOptions,
5 issueTrackerSummary,
6} from "@t3tools/client-runtime/state/issue-trackers";
7import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import type {
9 EnvironmentId,
10 IssueTrackerConnection,
11 IssueTrackerConnectionList,
12 ProjectId,
13} from "@t3tools/contracts";
14import { AsyncResult } from "effect/reactivity";
15import { useNavigation } from "@react-navigation/native";
16import { useGT, useMessages } from "gt-react-native";
17import { useState } from "react";
18import { Platform, View } from "react-native";
19import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
20import Svg, { Path } from "react-native-svg";
21import { withUniwind } from "uniwind";
22​
23import { SymbolView } from "../../../components/ui/AppSymbol";
24import { AppText as Text } from "../../../components/ui/AppText";
25import { Button } from "../../../components/ui/Button";
26import { Menu } from "../../../components/ui/Menu";
27import { SecretTextInput } from "../../../components/ui/SecretTextInput";
28import { useProjects } from "../../../state/entities";
29import { issueTrackerEnvironment } from "../../../state/issueTrackers";
30import { useEnvironmentQuery } from "../../../state/query";
31import { useAtomCommand } from "../../../state/use-atom-command";
32import type { SettingsTarget } from "../settings-environment-filter";
33import { SettingsProviderRow } from "./SettingsProviderRow";
34import { SettingsRow } from "./SettingsRow";
35import { SettingsSection } from "./SettingsSection";
36​
37const UNBOUND = "";
38const ThemedSvg = withUniwind(Svg);
39const ICON_SIZE = Platform.OS === "android" ? 20 : 18;
40​
41/** Art per tracker kind; the server supplies everything else about a tracker. */
42const TRACKER_MARKS: Partial<Record<string, string>> = {
43 linear:
44 "M1.225 61.523c-.222-.949.908-1.546 1.597-.857l36.512 36.512c.69.69.092 1.82-.857 1.597C20.15 94.612 5.388 79.85 1.225 61.523ZM.002 46.889a.99.99 0 0 0 .29.76l52.062 52.061a.99.99 0 0 0 .76.29c2.765-.169 5.47-.559 8.1-1.152.75-.169 1.014-1.084.47-1.63L2.784 38.32c-.545-.545-1.46-.28-1.63.47A50.229 50.229 0 0 0 .002 46.89ZM4.472 29.34a.99.99 0 0 0 .208 1.104l64.878 64.877a.99.99 0 0 0 1.104.208 50.293 50.293 0 0 0 5.807-3.132.99.99 0 0 0 .154-1.53L9.135 23.38a.99.99 0 0 0-1.53.154 50.29 50.29 0 0 0-3.132 5.807ZM12.293 18.229c-.309-.309-.334-.803-.045-1.13C21.376 6.626 34.637 0 49.45 0 76.869 0 99.1 22.231 99.1 49.65c0 14.813-6.626 28.074-17.099 37.202-.327.29-.821.264-1.13-.045L12.293 18.23Z",
45};
46​
47/**
48 * Standalone issue trackers, such as Linear, for each selected environment: connect one with a
49 * credential, then pick which of its scopes each project lists beside its repository's issues.
50 */
51export function IssueTrackerSection(props: { readonly environments: readonly SettingsTarget[] }) {
52 const gt = useGT();
53 return (
54 <>
55 {props.environments.map((environment) =>
56 environment.serverConfig.environment.capabilities.issues === true ? (
57 <EnvironmentTrackers
58 key={environment.environmentId}
59 environment={environment}
60 title={
61 props.environments.length > 1
62 ? gt("Issue trackers · {environment}", { environment: environment.label })
63 : gt("Issue trackers")
64 }
65 />
66 ) : null,
67 )}
68 </>
69 );
71​
72function EnvironmentTrackers(props: {
73 readonly environment: SettingsTarget;
74 readonly title: string;
75}) {
76 const gt = useGT();
77 const messages = useMessages();
78 const navigation = useNavigation();
79 const { environmentId } = props.environment;
80 const query = useEnvironmentQuery(
81 issueTrackerEnvironment.connections({ environmentId, input: {} }),
82 );
83 const trackers = query.data?.trackers ?? [];
84 if (trackers.length === 0) {
85 return query.error ? (
86 <SettingsSection title={props.title} footer={query.error}>
87 <View className="p-4">
88 <Button label={gt("Try again")} tone="secondary" onPress={query.refresh} />
89 </View>
90 </SettingsSection>
91 ) : null;
92 }
93 return (
94 <SettingsSection title={props.title}>
95 {trackers.map((tracker, index) => (
96 <SettingsProviderRow
97 key={tracker.tracker}
98 icon={<IssueTrackerMark tracker={tracker.tracker} />}
99 label={tracker.displayName}
100 description={issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)}
101 ready={tracker.connected && tracker.account !== null}
102 separated={index > 0}
103 onPress={() =>
104 navigation.navigate("SettingsIssueTracker", {
105 environmentId,
106 tracker: tracker.tracker,
107 })
108 }
109 />
110 ))}
111 </SettingsSection>
112 );
114​
115export function IssueTrackerMark(props: { readonly tracker: string }) {
116 const mark = TRACKER_MARKS[props.tracker];
117 return mark ? (
118 <ThemedSvg
119 width={ICON_SIZE}
120 height={ICON_SIZE}
121 viewBox="0 0 100 100"
122 colorClassName="accent-icon"
123 >
124 <Path fill="currentColor" d={mark} />
125 </ThemedSvg>
126 ) : (
127 <SymbolView name="circle.dashed" size={ICON_SIZE} tintColorClassName="accent-icon" />
128 );
130​
131/** The credential field for one tracker, with what replaces, removes or creates it. */
132export function IssueTrackerCredentialForm(props: {
133 readonly environmentId: EnvironmentId;
134 readonly tracker: IssueTrackerConnection;
135 readonly disabled: boolean;
136}) {
137 const gt = useGT();
138 const { environmentId, tracker } = props;
139 const connect = useAtomCommand(issueTrackerEnvironment.connect, { reportFailure: false });
140 const [draft, setDraft] = useState("");
141 const [busy, setBusy] = useState(false);
142 const [failure, setFailure] = useState<string | null>(null);
143 const submit = async (token: string | null) => {
144 setBusy(true);
145 setFailure(null);
146 const result = await connect({ environmentId, input: { tracker: tracker.tracker, token } });
147 setBusy(false);
148 if (!AsyncResult.isFailure(result)) {
149 setDraft("");
150 return;
151 }
152 const error = squashAtomCommandFailure(result);
153 setFailure(error instanceof Error ? error.message : gt("The request failed."));
154 };
155 const helpUrl = tracker.credential.helpUrl;
156 const locked = props.disabled || busy;
157 return (
158 <View className="gap-3 p-4">
159 <SecretTextInput
160 accessibilityLabel={tracker.credential.label}
161 placeholder={
162 tracker.connected
163 ? gt("Saved. Enter a new value to replace it")
164 : tracker.credential.label
165 }
166 value={draft}
167 onChangeText={setDraft}
168 onSubmitEditing={(value) => {
169 if (value.trim()) void submit(value.trim());
170 }}
171 editable={!locked}
172 />
173 {failure ? (
174 <Text selectable className="text-xs text-danger-foreground">
175 {failure}
176 </Text>
177 ) : null}
178 <View className="flex-row flex-wrap justify-end gap-2">
179 {helpUrl ? (
180 <Button
181 label={gt("Create one")}
182 tone="text"
183 size="compact"
184 onPress={() => void tryOpenExternalUrl(helpUrl)}
185 />
186 ) : null}
187 {tracker.connected ? (
188 <Button
189 label={gt("Disconnect")}
190 tone="secondary"
191 size="compact"
192 disabled={locked}
193 onPress={() => void submit(null)}
194 />
195 ) : null}
196 <Button
197 label={
198 tracker.connected
199 ? gt("Replace", { $context: "verb, replaces a saved credential" })
200 : gt("Connect", { $context: "verb, connects an issue tracker" })
201 }
202 tone="primary"
203 size="compact"
204 loading={busy}
205 disabled={locked || !draft.trim()}
206 onPress={() => void submit(draft.trim())}
207 />
208 </View>
209 </View>
210 );
212​
213/** One row per project of the environment: which of the tracker's scopes it reads, if any. */
214export function IssueTrackerProjectRows(props: {
215 readonly environmentId: EnvironmentId;
216 readonly tracker: IssueTrackerConnection;
217 readonly bindings: IssueTrackerConnectionList["bindings"];
218 readonly refreshing: boolean;
219 readonly refreshFailed: boolean;
220 readonly disabled: boolean;
221}) {
222 const gt = useGT();
223 const { environmentId, tracker } = props;
224 const bind = useAtomCommand(issueTrackerEnvironment.bindProject, {
225 label: `bind project to ${tracker.displayName}`,
226 });
227 const projects = useProjects().filter((project) => project.environmentId === environmentId);
228 const [picks, setPicks] = useState<Partial<Record<ProjectId, ReadonlyArray<string>>>>({});
229 const [saving, setSaving] = useState(false);
230 const held = Object.values(picks).some((scopes) => scopes !== undefined);
231 if (held && !saving && !props.refreshing && !props.refreshFailed) setPicks({});
232 const busy = saving || (held && props.refreshing);
233 const bound = (projectId: ProjectId) =>
234 picks[projectId] ?? boundIssueTrackerScopes(tracker.tracker, props.bindings[projectId]);
235 const change = async (projectId: ProjectId, scopes: ReadonlyArray<string>) => {
236 if (props.disabled || busy) return;
237 const binding = issueTrackerBindingFor(tracker.tracker, bound(projectId), scopes);
238 const before = picks[projectId];
239 setSaving(true);
240 setPicks((current) => ({
241 ...current,
242 [projectId]: boundIssueTrackerScopes(tracker.tracker, binding ?? undefined),
243 }));
244 const result = await bind({ environmentId, input: { projectId, binding } });
245 if (result._tag !== "Success") setPicks((current) => ({ ...current, [projectId]: before }));
246 setSaving(false);
247 };
248 return projects.map((project) => {
249 // A project bound to another tracker keeps that binding; this row shows it unbound.
250 const value = bound(project.id);
251 const options = issueTrackerScopeOptions(tracker, value);
252 const toggle = (key: string) =>
253 key === UNBOUND
254 ? []
255 : value.includes(key)
256 ? value.filter((scope) => scope !== key)
257 : [...value, key];
258 const locked = props.disabled || busy;
259 return (
260 <Menu
261 key={project.id}
262 title={gt("{tracker} {scope} for {project}", {
263 tracker: tracker.displayName,
264 scope: tracker.scopeNoun,
265 project: project.title,
266 })}
267 actions={[
268 {
269 id: UNBOUND,
270 title: gt("Not bound"),
271 state: value.length === 0 ? "on" : "off",
272 attributes: { disabled: locked },
273 },
274 ...options.map((scope) => ({
275 id: scope.key,
276 title: `${scope.name} (${scope.key})`,
277 state: value.includes(scope.key) ? ("on" as const) : ("off" as const),
278 attributes: { disabled: locked || !scope.addable },
279 })),
280 ]}
281 onPressAction={({ nativeEvent }) => void change(project.id, toggle(nativeEvent.event))}
282 >
283 <SettingsRow
284 icon="folder"
285 label={project.title}
286 valuePosition="trailing"
287 value={
288 value.length === 0
289 ? gt("Not bound")
290 : value
291 .map((key) => tracker.scopes.find((scope) => scope.key === key)?.name ?? key)
292 .join(", ")
293 }
294 disabled={locked}
295 />
296 </Menu>
297 );
298 });