340 lines · 16.1 KBRaw
// Search: go to a space or tab (⌘F, ⌘P, the sidebar search icon). Every space, last used
// first: the shown one with its tabs under it, the rest one row each. Type to filter, ↑/↓ and
// Enter to go, ctrl+d to close a tab, Esc to leave. Last rows: new work (a tab here, a space on
// this computer or on each connected machine).
import { View, div, svg, image } from "gpui-kit";
import { v_flex, h_flex, InputState, Input } from "gpui-base";
import { agents, spaces, terminals, panes, run, hc, theme, settings, props, closeOverlay, openOverlay, shared, setShared, home } from "herdr";
// An agent's title without the status glyph before it (as agents-activity's clean()), else its program.
const clean = (s) => (s ?? "").replace(/^[^\p{L}\p{N}\p{Ps}\p{Pi}]+/u, "").replace(/^\[ [!.] \] /, "").trim();
const agentName = (a) => clean(a.title) || a.program?.name || "agent";
const tilde = (d) => (d.startsWith(home()) ? "~" + d.slice(home().length) : d);
// A program's icon as pane-header draws it; a program without one gets the shell's.
function icon(p, size, color) {
if (!p?.icon) return svg("icons/shell.svg").size(size).flex_none().text_color(color);
return p.tint ? svg(p.icon).size(size).flex_none().text_color(color) : image(p.icon).w(size).h(size).flex_none();
}
// A tab's row text. A file tab (named by its full path, by files-tabs): the file's name, and its
// folder from the space's folder, else from ~. An agent tab nobody named: what its agent is doing.
function label(w, ctx, mine, file, doing) {
if (file && ctx.name.startsWith("/")) {
const dir = ctx.name.slice(0, ctx.name.lastIndexOf("/") + 1);
const base = w.folder && dir.startsWith(w.folder + "/") ? dir.slice(w.folder.length + 1) : tilde(dir);
return { name: ctx.name.slice(dir.length), dir: base, file: true };
}
return { name: !ctx.named && mine.length ? doing(mine[0]) : ctx.name, dir: "" };
}
const MARK = { ansi6: "#22a99a", ansi3: "#e3814f", ansi4: "#5b8def", ansi5: "#8b7cf6", ansi2: "#3fae6a", ansi1: "#d9649a" };
// Space colors, kept by space id in shared "space.colors": a theme
// color name ("ansi6") or a picked #rrggbb. A space seen without one gets
// the theme color fewest spaces use, once; every mod does the same in the
// same order, so they agree, and adding or renaming spaces moves nothing.
const PROJECT_COLORS = ["ansi6", "ansi3", "ansi4", "ansi5", "ansi2", "ansi1", "#883c00", "#792798", "#09672e", "#977e0d", "#ad215f", "#8e7699", "#c43b15", "#527d65", "#3e42b6", "#026fd7"];
function spaceColors() {
const ids = new Set(spaces().map((p) => p.id));
const kept = Object.fromEntries(Object.entries(shared("space.colors") ?? {}).filter(([id]) => ids.has(id)));
let changed = Object.keys(kept).length !== Object.keys(shared("space.colors") ?? {}).length;
for (const p of spaces()) {
if (kept[p.id] || p.name === "~") continue;
const uses = (c) => Object.values(kept).filter((v) => v === c).length;
kept[p.id] = PROJECT_COLORS.reduce((best, c) => (uses(c) < uses(best) ? c : best));
changed = true;
}
if (changed) setShared("space.colors", kept);
return kept;
}
function spaceColor(t, p) {
if (p.name === "~") return t.dim;
const c = spaceColors()[p.id] ?? PROJECT_COLORS[0];
return c.startsWith("#") ? c : (MARK[c] ?? t[c]);
}
export default class Picker extends View {
init(_props, cx) {
this.filter = "";
this.input = InputState.new({ placeholder: "Go to a tab, space or agent…" });
this.input.on("change", (_e, cx) => {
this.filter = this.input.value();
this.previous = null;
this.at =this.filter ? Math.max(0, this.rows().filter(r => r.kind !== "head").findIndex(r => r.kind === "ctx")) : 0;
cx.notify();
});
this.input.on("submit", (_e, cx) => this.go(this.rows().filter(r => r.kind !== "head")[this.at], cx));
this.input.focus();
cx.timer.after(600, () => this.input.focus());
this.at = null;
this.scroll = 0;
this.showEarlier = false;
this.machines = [];
this.handle = cx.focus_handle();
cx.spawn(async (cx) => {
try {
const r = await hc(["machine", "ls", "--json"]);
if (r.code === 0) this.machines = (JSON.parse(r.stdout).machines ?? []).filter((m) => m.state === "connected" && !m.temporary).map((m) => m.name);
} catch {}
cx.notify();
});
}
close() {
closeOverlay(props().overlay);
}
rows() {
const f = this.filter.toLowerCase();
const all = agents();
const live = terminals().filter((x) => x.state === "live");
const teamOf = (addrs) => {
let n = 0;
const walk = (a) => live.filter((x) => x.parent === a).forEach((k) => (n++, walk(k.address)));
addrs.forEach(walk);
return n;
};
const allPanes = panes();
const fileTabs = new Set(allPanes.filter((p) => p.mod === "file-view").map((p) => p.tab));
// A tab's program: its first agent's, else its first terminal's.
const progOf = (id) => (allPanes.find((p) => p.tab === id && p.program?.agent) ?? allPanes.find((p) => p.tab === id && p.terminal))?.program;
// What an agent is doing, as the sidebar says it (agents-activity): the herdr-activity hook's
// label, else its title, else its program.
const doing = (a) => live.find((x) => x.address === a.address)?.labels?.["kit.activity"] || agentName(a);
const groups = spaces().map((w) => {
const ctxs = w.tabs
.map((ctx) => {
const mine = all.filter((a) => a.tab === ctx.id);
return { w, ctx, mine, prog: progOf(ctx.id), team: teamOf(mine.map((a) => a.address)), ...label(w, ctx, mine, fileTabs.has(ctx.id), doing) };
})
.filter((c) => !f || [w.name, c.name, c.dir, ...c.mine.map(doing)].join(" ").toLowerCase().includes(f));
return { w, ctxs };
});
// Last used first (stamped in shared "space.used" by agents-activity); never-used keep the app's order.
const used = shared("space.used") ?? {};
const shown = groups.filter((p) => p.ctxs.length).sort((a, b) => (used[b.w.id] ?? 0) - (used[a.w.id] ?? 0));
const out = [];
// The shown space, and while filtering any space with several tabs, lists its tabs under its
// name. Any other space is one row: its name and what its agent is doing (never just a
// program's name); it goes to its shown tab.
const add = (p) => {
if (!p.w.active && !(f && p.w.tabs.length > 1)) {
const c = p.ctxs.find((c) => c.ctx.active) ?? p.ctxs[0];
const task = all
.filter((a) => a.space === p.w.id)
.map(doing)
.find((s) => !all.some((a) => a.program?.name === s));
return out.push({ kind: "ctx", solo: true, ...c, task: task ?? "", status: p.w.status });
}
out.push({ kind: "head", w: p.w });
p.ctxs.forEach((c, i) => out.push({ kind: "ctx", ...c, status: c.ctx.status, last: i === p.ctxs.length - 1 }));
};
shown.forEach(add);
out.push({ kind: "new" });
out.push({ kind: "space", machine: null });
for (const m of this.machines) out.push({ kind: "space", machine: m });
return out;
}
go(r, cx) {
if (!r) return;
if (r.kind === "earlier") {
this.at = this.rows().filter(r => r.kind !== "head").findIndex(r => r.kind === "earlier");
this.showEarlier = !this.showEarlier;
this.input.focus();
cx.notify();
return;
}
this.close();
if (r.kind === "ctx") run("tab.select", { id: r.ctx.id });
else if (r.kind === "new") run("tab.new");
else if (r.kind === "space") run("space.new", r.machine ? { machine: r.machine } : { machine: "", folder: `${home()}/Developer/projects` });
}
glyph(t, st) {
if (st === "working") return svg("mods/workspace-chrome/spinner.svg").size(12).flex_none().text_color(t.working).spin(900);
return div().w(12).flex_none().text_color(t[st] ?? t.dim).child("●");
}
render() {
const t = theme();
const rows = this.rows();
const pickable = rows.filter((r) => r.kind !== "head");
// Opens on the space before this one, so ⌘F then Enter goes back; that row says so ("↵ previous")
// until the selection moves or a filter is typed.
if (this.at === null) this.at = this.previous = Math.max(0, pickable.findIndex((r) => r.kind === "ctx" && !r.w.active));
this.at = Math.min(this.at, pickable.length - 1);
const sel = pickable[this.at];
// Moving the pointer onto a row selects it, so the selection is the only highlight. Only real
// movement does: a row that slides under a still pointer (typing, the arrows) doesn't.
const follow = (r) => (_e, cx) => {
const i = pickable.indexOf(r);
if (i === this.at) return;
this.at = i;
this.previous = null;
cx.notify();
};
// One continuous strip: each row (and the group title before it) at a fixed
// y. Scrolling moves the strip only as far as it takes to keep the selected
// row in view, so the arrows can't run the selection off the list.
const H = { head: 29, earlier: 35, new: 36, ctx: 32, space: 32 };
const tops = [];
let y = 0;
rows.forEach((r) => { tops.push(y); y += H[r.kind] ?? 32; });
const total = y;
const height = Math.min(320, this.listHeight ?? 320);
const fixed = total > height;
const maxScroll = Math.max(0, total - height);
this.scroll = Math.max(0, Math.min(this.scroll, maxScroll));
const si = rows.indexOf(sel);
if (si >= 0) {
if (tops[si] < this.scroll) this.scroll = tops[si];
if (tops[si] + (H[sel.kind] ?? 32) > this.scroll + height) this.scroll = tops[si] + (H[sel.kind] ?? 32) - height;
}
const place = (el, i) =>
fixed
? el.absolute().left(0).right(0).top(tops[i] - this.scroll).bottom(height - (tops[i] + (H[rows[i].kind] ?? 32) - this.scroll))
: el;
const visible = (i) => !fixed || (tops[i] + (H[rows[i].kind] ?? 32) > this.scroll && tops[i] < this.scroll + height);
const row = (r) => {
const badge = (w) => h_flex().size(18).flex_none().rounded(5).bg(spaceColor(t, w)).items_center().justify_center().text_size(10.5).font_bold().text_color("#ffffff").child([...w.name][0]?.toUpperCase() ?? "?");
if (r.kind === "head") {
return h_flex()
.px(10)
.pt(10)
.pb(3)
.gap(8)
.items_center()
.text_size(11)
.font_semibold()
.text_color(t.dim)
.child(h_flex().size(18).rounded(5).bg(spaceColor(t, r.w)).items_center().justify_center().text_size(10.5).font_bold().text_color("#ffffff").child([...r.w.name][0]?.toUpperCase() ?? "?"))
.child(r.w.name);
}
if (r.kind === "earlier") {
return h_flex()
.id("pk-earlier")
.mt(6)
.px(10)
.py(6)
.border_t(1)
.border_color(t.border)
.text_size(12)
.text_color(t.dim)
.cursor_pointer()
.when(r === sel, (el) => el.bg(t.hover).text_color(t.foreground))
.on_mouse_move(follow(r))
.on_click((_e, cx) => this.go(r, cx))
.child(`earlier: ${r.count} quiet space${r.count > 1 ? "s" : ""} ${this.showEarlier ? "▴" : "▾"}`);
}
const on = r === sel;
if (r.kind === "new" || r.kind === "space") {
const label = r.kind === "new" ? "new tab" : r.machine ? `new space on ${r.machine}` : "new space";
return h_flex()
.id(r.kind === "new" ? "pk-new" : `pk-space-${r.machine ?? "here"}`)
.mx(4)
.when(r.kind === "new", (el) => el.mt(4))
.px(10)
.h(32)
.items_center()
.rounded(7)
.gap(8)
.text_color(t.muted)
.cursor_pointer()
.when(on, (el) => el.bg(t.hover))
.on_mouse_move(follow(r))
.on_click(() => this.go(r))
.child(div().w(12).child("+"))
.child(label);
}
const here = r.w.active && r.ctx.active;
// A space's one row: tile, name, its agent's title. A tab under its space: indented on a guide
// line, a file icon on a file tab, then its name and (for a file) its folder, dimmed.
return h_flex()
.id(`pk-${r.ctx.id}`)
.relative()
.mx(4)
.px(10)
.when(!r.solo, (el) => el.pl(38))
.h(32)
.rounded(7)
.gap(10)
.items_center()
.cursor_pointer()
.when(on, (el) => el.bg(t.hover))
.on_mouse_move(follow(r))
.on_click(() => this.go(r))
.when(Boolean(r.solo), (el) => el.child(badge(r.w)))
// The branch, ├ or └ on the last tab: down from under the space's tile (its center, 4px
// left of this row's), and a tick across to the row's middle.
.when(!r.solo, (el) => el
.child(div().absolute().left(15).top(0).when(r.last, (d) => d.h(16)).when(!r.last, (d) => d.bottom(0)).w(1).bg(t.dim))
.child(div().absolute().left(15).top(16).w(14).h(1).bg(t.dim)))
.when(!r.solo, (el) => el.child(r.file ? svg("mods/files-tabs/file.svg").size(14).flex_none().text_color(t.muted) : icon(r.prog, 14, t.muted)))
.child(
h_flex().flex_1().min_w(0).gap(8).items_center()
.child(div().flex_none().text_color(t.foreground).when(here, (d) => d.font_semibold()).child(r.solo ? r.w.name : r.name))
.child(div().flex_1().min_w(0).truncate().text_color(t.dim).child(r.solo ? (r.task ? `— ${r.task}` : "") : r.dir)),
)
.when(r.status && r.status !== "idle", (el) => el.child(this.glyph(t, r.status)))
.when(r.status === "blocked", (el) => el.child(div().text_size(11).text_color(t.blocked).child("needs you")))
.when(r.status === "done", (el) => el.child(div().text_size(11).text_color(t.done).child("finished")))
.when(Boolean(r.team), (el) => el.child(div().text_size(11).text_color(t.dim).child(`+${r.team}`)))
.when(on && this.at === this.previous, (el) => el.child(div().flex_none().text_size(11).text_color(t.dim).child("↵ previous")));
};
return v_flex()
.id("picker")
.track_focus(this.handle)
.w_full()
.min_h(0)
.p(18)
.gap(10)
.bg(t.popover)
.text_size(13)
.on_key_down((e, cx) => {
const k = e.key;
if (k === "escape") return this.close();
if (k === "down" || k === "up") this.previous = null;
if (k === "down") this.at = (this.at + 1) % pickable.length;
else if (k === "up") this.at = (this.at + pickable.length - 1) % pickable.length;
else if (k === "d" && e.modifiers.control) {
if (sel?.kind === "ctx") {
this.close();
run("tab.close", { id: sel.ctx.id });
}
} else return;
cx.stop_propagation();
cx.notify();
})
.child(h_flex().items_center().child(div().flex_1().text_size(15).font_semibold().text_color(t.foreground).child("Search")).child(div().id("picker-esc").px(6).py(2).rounded(5).text_size(11).text_color(t.dim).cursor_pointer().hover((s) => s.bg(t.hover).text_color(t.foreground)).on_click(() => this.close()).child("Esc")))
.child(
h_flex().h(36).flex_none().px(10).gap(8).items_center().rounded(9).border_1().border_color(t.accent).bg(t.background)
.child(svg("mods/workspace-chrome/search.svg").size(15).text_color(t.dim))
.child(Input.new(this.input).flex_1().h_full().text_size(12.8).text_color(t.foreground)),
)
.child(
v_flex()
.id("pk-list")
.on_size_change((size, cx) => {
this.listHeight = size.height / settings().zoom;
cx.notify();
})
.h(Math.min(320, total))
.min_h(0)
.mb(6)
.when(fixed, (el) =>
el.overflow_hidden().on_scroll_wheel((e, cx) => {
this.scroll = Math.max(0, Math.min(this.scroll - e.delta.y, maxScroll));
// The selection follows the wheel, so the next frame doesn't scroll back to it.
while (this.at < pickable.length - 1 && tops[rows.indexOf(pickable[this.at])] < this.scroll) this.at++;
while (this.at > 0 && tops[rows.indexOf(pickable[this.at])] + (H[pickable[this.at].kind] ?? 32) > this.scroll + height) this.at--;
cx.notify();
}))
.children(rows.map((r, i) => (visible(i) ? place(row(r), i) : null)).filter(Boolean)),
);
}
}