Official
sidebar
Built-in sidebar UI (JavaScript UI plugin).
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/sidebar@0.2.4
Permissions in 0.2.4
Files
views.tsx37.3 KB
// The left sidebar's trees: search and actions, the workspace picker, the list
// of chats, and the footer with the notice that offers archived rows back. Handlers only run controller effects or mutate
// state and update; the preview hydration fires from rendering, guarded so
// each chat reads once.
// HTM whitespace is significant; keep these templates out of Prettier's
// HTML formatter.
import * as kit from "divergence";
import type { EffectViewContext } from "divergence/effect";
import type { ButtonClickEvent, Chat, ClickEvent, DragOverEvent, DropEvent, Element, Modifiers, PresetColor, Workspace } from "divergence";
import type { Sidebar } from "./controller.ts";
import {
pageOf,
canPlace,
chatStatus,
chatTitleOf,
completedOf,
elapsed,
isDraft,
isTaskRow,
openingChat,
rowMatches,
rowStatus,
rowTitleOf,
sections,
shownChats,
taskChats,
taskOf,
undoLabel,
stillWorking,
workspaceLooks,
workspaceMarkOf,
} from "./sections.ts";
import type { ChatRowStatus, Over, SectionId } from "./sections.ts";
// The shared surface looks from the runtime; an older runtime without them
// gets the same `elevation`, which its kernel already draws.
const RAISED = kit.RAISED ?? { elevation: "raised" };
const EDGED = kit.EDGED ?? { elevation: "edge" };
const FLAT = kit.FLAT ?? { elevation: "none" };
// The chats scroll as a list that opens at its first row and lays out only
// the rows on screen. A runtime without it scrolls a column of every row.
const LIST = kit.LIST;
// The kernel carries a dragged row itself and says where the pointer is, so
// the rows make way for it. An older kernel draws a line where it lands and
// says only where it was dropped.
const LIVE_DRAG = !!kit.LIVE_DRAG;
// Layout for the templates below: a flex column, a row that centres its
// children across, a child that takes the free space (and may shrink below
// its content), the whole of the parent, and the hover wash.
const column = { display: "flex", flexDirection: "column" } as const;
const row = { display: "flex", flexDirection: "row", alignItems: "center" } as const;
// The open chat is raised like the panes (the item's `lift`, which keeps the
// edge's width on every other row, so opening a chat never moves its text).
const fill = { flexGrow: 1, flexShrink: 1, flexBasis: "0%", minWidth: 0, minHeight: 0 } as const;
const full = { width: "100%", height: "100%" } as const;
const HOVER = { background: "hover" } as const;
// Shown only while the pointer is on a chat's status mark (the mark is the
// hover group `glyph`), or only while it is not: the check shows only
// where a click checks the chat off.
const revealOnGlyph = { visibility: "hidden", groupHover: { group: "glyph", visibility: "visible" } } as const;
const HIDE_ON_GLYPH = { group: "glyph", visibility: "hidden" } as const;
// The list's width as last measured, which places a row's popover and menu just past the
// sidebar's edge: their anchor runs from the row's mark to there.
let listWidth = 268;
const besideAnchor = () => <div width={Math.max(listWidth - 22, 1)} height={1} />;
// A popover in a row's leading slot, taking no room there.
const beside = (popover: Element) => <div position="absolute" left={0} top={0}>{popover}</div>;
// The task popover's timers: the second's wait before it opens and the
// fade before it closes (one popover at a time).
const popoverTimers: { open?: ReturnType<typeof setTimeout>; close?: ReturnType<typeof setTimeout> } = {};
// A layer over the whole of its parent that centres what it holds.
const layer = {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
display: "flex",
alignItems: "center",
justifyContent: "center",
};
const TONE: Record<ChatRowStatus, "warning" | "info" | "danger" | "success" | "faint"> = {
blocked: "warning",
running: "info",
failed: "danger",
review: "success",
idle: "faint",
};
const LIVE_TONE: Record<ChatRowStatus, "warning" | "info" | "danger" | "muted"> = {
blocked: "warning",
running: "info",
failed: "danger",
review: "muted",
idle: "muted",
};
// Rows other plugins add to the footer, above Settings (the market's
// Marketplace row): each publishes the id of a view of its own in the app's
// shared state under a key starting with `sidebarItem.`, and clears it when
// it goes. In the order of their keys, so they keep their places.
const ITEM_PREFIX = "sidebarItem.";
export function sidebarItems(shared: Readonly<Record<string, unknown>> | undefined): number[] {
return Object.entries(shared ?? {})
.filter((entry): entry is [string, number] => entry[0].startsWith(ITEM_PREFIX) && typeof entry[1] === "number")
.sort(([a], [b]) => a.localeCompare(b))
.map(([, view]) => view);
}
export function renderSidebar(ctx: EffectViewContext<{ cmd?: boolean }>, sidebar: Sidebar["Service"]): Element | null {
const { state } = sidebar;
const app = ctx.app;
// Settings takes the window: its own list of sections is the sidebar.
if (app.route === "settings") return null;
if (!state.loaded) {
return <div {...column} gap="small" padding="medium"><text style="muted">Loading…</text></div>;
}
// Only a multi-chat task can change which child rows belong in this flat list.
// Ordinary rows and members of the same task share one projected output.
const taskCases = Object.fromEntries(Object.entries(state.homes).filter(([id]) => isTaskRow(state, { id })));
const activeTask = sidebar.nativeApp?.project
? sidebar.nativeApp.project({ key: "chatId", cases: taskCases, default: null })
: app.chatId ? taskCases[app.chatId] ?? null : null;
// Latest model activity; status is the fallback for an empty transcript.
function liveLine(chat: Chat): string {
if (chat.status !== "running") {
const { agents, commands } = stillWorking(state, chat);
const count = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;
if (agents && commands) return `${count(agents, "agent")} and ${count(commands, "command")} working`;
if (agents) return `${count(agents, "agent")} working`;
if (commands) return `${count(commands, "command")} running`;
}
// The transcript is read once per chat, when a row first shows it. The
// check runs here, synchronously: a forked check could run after the
// chat was removed and resurrect its preview with a stray read.
const preview = state.previews[chat.id];
if (!preview?.loading && !preview?.revision) ctx.run(sidebar.ensurePreview(chat.id));
const status = chatStatus(state, chat);
// A failed turn says so before anything it said.
if (status === "failed") {
const ago = elapsed(Date.now(), chat.updatedAt);
return ago ? `Failed · ${ago}` : "Failed";
}
if (preview?.line) return preview.line;
const base =
status === "blocked"
? "Waiting on you"
: status === "running"
? "Working…"
: status === "review"
? "Finished"
: chat.sessionId
? "Idle"
: "Not started";
// A review always stamped its finish when the run ended; an idle chat
// shows how long ago it was touched.
const finishedAt = state.finished[chat.id];
const since =
status === "review" && finishedAt
? new Date(finishedAt).toISOString()
: status === "idle" && chat.sessionId
? chat.updatedAt
: null;
const ago = since ? elapsed(Date.now(), since) : "";
return ago ? `${base} · ${ago}` : base;
}
// --- rows -----------------------------------------------------------------
// Each workspace's mark (its project icon, the app's mark, or its
// coloured folder), for the rows of its chats.
const workspaceMarks = new Map<string, Workspace>(state.workspaces.map((w) => [w.id, w]));
const workspaceMark = (w: Workspace | undefined) => {
if (!w) return null;
const mark = workspaceMarkOf(w);
return mark.image
? <image path={mark.image} width={14} height={14} radius={3} />
: <icon name={mark.icon ?? "folder"} color={mark.color} small tone="faint" />;
};
function renameField(editing: { id: string; title: string }) {
return (
<input id={`rename-${editing.id}`} value={editing.title} onChange={(e: { value: string }) => {
editing.title = e.value;
}} onSubmit={() => ctx.run(sidebar.commitRename())} />
);
}
// The status mark: a dot or a spinner, and a check while the pointer is
// on the mark; clicking the check checks the chat off (or opens it again).
function glyph(chat: Chat, status: ChatRowStatus) {
const done = !!completedOf(state, chat);
if (!done && isDraft(state, chat)) return <button id={`play-${chat.id}`} icon={ctx.state.cmd ? "list-plus" : "play"} variant="ghost" small disabled={!state.chat || state.submitting.has(chat.id)} loading={state.submitting.has(chat.id)} tooltip={ctx.state.cmd ? "Queue draft" : "Send draft (⌘ or Ctrl click to queue)"} onClick={(event?: ButtonClickEvent) => ctx.run(sidebar.submitDraft(chat.id, event ? (event.modifiers.secondary ?? event.modifiers.meta) : !!ctx.state.cmd))} />;
if (!done && state.queued.has(chat.id)) return <button id={`unqueue-${chat.id}`} icon="list-minus" variant="ghost" small disabled={!state.chat} tooltip="Remove from queue" onClick={() => ctx.run(sidebar.unqueue(chat.id))} />;
// An empty circle reads as a box to tick; its colour says what the
// chat is doing. Running shows the spinner, complete the ticked circle.
const mark = done
? <icon name="circle-check" small tone="muted" />
: status === "running"
? <spinner activity />
: <icon name="circle" small tone={TONE[status]} />;
return checkable(`glyph-${chat.id}`, mark, done, () => ctx.run(sidebar.toggleCompleted(chat)));
}
// A status mark and the check that lie over each other: the pointer on
// the mark swaps them, and a click runs `check`.
function checkable(id: string, mark: Element, done: boolean, check: () => void) {
return (
<div {...column} group="glyph" id={id} width={17} height={17} flexShrink={0} borderRadius="full" hover={HOVER} position="relative" stopPropagation onClick={check}>
<div {...layer}><div {...column} groupHover={done ? undefined : HIDE_ON_GLYPH}>{mark}</div></div>
{done
? null
: (
<div {...layer}>
<div {...column} {...revealOnGlyph}><icon name="circle-check" small tone="muted" /></div>
</div>
)}
</div>
);
}
// The rows glide to their new places as chats come, go and change
// section, but not while a search narrows the list as it is typed.
const moves = !state.query;
// Every row, heading and the list itself take a dragged chat: where the
// pointer is moves its place, and the drop lands it there.
function dropTarget(over: (zone: string) => Over, row?: string) {
// The task the row stands for, which a carried chat's drop on its middle third joins.
const rowTask = row ? taskOf(state, row) : undefined;
return {
// A task row moves in the list as a chat row does; only a chat
// joins a task (document 4).
types: ["divergence/chat", "divergence/task"],
zones: row ? ("bands" as const) : undefined,
onOver: (e: DragOverEvent) => {
const carried = carriedChat(e);
const joins = e.type === "divergence/chat" && e.zone === "into" && !!rowTask && state.homes[carried] !== rowTask.id;
ctx.run(sidebar.markJoining(joins ? row! : null));
// A chat of a task of several is not a row yet: it has no place to move.
if (e.zone && e.zone !== "into" && !inTaskOfSeveral(carried)) ctx.run(sidebar.dragChat(carried, over(e.zone)));
},
// The kernel that tells where the pointer is has already moved the
// chat's place there; an older one tells only the drop.
onDrop: (e: DropEvent) => {
if (!("data" in e)) return;
const carried = carriedChat(e);
if (e.type === "divergence/chat" && e.zone === "into" && rowTask) {
if (state.homes[carried] !== rowTask.id) ctx.run(sidebar.placeChat(carried, { kind: "join", taskId: rowTask.id }));
return;
}
if (e.type === "divergence/chat" && inTaskOfSeveral(carried)) return ctx.run(sidebar.placeChat(carried, { kind: "alone" }, over(e.zone)));
ctx.run(sidebar.dropChat(carried, LIVE_DRAG ? undefined : over(e.zone)));
},
};
}
// The chat a drag carries: a chat's own, or the first chat of a carried task row.
function carriedChat(e: { data: unknown }): string {
const data = (e.data ?? {}) as { chatId?: string };
return String(data.chatId ?? "");
}
// Whether a chat shares its task with others, so dropping it in the list takes it out.
function inTaskOfSeveral(chatId: string): boolean {
const task = taskOf(state, chatId);
return !!task && taskChats(state, task).length > 1;
}
// A chat: its status mark (the check), its title and live line, its
// agent at the end, and rename and archive while the pointer is on it. A
// chat being renamed is the rename field. While Cmd is held, the first
// nine rows show the number that opens them with Cmd in place of the agent,
// in a cap the agent icon's size so holding Cmd moves nothing.
function chatRow(chat: Chat, position: number, section: SectionId) {
const task = taskOf(state, chat.id);
const taskRow = isTaskRow(state, chat);
const onScreen = taskRow && activeTask === task?.id;
// While a task's chats are listed under it, its active child is selected.
const listed = taskRow && (onScreen || state.expanded.has(task!.id) || !!state.query.trim());
// A new host resolves this component prop from native app state. The
// right side of `??` stays unread there, so a one-chat row does not
// subscribe the whole sidebar view to a selection it can draw itself.
const selected = taskRow ? false : (sidebar.nativeApp?.bind?.("chatId", chat.id) ?? app.chatId === chat.id);
const status = rowStatus(state, chat);
const editing = state.editing?.id === chat.id ? state.editing : null;
const agent = state.agents.find((a) => a.id === chat.agentId);
// A checked-off chat is one struck line, a draft or a queued chat one
// plain line: no live line under any of them. A task row is always one
// line: each chat's status shows on its own child row and tab.
const done = !!completedOf(state, chat);
const compact = taskRow || done || isDraft(state, chat) || state.queued.has(chat.id);
const title = rowTitleOf(state, chat);
const rename = () => {
state.editing = { id: chat.id, title, ...(taskRow ? { task: task!.id } : {}) };
ctx.update();
};
const opens = openingChat(state, chat);
// A row drags to another place in the list; where it may land is the
// model's (`dropTargets`).
const movable = canPlace(section) && !editing;
// Pinning is for a chat that has started and is not checked off.
const pinned = section === "pinned";
// A task row that does not list its chats offers them in a popover
// beside it after the pointer rests on it a second (document 1).
const pops = taskRow && !listed && !editing && !state.dragging;
// The row's menu (document 8), whose entries are the row's hover actions and Mark Done.
const menuOpen = state.rowMenu?.chatId === chat.id && !state.rowMenu.child;
const entries = [
...(taskRow && !onScreen ? [{ id: "row-menu-chats", label: state.expanded.has(task!.id) ? "Hide Chats" : "Show Chats", run: () => ctx.run(sidebar.toggleExpanded(task!.id)) }] : []),
...(!compact || (taskRow && !done) ? [{ id: "row-menu-pin", label: pinned ? "Unpin" : "Pin", key: "⌥⌘P", run: () => ctx.run(sidebar.togglePin(chat)) }] : []),
{ id: "row-menu-rename", label: "Rename", run: rename },
{ id: "row-menu-done", label: done ? "Open Again" : "Mark Done", key: "⇧⌘M", run: () => ctx.run(sidebar.toggleCompleted(chat)) },
{ id: "row-menu-archive", label: "Archive", key: "⌥⌘⌫", run: () => ctx.run(taskRow ? sidebar.archiveTask(task!.id) : sidebar.archive(chat)) },
];
const overlay = menuOpen
? rowMenu(chat.id, false, entries)
: pops
? beside(
<popover id={`task-popover-${task!.id}`} open={state.popover === task!.id} side="right" width={300} onDismiss={closePopover}>
{besideAnchor()}
{popoverContent(task!.id)}
</popover>,
)
: null;
const rowNode = (
<item opens id={`row-${chat.id}`} onSecondaryClick={() => ctx.run(sidebar.openRowMenu(chat.id, false))} label={editing ? "" : title} selected={selected} onClickAction={{ chatId: opens.id, workspaceId: opens.workspaceId, route: "chat" }} lift background={state.joining === chat.id ? "accent" : undefined} layoutMotion={moves} drag={movable
? { type: taskRow ? "divergence/task" : "divergence/chat", data: taskRow ? { taskId: task!.id, chatId: chat.id } : { chatId: chat.id }, label: title, onEnd: () => ctx.run(sidebar.endDragging()) }
: undefined} drop={dropTarget((zone) => ({ row: chat.id, zone }), chat.id)} sublabel={editing || compact ? undefined : liveLine(chat)} sublabelTone={LIVE_TONE[status]} stacked={!taskRow} actions={editing
? undefined
: [
...(taskRow && !onScreen
? [{ icon: state.expanded.has(task!.id) ? "chevron-down" : "chevron-right", tooltip: state.expanded.has(task!.id) ? "Hide chats" : "Show chats", onClick: () => ctx.run(sidebar.toggleExpanded(task!.id)) }]
: []),
...(!compact || (taskRow && !done)
? [{ icon: pinned ? "pin-off" : "pin", tooltip: pinned ? "Unpin" : "Pin", onClick: () => ctx.run(sidebar.togglePin(chat)) }]
: []),
{ icon: "pencil", tooltip: "Rename", onClick: rename },
{ icon: "archive", tooltip: "Archive", onClick: () => ctx.run(taskRow ? sidebar.archiveTask(task!.id) : sidebar.archive(chat)) },
]} onClick={(event?: ClickEvent) => {
closePopover();
if (!event?.applied) ctx.run(sidebar.select(opens.id, opens.workspaceId));
}} onPointerEnter={() => {
if (!taskRow || !onScreen) ctx.run(sidebar.restOn(opens.id));
if (pops) waitForPopover(task!.id);
}} onPointerLeave={() => {
ctx.run(sidebar.leaveRow(opens.id));
if (pops) leavePopover();
}}>
<slot name="leading">
{glyph(chat, status)}
{overlay}
</slot>
{editing
? renameField(editing)
: (
<div {...row} gap={6}>
{workspaceMark(workspaceMarks.get(chat.workspaceId))}
{ctx.state.cmd && position < 9
? (
<div {...row} justifyContent="center" width={14} height={14} flexShrink={0} background="muted" borderRadius={4}>
<text size={10} weight={500} lineHeight={14} tone="muted">{String(position + 1)}</text>
</div>
)
: taskRow
? <icon name="layers" small tone="muted" />
: <icon name="bot" small tone="faint" svg={agent?.icon} />}
</div>
)}
</item>
);
return rowNode;
}
// A row's menu (document 8): its own entries, then the plugins' after a line.
function rowMenu(chatId: string, child: boolean, entries: { id: string; label: string; key?: string; run: () => void }[]): Element {
// The kernel's list, opened under the row's mark: up, down, Enter and Escape work in it.
const plugins = state.rowMenu?.entries ?? [];
return (
<div position="absolute" left={0} bottom={0}>
<combobox
id="row-menu"
value=""
width={220}
options={entries.map((e) => ({ value: e.id, label: e.label, detail: e.key }))}
actions={plugins.map((e) => ({ label: e.title, onClick: () => ctx.run(sidebar.runRowEntry(e.id, chatId, child)) }))}
onChange={(e: { value?: string }) => entries.find((entry) => entry.id === e.value)?.run()}
>
<div width={1} height={1} />
</combobox>
</div>
);
}
// The popover's wait, its fade on leaving, and its rows. The second's wait
// starts when the pointer comes to rest on the row; leaving both the row
// and the popover closes it after 220ms, and coming back keeps it.
function waitForPopover(taskId: string) {
clearTimeout(popoverTimers.close);
if (state.popover === taskId) {
// Back before the fade ended: it comes back from where the fade got to.
if (state.popoverClosing) {
state.popoverClosing = false;
ctx.update();
}
return;
}
clearTimeout(popoverTimers.open);
popoverTimers.open = setTimeout(() => {
state.popover = taskId;
ctx.update();
}, 1000);
}
function leavePopover() {
clearTimeout(popoverTimers.open);
clearTimeout(popoverTimers.close);
if (state.popover === null) return;
state.popoverClosing = true;
ctx.update();
popoverTimers.close = setTimeout(closePopover, 220);
}
function closePopover() {
clearTimeout(popoverTimers.open);
clearTimeout(popoverTimers.close);
if (state.popover === null) return;
state.popover = null;
state.popoverClosing = false;
ctx.update();
}
function popoverContent(taskId: string): Element {
const task = state.tasks[taskId];
const chats = task ? taskChats(state, task) : [];
const workspaces = new Set(chats.map((c) => c.workspaceId));
return (
<div id="task-popover" {...column} gap={2} padding={4} borderRadius="md" background="card/40" backdrop={{ blur: 6 }} {...RAISED} opacity={0} motion={{ to: { opacity: state.popoverClosing ? 0 : 1 }, duration: state.popoverClosing ? 220 : 150 }} onPointerEnter={() => waitForPopover(taskId)} onPointerLeave={leavePopover}>
{chats.map((member) => {
const status = chatStatus(state, member);
const agent = state.agents.find((a) => a.id === member.agentId);
return (
<item opens id={`popover-chat-${member.id}`} label={chatTitleOf(state, member)} onClickAction={{ chatId: member.id, workspaceId: member.workspaceId, route: "chat" }} {...FLAT} drag={{ type: "divergence/chat", data: { chatId: member.id }, label: chatTitleOf(state, member), onEnd: closePopover }} onClick={(event?: ClickEvent) => {
closePopover();
if (!event?.applied) ctx.run(sidebar.select(member.id, member.workspaceId));
}}>
<slot name="leading">{status === "running" ? <spinner activity /> : <icon name="circle" small tone={TONE[status]} />}</slot>
<div {...row} gap={6}>
{workspaces.size > 1 ? workspaceMark(workspaceMarks.get(member.workspaceId)) : null}
<icon name="bot" small tone="faint" svg={agent?.icon} />
</div>
</item>
);
})}
</div>
);
}
// A task's chats under its row (document 1, Child rows): always while the
// task is on screen, when the user listed them, or the ones a search
// matched. Each opens the task on that chat.
function childRows(chat: Chat): Element[] {
if (!isTaskRow(state, chat)) return [];
const task = taskOf(state, chat.id)!;
const onScreen = activeTask === task.id;
const searching = !!state.query.trim();
if (!onScreen && !state.expanded.has(task.id) && !searching) return [];
const chats = searching && !onScreen && !state.expanded.has(task.id) ? rowMatches(state, chat) : taskChats(state, task);
const workspaces = new Set(taskChats(state, task).map((c) => c.workspaceId));
return chats.map((member) => {
const status = chatStatus(state, member);
const agent = state.agents.find((a) => a.id === member.agentId);
const editing = state.editing?.id === member.id ? state.editing : null;
const menuOpen = state.rowMenu?.chatId === member.id && state.rowMenu.child;
const separate = () => ctx.run(sidebar.placeChat(member.id, { kind: "alone" }));
// Its status mark. A started chat's checks it off on its own: as
// closing its tab does, the chat leaves the task for a row of its own
// in Complete.
const mark = status === "running" ? <spinner activity /> : <icon name="circle" small tone={TONE[status]} />;
const menu = menuOpen
? rowMenu(member.id, true, [
{ id: "row-menu-rename", label: "Rename", run: () => {
state.editing = { id: member.id, title: chatTitleOf(state, member) };
ctx.update();
} },
{ id: "row-menu-separate", label: "Separate from Task", run: separate },
{ id: "row-menu-archive", label: "Archive", run: () => ctx.run(sidebar.archive(member)) },
{ id: "row-menu-close", label: "Close", run: () => ctx.run(sidebar.closeChild(member.id)) },
])
: null;
return (
<item opens id={`child-${member.id}`} onSecondaryClick={() => ctx.run(sidebar.openRowMenu(member.id, true))} label={editing ? "" : chatTitleOf(state, member)} selected={sidebar.nativeApp?.bind?.("chatId", member.id) ?? member.id === app.chatId} onClickAction={{ chatId: member.id, workspaceId: member.workspaceId, route: "chat" }} lift paddingLeft={17 + 8} layoutMotion={moves} drag={{ type: "divergence/chat", data: { chatId: member.id }, label: chatTitleOf(state, member), onEnd: () => ctx.run(sidebar.endDragging()) }} actions={editing
? undefined
: [
{ icon: "pencil", tooltip: "Rename", onClick: () => {
state.editing = { id: member.id, title: chatTitleOf(state, member) };
ctx.update();
} },
{ icon: "archive", tooltip: "Archive", onClick: () => ctx.run(sidebar.archive(member)) },
]} onClick={(event?: ClickEvent) => {
if (!event?.applied) ctx.run(sidebar.select(member.id, member.workspaceId));
}} onPointerEnter={() => ctx.run(sidebar.restOn(member.id))} onPointerLeave={() => ctx.run(sidebar.leaveRow(member.id))}>
<slot name="leading">
{isDraft(state, member) || state.queued.has(member.id)
? <div {...column} alignItems="center" justifyContent="center" width={17} height={17} flexShrink={0}>{mark}</div>
: checkable(`glyph-child-${member.id}`, mark, false, () => ctx.run(sidebar.closeChild(member.id)))}
{menu}
</slot>
{editing
? renameField(editing)
: (
<div {...row} gap={6}>
{workspaces.size > 1 ? workspaceMark(workspaceMarks.get(member.workspaceId)) : null}
<icon name="bot" small tone="faint" svg={agent?.icon} />
</div>
)}
</item>
);
});
}
// The chats by status: Drafts, Queued, Needs you, Running, Finished,
// Open, Complete. Drafts and Complete show a page, then "Show more".
// One flat run of rows, so the list draws only the ones on screen: each
// section's heading, with the room between sections above it, then its
// chats and its "Show more". With `docked`, Complete is pinned at the foot
// of the list (`footer`): its heading, its first rows and its "Show more",
// or, once it is shown whole, its rows end the list and only "Show less"
// stays pinned.
function renderRows(docked: boolean): { rows: Element[]; footer: Element[] } {
let position = 0;
const rows: Element[] = [];
let footer: Element[] = [];
sections(state).forEach((section, index) => {
// A search shows its matches even in a folded section.
const folded = !!state.collapsed[section.id] && !state.query;
const shown = shownChats(state, section);
const more = folded ? 0 : section.chats.length - shown.length;
const heading = (
<div {...column} id={`heading-${section.id}`} layoutMotion={moves} paddingTop={index ? "0.75rem" : 0} drop={LIVE_DRAG ? dropTarget(() => ({ heading: section.id })) : undefined}>
<item heading id={`section-${section.id}`} label={section.label} tone={section.tone} onClick={() => ctx.run(sidebar.toggleSection(section.id))}>
<div {...row} gap={4}>
<text style="body" size={9.84} tone="muted">{String(section.chats.length)}</text>
<icon name={folded ? "chevron-right" : "chevron-down"} small tone="faint" />
</div>
</item>
</div>
);
const chats = shown.flatMap((chat) => [chatRow(chat, position++, section.id), ...childRows(chat)]);
const moreRow = more > 0
? (
<item id={`more-${section.id}`} icon="chevron-down" label="Show more" badge={String(more)} layoutMotion={moves} onClick={() => {
state.showAll[section.id] = true;
ctx.update();
}} />
)
: null;
const lessRow = !folded && state.showAll[section.id] && section.chats.length > pageOf(section.id)
? (
<item id={`less-${section.id}`} icon="chevron-up" label="Show less" layoutMotion={moves} onClick={() => {
state.showAll[section.id] = false;
ctx.update();
}} />
)
: null;
if (docked && section.id === "settled") {
if (lessRow) {
rows.push(heading, ...chats);
footer = [lessRow];
} else footer = [heading, ...chats, ...(moreRow ? [moreRow] : [])];
return;
}
rows.push(heading, ...chats, ...(moreRow ? [moreRow] : lessRow ? [lessRow] : []));
});
if (!rows.length && !footer.length) {
rows.push(
(
<div {...column} gap="small" padding="medium">
<text style="body" size="xs" tone="muted">{state.query ? "No matches" : "No chats yet"}</text>
</div>
),
);
}
return { rows, footer };
}
// --- chips and top actions ---------------------------------------------------
// The workspaces to list, a row like the ones around it: none chosen is
// all of them (every box checked, the folders mark); a choice shows its
// workspaces' own marks and names.
function renderWorkspacePicker() {
const chosen = state.workspaces.filter((w: Workspace) => state.filter.includes(w.id));
return (
<combobox id="workspace-filter" look="row" multiple values={state.filter} all="All workspaces" label={chosen.length ? chosen.map((w: Workspace) => w.name).join(", ") : "All workspaces"} marks={chosen.length ? chosen.slice(0, 3).map(workspaceMarkOf) : [{ icon: "folders" }]} search={state.workspaces.length > 6 ? "Search workspaces…" : undefined} options={state.workspaces.map((w: Workspace) => ({
value: w.id,
label: w.name,
description: w.path,
...workspaceMarkOf(w),
submenu: state.colors.length ? { context: true, ...workspaceLooks(w, state.colors) } : undefined,
}))} actions={[{ label: "Add workspace folder…", icon: "folder-plus", onClick: () => ctx.run(sidebar.addWorkspace()) }]} onChange={(e: { values?: readonly string[]; value?: string; option?: string }) =>
// A choice in a workspace's right-click menu is its look; any
// other change is which workspaces show.
e.option
? ctx.run(sidebar.setColor(e.option, e.value === "icon" ? null : (e.value as PresetColor)))
: ctx.run(sidebar.setFilter([...(e.values ?? [])]))} />
);
}
// A top action such as New chat: 12.2px medium text, and a key cap at the
// end while the shortcut key is held.
// An action row's icon and label sit where a text field puts its icon
// and text, so the search field above lines up.
function actionRow({
id,
icon,
label,
key,
trailing,
onClick,
}: {
id: string;
icon: string;
label: string;
key?: string;
trailing?: Element;
onClick: () => void;
}) {
return <item opens id={id} icon={icon} label={label} onClick={onClick}>{key ? <text keys>{key}</text> : (trailing ?? null)}</item>;
}
// The list as a whole: a drop between rows lands the chat in its place,
// and a pointer that leaves the list takes the chat back where it was.
const listTarget = LIVE_DRAG
? {
types: ["divergence/chat", "divergence/task"],
// A chat of a task of several, a tab carried from the title strip
// among them, has no row to move until it lands. Leaving the list
// ends the list's part of the drag: a drag that started in a pane
// never tells the sidebar it ended.
onOver: (e: DragOverEvent) => {
if (e.zone === null) return ctx.run(sidebar.endDragging());
const carried = carriedChat(e);
if (!inTaskOfSeveral(carried)) ctx.run(sidebar.dragChat(carried, { inside: true }));
},
onDrop: (e: DropEvent) => {
if (!("data" in e)) return;
const carried = carriedChat(e);
if (e.type === "divergence/chat" && inTaskOfSeveral(carried)) return ctx.run(sidebar.placeChat(carried, { kind: "alone" }));
ctx.run(sidebar.dropChat(carried));
},
}
: undefined;
// A list that draws only the rows on screen pins Complete at its foot; a
// kernel without one keeps every section in the flow.
const { rows, footer } = renderRows(!!LIST);
const revealCases = Object.fromEntries(rows.flatMap((row) => {
const id = "id" in row ? row.id : undefined;
return typeof id === "string" && (id.startsWith("row-") || id.startsWith("child-"))
? [[id.slice(id.startsWith("child-") ? 6 : 4), id]] : [];
}));
const reveal = sidebar.nativeApp?.project && sidebar.nativeApp.bind
? sidebar.nativeApp.bind({ key: "chatId", cases: revealCases, default: null })
: app.chatId ? revealCases[app.chatId] : undefined;
const [onlyId] = state.filter;
const filtered = state.filter.length === 1 ? (state.workspaces.find((w) => w.id === onlyId) ?? null) : null;
// The search field's outline lies just outside its box, half a point
// above it, so the box starts half a point down and the outline's top is
// level with the top edge of the chat pane beside it.
return (
<div id="sidebar" {...column} {...fill} {...full} position="relative" padding="small" paddingX="small" paddingTop={0} onModifiersChanged={({ modifiers }: { modifiers: Modifiers }) => {
// A kernel from before `secondary` reports only `meta`, the Mac's Command key.
const held = modifiers.secondary ?? modifiers.meta;
if (!!ctx.state.cmd === held) return;
ctx.state.cmd = held;
ctx.update();
}}>
<canvas position="absolute" left={0} top={0} width="100%" height={1} commands={[]} onResize={(e: { width: number }) => (listWidth = e.width)} />
<div {...column} gap="small" padding="small" paddingY="small" paddingTop={0.5}>
<input id="chat-search" value={state.query} placeholder="Search chats..." icon="search" onChange={(e: { value: string }) => {
state.query = e.value;
ctx.update();
}} />
{actionRow({ id: "new-chat", icon: "plus-large", label: "New chat", key: ctx.state.cmd ? "N" : undefined, onClick: () => ctx.run(sidebar.runCommand("sidebar.newChat")) })}
{renderWorkspacePicker()}
</div>
{LIST
? (
<div {...column} {...fill} paddingX="small" drop={listTarget}>
<scroller id="chat-list" {...LIST} reveal={reveal}>
{rows}
{footer.length
? (
// The list's rows pass under the pinned rows, which blur them
// away with no fill of their own: over the bare ground the
// blur changes nothing, so no box shows at rest.
<slot name="footer"><div {...column} backdrop={{ blur: 20 }}>{footer}</div></slot>
)
: null}
</scroller>
</div>
)
: <div {...column} {...fill} paddingX="small" paddingY="medium" overflowY="scroll" drop={listTarget}>{rows}</div>}
<div {...column} padding="small" paddingY="small">
{state.undo.length
? (
<item id="undo-archive" icon="archive" label={undoLabel(state.undo)} onPointerEnter={() => ctx.run(sidebar.holdNotice(true))} onPointerLeave={() => ctx.run(sidebar.holdNotice(false))}>
<button id="undo-archive-button" label="Undo" variant="ghost" small onClick={() => ctx.run(sidebar.undoArchive())} />
</item>
)
: null}
{filtered
? <item id="remove-workspace" icon="folder-x" label={`Remove ${filtered.name}`} onClick={() => ctx.run(sidebar.removeWorkspace(filtered))} />
: null}
{sidebarItems(app.shared).map((view) => <view view={view} fit />)}
<item opens id="sidebar-settings" icon="settings" label="Settings" onClick={() => ctx.run(sidebar.route("settings"))} />
</div>
</div>
);
}
No comments yet.