"use strict"; const byId = (id) => document.getElementById(id); const board = byId("board"); const detail = byId("detail"); const lanes = [ ["analysis", "Анализ", ["анализ"]], ["model", "Моделирование", ["моделирование", "на доработке"]], ["verify", "Проверка", ["проверка"]], ["decision", "Нужен просмотр или решение", ["заблокировано", "ожидает просмотра", "на рассмотрении"]], ["closed", "Завершено", ["принято", "отклонено"]], ]; const agentNames = { "cad-factory": "Координатор", "cad-analysis": "Аналитик", "cad-modeling": "Моделировщик", "cad-verification": "Проверяющий", }; let cards = []; let selected = null; function node(tag, text, className) { const element = document.createElement(tag); if (text !== undefined) element.textContent = text; if (className) element.className = className; return element; } function laneFor(card) { const status = card.status?.toLowerCase(); return lanes.find(([, , states]) => states.includes(status))?.[0] || "decision"; } function cardButton(id) { return Array.from(board.querySelectorAll("button")).find((button) => button.dataset.id === id); } function renderBoard() { const focused = board.contains(document.activeElement) ? document.activeElement.dataset.id : null; board.replaceChildren(...lanes.map(([key, label]) => { const group = node("section", undefined, `lane ${key}`); const heading = node("h3", label); const matches = cards.filter((card) => laneFor(card) === key); heading.append(node("span", String(matches.length), "lane-count")); group.append(heading); if (!matches.length) { group.append(node("p", "Нет карточек", "card-empty")); return group; } const list = node("ul", undefined, "card-list"); for (const card of matches) { const row = node("li"); const button = node("button", undefined, "card"); button.type = "button"; button.dataset.id = card.id; button.setAttribute("aria-controls", "detail"); button.setAttribute("aria-expanded", String(card.id === selected)); button.append(node("span", card.id, "ident"), node("span", card.title, "card-title"), node("span", card.status || "Статус не указан", "card-status")); if (card.revision) button.append(node("span", `Ревизия: ${card.revision}`, "card-revision")); row.append(button); list.append(row); } group.append(list); return group; })); if (focused) (cardButton(focused) || byId("board-title")).focus({ preventScroll: true }); } function markdownTables(text) { const lines = text.split(/\r?\n/); const cells = (line) => line.trim().slice(1, -1).split(/(? value.trim().replaceAll("\\|", "|")); const tables = []; for (let index = 0; index + 1 < lines.length; index++) { if (!/^\s*\|.*\|\s*$/.test(lines[index])) continue; const header = cells(lines[index]); const rule = lines[index + 1]; if (!/^\s*\|.*\|\s*$/.test(rule) || !cells(rule).every((value) => /^:?-{3,}:?$/.test(value))) continue; const name = header.includes("ID критерия") ? "Критерии проверки" : header.includes("Новая принятая база") ? "История решений" : null; if (!name) continue; const rows = []; index += 2; while (index < lines.length && /^\s*\|.*\|\s*$/.test(lines[index])) { const row = cells(lines[index++]); if (row.length === header.length && row.some(Boolean)) rows.push(row); } index--; tables.push({ name, header, rows }); } return tables; } function renderDetail(card) { byId("detail-id").textContent = card.id; byId("detail-title").textContent = card.title; const fields = [["Состояние", card.status], ["Предлагаемая ревизия", card.revision], ["Принятая база", card.base], ["Поручение и режим", card.task]]; byId("detail-fields").replaceChildren(...fields.map(([key, value]) => { const pair = node("div"); pair.append(node("dt", key), node("dd", value || "Не указано")); return pair; })); const tables = markdownTables(card.markdown); byId("table-note").hidden = !tables.some(({ rows }) => rows.length); byId("detail-tables").replaceChildren(...tables.map(({ name, header, rows }) => { const section = node("section"); section.append(node("h3", name)); if (!rows.length) { section.append(node("p", "Записей пока нет", "card-empty")); return section; } const wrapper = node("div", undefined, "table-wrap"); wrapper.tabIndex = 0; wrapper.setAttribute("role", "region"); wrapper.setAttribute("aria-label", name); const table = node("table"); const headRow = table.createTHead().insertRow(); headRow.append(...header.map((value) => { const th = node("th", value); th.scope = "col"; return th; })); const body = table.createTBody(); for (const row of rows) body.insertRow().append(...row.map((value) => node("td", value || "—"))); wrapper.append(table); section.append(wrapper); return section; })); byId("markdown").textContent = card.markdown; } function closeDetail(restoreFocus) { const previous = cardButton(selected); previous?.setAttribute("aria-expanded", "false"); selected = null; detail.hidden = true; if (restoreFocus) (previous || byId("board-title")).focus(); } board.addEventListener("click", (event) => { const button = event.target.closest("button[data-id]"); if (!button) return; if (button.dataset.id === selected) return closeDetail(true); cardButton(selected)?.setAttribute("aria-expanded", "false"); const card = cards.find(({ id }) => id === button.dataset.id); selected = card.id; button.setAttribute("aria-expanded", "true"); byId("source").open = false; renderDetail(card); detail.hidden = false; byId("detail-title").focus({ preventScroll: true }); detail.scrollIntoView({ block: "start" }); }); byId("close-detail").addEventListener("click", () => closeDetail(true)); function setStatus(element, text, warning = false) { if (element.textContent !== text) element.textContent = text; element.classList.toggle("warning", warning); } function renderCards(data) { const notice = byId("notice"); const status = byId("cards-status"); if (!data) { setStatus(status, "Не удалось прочитать карточки · повторяем", true); notice.textContent = "Если карточки уже загружались, ниже показаны последние доступные данные."; notice.hidden = false; return; } setStatus(status, `Всего: ${data.cards.length}`); notice.textContent = data.skipped ? `Не удалось прочитать часть карточек: ${data.skipped}.` : "Карточек ещё нет. Доска заполнится, когда CAD Factory сохранит первую карточку в changes/."; notice.hidden = !data.skipped && data.cards.length > 0; const before = cards.find(({ id }) => id === selected); cards = data.cards; renderBoard(); if (selected !== null) { const current = cards.find(({ id }) => id === selected); if (!current) closeDetail(detail.contains(document.activeElement)); else if (JSON.stringify(current) !== JSON.stringify(before)) renderDetail(current); } } function renderActivity(data) { const agents = byId("agents"); const state = data?.state; const active = data?.agents || []; const counts = new Map(); for (const { agent } of active) counts.set(agent, (counts.get(agent) || 0) + 1); agents.replaceChildren(...Array.from(counts, ([agent, count]) => { const item = node("li", undefined, "agent"); item.title = agent; const dot = node("span", undefined, "dot"); dot.setAttribute("aria-hidden", "true"); item.append(dot, node("span", `${agentNames[agent] || agent}${count > 1 ? ` · ${count}` : ""}`)); return item; })); const messages = { available: active.length ? `Активных сессий и задач: ${active.length}` : "Активных CAD-агентов нет", partial: "Доступна только часть данных OpenCode", disabled: "Подключение отключено при запуске", unavailable: "OpenCode недоступен. Проверьте CLI и общую службу.", }; setStatus(byId("activity-status"), messages[state] || "Не удалось обновить активность · повторяем", !state || ["unavailable", "partial"].includes(state)); } async function watch(path, render, interval) { let previous; const tick = async () => { let data; try { const response = await fetch(path, { signal: AbortSignal.timeout(15000) }); if (!response.ok) throw new Error("Request failed"); data = await response.json(); } catch { data = null; } const fingerprint = JSON.stringify(data); if (fingerprint !== previous) { render(data); previous = fingerprint; } window.setTimeout(tick, interval); }; await tick(); } watch("/api/cards", renderCards, 3000); watch("/api/activity", renderActivity, 4000);