diff --git a/README.md b/README.md index ea098cb..9b0d7e3 100644 --- a/README.md +++ b/README.md @@ -66,11 +66,11 @@ Left to itself, an AI agent tends to produce UI that *looks* AI-generated — ge ## Viewer -Run `npx -p framesmith framesmith-viewer` to start the standalone browser viewer (it takes the first free port from 3001 up; pass a port to pin one). Open a web canvas to review it at multiple breakpoints and compare them side-by-side (a canvas declared `desktop-app` offers the narrower windows of its profile instead, 1024 and 1280 under a 1440 artboard); open any canvas to inspect its JSON, leave comments, or archive / delete it. Cards keep each artboard's proportions (between a phone held upright and 2:1; a longer page shows its top), so phone screens are portrait cards. A canvas declared `mobile` opens at 1:1 in a device frame instead of the breakpoint buttons, with a **Safe area** toggle that shades the status-bar and home-indicator insets (47 and 34 on the default `iphone-390`). The overlay is viewer-only: it never changes a screenshot. +Run `npx -p framesmith framesmith-viewer` to start the standalone browser viewer (it takes the first free port from 3001 up; pass a port to pin one). Open a web canvas to review it at multiple breakpoints and compare them side-by-side (a canvas declared `desktop-app` offers the narrower windows of its profile instead, 1024 and 1280 under a 1440 artboard); open any canvas to leave comments, or use its **More** menu to view its JSON, copy its ID, and archive or delete it. The preview opens fitted to the pane's width, with zoom (50 / 75 / 100 / 150 / 200%) and Fit buttons; a moon button, **Preview in dark**, shows the dark theme when the design system has one. Cards keep each artboard's proportions (between a phone held upright and 2:1; a longer page shows its top), so phone screens are portrait cards. A canvas declared `mobile` opens at 1:1 in a device frame instead of the breakpoint tabs and zoom, with a **Show safe area** tool button that shades the status-bar and home-indicator insets (47 and 34 on the default `iphone-390`). The overlay is viewer-only: it never changes a screenshot. ![framesmith canvas detail view — the dashboard pattern rendered (grouped sidebar navigation with an account row, KPI cards with sparklines and delta pills, a real multi-series line chart with an area fill and a dashed reference line beside a recent-activity feed) with the Quality inspector open on the right: a 99/100 "Excellent" score, per-category bars (spacing, color, typography, structure, consistency, usability, coverage, cliche), and honest APCA advisories in the issue list. The toolbar shows the canvas's designed states (default / loading / empty), theme and viewport toggles, and a Comment toggle.](https://raw.githubusercontent.com/vicmaster/framesmith/master/docs/framesmith-canvas.png?v=2.0) -> Above: a canvas in the detail view with the **Quality inspector** on the right — the same `canvas_evaluate` score the agent sees, with per-category bars and the issue list; the tabs along the top switch to the **Design-system** and **Feedback** panels. The toolbar exposes breakpoint previews, Compare, Fit, JSON, a **Comment** toggle for point-and-tell feedback, and lifecycle actions. +> Above: a canvas in the detail view with the **Quality inspector** on the right — the same `canvas_evaluate` score the agent sees, with per-category bars and the issue list; the tabs along the top switch to the **Design-system** and **Feedback** panels. The toolbar carries the project back link, the canvas's designed states as a nav, breakpoint tabs with Compare, a **Comment** button with the open-comment count for point-and-tell feedback, a **More** menu (View JSON, Copy canvas ID, Archive or Restore, Delete canvas) and a Live / Offline status; zoom, Fit and Preview in dark sit in the preview tools. **Quality panel.** The canvas detail view shows a read-only **quality inspector** on the right: the heuristic `canvas_evaluate` score (0–100), per-category bars, and the issue list — each cliché tell with its `category · tell` badge, severity, and suggestion. Issues that `canvas_autofix` can resolve carry an **auto-fixable** tag, and clicking any issue **highlights its node** in the live preview. Every gallery card also shows a score chip on its thumbnail: neutral at 96 and above, amber at 95 or below (the quality bar), so canvases under the bar stand out at a glance. The project header sums it up as "N canvases · M below the bar". The score matches what your agent sees over MCP (same fast-mode evaluation, relaxed by the canvas's stored genre and applied preset) — it's computed for display only and never written back. @@ -214,7 +214,7 @@ Clone a screen into a linked **state variant** — the empty / loading / error v | `canvasId` | string | The base canvas (a variant id also works — it resolves to the root base; variants never nest) | | `state` | string | The state this variant designs — `empty` / `loading` / `error` for data states, `menu-open` / `comment-open` / `confirm-delete` / `toast` for overlay states; free string accepted | -Returns `{ canvasId, name, state, of, idMap }` — `idMap` maps every base node id to its clone, so follow-up edits target the right nodes immediately. One canvas per state per base (a duplicate state errors). The viewer's project page shows a screen and its variants as one card, with the designed-state count in the card's meta line ("… · 3 states"); the detail page lists the states as chips; `canvas_list` rolls designed states onto the base row. +Returns `{ canvasId, name, state, of, idMap }` — `idMap` maps every base node id to its clone, so follow-up edits target the right nodes immediately. One canvas per state per base (a duplicate state errors). The viewer's project page shows a screen and its variants as one card, with the designed-state count in the card's meta line ("… · 3 states"); the detail page lists the states as a nav of links in the toolbar; `canvas_list` rolls designed states onto the base row. ### `canvas_move` / `canvas_archive` / `canvas_unarchive` / `canvas_delete` @@ -1377,7 +1377,7 @@ The standalone viewer: - **Gallery** (`/`) — browse all canvases as clickable cards with live thumbnails - **Project** (`/project/:id`) — one project's canvases as cards (score chip, type, size, edit date, state count), with a Live / Offline status, a search field (`?q=`) and Web / Mobile / Desktop app tabs (`?type=`) kept in the URL - **Archive** (`/archive`) — soft-deleted canvases with restore / permadelete actions -- **Canvas detail** (`/canvas/:id`) — full rendered design with responsive viewport buttons (Mobile / Tablet / Desktop), Compare mode, Fit toggle, and JSON inspector; a canvas declared `mobile` opens 1:1 in a device frame with a Safe area toggle instead of the viewport, Compare and Fit buttons +- **Canvas detail** (`/canvas/:id`) — the rendered design, fitted to the pane with zoom (50–200%) and Fit buttons, breakpoint tabs (Mobile / Tablet / Desktop / Compare; a `desktop-app` canvas gets its window widths, the artboard and Compare), a **More** menu (View JSON, Copy canvas ID, Archive / Restore, Delete canvas) and a caption naming type, size and states; a canvas declared `mobile` opens 1:1 in a device frame with a **Show safe area** tool button instead of the tabs and zoom - **Raw HTML** (`/canvas/:id/html`) — the rendered HTML for embedding or inspection - **JSON API** (`/api/canvases`, `/api/canvas/:id/meta`) — programmatic access; each `/api/canvases` row carries the canvas's resolved `type` and `genre` - **Fonts** (`/assets/fonts/`) — the viewer's own faces (Inter, Space Grotesk), served from the font cache (`~/.framesmith/fonts/`) diff --git a/VISION.md b/VISION.md index e1814ec..490ac55 100644 --- a/VISION.md +++ b/VISION.md @@ -601,7 +601,7 @@ Phase 31 rebuilt the viewer as canvases and left the code alone. A design pass o - [x] Slice A — foundation: `src/viewer/` modules, tokens copied from the design system and pinned by a test, chrome that follows the system's light or dark setting, fonts served from the cache, one sidebar, tabs, menu and dialog used everywhere - [x] Slice B — gallery: thumbnail cards with a score chip against the bar, search and type filter kept in the URL, a live status, and refresh on every edit -- [ ] 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) +- [x] Slice C — detail shell: toolbar with state tabs, a More menu (JSON, copy ID, archive, delete), a delete dialog, and preview tools (zoom, fit, preview theme, safe area) - [ ] Slice D — inspector and comments: the Quality tab sorted lowest first with a reason line, Design system and Feedback restyled, the Import placeholder removed, the comment popover, and panels that refresh live - [ ] Slice E — archive, docs and acceptance: the archive tree with a preview panel, README and screenshots, and each screen beside its design - [ ] Follow-up — the viewer sends `Access-Control-Allow-Origin: *` on every response, the routes that archive, delete and post comments included. It listens on 127.0.0.1 only, but a page open in the same browser can still send it a simple cross-origin POST (archive, unarchive, add or resolve a comment) without a preflight. Drop the header from mutating routes, reject requests whose `Origin` is not the viewer's own, and test both; a separate change from the visual port diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 65d8471..8166672 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -47,7 +47,7 @@ A canvas declares what medium it is on, separately from its genre (what it is fo - **`canvas_set_type` re-declares an existing canvas** (`"web"`, `"mobile"`, `"desktop-app"`, or `null` to clear). A desktop-app canvas narrower than its window's 1024px minimum gets a `hint` naming `U("document", { width: 1440, height: 900 })`. It writes the declaration only, so it never moves the `versionHash`. It never resizes the artboard and never writes or removes `safeArea`, because either would reflow what you placed; clearing the type leaves the root as it is. When a mobile result has a `hint`, follow it: it names `U("document", { safeArea: { top: 47, bottom: 34 } })` when the root doesn't reserve both insets, and `U("document", { width: 390, height: 844 })` when the root is another size. Both ops change the render, so re-check the layout after them. State variants keep the type they were created with, so re-declaring a base does not reach them: the result's `variantsOutOfSync` lists each variant whose type now differs (`{ state, canvasId, type }`); declare those too. - **`generate_design_system` on a mobile canvas** pivots the type scale on the device body size: 17px for every personality except `data-dense`, which uses 16px. **On a desktop-app canvas** it pivots on 14px (13px for `data-dense`), the size dense apps read at. An explicit `baseSize` wins. The result reports the generated pivot as `baseSize` and `baseSizeSource` (`"mobile"`, `"desktop-app"`, `"explicit"`, or `"personality"` on web). A `$body` inherited from a workspace or project design system is preserved by default and listed in `designSystemConflicts`; pass `preserveInherited: false` to take the mobile body. - **Every evaluate result carries a `surface` report**: `{ type, device, source, rulesOn, rulesOff, conflicts }`. Each axis value (type, genre, preset) contributes a ruleset, and the active rules are their union. `rulesOn` and `rulesOff` name the rule ids the rulesets turned on and off. A rule both enabled and disabled stays on: it is listed in `rulesOn` and in `conflicts`, so composing declarations can never switch a guardrail off. On a web canvas `rulesOn` is `["desktop-app-artboard", "mobile-artboard"]` (the two base rules, on for every type); on a mobile canvas it adds every rule in [the mobile ruleset](#the-mobile-ruleset); on a desktop-app canvas it adds every rule in [the desktop-app ruleset](#the-desktop-app-ruleset), and `rulesOff` lists `type-scale-ratio`, the one rule a type turns off today. -- **The viewer shows the declaration to the human.** Gallery cards take the artboard's proportions, between a phone held upright (390:844) and 2:1 (a longer page shows its top), so a phone screen is a portrait card. A canvas declared `mobile` opens at 1:1 in a device frame, without the breakpoint, Compare and Fit buttons, and with a **Safe area** toggle that shades the top and bottom insets: each side is the root's `safeArea` when it sets one, else the device's (47 and 34 on `iphone-390`), so a canvas made mobile with `canvas_set_type` shows the bands its content must clear. The overlay is presentation only and never reaches a screenshot or the `versionHash`. A canvas declared `desktop-app` opens at its window size with breakpoint buttons for the narrower window widths of its profile (1024 and 1280 under a 1440 artboard, plus the artboard's own width), and Compare shows them side by side. An undeclared 390px canvas opens as a web page with breakpoint buttons, so a phone screen that was never declared looks wrong to the reviewer as well as to `mobile-artboard`; `canvas_set_type({ canvasId, type: "mobile" })` fixes both, and the open page switches to the device frame on its own. +- **The viewer shows the declaration to the human.** Gallery cards take the artboard's proportions, between a phone held upright (390:844) and 2:1 (a longer page shows its top), so a phone screen is a portrait card. A canvas declared `mobile` opens at 1:1 in a device frame, without the breakpoint tabs, Compare and zoom / Fit buttons, and with a **Show safe area** tool button that shades the top and bottom insets: each side is the root's `safeArea` when it sets one, else the device's (47 and 34 on `iphone-390`), so a canvas made mobile with `canvas_set_type` shows the bands its content must clear. The overlay is presentation only and never reaches a screenshot or the `versionHash`. A canvas declared `desktop-app` opens at its window size with breakpoint tabs for the narrower window widths of its profile (1024 and 1280 under a 1440 artboard, plus the artboard's own width), and Compare shows them side by side. An undeclared 390px canvas opens as a web page with breakpoint tabs, so a phone screen that was never declared looks wrong to the reviewer as well as to `mobile-artboard`; `canvas_set_type({ canvasId, type: "mobile" })` fixes both, and the open page switches to the device frame on its own. ## The mobile ruleset diff --git a/docs/specs/PHASE-33-SPEC.md b/docs/specs/PHASE-33-SPEC.md index f062f9f..bef436b 100644 --- a/docs/specs/PHASE-33-SPEC.md +++ b/docs/specs/PHASE-33-SPEC.md @@ -139,6 +139,14 @@ Its design system is the project's: seed `#B45309`, personality `technical`, 14p **Slice C — detail shell.** `pages/detail.ts` toolbar, More menu, delete dialog, preview tools, caption and JSON panel (FR-C1 to FR-C4). Tests rewritten: `test-archive-view.ts` (its `btn-archive`, `btn-restore`, `btn-delete` and `lifecycleAction` assertions), `test-viewer-surface.ts` (device frame and breakpoint strings), `test-desktop-app.ts:260-266` (its `bp-w1024`, `bp-w1280`, `bp-desktop` ids and `bp-btn` count), `test-variants.ts:88-98` (the detail page's state chips become the States nav), `test/browser/test-viewer-compare.ts`, `test/browser/test-viewer-surface-browser.ts` (`.bp-btn` becomes the tab selector). New: `test/browser/test-viewer-detail.ts`. The `src/viewer.ts` re-export keeps every name tests import, `evalCacheKey` included (`test-dual-theme.ts`, `test-viewer-perf.ts`, `test/e2e/test-surface.ts`). +**Slice C — as built.** +- **C1: the breakpoint tabs have no inline handler.** The shared tab code selects on click and arrow keys and fires `tabchange`; the page switches the preview from each tab's `data-w` and `data-h`. An inline `onclick` as well would switch twice on a click and not at all on a key. +- **C2: a menu item can keep the menu open.** `renderMenu` items take `keepOpen`, so Copy canvas ID can say "Copied" in place; every other item closes the menu as FR-A4 says. The copy falls back to `execCommand('copy')` where the clipboard API is refused. +- **C3: fit is by width.** The fitted scale fills the pane's width (never above 100%); a tall artboard scrolls. The stage reports its scale and mode in `data-scale` and `data-mode`. +- **C4: the crumbs give way in order.** In a crowded toolbar the provenance and critique chips shrink first, then the title, down to an 80px floor (it carries the full name as a tooltip); the back link and the state nav keep their width. Below 1400px the breakpoint tabs move right, next to the actions, so the crumbs get the room; at 1100px or less the chips and the size hide; at 900px or less the toolbar wraps, the crumbs taking the first row. +- **C6: narrow windows scroll.** At 720px or less the preview keeps 60% of the window's height and the page scrolls down to the inspector, which was cut off before this slice (on master too). The dialog is 480px wide with a Close button, as the design shows. +- **C5: the JSON panel is an overlay** under the toolbar with its own Close button, and it is still refreshed on every content change while open. + **Slice D — inspector and comments.** The Quality tab (FR-D1), the restyled Design system and Feedback tabs and the removed Import tab (FR-D2), the comment popover (FR-D3), and the live inspector with its route and `feedbackKey` (FR-D4). Tests rewritten: `test-viewer-panels.ts` (inspector selectors), `test-viewer-feedback.ts` (`data-tab="feedback"`, `btn-comment`, `FB_INIT`), `test-eval-cache-key.ts:104` (it reads the provenance chip from the toolbar; the chip moves into the Quality tab). New: `test/browser/test-viewer-inspector.ts`, with an MCP-driven check of FR-D4 in `test/e2e/`. **Slice E — archive, docs, acceptance.** `pages/archive.ts` (FR-E1, FR-E2), docs and screenshots (FR-E3), and the side-by-side acceptance (FR-E4). Tests rewritten: `test-archive-view.ts` (archive page half). `test/manual/test-viewer.ts` and `test-viewer-navbar.ts` follow the new markup. New: `test/browser/test-viewer-archive.ts`. diff --git a/src/viewer/client/detail.ts b/src/viewer/client/detail.ts index bb967ed..52452b7 100644 --- a/src/viewer/client/detail.ts +++ b/src/viewer/client/detail.ts @@ -5,12 +5,16 @@ import { listFeedback } from '../../feedback.js'; import { evalCacheKey } from '../scores.js'; import { buildNodeIndex, scriptJson } from '../shared.js'; import { LIGHT } from '../tokens.js'; +import { COMPONENTS_JS, icon } from '../components.js'; export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: string): string { return ` + ${COMPONENTS_JS} 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)}; + const MOON_ICON = ${scriptJson(icon('moon'))}; + const SUN_ICON = ${scriptJson(icon('sun'))}; let lastModified = ${scriptJson(canvas.lastModified)}; let contentKey = ${scriptJson(evalCacheKey(canvas))}; // The layout (device frame or breakpoints, artboard size, safe-area bands) @@ -24,12 +28,19 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: const FB_INIT = ${scriptJson(listFeedback(canvas, { includeResolved: true }))}; const NODE_INDEX = ${scriptJson(buildNodeIndex(canvas.root))}; - // Auto-refresh polling + // Auto-refresh polling, and the Live / Offline status (FR-C1). + const liveEl = document.getElementById('live'); + const setLive = (ok) => { + if (!liveEl) return; + liveEl.classList.toggle('offline', !ok); + liveEl.querySelector('.live-label').textContent = ok ? 'Live' : 'Offline'; + }; setInterval(async () => { try { - const res = await fetch('/api/canvas/' + canvasId + '/meta'); + const res = await fetch('/api/canvas/' + canvasId + '/meta', { cache: 'no-store' }); + if (!res.ok) throw new Error(String(res.status)); const meta = await res.json(); - document.getElementById('status').className = 'status'; + setLive(true); // 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) { @@ -39,11 +50,10 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: lastModified = meta.lastModified; contentKey = meta.contentKey || contentKey; refreshFrames(); - // Update JSON if panel is open - if (document.getElementById('json-panel').classList.contains('open')) loadJson(); + if (!document.getElementById('json-panel').hidden) loadJson(); } } catch { - document.getElementById('status').className = 'status stale'; + setLive(false); } }, 2000); @@ -52,7 +62,12 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: 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'); } + // The label stays "Preview in dark" and aria-pressed says whether it is + // on; the icon shows the theme the preview is in. + if (btn) { + btn.setAttribute('aria-pressed', themeMode === 'dark' ? 'true' : 'false'); + btn.innerHTML = themeMode === 'dark' ? SUN_ICON : MOON_ICON; + } document.querySelectorAll('iframe').forEach((frame) => { const u = new URL(frame.src, location.href); if (themeMode === 'dark') u.searchParams.set('theme', 'dark'); @@ -68,7 +83,8 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: url.searchParams.set('t', t); frame.src = url.toString(); }; - if (document.getElementById('viewport').classList.contains('compare')) { + const vp = document.getElementById('viewport'); + if (vp && vp.classList.contains('compare')) { document.querySelectorAll('.compare-cell iframe').forEach(bump); } else { bump(document.getElementById('frame')); @@ -78,59 +94,97 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: const canvasW = ${scriptJson(w)}; const canvasH = ${scriptJson(h)}; + // FR-C4 — the preview scales with a transform: fit (never above 100%) by + // default, or a zoom step. The box takes the scaled size, so the pane + // scrolls over it when the preview is larger than the pane. + const ZOOM_STEPS = [0.5, 0.75, 1, 1.5, 2]; + let bpW = canvasW, bpH = canvasH, zoom = null; // null = fit + function fitScale() { + const vp = document.getElementById('viewport'); + const style = getComputedStyle(vp); + const room = vp.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight) - 2; + return Math.max(0.05, Math.min(1, room / bpW)); + } + function applyScale() { + const box = document.getElementById('frame-box'); + const frame = document.getElementById('frame'); + if (!box || !frame) return; + const scale = zoom ?? fitScale(); + box.style.width = Math.round(bpW * scale) + 'px'; + box.style.height = Math.round(bpH * scale) + 'px'; + frame.style.width = bpW + 'px'; + frame.style.height = bpH + 'px'; + frame.style.transform = 'scale(' + scale + ')'; + document.getElementById('stage').dataset.scale = scale.toFixed(4); + document.getElementById('stage').dataset.mode = zoom === null ? 'fit' : 'zoom'; + if (!document.getElementById('viewport').classList.contains('compare')) { + document.getElementById('btn-zoom-in').disabled = !ZOOM_STEPS.some((s) => s > scale + 1e-6); + document.getElementById('btn-zoom-out').disabled = !ZOOM_STEPS.some((s) => s < scale - 1e-6); + } + } + function zoomBy(dir) { + const current = zoom ?? fitScale(); + const next = dir > 0 ? ZOOM_STEPS.find((s) => s > current + 1e-6) : [...ZOOM_STEPS].reverse().find((s) => s < current - 1e-6); + if (next === undefined) return; + zoom = next; + applyScale(); + } + function fitPreview() { zoom = null; applyScale(); } + function setZoomTools(enabled) { + ['btn-zoom-in', 'btn-zoom-out', 'btn-fit'].forEach((id) => { const b = document.getElementById(id); if (b) b.disabled = !enabled; }); + if (enabled) applyScale(); + } + window.addEventListener('resize', () => { if (zoom === null) applyScale(); }); + applyScale(); + + function selectBp(bp) { + document.querySelectorAll('.bp-btn').forEach((b) => { + const on = b.id === 'bp-' + bp; + b.setAttribute('aria-selected', on ? 'true' : 'false'); + b.tabIndex = on ? 0 : -1; + }); + currentBp = bp; + } + 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 + vp.classList.remove('compare'); + bpW = w; bpH = h; zoom = null; 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; + selectBp(bp); + setZoomTools(true); } 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'; + document.getElementById('viewport').classList.add('compare'); + setZoomTools(false); + selectBp('compare'); } + // The breakpoint tabs fire "tabchange" (click or arrow keys, COMPONENTS_JS). + const bpTabs = document.querySelector('.bp-tabs'); + if (bpTabs) bpTabs.addEventListener('tabchange', (e) => { + const tab = document.getElementById('bp-' + e.detail.tab); + if (e.detail.tab === 'compare') setCompareMode(); + else setViewport(Number(tab.dataset.w), Number(tab.dataset.h), e.detail.tab); + }); + function toggleSafeArea() { const overlay = document.getElementById('safe-overlay'); overlay.hidden = !overlay.hidden; - document.getElementById('btn-safe').classList.toggle('active', !overlay.hidden); + document.getElementById('btn-safe').setAttribute('aria-pressed', overlay.hidden ? 'false' : 'true'); } - function toggleFit() { - const vp = document.getElementById('viewport'); - const btn = document.getElementById('btn-fit'); - vp.classList.toggle('fit'); - btn.classList.toggle('active'); - } - - function toggleJson() { + function toggleJson(force) { 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(); + const open = typeof force === 'boolean' ? force : panel.hidden; + panel.hidden = !open; + if (open) { loadJson(); panel.querySelector('button').focus(); } } + document.getElementById('json-panel').addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); toggleJson(false); } }); async function loadJson() { try { @@ -142,11 +196,10 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: } } - // 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). + // Archive / restore / delete. Delete confirms in the dialog first (FR-C3); + // afterwards the canvas page has nothing to show, so go to the project. async function lifecycleAction(action) { - if (action === 'delete' && !confirm('Permanently delete this canvas? This cannot be undone.')) return; + if (action === 'delete' && !(await fsDialog.open('delete-dialog'))) return; const projectId = ${scriptJson(canvas.projectId)}; try { const url = '/api/canvas/' + canvasId + (action === 'archive' ? '/archive' : action === 'unarchive' ? '/unarchive' : ''); @@ -159,6 +212,32 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: } } + // FR-C2 — the More menu. + let copyTimer = 0; + async function copyCanvasId(item) { + let ok = false; + try { await navigator.clipboard.writeText(canvasId); ok = true; } catch { + const field = document.createElement('textarea'); + field.value = canvasId; field.setAttribute('readonly', ''); field.style.position = 'fixed'; field.style.opacity = '0'; + document.body.appendChild(field); field.select(); + try { ok = document.execCommand('copy'); } catch {} + field.remove(); + item.focus(); + } + const label = item.querySelector('span'); + label.dataset.label = label.dataset.label || label.textContent; + label.textContent = ok ? 'Copied' : 'Copy failed'; + clearTimeout(copyTimer); + copyTimer = setTimeout(() => { label.textContent = label.dataset.label; }, 2000); + } + const moreMenu = document.querySelector('[data-menu="more-menu"]'); + if (moreMenu) moreMenu.addEventListener('menuaction', (e) => { + const action = e.detail.action; + if (action === 'json') toggleJson(true); + else if (action === 'copy') copyCanvasId(moreMenu.querySelector('[data-action="copy"]')); + else lifecycleAction(action); + }); + // ── 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. @@ -316,6 +395,7 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: function toggleComment() { commentMode = !commentMode; document.getElementById('btn-comment').classList.toggle('active', commentMode); + document.getElementById('btn-comment').setAttribute('aria-pressed', commentMode ? 'true' : 'false'); if (!commentMode) closePopover(); hookFrame(); } @@ -404,7 +484,8 @@ export function detailScript(canvas: Canvas, w: number, h: number, surfaceType: ta.focus(); } - document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closePopover(); }); + // An Escape the menu, dialog or JSON panel already handled keeps the draft. + document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !e.defaultPrevented) closePopover(); }); document.getElementById('frame').addEventListener('load', hookFrame); hookFrame(); renderFeedbackPane(FB_INIT); diff --git a/src/viewer/components.ts b/src/viewer/components.ts index 08ce0ab..d5e8ced 100644 --- a/src/viewer/components.ts +++ b/src/viewer/components.ts @@ -81,7 +81,7 @@ export function renderTabs(tabs: TabSpec[], label: string): string { return `
${buttons}
`; } -export type MenuItemSpec = { action: string; label: string; icon?: string; danger?: boolean } | 'separator'; +export type MenuItemSpec = { action: string; label: string; icon?: string; danger?: boolean; keepOpen?: 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 @@ -89,7 +89,7 @@ export type MenuItemSpec = { action: string; label: string; icon?: string; dange export function renderMenu(id: string, buttonHtml: string, buttonLabel: string, items: MenuItemSpec[]): string { const rows = items.map((item) => item === 'separator' ? '' - : ``).join(''); + : ``).join(''); return `