558 lines
21 KiB
TypeScript
558 lines
21 KiB
TypeScript
import "./style.css";
|
|
import { createNest, getCrows, getNests, getTrust, listEvents, postList, postVerdict, type Nest, type Persona, type TrustLevels } from "./api";
|
|
import { crowAvatar, svgCrow, type CrowView, type Role } from "./crow";
|
|
|
|
// ---------- page ----------
|
|
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
|
|
const roster = $<HTMLDivElement>("roster");
|
|
const feedsBox = $<HTMLDivElement>("feeds");
|
|
const nestNav = $<HTMLElement>("nests");
|
|
const typing = $<HTMLParagraphElement>("typing");
|
|
const form = $<HTMLFormElement>("composer");
|
|
const listInput = $<HTMLTextAreaElement>("list");
|
|
const sendBtn = $<HTMLButtonElement>("send");
|
|
const requesterInput = $<HTMLInputElement>("requester");
|
|
|
|
const store = {
|
|
get(k: string) { try { return localStorage.getItem(k); } catch { return null; } },
|
|
set(k: string, v: string) { try { localStorage.setItem(k, v); } catch { /* storage off */ } },
|
|
};
|
|
requesterInput.value = store.get("requester") ?? "";
|
|
requesterInput.addEventListener("change", () => store.set("requester", requesterInput.value.trim()));
|
|
listInput.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); form.requestSubmit(); }
|
|
});
|
|
|
|
function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string) {
|
|
const e = document.createElement(tag);
|
|
if (cls) e.className = cls;
|
|
if (text !== undefined) e.textContent = text; // server text always goes in as text, never HTML
|
|
return e;
|
|
}
|
|
|
|
// ---------- the roster: one list tile per crow, latest update first ----------
|
|
type Tile = { view: CrowView; el: HTMLDivElement; update: HTMLParagraphElement; time: HTMLTimeElement; count: HTMLSpanElement; pending: Set<string> };
|
|
const tiles = new Map<string, Tile>();
|
|
let trust: TrustLevels = new Map();
|
|
let seq = 0;
|
|
let personas = new Map<string, Persona>();
|
|
|
|
function roleOf(name: string): Role {
|
|
return name === "Sentry" ? "sentry" : name === "Elder" ? "elder" : "crow";
|
|
}
|
|
|
|
function tile(name: string): Tile {
|
|
let t = tiles.get(name);
|
|
if (!t) {
|
|
const view = svgCrow(name, roleOf(name)); // the live, animated crow is the tile's avatar
|
|
const box = el("div", `tile role-${roleOf(name)}`);
|
|
const text = el("div", "tile-text");
|
|
const update = el("p", "update", name === "Sentry" ? "On watch" : "Perched");
|
|
const nameLine = el("p", "tile-name", name);
|
|
const epithet = el("span", "epithet");
|
|
nameLine.append(epithet);
|
|
text.append(nameLine, update);
|
|
const meta = el("div", "tile-meta");
|
|
const time = el("time", "tile-time");
|
|
const count = el("span", "tile-count");
|
|
meta.append(time, count);
|
|
box.append(view.el, text, meta);
|
|
roster.append(box);
|
|
t = { view, el: box, update, time, count, pending: new Set() };
|
|
tiles.set(name, t);
|
|
applyPersona(name);
|
|
}
|
|
return t;
|
|
}
|
|
|
|
// Epithet beside the name; the backstory on hover.
|
|
function applyPersona(name: string) {
|
|
const t = tiles.get(name);
|
|
const p = personas.get(name);
|
|
if (!t || !p) return;
|
|
t.el.querySelector(".epithet")!.textContent = ` · ${p.epithet}`;
|
|
t.el.title = p.backstory;
|
|
}
|
|
|
|
function crow(name: string): CrowView {
|
|
return tile(name).view;
|
|
}
|
|
|
|
// Each crow's latest update; the most recently updated tile moves to the top.
|
|
type Kind = "" | "waiting" | "good" | "bad";
|
|
function update(name: string, text: string, ts?: string, kind: Kind = "") {
|
|
const t = tile(name);
|
|
t.update.textContent = text;
|
|
t.update.className = `update ${kind}`.trim();
|
|
t.time.textContent = fmtTime(ts);
|
|
t.el.style.order = String(-(++seq));
|
|
renderWaitingCount();
|
|
}
|
|
|
|
// What each crow still owes a verdict on. Independent of its latest update,
|
|
// so a newer update never hides an open question.
|
|
function pending(name: string, key: string, open: boolean) {
|
|
const t = tile(name);
|
|
if (open) t.pending.add(key); else t.pending.delete(key);
|
|
const n = t.pending.size;
|
|
t.count.textContent = n ? `${n} waiting` : "";
|
|
t.el.classList.toggle("has-pending", n > 0);
|
|
renderWaitingCount();
|
|
}
|
|
|
|
// Phone tab badge: how many crows are waiting on you.
|
|
const flockTab = document.getElementById("tab-flock");
|
|
function renderWaitingCount() {
|
|
const n = [...tiles.values()].filter((t) => t.pending.size > 0).length;
|
|
if (flockTab) flockTab.dataset.count = n ? String(n) : "";
|
|
}
|
|
|
|
const q = (s: string) => `“${s}”`;
|
|
|
|
// Badges show trust for the task type the crow is working on now.
|
|
function showTrust(name: string, taskType: string) {
|
|
const key = name === "Sentry" ? `Sentry|triage/${taskType}` : `${name}|${taskType}`;
|
|
crow(name).setTrust(trust.get(key) ?? 0);
|
|
}
|
|
|
|
// ---------- the feed: messages from you, the Sentry, the crows ----------
|
|
type Msg = { li: HTMLLIElement; body: HTMLDivElement; actions: HTMLDivElement; reactions: HTMLDivElement };
|
|
|
|
const ROLE_TAG: Partial<Record<Role, string>> = { sentry: "sorts the list", elder: "merges reports" };
|
|
|
|
function fmtTime(ts?: string) {
|
|
const d = ts ? new Date(ts) : new Date();
|
|
return isNaN(+d) ? "" : d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
|
|
}
|
|
|
|
// ---------- nests: one room (and one feed) per team ----------
|
|
type NestRoom = Nest & { feed: HTMLOListElement; link: HTMLButtonElement; count: HTMLSpanElement };
|
|
const nests = new Map<string, NestRoom>();
|
|
let flockNames: string[] = [];
|
|
let current = "todo";
|
|
const roomTitle = $<HTMLHeadingElement>("room-title");
|
|
const roomSub = $<HTMLParagraphElement>("room-sub");
|
|
const roomTab = $<HTMLButtonElement>("tab-room");
|
|
|
|
function addNest(n: Nest): NestRoom {
|
|
const feed = el("ol", "feed");
|
|
feed.setAttribute("aria-live", "polite");
|
|
feed.hidden = true;
|
|
feedsBox.append(feed);
|
|
const link = el("button", "nest-link");
|
|
link.type = "button";
|
|
const count = el("span", "nest-count");
|
|
link.append(el("span", "nest-name", `# ${n.name}`), count);
|
|
link.addEventListener("click", () => { selectNest(n.nestId); showView("room"); });
|
|
nestNav.append(link);
|
|
const room = { ...n, feed, link, count };
|
|
nests.set(n.nestId, room);
|
|
return room;
|
|
}
|
|
|
|
function nest(id: string): NestRoom {
|
|
return nests.get(id) ?? nests.get("todo")!;
|
|
}
|
|
|
|
function selectNest(id: string) {
|
|
current = nest(id).nestId;
|
|
for (const r of nests.values()) {
|
|
r.feed.hidden = r.nestId !== current;
|
|
r.link.setAttribute("aria-current", String(r.nestId === current));
|
|
}
|
|
const r = nest(current);
|
|
roomTitle.textContent = `# ${r.name}`;
|
|
roomSub.textContent = r.crows.length
|
|
? `Core crows: ${r.crows.join(", ")}. The Sentry borrows others when a job needs more hands.`
|
|
: "The whole flock roosts here. Hand it a list: the Sentry sorts it, crows fly, you judge.";
|
|
roomTab.textContent = `# ${r.name}`;
|
|
r.feed.scrollTop = r.feed.scrollHeight;
|
|
renderTyping();
|
|
}
|
|
|
|
// Red count on each nest: questions waiting on you in that room.
|
|
function renderNestCounts() {
|
|
for (const r of nests.values()) {
|
|
const n = r.feed.querySelectorAll(".msg.asking").length;
|
|
r.count.textContent = n ? String(n) : "";
|
|
}
|
|
}
|
|
|
|
function append(li: HTMLLIElement, nestId: string) {
|
|
const feed = nest(nestId).feed;
|
|
const stick = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 120;
|
|
feed.append(li);
|
|
if (stick) feed.scrollTop = feed.scrollHeight;
|
|
}
|
|
|
|
function post(author: string, parts: Node[], ts: string | undefined, nestId: string): Msg {
|
|
const li = el("li", "msg");
|
|
li.dataset.author = author;
|
|
const last = nest(nestId).feed.lastElementChild as HTMLElement | null;
|
|
if (last?.dataset.author === author) li.classList.add("cont");
|
|
let avatar: Element;
|
|
if (author === "you") {
|
|
const who = requesterInput.value.trim() || "you";
|
|
avatar = el("span", "avatar you", who.charAt(0).toUpperCase());
|
|
} else {
|
|
avatar = crowAvatar(roleOf(author));
|
|
}
|
|
const head = el("div", "msg-head");
|
|
head.append(el("span", "author", author === "you" ? requesterInput.value.trim() || "You" : author));
|
|
const tag = personas.get(author)?.epithet ?? ROLE_TAG[roleOf(author)];
|
|
if (author !== "you" && tag) head.append(el("span", "tag", tag));
|
|
const time = el("time", "", fmtTime(ts));
|
|
head.append(time);
|
|
const body = el("div", "msg-body");
|
|
body.append(...parts);
|
|
const actions = el("div", "actions");
|
|
const reactions = el("div", "reactions");
|
|
const main = el("div", "msg-main");
|
|
main.append(head, body, actions, reactions);
|
|
li.append(avatar, main);
|
|
append(li, nestId);
|
|
return { li, body, actions, reactions };
|
|
}
|
|
|
|
function note(text: string, nestId: string, kind = "") {
|
|
const li = el("li", `msg system ${kind}`.trim());
|
|
li.append(el("p", "", text));
|
|
append(li, nestId);
|
|
}
|
|
|
|
// Banter: a small aside between crows, kept visually apart from the work.
|
|
function aside(speaker: string, to: string, text: string, nestId: string) {
|
|
const li = el("li", "msg banter");
|
|
li.append(crowAvatar(roleOf(speaker)));
|
|
const body = el("p", "banter-line");
|
|
body.append(el("span", "banter-who", `${speaker} to ${to}`), el("span", "banter-text", text));
|
|
li.append(body);
|
|
append(li, nestId);
|
|
}
|
|
|
|
function re(text: string) {
|
|
return el("p", "re", `re: ${text}`);
|
|
}
|
|
|
|
function react(m: Msg, text: string, kind: string) {
|
|
m.reactions.append(el("span", `reaction ${kind}`, text));
|
|
}
|
|
|
|
// ---------- per-item state ----------
|
|
type Item = { text: string; nest: string; crows: string[]; borrowed: Set<string>; taskType: string; triage?: Msg; answer?: Msg };
|
|
const items = new Map<string, Item>();
|
|
|
|
function ask(m: Msg, itemId: string, target: "triage" | "output") {
|
|
m.li.classList.add("asking");
|
|
m.actions.replaceChildren();
|
|
const yes = el("button", "btn btn-go inked", target === "triage" ? "Proceed" : "Looks good");
|
|
const no = el("button", "btn btn-no inked", target === "triage" ? "Deny" : "Not right");
|
|
const err = el("p", "err");
|
|
for (const [b, approve] of [[yes, true], [no, false]] as const) {
|
|
b.type = "button";
|
|
b.addEventListener("click", async () => {
|
|
yes.disabled = no.disabled = true;
|
|
err.textContent = "";
|
|
try {
|
|
await postVerdict(itemId, target, approve);
|
|
} catch (e) {
|
|
err.textContent = (e as Error).message;
|
|
yes.disabled = no.disabled = false;
|
|
}
|
|
});
|
|
}
|
|
m.actions.append(yes, no, err);
|
|
renderNestCounts();
|
|
}
|
|
|
|
// ---------- who's flying ----------
|
|
const flying = new Set<string>();
|
|
let flyingNest = "";
|
|
function renderTyping() {
|
|
const names = flyingNest === current ? [...flying] : [];
|
|
if (names.length === 0) { typing.textContent = ""; return; }
|
|
const who = names.length === 1 ? names[0]
|
|
: names.length === 2 ? `${names[0]} and ${names[1]}`
|
|
: `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;
|
|
typing.textContent = `${who} ${names.length === 1 ? "is" : "are"} flying…`;
|
|
}
|
|
|
|
// ---------- events (mapping from RIVE_CONTRACT.md section 3) ----------
|
|
type Payload = Record<string, any>;
|
|
let source: EventSource | null = null;
|
|
const LEVELS = ["stranger", "regular", "trusted"];
|
|
|
|
const handlers: Record<string, (d: Payload) => void> = {
|
|
"list.started": (d) => {
|
|
const nestId = nests.has(d.nest_id) ? d.nest_id : sendingNest;
|
|
flyingNest = nestId;
|
|
const ol = el("ol", "list");
|
|
for (const it of d.items ?? []) {
|
|
items.set(it.item_id, { text: it.text, nest: nestId, crows: [], borrowed: new Set(), taskType: "other" });
|
|
ol.append(el("li", "", it.text));
|
|
}
|
|
post("you", [ol], d.ts, nestId);
|
|
crow("Sentry").setPose("perched");
|
|
const n = (d.items ?? []).length;
|
|
update("Sentry", `Got a list of ${n} item${n === 1 ? "" : "s"}`, d.ts);
|
|
},
|
|
|
|
"item.triaged": (d) => {
|
|
const it = items.get(d.item_id);
|
|
if (!it) return;
|
|
it.taskType = d.task_type;
|
|
const parts: Node[] = [re(it.text), el("p", "plan", `${d.mode} · ${d.task_type}`)];
|
|
if (d.reason) parts.push(el("p", "reason", d.reason));
|
|
if (d.subtasks?.length) {
|
|
const ul = el("ul");
|
|
for (const s of d.subtasks) ul.append(el("li", "", s));
|
|
parts.push(ul);
|
|
}
|
|
it.triage = post("Sentry", parts, d.ts, it.nest);
|
|
showTrust("Sentry", d.task_type);
|
|
if (d.needs_approval) {
|
|
crow("Sentry").setPose("waiting");
|
|
ask(it.triage, d.item_id, "triage");
|
|
update("Sentry", `Waiting on you: plan for ${q(it.text)}`, d.ts, "waiting");
|
|
pending("Sentry", `${d.item_id}/triage`, true);
|
|
} else {
|
|
update("Sentry", `Sorted ${q(it.text)}`, d.ts);
|
|
}
|
|
},
|
|
|
|
"crow.flying": (d) => {
|
|
const it = items.get(d.item_id);
|
|
if (it && d.crow !== "Sentry") showTrust(d.crow, it.taskType);
|
|
crow(d.crow).setPose("flying");
|
|
if (it) {
|
|
if (d.borrowed) it.borrowed.add(d.crow);
|
|
const doing = d.crow === "Sentry" ? "Sorting" : d.crow === "Elder" ? "Merging reports on" : "Flying";
|
|
const where = d.borrowed ? ` (borrowed for # ${nest(it.nest).name})` : "";
|
|
update(d.crow, `${doing}${where}${doing === "Flying" ? ":" : ""} ${q(it.text)}`, d.ts);
|
|
}
|
|
flying.add(d.crow);
|
|
renderTyping();
|
|
},
|
|
|
|
"crow.landed": (d) => {
|
|
crow(d.crow).setPose(d.ok ? "perched" : "grounded");
|
|
const it = items.get(d.item_id);
|
|
if (it && !d.ok) update(d.crow, `Grounded on ${q(it.text)}`, d.ts, "bad");
|
|
else if (it && d.crow !== "Sentry" && d.crow !== "Elder") update(d.crow, `Reported back on ${q(it.text)}`, d.ts);
|
|
flying.delete(d.crow);
|
|
renderTyping();
|
|
},
|
|
|
|
"item.answered": (d) => {
|
|
const it = items.get(d.item_id);
|
|
if (!it) return;
|
|
it.crows = d.crows ?? [];
|
|
const author = it.crows.includes("Elder") ? "Elder" : it.crows[0] ?? "Elder";
|
|
const parts: Node[] = [re(it.text), el("p", "answer", d.answer)];
|
|
const helpers = it.crows.filter((n) => n !== "Elder");
|
|
const named = helpers.map((n) => (it.borrowed.has(n) ? `${n} (borrowed)` : n));
|
|
if (author === "Elder" && helpers.length) parts.push(el("p", "with", `from ${named.join(", ")}`));
|
|
it.answer = post(author, parts, d.ts, it.nest);
|
|
if (d.needs_approval) {
|
|
for (const n of it.crows) {
|
|
crow(n).setPose("waiting");
|
|
update(n, `Waiting on you: ${q(it.text)}`, d.ts, "waiting");
|
|
pending(n, `${d.item_id}/output`, true);
|
|
}
|
|
ask(it.answer, d.item_id, "output");
|
|
}
|
|
},
|
|
|
|
verdict: (d) => {
|
|
const it = items.get(d.item_id);
|
|
if (!it) return;
|
|
for (const n of d.target === "triage" ? ["Sentry"] : it.crows) pending(n, `${d.item_id}/${d.target}`, false);
|
|
const m = d.target === "triage" ? it.triage : it.answer;
|
|
const good = d.verdict === "approved" || d.verdict === "auto";
|
|
if (m) {
|
|
m.li.classList.remove("asking");
|
|
m.actions.replaceChildren();
|
|
const label: Record<string, [string, string]> = {
|
|
approved: ["✓ Approved", "good"], rejected: ["✕ Rejected", "bad"],
|
|
auto: ["✓ Trusted, no review", "auto"], timeout: ["⌛ Timed out", "bad"],
|
|
};
|
|
const [text, kind] = label[d.verdict] ?? [d.verdict, ""];
|
|
react(m, text, kind);
|
|
renderNestCounts();
|
|
}
|
|
if (d.target === "triage" && d.verdict === "auto") return; // a trusted Sentry just keeps going
|
|
const word: Record<string, string> = { approved: "Approved", rejected: "Rejected", auto: "Accepted (trusted)", timeout: "Timed out" };
|
|
for (const n of d.target === "triage" ? ["Sentry"] : it.crows) {
|
|
crow(n).fire(good ? "cheer" : "sulk");
|
|
crow(n).setPose(tile(n).pending.size ? "waiting" : "perched");
|
|
const what = d.target === "triage" ? `plan for ${q(it.text)}` : q(it.text);
|
|
update(n, `${word[d.verdict] ?? d.verdict}: ${what}`, d.ts, good ? "good" : "bad");
|
|
}
|
|
},
|
|
|
|
"trust.changed": (d) => {
|
|
trust.set(`${d.holder}|${d.task_type}`, d.to);
|
|
const what = String(d.task_type).replace("triage/", "sorting ");
|
|
const up = d.to > d.from;
|
|
if (d.holder === "flock") {
|
|
note(`The flock ${up ? "earned" : "dropped to"} “${LEVELS[d.to]}” on ${what}.`, flyingNest || current, up ? "sparkle" : "");
|
|
return;
|
|
}
|
|
const c = crow(d.holder);
|
|
c.setTrust(d.to);
|
|
c.fire(up ? "levelUp" : "levelDown");
|
|
update(d.holder, `${up ? "Leveled up to" : "Dropped to"} ${LEVELS[d.to]} on ${what}`, d.ts, up ? "good" : "bad");
|
|
note(`${d.holder} ${up ? "leveled up to" : "dropped to"} “${LEVELS[d.to]}” on ${what}.`, flyingNest || current, up ? "sparkle" : "");
|
|
},
|
|
|
|
"item.skipped": (d) => {
|
|
const it = items.get(d.item_id);
|
|
note(`Skipped “${it?.text ?? d.item_id}”: ${d.reason}.`, it?.nest ?? flyingNest ?? current);
|
|
renderNestCounts();
|
|
for (const n of it?.crows ?? []) crow(n).setPose("perched");
|
|
update("Sentry", `Skipped ${q(it?.text ?? d.item_id)}`, d.ts, "bad");
|
|
},
|
|
|
|
"crow.banter": (d) => {
|
|
const it = items.get(d.item_id);
|
|
aside(d.crow, d.to, d.text, it?.nest ?? flyingNest ?? current);
|
|
},
|
|
|
|
"requester.pranked": (d) => prank(d.message, d.cooldown_s),
|
|
|
|
"list.finished": (d) => {
|
|
for (const t of tiles.values()) { t.view.setPose("perched"); t.view.fire("cheer"); }
|
|
flying.clear();
|
|
renderTyping();
|
|
note(`List done. The flock used ${Number(d.tokens_used).toLocaleString()} of ${Number(d.token_budget).toLocaleString()} tokens.`, flyingNest || current);
|
|
flyingNest = "";
|
|
source?.close();
|
|
source = null;
|
|
sendBtn.disabled = false;
|
|
},
|
|
};
|
|
|
|
// ---------- pranks: the Sentry says something, the send button counts down ----------
|
|
let cooldownTimer = 0;
|
|
const sendLabel = sendBtn.textContent ?? "Send";
|
|
function prank(message: string, cooldownS: number) {
|
|
crow("Sentry").fire("prank");
|
|
post("Sentry", [el("p", "", message)], undefined, current);
|
|
update("Sentry", "Left a gift on someone's windshield", undefined, "bad");
|
|
let left = Math.max(0, Math.round(cooldownS));
|
|
clearInterval(cooldownTimer);
|
|
const tick = () => {
|
|
if (left <= 0) {
|
|
clearInterval(cooldownTimer);
|
|
sendBtn.textContent = sendLabel;
|
|
sendBtn.disabled = !!source;
|
|
return;
|
|
}
|
|
sendBtn.disabled = true;
|
|
sendBtn.textContent = `${left--}s`;
|
|
};
|
|
tick();
|
|
cooldownTimer = window.setInterval(tick, 1000);
|
|
}
|
|
|
|
// ---------- send a list ----------
|
|
let sendingNest = "todo";
|
|
form.addEventListener("submit", async (e) => {
|
|
e.preventDefault();
|
|
const text = listInput.value.trim();
|
|
if (!text || sendBtn.disabled) { listInput.focus(); return; }
|
|
const requester = requesterInput.value.trim() || "anonymous";
|
|
store.set("requester", requester);
|
|
sendBtn.disabled = true;
|
|
sendingNest = current;
|
|
|
|
const res = await postList(text, requester, current).catch(() => ({ ok: false as const, pranked: false as const, message: "Can't reach the flock. Is `crows serve` running?" }));
|
|
if (!res.ok) {
|
|
if (res.pranked) {
|
|
prank(res.message, res.cooldownS); // re-enables the button when the cooldown ends
|
|
} else {
|
|
note(res.message, current);
|
|
sendBtn.disabled = false;
|
|
}
|
|
return;
|
|
}
|
|
|
|
listInput.value = "";
|
|
trust = await getTrust();
|
|
source?.close();
|
|
source = listEvents(res.listId);
|
|
for (const [name, fn] of Object.entries(handlers)) {
|
|
source.addEventListener(name, (ev) => {
|
|
try { fn(JSON.parse((ev as MessageEvent).data)); } catch (err) { console.error(name, err); }
|
|
});
|
|
}
|
|
});
|
|
|
|
// ---------- phone tabs: the room or the roost (nests + flock) ----------
|
|
const app = document.getElementById("app")!;
|
|
function showView(view: "room" | "flock") {
|
|
app.dataset.view = view;
|
|
for (const t of document.querySelectorAll<HTMLButtonElement>(".tab")) {
|
|
t.setAttribute("aria-pressed", String(t.id === (view === "room" ? "tab-room" : "tab-flock")));
|
|
}
|
|
if (view === "room") nest(current).feed.scrollTop = nest(current).feed.scrollHeight;
|
|
}
|
|
roomTab.addEventListener("click", () => showView("room"));
|
|
$<HTMLButtonElement>("tab-flock").addEventListener("click", () => showView("flock"));
|
|
|
|
// ---------- new nest dialog ----------
|
|
const dialog = $<HTMLDialogElement>("nest-dialog");
|
|
const nestForm = $<HTMLFormElement>("nest-form");
|
|
const nestName = $<HTMLInputElement>("nest-name");
|
|
const nestCrows = $<HTMLDivElement>("nest-crows");
|
|
const nestErr = $<HTMLParagraphElement>("nest-err");
|
|
|
|
$<HTMLButtonElement>("new-nest").addEventListener("click", () => {
|
|
nestErr.textContent = "";
|
|
nestName.value = "";
|
|
nestCrows.replaceChildren();
|
|
for (const name of flockNames) {
|
|
const label = el("label", "pick-crow");
|
|
const box = el("input");
|
|
box.type = "checkbox";
|
|
box.value = name;
|
|
label.append(box, crowAvatar("crow"), el("span", "", name));
|
|
nestCrows.append(label);
|
|
}
|
|
dialog.showModal();
|
|
nestName.focus();
|
|
});
|
|
|
|
nestForm.addEventListener("submit", async (e) => {
|
|
const submitter = (e as SubmitEvent).submitter as HTMLButtonElement | null;
|
|
if (submitter?.value !== "create") return; // Cancel closes the dialog
|
|
e.preventDefault();
|
|
const name = nestName.value.trim();
|
|
const crows = [...nestCrows.querySelectorAll<HTMLInputElement>("input:checked")].map((b) => b.value);
|
|
if (!name) { nestErr.textContent = "Give the nest a name."; return; }
|
|
if (!crows.length) { nestErr.textContent = "Pick at least one crow for the core team."; return; }
|
|
try {
|
|
const n = await createNest(name, crows);
|
|
addNest(n);
|
|
dialog.close();
|
|
selectNest(n.nestId);
|
|
showView("room");
|
|
post("Sentry", [el("p", "", `New nest. Core crows: ${n.crows.join(", ")}. I'll borrow others when a job needs more hands.`)], undefined, n.nestId);
|
|
} catch (err) {
|
|
nestErr.textContent = (err as Error).message;
|
|
}
|
|
});
|
|
|
|
// ---------- start: load the nests, open # todo, the Sentry says hello ----------
|
|
crow("Sentry");
|
|
(async () => {
|
|
personas = await getCrows();
|
|
for (const name of tiles.keys()) applyPersona(name);
|
|
const data = await getNests();
|
|
flockNames = data.roster;
|
|
if (!data.nests.some((n) => n.nestId === "todo")) data.nests.unshift({ nestId: "todo", name: "todo", crows: [] });
|
|
for (const n of data.nests) addNest(n);
|
|
selectNest("todo");
|
|
post("Sentry", [el("p", "", "Caw. Send me a todo list, one item per line. I'll sort it, the flock will fly it, and you judge the results.")], undefined, "todo");
|
|
})();
|