Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
320 linesCodeBlameRaw
1import { useState } from "react";
2import { Form, data, redirect } from "react-router";
3
4import {
5 MAX_ASSIGNED,
6 REVIEW_ALGORITHM_LABELS,
7 REVIEW_ALGORITHM_SUMMARIES,
8 TEAM_VISIBILITY_SUMMARIES,
9 type ReviewAlgorithm,
10 type TeamVisibility,
11} from "@g1t/contracts";
12
13import type { Route } from "./+types/settings";
14import { ConfirmDialog } from "../../../components/repo-lifecycle";
15import { useTeam } from "../../../components/teams";
16import { Coming } from "../../../components/people";
17import { SelectField } from "../../../components/ui/select";
18import { ErrorText, Field, Input, SubmitButton } from "../../../components/ui";
19import { Button } from "../../../components/ui/button";
20import { Card } from "../../../components/ui/card";
21import { Input as NumberInput } from "../../../components/ui/input";
22import { Textarea } from "../../../components/ui/textarea";
23import { CheckboxOption } from "../../../components/ui/checkbox";
24import { RadioGroup, RadioOption } from "../../../components/ui/radio-group";
25import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../components/ui/select";
26import { SwitchCard } from "../../../components/ui/switch";
27import { parentChoices, reviewAssignmentFromForm, teamChangesFromForm, teamPath } from "../../../lib/teams";
28import { chat, identity } from "../../../lib/services.server";
29import { assertSameOrigin, getViewer, requireUser, roleIn, unwrap } from "../../../lib/session.server";
30
31/** The parent select's value for "no parent". */
32const NO_PARENT = "-";
33/** The lead select's value for no lead. */
34const NO_LEAD = "none";
35
36/**
37 * Its lead and channel. The lead is a person on the team; a channel is
38 * found by its name in Chat, as the viewer sees it.
39 */
40async function saveLeadChannel(form: FormData, workspace: string, slug: string, user: Parameters<typeof identity.updateTeam>[0]) {
41 const intent = "people";
42 const lead = String(form.get("lead") ?? NO_LEAD);
43 const channel = String(form.get("channel") ?? "").trim().replace(/^#/, "").toLowerCase();
44 if (lead !== NO_LEAD && !lead.startsWith("@")) return { intent, error: "Choose someone on the team.", saved: false };
45 let channelId = "";
46 let channelName = "";
47 if (channel) {
48 const found = await chat.channelByName(workspace, channel, user).catch(() => null);
49 if (!found?.ok || found.value.channel.kind !== "channel") return { intent, error: `There is no channel #${channel} you can see.`, saved: false };
50 channelId = found.value.channel.id;
51 channelName = found.value.channel.name ?? channel;
52 }
53 const saved = await identity.updateTeam(user, workspace, slug, {
54 lead: lead === NO_LEAD ? "" : lead,
55 channel_id: channelId,
56 channel_name: channelName,
57 });
58 return saved.ok ? { intent, error: null, saved: true } : { intent, error: saved.error.message, saved: false };
59}
60
61export async function loader({ params, context }: Route.LoaderArgs) {
62 const viewer = getViewer(context);
63 if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 });
64 const team = unwrap(await identity.getTeam(viewer, params.owner, params.team));
65 if (!team.can_manage) throw data(null, { status: 404 });
66 const [all, members] = await Promise.all([
67 identity.listTeams(viewer, params.owner).then((found) => (found.ok ? found.value : [])),
68 // Who can lead it: its own people.
69 identity.teamMembers(viewer, params.owner, params.team, false).then((found) => (found.ok ? found.value : [])),
70 ]);
71 const parents = parentChoices(all, team.slug).filter((other) => other.can_manage || other.slug === team.parent?.slug);
72 return { parents, people: members.map((member) => ({ username: member.username, name: member.name })) };
73}
74
75export async function action({ request, params, context }: Route.ActionArgs) {
76 assertSameOrigin(request);
77 const user = requireUser(context, request);
78 const form = await request.formData();
79 const intent = String(form.get("intent") ?? "");
80 if (intent === "delete") {
81 const deleted = await identity.deleteTeam(user, params.owner, params.team);
82 if (!deleted.ok) return { intent, error: deleted.error.message, saved: false };
83 throw redirect(`/${params.owner}/-/teams`);
84 }
85 if (intent === "review") {
86 const current = unwrap(await identity.getTeam(user, params.owner, params.team));
87 const review = reviewAssignmentFromForm(form, current.review_assignment);
88 const saved = await identity.updateTeam(user, params.owner, params.team, { review_assignment: review });
89 return saved.ok ? { intent, error: null, saved: true } : { intent, error: saved.error.message, saved: false };
90 }
91 if (intent === "people") return saveLeadChannel(form, params.owner, params.team, user);
92 const changes = teamChangesFromForm(form);
93 if (changes.parent === NO_PARENT) changes.parent = "";
94 const saved = await identity.updateTeam(user, params.owner, params.team, changes);
95 if (!saved.ok) return { intent, error: saved.error.message, saved: false };
96 // A new slug is a new address.
97 if (saved.value.slug !== params.team) throw redirect(teamPath(saved.value.workspace, saved.value.slug, "settings"));
98 return { intent, error: null, saved: true };
99}
100
101export default function TeamSettings({ loaderData, actionData }: Route.ComponentProps) {
102 const team = useTeam();
103 const { parents, people } = loaderData;
104 // An old agent lead (agents no longer exist) shows as no lead.
105 const leadValue = team.lead?.kind === "user" ? `@${team.lead.username}` : NO_LEAD;
106 const said = (intent: string) => (actionData?.intent === intent ? actionData : null);
107 const [visibility, setVisibility] = useState<TeamVisibility>(team.visibility);
108 const review = team.review_assignment;
109 const [assigning, setAssigning] = useState(review.enabled);
110 const [algorithm, setAlgorithm] = useState<ReviewAlgorithm>(review.algorithm);
111 const [skipBusy, setSkipBusy] = useState(review.skip_busy);
112
113 return (
114 <div className="max-w-2xl space-y-10">
115 <section aria-labelledby="profile">
116 <h2 id="profile" className="font-medium">
117 Profile
118 </h2>
119 <Form method="post" className="mt-4 space-y-5" key={team.updated_at}>
120 <input type="hidden" name="intent" value="profile" />
121 <Field label="Name">
122 <Input name="name" required maxLength={80} defaultValue={team.name} />
123 </Field>
124 <Field label="Slug" hint={`Mentioned as @${team.workspace}/<slug>. Changing it changes the team's address and how it is mentioned.`}>
125 <Input name="slug" required maxLength={60} defaultValue={team.slug} pattern="[a-z0-9]+(-[a-z0-9]+)*" />
126 </Field>
127 <Field label="Description">
128 <Textarea name="description" rows={2} maxLength={280} defaultValue={team.description ?? ""} />
129 </Field>
130 <fieldset>
131 <legend className="mb-2 text-sm font-medium text-muted">Visibility</legend>
132 <RadioGroup name="visibility" value={visibility} onValueChange={(value) => setVisibility(value as TeamVisibility)} className="space-y-3">
133 <RadioOption value="visible" label="Visible" description={TEAM_VISIBILITY_SUMMARIES.visible} />
134 <RadioOption value="secret" label="Secret" description={TEAM_VISIBILITY_SUMMARIES.secret} />
135 </RadioGroup>
136 </fieldset>
137 {visibility === "visible" && (
138 <div>
139 <span className="mb-1.5 block text-sm font-medium text-muted">Parent team</span>
140 <Select name="parent" defaultValue={team.parent?.slug ?? NO_PARENT}>
141 <SelectTrigger aria-label="Parent team" className="sm:max-w-72">
142 <SelectValue />
143 </SelectTrigger>
144 <SelectContent>
145 <SelectItem value={NO_PARENT}>No parent</SelectItem>
146 {parents.map((parent) => (
147 <SelectItem key={parent.slug} value={parent.slug}>
148 {parent.name}
149 </SelectItem>
150 ))}
151 </SelectContent>
152 </Select>
153 <span className="mt-1.5 block text-xs text-faint">
154 It has its parent's roles on repositories, and hears what is asked of its parent. Moving it needs you to
155 maintain both teams, or own the workspace.
156 </span>
157 </div>
158 )}
159 <input type="hidden" name="notify-shown" value="1" />
160 <SwitchCard name="notify" defaultChecked={team.notify} title="Notify the team when it is mentioned">
161 Everyone in it, and in its child teams, hears of @{team.workspace}/{team.slug} in their notifications.
162 </SwitchCard>
163 <ErrorText>{said("profile")?.error ?? null}</ErrorText>
164 <div className="flex items-center gap-3">
165 <SubmitButton match={{ intent: "profile" }} pending="Saving…">
166 Save
167 </SubmitButton>
168 {said("profile")?.saved && <span className="text-sm text-muted">Saved.</span>}
169 </div>
170 </Form>
171 </section>
172
173 <section aria-labelledby="lead" className="border-t border-line pt-8">
174 <h2 id="lead" className="font-medium">
175 Lead and channel
176 </h2>
177 <p className="mt-1 text-sm text-muted">Who leads {team.name}, and where it talks.</p>
178 <Form method="post" className="mt-4 space-y-5" key={`people-${team.updated_at}`}>
179 <input type="hidden" name="intent" value="people" />
180 <label className="block">
181 <span className="mb-1.5 block text-sm font-medium text-muted">Lead</span>
182 <SelectField
183 name="lead"
184 defaultValue={leadValue}
185 className="w-full sm:max-w-72"
186 options={[
187 { value: NO_LEAD, label: "No lead" },
188 ...people.map((person) => ({ value: `@${person.username}`, label: person.name ? `${person.name} (@${person.username})` : `@${person.username}` })),
189 ]}
190 />
191 <span className="mt-1.5 block text-xs text-faint">Someone on the team.</span>
192 </label>
193 <Field label="Channel" hint="The team's channel in Chat, by name. Leave it empty for none.">
194 <span className="block sm:max-w-72">
195 <Input name="channel" defaultValue={team.channel?.name ?? ""} placeholder="sales" />
196 </span>
197 </Field>
198 <div className="flex items-center gap-2 text-sm text-muted">
199 Storage level <Coming />
200 </div>
201 <ErrorText>{said("people")?.error ?? null}</ErrorText>
202 <div className="flex items-center gap-3">
203 <SubmitButton match={{ intent: "people" }} pending="Saving…">
204 Save
205 </SubmitButton>
206 {said("people")?.saved && <span className="text-sm text-muted">Saved.</span>}
207 </div>
208 </Form>
209 </section>
210
211 <section aria-labelledby="review" className="border-t border-line pt-8">
212 <h2 id="review" className="font-medium">
213 Code review assignment
214 </h2>
215 <p className="mt-1 text-sm text-muted">
216 When {team.name} is asked to review a pull request, by a person or by a CODEOWNERS file. Off, everyone in the
217 team is asked. On, g1t picks people from it; the team stays shown as asked.
218 </p>
219 <Form method="post" className="mt-4 space-y-5" key={`review-${team.updated_at}`}>
220 <input type="hidden" name="intent" value="review" />
221 <SwitchCard name="enabled" checked={assigning} onCheckedChange={setAssigning} title="Assign reviewers from the team">
222 Never the pull request's author, and people from the team already asked count.
223 </SwitchCard>
224 {assigning && (
225 <Card tone="plain" className="space-y-5 p-4">
226 <Field label="How many people" hint={`1 to ${MAX_ASSIGNED}.`}>
227 <NumberInput name="count" type="number" min={1} max={MAX_ASSIGNED} defaultValue={review.count} className="max-w-24" />
228 </Field>
229 <fieldset>
230 <legend className="mb-2 text-sm font-medium text-muted">Who goes first</legend>
231 <RadioGroup name="algorithm" value={algorithm} onValueChange={(value) => setAlgorithm(value as ReviewAlgorithm)} className="space-y-3">
232 {(["round_robin", "load_balance"] as const).map((value) => (
233 <RadioOption key={value} value={value} label={REVIEW_ALGORITHM_LABELS[value]} description={REVIEW_ALGORITHM_SUMMARIES[value]} />
234 ))}
235 </RadioGroup>
236 </fieldset>
237 <div className="space-y-2">
238 <CheckboxOption
239 name="skip_busy"
240 checked={skipBusy}
241 onCheckedChange={(on) => setSkipBusy(on === true)}
242 label="Skip people who are busy"
243 description="Busy: this many or more open pull requests are waiting on their review."
244 />
245 {skipBusy && (
246 <div className="pl-6">
247 <NumberInput name="busy_at" type="number" min={1} max={100} defaultValue={review.busy_at} aria-label="Busy at" className="max-w-24" />
248 </div>
249 )}
250 </div>
251 <CheckboxOption
252 name="include_child_teams"
253 defaultChecked={review.include_child_teams}
254 label="Pick from child teams too"
255 description="Otherwise only the team's own people are picked."
256 />
257 <CheckboxOption
258 name="notify_team"
259 defaultChecked={review.notify_team}
260 label="Also tell the rest of the team"
261 description="Everyone in the team hears of the request, not only the people picked."
262 />
263 <Field label="Never pick" hint="Usernames, separated by spaces or commas.">
264 <Input name="excluded" defaultValue={review.excluded.join(" ")} placeholder="ana bo" />
265 </Field>
266 </Card>
267 )}
268 {!assigning && (
269 <>
270 {/* Kept as they are while assignment is off. */}
271 <input type="hidden" name="algorithm" value={review.algorithm} />
272 <input type="hidden" name="count" value={review.count} />
273 <input type="hidden" name="busy_at" value={review.busy_at} />
274 <input type="hidden" name="excluded" value={review.excluded.join(" ")} />
275 {review.skip_busy && <input type="hidden" name="skip_busy" value="on" />}
276 {review.include_child_teams && <input type="hidden" name="include_child_teams" value="on" />}
277 {review.notify_team && <input type="hidden" name="notify_team" value="on" />}
278 </>
279 )}
280 <ErrorText>{said("review")?.error ?? null}</ErrorText>
281 <div className="flex items-center gap-3">
282 <SubmitButton match={{ intent: "review" }} pending="Saving…">
283 Save
284 </SubmitButton>
285 {said("review")?.saved && <span className="text-sm text-muted">Saved.</span>}
286 </div>
287 </Form>
288 </section>
289
290 <section aria-labelledby="danger" className="border-t border-line pt-8">
291 <h2 id="danger" className="font-medium">
292 Delete this team
293 </h2>
294 <p className="mt-1 text-sm text-muted">
295 Its people stay in {team.workspace}, and lose the roles the team gave them. Its child teams move up to{" "}
296 {team.parent ? team.parent.name : "the top"}.
297 </p>
298 <div className="mt-4">
299 <ConfirmDialog
300 intent="delete"
301 title={`Delete ${team.name}?`}
302 description="This cannot be undone."
303 confirm={`${team.workspace}/${team.slug}`}
304 submit="Delete team"
305 busy="Deleting…"
306 error={said("delete")?.error ?? null}
307 trigger={(open) => (
308 <Button type="button" variant="destructive" onClick={open}>
309 Delete team
310 </Button>
311 )}
312 >
313 <li>Mentions of @{team.workspace}/{team.slug} stop telling anyone.</li>
314 <li>Pull requests that asked it to review keep the people it picked.</li>
315 </ConfirmDialog>
316 </div>
317 </section>
318 </div>
319 );
320}