Skip to content
refs
523 lines · 20.9 KBRaw
1import { MAX_BODY_LENGTH, NONE } from "@refs/backend/contract";
2import { AgentAvatar, Ago, Avatar, Banner, Button, Dialog, DropdownMenu, InputArea, LayerCard } from "@refs/design-system";
3import {
4 ArrowsLeftRightIcon,
5 AtIcon,
6 CheckCircleIcon,
7 DotsThreeIcon,
8 PencilSimpleIcon,
9 RecordIcon,
10 TagIcon,
11 TextAaIcon,
12 TrashIcon,
13 UserCircleIcon,
14} from "@refs/design-system/icons";
15import { useEffect, useState } from "react";
16import { Link, data, redirect, useFetcher } from "react-router";
17import type { Route } from "./+types/task";
18import { pullLink, taskLink, type Attribution, type Choice, type EventOf, type Label, type OnlineAgent, type Outcome, type TaskStatus, type TimelineItem } from "@refs/backend/contract";
19import { LabelBadge, LabelPicker, StatusBadge, StatusIcon } from "@refs/design-system";
20import { useLive } from "../components/live";
21import { failed, formList, formText, found, signedIn, fullName, nowSeconds } from "../lib/session";
22import { TitleEditor } from "../components/title-editor";
23import { useOnSuccess } from "../components/use-on-success";
24import { useLabelCreation } from "../components/label-creation";
25import { agentLabel, MentionTools } from "../components/mentions";
26import { ActorMark, ActorName, AgentName, EventLine, Field, GearButton, Timeline, TimelineRow, human, toneOf } from "../components/timeline";
27
28export const meta: Route.MetaFunction = ({ loaderData }) => [{ title: loaderData ? `${loaderData.task.title} · ${loaderData.task.repo}#${loaderData.task.number} · refs` : "Task · refs" }];
29
30function opposite(status: TaskStatus): TaskStatus {
31 return status === "open" ? "closed" : "open";
32}
33
34export async function loader({ params, context }: Route.LoaderArgs) {
35 const refs = signedIn(context);
36 const task = await found(refs.task(fullName(params), Number(params.number)));
37 const { detail } = task;
38 if (detail.repo !== fullName(params) || String(detail.number) !== params.number) throw redirect(taskLink(detail.repo, detail.number));
39 const [timeline, choices, agents] = await Promise.all([task.timeline(), refs.taskChoices(), refs.repo(detail.repo).then((repo) => repo.agents())]);
40 return { task: detail, timeline, choices, agents, now: nowSeconds() };
41}
42
43export async function action({ request, params, context }: Route.ActionArgs) {
44 const refs = signedIn(context);
45 const task = await found(refs.task(fullName(params), Number(params.number)));
46 const form = await request.formData();
47 const intent = formText(form, "intent");
48 const respond = (outcome: Outcome<unknown>) => (outcome.ok ? { intent, error: null } : failed(outcome.problem, { intent }));
49
50 switch (intent) {
51 case "comment": {
52 const body = formText(form, "body");
53 const then = formText(form, "toggle") === "1" ? opposite(task.detail.status) : undefined;
54 return respond(await (!body && then ? task.setStatus(then) : task.comment(body, then)));
55 }
56 case "title":
57 return respond(await task.rename(formText(form, "title")));
58 case "description":
59 return respond(await task.describe(formText(form, "body")));
60 case "assignee": {
61 const assignee = formText(form, "assignee");
62 return respond(await task.assign(assignee && assignee !== NONE ? assignee : null));
63 }
64 case "agent":
65 return respond(await task.handToAgent(formText(form, "agent")));
66 case "repo": {
67 const outcome = await task.transfer(formText(form, "repo"));
68 if (outcome.ok) throw redirect(taskLink(outcome.value.repo, outcome.value.number));
69 return respond(outcome);
70 }
71 case "labels":
72 return respond(await task.setLabels(formList(form, "label")));
73 case "edit-comment":
74 return respond(await found(task.editComment(formText(form, "comment"), formText(form, "body"))));
75 case "delete-comment":
76 return respond(await found(task.deleteComment(formText(form, "comment"))));
77 default:
78 return data({ intent, error: "Unknown action." }, { status: 400 });
79 }
80}
81
82type Event = Exclude<TimelineItem, { kind: "task.commented" | "task.opened" }>;
83
84function MarkdownEditor({
85 intent,
86 body: initial,
87 commentId,
88 onDone,
89 submit,
90}: {
91 intent: string;
92 body: string;
93 commentId?: string;
94 onDone: () => void;
95 submit: string;
96}) {
97 const fetcher = useFetcher<typeof action>();
98 const [body, setBody] = useState(initial);
99 useOnSuccess(fetcher, onDone);
100 return (
101 <fetcher.Form method="post" className="flex flex-col gap-3">
102 <input type="hidden" name="intent" value={intent} />
103 {commentId !== undefined && <input type="hidden" name="comment" value={commentId} />}
104 <InputArea aria-label="Markdown" name="body" value={body} onValueChange={setBody} maxLength={MAX_BODY_LENGTH} rows={8} autoFocus />
105 {fetcher.data?.error && <Banner variant="error" description={fetcher.data.error} />}
106 <div className="flex justify-end gap-2">
107 <Button type="button" variant="secondary" onClick={onDone}>
108 Cancel
109 </Button>
110 <Button type="submit" variant="primary" loading={fetcher.state !== "idle"}>
111 {submit}
112 </Button>
113 </div>
114 </fetcher.Form>
115 );
116}
117
118function DeleteComment({ commentId, open, onOpenChange }: { commentId: string; open: boolean; onOpenChange: (open: boolean) => void }) {
119 const fetcher = useFetcher<typeof action>();
120 return (
121 <Dialog.Root open={open} onOpenChange={onOpenChange}>
122 <Dialog size="sm" className="p-6">
123 <Dialog.Title className="m-0 text-lg font-semibold">Delete comment?</Dialog.Title>
124 <Dialog.Description className="mt-2 mb-5 text-muted">This can't be undone.</Dialog.Description>
125 <fetcher.Form method="post" className="flex justify-end gap-2">
126 <input type="hidden" name="intent" value="delete-comment" />
127 <input type="hidden" name="comment" value={commentId} />
128 <Dialog.Close render={(props) => <Button {...props} variant="secondary">Cancel</Button>} />
129 <Button type="submit" variant="primary" loading={fetcher.state !== "idle"}>
130 Delete
131 </Button>
132 </fetcher.Form>
133 </Dialog>
134 </Dialog.Root>
135 );
136}
137
138function CommentCard({
139 by,
140 verb,
141 at,
142 edited,
143 html,
144 body,
145 now: current,
146 editIntent,
147 commentId,
148 canEdit,
149 canDelete,
150 emptyText,
151}: {
152 by: Attribution;
153 verb: string;
154 at: number;
155 edited: boolean;
156 html: string | null;
157 body: string;
158 now: number;
159 editIntent: string;
160 commentId?: string;
161 canEdit: boolean;
162 canDelete: boolean;
163 emptyText?: string;
164}) {
165 const [editing, setEditing] = useState(false);
166 const [deleting, setDeleting] = useState(false);
167 return (
168 <TimelineRow tone={toneOf(by)}>
169 <LayerCard>
170 <LayerCard.Secondary className="flex items-center justify-between gap-3 py-1.5 font-normal">
171 <span className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 py-1">
172 <ActorMark by={by} />
173 <ActorName by={by} />
174 <span>{verb}</span>
175 <Ago at={at} now={current} />
176 {edited && <span className="text-faint">· edited</span>}
177 </span>
178 {(canEdit || canDelete) && (
179 <DropdownMenu>
180 <DropdownMenu.Trigger
181 render={
182 <Button variant="ghost" size="sm" shape="square" className="hit-area" aria-label="Comment actions">
183 <DotsThreeIcon size={18} weight="bold" />
184 </Button>
185 }
186 />
187 <DropdownMenu.Content align="end">
188 {canEdit && (
189 <DropdownMenu.Item icon={<PencilSimpleIcon />} onClick={() => setEditing(true)}>
190 Edit
191 </DropdownMenu.Item>
192 )}
193 {canDelete && (
194 <DropdownMenu.Item variant="danger" icon={<TrashIcon />} onClick={() => setDeleting(true)}>
195 Delete
196 </DropdownMenu.Item>
197 )}
198 </DropdownMenu.Content>
199 </DropdownMenu>
200 )}
201 </LayerCard.Secondary>
202 <LayerCard.Primary className="px-4 py-3">
203 {editing ? (
204 <MarkdownEditor intent={editIntent} body={body} commentId={commentId} onDone={() => setEditing(false)} submit="Save" />
205 ) : html ? (
206 <article className="markdown" dangerouslySetInnerHTML={{ __html: html }} />
207 ) : (
208 <p className="m-0 text-muted italic">{emptyText}</p>
209 )}
210 </LayerCard.Primary>
211 </LayerCard>
212 {commentId !== undefined && canDelete && <DeleteComment commentId={commentId} open={deleting} onOpenChange={setDeleting} />}
213 </TimelineRow>
214 );
215}
216
217function eventIcon(kind: Event["kind"]) {
218 switch (kind) {
219 case "task.closed":
220 return <CheckCircleIcon size={14} weight="fill" />;
221 case "task.reopened":
222 return <RecordIcon size={14} className="text-success" />;
223 case "task.assigned":
224 case "task.unassigned":
225 return <UserCircleIcon size={14} />;
226 case "task.transferred":
227 return <ArrowsLeftRightIcon size={14} />;
228 case "task.handed":
229 return <AtIcon size={14} />;
230 case "task.labeled":
231 case "task.unlabeled":
232 return <TagIcon size={14} />;
233 default:
234 return <TextAaIcon size={14} />;
235 }
236}
237
238function EventDescription({ event, repo }: { event: Event; repo: string }) {
239 switch (event.kind) {
240 case "task.closed":
241 return event.data.pull ? (
242 <>
243 closed this by merging{" "}
244 <Link to={pullLink(repo, event.data.pull)} className="font-medium text-accent-text">
245 #{event.data.pull}
246 </Link>
247 </>
248 ) : (
249 <>closed this</>
250 );
251 case "task.reopened":
252 return <>reopened this</>;
253 case "task.assigned":
254 return (
255 <>
256 assigned <span className="font-medium text-ink">{event.data.assignee.name}</span>
257 </>
258 );
259 case "task.unassigned":
260 return (
261 <>
262 unassigned <span className="font-medium text-ink">{event.data.assignee.name}</span>
263 </>
264 );
265 case "task.handed":
266 return (
267 <>
268 handed this to <AgentName agent={event.data.agent} /> on{" "}
269 <Link to={pullLink(event.data.repo, event.data.pull)} className="font-medium text-accent-text">
270 #{event.data.pull}
271 </Link>
272 </>
273 );
274 case "task.transferred":
275 return (
276 <>
277 transferred this from <span className="font-medium text-ink">{event.data.from.repo}</span> to{" "}
278 <span className="font-medium text-ink">{event.data.to.repo}</span>
279 </>
280 );
281 case "task.labeled":
282 return (
283 <>
284 added <LabelBadge label={event.data.label} />
285 </>
286 );
287 case "task.unlabeled":
288 return (
289 <>
290 removed <LabelBadge label={event.data.label} />
291 </>
292 );
293 case "task.renamed":
294 return (
295 <>
296 changed the title <span className="line-through">{event.data.from}</span> <span className="font-medium text-ink">{event.data.to}</span>
297 </>
298 );
299 default:
300 return null;
301 }
302}
303
304function TaskEvent({ event, repo, now: current }: { event: Event; repo: string; now: number }) {
305 return (
306 <EventLine by={event.by} icon={eventIcon(event.kind)}>
307 <span className="min-w-0">
308 <EventDescription event={event} repo={repo} />
309 </span>
310 <Ago at={event.at} now={current} />
311 </EventLine>
312 );
313}
314
315function Composer({ status, agents }: { status: "open" | "closed"; agents: readonly OnlineAgent[] }) {
316 const fetcher = useFetcher<typeof action>();
317 const [body, setBody] = useState("");
318 const [round, setRound] = useState(0);
319 const busy = fetcher.state !== "idle";
320 useOnSuccess(fetcher, (answer) => {
321 if (answer.intent !== "comment") return;
322 setBody("");
323 setRound((value) => value + 1);
324 });
325 const toggleLabel = status === "open" ? (body ? "Close with comment" : "Close task") : body ? "Reopen with comment" : "Reopen task";
326
327 return (
328 <TimelineRow tone="event">
329 <LayerCard className="p-4">
330 <fetcher.Form key={round} method="post" className="flex flex-col gap-3">
331 <input type="hidden" name="intent" value="comment" />
332 <InputArea label="Add a comment" name="body" value={body} onValueChange={setBody} maxLength={MAX_BODY_LENGTH} rows={4} description="Markdown is supported. Mention an agent to hand this task to it." />
333 {agents.length > 0 && <MentionTools agents={agents} body={body} onBody={setBody} canAssign={false} />}
334 {fetcher.data?.intent === "comment" && fetcher.data.error && <Banner variant="error" description={fetcher.data.error} />}
335 <div className="flex flex-wrap justify-end gap-2">
336 <Button type="submit" name="toggle" value="1" variant="secondary" icon={<StatusIcon status={status === "open" ? "closed" : "open"} size={16} />} loading={busy && fetcher.formData?.get("toggle") === "1"}>
337 {toggleLabel}
338 </Button>
339 <Button type="submit" variant="primary" disabled={!body.trim()} loading={busy && fetcher.formData?.get("toggle") !== "1"}>
340 Comment
341 </Button>
342 </div>
343 </fetcher.Form>
344 </LayerCard>
345 </TimelineRow>
346 );
347}
348
349function settingsTrigger(label: string) {
350 return <GearButton label={label} />;
351}
352
353function SinglePicker({ intent, field, label, options, current, empty }: { intent: string; field: string; label: string; options: readonly Choice[]; current: string | null; empty?: string }) {
354 const fetcher = useFetcher<typeof action>();
355 const pending = fetcher.formData?.get(field);
356 const value = typeof pending === "string" ? pending : (current ?? NONE);
357 return (
358 <DropdownMenu>
359 <DropdownMenu.Trigger render={settingsTrigger(label)} />
360 <DropdownMenu.Content align="end" className="max-h-96 min-w-56 overflow-y-auto">
361 <div className="caption px-2 py-1.5 text-faint">{label}</div>
362 <DropdownMenu.RadioGroup value={value} onValueChange={(next) => fetcher.submit({ intent, [field]: String(next) }, { method: "post" })}>
363 {empty && <DropdownMenu.RadioItem value={NONE}>{empty}</DropdownMenu.RadioItem>}
364 {options.map((option) => (
365 <DropdownMenu.RadioItem key={option.id} value={option.id}>
366 {option.name}
367 </DropdownMenu.RadioItem>
368 ))}
369 </DropdownMenu.RadioGroup>
370 </DropdownMenu.Content>
371 </DropdownMenu>
372 );
373}
374
375function AgentField({ agents, handed }: { agents: readonly OnlineAgent[]; handed: EventOf<"task.handed"> | undefined }) {
376 const fetcher = useFetcher<typeof action>();
377 const busy = fetcher.state !== "idle";
378 const picker = agents.length > 0 && (
379 <DropdownMenu>
380 <DropdownMenu.Trigger render={settingsTrigger("Hand to agent")} disabled={busy} />
381 <DropdownMenu.Content align="end" className="max-h-96 min-w-56 overflow-y-auto">
382 <div className="caption px-2 py-1.5 text-faint">Hand to agent</div>
383 {agents.map((agent) => (
384 <DropdownMenu.Item key={agent.session} onClick={() => fetcher.submit({ intent: "agent", agent: agent.session }, { method: "post" })}>
385 {agentLabel(agent)}
386 </DropdownMenu.Item>
387 ))}
388 </DropdownMenu.Content>
389 </DropdownMenu>
390 );
391 return (
392 <Field label="Agent" action={picker}>
393 {busy ? (
394 <span className="text-muted">Opening a pull request…</span>
395 ) : handed ? (
396 <span className="flex min-w-0 items-center gap-2">
397 <AgentAvatar name={handed.data.agent.runtime} size="xs" />
398 <AgentName agent={handed.data.agent} />
399 <Link to={pullLink(handed.data.repo, handed.data.pull)} className="shrink-0 text-accent-text hover:underline">
400 #{handed.data.pull}
401 </Link>
402 </span>
403 ) : (
404 <span className="text-muted">{agents.length ? "No agent yet" : "No agents online. Connect one from your terminal."}</span>
405 )}
406 {fetcher.data?.intent === "agent" && fetcher.data.error && <Banner variant="error" description={fetcher.data.error} />}
407 </Field>
408 );
409}
410
411function LabelsSection({ repo, all, current }: { repo: string; all: readonly Label[]; current: readonly Label[] }) {
412 const fetcher = useFetcher<typeof action>();
413 const [selected, setSelected] = useState(current.map((label) => label.id));
414 const creation = useLabelCreation();
415 useEffect(() => setSelected(current.map((label) => label.id)), [current.map((label) => label.id).join()]);
416 const save = () => {
417 const before = current.map((label) => label.id).sort().join();
418 if (before === [...selected].sort().join()) return;
419 const form = new FormData();
420 form.set("intent", "labels");
421 for (const id of selected) form.append("label", id);
422 fetcher.submit(form, { method: "post" });
423 };
424 const shown = all.filter((label) => selected.includes(label.id));
425 return (
426 <Field label="Labels" action={<LabelPicker labels={all} selected={selected} creation={creation} onToggle={(id, checked) => setSelected((previous) => (checked ? [...new Set([...previous, id])] : previous.filter((value) => value !== id)))} onClose={save} trigger={settingsTrigger("Edit labels")} />}>
427 {shown.length ? (
428 <div className="flex flex-wrap gap-1.5">
429 {shown.map((label) => (
430 <LabelBadge key={label.id} label={label} href={`/${repo}/tasks?label=${encodeURIComponent(label.name)}`} />
431 ))}
432 </div>
433 ) : (
434 <span className="text-muted">None yet</span>
435 )}
436 </Field>
437 );
438}
439
440export default function TaskPage({ loaderData }: Route.ComponentProps) {
441 const { task, timeline, choices, agents, now: current } = loaderData;
442 const handed = timeline.findLast((event): event is EventOf<"task.handed"> => event.kind === "task.handed");
443 useLive(task.repo, task.number);
444
445 return (
446 <>
447 <div className="mb-5 pb-5 shadow-[inset_0_-1px_0_var(--hairline)]">
448 <TitleEditor
449 title={task.title}
450 number={task.number}
451 meta={(edit) => (
452 <div className="flex flex-wrap items-center gap-x-2.5 gap-y-2 text-compact text-muted">
453 <StatusBadge status={task.status} />
454 <span aria-hidden className="text-faint">·</span>
455 <span className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
456 <Avatar name={task.author.name} size="xs" />
457 <span className="font-medium text-ink">{task.author.name}</span> opened this <Ago at={task.createdAt} now={current} />
458 {task.comments > 0 && <span className="tabular-nums">· {task.comments} {task.comments === 1 ? "comment" : "comments"}</span>}
459 </span>
460 {edit && <span className="sm:ml-auto">{edit}</span>}
461 </div>
462 )}
463 />
464 </div>
465 <div className="grid items-start gap-8 lg:grid-cols-[minmax(0,1fr)_17rem]">
466 <Timeline>
467 <CommentCard
468 by={human(task.author.name)}
469 verb="opened this"
470 at={task.createdAt}
471 edited={task.updatedAt > task.createdAt && task.body !== ""}
472 html={task.bodyHtml}
473 body={task.body}
474 now={current}
475 editIntent="description"
476 canEdit
477 canDelete={false}
478 emptyText="No description provided."
479 />
480 {timeline.map((event) =>
481 event.kind === "task.opened" ? null : event.kind === "task.commented" ? (
482 <CommentCard
483 key={event.id}
484 by={event.by}
485 verb="commented"
486 at={event.at}
487 edited={event.data.editedAt !== null}
488 html={event.data.html}
489 body={event.data.body}
490 now={current}
491 editIntent="edit-comment"
492 commentId={event.id}
493 canEdit={event.can?.edit ?? false}
494 canDelete={event.can?.delete ?? false}
495 />
496 ) : (
497 <TaskEvent key={event.id} event={event} repo={task.repo} now={current} />
498 ),
499 )}
500 <Composer status={task.status} agents={agents} />
501 </Timeline>
502 <aside className="flex flex-col">
503 <Field label="Assignee" action={<SinglePicker intent="assignee" field="assignee" label="Assign to" options={choices.people} current={task.assignee?.id ?? null} empty="Unassigned" />}>
504 {task.assignee ? (
505 <span className="flex items-center gap-2">
506 <Avatar name={task.assignee.name} size="xs" /> {task.assignee.name}
507 </span>
508 ) : (
509 <span className="text-muted">No one assigned</span>
510 )}
511 </Field>
512 <AgentField agents={agents} handed={handed} />
513 <LabelsSection repo={task.repo} all={choices.labels} current={task.labels} />
514 <Field label="Repository" action={<SinglePicker intent="repo" field="repo" label="Transfer to repository" options={choices.repos} current={task.repo} />}>
515 <Link to={`/${task.repo}`} className="text-accent-text hover:underline">
516 {task.repo}
517 </Link>
518 </Field>
519 </aside>
520 </div>
521 </>
522 );
523}