// Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only. import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES, loadAgentsDoc, openPrototypeDoc, closePrototypeDoc, } from "../selectors.js"; import { el, icon, md } from "../render.js"; import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js"; import { hooks, page, redraw } from "../state.js"; const $ = (id) => document.getElementById(id); import { sendState } from "../send-state.js"; import { briefPhrase } from "../answers.js"; let docObserver = null; // A brief is a Pathfinder thing: a plain-English report of the decisions made // in a date range, the ones still open, and what happens next. It is the // artifact someone takes to a meeting, and the reason a non-engineer is in this // session at all, so it should not need knowing that you can type "brief" at a // terminal to get one. // // The request travels as an ordinary send. The agent's own wait loop returns // it, `reply` carries the range in the grammar its playbook already parses, and // the finished brief comes back as a doc like any other. const BRIEF_RANGES = { today: "today", "this week": "this week", full: "full", }; function briefRange() { const picked = document.querySelector('input[name="brief-range"]:checked'); const value = picked ? picked.value : "today"; if (value !== "since") return { range: BRIEF_RANGES[value] || "today" }; const on = $("brief-since").value; if (!on) return { problem: "Pick the date to count from, or choose another range." }; if (on > localDay()) return { problem: "Pick a date that has already happened: a brief covers what was decided since then." }; return { range: `since ${on}` }; } function openBrief() { const why = $("brief-why"); why.textContent = ""; syncBriefDate(); $("brief-modal").showModal(); } // The date only means anything for "since", so it is dimmed and inert until // that is the choice, rather than sitting there inviting a value it will ignore. function syncBriefDate() { const picked = document.querySelector('input[name="brief-range"]:checked'); const on = Boolean(picked && picked.value === "since"); const row = document.querySelector(".since-row"); const input = $("brief-since"); row.classList.toggle("is-off", !on); input.disabled = !on; input.max = localDay(); } // Today as YYYY-MM-DD in the person's own time zone, the shape a date input uses. function localDay(d = new Date()) { const p = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`; } export async function sendBrief() { const choice = briefRange(); const why = $("brief-why"); if (choice.problem) { why.textContent = choice.problem; return; } const state = sendState(); // The same guard the Send button uses. A brief is a turn like any other, and // two turns in flight is the one thing this protocol will not do. if (page.gone || page.pendingResult || (agentWorking() && workingMs() <= patience(WORKING_GRACE_MS))) { why.textContent = state.why || "Wait for Plan2Code to finish, then ask again."; return; } const go = $("brief-go"); go.disabled = true; go.textContent = "Asking…"; try { const res = await fetch("/submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [{ i: "__brief", type: "brief", range: choice.range }], reply: briefPhrase(choice.range), }), }); if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true }); if (!res.ok) throw new Error(String(res.status)); $("brief-modal").close(); const asked = hooks.banner("Asked for a brief. It will appear as a tab when it is written.", "good"); setTimeout(() => hooks.clearBanner(asked), 5000); page.pendingResult = true; redraw(); } catch (err) { if (err && err.pending) page.pendingResult = true; why.textContent = err && err.pending ? "Your last answers are still being picked up. Try again in a moment." : "That did not go through. Try again in a moment."; } finally { go.disabled = false; go.textContent = "Write the brief"; } } export function renderBriefButton() { const btn = $("btn-brief"); // Only Pathfinder has a brief playbook. Offering the button anywhere else // would send the agent a request it has no procedure for. const offer = page.S && page.S.workflow === "pathfinder"; btn.hidden = !offer; // A finished (or paused) session has nobody to write it: the request would // wait on disk for a session that may never come. if (offer) btn.disabled = page.gone || page.pendingResult || Boolean(finish()); } // The page's one empty block (.empty): an icon from the sheet and one line. function emptyBlock(text) { const box = el("div", "empty"); box.appendChild(icon("document", "empty-icon")); box.appendChild(el("p", null, text)); return box; } export function renderDoc(main, id) { const doc = docs().find((d) => d.id === id); if (!doc) { main.appendChild(emptyBlock("That document is not ready yet.")); return; } const head = el("div", "doc-head"); head.appendChild(el("h2", null, doc.title || "Document")); head.appendChild(el("span", "doc-version", "v" + (doc.version || 1))); if (doc.stale) { head.appendChild(el("span", "pill is-stage", "Out of date")); } const tools = el("div", "doc-tools"); tools.appendChild(backButton()); // A brief is handed to people who were not in the room, so it gets a copy // that opens in any browser, formatting and all. if (doc.id === "brief") { const html = el("button", "btn sm", "Save as HTML"); html.type = "button"; html.addEventListener("click", () => downloadDocHtml(doc)); tools.appendChild(html); } tools.appendChild(printButton()); if (doc.saved) { tools.appendChild(docSavedNote(doc)); } else { const save = el("button", "btn sm", "Download"); save.type = "button"; save.addEventListener("click", () => downloadDoc(doc)); tools.appendChild(save); } head.appendChild(tools); main.appendChild(head); if (doc.note) main.appendChild(el("p", "help", doc.note)); const blocks = doc.blocks || []; if (!blocks.length) { main.appendChild(emptyBlock("Nothing written yet. It fills in as you answer.")); return; } // The block nearest the top of the column is the section + Add context // offers after leaving this tab. Its label is its first heading. docObserver?.disconnect(); if (page.docInView && page.docInView.docId !== doc.id) page.docInView = null; const boxes = []; const topmost = () => { const top = main.getBoundingClientRect().top; const box = boxes.find((x) => x.getBoundingClientRect().bottom > top + 1); if (!box) return; const heading = box.querySelector("h1, h2, h3, h4, h5, h6"); page.docInView = { docId: doc.id, blockId: box.dataset.block, label: (heading && heading.textContent.trim()) || doc.title || "Document", }; }; docObserver = typeof IntersectionObserver === "function" ? new IntersectionObserver(topmost, { root: main, threshold: [0, 0.25, 0.5, 0.75, 1] }) : null; blocks.forEach((b, i) => { const box = el("div", "block " + (b.state || "settled")); box.dataset.block = b.id || String(i); boxes.push(box); docObserver?.observe(box); if (b.state === "assumed") { // Borrowed from grill-with-ui and the best idea in it: show plainly which // parts are still a guess, so nobody mistakes a placeholder for a decision. box.appendChild(el("span", "block-tag", "Assumed for now, still open")); } if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft")); box.appendChild(blockBody(b, doc)); main.appendChild(box); }); } // The way home from a document, in the highlight color so it is the easiest // thing to find after reading. A finished session's first tab is its finish // screen, the same as the tab itself. function backButton() { const flow = page.S.workflow; const home = flow === "dashboard" ? "Dashboard" : flow === "git" ? "Git" : "Questions"; const back = el("button", "btn sm back-home", "Back to " + home); back.type = "button"; back.addEventListener("click", () => { page.view = finish() ? "end" : "questions"; redraw(); $("main").focus(); }); return back; } function printButton() { const print = el("button", "btn sm", "Print"); print.type = "button"; // The print stylesheet drops everything that steers the session, so what // comes out is the document alone. "Save as PDF" in that dialog is also the // most portable save this page can offer. print.addEventListener("click", () => window.print()); return print; } // One of the spec's files (overview.md, the Pathfinder map, the Plan draft), // read-only and drawn through the same markdown path as every doc. No // Download: the file is already on disk. export function renderOverview(main, kind = "overview") { const spec = SPEC_FILES.find((f) => f.id === kind) || SPEC_FILES[0]; const found = page.overview.files[spec.id]; const head = el("div", "doc-head"); head.appendChild(el("h2", null, spec.label)); const tools = el("div", "doc-tools"); tools.appendChild(backButton()); tools.appendChild(printButton()); head.appendChild(tools); main.appendChild(head); main.appendChild(el("p", "help", `${page.overview.key}/${found ? found.file : ""} · read-only, straight from disk`)); const box = el("div", "block settled"); if (found) box.appendChild(md(found.text, "md")); else box.appendChild(loadingRows()); main.appendChild(box); } // Muted rows where a file's lines will be, the diff view's loading look // (they shimmer under no-preference, diff.css). function loadingRows(count = 7) { const rows = el("div", "diff-skeleton doc-skeleton"); rows.setAttribute("role", "status"); rows.setAttribute("aria-label", "Reading the file"); for (let i = 0; i < count; i++) rows.appendChild(el("span", "diff-skel-row")); return rows; } // The files the AGENTS.md tab may show: the same two shapes the server serves. const AGENTS_FILE = /^(?:AGENTS\.md|\.agents-docs\/[A-Za-z0-9._-]+\.md)$/; // A link in an agent-guide file, resolved against the file it sits in: the // guide's own name when it points at another agent-guide file, else null (an // outside link keeps the usual rules). export function agentsLinkTarget(from, href) { if (!href || /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith("#") || href.startsWith("/")) return null; try { const u = new URL(href, "http://guide.invalid/" + from); const rel = decodeURIComponent(u.pathname.slice(1)); return AGENTS_FILE.test(rel) ? rel : null; } catch { return null; } } // The Dashboard's AGENTS.md tab: the project's agent guide, read-only, straight // from disk. A link to another guide file (.agents-docs/...) opens in place, // with a way back to AGENTS.md. export function renderAgentsDoc(main) { const { open, texts } = page.agentsDoc; const head = el("div", "doc-head"); head.appendChild(el("h2", null, open === "AGENTS.md" ? "AGENTS.md" : open)); const tools = el("div", "doc-tools"); if (open !== "AGENTS.md") { const guide = el("button", "btn sm", "Back to AGENTS.md"); guide.type = "button"; guide.addEventListener("click", () => { page.agentsDoc.open = "AGENTS.md"; redraw(); main.scrollTop = 0; }); tools.appendChild(guide); } tools.appendChild(backButton()); tools.appendChild(printButton()); head.appendChild(tools); main.appendChild(head); main.appendChild(el("p", "help", open + " · read-only, straight from disk")); const box = el("div", "block settled"); box.appendChild( md(texts[open] || "", "md", { link: (href) => { const rel = agentsLinkTarget(open, href); if (!rel) return null; return () => { page.agentsDoc.open = rel; redraw(); main.scrollTop = 0; loadAgentsDoc(); }; }, }) ); main.appendChild(box); } // A saved prototype page, handed to the server to open in the person's // default browser (the app's webview opens no windows, and a page served over // http cannot open a file:// link). A failure says so on the banner. async function openPrototypePage(spec, name) { const ok = await fetch("/open-prototype", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ spec, name }), }) .then((res) => res.ok) .catch(() => false); if (!ok) hooks.banner(`${name} could not open in your browser. Open it from ${spec}/prototypes/ yourself.`, "warn"); } // The Prototypes tab: the .md and .html files in the spec's prototypes/ // folder. An .md opens in place, with a way back to the list (like Back to // AGENTS.md); an .html opens in the default browser. export function renderPrototypes(main) { const { key, files, open, texts } = page.prototypes; const reading = open && typeof texts[open] === "string"; const head = el("div", "doc-head"); head.appendChild(el("h2", null, reading ? open : "Prototypes")); const tools = el("div", "doc-tools"); if (reading) { const list = el("button", "btn sm", "Back to Prototypes"); list.type = "button"; list.addEventListener("click", () => { closePrototypeDoc(); main.scrollTop = 0; }); tools.appendChild(list); } tools.appendChild(backButton()); if (reading) tools.appendChild(printButton()); head.appendChild(tools); main.appendChild(head); main.appendChild(el("p", "help", `${key}/prototypes/${reading ? open : ""} · read-only, straight from disk`)); if (reading) { const box = el("div", "block settled"); box.appendChild(md(texts[open], "md")); main.appendChild(box); return; } const list = el("ul", "proto-list"); for (const f of files) { const row = el("li", "proto-row"); const b = el("button", "proto-open", null); b.type = "button"; b.appendChild(el("span", "code-tag" + (f.kind === "md" ? "" : " is-accent") + " proto-kind proto-kind-" + f.kind, f.kind === "md" ? "MD" : "HTML")); b.appendChild(el("span", "proto-name", f.name)); b.appendChild(el("span", "proto-how", f.kind === "md" ? "Read it here" : "Opens in your browser ↗")); b.title = f.kind === "md" ? `Read ${f.name} here` : `Open ${f.name} in your default browser`; b.addEventListener("click", () => { if (f.kind === "md") { openPrototypeDoc(f.name); main.scrollTop = 0; } else openPrototypePage(key, f.name); }); row.appendChild(b); list.appendChild(row); } main.appendChild(list); } // The brief dialog's buttons, wired once at start-up. export function wireDocs() { $("btn-brief").addEventListener("click", openBrief); $("brief-cancel").addEventListener("click", () => $("brief-modal").close()); $("brief-go").addEventListener("click", sendBrief); for (const radio of document.querySelectorAll('input[name="brief-range"]')) { radio.addEventListener("change", syncBriefDate); } }