diff --git a/README.md b/README.md index b4adbd1..d51683c 100644 --- a/README.md +++ b/README.md @@ -1380,6 +1380,7 @@ The standalone viewer: - **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 +- **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` 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 31a62d2..6fdb50f 100644 --- a/VISION.md +++ b/VISION.md @@ -599,11 +599,12 @@ _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. -- [ ] Slice A — foundation: `src/viewer/` modules, tokens copied from the design system and pinned by a test, fonts served from the cache, one sidebar, tabs, menu and dialog used everywhere +- [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 - [ ] 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 +- [ ] 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 _Full spec-driven breakdown in [`docs/specs/PHASE-33-SPEC.md`](docs/specs/PHASE-33-SPEC.md). Deliberately out of scope: a bundler or framework, a theme toggle, static thumbnails, a mirror marker, the Import tab's content, and the CORS policy on mutating routes (its own change)._ diff --git a/src/fonts.ts b/src/fonts.ts index 3091bca..20d36b4 100644 --- a/src/fonts.ts +++ b/src/fonts.ts @@ -202,6 +202,24 @@ function mimeOf(ext: string): string { return ext === 'woff2' ? 'font/woff2' : ext === 'woff' ? 'font/woff' : ext === 'otf' ? 'font/otf' : 'font/ttf'; } +/** Phase 33 — the cached faces of a family whose files are on disk, with no + * network: what the viewer declares in @font-face and serves by file name. */ +export function cachedFontFaces(family: string): Array<{ family: string; file: string; weight?: string; style?: 'normal' | 'italic' }> { + const entry = readRegistry().families[family.toLowerCase()]; + return (entry?.faces ?? []) + .filter((face) => existsSync(join(fontsDir(), face.file))) + .map(({ family: name, file, weight, style }) => ({ family: name, file, ...(weight !== undefined ? { weight } : {}), ...(style ? { style } : {}) })); +} + +/** A cached font file by bare name, with its media type; null for anything + * that is not a file directly in the fonts dir (no separators, no dot-files). */ +export function cachedFontFile(file: string): { path: string; mime: string } | null { + if (!/^[A-Za-z0-9_-]+\.(woff2|woff|ttf|otf)$/.test(file)) return null; + const path = join(fontsDir(), file); + if (!existsSync(path)) return null; + return { path, mime: mimeOf(file.split('.').pop() ?? 'woff2') }; +} + function faceToDataUri(face: RegistryFace): FontFace | null { const path = join(fontsDir(), face.file); if (!existsSync(path)) return null; diff --git a/src/viewer.ts b/src/viewer.ts index 546a310..ac5bb12 100644 --- a/src/viewer.ts +++ b/src/viewer.ts @@ -1,1943 +1,7 @@ -import { createServer, type IncomingMessage, type Server } from 'node:http'; -import { getCanvas, listCanvases, archiveCanvas, unarchiveCanvas, deleteCanvas, ensureFresh, touchCanvas, type CanvasSummary } from './scene-graph.js'; -import { expandTree } from './expand.js'; -import { renderToHtml } from './renderer.js'; -import { getProject, listProjects, listWorkspaces, getCanvasTokens, getProjectDesignSystem, getWorkspaceDesignSystem } from './workspaces.js'; -import { getRepoLocation, archiveRepoCanvas, deleteRepoCanvas, updateRepoCanvas } from './aggregate.js'; -import { DEFAULT_PROJECT_ID, type Canvas, type SceneNode } from './types.js'; -import { evaluateCanvas, resolveGenre, type EvaluationResult, type EvaluationIssue } from './evaluate.js'; -import { resolveSurface, usableSafeArea, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, windowProfile, WINDOW_PROFILES, DEFAULT_WINDOW, type DeviceProfile } from './surfaces.js'; -import { isPresetName } from './genre.js'; -import { addFeedback, listFeedback, resolveFeedback, deleteFeedback, openFeedbackCount } from './feedback.js'; -import { withoutRetiredSeeds } from './variables.js'; - -let runningPort: number | null = null; -let externalViewerUrl: string | null = null; -const BASE_PORT = 3001; -const MAX_ATTEMPTS = 20; - -/** - * Set an external viewer URL (used when a standalone viewer is already running). - * When set, getViewerUrl() returns this instead of the built-in server's URL. - */ -export function setExternalViewerUrl(url: string): void { - externalViewerUrl = url; -} - -export function getViewerUrl(): string | null { - if (externalViewerUrl) return externalViewerUrl; - return runningPort ? `http://localhost:${runningPort}` : null; -} - -/** Read + parse a JSON request body (Phase 21 — the feedback POSTs are the - * viewer's first body-carrying endpoints). Empty body → {}. */ -function readJsonBody(req: IncomingMessage): Promise> { - return new Promise((resolve, reject) => { - let raw = ''; - req.on('data', (chunk) => { raw += chunk; if (raw.length > 64 * 1024) reject(new Error('Body too large')); }); - req.on('end', () => { - if (!raw.trim()) { resolve({}); return; } - try { resolve(JSON.parse(raw)); } catch { reject(new Error('Invalid JSON body')); } - }); - req.on('error', reject); - }); -} - -/** Mutate a canvas's feedback through the right backend: repo mirrors write - * back to their `.framesmith/` file (standalone viewer), everything else goes - * through the store + touchCanvas (which persists global canvases, and repo - * canvases when this is the MCP server's embedded viewer). Mirrors the - * archive-endpoint routing at the top of startViewer. */ -function mutateFeedback(id: string, mutate: (c: Canvas) => boolean): boolean { - if (getRepoLocation(id)) return updateRepoCanvas(id, mutate); - ensureFresh(id); // embedded-viewer case: pick up external edits before mutating - const c = getCanvas(id); - if (!c) return false; - if (!mutate(c)) return false; - touchCanvas(id); - return true; -} - -function tryListen(httpServer: Server, port: number): Promise { - return new Promise((resolve, reject) => { - const onError = (err: NodeJS.ErrnoException) => { - httpServer.removeListener('error', onError); - if (err.code === 'EADDRINUSE') { - reject(err); - } else { - reject(err); - } - }; - httpServer.on('error', onError); - httpServer.listen(port, '127.0.0.1', () => { - httpServer.removeListener('error', onError); - resolve(port); - }); - }); -} - -export async function startViewer(port: number): Promise { - const httpServer = createServer(async (req, res) => { - const url = new URL(req.url ?? '/', `http://localhost:${runningPort ?? port}`); - const path = url.pathname; - - // CORS headers for API routes - res.setHeader('Access-Control-Allow-Origin', '*'); - - try { - // API: list canvases - if (path === '/api/canvases') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(listCanvases())); - return; - } - - // API: canvas meta (for polling) - const metaMatch = path.match(/^\/api\/canvas\/([^/]+)\/meta$/); - if (metaMatch) { - const canvas = getCanvas(metaMatch[1]); - if (!canvas) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ - id: canvas.id, - name: canvas.name, - lastModified: canvas.lastModified, - // Content hash for the poll loop — catches edits that don't bump - // lastModified (hand-edited repo JSON, metadata stamps; issue #150). - contentKey: evalCacheKey(canvas), - width: canvas.root.width, - height: canvas.root.height, - type: resolveSurface(canvas).type, - safeArea: canvas.root.safeArea, - })); - return; - } - - // Canvas raw HTML (for iframe) — supports ?w=WIDTH&h=HEIGHT overrides - const htmlMatch = path.match(/^\/canvas\/([^/]+)\/html$/); - if (htmlMatch) { - const canvas = getCanvas(htmlMatch[1]); - if (!canvas) { res.writeHead(404); res.end('Not found'); return; } - // Phase 25 slice D — ?theme=dark renders the dark token layer. - const theme = url.searchParams.get('theme') === 'dark' ? 'dark' as const : undefined; - const resolved = expandTree(canvas.root, canvas, getCanvasTokens(canvas), { theme }).root; - const defaultW = typeof canvas.root.width === 'number' ? canvas.root.width : 1440; - const defaultH = typeof canvas.root.height === 'number' ? canvas.root.height : 900; - const w = url.searchParams.has('w') ? parseInt(url.searchParams.get('w')!, 10) : defaultW; - const h = url.searchParams.has('h') ? parseInt(url.searchParams.get('h')!, 10) : defaultH; - // skeletonPulse: the live viewer is the ONE context where skeleton - // blocks animate — screenshots/exports/diffs stay static. - const html = renderToHtml(resolved, w, h, canvas, { skeletonPulse: true }); - res.setHeader('Content-Type', 'text/html'); - res.end(html); - return; - } - - // Canvas JSON - const jsonMatch = path.match(/^\/canvas\/([^/]+)\/json$/); - if (jsonMatch) { - const canvas = getCanvas(jsonMatch[1]); - if (!canvas) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(canvas, null, 2)); - return; - } - - // Canvas detail page - const detailMatch = path.match(/^\/canvas\/([^/]+)$/); - if (detailMatch) { - const canvas = getCanvas(detailMatch[1]); - if (!canvas) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'text/html'); - res.end(await renderDetailPage(canvas, runningPort ?? 3001)); - return; - } - - // Project page - const projectMatch = path.match(/^\/project\/([^/]+)$/); - if (projectMatch) { - const html = await renderProjectPage(projectMatch[1], runningPort ?? 3001); - if (!html) { res.writeHead(404); res.end('Project not found'); return; } - res.setHeader('Content-Type', 'text/html'); - res.end(html); - return; - } - - // Archive page - if (path === '/archive') { - res.setHeader('Content-Type', 'text/html'); - res.end(renderArchivePage(runningPort ?? 3001)); - return; - } - - // Lifecycle API: archive / unarchive / delete a canvas. Three small - // wrappers around the scene-graph functions so the viewer's action - // buttons (archive page + detail page) don't need to round-trip - // through an MCP client. - const archiveApi = path.match(/^\/api\/canvas\/([^/]+)\/archive$/); - if (archiveApi && req.method === 'POST') { - const id = archiveApi[1]; - // Repo-mirrored canvases write back to their `.framesmith/` file; global - // canvases use the in-memory + global-store path. - const result = getRepoLocation(id) ? archiveRepoCanvas(id, true) : !!archiveCanvas(id); - if (!result) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ ok: true, canvasId: id, archived: true })); - return; - } - const unarchiveApi = path.match(/^\/api\/canvas\/([^/]+)\/unarchive$/); - if (unarchiveApi && req.method === 'POST') { - const id = unarchiveApi[1]; - const result = getRepoLocation(id) ? archiveRepoCanvas(id, false) : !!unarchiveCanvas(id); - if (!result) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ ok: true, canvasId: id, archived: false })); - return; - } - // Feedback API (Phase 21 Slice B) — point-and-tell comments. Same - // backend routing as the lifecycle endpoints above. - const feedbackApi = path.match(/^\/api\/canvas\/([^/]+)\/feedback$/); - if (feedbackApi && req.method === 'GET') { - const canvas = getCanvas(feedbackApi[1]); - if (!canvas) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ openCount: openFeedbackCount(canvas), entries: listFeedback(canvas, { includeResolved: true }) })); - return; - } - if (feedbackApi && req.method === 'POST') { - const id = feedbackApi[1]; - const body = await readJsonBody(req); - const nodeId = typeof body.nodeId === 'string' && body.nodeId ? body.nodeId : undefined; - const comment = typeof body.comment === 'string' ? body.comment : ''; - let entry: unknown = null; - let addError: string | null = null; - const ok = mutateFeedback(id, (c) => { - try { entry = addFeedback(c, { nodeId, comment }); return true; } - catch (e) { addError = (e as Error).message; return false; } - }); - if (addError) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: addError })); return; } - if (!ok) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ ok: true, entry })); - return; - } - const feedbackItemApi = path.match(/^\/api\/canvas\/([^/]+)\/feedback\/([^/]+)$/); - if (feedbackItemApi && req.method === 'DELETE') { - const [, id, fbId] = feedbackItemApi; - let removed = false; - const ok = mutateFeedback(id, (c) => { removed = deleteFeedback(c, fbId); return removed; }); - if (!ok || !removed) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ ok: true, deleted: fbId })); - return; - } - const feedbackResolveApi = path.match(/^\/api\/canvas\/([^/]+)\/feedback\/([^/]+)\/resolve$/); - if (feedbackResolveApi && req.method === 'POST') { - const [, id, fbId] = feedbackResolveApi; - const body = await readJsonBody(req); - const note = typeof body.note === 'string' && body.note.trim() ? body.note.trim() : undefined; - let resolved = false; - const ok = mutateFeedback(id, (c) => { resolved = resolveFeedback(c, [fbId], 'user', note).resolved.length > 0; return resolved; }); - if (!ok || !resolved) { res.writeHead(404); res.end('Not found'); return; } - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ ok: true, resolved: fbId })); - return; - } - - const deleteApi = path.match(/^\/api\/canvas\/([^/]+)$/); - if (deleteApi && req.method === 'DELETE') { - const id = deleteApi[1]; - if (!getCanvas(id)) { res.writeHead(404); res.end('Not found'); return; } - if (getRepoLocation(id)) deleteRepoCanvas(id); else deleteCanvas(id); - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify({ ok: true, canvasId: id, deleted: true })); - return; - } - - // Index → default project - if (path === '/') { - res.writeHead(302, { Location: `/project/${DEFAULT_PROJECT_ID}` }); - res.end(); - return; - } - - res.writeHead(404); - res.end('Not found'); - } catch (err) { - res.writeHead(500); - res.end(`Server error: ${(err as Error).message}`); - } - }); - - // Try sequential ports starting from BASE_PORT (or a specific port if given) - if (port > 0) { - // Specific port requested - const actualPort = await tryListen(httpServer, port); - runningPort = actualPort; - process.stderr.write(`Canvas viewer running at http://localhost:${actualPort}\n`); - return actualPort; - } - - // Auto-assign: try 3001, 3002, 3003... - for (let i = 0; i < MAX_ATTEMPTS; i++) { - try { - const tryPort = BASE_PORT + i; - const actualPort = await tryListen(httpServer, tryPort); - runningPort = actualPort; - process.stderr.write(`Canvas viewer running at http://localhost:${actualPort}\n`); - return actualPort; - } catch (err) { - if ((err as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw err; - // Port in use, try next - } - } - - // Fallback: let OS assign - const actualPort = await tryListen(httpServer, 0); - runningPort = actualPort; - process.stderr.write(`Canvas viewer running at http://localhost:${actualPort}\n`); - return actualPort; -} - -/** Shared visual tokens. All page-renderers inject this at the top of their - * inline - - - ${MOBILE_TOGGLE_HTML} -
- ${renderSidebar(projectId)} -
-
- -

${esc(project.name)}

-
${canvases.length} canvas${canvases.length !== 1 ? 'es' : ''}
-
- ${canvases.length > 0 ? `
${cards}
` : emptyState} -
-
- - -`; -} - -/** 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. */ -export async function renderGalleryPage(port: number): Promise { - return (await renderProjectPage(DEFAULT_PROJECT_ID, port)) ?? '

No projects found

'; -} - -/** Archive view: shows all archived canvases across every project. Each card - * includes the source-project name (since archive is cross-project) and - * inline Restore / Delete actions that call the JSON API. */ -export function renderArchivePage(port: number): string { - const archived = listCanvases().filter((c) => c.archived); - const projectName = (projectId: string) => getProject(projectId)?.name ?? '—'; - - const cards = archived.map((c) => { - const canvas = getCanvas(c.id)!; - const { w, h } = artboardSize(canvas); - const archivedDate = c.lastModified ? new Date(c.lastModified).toLocaleString() : ''; - return ` - `; - }).join('\n'); - - const emptyState = archived.length === 0 - ? `
-
▢
-
No archived canvases
-
Archive a canvas with canvas_archive({ canvasId }) or the Archive button on a canvas page.
-
` - : ''; - - return ` - - - -Archive — Framesmith -${FAVICON_HTML} - - - - ${MOBILE_TOGGLE_HTML} -
- ${renderSidebar('archive')} -
-
- -

Archived canvases

-
${archived.length} canvas${archived.length !== 1 ? 'es' : ''} across all projects
-
- ${archived.length > 0 ? `
${cards}
` : emptyState} -
-
- - -`; -} - -/* ── Phase 19 Slice A — Quality panel ───────────────────────────────────── - * The viewer surfaces the heuristic (fast, Chrome-free) canvas_evaluate so a - * human reviewer sees the same score + cliché tells the agent sees over MCP. - * Read-only: computed for display, never written back to the scene graph. */ - -// Cache fast-eval by a content hash of everything the evaluation actually -// reads — the node tree, the merged tokens, the genre and preset, -// and the component registry. NOT lastModified: metadata edits and hand-edits -// of a repo-bound file don't reliably bump it (issue #150), and a stale score -// that survives a legitimate fix makes the fix look broken. Bounded — drop -// the oldest when it grows past a cap. -const scoreCache = new Map(); - -/** FNV-1a over the evaluation's actual inputs. Exported for tests. */ -/** The state variants designed for a canvas (sibling lookup, non-archived). - * - * `listing` exists because this is called once per canvas while rendering a - * gallery, and `listCanvases()` version-hashes every canvas in the store on - * every call — so looking it up per card made a page render quadratic (a - * 43-canvas project did ~7,600 whole-canvas hashes and spent 2s of a 2.2s - * response inside this one line). Pass the listing the caller already has. */ -function designedStatesFor(canvasId: string, listing?: CanvasSummary[]): string[] { - return (listing ?? listCanvases()).find((r) => r.id === canvasId)?.variants?.map((v) => v.state) ?? []; -} - -export function evalCacheKey(canvas: Canvas, states?: string[]): string { - // Phase 30: type, genre and preset are separate axes, and each changes the - // score (they select the rulesets that run). - const prov = canvas.metadata?.provenance; - const surface = resolveSurface(canvas); - const genre = `${resolveGenre(canvas).genre ?? ''}/${prov?.preset ?? ''}/${surface.type}/${surface.device ?? ''}`; - let tokens = ''; - try { tokens = JSON.stringify(getCanvasTokens(canvas)); } catch { /* mirrored canvas with no live project — tree + genre still key it */ } - // Phase 24 slice C — the coverage check reads the canvas's designed state - // variants, so adding/removing a variant must invalidate the base's score. - const stateKey = (states ?? designedStatesFor(canvas.id)).slice().sort().join(','); - const payload = `${JSON.stringify(canvas.root)}|${tokens}|${genre}|${JSON.stringify(canvas.components ?? {})}|${stateKey}`; - let h = 0x811c9dc5; - for (let i = 0; i < payload.length; i++) { - h ^= payload.charCodeAt(i); - h = Math.imul(h, 0x01000193); - } - return `${canvas.id}:${(h >>> 0).toString(36)}`; -} - -export async function evalFor(canvas: Canvas, states?: string[]): Promise { - if (!canvas.root.children || canvas.root.children.length === 0) return null; // empty → no score - const designed = states ?? designedStatesFor(canvas.id); - const key = evalCacheKey(canvas, designed); - const hit = scoreCache.get(key); - if (hit) return hit; - try { - // Match the agent: evaluateCanvas resolves the canvas's own genre and preset. - const result = await evaluateCanvas(canvas, { mode: 'fast', designedStates: designed }); - if (scoreCache.size > 200) scoreCache.delete(scoreCache.keys().next().value as string); - scoreCache.set(key, result); - return result; - } catch { - return null; // a scoring failure must never break the page - } -} - -function gradeFor(score: number): { label: string; warn: boolean } { - if (score >= 90) return { label: 'Excellent', warn: false }; - if (score >= 75) return { label: 'Good', warn: false }; - if (score >= 60) return { label: 'Needs improvement', warn: true }; - return { label: 'Poor', warn: true }; -} -// ≥80 green, 60–79 amber, <60 red — the bar colors in the panel + gallery badge. -function scoreColor(score: number): string { - return score >= 80 ? 'var(--success)' : score >= 60 ? 'var(--accent)' : 'var(--danger)'; -} -function sevColor(severity: string): string { - return severity === 'error' ? 'var(--danger)' : severity === 'warning' ? 'var(--accent)' : 'var(--info)'; -} - -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` : ''; - return ` -
-
- - ${label} - ${fixTag} -
-
${esc(issue.message)}
- ${issue.suggestion ? `
${esc(issue.suggestion)}
` : ''} -
`; -} - -/* ── Phase 19 Slice B — Design-system panel ─────────────────────────────── - * Resolves the canvas's effective tokens (the merged workspace▸project▸canvas - * chain) and shows them as swatches / type scale / spacing / radius. Each token - * is attributed to the layer it resolved from; only OVERRIDES of the dominant - * layer are tagged (the section header states the default), keeping it clean. */ -type TokenLayer = 'canvas' | 'project' | 'workspace' | 'default'; - -function mostCommon(layers: TokenLayer[]): TokenLayer { - const tally = new Map(); - for (const l of layers) tally.set(l, (tally.get(l) ?? 0) + 1); - let best: TokenLayer = 'default'; let n = -1; - for (const [l, c] of tally) if (c > n) { best = l; n = c; } - return best; -} - -function renderDesignSystem(canvas: Canvas): string { - const tokens = getCanvasTokens(canvas); - const project = getProject(canvas.projectId); - const projectDS = project ? getProjectDesignSystem(project.id) : undefined; - const workspaceDS = project ? getWorkspaceDesignSystem(project.workspaceId) : undefined; - - const has = (ds: unknown, cat: string, name: string): boolean => { - const m = ds && (ds as Record)[cat]; - return !!m && Object.prototype.hasOwnProperty.call(m, name); - }; - const sourceOf = (cat: string, name: string): TokenLayer => { - // A retired scaffold seed is not the canvas's value (FR-C6). - if (has(withoutRetiredSeeds(canvas.variables), cat, name)) return 'canvas'; - if (has(projectDS, cat, name)) return 'project'; - if (has(workspaceDS, cat, name)) return 'workspace'; - return 'default'; - }; - - const cats = ['colors', 'spacing', 'radius', 'typography'] as const; - const allSources: TokenLayer[] = []; - for (const cat of cats) { - const m = (tokens as Record)[cat] as Record | undefined; - if (m) for (const n of Object.keys(m)) allSources.push(sourceOf(cat, n)); - } - if (allSources.length === 0) { - return ` - `; - } - const dominant = mostCommon(allSources); - const defaultLabel = dominant === 'default' ? 'defaults' : `from ${dominant}`; - const tag = (cat: string, name: string): string => { - const s = sourceOf(cat, name); - return s === dominant ? '' : ` ${s}`; - }; - const sectionLabel = (title: string): string => - `
${defaultLabel}
`; - - const colors = (tokens.colors ?? {}) as Record; - const colorEntries = Object.entries(colors); - const colorSec = colorEntries.length ? ` -
- ${sectionLabel('Colors')} -
- ${colorEntries.map(([name, hex]) => ` -
-
-
- ${esc(name)}${tag('colors', name)} - ${esc(String(hex))} -
-
`).join('')} -
-
` : ''; - - const typo = (tokens.typography ?? {}) as Record; - const typoEntries = Object.entries(typo); - const typeSec = typoEntries.length ? ` -
-
- ${sectionLabel('Type scale')} - ${typoEntries.map(([name, t]) => { - const size = Number(t.fontSize ?? 14); - const weight = t.fontWeight ?? 400; - const disp = Math.min(Number.isFinite(size) ? size : 14, 30); - return `
- ${esc(name)} - ${esc(String(t.fontSize ?? '—'))}/${esc(String(weight))}${tag('typography', name)} -
`; - }).join('')} -
` : ''; - - const spacing = (tokens.spacing ?? {}) as Record; - const spacingEntries = Object.entries(spacing); - const maxSp = Math.max(1, ...spacingEntries.map(([, v]) => Number(v)).filter((n) => Number.isFinite(n))); - const spaceSec = spacingEntries.length ? ` -
-
- ${sectionLabel('Spacing')} - ${spacingEntries.map(([name, val]) => { - const w = Math.max(6, Math.round((Number(val) / maxSp) * 120)); - return `
- ${esc(name)}${tag('spacing', name)} - - ${esc(String(val))} -
`; - }).join('')} -
` : ''; - - const radius = (tokens.radius ?? {}) as Record; - const radiusEntries = Object.entries(radius); - const radiusSec = radiusEntries.length ? ` -
-
- ${sectionLabel('Radius')} -
- ${radiusEntries.map(([name, val]) => { - const r = Math.min(Math.max(0, Number(val) || 0), 22); - return `
-
- ${esc(name)} · ${esc(String(val))}${tag('radius', name)} -
`; - }).join('')} -
-
` : ''; - - return ` - `; -} - -/** Phase 21 — id → { name, type } for every node, embedded in the detail page - * so the comment-mode breadcrumb can label ancestors without extra requests. */ -function buildNodeIndex(root: SceneNode): Record { - const index: Record = {}; - const walk = (n: SceneNode) => { - index[n.id] = { ...(n.name ? { name: n.name } : {}), type: n.type }; - for (const child of n.children ?? []) walk(child); - }; - walk(root); - return index; -} - -/** JSON.stringify safe to inline inside a - -`; -} - -function esc(str: string): string { - return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); -} +// Phase 33 — the viewer lives in src/viewer/. This file re-exports what the +// server, the standalone viewer and the tests import, so their paths hold. +export { startViewer, getViewerUrl, setExternalViewerUrl } from './viewer/server.js'; +export { renderProjectPage, renderGalleryPage } from './viewer/pages/project.js'; +export { renderArchivePage } from './viewer/pages/archive.js'; +export { renderDetailPage } from './viewer/pages/detail.js'; +export { evalCacheKey, evalFor } from './viewer/scores.js'; diff --git a/src/viewer/client/archive.ts b/src/viewer/client/archive.ts new file mode 100644 index 0000000..79b6951 --- /dev/null +++ b/src/viewer/client/archive.ts @@ -0,0 +1,32 @@ +// Phase 33 slice A — the archive page's browser script, moved from viewer.ts. +import { COMPONENTS_JS, MOBILE_TOGGLE_JS } from '../components.js'; +import { THUMB_FIT_JS } from '../shared.js'; + +export function archiveScript(): string { + return ` + ${MOBILE_TOGGLE_JS} + ${COMPONENTS_JS} + ${THUMB_FIT_JS} + + // Lifecycle actions: restore / permanent delete. Both call JSON endpoints + // and reload on success. Delete prompts to confirm — it's irreversible. + document.querySelectorAll('.card-action').forEach((btn) => { + btn.addEventListener('click', async (e) => { + e.preventDefault(); + e.stopPropagation(); + const action = btn.dataset.action; + const id = btn.dataset.id; + if (action === 'delete' && !confirm('Permanently delete this canvas? This cannot be undone.')) return; + try { + const url = '/api/canvas/' + id + (action === 'restore' ? '/unarchive' : ''); + const method = action === 'delete' ? 'DELETE' : 'POST'; + const res = await fetch(url, { method }); + if (!res.ok) throw new Error('Request failed: ' + res.status); + location.reload(); + } catch (err) { + alert('Action failed: ' + err.message); + } + }); + }); +`; +} diff --git a/src/viewer/client/detail.ts b/src/viewer/client/detail.ts new file mode 100644 index 0000000..bb967ed --- /dev/null +++ b/src/viewer/client/detail.ts @@ -0,0 +1,456 @@ +// Phase 33 slice A — the canvas detail page's browser script, moved verbatim +// from viewer.ts; every server value it inlines goes through scriptJson. +import type { Canvas } from '../../types.js'; +import { listFeedback } from '../../feedback.js'; +import { evalCacheKey } from '../scores.js'; +import { buildNodeIndex, scriptJson } from '../shared.js'; +import { LIGHT } from '../tokens.js'; + +export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: string): string { + return ` + const canvasId = ${scriptJson(canvas.id)}; + // Outlines drawn inside the canvas iframe, which cannot read the page's CSS variables. + const HIGHLIGHT = ${scriptJson(LIGHT.colors.accent)}; + let lastModified = ${scriptJson(canvas.lastModified)}; + let contentKey = ${scriptJson(evalCacheKey(canvas))}; + // The layout (device frame or breakpoints, artboard size, safe-area bands) + // is server-rendered, so a change to the type, the root size or its + // safeArea reloads the page. + const pageShape = ${scriptJson({ type: surfaceType, width: canvas.root.width ?? null, height: canvas.root.height ?? null, safeArea: JSON.stringify(canvas.root.safeArea ?? null) })}; + let currentBp = 'desktop'; + + // 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))}; + + // Auto-refresh polling + setInterval(async () => { + try { + const res = await fetch('/api/canvas/' + canvasId + '/meta'); + const meta = await res.json(); + document.getElementById('status').className = 'status'; + // contentKey catches edits that never bump lastModified (issue #150). + if (meta.lastModified !== lastModified || (meta.contentKey && meta.contentKey !== contentKey)) { + if (meta.type !== pageShape.type || (meta.width ?? null) !== pageShape.width || (meta.height ?? null) !== pageShape.height || JSON.stringify(meta.safeArea ?? null) !== pageShape.safeArea) { + location.reload(); + return; + } + lastModified = meta.lastModified; + contentKey = meta.contentKey || contentKey; + refreshFrames(); + // Update JSON if panel is open + if (document.getElementById('json-panel').classList.contains('open')) loadJson(); + } + } catch { + document.getElementById('status').className = 'status stale'; + } + }, 2000); + + // Phase 25 slice D — flip every iframe between light and dark renders. + let themeMode = 'light'; + function toggleTheme() { + themeMode = themeMode === 'light' ? 'dark' : 'light'; + const btn = document.getElementById('theme-toggle'); + if (btn) { btn.textContent = themeMode === 'light' ? 'Dark' : 'Light'; btn.classList.toggle('active', themeMode === 'dark'); } + document.querySelectorAll('iframe').forEach((frame) => { + const u = new URL(frame.src, location.href); + if (themeMode === 'dark') u.searchParams.set('theme', 'dark'); + else u.searchParams.delete('theme'); + frame.src = u.toString(); + }); + } + + function refreshFrames() { + const t = Date.now(); + const bump = (frame) => { + const url = new URL(frame.src, location.href); + url.searchParams.set('t', t); + frame.src = url.toString(); + }; + if (document.getElementById('viewport').classList.contains('compare')) { + document.querySelectorAll('.compare-cell iframe').forEach(bump); + } else { + bump(document.getElementById('frame')); + } + } + + const canvasW = ${scriptJson(w)}; + const canvasH = ${scriptJson(h)}; + + function setViewport(w, h, bp) { + const frame = document.getElementById('frame'); + const vp = document.getElementById('viewport'); + vp.classList.remove('fit', 'compare'); + document.getElementById('btn-fit').classList.remove('active'); + + // Reload iframe at the new viewport size so content reflows + frame.width = w; + frame.height = h; + frame.style.transform = ''; + frame.style.maxWidth = ''; + frame.style.maxHeight = ''; + frame.style.width = ''; + frame.style.height = ''; + frame.style.overflow = ''; + frame.src = '/canvas/' + canvasId + '/html?w=' + w + '&h=' + h + (themeMode === 'dark' ? '&theme=dark' : '') + '&t=' + Date.now(); + + // The pressed button is the active breakpoint; other toolbar state stays. + document.querySelectorAll('.bp-btn').forEach(b => b.classList.remove('active')); + document.getElementById('bp-' + bp).classList.add('active'); + currentBp = bp; + } + + function setCompareMode() { + const vp = document.getElementById('viewport'); + vp.classList.remove('fit'); + vp.classList.add('compare'); + document.getElementById('btn-fit').classList.remove('active'); + document.querySelectorAll('.bp-btn').forEach(b => b.classList.remove('active')); + document.getElementById('bp-compare').classList.add('active'); + currentBp = 'compare'; + } + + function toggleSafeArea() { + const overlay = document.getElementById('safe-overlay'); + overlay.hidden = !overlay.hidden; + document.getElementById('btn-safe').classList.toggle('active', !overlay.hidden); + } + + function toggleFit() { + const vp = document.getElementById('viewport'); + const btn = document.getElementById('btn-fit'); + vp.classList.toggle('fit'); + btn.classList.toggle('active'); + } + + function toggleJson() { + const panel = document.getElementById('json-panel'); + const btn = document.getElementById('btn-json'); + panel.classList.toggle('open'); + btn.classList.toggle('active'); + if (panel.classList.contains('open')) loadJson(); + } + + async function loadJson() { + try { + const res = await fetch('/canvas/' + canvasId + '/json'); + const data = await res.json(); + document.getElementById('json-content').textContent = JSON.stringify(data, null, 2); + } catch (e) { + document.getElementById('json-content').textContent = 'Error loading JSON'; + } + } + + // Archive / unarchive / delete. Delete is irreversible — confirm first. + // After action: archive / unarchive bounce back to the project page; + // delete bounces too (the canvas is gone, no point staying on its page). + async function lifecycleAction(action) { + if (action === 'delete' && !confirm('Permanently delete this canvas? This cannot be undone.')) return; + const projectId = ${scriptJson(canvas.projectId)}; + try { + const url = '/api/canvas/' + canvasId + (action === 'archive' ? '/archive' : action === 'unarchive' ? '/unarchive' : ''); + const method = action === 'delete' ? 'DELETE' : 'POST'; + const res = await fetch(url, { method }); + if (!res.ok) throw new Error('Request failed: ' + res.status); + location.href = '/project/' + projectId; + } catch (err) { + alert('Action failed: ' + err.message); + } + } + + // ── Phase 21 — point-and-tell feedback ───────────────────────────────── + // Pane renderer: cards are built with DOM APIs (never innerHTML from user + // text) so comment content can't inject markup. + function nodeLabel(nodeId) { + const n = NODE_INDEX[nodeId]; + return n ? (n.name || n.type) : nodeId; + } + + function fbCard(entry) { + const card = document.createElement('div'); + card.className = 'fb-card' + (entry.resolvedAt ? ' resolved' : ''); + const top = document.createElement('div'); + top.className = 'fb-card-top'; + const anchor = document.createElement('span'); + anchor.className = 'fb-anchor'; + anchor.textContent = entry.nodeId ? ((entry.node && (entry.node.name || entry.node.type)) || nodeLabel(entry.nodeId)) : 'whole page'; + top.appendChild(anchor); + if (entry.orphaned) { + const o = document.createElement('span'); + o.className = 'fb-orphan'; + o.title = 'The anchored node no longer exists — the concern may still apply to its replacement'; + o.textContent = 'node gone'; + top.appendChild(o); + } + const when = document.createElement('span'); + when.className = 'fb-when'; + when.textContent = new Date(entry.at).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); + top.appendChild(when); + card.appendChild(top); + const msg = document.createElement('div'); + msg.className = 'fb-comment'; + msg.textContent = entry.comment; + card.appendChild(msg); + if (entry.resolutionNote) { + const reply = document.createElement('div'); + reply.className = 'fb-reply'; + reply.textContent = (entry.resolvedBy === 'agent' ? 'agent: ' : '') + entry.resolutionNote; + card.appendChild(reply); + } + if (!entry.resolvedAt) { + const actions = document.createElement('div'); + actions.className = 'fb-actions'; + const resolveBtn = document.createElement('button'); + resolveBtn.className = 'fb-btn'; + 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.textContent = 'Delete'; + delBtn.onclick = (e) => { e.stopPropagation(); if (confirm('Delete this comment?')) fbAction('/feedback/' + entry.id, 'DELETE'); }; + actions.appendChild(resolveBtn); + actions.appendChild(delBtn); + card.appendChild(actions); + } + if (entry.nodeId && !entry.orphaned) { + card.onclick = () => { + const wasSel = card.classList.contains('sel'); + document.querySelectorAll('.fb-card.sel').forEach((o) => o.classList.remove('sel')); + if (wasSel) { highlightNode(null, false); return; } + card.classList.add('sel'); + highlightNode(entry.nodeId, true); + }; + } + return card; + } + + 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; } + if (!open.length && !done.length) { + const empty = document.createElement('div'); + empty.className = 'fb-empty'; + empty.textContent = 'No comments yet.'; + pane.appendChild(empty); + return; + } + open.forEach((e) => pane.appendChild(fbCard(e))); + if (done.length) { + const sep = document.createElement('div'); + sep.className = 'fb-sep'; + sep.textContent = 'Resolved'; + pane.appendChild(sep); + done.forEach((e) => pane.appendChild(fbCard(e))); + } + } + + async function loadFeedback() { + try { + const res = await fetch('/api/canvas/' + canvasId + '/feedback'); + const data = await res.json(); + renderFeedbackPane(data.entries); + } catch { /* pane keeps its last state */ } + } + + 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(); + } catch (err) { alert('Action failed: ' + err.message); } + } + + // Comment mode: crosshair + hover outline inside the main iframe; click + // resolves the nearest data-node-id, a popover picks scope + takes the note. + let commentMode = false; + const HOVER_STYLE_ID = 'fs-comment-hover'; + + function frameDoc() { + const frame = document.getElementById('frame'); + try { return frame.contentDocument; } catch { return null; } + } + + function setFrameCommentAffordance(on) { + const doc = frameDoc(); + if (!doc || !doc.body) return; + doc.getElementById(HOVER_STYLE_ID)?.remove(); + if (on) { + const style = doc.createElement('style'); + style.id = HOVER_STYLE_ID; + style.textContent = 'body { cursor: crosshair !important; } [data-node-id]:hover { outline: 1px dashed ' + HIGHLIGHT + ' !important; outline-offset: 1px; }'; + doc.head.appendChild(style); + } + } + + function onFrameClick(e) { + if (!commentMode) return; + e.preventDefault(); + e.stopPropagation(); + const target = e.target.closest ? e.target.closest('[data-node-id]') : null; + const chain = []; + let el = target; + while (el) { + // A node inside a component instance renders as "/": + // the comment anchors on the instance, the node the canvas stores. + const id = el.getAttribute('data-node-id').split('/')[0]; + if (!chain.includes(id)) chain.push(id); + el = el.parentElement && el.parentElement.closest('[data-node-id]'); + } + openPopover(chain, e); + } + + function hookFrame() { + const doc = frameDoc(); + if (!doc) return; + doc.removeEventListener('click', onFrameClick, true); + doc.addEventListener('click', onFrameClick, true); + setFrameCommentAffordance(commentMode); + } + + function toggleComment() { + commentMode = !commentMode; + document.getElementById('btn-comment').classList.toggle('active', commentMode); + if (!commentMode) closePopover(); + hookFrame(); + } + + let popoverEl = null; + let popoverSelected = null; // nodeId or null = whole page + + function closePopover() { + if (popoverEl) { popoverEl.remove(); popoverEl = null; } + highlightNode(null, false); + } + + function openPopover(chain, clickEvent) { + closePopover(); + 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 = []; + const makeChip = (label, nodeId, title) => { + const chip = document.createElement('span'); + chip.className = 'fb-chip'; + chip.textContent = label; + if (title) chip.title = title; + chip.onclick = () => { + popoverSelected = nodeId; + allChips.forEach((c) => c.classList.remove('sel')); + chip.classList.add('sel'); + 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); } + }; + 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(); + } + + document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closePopover(); }); + document.getElementById('frame').addEventListener('load', hookFrame); + hookFrame(); + renderFeedbackPane(FB_INIT); + + // 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) { + const frames = []; + const main = document.getElementById('frame'); + if (main && getComputedStyle(main).display !== 'none') frames.push(main); + document.querySelectorAll('.compare-cell iframe').forEach((f) => frames.push(f)); + for (const f of frames) { + let doc; + try { doc = f.contentDocument; } catch { continue; } + if (!doc) continue; + doc.querySelectorAll('[data-fs-hl]').forEach((n) => { + n.style.outline = ''; n.style.outlineOffset = ''; n.removeAttribute('data-fs-hl'); + }); + if (on && nodeId) { + 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' }); + } + } + } + } + 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); + }); + }); + + // 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; }); + }); + }); +`; +} diff --git a/src/viewer/client/project.ts b/src/viewer/client/project.ts new file mode 100644 index 0000000..68e3d97 --- /dev/null +++ b/src/viewer/client/project.ts @@ -0,0 +1,23 @@ +// Phase 33 slice A — the project page's browser script, moved from viewer.ts. +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 { + 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); +`; +} diff --git a/src/viewer/components.ts b/src/viewer/components.ts new file mode 100644 index 0000000..8fe71a1 --- /dev/null +++ b/src/viewer/components.ts @@ -0,0 +1,209 @@ +// Phase 33 slice A — the viewer's shared components (FR-A4): sidebar, tabs, +// menu and dialog, built once. Markup here; behaviour in COMPONENTS_JS, which +// every page includes; styles in styles.ts. + +import { listCanvases } from '../scene-graph.js'; +import { listProjects, listWorkspaces } from '../workspaces.js'; +import { getIconSvg } from '../icons.js'; +import { esc } from './shared.js'; +import { LIGHT } from './tokens.js'; + +/** A bundled Lucide icon, stroked in the current text colour. */ +export function icon(name: string, size = 16): string { + return getIconSvg(name, size, 'currentColor') ?? ''; +} + +/** SVG favicon embedded as a data URI, so the viewer needs no favicon route. + * URL-encoded: `<` → `%3C`, `>` → `%3E`. The stroke is the light accent's + * value, because a favicon cannot read CSS variables. */ +export const FAVICON_HTML = ``; + +/** Mobile sidebar drawer (FR-A5): a fixed toggle and a backdrop that closes it. */ +export const MOBILE_TOGGLE_HTML = ` + + `; + +export const MOBILE_TOGGLE_JS = ` + function toggleSidebar() { + document.body.classList.toggle('sidebar-open'); + }`; + +const DOT_TOKENS = ['--chart-1', '--chart-2', '--chart-3', '--chart-4', '--chart-5']; + +/** A project's identity dot: one of the design system's series colours, + * picked by hashing the id so it stays stable without a stored field. */ +export function projectDotToken(projectId: string): string { + let hash = 0; + for (let i = 0; i < projectId.length; i++) hash = ((hash << 5) - hash + projectId.charCodeAt(i)) | 0; + return `var(${DOT_TOKENS[Math.abs(hash) % DOT_TOKENS.length]})`; +} + +/** The sidebar: wordmark; per workspace its label and one link per project + * (identity dot, name, non-archived 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; + const archivedCount = all.filter((c) => c.archived).length; + const current = (on: boolean) => (on ? ' aria-current="page"' : ''); + + const sections = listWorkspaces().map((ws) => { + const projects = listProjects(ws.id); + const items = projects.length === 0 + ? '
No projects yet
' + : projects.map((p) => ` + + ${esc(p.name)} + ${projectCount(p.id)} + `).join(''); + return `
${esc(ws.name)}
${items}
`; + }).join(''); + + return ``; +} + +export interface TabSpec { id: string; label: string; count?: number; selected?: boolean; panelId?: string } + +/** A tab list: real buttons with role="tab", arrow keys move between them + * (COMPONENTS_JS). Selecting one shows its panel (aria-controls) and hides + * the others, and fires a "tabchange" event on the list. */ +export function renderTabs(tabs: TabSpec[], label: string): string { + const buttons = tabs.map((t) => ``).join(''); + return `
${buttons}
`; +} + +export type MenuItemSpec = { action: string; label: string; icon?: string; danger?: boolean } | 'separator'; + +/** A menu behind a button: Up and Down move, Enter activates, Escape and an + * outside click close it and return focus (COMPONENTS_JS). Choosing an item + * fires a "menuaction" event on the wrapper with detail.action. */ +export function renderMenu(id: string, buttonHtml: string, buttonLabel: string, items: MenuItemSpec[]): string { + const rows = items.map((item) => item === 'separator' + ? '' + : ``).join(''); + return ``; +} + +export interface DialogSpec { id: string; title: string; body: string; confirmLabel: string; destructive?: boolean } + +/** A modal dialog over a scrim, hidden until fsDialog.open(id) (COMPONENTS_JS): + * focus moves to Cancel, Tab stays inside, Escape or the scrim cancels. */ +export function renderDialog(d: DialogSpec): string { + return ``; +} + +/** Behaviour for every tab list, menu and dialog on the page. */ +export const COMPONENTS_JS = ` + (() => { + // Tabs: click or arrow keys select; the selected tab's panel shows. + document.querySelectorAll('[role="tablist"]').forEach((list) => { + const tabs = () => Array.from(list.querySelectorAll('[role="tab"]')); + const select = (tab, focus) => { + tabs().forEach((t) => { + const on = t === tab; + t.setAttribute('aria-selected', on ? 'true' : 'false'); + t.tabIndex = on ? 0 : -1; + const panel = t.getAttribute('aria-controls') && document.getElementById(t.getAttribute('aria-controls')); + if (panel) panel.hidden = !on; + }); + if (focus) tab.focus(); + list.dispatchEvent(new CustomEvent('tabchange', { detail: { tab: tab.dataset.tab } })); + }; + list.addEventListener('click', (e) => { const t = e.target.closest('[role="tab"]'); if (t) select(t, false); }); + list.addEventListener('keydown', (e) => { + const all = tabs(); const i = all.indexOf(document.activeElement); + if (i < 0) return; + const next = e.key === 'ArrowRight' ? all[(i + 1) % all.length] + : e.key === 'ArrowLeft' ? all[(i - 1 + all.length) % all.length] + : e.key === 'Home' ? all[0] : e.key === 'End' ? all[all.length - 1] : null; + if (next) { e.preventDefault(); select(next, true); } + }); + }); + + // Menus: the button toggles; Up/Down/Home/End move; Escape, Tab and an + // outside click close and return focus to the button. + document.querySelectorAll('[data-menu]').forEach((wrap) => { + const button = wrap.querySelector('[aria-haspopup="menu"]'); + const menu = wrap.querySelector('[role="menu"]'); + const items = () => Array.from(menu.querySelectorAll('[role="menuitem"]')); + const close = (refocus) => { menu.hidden = true; button.setAttribute('aria-expanded', 'false'); if (refocus) button.focus(); }; + const open = () => { menu.hidden = false; button.setAttribute('aria-expanded', 'true'); const first = items()[0]; if (first) first.focus(); }; + button.addEventListener('click', () => (menu.hidden ? open() : close(true))); + menu.addEventListener('keydown', (e) => { + const all = items(); const i = all.indexOf(document.activeElement); + if (e.key === 'Escape') { e.preventDefault(); close(true); return; } + if (e.key === 'Tab') { close(false); return; } + const next = e.key === 'ArrowDown' ? all[(i + 1) % all.length] + : e.key === 'ArrowUp' ? all[(i - 1 + all.length) % all.length] + : e.key === 'Home' ? all[0] : e.key === 'End' ? all[all.length - 1] : null; + if (next) { e.preventDefault(); next.focus(); } + }); + menu.addEventListener('click', (e) => { + const item = e.target.closest('[role="menuitem"]'); + if (!item) return; + close(true); + wrap.dispatchEvent(new CustomEvent('menuaction', { detail: { action: item.dataset.action } })); + }); + document.addEventListener('click', (e) => { if (!menu.hidden && !wrap.contains(e.target)) close(false); }); + }); + + // Dialogs: fsDialog.open(id) resolves true on confirm, false on cancel. + window.fsDialog = { + open(id) { + const dialog = document.getElementById(id); + const scrim = dialog && dialog.closest('[data-dialog-scrim]'); + if (!scrim) return Promise.resolve(false); + const opener = document.activeElement; + scrim.hidden = false; + const cancel = dialog.querySelector('[data-dialog-cancel]'); + const confirm = dialog.querySelector('[data-dialog-confirm]'); + cancel.focus(); + return new Promise((resolve) => { + const done = (value) => { + scrim.hidden = true; + dialog.removeEventListener('keydown', onKey); + scrim.removeEventListener('click', onScrim); + cancel.removeEventListener('click', onCancel); + confirm.removeEventListener('click', onConfirm); + if (opener && opener.focus) opener.focus(); + resolve(value); + }; + const onCancel = () => done(false); + const onConfirm = () => done(true); + const onScrim = (e) => { if (e.target === scrim) done(false); }; + const onKey = (e) => { + if (e.key === 'Escape') { e.preventDefault(); done(false); return; } + if (e.key !== 'Tab') return; + const focusable = Array.from(dialog.querySelectorAll('button, [href], input, textarea, select, [tabindex]:not([tabindex="-1"])')); + const first = focusable[0]; const last = focusable[focusable.length - 1]; + if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } + else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } + }; + dialog.addEventListener('keydown', onKey); + scrim.addEventListener('click', onScrim); + cancel.addEventListener('click', onCancel); + confirm.addEventListener('click', onConfirm); + }); + }, + }; + })();`; diff --git a/src/viewer/pages/archive.ts b/src/viewer/pages/archive.ts new file mode 100644 index 0000000..adf72ef --- /dev/null +++ b/src/viewer/pages/archive.ts @@ -0,0 +1,112 @@ +import { getCanvas, listCanvases } from '../../scene-graph.js'; +import { getProject } from '../../workspaces.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 { archiveScript } from '../client/archive.js'; + +/** Archive view: shows all archived canvases across every project. Each card + * includes the source-project name (since archive is cross-project) and + * inline Restore / Delete actions that call the JSON API. */ +export function renderArchivePage(port: number): string { + const archived = listCanvases().filter((c) => c.archived); + const projectName = (projectId: string) => getProject(projectId)?.name ?? '—'; + + const cards = archived.map((c) => { + const canvas = getCanvas(c.id)!; + const { w, h } = artboardSize(canvas); + const archivedDate = c.lastModified ? new Date(c.lastModified).toLocaleString() : ''; + return ` + `; + }).join('\n'); + + const emptyState = archived.length === 0 + ? `
+
▢
+
No archived canvases
+
Archive a canvas with canvas_archive({ canvasId }) or the Archive button on a canvas page.
+
` + : ''; + + return ` + + + +Archive — Framesmith +${FAVICON_HTML} + + + + ${MOBILE_TOGGLE_HTML} +
+ ${renderSidebar('archive')} +
+
+ +

Archived canvases

+
${archived.length} canvas${archived.length !== 1 ? 'es' : ''} across all projects
+
+ ${archived.length > 0 ? `
${cards}
` : emptyState} +
+
+ + +`; +} diff --git a/src/viewer/pages/detail.ts b/src/viewer/pages/detail.ts new file mode 100644 index 0000000..61ca12b --- /dev/null +++ b/src/viewer/pages/detail.ts @@ -0,0 +1,557 @@ +// Phase 33 slice A — the canvas detail page, moved from viewer.ts. +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 { isPresetName } from '../../genre.js'; +import { openFeedbackCount } from '../../feedback.js'; +import { withoutRetiredSeeds } from '../../variables.js'; +import { baseCss } from '../styles.js'; +import { FAVICON_HTML } from '../components.js'; +import { artboardSize, esc, PHONE } from '../shared.js'; +import { evalFor, gradeFor, scoreColor, sevColor } 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` : ''; + return ` +
+
+ + ${label} + ${fixTag} +
+
${esc(issue.message)}
+ ${issue.suggestion ? `
${esc(issue.suggestion)}
` : ''} +
`; +} + +/* ── Phase 19 Slice B — Design-system panel ─────────────────────────────── + * Resolves the canvas's effective tokens (the merged workspace▸project▸canvas + * chain) and shows them as swatches / type scale / spacing / radius. Each token + * is attributed to the layer it resolved from; only OVERRIDES of the dominant + * layer are tagged (the section header states the default), keeping it clean. */ +type TokenLayer = 'canvas' | 'project' | 'workspace' | 'default'; + +function mostCommon(layers: TokenLayer[]): TokenLayer { + const tally = new Map(); + for (const l of layers) tally.set(l, (tally.get(l) ?? 0) + 1); + let best: TokenLayer = 'default'; let n = -1; + for (const [l, c] of tally) if (c > n) { best = l; n = c; } + return best; +} + +function renderDesignSystem(canvas: Canvas): string { + const tokens = getCanvasTokens(canvas); + const project = getProject(canvas.projectId); + const projectDS = project ? getProjectDesignSystem(project.id) : undefined; + const workspaceDS = project ? getWorkspaceDesignSystem(project.workspaceId) : undefined; + + const has = (ds: unknown, cat: string, name: string): boolean => { + const m = ds && (ds as Record)[cat]; + return !!m && Object.prototype.hasOwnProperty.call(m, name); + }; + const sourceOf = (cat: string, name: string): TokenLayer => { + // A retired scaffold seed is not the canvas's value (FR-C6). + if (has(withoutRetiredSeeds(canvas.variables), cat, name)) return 'canvas'; + if (has(projectDS, cat, name)) return 'project'; + if (has(workspaceDS, cat, name)) return 'workspace'; + return 'default'; + }; + + const cats = ['colors', 'spacing', 'radius', 'typography'] as const; + const allSources: TokenLayer[] = []; + for (const cat of cats) { + const m = (tokens as Record)[cat] as Record | undefined; + if (m) for (const n of Object.keys(m)) allSources.push(sourceOf(cat, n)); + } + if (allSources.length === 0) { + return ` + `; + } + const dominant = mostCommon(allSources); + const defaultLabel = dominant === 'default' ? 'defaults' : `from ${dominant}`; + const tag = (cat: string, name: string): string => { + const s = sourceOf(cat, name); + return s === dominant ? '' : ` ${s}`; + }; + const sectionLabel = (title: string): string => + `
${defaultLabel}
`; + + const colors = (tokens.colors ?? {}) as Record; + const colorEntries = Object.entries(colors); + const colorSec = colorEntries.length ? ` +
+ ${sectionLabel('Colors')} +
+ ${colorEntries.map(([name, hex]) => ` +
+
+
+ ${esc(name)}${tag('colors', name)} + ${esc(String(hex))} +
+
`).join('')} +
+
` : ''; + + const typo = (tokens.typography ?? {}) as Record; + const typoEntries = Object.entries(typo); + const typeSec = typoEntries.length ? ` +
+
+ ${sectionLabel('Type scale')} + ${typoEntries.map(([name, t]) => { + const size = Number(t.fontSize ?? 14); + const weight = t.fontWeight ?? 400; + const disp = Math.min(Number.isFinite(size) ? size : 14, 30); + return `
+ ${esc(name)} + ${esc(String(t.fontSize ?? '—'))}/${esc(String(weight))}${tag('typography', name)} +
`; + }).join('')} +
` : ''; + + const spacing = (tokens.spacing ?? {}) as Record; + const spacingEntries = Object.entries(spacing); + const maxSp = Math.max(1, ...spacingEntries.map(([, v]) => Number(v)).filter((n) => Number.isFinite(n))); + const spaceSec = spacingEntries.length ? ` +
+
+ ${sectionLabel('Spacing')} + ${spacingEntries.map(([name, val]) => { + const w = Math.max(6, Math.round((Number(val) / maxSp) * 120)); + return `
+ ${esc(name)}${tag('spacing', name)} + + ${esc(String(val))} +
`; + }).join('')} +
` : ''; + + const radius = (tokens.radius ?? {}) as Record; + const radiusEntries = Object.entries(radius); + const radiusSec = radiusEntries.length ? ` +
+
+ ${sectionLabel('Radius')} +
+ ${radiusEntries.map(([name, val]) => { + const r = Math.min(Math.max(0, Number(val) || 0), 22); + return `
+
+ ${esc(name)} · ${esc(String(val))}${tag('radius', name)} +
`; + }).join('')} +
+
` : ''; + + return ` + `; +} + +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.
`; + return ` + `; +} + +/** The detail view's device presentation: the canvas at 1:1 inside a bezel, + * with the safe-area bands (the root's `safeArea`, else the profile's insets, + * per side — the hardware intrudes there either way) hidden until toggled. A + * side set to 0 draws no band. */ +function renderDevice(canvas: Canvas, w: number, h: number, deviceId: string, profile: DeviceProfile): string { + const reserved = canvas.root.type === 'document' ? usableSafeArea(canvas.root.safeArea) : {}; + const top = reserved.top ?? profile.safeArea.top; + const bottom = reserved.bottom ?? profile.safeArea.bottom; + return `
+
+
+ + +
+
+
`; +} + +export async function renderDetailPage(canvas: Canvas, port: number): Promise { + const { w, h } = artboardSize(canvas); + // Phase 30 slice F — a mobile canvas opens 1:1 in a device frame; a web + // canvas keeps the breakpoint buttons, sized from the device profile table. + const surface = resolveSurface(canvas); + const isMobile = surface.type === 'mobile'; + // Phase 31 FR-I1 — a desktop-app canvas's breakpoints are window widths + // from its window profile (narrower than the artboard), not phone/tablet. + const window = surface.type === 'desktop-app' ? windowProfile(surface.device ?? DEFAULT_WINDOW) ?? WINDOW_PROFILES[DEFAULT_WINDOW] : undefined; + const windowWidths = window ? window.breakpoints.filter((bw) => bw < w) : []; + const deviceId = surface.device ?? DEFAULT_DEVICE; + const profile = deviceProfile(deviceId) ?? PHONE; + + // Provenance chip (Phase 11) — structure · genre · preset · alignment/density. Shows + // only the parts that exist; hidden entirely when a canvas has no provenance. + const prov = canvas.metadata?.provenance; + let provChip = ''; + if (prov) { + const parts: string[] = []; + if (prov.structure) parts.push(esc(prov.structure)); + const genre = resolveGenre(canvas).genre; + if (genre) parts.push(esc(genre)); + // A legacy genre stored in `preset` already showed as the genre above. + if (prov.preset && ('genre' in prov || isPresetName(prov.preset))) parts.push(esc(prov.preset)); + const ax = prov.axes ? [prov.axes.alignment, prov.axes.density].filter(Boolean).join('/') : ''; + if (ax) parts.push(esc(ax)); + if (parts.length) provChip = `◆${parts.join(' · ')}`; + } + + // Phase 25 slice D — a dark token layer makes the theme toggle appear. + const hasDark = Object.keys(getCanvasTokens(canvas).dark?.colors ?? {}).length > 0; + + // State chips (Phase 24 slice A) — a screen and its designed states cross- + // link: on a base with variants, "default" (active) + each state; on a + // variant, the base ("default") + every sibling state. Orphan-safe: a + // variant whose base is gone simply shows no chips. + const rows = listCanvases(); + const selfRow = rows.find((r) => r.id === canvas.id); + let stateChips = ''; + { + const chip = (label: string, id: string | null) => id === null + ? `${esc(label)}` + : `${esc(label)}`; + if (selfRow?.variants?.length) { + stateChips = `${[ + chip('default', null), + ...selfRow.variants.map((v) => chip(v.state, v.canvasId)), + ].join('')}`; + } else if (selfRow?.variant) { + const base = rows.find((r) => r.id === selfRow.variant!.of); + if (base) { + const siblings = (base.variants ?? []).filter((v) => v.canvasId !== canvas.id); + stateChips = `${[ + chip('default', base.id), + ...siblings.map((v) => chip(v.state, v.canvasId)), + chip(selfRow.variant.state, null), + ].join('')}`; + } + } + } + + // Critique verdict chip (Phase 13) — latest rubric overall + needs-revision + // flag. Hidden when a canvas has never been judged. + const crit = canvas.metadata?.critique; + let verdictChip = ''; + if (crit) { + const cls = crit.needsRevision ? 'verdict warn' : 'verdict'; + const tail = crit.needsRevision ? ' · needs revision' : ''; + verdictChip = `◇${crit.overall}/100${tail}`; + } + + // Phase 19 Slice A — heuristic quality inspector (fast, Chrome-free, read-only). + const ev = await evalFor(canvas); + const inspectorHtml = ev ? renderInspector(ev, canvas) : ''; + + return ` + + + +${esc(canvas.name)} — Framesmith +${FAVICON_HTML} + + + +
+ ← Back + ${esc(canvas.name)} + ${w} x ${h}${isMobile ? ` · ${esc(deviceId)}` : window ? ` · ${esc(window.id)}` : ''} + ${stateChips} + ${provChip} + ${verdictChip} +
+
+ ${hasDark ? '' : ''} + ${isMobile + ? '' + : window + ? `${windowWidths.map((bw) => ``).join('\n ')} + + ` + : ` + + + `} +
+ +
+ ${isMobile ? '' : ''} + + +
+ +
+ ${canvas.archived + ? `` + : `` + } + +
+
+
+
+ ${isMobile ? renderDevice(canvas, w, h, deviceId, profile) : `
+ +
+ ${window ? windowWidths.map((bw) => `
+
Window · ${bw}×${h}
+
+
`).join('\n ') : `
+
Mobile · ${PHONE.width}×${PHONE.height}
+
+
+
+
Tablet · 768×1024
+
+
`} +
+
${window ? "Window" : "Desktop"} · ${w}×${h}
+
+
+
+
`} + ${inspectorHtml} +
+
+
Loading...
+
+ + +`; +} diff --git a/src/viewer/pages/project.ts b/src/viewer/pages/project.ts new file mode 100644 index 0000000..4681167 --- /dev/null +++ b/src/viewer/pages/project.ts @@ -0,0 +1,144 @@ +import { getCanvas, listCanvases } from '../../scene-graph.js'; +import { getProject, listWorkspaces } from '../../workspaces.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 { 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 { + 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 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)}
+
+
`; + }))).join('\n'); + + const emptyState = canvases.length === 0 + ? `
+
▢
+
No canvases in ${esc(project.name)} yet
+
Create one via your MCP client using canvas_create({ projectId: "${project.id}" })
+
` + : ''; + + return ` + + + +${esc(project.name)} — Framesmith +${FAVICON_HTML} + + + + ${MOBILE_TOGGLE_HTML} +
+ ${renderSidebar(projectId)} +
+
+ +

${esc(project.name)}

+
${canvases.length} canvas${canvases.length !== 1 ? 'es' : ''}
+
+ ${canvases.length > 0 ? `
${cards}
` : emptyState} +
+
+ + +`; +} + +/** 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. */ +export async function renderGalleryPage(port: number): Promise { + return (await renderProjectPage(DEFAULT_PROJECT_ID, port)) ?? '

No projects found

'; +} diff --git a/src/viewer/scores.ts b/src/viewer/scores.ts new file mode 100644 index 0000000..10794dc --- /dev/null +++ b/src/viewer/scores.ts @@ -0,0 +1,82 @@ +// Phase 33 slice A — the cached fast evaluation every viewer page shows. +import type { Canvas } from '../types.js'; +import { listCanvases, type CanvasSummary } from '../scene-graph.js'; +import { getCanvasTokens } from '../workspaces.js'; +import { evaluateCanvas, resolveGenre, type EvaluationResult } from '../evaluate.js'; +import { resolveSurface } from '../surfaces.js'; + +/* ── Phase 19 Slice A — Quality panel ───────────────────────────────────── + * The viewer surfaces the heuristic (fast, Chrome-free) canvas_evaluate so a + * human reviewer sees the same score + cliché tells the agent sees over MCP. + * Read-only: computed for display, never written back to the scene graph. */ + +// Cache fast-eval by a content hash of everything the evaluation actually +// reads — the node tree, the merged tokens, the genre and preset, +// and the component registry. NOT lastModified: metadata edits and hand-edits +// of a repo-bound file don't reliably bump it (issue #150), and a stale score +// that survives a legitimate fix makes the fix look broken. Bounded — drop +// the oldest when it grows past a cap. +const scoreCache = new Map(); + +/** FNV-1a over the evaluation's actual inputs. Exported for tests. */ +/** The state variants designed for a canvas (sibling lookup, non-archived). + * + * `listing` exists because this is called once per canvas while rendering a + * gallery, and `listCanvases()` version-hashes every canvas in the store on + * every call — so looking it up per card made a page render quadratic (a + * 43-canvas project did ~7,600 whole-canvas hashes and spent 2s of a 2.2s + * response inside this one line). Pass the listing the caller already has. */ +export function designedStatesFor(canvasId: string, listing?: CanvasSummary[]): string[] { + return (listing ?? listCanvases()).find((r) => r.id === canvasId)?.variants?.map((v) => v.state) ?? []; +} + +export function evalCacheKey(canvas: Canvas, states?: string[]): string { + // Phase 30: type, genre and preset are separate axes, and each changes the + // score (they select the rulesets that run). + const prov = canvas.metadata?.provenance; + const surface = resolveSurface(canvas); + const genre = `${resolveGenre(canvas).genre ?? ''}/${prov?.preset ?? ''}/${surface.type}/${surface.device ?? ''}`; + let tokens = ''; + try { tokens = JSON.stringify(getCanvasTokens(canvas)); } catch { /* mirrored canvas with no live project — tree + genre still key it */ } + // Phase 24 slice C — the coverage check reads the canvas's designed state + // variants, so adding/removing a variant must invalidate the base's score. + const stateKey = (states ?? designedStatesFor(canvas.id)).slice().sort().join(','); + const payload = `${JSON.stringify(canvas.root)}|${tokens}|${genre}|${JSON.stringify(canvas.components ?? {})}|${stateKey}`; + let h = 0x811c9dc5; + for (let i = 0; i < payload.length; i++) { + h ^= payload.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return `${canvas.id}:${(h >>> 0).toString(36)}`; +} + +export async function evalFor(canvas: Canvas, states?: string[]): Promise { + if (!canvas.root.children || canvas.root.children.length === 0) return null; // empty → no score + const designed = states ?? designedStatesFor(canvas.id); + const key = evalCacheKey(canvas, designed); + const hit = scoreCache.get(key); + if (hit) return hit; + try { + // Match the agent: evaluateCanvas resolves the canvas's own genre and preset. + const result = await evaluateCanvas(canvas, { mode: 'fast', designedStates: designed }); + if (scoreCache.size > 200) scoreCache.delete(scoreCache.keys().next().value as string); + scoreCache.set(key, result); + return result; + } catch { + return null; // a scoring failure must never break the page + } +} + +export function gradeFor(score: number): { label: string; warn: boolean } { + if (score >= 90) return { label: 'Excellent', warn: false }; + if (score >= 75) return { label: 'Good', warn: false }; + if (score >= 60) return { label: 'Needs improvement', warn: true }; + return { label: 'Poor', warn: true }; +} +// ≥80 green, 60–79 amber, <60 red — the bar colors in the panel + gallery badge. +export function scoreColor(score: number): string { + return score >= 80 ? 'var(--success)' : score >= 60 ? 'var(--accent)' : 'var(--danger)'; +} +export function sevColor(severity: string): string { + return severity === 'error' ? 'var(--danger)' : severity === 'warning' ? 'var(--accent)' : 'var(--info)'; +} diff --git a/src/viewer/server.ts b/src/viewer/server.ts new file mode 100644 index 0000000..621edc0 --- /dev/null +++ b/src/viewer/server.ts @@ -0,0 +1,320 @@ +// Phase 33 slice A — the viewer's HTTP server and routes, moved from viewer.ts. +import { createServer, type IncomingMessage, type Server } from 'node:http'; +import { readFileSync } from 'node:fs'; +import { getCanvas, listCanvases, archiveCanvas, unarchiveCanvas, deleteCanvas, ensureFresh, touchCanvas } from '../scene-graph.js'; +import { expandTree } from '../expand.js'; +import { renderToHtml } from '../renderer.js'; +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 { addFeedback, listFeedback, resolveFeedback, deleteFeedback, openFeedbackCount } from '../feedback.js'; +import { cachedFontFile, resolveFamily } from '../fonts.js'; +import { evalCacheKey } from './scores.js'; +import { renderProjectPage } from './pages/project.js'; +import { renderArchivePage } from './pages/archive.js'; +import { renderDetailPage } from './pages/detail.js'; +import { VIEWER_FONT_FAMILIES } from './tokens.js'; + +let runningPort: number | null = null; +let externalViewerUrl: string | null = null; +const BASE_PORT = 3001; +const MAX_ATTEMPTS = 20; + +/** + * Set an external viewer URL (used when a standalone viewer is already running). + * When set, getViewerUrl() returns this instead of the built-in server's URL. + */ +export function setExternalViewerUrl(url: string): void { + externalViewerUrl = url; +} + +export function getViewerUrl(): string | null { + if (externalViewerUrl) return externalViewerUrl; + return runningPort ? `http://localhost:${runningPort}` : null; +} + +/** Read + parse a JSON request body (Phase 21 — the feedback POSTs are the + * viewer's first body-carrying endpoints). Empty body → {}. */ +function readJsonBody(req: IncomingMessage): Promise> { + return new Promise((resolve, reject) => { + let raw = ''; + req.on('data', (chunk) => { raw += chunk; if (raw.length > 64 * 1024) reject(new Error('Body too large')); }); + req.on('end', () => { + if (!raw.trim()) { resolve({}); return; } + try { resolve(JSON.parse(raw)); } catch { reject(new Error('Invalid JSON body')); } + }); + req.on('error', reject); + }); +} + +/** Mutate a canvas's feedback through the right backend: repo mirrors write + * back to their `.framesmith/` file (standalone viewer), everything else goes + * through the store + touchCanvas (which persists global canvases, and repo + * canvases when this is the MCP server's embedded viewer). Mirrors the + * archive-endpoint routing at the top of startViewer. */ +function mutateFeedback(id: string, mutate: (c: Canvas) => boolean): boolean { + if (getRepoLocation(id)) return updateRepoCanvas(id, mutate); + ensureFresh(id); // embedded-viewer case: pick up external edits before mutating + const c = getCanvas(id); + if (!c) return false; + if (!mutate(c)) return false; + touchCanvas(id); + return true; +} + +function tryListen(httpServer: Server, port: number): Promise { + return new Promise((resolve, reject) => { + const onError = (err: NodeJS.ErrnoException) => { + httpServer.removeListener('error', onError); + if (err.code === 'EADDRINUSE') { + reject(err); + } else { + reject(err); + } + }; + httpServer.on('error', onError); + httpServer.listen(port, '127.0.0.1', () => { + httpServer.removeListener('error', onError); + resolve(port); + }); + }); +} + +export async function startViewer(port: number): Promise { + // Warm the viewer's own fonts in the background, once. Pages read the cache + // on every render, so a warm-up that lands after the first page shows on the + // next load; offline, the fallback stack draws until the viewer restarts. + for (const family of VIEWER_FONT_FAMILIES) resolveFamily(family).catch(() => {}); + + const httpServer = createServer(async (req, res) => { + const url = new URL(req.url ?? '/', `http://localhost:${runningPort ?? port}`); + const path = url.pathname; + + // CORS headers for API routes + res.setHeader('Access-Control-Allow-Origin', '*'); + + try { + // Phase 33 — the design system's fonts, from the font cache by file name. + const fontMatch = path.match(/^\/assets\/fonts\/([^/]+)$/); + if (fontMatch) { + const font = cachedFontFile(fontMatch[1]); + if (!font) { res.writeHead(404); res.end('Not found'); return; } + res.writeHead(200, { 'Content-Type': font.mime, 'Cache-Control': 'max-age=31536000, immutable' }); + res.end(readFileSync(font.path)); + return; + } + + // API: list canvases + if (path === '/api/canvases') { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(listCanvases())); + return; + } + + // API: canvas meta (for polling) + const metaMatch = path.match(/^\/api\/canvas\/([^/]+)\/meta$/); + if (metaMatch) { + const canvas = getCanvas(metaMatch[1]); + if (!canvas) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ + id: canvas.id, + name: canvas.name, + lastModified: canvas.lastModified, + // Content hash for the poll loop — catches edits that don't bump + // lastModified (hand-edited repo JSON, metadata stamps; issue #150). + contentKey: evalCacheKey(canvas), + width: canvas.root.width, + height: canvas.root.height, + type: resolveSurface(canvas).type, + safeArea: canvas.root.safeArea, + })); + return; + } + + // Canvas raw HTML (for iframe) — supports ?w=WIDTH&h=HEIGHT overrides + const htmlMatch = path.match(/^\/canvas\/([^/]+)\/html$/); + if (htmlMatch) { + const canvas = getCanvas(htmlMatch[1]); + if (!canvas) { res.writeHead(404); res.end('Not found'); return; } + // Phase 25 slice D — ?theme=dark renders the dark token layer. + const theme = url.searchParams.get('theme') === 'dark' ? 'dark' as const : undefined; + const resolved = expandTree(canvas.root, canvas, getCanvasTokens(canvas), { theme }).root; + const defaultW = typeof canvas.root.width === 'number' ? canvas.root.width : 1440; + const defaultH = typeof canvas.root.height === 'number' ? canvas.root.height : 900; + const w = url.searchParams.has('w') ? parseInt(url.searchParams.get('w')!, 10) : defaultW; + const h = url.searchParams.has('h') ? parseInt(url.searchParams.get('h')!, 10) : defaultH; + // skeletonPulse: the live viewer is the ONE context where skeleton + // blocks animate — screenshots/exports/diffs stay static. + const html = renderToHtml(resolved, w, h, canvas, { skeletonPulse: true }); + res.setHeader('Content-Type', 'text/html'); + res.end(html); + return; + } + + // Canvas JSON + const jsonMatch = path.match(/^\/canvas\/([^/]+)\/json$/); + if (jsonMatch) { + const canvas = getCanvas(jsonMatch[1]); + if (!canvas) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(canvas, null, 2)); + return; + } + + // Canvas detail page + const detailMatch = path.match(/^\/canvas\/([^/]+)$/); + if (detailMatch) { + const canvas = getCanvas(detailMatch[1]); + if (!canvas) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'text/html'); + res.end(await renderDetailPage(canvas, runningPort ?? 3001)); + return; + } + + // Project page + const projectMatch = path.match(/^\/project\/([^/]+)$/); + if (projectMatch) { + const html = await renderProjectPage(projectMatch[1], runningPort ?? 3001); + if (!html) { res.writeHead(404); res.end('Project not found'); return; } + res.setHeader('Content-Type', 'text/html'); + res.end(html); + return; + } + + // Archive page + if (path === '/archive') { + res.setHeader('Content-Type', 'text/html'); + res.end(renderArchivePage(runningPort ?? 3001)); + return; + } + + // Lifecycle API: archive / unarchive / delete a canvas. Three small + // wrappers around the scene-graph functions so the viewer's action + // buttons (archive page + detail page) don't need to round-trip + // through an MCP client. + const archiveApi = path.match(/^\/api\/canvas\/([^/]+)\/archive$/); + if (archiveApi && req.method === 'POST') { + const id = archiveApi[1]; + // Repo-mirrored canvases write back to their `.framesmith/` file; global + // canvases use the in-memory + global-store path. + const result = getRepoLocation(id) ? archiveRepoCanvas(id, true) : !!archiveCanvas(id); + if (!result) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ ok: true, canvasId: id, archived: true })); + return; + } + const unarchiveApi = path.match(/^\/api\/canvas\/([^/]+)\/unarchive$/); + if (unarchiveApi && req.method === 'POST') { + const id = unarchiveApi[1]; + const result = getRepoLocation(id) ? archiveRepoCanvas(id, false) : !!unarchiveCanvas(id); + if (!result) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ ok: true, canvasId: id, archived: false })); + return; + } + // Feedback API (Phase 21 Slice B) — point-and-tell comments. Same + // backend routing as the lifecycle endpoints above. + const feedbackApi = path.match(/^\/api\/canvas\/([^/]+)\/feedback$/); + if (feedbackApi && req.method === 'GET') { + const canvas = getCanvas(feedbackApi[1]); + if (!canvas) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ openCount: openFeedbackCount(canvas), entries: listFeedback(canvas, { includeResolved: true }) })); + return; + } + if (feedbackApi && req.method === 'POST') { + const id = feedbackApi[1]; + const body = await readJsonBody(req); + const nodeId = typeof body.nodeId === 'string' && body.nodeId ? body.nodeId : undefined; + const comment = typeof body.comment === 'string' ? body.comment : ''; + let entry: unknown = null; + let addError: string | null = null; + const ok = mutateFeedback(id, (c) => { + try { entry = addFeedback(c, { nodeId, comment }); return true; } + catch (e) { addError = (e as Error).message; return false; } + }); + if (addError) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: false, error: addError })); return; } + if (!ok) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ ok: true, entry })); + return; + } + const feedbackItemApi = path.match(/^\/api\/canvas\/([^/]+)\/feedback\/([^/]+)$/); + if (feedbackItemApi && req.method === 'DELETE') { + const [, id, fbId] = feedbackItemApi; + let removed = false; + const ok = mutateFeedback(id, (c) => { removed = deleteFeedback(c, fbId); return removed; }); + if (!ok || !removed) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ ok: true, deleted: fbId })); + return; + } + const feedbackResolveApi = path.match(/^\/api\/canvas\/([^/]+)\/feedback\/([^/]+)\/resolve$/); + if (feedbackResolveApi && req.method === 'POST') { + const [, id, fbId] = feedbackResolveApi; + const body = await readJsonBody(req); + const note = typeof body.note === 'string' && body.note.trim() ? body.note.trim() : undefined; + let resolved = false; + const ok = mutateFeedback(id, (c) => { resolved = resolveFeedback(c, [fbId], 'user', note).resolved.length > 0; return resolved; }); + if (!ok || !resolved) { res.writeHead(404); res.end('Not found'); return; } + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ ok: true, resolved: fbId })); + return; + } + + const deleteApi = path.match(/^\/api\/canvas\/([^/]+)$/); + if (deleteApi && req.method === 'DELETE') { + const id = deleteApi[1]; + if (!getCanvas(id)) { res.writeHead(404); res.end('Not found'); return; } + if (getRepoLocation(id)) deleteRepoCanvas(id); else deleteCanvas(id); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ ok: true, canvasId: id, deleted: true })); + return; + } + + // Index → default project + if (path === '/') { + res.writeHead(302, { Location: `/project/${DEFAULT_PROJECT_ID}` }); + res.end(); + return; + } + + res.writeHead(404); + res.end('Not found'); + } catch (err) { + res.writeHead(500); + res.end(`Server error: ${(err as Error).message}`); + } + }); + + // Try sequential ports starting from BASE_PORT (or a specific port if given) + if (port > 0) { + // Specific port requested + const actualPort = await tryListen(httpServer, port); + runningPort = actualPort; + process.stderr.write(`Canvas viewer running at http://localhost:${actualPort}\n`); + return actualPort; + } + + // Auto-assign: try 3001, 3002, 3003... + for (let i = 0; i < MAX_ATTEMPTS; i++) { + try { + const tryPort = BASE_PORT + i; + const actualPort = await tryListen(httpServer, tryPort); + runningPort = actualPort; + process.stderr.write(`Canvas viewer running at http://localhost:${actualPort}\n`); + return actualPort; + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw err; + // Port in use, try next + } + } + + // Fallback: let OS assign + const actualPort = await tryListen(httpServer, 0); + runningPort = actualPort; + process.stderr.write(`Canvas viewer running at http://localhost:${actualPort}\n`); + return actualPort; +} diff --git a/src/viewer/shared.ts b/src/viewer/shared.ts new file mode 100644 index 0000000..e54d328 --- /dev/null +++ b/src/viewer/shared.ts @@ -0,0 +1,77 @@ +// 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 { DEFAULT_DEVICE, DEVICE_PROFILES } from '../surfaces.js'; + +export function esc(str: string): string { + return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +} + +/** JSON.stringify safe to inline inside a `; +await page.setContent(harness); + +// Tabs. +await page.focus('#tab-one'); +await page.keyboard.press('ArrowRight'); +const tabState = () => page.evaluate(() => ({ + selected: document.querySelector('[role="tab"][aria-selected="true"]')?.id, + shown: [...document.querySelectorAll('[role="tabpanel"]')].filter((p) => !(p as HTMLElement).hidden).map((p) => p.id), + tabbable: [...document.querySelectorAll('[role="tab"]')].filter((t) => (t as HTMLElement).tabIndex === 0).map((t) => t.id), +})); +let t = await tabState(); +check('tabs: ArrowRight selects the next tab and shows its panel', t.selected === 'tab-two' && t.shown.join() === 'panel-two', JSON.stringify(t)); +check('tabs: only the selected tab is in the tab order', t.tabbable.join() === 'tab-two'); +await page.keyboard.press('End'); +t = await tabState(); +check('tabs: End selects the last tab', t.selected === 'tab-three' && t.shown.join() === 'panel-three'); +await page.keyboard.press('ArrowRight'); +t = await tabState(); +check('tabs: ArrowRight wraps to the first tab', t.selected === 'tab-one' && (await focused(page)) === 'tab-one'); +await page.keyboard.press('ArrowLeft'); +check('tabs: ArrowLeft wraps to the last tab', (await tabState()).selected === 'tab-three'); + +// Menu. +const menuOpen = () => page.evaluate(() => !(document.getElementById('more') as HTMLElement).hidden); +await page.focus('[aria-haspopup="menu"]'); +await page.keyboard.press('Enter'); +check('menu: Enter on the button opens it with the first item focused', (await menuOpen()) && (await focused(page)) === 'json'); +check('menu: the button reports aria-expanded', await page.$eval('[aria-haspopup="menu"]', (b) => b.getAttribute('aria-expanded') === 'true')); +await page.keyboard.press('ArrowDown'); +check('menu: ArrowDown moves to the next item', (await focused(page)) === 'copy'); +await page.keyboard.press('ArrowDown'); +await page.keyboard.press('ArrowDown'); +check('menu: ArrowDown wraps past the last item', (await focused(page)) === 'json'); +await page.keyboard.press('ArrowUp'); +check('menu: ArrowUp wraps to the last item', (await focused(page)) === 'delete'); +await page.keyboard.press('Escape'); +check('menu: Escape closes it and returns focus to the button', !(await menuOpen()) && (await focused(page)) === 'More actions'); +await page.keyboard.press('Enter'); +await page.keyboard.press('ArrowDown'); +await page.keyboard.press('Enter'); +check('menu: Enter on an item fires menuaction and closes', (await page.evaluate(() => (window as unknown as { actions: string[] }).actions.join())) === 'copy' && !(await menuOpen())); +await page.click('[aria-haspopup="menu"]'); +await page.click('#outside'); +check('menu: an outside click closes it', !(await menuOpen())); + +// Dialog. +const dialogOpen = () => page.evaluate(() => !(document.querySelector('[data-dialog-scrim]') as HTMLElement).hidden); +await page.focus('#opener'); +await page.keyboard.press('Enter'); +check('dialog: opens with focus on Cancel', (await dialogOpen()) && (await focused(page)) === 'Cancel'); +check('dialog: is a modal dialog named by its title', await page.$eval('#confirm', (d) => d.getAttribute('role') === 'dialog' && d.getAttribute('aria-modal') === 'true' && document.getElementById(d.getAttribute('aria-labelledby')!)?.textContent === 'Delete dashboard?')); +await page.keyboard.press('Tab'); +check('dialog: Tab moves to the confirm button', (await focused(page)) === 'Delete canvas'); +await page.keyboard.press('Tab'); +check('dialog: Tab wraps inside the dialog', (await focused(page)) === 'Cancel'); +await page.keyboard.down('Shift'); await page.keyboard.press('Tab'); await page.keyboard.up('Shift'); +check('dialog: Shift+Tab wraps backwards', (await focused(page)) === 'Delete canvas'); +await page.keyboard.press('Escape'); +check('dialog: Escape cancels and returns focus to the opener', !(await dialogOpen()) && (await focused(page)) === 'opener'); +await page.keyboard.press('Enter'); +await page.keyboard.press('Tab'); +await page.keyboard.press('Enter'); +const results = await page.evaluate(() => (window as unknown as { results: boolean[] }).results); +check('dialog: resolves false on cancel and true on confirm', results.join() === 'false,true', results.join()); + +// ── FR-A3 offline: an empty font cache renders the fallback stack ──────────── +// env.js points FRAMESMITH_HOME at an empty temp dir, so nothing is cached yet. +{ + loadPersistedWorkspaces(); + ensureDefaultWorkspaceAndProject(); + const cold = (await renderProjectPage(DEFAULT_PROJECT_ID, 0))!; + check('fonts offline: no @font-face is declared with an empty cache', !cold.includes('@font-face')); + const coldErrors: string[] = []; + const onError = (e: unknown) => coldErrors.push(String(e)); + page.on('pageerror', onError); + await page.setContent(cold, { waitUntil: 'load' }); + const family = await page.evaluate(() => getComputedStyle(document.body).fontFamily); + check('fonts offline: the body falls back to system-ui', family.includes('system-ui'), family); + check('fonts offline: the page renders with no script error', coldErrors.length === 0, coldErrors.join(' | ')); + page.off('pageerror', onError); +} + +// ── a live viewer for FR-A5 and FR-A3 ──────────────────────────────────────── +loadPersistedWorkspaces(); +ensureDefaultWorkspaceAndProject(); +const canvas = createCanvas('narrow', DEFAULT_PROJECT_ID); +parseAndExecute(canvas.root, 'I("document", { type: "frame", width: "100%", height: 200, fill: "#E2E2DF" })', canvas); +archiveCanvas(createCanvas('archived', DEFAULT_PROJECT_ID).id); + +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 base = `http://127.0.0.1:${port}`; +const errors: string[] = []; +page.on('pageerror', (e) => errors.push(String(e))); +page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); }); + +// FR-A5: 390×844, no page scrolls sideways; the drawer opens and closes. +await page.setViewport({ width: 390, height: 844 }); +for (const [name, path] of [['project', `/project/${DEFAULT_PROJECT_ID}`], ['archive', '/archive'], ['detail', `/canvas/${canvas.id}`]] as const) { + await page.goto(base + path, { waitUntil: 'load' }); + const wide = await page.evaluate(() => ({ scroll: document.documentElement.scrollWidth, client: document.documentElement.clientWidth })); + check(`narrow: the ${name} page has no horizontal scroll at 390px`, wide.scroll <= wide.client, `${wide.scroll} > ${wide.client}`); +} +await page.goto(`${base}/project/${DEFAULT_PROJECT_ID}`, { waitUntil: 'load' }); +const sidebarLeft = () => page.$eval('.sidebar', (s) => s.getBoundingClientRect().right); +check('narrow: the sidebar starts off-canvas', (await sidebarLeft()) <= 0); +await page.click('.sidebar-toggle'); +await new Promise((r) => setTimeout(r, 400)); +check('narrow: the toggle opens the drawer', (await sidebarLeft()) > 0); +await page.mouse.click(380, 400); +await new Promise((r) => setTimeout(r, 400)); +check('narrow: the backdrop closes it', (await sidebarLeft()) <= 0); +// FR-A5: the detail page's inspector stacks at 720px or less, and its toolbar +// wraps at 640px or less. +await page.setViewport({ width: 700, height: 900 }); +await page.goto(`${base}/canvas/${canvas.id}`, { waitUntil: 'load' }); +const stacked = await page.evaluate(() => { + const inspector = document.getElementById('inspector')!.getBoundingClientRect(); + const viewport = document.getElementById('viewport')!.getBoundingClientRect(); + return { inspectorWidth: inspector.width, inspectorTop: inspector.top, viewportBottom: viewport.bottom, page: document.documentElement.clientWidth }; +}); +check('narrow: at 700px the inspector stacks under the preview, full width', stacked.inspectorWidth >= stacked.page - 1 && stacked.inspectorTop >= stacked.viewportBottom - 1, JSON.stringify(stacked)); +const toolbarHeight = async (width: number) => { + await page.setViewport({ width, height: 900 }); + await page.goto(`${base}/canvas/${canvas.id}`, { waitUntil: 'load' }); + return page.$eval('.toolbar', (t) => t.getBoundingClientRect().height); +}; +const wide = await toolbarHeight(1440); +const wrapped = await toolbarHeight(600); +check('narrow: at 600px the detail toolbar wraps onto more rows', wrapped > wide * 1.5, `${wide} → ${wrapped}`); +await page.setViewport({ width: 1440, height: 900 }); + +// FR-A3: with the cache warm, the design system's faces load from the font route. +let warm = true; +for (const family of VIEWER_FONT_FAMILIES) { + try { await resolveFamily(family); } catch { warm = false; } +} +if (!warm) { + console.log('SKIP fonts: no network to warm the font cache'); +} else { + await page.goto(`${base}/project/${DEFAULT_PROJECT_ID}`, { waitUntil: 'load' }); + const loaded = await page.evaluate(async () => { + const faces = await document.fonts.load('14px Inter'); + return { count: faces.length, family: faces[0]?.family ?? '' }; + }); + check('fonts: Inter loads from /assets/fonts', loaded.count > 0 && loaded.family.includes('Inter'), JSON.stringify(loaded)); + const body = await page.evaluate(() => getComputedStyle(document.body).fontFamily); + check('fonts: the body uses Inter first', body.startsWith('Inter') || body.startsWith('"Inter"'), body); +} +check('no page error or console error on any page', errors.length === 0, errors.join(' | ').slice(0, 300)); + +await browser.close(); +process.exit(allPass ? 0 : 1); diff --git a/test/unit/test-archive-view.ts b/test/unit/test-archive-view.ts index 693e26c..c3e7a30 100644 --- a/test/unit/test-archive-view.ts +++ b/test/unit/test-archive-view.ts @@ -38,14 +38,19 @@ const archivedB = sg.createCanvas('to-archive-b', brand.id); sg.archiveCanvas(archivedA.id); sg.archiveCanvas(archivedB.id); +/** The sidebar's Archive link (Phase 33): whether it is the current place, and its count. */ +function archiveLink(html: string): { current: boolean; count: number } | null { + const m = /([\s\S]*?)<\/a>/.exec(html); + return m ? { current: !!m[1], count: Number(/(\d+)<\/span>/.exec(m[2])?.[1] ?? NaN) } : null; +} + // ---- 1. Sidebar Archive entry on a project page ------------------------ { const html = (await viewer.renderProjectPage(DEFAULT_PROJECT_ID, 3001))!; - check('project page: sidebar contains Archive link', html.includes('class="sidebar-archive')); + check('project page: sidebar contains Archive link', html.includes('class="nav-item sidebar-archive"')); check('project page: Archive link points to /archive', html.includes('href="/archive"')); - check('project page: Archive count = 2 (cross-project total)', - /class="sidebar-archive-count">2<\/span>/.test(html)); - check('project page: Archive entry is NOT active', !/class="sidebar-archive active"/.test(html)); + check('project page: Archive count = 2 (cross-project total)', archiveLink(html)?.count === 2); + check('project page: Archive entry is NOT the current place', archiveLink(html)?.current === false); } // ---- 2. Archive page renders the right canvases ----------------------- @@ -54,7 +59,7 @@ sg.archiveCanvas(archivedB.id); check('archive: title shows "Archived canvases"', /

Archived canvases<\/h1>/.test(html)); check('archive: meta shows count across all projects', html.includes('2 canvases across all projects')); - check('archive: Archive sidebar entry IS active', /class="sidebar-archive active"/.test(html)); + check('archive: Archive sidebar entry IS the current place', archiveLink(html)?.current === true); check('archive: contains archivedA card', html.includes(`/canvas/${archivedA.id}`)); check('archive: contains archivedB card', html.includes(`/canvas/${archivedB.id}`)); @@ -109,8 +114,7 @@ sg.archiveCanvas(archivedB.id); // Delete the archived canvas, archive count should drop in the sidebar. sg.deleteCanvas(archivedA.id); const html = (await viewer.renderProjectPage(DEFAULT_PROJECT_ID, 3001))!; - check('after delete: sidebar archive count drops to 0', - /class="sidebar-archive-count">0<\/span>/.test(html)); + check('after delete: sidebar archive count drops to 0', archiveLink(html)?.count === 0); } rmSync(tmp, { recursive: true, force: true }); diff --git a/test/unit/test-viewer-logo-favicon.ts b/test/unit/test-viewer-logo-favicon.ts index dd3a060..745a021 100644 --- a/test/unit/test-viewer-logo-favicon.ts +++ b/test/unit/test-viewer-logo-favicon.ts @@ -1,9 +1,8 @@ // Smoke for the viewer logo + favicon swap. // -// - Sidebar shows the framesmith grid path mark (not the old amber square). -// - Every page emits a `` favicon. -// - .sidebar-mark CSS no longer uses background-color (background is set on -// the placeholder span; the new SVG draws via stroke="currentColor"). +// - Every page emits a `` favicon with +// the framesmith grid mark, stroked in the design system's accent. +// - Phase 33: the sidebar's brand is the "framesmith" wordmark linked home. // // Usage: npx tsx test/unit/test-viewer-logo-favicon.ts @@ -18,6 +17,7 @@ const { loadPersistedWorkspaces, ensureDefaultWorkspaceAndProject } = await impo const { createCanvas } = await import('../../src/scene-graph.js'); const { renderProjectPage, renderArchivePage, renderDetailPage } = await import('../../src/viewer.js'); const { DEFAULT_PROJECT_ID } = await import('../../src/types.js'); +const { LIGHT } = await import('../../src/viewer/tokens.js'); interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; @@ -40,20 +40,14 @@ try { html.includes("d='M 4 4 L 20 4 L 20 20 L 4 20 Z")); } - // --- Sidebar shows the new logo SVG instead of the empty span --- + // --- Phase 33: the sidebar's brand is the wordmark, linked home; the grid + // mark lives on in the favicon, stroked in the design system's accent. --- for (const [name, html] of [['gallery', gallery], ['archive', archive]] as const) { - expect(`logo: ${name} sidebar contains the grid path mark`, - html.includes('`, - !html.includes('')); + expect(`brand: ${name} sidebar shows the framesmith wordmark linked to /`, + html.includes('framesmith')); + expect(`brand: ${name} sidebar has no grid mark`, !html.includes('sidebar-mark')); } - - // --- .sidebar-mark CSS no longer paints a solid amber rectangle --- - expect('css: .sidebar-mark no background-color: var(--accent)', - !gallery.includes('background: var(--accent); flex-shrink: 0; }'), - 'old rule (background: var(--accent)) should be replaced with color: var(--accent)'); - expect('css: .sidebar-mark uses color: var(--accent) for stroke', - gallery.includes('color: var(--accent)') && gallery.includes('.sidebar-mark {')); + expect('favicon: stroked in the light accent token', gallery.includes(`stroke='${encodeURIComponent(LIGHT.colors.accent)}'`)); // --- Detail page has no sidebar so logo-mark CSS may or may not appear, // but favicon must still be on the page (covered above). --- diff --git a/test/unit/test-viewer-routes.ts b/test/unit/test-viewer-routes.ts new file mode 100644 index 0000000..ba72f34 --- /dev/null +++ b/test/unit/test-viewer-routes.ts @@ -0,0 +1,94 @@ +// Phase 33 slice A (FR-A1, FR-A3) — every viewer route still answers after the +// move into src/viewer/, with its status and content type; and the new font +// route serves a cached file and nothing else. +// +// Usage: npx tsx test/unit/test-viewer-routes.ts + +import '../env.js'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { join } from 'node:path'; +import { loadPersistedWorkspaces, ensureDefaultWorkspaceAndProject } from '../../src/workspaces.js'; +import { createCanvas, archiveCanvas } from '../../src/scene-graph.js'; +import { startViewer } from '../../src/viewer.js'; +import { DEFAULT_PROJECT_ID } from '../../src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +/** A free port, so the test never meets a running viewer on 3001. */ +function freePort(): Promise { + return new Promise((resolve) => { + const s = createServer(); + s.listen(0, '127.0.0.1', () => { + const { port } = s.address() as { port: number }; + s.close(() => resolve(port)); + }); + }); +} + +loadPersistedWorkspaces(); +ensureDefaultWorkspaceAndProject(); +const canvas = createCanvas('routes', DEFAULT_PROJECT_ID); +const gone = createCanvas('to-delete', DEFAULT_PROJECT_ID); + +// A cached font file, as the font cache stores it (FRAMESMITH_HOME/fonts). +const fontsDir = join(process.env.FRAMESMITH_HOME!, 'fonts'); +mkdirSync(fontsDir, { recursive: true }); +writeFileSync(join(fontsDir, 'abc123.woff2'), Buffer.from('wOF2-test')); + +const port = await startViewer(await freePort()); +const base = `http://127.0.0.1:${port}`; + +async function expect(method: string, path: string, status: number, type?: string, body?: unknown) { + const res = await fetch(base + path, { + method, + redirect: 'manual', + ...(body !== undefined ? { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } } : {}), + }); + const ct = res.headers.get('content-type') ?? ''; + check(`${method} ${path} → ${status}${type ? ` ${type}` : ''}`, res.status === status && (!type || ct.startsWith(type)), `${res.status} ${ct}`); + return res; +} + +const root = await expect('GET', '/', 302); +check('GET / redirects to the default project', root.headers.get('location') === `/project/${DEFAULT_PROJECT_ID}`, root.headers.get('location') ?? ''); +await expect('GET', `/project/${DEFAULT_PROJECT_ID}`, 200, 'text/html'); +await expect('GET', '/project/nope', 404); +await expect('GET', `/canvas/${canvas.id}`, 200, 'text/html'); +await expect('GET', `/canvas/${canvas.id}/html`, 200, 'text/html'); +await expect('GET', `/canvas/${canvas.id}/html?w=390&h=844&theme=dark`, 200, 'text/html'); +await expect('GET', `/canvas/${canvas.id}/json`, 200, 'application/json'); +await expect('GET', '/canvas/nope', 404); +await expect('GET', '/archive', 200, 'text/html'); +await expect('GET', '/api/canvases', 200, 'application/json'); +const meta = await (await expect('GET', `/api/canvas/${canvas.id}/meta`, 200, 'application/json')).json() as { id: string; contentKey?: string }; +check('meta carries the id and a contentKey', meta.id === canvas.id && typeof meta.contentKey === 'string'); +await expect('GET', `/api/canvas/${canvas.id}/feedback`, 200, 'application/json'); + +const added = await (await expect('POST', `/api/canvas/${canvas.id}/feedback`, 200, 'application/json', { comment: 'tighten the header' })).json() as { entry?: { id: string }; id?: string }; +const fbId = added.entry?.id ?? added.id; +check('feedback POST returns the new entry id', typeof fbId === 'string', JSON.stringify(added).slice(0, 120)); +await expect('POST', `/api/canvas/${canvas.id}/feedback/${fbId}/resolve`, 200, 'application/json', { note: 'done' }); +await expect('DELETE', `/api/canvas/${canvas.id}/feedback/${fbId}`, 200); +await expect('POST', `/api/canvas/${canvas.id}/feedback`, 400, undefined, { nodeId: 'no-such-node', comment: 'x' }); + +await expect('POST', `/api/canvas/${canvas.id}/archive`, 200); +await expect('POST', `/api/canvas/${canvas.id}/unarchive`, 200); +archiveCanvas(gone.id); +await expect('DELETE', `/api/canvas/${gone.id}`, 200); + +// FR-A3: the font route. +const font = await expect('GET', '/assets/fonts/abc123.woff2', 200, 'font/woff2'); +check('font route: long-lived immutable cache header', (font.headers.get('cache-control') ?? '').includes('immutable')); +check('font route: serves the cached bytes', (await font.text()) === 'wOF2-test'); +await expect('GET', '/assets/fonts/missing.woff2', 404); +await expect('GET', '/assets/fonts/registry.json', 404); +await expect('GET', '/assets/fonts/..%2Fregistry.json', 404); + +await expect('GET', '/no/such/route', 404); + +process.exit(allPass ? 0 : 1); diff --git a/test/unit/test-viewer-sidebar.ts b/test/unit/test-viewer-sidebar.ts index 63789ca..0f8f828 100644 --- a/test/unit/test-viewer-sidebar.ts +++ b/test/unit/test-viewer-sidebar.ts @@ -46,31 +46,39 @@ sg.archiveCanvas(archivedOne.id); const htmlDefault = (await viewer.renderProjectPage(DEFAULT_PROJECT_ID, 3001))!; // ---- 1. Sidebar tree structure ------------------------------------------ -check('sidebar: contains "Framesmith" logo', htmlDefault.includes('sidebar-logo')); +// Phase 33 slice A: one nav-item link per project, the current one marked +// with aria-current="page"; an identity dot, the name and a count in each. +interface SidebarItem { current: boolean; label: string; count: number; dot: boolean } +function sidebarItem(html: string, projectId: string): SidebarItem | null { + const m = new RegExp(`([\\s\\S]*?)`).exec(html); + if (!m) return null; + return { + current: !!m[1], + label: /([^<]*)<\/span>/.exec(m[2])?.[1] ?? '', + count: Number(/(\d+)<\/span>/.exec(m[2])?.[1] ?? NaN), + dot: m[2].includes('class="nav-dot"'), + }; +} +const defaultItem = sidebarItem(htmlDefault, DEFAULT_PROJECT_ID); +const brandItem = sidebarItem(htmlDefault, projAcmeA.id); +check('sidebar: contains the "framesmith" wordmark', htmlDefault.includes('class="sidebar-brand">framesmith<')); check('sidebar: contains "Personal" workspace label', htmlDefault.includes('>Personal<')); check('sidebar: contains "Acme" workspace label', htmlDefault.includes('>Acme<')); -check('sidebar: contains "Untitled" project link', /\/project\/default-project[^"]*"[^>]*class="project[^"]*"[\s\S]*?Untitled/.test(htmlDefault)); -check('sidebar: project rows include a project-dot', /]*class="project active"`); -check('sidebar: requested project carries `active` class', activeRegex.test(htmlDefault)); +check('sidebar: contains "Untitled" project link', defaultItem?.label === 'Untitled', JSON.stringify(defaultItem)); +check('sidebar: project rows include an identity dot', defaultItem?.dot === true && brandItem?.dot === true); +check('sidebar: contains "Brand" project link', brandItem?.label === 'Brand'); +check('sidebar: contains "Marketing" project link', sidebarItem(htmlDefault, projAcmeB.id)?.label === 'Marketing'); -const inactiveRegex = new RegExp(`]*class="project"(?!\\s*active)`); -check('sidebar: other projects do NOT carry `active` class', inactiveRegex.test(htmlDefault)); +// ---- 2. The requested project is the current place ----------------------- +check('sidebar: requested project carries aria-current="page"', defaultItem?.current === true); +check('sidebar: other projects do NOT carry aria-current', brandItem?.current === false); +check('sidebar: exactly one current place on a project page', (htmlDefault.match(/]*aria-current="page"/g) ?? []).length === 1); // ---- 3. Canvas count badges count non-archived canvases per project ----- -// Default project has 2 active canvases (home + about) -check('sidebar: default project shows count 2', /default-project[^"]*"[^>]*class="project active"[^>]*>[\s\S]*?>2<\/span>/.test(htmlDefault)); -// Brand has 3 -check('sidebar: Brand project shows count 3', new RegExp(`${projAcmeA.id}[^"]*"[^>]*class="project"[^>]*>[\\s\\S]*?>3<\/span>`).test(htmlDefault)); -// Marketing has 0 -check('sidebar: Marketing project shows count 0', new RegExp(`${projAcmeB.id}[^"]*"[^>]*class="project"[^>]*>[\\s\\S]*?>0<\/span>`).test(htmlDefault)); -// Side has 1 archived canvas, count should be 0 (archived excluded) -check('sidebar: Side project shows count 0 (archived excluded)', new RegExp(`${projInDefault.id}[^"]*"[^>]*class="project"[^>]*>[\\s\\S]*?>0<\/span>`).test(htmlDefault)); +check('sidebar: default project shows count 2', defaultItem?.count === 2, String(defaultItem?.count)); +check('sidebar: Brand project shows count 3', brandItem?.count === 3, String(brandItem?.count)); +check('sidebar: Marketing project shows count 0', sidebarItem(htmlDefault, projAcmeB.id)?.count === 0); +check('sidebar: Side project shows count 0 (archived excluded)', sidebarItem(htmlDefault, projInDefault.id)?.count === 0); // ---- 4. Breadcrumb + main pane title ------------------------------------ check('main: breadcrumb shows "Personal / Untitled"', htmlDefault.includes('Personal / Untitled')); @@ -88,9 +96,8 @@ check('main: grid does NOT contain archived "old" canvas', !htmlDefault.includes 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: active highlight is on Brand, not Untitled', - new RegExp(`]*class="project active"`).test(htmlAcme) && - new RegExp(`]*class="project"(?!\\s*active)`).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, ); // ---- 7. Empty-project state --------------------------------------------- diff --git a/test/unit/test-viewer-tokens.ts b/test/unit/test-viewer-tokens.ts new file mode 100644 index 0000000..b9a4cf6 --- /dev/null +++ b/test/unit/test-viewer-tokens.ts @@ -0,0 +1,74 @@ +// Phase 33 slice A (FR-A2) — the viewer's tokens are the design's tokens. Loads +// the repo's .framesmith/workspace.json, reads the "Viewer redesign" project's +// design system, and asserts src/viewer/tokens.ts equals it in both themes. Then +// scans every other src/viewer file for a colour literal, which must not exist. +// +// Usage: npx tsx test/unit/test-viewer-tokens.ts + +import '../env.js'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; +import { loadRepoWorkspace, getProjectDesignSystem, listProjects } from '../../src/workspaces.js'; +import type { RepoWorkspaceFile } from '../../src/repo-store.js'; +import { DARK, LIGHT, RADIUS, SPACING, TYPE_ROLES, VIEWER_DESIGN_PROJECT, toBoxShadow, type ViewerTheme } from '../../src/viewer/tokens.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +// ── drift: tokens.ts against the committed design system ───────────────────── +const wf = JSON.parse(readFileSync('.framesmith/workspace.json', 'utf-8')) as RepoWorkspaceFile; +loadRepoWorkspace(wf); +const project = listProjects().find((p) => p.name === VIEWER_DESIGN_PROJECT.name); +check('the "Viewer redesign" project is in the repo workspace', !!project && project.id === VIEWER_DESIGN_PROJECT.id, project?.id); +const ds = project ? getProjectDesignSystem(project.id) : undefined; +check('it has a design system with a dark layer', !!ds?.colors && !!ds.dark?.colors); + +type Layers = Record>; +function compareTheme(label: string, theme: ViewerTheme, colors: Record | undefined, elevation: Layers | undefined) { + const drift = Object.entries(theme.colors).filter(([name, value]) => colors?.[name]?.toLowerCase() !== value.toLowerCase()); + check(`${label}: every colour token equals the design system`, drift.length === 0, drift.map(([n, v]) => `${n} ${v} ≠ ${colors?.[n]}`).join(', ')); + const shadowDrift = Object.entries(theme.elevation).filter(([name, value]) => !elevation?.[name] || toBoxShadow(elevation[name]) !== value); + check(`${label}: every elevation equals the design system`, shadowDrift.length === 0, shadowDrift.map(([n]) => n).join(', ')); +} +compareTheme('light', LIGHT, ds?.colors, ds?.elevation as Layers | undefined); +// The dark layer overrides; a name it leaves out inherits the light value. +compareTheme('dark', DARK, { ...ds?.colors, ...ds?.dark?.colors }, { ...(ds?.elevation as Layers | undefined), ...(ds?.dark?.elevation as Layers | undefined) }); + +const radiusDrift = Object.entries(RADIUS).filter(([n, v]) => ds?.radius?.[n] !== v); +check('radius equals the design system', radiusDrift.length === 0, radiusDrift.map(([n]) => n).join(', ')); +const spacingDrift = Object.entries(SPACING).filter(([n, v]) => ds?.spacing?.[n] !== v); +check('spacing equals the design system', spacingDrift.length === 0, spacingDrift.map(([n]) => n).join(', ')); +const typeDrift = Object.entries(TYPE_ROLES).filter(([role, spec]) => JSON.stringify(ds?.typography?.[role]) !== JSON.stringify(spec)); +check('type roles equal the design system', typeDrift.length === 0, typeDrift.map(([n]) => n).join(', ')); + +// ── no colour literal outside tokens.ts ────────────────────────────────────── +function files(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + return statSync(path).isDirectory() ? files(path) : path.endsWith('.ts') ? [path] : []; + }); +} +/** Comments and numeric HTML entities removed, so `issue #150` and `▢` + * are not read as colours. */ +function stripped(source: string): string { + return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:'"`\\])\/\/.*$/gm, '$1').replace(/&#\d+;/g, ''); +} +const LITERAL = /#[0-9A-Fa-f]{3,8}(?![\w-])|\b(rgba?|hsla?)\(/g; +const viewerFiles = files('src/viewer').filter((f) => !f.endsWith('tokens.ts')); +check('src/viewer has the expected modules', viewerFiles.length >= 9, String(viewerFiles.length)); +for (const file of viewerFiles) { + const hits = stripped(readFileSync(file, 'utf-8')).match(LITERAL) ?? []; + check(`${file}: no colour literal`, hits.length === 0, hits.join(' ')); +} + +// The scanner must catch what it is for: a self-test on known shapes. +check('scanner: finds a hex colour', (stripped('a { color: #FF00aa; }').match(LITERAL) ?? []).length === 1); +check('scanner: finds rgba()', (stripped('box-shadow: 0 0 1px rgba(0,0,0,0.5)').match(LITERAL) ?? []).length === 1); +check('scanner: ignores an id selector', (stripped('#add-btn { }').match(LITERAL) ?? []).length === 0); +check('scanner: ignores an issue reference in a comment', (stripped('// issue #150').match(LITERAL) ?? []).length === 0); +check('scanner: ignores an HTML entity', (stripped('▢').match(LITERAL) ?? []).length === 0); + +process.exit(allPass ? 0 : 1);