Skip to content
refs
522 lines · 20.6 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 } 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 }: { status: "open" | "closed" }) {
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." />
333 {fetcher.data?.intent === "comment" && fetcher.data.error && <Banner variant="error" description={fetcher.data.error} />}
334 <div className="flex flex-wrap justify-end gap-2">
335 <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"}>
336 {toggleLabel}
337 </Button>
338 <Button type="submit" variant="primary" disabled={!body.trim()} loading={busy && fetcher.formData?.get("toggle") !== "1"}>
339 Comment
340 </Button>
341 </div>
342 </fetcher.Form>
343 </LayerCard>
344 </TimelineRow>
345 );
346}
347
348function settingsTrigger(label: string) {
349 return <GearButton label={label} />;
350}
351
352function SinglePicker({ intent, field, label, options, current, empty }: { intent: string; field: string; label: string; options: readonly Choice[]; current: string | null; empty?: string }) {
353 const fetcher = useFetcher<typeof action>();
354 const pending = fetcher.formData?.get(field);
355 const value = typeof pending === "string" ? pending : (current ?? NONE);
356 return (
357 <DropdownMenu>
358 <DropdownMenu.Trigger render={settingsTrigger(label)} />
359 <DropdownMenu.Content align="end" className="max-h-96 min-w-56 overflow-y-auto">
360 <div className="caption px-2 py-1.5 text-faint">{label}</div>
361 <DropdownMenu.RadioGroup value={value} onValueChange={(next) => fetcher.submit({ intent, [field]: String(next) }, { method: "post" })}>
362 {empty && <DropdownMenu.RadioItem value={NONE}>{empty}</DropdownMenu.RadioItem>}
363 {options.map((option) => (
364 <DropdownMenu.RadioItem key={option.id} value={option.id}>
365 {option.name}
366 </DropdownMenu.RadioItem>
367 ))}
368 </DropdownMenu.RadioGroup>
369 </DropdownMenu.Content>
370 </DropdownMenu>
371 );
372}
373
374function AgentField({ agents, handed }: { agents: readonly OnlineAgent[]; handed: EventOf<"task.handed"> | undefined }) {
375 const fetcher = useFetcher<typeof action>();
376 const busy = fetcher.state !== "idle";
377 const picker = agents.length > 0 && (
378 <DropdownMenu>
379 <DropdownMenu.Trigger render={settingsTrigger("Hand to agent")} disabled={busy} />
380 <DropdownMenu.Content align="end" className="max-h-96 min-w-56 overflow-y-auto">
381 <div className="caption px-2 py-1.5 text-faint">Hand to agent</div>
382 {agents.map((agent) => (
383 <DropdownMenu.Item key={agent.session} onClick={() => fetcher.submit({ intent: "agent", agent: agent.session }, { method: "post" })}>
384 {agentLabel(agent)}
385 </DropdownMenu.Item>
386 ))}
387 </DropdownMenu.Content>
388 </DropdownMenu>
389 );
390 return (
391 <Field label="Agent" action={picker}>
392 {busy ? (
393 <span className="text-muted">Opening a pull request…</span>
394 ) : handed ? (
395 <span className="flex min-w-0 items-center gap-2">
396 <AgentAvatar name={handed.data.agent.runtime} size="xs" />
397 <AgentName agent={handed.data.agent} />
398 <Link to={pullLink(handed.data.repo, handed.data.pull)} className="shrink-0 text-accent-text hover:underline">
399 #{handed.data.pull}
400 </Link>
401 </span>
402 ) : (
403 <span className="text-muted">{agents.length ? "No agent yet" : "No agents online. Connect one from your terminal."}</span>
404 )}
405 {fetcher.data?.intent === "agent" && fetcher.data.error && <Banner variant="error" description={fetcher.data.error} />}
406 </Field>
407 );
408}
409
410function LabelsSection({ repo, all, current }: { repo: string; all: readonly Label[]; current: readonly Label[] }) {
411 const fetcher = useFetcher<typeof action>();
412 const [selected, setSelected] = useState(current.map((label) => label.id));
413 const creation = useLabelCreation();
414 useEffect(() => setSelected(current.map((label) => label.id)), [current.map((label) => label.id).join()]);
415 const save = () => {
416 const before = current.map((label) => label.id).sort().join();
417 if (before === [...selected].sort().join()) return;
418 const form = new FormData();
419 form.set("intent", "labels");
420 for (const id of selected) form.append("label", id);
421 fetcher.submit(form, { method: "post" });
422 };
423 const shown = all.filter((label) => selected.includes(label.id));
424 return (
425 <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")} />}>
426 {shown.length ? (
427 <div className="flex flex-wrap gap-1.5">
428 {shown.map((label) => (
429 <LabelBadge key={label.id} label={label} href={`/${repo}/tasks?label=${encodeURIComponent(label.name)}`} />
430 ))}
431 </div>
432 ) : (
433 <span className="text-muted">None yet</span>
434 )}
435 </Field>
436 );
437}
438
439export default function TaskPage({ loaderData }: Route.ComponentProps) {
440 const { task, timeline, choices, agents, now: current } = loaderData;
441 const handed = timeline.findLast((event): event is EventOf<"task.handed"> => event.kind === "task.handed");
442 useLive(task.repo, task.number);
443
444 return (
445 <>
446 <div className="mb-5 pb-5 shadow-[inset_0_-1px_0_var(--hairline)]">
447 <TitleEditor
448 title={task.title}
449 number={task.number}
450 meta={(edit) => (
451 <div className="flex flex-wrap items-center gap-x-2.5 gap-y-2 text-compact text-muted">
452 <StatusBadge status={task.status} />
453 <span aria-hidden className="text-faint">·</span>
454 <span className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
455 <Avatar name={task.author.name} size="xs" />
456 <span className="font-medium text-ink">{task.author.name}</span> opened this <Ago at={task.createdAt} now={current} />
457 {task.comments > 0 && <span className="tabular-nums">· {task.comments} {task.comments === 1 ? "comment" : "comments"}</span>}
458 </span>
459 {edit && <span className="sm:ml-auto">{edit}</span>}
460 </div>
461 )}
462 />
463 </div>
464 <div className="grid items-start gap-8 lg:grid-cols-[minmax(0,1fr)_17rem]">
465 <Timeline>
466 <CommentCard
467 by={human(task.author.name)}
468 verb="opened this"
469 at={task.createdAt}
470 edited={task.updatedAt > task.createdAt && task.body !== ""}
471 html={task.bodyHtml}
472 body={task.body}
473 now={current}
474 editIntent="description"
475 canEdit
476 canDelete={false}
477 emptyText="No description provided."
478 />
479 {timeline.map((event) =>
480 event.kind === "task.opened" ? null : event.kind === "task.commented" ? (
481 <CommentCard
482 key={event.id}
483 by={event.by}
484 verb="commented"
485 at={event.at}
486 edited={event.data.editedAt !== null}
487 html={event.data.html}
488 body={event.data.body}
489 now={current}
490 editIntent="edit-comment"
491 commentId={event.id}
492 canEdit={event.can?.edit ?? false}
493 canDelete={event.can?.delete ?? false}
494 />
495 ) : (
496 <TaskEvent key={event.id} event={event} repo={task.repo} now={current} />
497 ),
498 )}
499 <Composer status={task.status} />
500 </Timeline>
501 <aside className="flex flex-col">
502 <Field label="Assignee" action={<SinglePicker intent="assignee" field="assignee" label="Assign to" options={choices.people} current={task.assignee?.id ?? null} empty="Unassigned" />}>
503 {task.assignee ? (
504 <span className="flex items-center gap-2">
505 <Avatar name={task.assignee.name} size="xs" /> {task.assignee.name}
506 </span>
507 ) : (
508 <span className="text-muted">No one assigned</span>
509 )}
510 </Field>
511 <AgentField agents={agents} handed={handed} />
512 <LabelsSection repo={task.repo} all={choices.labels} current={task.labels} />
513 <Field label="Repository" action={<SinglePicker intent="repo" field="repo" label="Transfer to repository" options={choices.repos} current={task.repo} />}>
514 <Link to={`/${task.repo}`} className="text-accent-text hover:underline">
515 {task.repo}
516 </Link>
517 </Field>
518 </aside>
519 </div>
520 </>
521 );
522}