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