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

IssueTrackerSection.tsx

351 lines13.3 KB

1import {
2 boundIssueTrackerScopes,
3 issueTrackerBindInput,
4 issueTrackerBindingFor,
5 issueTrackerBindings,
6 issueTrackerConnectFailure,
7 issueTrackerScopeOptions,
8 issueTrackerSummary,
9} from "@t3tools/client-runtime/state/issue-trackers";
10import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
11import type {
12 EnvironmentId,
13 IssueTrackerConnection,
14 IssueTrackerConnectionList,
15 ProjectId,
16} from "@t3tools/contracts";
17import { AsyncResult } from "effect/reactivity";
18import { useNavigation } from "@react-navigation/native";
19import { useGT, useMessages } from "gt-react-native";
20import { useState } from "react";
21import { Platform, View } from "react-native";
22import { tryOpenExternalUrl } from "../../../lib/openExternalUrl";
23import Svg, { Path } from "react-native-svg";
24import { withUniwind } from "uniwind";
25​
26import { SymbolView } from "../../../components/ui/AppSymbol";
27import { AppText as Text } from "../../../components/ui/AppText";
28import { Button } from "../../../components/ui/Button";
29import { Menu } from "../../../components/ui/Menu";
30import { SecretTextInput } from "../../../components/ui/SecretTextInput";
31import { useProjects } from "../../../state/entities";
32import { issueTrackerEnvironment } from "../../../state/issueTrackers";
33import { useEnvironmentQuery } from "../../../state/query";
34import { useAtomCommand } from "../../../state/use-atom-command";
35import { ConnectionFormField } from "../../connection/ConnectionFormField";
36import type { SettingsTarget } from "../settings-environment-filter";
37import { SettingsProviderRow } from "./SettingsProviderRow";
38import { SettingsRow } from "./SettingsRow";
39import { SettingsSection } from "./SettingsSection";
40​
41const UNBOUND = "";
42const ThemedSvg = withUniwind(Svg);
43const ICON_SIZE = Platform.OS === "android" ? 20 : 18;
44​
45/** Art per tracker kind; the server supplies everything else about a tracker. */
46const TRACKER_MARKS: Partial<Record<string, { readonly box: number; readonly path: string }>> = {
47 jira: {
48 box: 24,
49 path: "M11.571 11.513H0a5.218 5.218 0 0 0 5.232 5.215h2.13v2.057A5.215 5.215 0 0 0 12.575 24V12.518a1.005 1.005 0 0 0-1.005-1.005zm5.723-5.756H5.736a5.215 5.215 0 0 0 5.215 5.214h2.129v2.058a5.218 5.218 0 0 0 5.215 5.214V6.758a1.001 1.001 0 0 0-1.001-1.001zM23.013 0H11.455a5.215 5.215 0 0 0 5.215 5.215h2.129v2.057A5.215 5.215 0 0 0 24 12.483V1.005A1.001 1.001 0 0 0 23.013 0Z",
50 },
51 linear: {
52 box: 100,
53 path: "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",
54 },
55};
56​
57/**
58 * Standalone issue trackers, such as Linear, for each selected environment: connect one with a
59 * credential, then pick which of its scopes each project lists beside its repository's issues.
60 */
61export function IssueTrackerSection(props: { readonly environments: readonly SettingsTarget[] }) {
62 const gt = useGT();
63 return (
64 <>
65 {props.environments.map((environment) =>
66 environment.serverConfig.environment.capabilities.issues === true ? (
67 <EnvironmentTrackers
68 key={environment.environmentId}
69 environment={environment}
70 title={
71 props.environments.length > 1
72 ? gt`Issue trackers · ${{ environment: environment.label }}`
73 : gt`Issue trackers`
74 }
75 />
76 ) : null,
77 )}
78 </>
79 );
81​
82function EnvironmentTrackers(props: {
83 readonly environment: SettingsTarget;
84 readonly title: string;
85}) {
86 const gt = useGT();
87 const messages = useMessages();
88 const navigation = useNavigation();
89 const { environmentId } = props.environment;
90 const query = useEnvironmentQuery(
91 issueTrackerEnvironment.connections({ environmentId, input: {} }),
92 );
93 const firstAccounts = query.data?.trackers ?? [];
94 const trackers = firstAccounts.flatMap((tracker) => [
95 tracker,
96 ...(query.data?.accounts ?? []).filter((account) => account.tracker === tracker.tracker),
97 ]);
98 if (trackers.length === 0) {
99 return query.error ? (
100 <SettingsSection title={props.title} footer={query.error}>
101 <View className="p-4">
102 <Button label={gt`Try again`} tone="secondary" onPress={query.refresh} />
103 </View>
104 </SettingsSection>
105 ) : null;
106 }
107 return (
108 <SettingsSection title={props.title}>
109 {trackers.map((tracker, index) => (
110 <SettingsProviderRow
111 key={`${tracker.tracker}-${tracker.accountId ?? ""}`}
112 icon={<IssueTrackerMark tracker={tracker.tracker} />}
113 label={
114 tracker.workspace
115 ? `${tracker.displayName} · ${tracker.workspace}`
116 : tracker.displayName
117 }
118 description={issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)}
119 ready={tracker.connected && tracker.account !== null}
120 separated={index > 0}
121 onPress={() =>
122 navigation.navigate("SettingsIssueTracker", {
123 environmentId,
124 tracker: tracker.tracker,
125 ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }),
126 })
127 }
128 />
129 ))}
130 </SettingsSection>
131 );
133​
134export function IssueTrackerMark(props: { readonly tracker: string }) {
135 const mark = TRACKER_MARKS[props.tracker];
136 return mark ? (
137 <ThemedSvg
138 width={ICON_SIZE}
139 height={ICON_SIZE}
140 viewBox={`0 0 ${mark.box} ${mark.box}`}
141 colorClassName="accent-icon"
142 >
143 <Path fill="currentColor" d={mark.path} />
144 </ThemedSvg>
145 ) : (
146 <SymbolView name="circle.dashed" size={ICON_SIZE} tintColorClassName="accent-icon" />
147 );
149​
150/** The credential field for one tracker, with what replaces, removes or creates it. */
151export function IssueTrackerCredentialForm(props: {
152 readonly environmentId: EnvironmentId;
153 readonly tracker: IssueTrackerConnection;
154 readonly disabled: boolean;
155 /** Saves the credential as a new account instead of replacing this one's. */
156 readonly addAccount?: boolean;
157}) {
158 const gt = useGT();
159 const { environmentId, tracker } = props;
160 const connect = useAtomCommand(issueTrackerEnvironment.connect, { reportFailure: false });
161 const [draft, setDraft] = useState("");
162 const fields = tracker.credential.fields ?? [];
163 const [drafts, setDrafts] = useState<Readonly<Record<string, string>>>(
164 props.addAccount ? {} : (tracker.fields ?? {}),
165 );
166 const [busy, setBusy] = useState(false);
167 const [failure, setFailure] = useState<string | null>(null);
168 const complete = fields.every((field) => drafts[field.key]?.trim());
169 const submit = async (token: string | null) => {
170 if (token !== null && !complete) return;
171 setBusy(true);
172 setFailure(null);
173 const result = await connect({
174 environmentId,
175 input: {
176 tracker: tracker.tracker,
177 token,
178 ...(props.addAccount ? { addAccount: true } : { accountId: tracker.accountId }),
179 ...(token === null || fields.length === 0
180 ? {}
181 : {
182 fields: Object.fromEntries(
183 fields.map((field) => [field.key, drafts[field.key]!.trim()]),
184 ),
185 }),
186 },
187 });
188 setBusy(false);
189 if (!AsyncResult.isFailure(result)) {
190 setDraft("");
191 if (props.addAccount) setDrafts({});
192 return;
193 }
194 const error = squashAtomCommandFailure(result);
195 setFailure(issueTrackerConnectFailure(error) ?? gt`The request failed.`);
196 };
197 const helpUrl = tracker.credential.helpUrl;
198 const locked = props.disabled || busy;
199 const replacing = tracker.connected && !props.addAccount;
200 return (
201 <View className="gap-3 p-4">
202 {fields.map((field) => (
203 <ConnectionFormField
204 key={field.key}
205 label={field.label}
206 autoCapitalize="none"
207 autoCorrect={false}
208 placeholder={field.placeholder ?? field.label}
209 editable={!locked}
210 value={drafts[field.key] ?? ""}
211 onChangeText={(value) => setDrafts({ ...drafts, [field.key]: value })}
212 />
213 ))}
214 <SecretTextInput
215 accessibilityLabel={tracker.credential.label}
216 placeholder={
217 replacing ? gt`Saved. Enter a new value to replace it` : tracker.credential.label
218 }
219 value={draft}
220 onChangeText={setDraft}
221 onSubmitEditing={(value) => {
222 if (value.trim()) void submit(value.trim());
223 }}
224 editable={!locked}
225 />
226 {failure ? (
227 <Text selectable className="text-xs text-danger-foreground">
228 {failure}
229 </Text>
230 ) : null}
231 <View className="flex-row flex-wrap justify-end gap-2">
232 {helpUrl ? (
233 <Button
234 label={gt`Create one`}
235 tone="text"
236 size="compact"
237 onPress={() => void tryOpenExternalUrl(helpUrl)}
238 />
239 ) : null}
240 {replacing ? (
241 <Button
242 label={gt`Disconnect`}
243 tone="secondary"
244 size="compact"
245 disabled={locked}
246 onPress={() => void submit(null)}
247 />
248 ) : null}
249 <Button
250 label={
251 replacing
252 ? gt({ context: "verb, replaces a saved credential" })`Replace`
253 : gt({ context: "verb, connects an issue tracker" })`Connect`
254 }
255 tone="primary"
256 size="compact"
257 loading={busy}
258 disabled={locked || !draft.trim() || !complete}
259 onPress={() => void submit(draft.trim())}
260 />
261 </View>
262 </View>
263 );
265​
266/** One row per project of the environment: which of the tracker's scopes it reads, if any. */
267export function IssueTrackerProjectRows(props: {
268 readonly environmentId: EnvironmentId;
269 readonly tracker: IssueTrackerConnection;
270 readonly bindings: IssueTrackerConnectionList["bindings"];
271 readonly refreshing: boolean;
272 readonly refreshFailed: boolean;
273 readonly disabled: boolean;
274}) {
275 const gt = useGT();
276 const { environmentId, tracker } = props;
277 const bind = useAtomCommand(issueTrackerEnvironment.bindProject, {
278 label: `bind project to ${tracker.displayName}`,
279 });
280 const projects = useProjects().filter((project) => project.environmentId === environmentId);
281 const [picks, setPicks] = useState<Partial<Record<ProjectId, ReadonlyArray<string>>>>({});
282 const [saving, setSaving] = useState(false);
283 const held = Object.values(picks).some((scopes) => scopes !== undefined);
284 if (held && !saving && !props.refreshing && !props.refreshFailed) setPicks({});
285 const busy = saving || (held && props.refreshing);
286 const bound = (projectId: ProjectId) =>
287 picks[projectId] ?? boundIssueTrackerScopes(tracker, props.bindings[projectId]);
288 const change = async (projectId: ProjectId, scopes: ReadonlyArray<string>) => {
289 if (props.disabled || busy) return;
290 const binding = issueTrackerBindingFor(tracker, bound(projectId), scopes);
291 const before = picks[projectId];
292 setSaving(true);
293 setPicks((current) => ({
294 ...current,
295 [projectId]: boundIssueTrackerScopes(tracker, binding ?? undefined),
296 }));
297 const result = await bind({
298 environmentId,
299 input: issueTrackerBindInput(projectId, tracker, binding),
300 });
301 if (result._tag !== "Success") setPicks((current) => ({ ...current, [projectId]: before }));
302 setSaving(false);
303 };
304 return projects.map((project) => {
305 // A project bound to another tracker or account keeps that binding; this row shows it unbound.
306 const value = bound(project.id);
307 const options = issueTrackerScopeOptions(tracker, value);
308 const toggle = (key: string) =>
309 key === UNBOUND
310 ? []
311 : value.includes(key)
312 ? value.filter((scope) => scope !== key)
313 : [...value, key];
314 const locked = props.disabled || busy;
315 return (
316 <Menu
317 key={project.id}
318 title={gt`${{ tracker: tracker.displayName }} ${{ scope: tracker.scopeNoun }} for ${{ project: project.title }}`}
319 actions={[
320 {
321 id: UNBOUND,
322 title: gt`Not bound`,
323 state: value.length === 0 ? "on" : "off",
324 attributes: { disabled: locked },
325 },
326 ...options.map((scope) => ({
327 id: scope.key,
328 title: `${scope.name} (${scope.key})`,
329 state: value.includes(scope.key) ? ("on" as const) : ("off" as const),
330 attributes: { disabled: locked || !scope.addable },
331 })),
332 ]}
333 onPressAction={({ nativeEvent }) => void change(project.id, toggle(nativeEvent.event))}
334 >
335 <SettingsRow
336 icon="folder"
337 label={project.title}
338 valuePosition="trailing"
339 value={
340 value.length === 0
341 ? gt`Not bound`
342 : value
343 .map((key) => tracker.scopes.find((scope) => scope.key === key)?.name ?? key)
344 .join(", ")
345 }
346 disabled={locked}
347 />
348 </Menu>
349 );
350 });