diff --git a/README.md b/README.md index d51683c..ea098cb 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ Run `npx -p framesmith framesmith-viewer` to start the standalone browser viewer > 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 exposes breakpoint previews, Compare, Fit, JSON, a **Comment** toggle for point-and-tell feedback, and lifecycle actions. -**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 color-coded score badge so weak canvases stand out at a glance. 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 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. ![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) @@ -214,7 +214,7 @@ Clone a screen into a linked **state variant** — the empty / loading / error v | `canvasId` | string | The base canvas (a variant id also works — it resolves to the root base; variants never nest) | | `state` | string | The state this variant designs — `empty` / `loading` / `error` for data states, `menu-open` / `comment-open` / `confirm-delete` / `toast` for overlay states; free string accepted | -Returns `{ canvasId, name, state, of, idMap }` — `idMap` maps every base node id to its clone, so follow-up edits target the right nodes immediately. One canvas per state per base (a duplicate state errors). The viewer shows a screen and its variants as one card with state chips; `canvas_list` rolls designed states onto the base row. +Returns `{ canvasId, name, state, of, idMap }` — `idMap` maps every base node id to its clone, so follow-up edits target the right nodes immediately. One canvas per state per base (a duplicate state errors). The viewer's project page shows a screen and its variants as one card, with the designed-state count in the card's meta line ("… · 3 states"); the detail page lists the states as chips; `canvas_list` rolls designed states onto the base row. ### `canvas_move` / `canvas_archive` / `canvas_unarchive` / `canvas_delete` @@ -1375,13 +1375,13 @@ The standalone viewer: ### Routes & API - **Gallery** (`/`) — browse all canvases as clickable cards with live thumbnails -- **Project** (`/project/:id`) — same gallery but scoped to one project +- **Project** (`/project/:id`) — one project's canvases as cards (score chip, type, size, edit date, state count), with a Live / Offline status, a search field (`?q=`) and Web / Mobile / Desktop app tabs (`?type=`) kept in the URL - **Archive** (`/archive`) — soft-deleted canvases with restore / permadelete actions - **Canvas detail** (`/canvas/:id`) — full rendered design with responsive viewport buttons (Mobile / Tablet / Desktop), Compare mode, Fit toggle, and JSON inspector; a canvas declared `mobile` opens 1:1 in a device frame with a Safe area toggle instead of the viewport, Compare and Fit buttons - **Raw HTML** (`/canvas/:id/html`) — the rendered HTML for embedding or inspection -- **JSON API** (`/api/canvases`, `/api/canvas/:id/meta`) — programmatic access +- **JSON API** (`/api/canvases`, `/api/canvas/:id/meta`) — programmatic access; each `/api/canvases` row carries the canvas's resolved `type` and `genre` - **Fonts** (`/assets/fonts/`) — the viewer's own faces (Inter, Space Grotesk), served from the font cache (`~/.framesmith/fonts/`) -- **Live auto-refresh** — the viewer polls for changes every 2 seconds, so the browser updates automatically as your agent runs `batch_design` +- **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 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 6fdb50f..e1814ec 100644 --- a/VISION.md +++ b/VISION.md @@ -600,7 +600,7 @@ _Full spec-driven breakdown in [`docs/specs/PHASE-32-SPEC.md`](docs/specs/PHASE- Phase 31 rebuilt the viewer as canvases and left the code alone. A design pass on 2026-11-24 redrew those seven screens (gallery, detail with its menu, comment and delete states, archive and its empty state), each clean in both themes, and they are committed under `.framesmith/viewer-redesign/`. This phase ports them into the viewer: neutral chrome that follows the system's light or dark setting, real thumbnails scored against the evaluator's bar, an inspector that leads with what holds a design back, and live updates that cover thumbnails, scores and comments, not only the preview. - [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 -- [ ] 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 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 - [ ] 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 - [ ] Slice E — archive, docs and acceptance: the archive tree with a preview panel, README and screenshots, and each screen beside its design diff --git a/docs/specs/PHASE-33-SPEC.md b/docs/specs/PHASE-33-SPEC.md index 7016137..f062f9f 100644 --- a/docs/specs/PHASE-33-SPEC.md +++ b/docs/specs/PHASE-33-SPEC.md @@ -130,6 +130,13 @@ Its design system is the project's: seed `#B45309`, personality `technical`, 14p **Slice B — gallery.** `pages/project.ts` and `client/project.ts` (FR-B1 to FR-B4), with the fixture store. Tests rewritten: `test-viewer-panels.ts` (its `card-score` assertion), `test-empty-thumbnail.ts`, `test-variants.ts` (state chips become the meta line), `test-viewer-surface.ts` (thumbnail sizing strings). New: `test/browser/test-viewer-gallery.ts`. +**Slice B — as built.** +- **B1: the fixture store is a builder, not JSON.** `test/fixtures/viewer-store.ts` seeds whatever store `FRAMESMITH_HOME` points at through the store's own functions, so it follows the canvas format as it changes; `test/unit/test-viewer-fixture.ts` pins what it holds. The 95 canvas is the pattern library's own dashboard; the 96 canvas is a marquee-hero copy (100) with a 13px low-contrast note and one off-scale gap. The fixture test asserts both scores, so a scoring change fails there, not in a page test. +- **B2: the sidebar counts cards.** A state variant folds into its base in the sidebar count too (`baseRows`, now in `shared.ts`), so the sidebar and the header agree (19 canvases were 17 cards on the fixture). +- **B3: the gallery header has no breadcrumb**, as the design shows; the workspace is the sidebar's label. +- **B4: one key, two places.** The live key is `galleryKey` in `pages/project.ts`, computed once per render from the same listing as the cards, and the same fold in `client/project.ts` over `/api/canvases`. The browser test checks that nothing reloads when nothing changed. +- **B5: `scoreColor` survives until slice D.** The gallery no longer uses the 80/60 scale; the detail page's inspector still does, and slice D's Quality tab replaces it (FR-D1), so it is deleted there. + **Slice C — detail shell.** `pages/detail.ts` toolbar, More menu, delete dialog, preview tools, caption and JSON panel (FR-C1 to FR-C4). Tests rewritten: `test-archive-view.ts` (its `btn-archive`, `btn-restore`, `btn-delete` and `lifecycleAction` assertions), `test-viewer-surface.ts` (device frame and breakpoint strings), `test-desktop-app.ts:260-266` (its `bp-w1024`, `bp-w1280`, `bp-desktop` ids and `bp-btn` count), `test-variants.ts:88-98` (the detail page's state chips become the States nav), `test/browser/test-viewer-compare.ts`, `test/browser/test-viewer-surface-browser.ts` (`.bp-btn` becomes the tab selector). New: `test/browser/test-viewer-detail.ts`. The `src/viewer.ts` re-export keeps every name tests import, `evalCacheKey` included (`test-dual-theme.ts`, `test-viewer-perf.ts`, `test/e2e/test-surface.ts`). **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/`. diff --git a/src/viewer/client/project.ts b/src/viewer/client/project.ts index 68e3d97..0df23d2 100644 --- a/src/viewer/client/project.ts +++ b/src/viewer/client/project.ts @@ -1,23 +1,85 @@ -// Phase 33 slice A — the project page's browser script, moved from viewer.ts. +// Phase 33 slice B — the gallery's browser script: search and type filter +// kept in the URL (FR-B3), and the live poll with its Live / Offline status +// (FR-B4). import { COMPONENTS_JS, MOBILE_TOGGLE_JS } from '../components.js'; import { scriptJson, THUMB_FIT_JS } from '../shared.js'; -export function projectScript(projectId: string, count: number): string { +export function projectScript(projectId: string, initialKey: string): string { return ` ${MOBILE_TOGGLE_JS} ${COMPONENTS_JS} ${THUMB_FIT_JS} - // Auto-refresh: poll the canvas count for this project, reload if it changes. - let lastCount = ${scriptJson(count)}; - const projectId = ${scriptJson(projectId)}; - setInterval(async () => { - try { - const res = await fetch('/api/canvases'); - const data = await res.json(); - const inProject = data.filter((c) => c.projectId === projectId && !c.archived).length; - if (inProject !== lastCount) location.reload(); - } catch {} - }, 3000); + (() => { + const projectId = ${scriptJson(projectId)}; + const cards = Array.from(document.querySelectorAll('.card')); + const search = document.getElementById('search'); + const tablist = document.querySelector('.filter-bar [role="tablist"]'); + const noMatch = document.getElementById('no-match'); + const params = new URLSearchParams(location.search); + let query = params.get('q') || ''; + let type = params.get('type') || 'all'; + + const apply = () => { + const q = query.trim().toLowerCase(); + let shown = 0; + for (const card of cards) { + const on = (!q || card.dataset.name.includes(q)) && (type === 'all' || card.dataset.type === type); + card.hidden = !on; + if (on) shown++; + } + if (noMatch) { + noMatch.hidden = shown > 0 || cards.length === 0; + document.getElementById('no-match-text').textContent = q ? 'No canvases match \\u201c' + query.trim() + '\\u201d' : 'No canvases of this type'; + } + const next = new URLSearchParams(); + if (q) next.set('q', query.trim()); + if (type !== 'all') next.set('type', type); + const url = location.pathname + (next.toString() ? '?' + next : ''); + if (url !== location.pathname + location.search) history.replaceState(null, '', url); + }; + const selectTab = (id) => { + const tab = tablist && tablist.querySelector('[data-tab="' + id + '"]'); + if (!tab) { type = 'all'; return; } + tablist.querySelectorAll('[role="tab"]').forEach((t) => { const on = t === tab; t.setAttribute('aria-selected', on ? 'true' : 'false'); t.tabIndex = on ? 0 : -1; }); + }; + + if (search) { + search.value = query; + search.addEventListener('input', () => { query = search.value; apply(); }); + } + if (tablist) tablist.addEventListener('tabchange', (e) => { type = e.detail.tab; apply(); }); + const clear = document.getElementById('clear-filters'); + if (clear) clear.addEventListener('click', () => { query = ''; if (search) search.value = ''; selectTab('all'); type = 'all'; apply(); if (search) search.focus(); }); + selectTab(type); + apply(); + + // Live: reload when a base canvas of this project is added, removed, + // edited, renamed, retyped, re-genred or gains or loses a state. + const galleryKey = (rows) => { + const live = rows.filter((r) => r.projectId === projectId && !r.archived); + const present = new Set(live.map((r) => r.id)); + return live + .filter((r) => !(r.variant && present.has(r.variant.of))) + .map((r) => [r.id, r.versionHash, r.name, r.type || '', r.genre || '', (r.variants || []).map((v) => v.state).sort().join(',')].join('|')) + .sort() + .join('\\n'); + }; + const initialKey = ${scriptJson(initialKey)}; + const live = document.getElementById('live'); + const setLive = (ok) => { + live.classList.toggle('offline', !ok); + live.querySelector('.live-label').textContent = ok ? 'Live' : 'Offline'; + }; + setInterval(async () => { + try { + const res = await fetch('/api/canvases', { cache: 'no-store' }); + if (!res.ok) throw new Error(String(res.status)); + const rows = await res.json(); + setLive(true); + if (galleryKey(rows) !== initialKey) location.reload(); + } catch { setLive(false); } + }, 3000); + })(); `; } diff --git a/src/viewer/components.ts b/src/viewer/components.ts index 8fe71a1..08ce0ab 100644 --- a/src/viewer/components.ts +++ b/src/viewer/components.ts @@ -5,7 +5,7 @@ import { listCanvases } from '../scene-graph.js'; import { listProjects, listWorkspaces } from '../workspaces.js'; import { getIconSvg } from '../icons.js'; -import { esc } from './shared.js'; +import { baseRows, esc } from './shared.js'; import { LIGHT } from './tokens.js'; /** A bundled Lucide icon, stroked in the current text colour. */ @@ -39,11 +39,12 @@ export function projectDotToken(projectId: string): string { } /** The sidebar: wordmark; per workspace its label and one link per project - * (identity dot, name, non-archived count), or "No projects yet"; Archive + * (identity dot, name, card count), or "No projects yet"; Archive * pinned to the bottom with its count. `active` is a project id or 'archive'. */ export function renderSidebar(active: string): string { const all = listCanvases(); - const projectCount = (projectId: string) => all.filter((c) => c.projectId === projectId && !c.archived).length; + // Cards, not canvases: a state variant folds into its base, as on the page. + const projectCount = (projectId: string) => baseRows(all, projectId).length; const archivedCount = all.filter((c) => c.archived).length; const current = (on: boolean) => (on ? ' aria-current="page"' : ''); diff --git a/src/viewer/pages/project.ts b/src/viewer/pages/project.ts index 4681167..9da3413 100644 --- a/src/viewer/pages/project.ts +++ b/src/viewer/pages/project.ts @@ -1,118 +1,124 @@ -import { getCanvas, listCanvases } from '../../scene-graph.js'; -import { getProject, listWorkspaces } from '../../workspaces.js'; +// Phase 33 slice B — the project page (the gallery), design screen 1: a header +// with the project, a summary against the bar and a Live status; a search +// field and type tabs; a grid of cards, each a live thumbnail with its score +// on the corner. Search, filter and live refresh run in client/project.ts. + +import { getCanvas, listCanvases, type CanvasSummary } from '../../scene-graph.js'; +import { getProject } from '../../workspaces.js'; +import { resolveSurface, type SurfaceType } from '../../surfaces.js'; +import { resolveGenre } from '../../evaluate.js'; import { DEFAULT_PROJECT_ID } from '../../types.js'; import { baseCss, COMPONENTS_CSS, MOBILE_TOGGLE_CSS, SIDEBAR_CSS } from '../styles.js'; -import { FAVICON_HTML, MOBILE_TOGGLE_HTML, renderSidebar } from '../components.js'; -import { artboardSize, esc, renderThumb } from '../shared.js'; -import { evalFor, scoreColor } from '../scores.js'; +import { FAVICON_HTML, MOBILE_TOGGLE_HTML, icon, renderSidebar, renderTabs } from '../components.js'; +import { artboardSize, baseRows, esc, renderThumb } from '../shared.js'; +import { evalFor } from '../scores.js'; import { projectScript } from '../client/project.js'; -/** Project-scoped main page. Sidebar on left, breadcrumb + canvas grid on right. - * Returns null when the project doesn't exist so the route handler can 404. */ -export async function renderProjectPage(projectId: string, port: number): Promise { +/** The evaluator's quality bar: a score above 95 is at it. */ +export const BAR = 96; + +export const TYPE_LABELS: Record = { web: 'Web', mobile: 'Mobile', 'desktop-app': 'Desktop app' }; + +/** "Edited Nov 24", with the year when it is not the current one. */ +export function editedLabel(iso: string, now = new Date()): string { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ''; + const sameYear = d.getUTCFullYear() === now.getUTCFullYear(); + return `Edited ${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', ...(sameYear ? {} : { year: 'numeric' }), timeZone: 'UTC' })}`; +} + +/** The score chip on a card's thumbnail: quiet at the bar, amber below it. */ +function scoreChip(score: number): string { + const below = score < BAR; + return `${score}`; +} + +/** What the gallery's live poll compares (FR-B4): for each base canvas, its + * id, versionHash, name, type, genre and designed states. versionHash alone + * misses a rename, a genre change, a new state and a type change. Mirrors + * galleryKey in client/project.ts, which computes it from /api/canvases. */ +export function galleryKey(rows: Array, projectId: string): string { + return baseRows(rows, projectId) + .map((r) => { + const c = getCanvas(r.id); + const type = r.type ?? (c ? resolveSurface(c).type : ''); + const genre = r.genre !== undefined ? r.genre : (c ? resolveGenre(c).genre : null); + return [r.id, r.versionHash, r.name, type, genre ?? '', (r.variants ?? []).map((v) => v.state).sort().join(',')].join('|'); + }) + .sort() + .join('\n'); +} + +/** Project-scoped main page. Returns null when the project doesn't exist so + * the route handler can 404. */ +export async function renderProjectPage(projectId: string, _port: number): Promise { const project = getProject(projectId); if (!project) return null; - // Find the parent workspace for the breadcrumb. Default to "Personal" if - // somehow orphaned (shouldn't happen after slice 1 migration). - const ws = listWorkspaces().find((w) => w.id === project.workspaceId); - const wsName = ws?.name ?? 'Personal'; - // One listing for the whole render: it version-hashes every canvas in the // store, so it is the most expensive call on this path and must not be // repeated per card. - const allRows = listCanvases(); - const statesById = new Map(allRows.map((r) => [r.id, r.variants?.map((v) => v.state) ?? []])); - const canvases = allRows.filter((c) => c.projectId === projectId && !c.archived); - // Phase 24 slice A — a screen and its state variants are ONE card: variants - // whose base is in this listing fold into the base card as chips. A variant - // whose base is missing (orphan) or lives elsewhere stays a standalone card. - const present = new Set(canvases.map((c) => c.id)); - const shown = canvases.filter((c) => !(c.variant && present.has(c.variant.of))); - const cards = (await Promise.all(shown.map(async (c) => { + const rows = listCanvases(); + const shown = baseRows(rows, projectId); + const typeCounts: Record = { web: 0, mobile: 0, 'desktop-app': 0 }; + let below = 0; + + const cards = await Promise.all(shown.map(async (c) => { const canvas = getCanvas(c.id)!; const { w, h } = artboardSize(canvas); - const date = new Date(c.createdAt).toLocaleString(); - // Phase 19 Slice A — gallery score badge (fast eval, cached; empty → none). - const ev = await evalFor(canvas, statesById.get(c.id) ?? []); - const scoreBadge = ev - ? `
${ev.overallScore}
` - : ''; - const stateChips = c.variants?.length - ? `
- default - ${c.variants.map((v) => `${esc(v.state)}`).join('')} -
` - : ''; - return stateChips - ? ` - ` - : ` - - ${renderThumb(canvas, scoreBadge)} -
-
${esc(c.name)}
-
${w} x ${h} · ${esc(date)}
+ const type = resolveSurface(canvas).type; + typeCounts[type]++; + const states = c.variants?.map((v) => v.state) ?? []; + const ev = await evalFor(canvas, states); + if (ev && ev.overallScore < BAR) below++; + const meta = [TYPE_LABELS[type], `${w} × ${h}`, editedLabel(c.lastModified), ...(states.length ? [`${states.length} state${states.length === 1 ? '' : 's'}`] : [])].filter(Boolean).join(' · '); + return ` +
`; + })); - const emptyState = canvases.length === 0 + const n = shown.length; + const summary = `${n} canvas${n === 1 ? '' : 'es'}${n === 0 ? '' : below === 0 ? ' · all at the bar' : ` · ${below} below the bar`}`; + const tabs = renderTabs([ + { id: 'all', label: 'All', count: n, selected: true }, + ...(Object.keys(typeCounts) as SurfaceType[]).filter((t) => typeCounts[t] > 0).map((t) => ({ id: t, label: TYPE_LABELS[t], count: typeCounts[t] })), + ], 'Canvas type'); + + const body = n === 0 ? `
-
▢
-
No canvases in ${esc(project.name)} yet
-
Create one via your MCP client using canvas_create({ projectId: "${project.id}" })
-
` - : ''; +
${icon('layout-grid', 32)}
+
No canvases in ${esc(project.name)} yet
+
Create one from your MCP client with canvas_create({ projectId: "${esc(project.id)}" }).
+
` + : `
+ + ${tabs} +
+
+
${cards.join('')}
+ +
`; return ` - + -${esc(project.name)} — Framesmith + +${esc(project.name)} — framesmith ${FAVICON_HTML} @@ -121,21 +127,70 @@ ${FAVICON_HTML}
${renderSidebar(projectId)}
-
- -

${esc(project.name)}

-
${canvases.length} canvas${canvases.length !== 1 ? 'es' : ''}
-
- ${canvases.length > 0 ? `
${cards}
` : emptyState} +
+

${esc(project.name)}

+
+ ${esc(summary)} + Live +
+
+ ${body}
`; } +const GALLERY_CSS = ` + .main { flex: 1; min-width: 0; display: flex; flex-direction: column; background: var(--bg-primary); } + .main-header { height: 48px; flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); padding: 0 var(--space-md); border-bottom: 1px solid var(--border); } + .page-title { font-size: 18px; font-weight: 600; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .header-side { display: flex; align-items: center; gap: var(--space-md); min-width: 0; } + .summary { font-size: var(--font-label); color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } + .live { display: inline-flex; align-items: center; gap: var(--space-2xs); font-size: var(--font-label); color: var(--text-secondary); white-space: nowrap; } + .live-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--success); } + .live.offline .live-dot { background: var(--border-strong); } + + .filter-bar { min-height: 48px; flex-shrink: 0; display: flex; align-items: center; gap: var(--space-md); padding: var(--space-xs) var(--space-md); border-bottom: 1px solid var(--border); flex-wrap: wrap; } + .search { display: flex; align-items: center; gap: var(--space-xs); width: 280px; max-width: 100%; height: 32px; padding: 0 var(--space-xs); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); background: var(--bg-surface); color: var(--text-secondary); } + .search:focus-within { outline: 2px solid var(--focus-ring); outline-offset: 1px; } + .search input { flex: 1; min-width: 0; border: none; outline: none; background: transparent; font: inherit; font-size: var(--font-body); color: var(--text-primary); } + .search input::placeholder { color: var(--text-secondary); } + .filter-bar .tablist { border-bottom: none; gap: var(--space-2xs); } + .filter-bar .tab { padding: 0 var(--space-xs); border-radius: var(--radius-sm); } + .filter-bar .tab[aria-selected="true"] { background: var(--accent-tint); } + .filter-bar .tab[aria-selected="true"]::after { display: none; } + + .grid-pane { flex: 1; padding: var(--space-lg); } + .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: var(--space-lg); align-items: start; } + .card { position: relative; display: flex; flex-direction: column; background: var(--bg-surface); border: 1px solid var(--border); border-radius: var(--radius-md); overflow: hidden; box-shadow: var(--elevation-flat); transition: border-color 0.15s, box-shadow 0.15s; } + .card:hover { border-color: var(--border-strong); box-shadow: var(--elevation-raised); } + .card:has(.card-name:focus-visible) { outline: 2px solid var(--focus-ring); outline-offset: 2px; } + .card[hidden] { display: none; } + .thumb { width: 100%; overflow: hidden; background: var(--bg-elevated); position: relative; border-bottom: 1px solid var(--border); } + .thumb iframe { border: none; transform-origin: 0 0; transform: scale(var(--thumb-scale, 0.222)); pointer-events: none; position: absolute; top: 0; left: 0; } + .thumb-empty { position: absolute; inset: 0; } + .thumb-empty-back, .thumb-empty-front { position: absolute; width: 38px; height: 28px; border-radius: 4px; border: 1px solid var(--border); } + .thumb-empty-back { top: calc(50% - 6px); left: calc(50% - 27px); } + .thumb-empty-front { top: calc(50% - 10px); left: calc(50% - 19px); background: var(--bg-surface); border-color: var(--border-strong); } + .score-chip { position: absolute; top: var(--space-xs); right: var(--space-xs); z-index: 2; font-size: var(--font-caption); font-weight: 600; font-variant-numeric: tabular-nums; line-height: 1.5; padding: 2px 6px; border-radius: var(--radius-sm); background: var(--neutral-tint); color: var(--text-secondary); pointer-events: none; } + .score-chip--below { background: var(--warning-tint); color: var(--warning); } + .card-copy { display: flex; flex-direction: column; gap: 2px; padding: var(--space-sm) var(--space-md); min-width: 0; } + .card-name { font-size: var(--font-body); font-weight: 600; color: var(--text-primary); text-decoration: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; outline: none; } + .card-name::after { content: ''; position: absolute; inset: 0; z-index: 1; } + .card-meta { font-size: var(--font-caption); color: var(--text-secondary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + + .empty, .no-match { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--space-sm); padding: 120px var(--space-lg); text-align: center; color: var(--text-secondary); } + .no-match[hidden] { display: none; } + .empty-icon { color: var(--text-secondary); } + .empty-title { font-size: var(--font-body); font-weight: 600; color: var(--text-primary); } + .empty-hint { font-size: var(--font-label); max-width: 480px; } + .empty-hint code { background: var(--neutral-tint); padding: 2px 6px; border-radius: 4px; font-size: var(--font-label); color: var(--text-primary); } + @media (max-width: 640px) { .main-header { height: auto; min-height: 48px; flex-wrap: wrap; row-gap: 2px; padding-top: var(--space-xs); padding-bottom: var(--space-xs); } .filter-bar .tablist { overflow-x: auto; max-width: 100%; } .grid-pane { padding: var(--space-md); } .grid { grid-template-columns: 1fr; } }`; + /** Backwards-compatible alias: renders the default project. The previous * `renderGalleryPage` was a flat all-canvases view; the new model is * project-scoped, and the default project is the natural landing place. */ diff --git a/src/viewer/server.ts b/src/viewer/server.ts index 621edc0..58efd71 100644 --- a/src/viewer/server.ts +++ b/src/viewer/server.ts @@ -8,6 +8,7 @@ import { getCanvasTokens } from '../workspaces.js'; import { getRepoLocation, archiveRepoCanvas, deleteRepoCanvas, updateRepoCanvas } from '../aggregate.js'; import { DEFAULT_PROJECT_ID, type Canvas } from '../types.js'; import { resolveSurface } from '../surfaces.js'; +import { resolveGenre } from '../evaluate.js'; import { addFeedback, listFeedback, resolveFeedback, deleteFeedback, openFeedbackCount } from '../feedback.js'; import { cachedFontFile, resolveFamily } from '../fonts.js'; import { evalCacheKey } from './scores.js'; @@ -108,7 +109,12 @@ export async function startViewer(port: number): Promise { // API: list canvases if (path === '/api/canvases') { res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(listCanvases())); + // Phase 33 slice B — each row carries its type and genre, which the + // gallery's live poll compares (FR-B4). + res.end(JSON.stringify(listCanvases().map((row) => { + const canvas = getCanvas(row.id); + return canvas ? { ...row, type: resolveSurface(canvas).type, genre: resolveGenre(canvas).genre } : row; + }))); return; } diff --git a/src/viewer/shared.ts b/src/viewer/shared.ts index e54d328..980dade 100644 --- a/src/viewer/shared.ts +++ b/src/viewer/shared.ts @@ -1,6 +1,7 @@ // Phase 33 slice A — helpers every viewer page shares: escaping, safe script // JSON, the node index, and the artboard-proportioned thumbnails. import type { Canvas, SceneNode } from '../types.js'; +import type { CanvasSummary } from '../scene-graph.js'; import { DEFAULT_DEVICE, DEVICE_PROFILES } from '../surfaces.js'; export function esc(str: string): string { @@ -75,3 +76,11 @@ export const THUMB_FIT_JS = ` const observer = new ResizeObserver((entries) => entries.forEach((e) => fit(e.target))); thumbs.forEach((t) => observer.observe(t)); })();`; + +/** The base canvases a project page shows as cards: a variant whose base is in + * the project folds into that base (Phase 24); an orphan stays a card. */ +export function baseRows(rows: T[], projectId: string): T[] { + const live = rows.filter((c) => c.projectId === projectId && !c.archived); + const present = new Set(live.map((c) => c.id)); + return live.filter((c) => !(c.variant && present.has(c.variant.of))); +} diff --git a/src/viewer/styles.ts b/src/viewer/styles.ts index b26a401..b24877f 100644 --- a/src/viewer/styles.ts +++ b/src/viewer/styles.ts @@ -146,7 +146,7 @@ export const COMPONENTS_CSS = ` .btn[aria-expanded="true"] { background: var(--hover); } .tablist { display: flex; gap: var(--space-md); border-bottom: 1px solid var(--border); } - .tab { position: relative; height: 32px; padding: 0 var(--space-2xs); border: none; background: none; font: inherit; font-size: var(--font-body); font-weight: 500; color: var(--text-secondary); cursor: pointer; display: inline-flex; align-items: center; gap: var(--space-2xs); } + .tab { position: relative; white-space: nowrap; flex-shrink: 0; height: 32px; padding: 0 var(--space-2xs); border: none; background: none; font: inherit; font-size: var(--font-body); font-weight: 500; color: var(--text-secondary); cursor: pointer; display: inline-flex; align-items: center; gap: var(--space-2xs); } .tab:hover { color: var(--text-primary); } .tab[aria-selected="true"] { color: var(--text-primary); font-weight: 600; } .tab[aria-selected="true"]::after { content: ''; position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; background: var(--accent); border-radius: 2px; } diff --git a/test/browser/test-viewer-gallery.ts b/test/browser/test-viewer-gallery.ts new file mode 100644 index 0000000..3520c27 --- /dev/null +++ b/test/browser/test-viewer-gallery.ts @@ -0,0 +1,137 @@ +// Phase 33 slice B — the gallery on the fixture store: cards, counts and the +// summary (FR-B1), score chips against the bar (FR-B2), search and type +// filter kept in the URL (FR-B3), and the live poll (FR-B4). +// +// Usage: npx tsx test/browser/test-viewer-gallery.ts + +import '../env.js'; +import { createServer } from 'node:net'; +import puppeteer, { type Page } from 'puppeteer'; +import { getCanvas, listCanvases, touchCanvas, addVariant, setCanvasGenre, setCanvasType } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { startViewer } from '../../src/viewer.js'; +import { evalFor } from '../../src/viewer/scores.js'; +import { baseRows } from '../../src/viewer/shared.js'; +import { seedViewerStore } from '../fixtures/viewer-store.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const store = seedViewerStore(); +const port = await new Promise((resolve) => { + const s = createServer(); + s.listen(0, '127.0.0.1', () => { const { port: p } = s.address() as { port: number }; s.close(() => resolve(p)); }); +}); +await startViewer(port); +const url = `http://127.0.0.1:${port}/project/${store.patternProjectId}`; + +const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] }); +const page = await browser.newPage(); +await page.setViewport({ width: 1440, height: 900 }); +const errors: string[] = []; +page.on('pageerror', (e) => errors.push(String(e))); +await page.goto(url, { waitUntil: 'load' }); + +// ── FR-B1: cards, counts, summary, meta ────────────────────────────────────── +const bases = baseRows(listCanvases(), store.patternProjectId); +let below = 0; +for (const row of bases) { + const ev = await evalFor(getCanvas(row.id)!, row.variants?.map((v) => v.state) ?? []); + if (ev && ev.overallScore < 96) below++; +} +const cardCount = await page.$$eval('article.card', (cards) => cards.length); +check('one card per base canvas', cardCount === bases.length, `${cardCount} vs ${bases.length}`); +const summary = await page.$eval('#summary', (s) => s.textContent); +check('summary counts canvases and those below the bar', summary === `${bases.length} canvases · ${below} below the bar`, `${summary} (below=${below})`); +const tabs = await page.$$eval('.filter-bar [role="tab"]', (ts) => ts.map((t) => t.textContent!.replace(/\s+/g, ' ').trim())); +check('type tabs carry their counts', JSON.stringify(tabs) === JSON.stringify([`All ${bases.length}`, `Web ${bases.length - 2}`, 'Mobile 1', 'Desktop app 1']), JSON.stringify(tabs)); +const meta = (id: string) => page.$eval(`[data-canvas-id="${id}"] .card-meta`, (m) => m.textContent); +check('meta line: type, size and edited date', (await meta(store.ids.auth)) === 'Web · 1440 × 900 · Edited Jun 26', String(await meta(store.ids.auth))); +check('meta line: a screen with states counts them', (await meta(store.ids.withStates))?.endsWith(' · 2 states') === true, String(await meta(store.ids.withStates))); +const height = (id: string) => page.$eval(`[data-canvas-id="${id}"] .thumb`, (t) => t.getBoundingClientRect().height); +check('a phone card is taller than a web card', (await height(store.ids.mobile)) > (await height(store.ids.auth)) * 1.5); +const link = await page.$eval(`[data-canvas-id="${store.ids.auth}"] .card-name`, (a) => a.getAttribute('href')); +check('the card name links to the canvas', link === `/canvas/${store.ids.auth}`); + +// ── FR-B2: score chips against the bar ─────────────────────────────────────── +const chip = (id: string) => page.$eval(`[data-canvas-id="${id}"]`, (card) => { + const c = card.querySelector('.score-chip'); + return c ? { text: c.textContent, below: c.classList.contains('score-chip--below') } : null; +}); +check('100 is a neutral chip', JSON.stringify(await chip(store.ids['marquee-hero'])) === '{"text":"100","below":false}'); +check('96 is a neutral chip (at the bar)', JSON.stringify(await chip(store.ids.at96)) === '{"text":"96","below":false}', JSON.stringify(await chip(store.ids.at96))); +check('95 is a warning chip (below the bar)', JSON.stringify(await chip(store.ids.at95)) === '{"text":"95","below":true}', JSON.stringify(await chip(store.ids.at95))); +check('an empty canvas shows no chip', (await chip(store.ids.blank)) === null); +const colors = await page.$eval(`[data-canvas-id="${store.ids.at95}"] .score-chip`, (c) => { const s = getComputedStyle(c); return s.color + ' / ' + s.backgroundColor; }); +const neutralColors = await page.$eval(`[data-canvas-id="${store.ids.at96}"] .score-chip`, (c) => { const s = getComputedStyle(c); return s.color + ' / ' + s.backgroundColor; }); +check('the below-the-bar chip is drawn differently from the neutral one', colors !== neutralColors, `${colors} vs ${neutralColors}`); + +// ── FR-B3: search and filter, kept in the URL ──────────────────────────────── +const visible = (p: Page) => p.$$eval('article.card', (cards) => cards.filter((c) => !(c as HTMLElement).hidden).map((c) => (c.querySelector('.card-name') as HTMLElement).textContent)); +await page.type('#search', 'AUTH'); +check('search filters by name, case-insensitive', JSON.stringify((await visible(page)).sort()) === '["auth","auth-feedback"]', JSON.stringify(await visible(page))); +check('the query is kept in the URL', new URL(page.url()).searchParams.get('q') === 'AUTH'); +await page.click('[data-tab="mobile"]'); +check('the type tab narrows the search further', (await visible(page)).length === 0); +check('no match shows the message and a Clear button', await page.$eval('#no-match', (n) => !(n as HTMLElement).hidden && n.textContent!.includes('No canvases match “AUTH”'))); +await page.click('#clear-filters'); +check('Clear restores every card', (await visible(page)).length === bases.length); +check('Clear empties the URL', new URL(page.url()).search === ''); +await page.goto(`${url}?q=auth&type=web`, { waitUntil: 'load' }); +check('reloading ?q=auth&type=web restores the query', (await page.$eval('#search', (i) => (i as HTMLInputElement).value)) === 'auth'); +check('…and the Web tab', (await page.$eval('[role="tab"][aria-selected="true"]', (t) => (t as HTMLElement).dataset.tab)) === 'web'); +check('…and the filtered cards', JSON.stringify((await visible(page)).sort()) === '["auth","auth-feedback"]'); + +// ── FR-B4: live ────────────────────────────────────────────────────────────── +await page.goto(url, { waitUntil: 'load' }); +const mark = () => page.evaluate(() => { (window as unknown as { __mark: boolean }).__mark = true; }); +const reloaded = async () => !(await page.evaluate(() => (window as unknown as { __mark?: boolean }).__mark)); +const settle = () => new Promise((r) => setTimeout(r, 7000)); // two polls + +await mark(); await settle(); +check('no reload when nothing changed', !(await reloaded())); +check('the status reads Live', (await page.$eval('#live .live-label', (l) => l.textContent)) === 'Live'); + +const edited = getCanvas(store.ids.catalogue)!; +parseAndExecute(edited.root, 'I("document", { type: "text", content: "edited" })', edited); +touchCanvas(edited.id); +await settle(); +check('an edit reloads the gallery', await reloaded()); + +await page.waitForSelector('#live'); await mark(); +getCanvas(store.ids.onboarding)!.name = 'onboarding-renamed'; +await settle(); +check('a rename reloads the gallery', await reloaded()); +check('…and shows the new name', (await page.$eval(`[data-canvas-id="${store.ids.onboarding}"] .card-name`, (a) => a.textContent)) === 'onboarding-renamed'); + +await mark(); +addVariant(store.ids.pricing, 'empty'); +await settle(); +check('a new state variant reloads the gallery', await reloaded()); +check('…and the card counts it', (await meta(store.ids.pricing))?.endsWith(' · 1 state') === true, String(await meta(store.ids.pricing))); + +// Genre and type live in metadata, outside versionHash; the key carries both. +await mark(); +setCanvasGenre(store.ids['stat-led'], 'data'); +await settle(); +check('a genre change reloads the gallery', await reloaded()); + +await mark(); +setCanvasType(store.ids['editorial-longform'], { type: 'mobile' }); +await settle(); +check('a type change reloads the gallery', await reloaded()); +check('…and the card shows the new type', (await meta(store.ids['editorial-longform']))?.startsWith('Mobile · ') === true, String(await meta(store.ids['editorial-longform']))); + +await page.setOfflineMode(true); +await new Promise((r) => setTimeout(r, 3500)); +check('a failed poll shows Offline', (await page.$eval('#live .live-label', (l) => l.textContent)) === 'Offline'); +await page.setOfflineMode(false); +await new Promise((r) => setTimeout(r, 3500)); +check('the next good poll shows Live again', (await page.$eval('#live .live-label', (l) => l.textContent)) === 'Live'); + +check('no page error', errors.length === 0, errors.join(' | ').slice(0, 300)); +await browser.close(); +process.exit(allPass ? 0 : 1); diff --git a/test/fixtures/viewer-store.ts b/test/fixtures/viewer-store.ts new file mode 100644 index 0000000..664649b --- /dev/null +++ b/test/fixtures/viewer-store.ts @@ -0,0 +1,115 @@ +// Phase 33 — the viewer fixture store (PHASE-33-SPEC §3 PLAN). Seeds whatever +// store FRAMESMITH_HOME points at (import '../env.js' first, so that is a temp +// dir) with what the viewer's pages and screenshots need: +// +// Personal / Untitled the default project, empty (the empty state) +// Personal / Pattern library a copy of the repo's pattern library, plus a +// mobile and a desktop-app canvas, one canvas with +// two state variants, one empty canvas, one canvas +// with open and resolved comments, and canvases +// scoring exactly 96 and 95 +// Personal / Archived work three archived canvases +// +// Built through the store's own functions rather than checked in as JSON, so it +// follows the canvas format as it changes. Copies keep their source's dates, so +// "Edited " is stable. + +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { loadPersistedWorkspaces, ensureDefaultWorkspaceAndProject, createProject } from '../../src/workspaces.js'; +import { createCanvas, touchCanvas, addVariant, archiveCanvas, getCanvas } from '../../src/scene-graph.js'; +import { applyStructure } from '../../src/structures.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { addFeedback, resolveFeedback } from '../../src/feedback.js'; +import { DEFAULT_PROJECT_ID, DEFAULT_WORKSPACE_ID, type Canvas } from '../../src/types.js'; + +export interface ViewerStore { + patternProjectId: string; + archivedProjectId: string; + /** Canvas ids by role: each pattern copy by its source name, plus mobile, + * desktopApp, withStates, blank, withFeedback, at96, at95, archived1..3. */ + ids: Record; +} + +const PATTERN_DIR = join('.framesmith', 'pattern-library'); + +/** A copy of a repo canvas file in `projectId`, keeping its content and dates. */ +function copyCanvas(file: string, projectId: string, name?: string): Canvas { + const source = JSON.parse(readFileSync(join(PATTERN_DIR, file), 'utf-8')) as Canvas; + const canvas = createCanvas(name ?? source.name, projectId); + canvas.root = source.root; + canvas.variables = source.variables ?? {}; + canvas.components = source.components ?? {}; + canvas.metadata = { ...(source.metadata ?? {}) }; + touchCanvas(canvas.id); + canvas.createdAt = source.createdAt; + canvas.lastModified = source.lastModified; + return canvas; +} + +export function seedViewerStore(): ViewerStore { + loadPersistedWorkspaces(); + ensureDefaultWorkspaceAndProject(); + const pattern = createProject(DEFAULT_WORKSPACE_ID, 'Pattern library')!; + const archivedProject = createProject(DEFAULT_WORKSPACE_ID, 'Archived work')!; + const ids: Record = {}; + + for (const file of readdirSync(PATTERN_DIR).filter((f) => f.endsWith('.json')).sort()) { + const c = copyCanvas(file, pattern.id); + ids[c.name] = c.id; + } + + // One canvas of each other type, from their realisations. + const mobile = createCanvas('mobile-dashboard', pattern.id, {}, { type: 'mobile' }); + applyStructure(mobile, 'dashboard'); + touchCanvas(mobile.id); + ids.mobile = mobile.id; + const app = createCanvas('file-browser', pattern.id, {}, { type: 'desktop-app' }); + applyStructure(app, 'browser'); + touchCanvas(app.id); + ids.desktopApp = app.id; + + // A screen with two designed states. + const withStates = copyCanvas('settings.json', pattern.id, 'settings-states'); + addVariant(withStates.id, 'empty'); + addVariant(withStates.id, 'loading'); + ids.withStates = withStates.id; + + ids.blank = createCanvas('blank', pattern.id).id; + + // Open and resolved point-and-tell comments. + const withFeedback = copyCanvas('auth.json', pattern.id, 'auth-feedback'); + const target = withFeedback.root.children?.[0]?.id; + addFeedback(withFeedback, { comment: 'The sign-in button reads too quiet.', ...(target ? { nodeId: target } : {}) }); + const done = addFeedback(withFeedback, { comment: 'Tighten the heading spacing.' }); + resolveFeedback(withFeedback, [done.id], 'agent', 'Spacing moved to the scale.'); + touchCanvas(withFeedback.id); + ids.withFeedback = withFeedback.id; + + // Either side of the bar (a score above 95): the pattern library's own + // dashboard scores 95, and a marquee-hero copy (100) with an off-scale note + // (13px, low contrast) and one off-scale gap scores 96. The fixture test + // asserts both, so a scoring change shows up there, not in a page test. + ids.at95 = ids.dashboard; + const at96 = copyCanvas('marquee-hero.json', pattern.id, 'marquee-96'); + parseAndExecute(at96.root, AT_96_OPS, at96); + touchCanvas(at96.id); + ids.at96 = at96.id; + + // Three archived canvases, newest last. + for (let i = 1; i <= 3; i++) { + const c = copyCanvas(['pricing.json', 'stat-led.json', 'bento-grid.json'][i - 1], archivedProject.id, `old-${i}`); + archiveCanvas(c.id); + getCanvas(c.id)!.archivedAt = new Date(Date.UTC(2026, 10, 10 + i)).toISOString(); + ids[`archived${i}`] = c.id; + } + + return { patternProjectId: pattern.id, archivedProjectId: archivedProject.id, ids }; +} + +const AT_96_OPS = [ + 'I("mh-hero", { type: "text", name: "Off-scale note", content: "Draft note", fontSize: 13 })', + 'I("mh-hero", { type: "frame", name: "Off-scale gap", width: 100, height: 40, gap: 13, layout: "horizontal" })', +].join('\n'); + +export { DEFAULT_PROJECT_ID }; diff --git a/test/unit/test-empty-thumbnail.ts b/test/unit/test-empty-thumbnail.ts index 1c718a9..6b1659a 100644 --- a/test/unit/test-empty-thumbnail.ts +++ b/test/unit/test-empty-thumbnail.ts @@ -52,7 +52,7 @@ check( ); // The empty card should NOT have an iframe; the with-content one should. -const emptyCardMatch = html.match(new RegExp(`href="/canvas/${emptyCanvas.id}"[^]*?`)); +const emptyCardMatch = html.match(new RegExp(`data-canvas-id="${emptyCanvas.id}"[^]*?`)); check('empty card section located in gallery', !!emptyCardMatch); if (emptyCardMatch) { check( @@ -65,7 +65,7 @@ if (emptyCardMatch) { ); } -const contentCardMatch = html.match(new RegExp(`href="/canvas/${withContent.id}"[^]*?`)); +const contentCardMatch = html.match(new RegExp(`data-canvas-id="${withContent.id}"[^]*?`)); check('with-content card section located in gallery', !!contentCardMatch); if (contentCardMatch) { check( @@ -79,7 +79,6 @@ if (contentCardMatch) { } // CSS hooks for the new placeholder must be in the inline stylesheet. -check('CSS contains .thumb--empty rule', html.includes('.thumb--empty')); check('CSS contains .thumb-empty rule (placeholder body)', html.includes('.thumb-empty {')); check('CSS contains .thumb-empty-back/front rules (layered hairlines)', html.includes('.thumb-empty-back') && html.includes('.thumb-empty-front')); diff --git a/test/unit/test-variants.ts b/test/unit/test-variants.ts index bc25a1c..9b4b454 100644 --- a/test/unit/test-variants.ts +++ b/test/unit/test-variants.ts @@ -82,8 +82,10 @@ check('base row has no variant field', baseRow.variant === undefined); // ── viewer: one card + chips; detail cross-links; orphan-safe ─────────────── const page = await renderProjectPage(DEFAULT_PROJECT_ID, 0); -check('gallery folds variants into base card', page !== null && !page!.includes('Orders · empty'), undefined); -check('gallery base card shows state chips', !!page && page.includes('state-chip') && page.includes('>empty') && page.includes('>loading')); +check('gallery folds variants into base card', page !== null && !page!.includes(`data-canvas-id="${empty.id}"`) && !page!.includes(`data-canvas-id="${loading.id}"`) && page!.includes(`data-canvas-id="${base.id}"`)); +// Phase 33 slice B: the card's meta line counts the states; variants never get a card of their own. +const baseCard = page ? page.slice(page.indexOf(`data-canvas-id="${base.id}"`), page.indexOf('', page.indexOf(`data-canvas-id="${base.id}"`))) : ''; +check('gallery base card counts its two states', baseCard.includes(' · 2 states'), baseCard.slice(0, 200)); const detailBase = await renderDetailPage(getCanvas(base.id)!, 0); check('base detail chips: default active + links', detailBase.includes('state-chip--active">default') && detailBase.includes(`/canvas/${empty.id}`)); diff --git a/test/unit/test-viewer-fixture.ts b/test/unit/test-viewer-fixture.ts new file mode 100644 index 0000000..a21b1c7 --- /dev/null +++ b/test/unit/test-viewer-fixture.ts @@ -0,0 +1,53 @@ +// Phase 33 — the viewer fixture store holds what the spec says it holds, and +// its two canvases either side of the bar score exactly 96 and 95. When scoring +// changes, this test names it instead of a gallery test failing obscurely. +// +// Usage: npx tsx test/unit/test-viewer-fixture.ts + +import '../env.js'; +import { listCanvases, getCanvas } from '../../src/scene-graph.js'; +import { listProjects } from '../../src/workspaces.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { resolveSurface } from '../../src/surfaces.js'; +import { DEFAULT_PROJECT_ID } from '../../src/types.js'; +import { seedViewerStore } from '../fixtures/viewer-store.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const store = seedViewerStore(); +const rows = listCanvases(); +const inProject = (projectId: string) => rows.filter((r) => r.projectId === projectId); +const score = async (id: string) => { + const row = rows.find((r) => r.id === id)!; + return (await evaluateCanvas(getCanvas(id)!, { mode: 'fast', designedStates: row.variants?.map((v) => v.state) ?? [] })).overallScore; +}; + +check('three projects: Untitled, Pattern library, Archived work', + JSON.stringify(listProjects().map((p) => p.name).sort()) === JSON.stringify(['Archived work', 'Pattern library', 'Untitled'])); +check('the default project is empty', inProject(DEFAULT_PROJECT_ID).length === 0); + +const pattern = inProject(store.patternProjectId); +check('the pattern library copies all eleven repo canvases', ['auth', 'bento-grid', 'catalogue', 'dashboard', 'editorial-longform', 'marquee-hero', 'onboarding', 'pricing', 'settings', 'split-workbench', 'stat-led'].every((n) => pattern.some((r) => r.name === n))); +check('one mobile and one desktop-app canvas', resolveSurface(getCanvas(store.ids.mobile)!).type === 'mobile' && resolveSurface(getCanvas(store.ids.desktopApp)!).type === 'desktop-app'); +const states = rows.find((r) => r.id === store.ids.withStates)?.variants?.map((v) => v.state).sort(); +check('one canvas with the empty and loading states', JSON.stringify(states) === '["empty","loading"]', JSON.stringify(states)); +check('one empty canvas', (getCanvas(store.ids.blank)!.root.children ?? []).length === 0); +const feedback = getCanvas(store.ids.withFeedback)!.metadata?.feedback ?? []; +check('one canvas with an open and a resolved comment', feedback.filter((e) => !e.resolvedAt).length === 1 && feedback.filter((e) => e.resolvedAt).length === 1); +check('copies keep their source dates', getCanvas(store.ids.auth)!.lastModified.startsWith('2026-06-26'), getCanvas(store.ids.auth)!.lastModified); + +check('marquee-hero scores 100', (await score(store.ids['marquee-hero'])) === 100); +const at96 = await score(store.ids.at96); +check('the at-the-bar canvas scores exactly 96', at96 === 96, String(at96)); +const at95 = await score(store.ids.at95); +check('the below-the-bar canvas scores exactly 95', at95 === 95, String(at95)); + +const archived = inProject(store.archivedProjectId); +check('three archived canvases in Archived work', archived.length === 3 && archived.every((r) => r.archived)); +check('archived canvases carry distinct archive dates', new Set(archived.map((r) => getCanvas(r.id)!.archivedAt)).size === 3); + +process.exit(allPass ? 0 : 1); diff --git a/test/unit/test-viewer-panels.ts b/test/unit/test-viewer-panels.ts index 59f8534..dda82d3 100644 --- a/test/unit/test-viewer-panels.ts +++ b/test/unit/test-viewer-panels.ts @@ -64,7 +64,7 @@ I(page, { type:"text", content:"A short honest description.", fontSize:16, color console.log('\n── gallery: score badge per card ──'); // Both fixtures landed in the default project; render it and check the badge. const proj = await renderProjectPage(projectId, 3001) ?? ''; - assert(proj.includes('class="card-score"'), 'the gallery stamps a score badge on scored cards'); + assert(/Untitled<\/h1>/.test(htmlDefault)); +check('main: title shows "Untitled"', /

Untitled<\/h1>/.test(htmlDefault)); check('main: project-meta shows "2 canvases"', htmlDefault.includes('2 canvases')); // ---- 5. Canvas grid is project-scoped ----------------------------------- @@ -94,8 +93,7 @@ check('main: grid does NOT contain archived "old" canvas', !htmlDefault.includes // ---- 6. Acme project page scoping --------------------------------------- const htmlAcme = (await viewer.renderProjectPage(projAcmeA.id, 3001))!; -check('acme page: breadcrumb shows "Acme / Brand"', htmlAcme.includes('Acme / Brand')); -check('acme page: title shows "Brand"', /

Brand<\/h1>/.test(htmlAcme)); +check('acme page: title shows "Brand"', /

Brand<\/h1>/.test(htmlAcme)); check('acme page: the current place is Brand, not Untitled', sidebarItem(htmlAcme, projAcmeA.id)?.current === true && sidebarItem(htmlAcme, DEFAULT_PROJECT_ID)?.current === false, ); diff --git a/test/unit/test-viewer-surface.ts b/test/unit/test-viewer-surface.ts index 47a13df..3c0279e 100644 --- a/test/unit/test-viewer-surface.ts +++ b/test/unit/test-viewer-surface.ts @@ -36,12 +36,12 @@ function make(name: string, size: { width?: number; height?: number }, surface?: return c; } -/** The card markup for one canvas: from its card's opening tag to the next card. */ +/** The card markup for one canvas: its