diff --git a/README.md b/README.md index 1b7e645..447a3c6 100644 --- a/README.md +++ b/README.md @@ -70,15 +70,15 @@ Run `npx -p framesmith framesmith-viewer` to start the standalone browser viewer ![framesmith canvas detail view — the dashboard pattern rendered (grouped sidebar navigation with an account row, KPI cards with sparklines and delta pills, a real multi-series line chart with an area fill and a dashed reference line beside a recent-activity feed) with the Quality inspector open on the right: a 99/100 "Excellent" score, per-category bars (spacing, color, typography, structure, consistency, usability, coverage, cliche), and honest APCA advisories in the issue list. The toolbar shows the canvas's designed states (default / loading / empty), theme and viewport toggles, and a Comment toggle.](https://raw.githubusercontent.com/vicmaster/framesmith/master/docs/framesmith-canvas.png?v=2.0) -> Above: a canvas in the detail view with the **Quality inspector** on the right — the same `canvas_evaluate` score the agent sees, with per-category bars and the issue list; the tabs along the top switch to the **Design-system** and **Feedback** panels. The toolbar carries the project back link, the canvas's designed states as a nav, breakpoint tabs with Compare, a **Comment** button with the open-comment count for point-and-tell feedback, a **More** menu (View JSON, Copy canvas ID, Archive or Restore, Delete canvas) and a Live / Offline status; zoom, Fit and Preview in dark sit in the preview tools. +> Above: a canvas in the detail view with the **Quality inspector** on the right — the same `canvas_evaluate` score the agent sees, with the categories lowest first and the grouped issue list; the tabs along the top switch to the **Design system** and **Feedback** panels. The toolbar carries the project back link, the canvas's designed states as a nav, breakpoint tabs with Compare, a **Comment** button with the open-comment count for point-and-tell feedback, a **More** menu (View JSON, Copy canvas ID, Archive or Restore, Delete canvas) and a Live / Offline status; zoom, Fit and Preview in dark sit in the preview tools. -**Quality panel.** The canvas detail view shows a read-only **quality inspector** on the right: the heuristic `canvas_evaluate` score (0–100), per-category bars, and the issue list — each cliché tell with its `category · tell` badge, severity, and suggestion. Issues that `canvas_autofix` can resolve carry an **auto-fixable** tag, and clicking any issue **highlights its node** in the live preview. Every gallery card also shows a score chip on its thumbnail: neutral at 96 and above, amber at 95 or below (the quality bar), so canvases under the bar stand out at a glance. The project header sums it up as "N canvases · M below the bar". The score matches what your agent sees over MCP (same fast-mode evaluation, relaxed by the canvas's stored genre and applied preset) — it's computed for display only and never written back. +**Quality panel.** The canvas detail view shows a read-only **Quality** tab on the right: the heuristic `canvas_evaluate` score as "NN / 100" with an **At the bar** (96 and above) or **Below the bar** (95 or below) chip, a reason line ("Coverage holds it back: …", or "Every category is at 100."), the structure, genre and preset the canvas was built from, the vision critique when one exists, the categories lowest first, and the issues grouped as `canvas_evaluate` groups them for agents ("N findings in M groups", errors first). Each row reads `Category · kind`, where the kind is the cliché tell, **auto-fixable** when `canvas_autofix` can resolve it, or the severity; the suggestion is the row's tooltip, and **Show n nodes** outlines its nodes in the live preview. Every gallery card also shows a score chip on its thumbnail: neutral at 96 and above, amber at 95 or below (the quality bar), so canvases under the bar stand out at a glance. The project header sums it up as "N canvases · M below the bar". The score matches what your agent sees over MCP (same fast-mode evaluation, relaxed by the canvas's stored genre and applied preset) — it's computed for display only and never written back. ![framesmith point-and-tell feedback — a newsletter signup card in the detail view with Comment mode active: a popover anchored to the clicked paragraph shows breadcrumb chips (Body · Signup Card · Document · whole page) and a typed note, while the Feedback inspector tab on the right lists one open comment on "Fine Print" and one resolved comment with the agent's reply beneath it.](https://raw.githubusercontent.com/vicmaster/framesmith/master/docs/framesmith-feedback.png?v=1.8) > Above: **point-and-tell** in action — Comment mode is on, the clicked element is outlined, the popover's breadcrumb re-scopes the anchor, and the Feedback tab tracks open comments plus the agent's replies to resolved ones. -**Feedback panel.** Point-and-tell: toggle **Comment** in the toolbar and click any element in the preview to leave a note for the agent — a breadcrumb in the popover re-scopes the anchor from the exact element up to its card, section, or the whole page. The **Feedback** tab lists open comments (badge = open count) with click-to-highlight, lets you resolve or delete them, and shows the agent's resolution note as a reply once it has addressed the item. Comments persist on the canvas itself (`metadata.feedback` — git-diffable in bound repos) and the agent reads them over MCP via `get_feedback`; open feedback blocks the agent from presenting, same as open quality issues. +**Feedback panel.** Point-and-tell: press **Comment** in the toolbar and a popover opens under it. Click an element in the preview to pin the note to it (chips re-scope the anchor from the exact element up to its card, section, or the whole page); without a click the note is about the whole page. The **Feedback** tab lists open comments (its count, and the Comment button's, is the open count) with click-to-highlight, lets you resolve or delete them (deleting asks first), and shows the agent's resolution note as a reply once it has addressed the item. The list and the counts refresh on their own: a comment the agent resolves with `resolve_feedback` moves to Resolved while you watch. Comments persist on the canvas itself (`metadata.feedback` — git-diffable in bound repos) and the agent reads them over MCP via `get_feedback`; open feedback blocks the agent from presenting, same as open quality issues. **Design-system panel.** A second inspector tab shows the canvas's effective design tokens — color swatches, type scale, spacing, and radius — resolved through the full workspace ▸ project ▸ canvas inheritance chain. Each section notes its dominant source layer, and any token resolving from a *different* layer is tagged (`canvas` / `project` / `workspace`) so you can see at a glance what a given canvas customized versus inherited. @@ -1379,9 +1379,9 @@ The standalone viewer: - **Archive** (`/archive`) — soft-deleted canvases with restore / permadelete actions - **Canvas detail** (`/canvas/:id`) — the rendered design, fitted to the pane with zoom (50–200%) and Fit buttons, breakpoint tabs (Mobile / Tablet / Desktop / Compare; a `desktop-app` canvas gets its window widths, the artboard and Compare), a **More** menu (View JSON, Copy canvas ID, Archive / Restore, Delete canvas) and a caption naming type, size and states; a canvas declared `mobile` opens 1:1 in a device frame with a **Show safe area** tool button instead of the tabs and zoom - **Raw HTML** (`/canvas/:id/html`) — the rendered HTML for embedding or inspection -- **JSON API** (`/api/canvases`, `/api/canvas/:id/meta`) — programmatic access; each `/api/canvases` row carries the canvas's resolved `type` and `genre` +- **JSON API** (`/api/canvases`, `/api/canvas/:id/meta`, `/canvas/:id/inspector`) — programmatic access; each `/api/canvases` row carries the canvas's resolved `type` and `genre`, `/meta` carries a `contentKey` and a `feedbackKey`, and `/canvas/:id/inspector` returns `{ quality, design, nodeIndex }` - **Fonts** (`/assets/fonts/`) — the viewer's own faces (Inter, Space Grotesk), served from the font cache (`~/.framesmith/fonts/`) -- **Live auto-refresh** — the canvas page polls every 2 seconds and the project page every 3, so the browser updates as your agent runs `batch_design`; the project page reloads on any edit, rename, genre, type or state change +- **Live auto-refresh** — the canvas page polls every 2 seconds and the project page every 3, so the browser updates as your agent runs `batch_design`; the project page reloads on any edit, rename, genre, type or state change, and the canvas page refreshes its Quality and Design system panels, its Feedback list and its comment counts without a reload Unbound canvases persist to `~/.framesmith/canvases/` as JSON files, and canvases in a bound repo persist to that repo's `.framesmith/` (see [`canvas_bind`](#canvas_bind)). Both survive process restarts, and the viewer shows both: the global store plus every repo registered in `~/.framesmith/registry.json`. Set `FRAMESMITH_VIEWER_URL` in the MCP server env to point at a viewer running on a non-default port. diff --git a/VISION.md b/VISION.md index 490ac55..88f7f87 100644 --- a/VISION.md +++ b/VISION.md @@ -602,7 +602,7 @@ Phase 31 rebuilt the viewer as canvases and left the code alone. A design pass o - [x] Slice A — foundation: `src/viewer/` modules, tokens copied from the design system and pinned by a test, chrome that follows the system's light or dark setting, fonts served from the cache, one sidebar, tabs, menu and dialog used everywhere - [x] Slice B — gallery: thumbnail cards with a score chip against the bar, search and type filter kept in the URL, a live status, and refresh on every edit - [x] Slice C — detail shell: toolbar with state tabs, a More menu (JSON, copy ID, archive, delete), a delete dialog, and preview tools (zoom, fit, preview theme, safe area) -- [ ] Slice D — inspector and comments: the Quality tab sorted lowest first with a reason line, Design system and Feedback restyled, the Import placeholder removed, the comment popover, and panels that refresh live +- [x] Slice D — inspector and comments: the Quality tab sorted lowest first with a reason line, Design system and Feedback restyled, the Import placeholder removed, the comment popover, and panels that refresh live - [ ] Slice E — archive, docs and acceptance: the archive tree with a preview panel, README and screenshots, and each screen beside its design - [ ] Follow-up — the viewer sends `Access-Control-Allow-Origin: *` on every response, the routes that archive, delete and post comments included. It listens on 127.0.0.1 only, but a page open in the same browser can still send it a simple cross-origin POST (archive, unarchive, add or resolve a comment) without a preflight. Drop the header from mutating routes, reject requests whose `Origin` is not the viewer's own, and test both; a separate change from the visual port diff --git a/docs/specs/PHASE-33-SPEC.md b/docs/specs/PHASE-33-SPEC.md index bef436b..7a7af97 100644 --- a/docs/specs/PHASE-33-SPEC.md +++ b/docs/specs/PHASE-33-SPEC.md @@ -149,6 +149,15 @@ Its design system is the project's: seed `#B45309`, personality `technical`, 14p **Slice D — inspector and comments.** The Quality tab (FR-D1), the restyled Design system and Feedback tabs and the removed Import tab (FR-D2), the comment popover (FR-D3), and the live inspector with its route and `feedbackKey` (FR-D4). Tests rewritten: `test-viewer-panels.ts` (inspector selectors), `test-viewer-feedback.ts` (`data-tab="feedback"`, `btn-comment`, `FB_INIT`), `test-eval-cache-key.ts:104` (it reads the provenance chip from the toolbar; the chip moves into the Quality tab). New: `test/browser/test-viewer-inspector.ts`, with an MCP-driven check of FR-D4 in `test/e2e/`. +**Slice D — as built.** +- **D1: the inspector is always there.** An empty canvas used to get no inspector; it now gets one whose Quality tab says it has no score yet, so the Feedback tab is reachable on an empty canvas too. +- **D2: `/canvas/:id/inspector` returns JSON**, `{ quality, design, nodeIndex }`: the two server-rendered panels and the node index. The Feedback list stays client-rendered from `/api/canvas/:id/feedback`, so comment text never passes through `innerHTML`. `feedbackKey` lives in `src/viewer/feedback-key.ts`, shared by the page, its script and `/meta`. +- **D3: the popover is the comment mode.** It is static markup under the Comment button; opening it turns comment mode on, a click in the preview fills its anchor chips without moving it, and Cancel, Escape or a save closes it and leaves comment mode. Deleting a comment confirms in the shared dialog. +- **D4: the critique row says when the rubric asked for revision** ("Vision critique 82/100 · needs revision"), as the old toolbar chip did. +- **D5: the 80/60 helpers are gone.** `gradeFor`, `scoreColor` and `sevColor` are deleted (slice B's B5). +- **D7: "Built from" leaves out the axes.** The old toolbar chip also showed the alignment and density axes; FR-D1 names structure, genre and preset, so the caption shows those three. The panels' keys move only after a fetch succeeds and the newest response wins, so a failed or slow fetch is retried on the next poll, and an edit re-reads the comments, whose "node gone" flags it can change. +- **D6: the end-to-end check pins the viewer port.** Left to itself the MCP server reuses any viewer on 3001–3020, which would be the user's own, so `test/e2e/test-viewer-live-mcp.ts` sets `FRAMESMITH_VIEWER_PORT` to a free port. + **Slice E — archive, docs, acceptance.** `pages/archive.ts` (FR-E1, FR-E2), docs and screenshots (FR-E3), and the side-by-side acceptance (FR-E4). Tests rewritten: `test-archive-view.ts` (archive page half). `test/manual/test-viewer.ts` and `test-viewer-navbar.ts` follow the new markup. New: `test/browser/test-viewer-archive.ts`. Tests that read data, not markup, are untouched: `test-viewer-perf.ts`, `test-dual-theme.ts`, `test-viewer-resolves-workspace-tokens.ts`, `test-skeleton.ts`, `test-viewer-repo-aggregation.ts`, `test-viewer-repo-lifecycle.ts`, `test-viewer-watch.ts`. Each slice PR states that `test-viewer-perf.ts` still holds its 4x-store bound, since the gallery now renders more per card. diff --git a/src/viewer/client/detail.ts b/src/viewer/client/detail.ts index 52452b7..87319dc 100644 --- a/src/viewer/client/detail.ts +++ b/src/viewer/client/detail.ts @@ -4,6 +4,7 @@ import type { Canvas } from '../../types.js'; import { listFeedback } from '../../feedback.js'; import { evalCacheKey } from '../scores.js'; import { buildNodeIndex, scriptJson } from '../shared.js'; +import { feedbackKey as feedbackKeyOf } from '../feedback-key.js'; import { LIGHT } from '../tokens.js'; import { COMPONENTS_JS, icon } from '../components.js'; @@ -26,7 +27,8 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: // Phase 21 — point-and-tell: initial feedback entries + node labels for // the breadcrumb. Kept fresh client-side via GET /api/canvas/:id/feedback. const FB_INIT = ${scriptJson(listFeedback(canvas, { includeResolved: true }))}; - const NODE_INDEX = ${scriptJson(buildNodeIndex(canvas.root))}; + let NODE_INDEX = ${scriptJson(buildNodeIndex(canvas.root))}; + let feedbackKey = ${scriptJson(feedbackKeyOf(canvas))}; // Auto-refresh polling, and the Live / Offline status (FR-C1). const liveEl = document.getElementById('live'); @@ -52,6 +54,11 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: refreshFrames(); if (!document.getElementById('json-panel').hidden) loadJson(); } + // The panels catch up on their own keys, which move only after a fetch + // succeeds, so a failed or slow one is retried on the next poll. An + // edit also re-reads the comments: their "node gone" flags can change. + if (meta.contentKey && meta.contentKey !== inspectorKey) refreshInspector(meta.contentKey); + if ((meta.feedbackKey && meta.feedbackKey !== feedbackKey) || (meta.contentKey && meta.contentKey !== feedbackContentKey)) loadFeedback(meta.feedbackKey, meta.contentKey); } catch { setLive(false); } @@ -281,13 +288,20 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: const actions = document.createElement('div'); actions.className = 'fb-actions'; const resolveBtn = document.createElement('button'); - resolveBtn.className = 'fb-btn'; + resolveBtn.type = 'button'; + resolveBtn.className = 'btn btn--secondary'; resolveBtn.textContent = 'Resolve'; resolveBtn.onclick = (e) => { e.stopPropagation(); fbAction('/feedback/' + entry.id + '/resolve', 'POST'); }; const delBtn = document.createElement('button'); - delBtn.className = 'fb-btn fb-btn--danger'; + delBtn.type = 'button'; + delBtn.className = 'btn btn--ghost'; delBtn.textContent = 'Delete'; - delBtn.onclick = (e) => { e.stopPropagation(); if (confirm('Delete this comment?')) fbAction('/feedback/' + entry.id, 'DELETE'); }; + delBtn.onclick = async (e) => { + e.stopPropagation(); + if (!(await fsDialog.open('fb-delete-dialog'))) return; + await fbAction('/feedback/' + entry.id, 'DELETE'); + document.getElementById('tab-feedback').focus(); // the card it came from is gone + }; actions.appendChild(resolveBtn); actions.appendChild(delBtn); card.appendChild(actions); @@ -306,12 +320,15 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: function renderFeedbackPane(entries) { const pane = document.getElementById('fb-pane'); - const badge = document.getElementById('fb-badge'); if (!pane) return; pane.replaceChildren(); const open = entries.filter((e) => !e.resolvedAt); const done = entries.filter((e) => e.resolvedAt); - if (badge) { badge.textContent = String(open.length); badge.hidden = open.length === 0; } + // The open count on the Feedback tab and the Comment button. + const tabCount = document.querySelector('#tab-feedback .tab-count'); + if (tabCount) tabCount.textContent = String(open.length); + const commentCount = document.getElementById('comment-count'); + if (commentCount) { commentCount.textContent = String(open.length); commentCount.hidden = open.length === 0; } if (!open.length && !done.length) { const empty = document.createElement('div'); empty.className = 'fb-empty'; @@ -329,19 +346,26 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: } } - async function loadFeedback() { + let feedbackSeq = 0; + let feedbackContentKey = contentKey; + async function loadFeedback(key, forContent) { + const seq = ++feedbackSeq; try { - const res = await fetch('/api/canvas/' + canvasId + '/feedback'); + const res = await fetch('/api/canvas/' + canvasId + '/feedback', { cache: 'no-store' }); + if (!res.ok) return; const data = await res.json(); + if (seq !== feedbackSeq) return; // a newer fetch is on its way renderFeedbackPane(data.entries); - } catch { /* pane keeps its last state */ } + if (key) feedbackKey = key; + if (forContent) feedbackContentKey = forContent; + } catch { /* the pane keeps its last state; the next poll retries */ } } async function fbAction(suffix, method) { try { const res = await fetch('/api/canvas/' + canvasId + suffix, { method }); if (!res.ok) throw new Error('Request failed: ' + res.status); - loadFeedback(); + await loadFeedback(); } catch (err) { alert('Action failed: ' + err.message); } } @@ -381,7 +405,7 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: if (!chain.includes(id)) chain.push(id); el = el.parentElement && el.parentElement.closest('[data-node-id]'); } - openPopover(chain, e); + openPopover(chain); } function hookFrame() { @@ -392,97 +416,82 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: setFrameCommentAffordance(commentMode); } - function toggleComment() { - commentMode = !commentMode; - document.getElementById('btn-comment').classList.toggle('active', commentMode); - document.getElementById('btn-comment').setAttribute('aria-pressed', commentMode ? 'true' : 'false'); - if (!commentMode) closePopover(); + // FR-D3 — Comment opens the popover under the button and turns comment + // mode on; clicking an element in the preview pins the comment to it. + const pop = document.getElementById('comment-pop'); + const chipsEl = document.getElementById('fb-chips'); + const textEl = document.getElementById('comment-text'); + let popoverSelected = null; // nodeId, or null for the whole page + + function setCommentMode(on) { + commentMode = on; + const btn = document.getElementById('btn-comment'); + btn.classList.toggle('active', on); + btn.setAttribute('aria-pressed', on ? 'true' : 'false'); + btn.setAttribute('aria-expanded', on ? 'true' : 'false'); + pop.hidden = !on; + if (on) { textEl.focus(); } else { + if (popoverSelected) highlightNode(null, false); + chipsEl.replaceChildren(); chipsEl.hidden = true; popoverSelected = null; + textEl.value = ''; + } hookFrame(); } - - let popoverEl = null; - let popoverSelected = null; // nodeId or null = whole page - + function toggleComment() { setCommentMode(!commentMode); } + /** Close the popover; refocus the Comment button when the popover had focus. */ function closePopover() { - if (popoverEl) { popoverEl.remove(); popoverEl = null; } - highlightNode(null, false); + if (!commentMode) return; + const hadFocus = pop.contains(document.activeElement); + setCommentMode(false); + if (hadFocus) document.getElementById('btn-comment').focus(); } - function openPopover(chain, clickEvent) { - closePopover(); + /** Fill the anchor chips from a clicked element's chain (nearest first). */ + function setAnchor(chain) { + chipsEl.replaceChildren(); popoverSelected = chain.length ? chain[0] : null; - const pop = document.createElement('div'); - pop.className = 'fb-popover'; - const chips = document.createElement('div'); - chips.className = 'fb-chips'; - const allChips = []; + chipsEl.hidden = chain.length === 0; + highlightNode(popoverSelected, !!popoverSelected); + if (!chain.length) return; + const chips = []; const makeChip = (label, nodeId, title) => { - const chip = document.createElement('span'); + const chip = document.createElement('button'); + chip.type = 'button'; chip.className = 'fb-chip'; chip.textContent = label; - if (title) chip.title = title; + chip.title = title; + chip.setAttribute('aria-pressed', nodeId === popoverSelected ? 'true' : 'false'); chip.onclick = () => { popoverSelected = nodeId; - allChips.forEach((c) => c.classList.remove('sel')); - chip.classList.add('sel'); + chips.forEach((c) => c.setAttribute('aria-pressed', c === chip ? 'true' : 'false')); highlightNode(nodeId, !!nodeId); }; - allChips.push(chip); - chips.appendChild(chip); - return chip; - }; - chain.slice(0, 5).forEach((nodeId) => makeChip(nodeLabel(nodeId), nodeId, 'Anchor the comment to this element')); - makeChip('whole page', null, 'A general note not tied to one element'); - const selIdx = chain.length ? 0 : allChips.length - 1; - allChips[selIdx].classList.add('sel'); - if (popoverSelected) highlightNode(popoverSelected, true); - pop.appendChild(chips); - const ta = document.createElement('textarea'); - ta.placeholder = 'Tell the agent what to change…'; - pop.appendChild(ta); - const actions = document.createElement('div'); - actions.className = 'fb-pop-actions'; - const cancel = document.createElement('button'); - cancel.className = 'fb-btn'; - cancel.textContent = 'Cancel'; - cancel.onclick = closePopover; - const save = document.createElement('button'); - save.className = 'fb-btn'; - save.textContent = 'Save comment'; - save.onclick = async () => { - const comment = ta.value.trim(); - if (!comment) { ta.focus(); return; } - try { - const res = await fetch('/api/canvas/' + canvasId + '/feedback', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(popoverSelected ? { nodeId: popoverSelected, comment } : { comment }), - }); - if (!res.ok) throw new Error('Request failed: ' + res.status); - closePopover(); - loadFeedback(); - const fbTab = document.querySelector('.insp-tab[data-tab="feedback"]'); - if (fbTab) fbTab.click(); - } catch (err) { alert('Could not save comment: ' + err.message); } + chips.push(chip); + chipsEl.appendChild(chip); }; - actions.appendChild(cancel); - actions.appendChild(save); - pop.appendChild(actions); - document.body.appendChild(pop); - popoverEl = pop; - // Position near the click, mapping iframe coords → page coords (handles - // Fit-mode scaling); clamp so the popover stays on-screen. - const frame = document.getElementById('frame'); - const rect = frame.getBoundingClientRect(); - const win = frame.contentWindow; - const sx = win && win.innerWidth ? rect.width / win.innerWidth : 1; - const sy = win && win.innerHeight ? rect.height / win.innerHeight : 1; - const px = rect.left + clickEvent.clientX * sx; - const py = rect.top + clickEvent.clientY * sy; - pop.style.left = Math.max(8, Math.min(px, window.innerWidth - 316)) + 'px'; - pop.style.top = Math.max(60, Math.min(py + 8, window.innerHeight - pop.offsetHeight - 8)) + 'px'; - ta.focus(); + chain.slice(0, 5).forEach((nodeId) => makeChip(nodeLabel(nodeId), nodeId, 'Pin the comment to this element')); + makeChip('whole page', null, 'A note about the whole page'); } + function openPopover(chain) { if (!commentMode) setCommentMode(true); setAnchor(chain); textEl.focus(); } + + document.getElementById('comment-cancel').addEventListener('click', closePopover); + pop.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); closePopover(); } }); + document.getElementById('comment-save').addEventListener('click', async () => { + const comment = textEl.value.trim(); + if (!comment) { textEl.focus(); return; } + try { + const res = await fetch('/api/canvas/' + canvasId + '/feedback', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(popoverSelected ? { nodeId: popoverSelected, comment } : { comment }), + }); + if (!res.ok) throw new Error('Request failed: ' + res.status); + closePopover(); + loadFeedback(); + document.getElementById('tab-feedback').click(); + document.getElementById('tab-feedback').focus(); + } catch (err) { alert('Could not save comment: ' + err.message); } + }); // An Escape the menu, dialog or JSON panel already handled keeps the draft. document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !e.defaultPrevented) closePopover(); }); @@ -493,7 +502,11 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: // Phase 19 Slice A — click an issue to outline its node in the preview. // The render carries data-node-id on every element; iframes are same-origin // so we toggle an outline directly in their documents. - function highlightNode(nodeId, on) { + function highlightNode(nodeId, on) { highlightNodes(on && nodeId ? [nodeId] : []); } + // Every outline goes through here, so a "Show n nodes" button is pressed + // only while its own outline is the one showing. + function highlightNodes(nodeIds) { + document.querySelectorAll('.issue-nodes[aria-pressed="true"]').forEach((b) => b.setAttribute('aria-pressed', 'false')); const frames = []; const main = document.getElementById('frame'); if (main && getComputedStyle(main).display !== 'none') frames.push(main); @@ -505,33 +518,46 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: doc.querySelectorAll('[data-fs-hl]').forEach((n) => { n.style.outline = ''; n.style.outlineOffset = ''; n.removeAttribute('data-fs-hl'); }); - if (on && nodeId) { + let first = null; + for (const nodeId of nodeIds) { const t = doc.querySelector('[data-node-id="' + (window.CSS && CSS.escape ? CSS.escape(nodeId) : nodeId) + '"]'); - if (t) { - t.style.outline = '2px solid ' + HIGHLIGHT; t.style.outlineOffset = '1px'; - t.setAttribute('data-fs-hl', '1'); - t.scrollIntoView({ block: 'center', behavior: 'smooth' }); - } + if (!t) continue; + t.style.outline = '2px solid ' + HIGHLIGHT; t.style.outlineOffset = '1px'; + t.setAttribute('data-fs-hl', '1'); + first = first || t; } + if (first) first.scrollIntoView({ block: 'center', behavior: 'smooth' }); } } - document.querySelectorAll('.insp-issue[data-issue-node]').forEach((el) => { - el.addEventListener('click', () => { - const wasSel = el.classList.contains('sel'); - document.querySelectorAll('.insp-issue.sel').forEach((o) => o.classList.remove('sel')); - if (wasSel) { highlightNode(null, false); return; } - el.classList.add('sel'); - highlightNode(el.getAttribute('data-issue-node'), true); - }); + // FR-D1 — "Show n nodes" outlines an issue's nodes; delegated, so it works + // after a live swap of the Quality panel. + document.getElementById('inspector').addEventListener('click', (e) => { + const btn = e.target.closest && e.target.closest('.issue-nodes'); + if (!btn) return; + const on = btn.getAttribute('aria-pressed') !== 'true'; + highlightNodes(on ? JSON.parse(btn.dataset.nodes) : []); + if (on) btn.setAttribute('aria-pressed', 'true'); }); - // Phase 19 Slice B — inspector tab switching (Quality / Design system). - document.querySelectorAll('.insp-tab[data-tab]').forEach((tab) => { - tab.addEventListener('click', () => { - const name = tab.getAttribute('data-tab'); - document.querySelectorAll('.insp-tab[data-tab]').forEach((t) => t.classList.toggle('active', t === tab)); - document.querySelectorAll('.insp-tabpane').forEach((p) => { p.hidden = p.getAttribute('data-pane') !== name; }); - }); - }); + // FR-D4 — swap the Quality and Design system panels (and the node index) + // when the canvas changes, keeping the scroll position. + let inspectorKey = contentKey; + let inspectorSeq = 0; + async function refreshInspector(key) { + const seq = ++inspectorSeq; + try { + const res = await fetch('/canvas/' + canvasId + '/inspector', { cache: 'no-store' }); + if (!res.ok) return; + const parts = await res.json(); + if (seq !== inspectorSeq) return; // a newer fetch is on its way + const inspector = document.getElementById('inspector'); + const top = inspector.scrollTop; + document.getElementById('insp-quality').innerHTML = parts.quality; + document.getElementById('insp-design').innerHTML = parts.design; + NODE_INDEX = parts.nodeIndex; + inspector.scrollTop = top; + inspectorKey = key; + } catch { /* the panels keep their last state */ } + } `; } diff --git a/src/viewer/feedback-key.ts b/src/viewer/feedback-key.ts new file mode 100644 index 0000000..2cd1c42 --- /dev/null +++ b/src/viewer/feedback-key.ts @@ -0,0 +1,13 @@ +// Phase 33 slice D (FR-D4) — a key for a canvas's comments that changes when +// one is added, resolved or deleted: the total, the open count and the latest +// of every entry's \`at\` and \`resolvedAt\`. /api/canvas/:id/meta carries it and +// the detail page reloads its Feedback list when it changes. +import type { Canvas } from '../types.js'; +import { listFeedback } from '../feedback.js'; + +export function feedbackKey(canvas: Canvas): string { + const entries = listFeedback(canvas, { includeResolved: true }); + const open = entries.filter((e) => !e.resolvedAt).length; + const latest = entries.reduce((max, e) => [e.at, e.resolvedAt ?? ''].reduce((m, t) => (t > m ? t : m), max), ''); + return `${entries.length}:${open}:${latest}`; +} diff --git a/src/viewer/pages/detail.ts b/src/viewer/pages/detail.ts index 093d514..0ea36ac 100644 --- a/src/viewer/pages/detail.ts +++ b/src/viewer/pages/detail.ts @@ -3,31 +3,43 @@ import type { Canvas } from '../../types.js'; import { getProject, getCanvasTokens, getProjectDesignSystem, getWorkspaceDesignSystem } from '../../workspaces.js'; import { listCanvases } from '../../scene-graph.js'; import { resolveSurface, usableSafeArea, deviceProfile, windowProfile, WINDOW_PROFILES, DEFAULT_WINDOW, DEFAULT_DEVICE, type DeviceProfile } from '../../surfaces.js'; -import { resolveGenre, type EvaluationResult, type EvaluationIssue } from '../../evaluate.js'; +import { foldIssues, resolveGenre, type EvaluationResult, type EvaluationIssue } from '../../evaluate.js'; import { isPresetName } from '../../genre.js'; import { openFeedbackCount } from '../../feedback.js'; import { withoutRetiredSeeds } from '../../variables.js'; import { baseCss, COMPONENTS_CSS } from '../styles.js'; import { TYPE_LABELS } from './project.js'; -import { FAVICON_HTML, icon, renderDialog, renderMenu } from '../components.js'; -import { artboardSize, esc, PHONE } from '../shared.js'; -import { evalFor, gradeFor, scoreColor, sevColor } from '../scores.js'; +import { FAVICON_HTML, icon, renderDialog, renderMenu, renderTabs } from '../components.js'; +import { artboardSize, buildNodeIndex, esc, PHONE } from '../shared.js'; +import { evalFor } from '../scores.js'; import { detailScript } from '../client/detail.js'; -function renderIssueCard(issue: EvaluationIssue): string { - const label = issue.tell ? `${esc(issue.category)} · ${esc(issue.tell)}` : esc(issue.category); - const clickable = typeof issue.nodeId === 'string' && issue.nodeId.length > 0; - const fixTag = issue.fix - ? `⚡ auto-fixable` : ''; +/** The evaluator's quality bar: a score above 95 is at it (FR-B2, FR-D1). */ +const BAR = 96; + +const CATEGORY_LABELS: Record = { + spacing: 'Spacing', color: 'Color', typography: 'Typography', structure: 'Structure', + consistency: 'Consistency', usability: 'Usability', coverage: 'Coverage', cliche: 'Cliché', +}; +const categoryLabel = (name: string) => CATEGORY_LABELS[name] ?? name.charAt(0).toUpperCase() + name.slice(1); +const SEVERITY_RANK: Record = { error: 0, warning: 1 }; +const severityRank = (sev: string) => SEVERITY_RANK[sev] ?? 2; + +/** One folded issue as a ruled row (FR-D1): " · ", the + * message, and a link that outlines its nodes. The suggestion is the row's + * tooltip; the agent reads it from canvas_evaluate. */ +function renderIssueRow(issue: EvaluationIssue): string { + const fixable = !!issue.fix || (issue.fixes?.length ?? 0) > 0; + const kind = issue.tell ?? (fixable ? 'auto-fixable' : issue.severity); + const nodes = issue.nodeIds?.length ? issue.nodeIds : issue.nodeId ? [issue.nodeId] : []; + const show = nodes.length + ? `` + : ''; return ` -
-
- - ${label} - ${fixTag} -
-
${esc(issue.message)}
- ${issue.suggestion ? `
${esc(issue.suggestion)}
` : ''} +
+
${esc(categoryLabel(issue.category))} · ${esc(kind)}
+
${esc(issue.message)}
+ ${show}
`; } @@ -71,10 +83,7 @@ function renderDesignSystem(canvas: Canvas): string { if (m) for (const n of Object.keys(m)) allSources.push(sourceOf(cat, n)); } if (allSources.length === 0) { - return ` - `; + return '
This canvas inherits no design tokens. Set them with set_variables or bind a design system.
'; } const dominant = mostCommon(allSources); const defaultLabel = dominant === 'default' ? 'defaults' : `from ${dominant}`; @@ -153,59 +162,84 @@ function renderDesignSystem(canvas: Canvas): string {
` : ''; - return ` - `; + const body = `${colorSec}${typeSec}${spaceSec}${radiusSec}`; + return body.trim() ? body : '
This canvas inherits no design tokens.
'; } -function renderInspector(ev: EvaluationResult, canvas: Canvas): string { - const grade = gradeFor(ev.overallScore); - const fbOpen = openFeedbackCount(canvas); - const cats = ev.categories.map((c) => ` -
- ${esc(c.name)} - - ${c.score} -
`).join(''); - const issues = ev.issues.length - ? ev.issues.map(renderIssueCard).join('') - : `
No issues — this canvas is clean.
`; +/** The Quality tab (FR-D1): the score against the bar with a reason line, + * provenance and critique, the categories lowest first, then the folded + * issues, errors first. */ +export function renderQualityPanel(ev: EvaluationResult | null, canvas: Canvas): string { + if (!ev) { + const empty = !canvas.root.children?.length; + return `
${empty ? 'An empty canvas has no score yet.' : 'The score could not be computed for this canvas.'}
`; + } + const below = ev.overallScore < BAR; + const folded = foldIssues(ev.issues); + const ordered = [...folded].sort((a, b) => severityRank(a.severity) - severityRank(b.severity)); + const cats = [...ev.categories].sort((a, b) => a.score - b.score); + const weakest = cats.find((c) => c.score < 100); + const blocker = weakest ? ordered.find((i) => i.category === weakest.name) : undefined; + const reason = weakest + ? `${categoryLabel(weakest.name)} holds it back${blocker ? `: ${blocker.message}` : '.'}` + : 'Every category is at 100.'; + + const prov = canvas.metadata?.provenance; + const genre = resolveGenre(canvas).genre; + const built = [prov?.structure, genre, prov?.preset && ('genre' in (prov ?? {}) || isPresetName(prov.preset)) ? prov.preset : undefined].filter(Boolean) as string[]; + const crit = canvas.metadata?.critique; + + const findings = folded.reduce((n, i) => n + (i.count ?? 1), 0); return ` - + ${renderDialog({ id: 'fb-delete-dialog', title: 'Delete this comment?', body: 'The comment is removed for everyone, your agent included.', confirmLabel: 'Delete comment', destructive: true })} ${renderDialog({ id: 'delete-dialog', title: `Delete ${canvas.name}?`, body: 'The canvas is deleted for good and cannot be restored. To hide it from the gallery and keep it, archive it instead.', confirmLabel: 'Delete canvas', destructive: true })}