From 1da04b1d59ab3c2914029cb4615fcefbe0643aa8 Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:22:17 -0400 Subject: [PATCH] fix(ui-canvas): address review findings on gestures, exports, and replay - Editor: pass the finished gesture to endResize/endDrag (mouseup cleared it first, so handle resize, reorder, and Alt-drag threw on release); compute the drop target on the move that starts a drag; report border-radius from the four real corner properties. - Exports: refuse feedback for an ended session before writing any file; give each Apply batch its own .apply-.* pair so a later batch never rewrites an earlier queued snapshot. Finish keeps .edited.html. - Replay: applied edits keep replaying on reload until the artifact changes on disk, instead of vanishing as soon as the request is queued. - Stop hook: an ended UI session still delivers an undelivered Save and Finish. - Shell: clamp viewports from the bootstrap and sessionStorage; `pending` next_step points at each session's resume command. - Split ui.js (inspector.js, ui-css.js), editor.js (editor-gestures.js), and the UI routes out of plan-canvas/server.js (ui-canvas/server-routes.js) to keep every file under 800 lines. - Docs: state the server-side Host/Origin checks behind the sandbox claim. - Remove two unreferenced captured-export fixtures (one held a local path). --- .agents/skills/ui-canvas/SKILL.md | 14 +- docs/design/ui-canvas.md | 10 +- manifests/context-packs/skill-triggers@1.json | 2 +- scripts/hooks/plan-canvas-pending.js | 11 +- scripts/lib/plan-canvas/agent-identity.js | 12 +- scripts/lib/plan-canvas/server.js | 58 +- scripts/lib/ui-canvas/editor-gestures.js | 263 ++++++ scripts/lib/ui-canvas/editor.js | 289 +------ scripts/lib/ui-canvas/feedback.js | 14 +- scripts/lib/ui-canvas/inspector.js | 587 +++++++++++++ scripts/lib/ui-canvas/server-routes.js | 55 ++ scripts/lib/ui-canvas/ui-css.js | 217 +++++ scripts/lib/ui-canvas/ui.js | 807 +----------------- scripts/plan-canvas.js | 2 +- scripts/ui-canvas.js | 3 +- skills/ui-canvas/SKILL.md | 14 +- .../ui-canvas/pricing-card.edited.html | 66 -- .../ui-canvas/pricing-card.edits.json | 45 - tests/hooks/plan-canvas-pending-hook.test.js | 27 + tests/lib/plan-canvas-agent-identity.test.js | 8 + tests/lib/ui-canvas-feedback.test.js | 3 + tests/lib/ui-canvas-server-routes.test.js | 86 ++ tests/lib/ui-canvas-ui.test.js | 41 + tests/scripts/ui-canvas.test.js | 24 +- 24 files changed, 1436 insertions(+), 1222 deletions(-) create mode 100644 scripts/lib/ui-canvas/editor-gestures.js create mode 100644 scripts/lib/ui-canvas/inspector.js create mode 100644 scripts/lib/ui-canvas/server-routes.js create mode 100644 scripts/lib/ui-canvas/ui-css.js delete mode 100644 tests/fixtures/ui-canvas/pricing-card.edited.html delete mode 100644 tests/fixtures/ui-canvas/pricing-card.edits.json create mode 100644 tests/lib/ui-canvas-server-routes.test.js diff --git a/.agents/skills/ui-canvas/SKILL.md b/.agents/skills/ui-canvas/SKILL.md index 1112e29a0..cb7191101 100644 --- a/.agents/skills/ui-canvas/SKILL.md +++ b/.agents/skills/ui-canvas/SKILL.md @@ -106,15 +106,17 @@ listening" so the human knows you are connected. ```json { "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ], "viewport": { "preset": "mobile", "width": 393, "height": 852 }, - "exportPath": "/abs/.claude/previews/pricing-card.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.edits.json" } + "exportPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edits.json" } ``` - `edits` means the human clicked **Apply to file**: they want their hand edits written into the mockup now. Replace the mockup file with the contents of `exportPath` (it is the full DOM they are looking at, with their inline-style changes), tidy it into real CSS if it is messy, keep it - self-contained, and reply. The canvas clears its pending list, so nothing - is applied twice. + self-contained, and reply. Each Apply writes its own + `.apply-.*` pair, so a queued earlier batch keeps its own + snapshot. The canvas keeps showing the applied edits until your write to + the mockup reloads it, then drops them, so nothing is applied twice. ```json { "kind": "finish", "editCount": 5, "edits": [ "…" ], "viewport": { "preset": "desktop", "width": 1412, "height": 806 }, @@ -179,8 +181,10 @@ never the other way, so media queries are honest. only from an `edits` or `finish` payload, from `exportPath`. - Reply in the canvas (`await --reply`), not only in the terminal, while the session is open. -- The exported `.edited.html` and `.edits.json` are review artifacts, not - production code. Do not commit them unless the repo keeps previews. +- The exported `.edited.html` and `.edits.json` files (including the + per-Apply `.apply-.*` pairs) are review artifacts, not production + code. Do not commit them unless the repo keeps previews; delete the + `.apply-*` pairs once the mockup is updated. - The server is loopback-only, idles out after 30 minutes (`ECC_PLAN_CANVAS_IDLE_MS`), and keeps state in `~/.claude/plan-canvas/` (`ECC_PLAN_CANVAS_STATE_DIR`). `ECC_CANVAS_AGENT` overrides the detected diff --git a/docs/design/ui-canvas.md b/docs/design/ui-canvas.md index 810b3dd3f..e4ee68569 100644 --- a/docs/design/ui-canvas.md +++ b/docs/design/ui-canvas.md @@ -64,8 +64,14 @@ and `install-modules.json` (workflow-quality), `manifests/pi-core.json` exclusio ## Protocol -Shell and editor talk only over `postMessage` (the frame is sandboxed without -`allow-same-origin`, exactly like Plan Canvas, so a hostile mockup cannot reach the loopback API). +Shell and editor talk only over `postMessage`. The frame is sandboxed without +`allow-same-origin`, exactly like Plan Canvas, so the mockup runs with an opaque origin. That alone +does not stop its scripts from making requests; the server does: every request must carry an +allowed loopback `Host`, and any `Origin` header must name an allowed loopback host, so requests +from the frame (which send `Origin: null`) get `403`, including the preflight a JSON POST needs. The +shell accepts only messages whose source is the frame window and only the `uc:*` types listed +below; a mockup script can post those too, so it can describe or alter its own edits (the agent +wrote that mockup) but cannot read or post anything else in the shell. Editor → shell: `uc:ready`, `uc:selection` (descriptor, style report, breadcrumb), `uc:edits` (log plus undo/redo availability), `uc:status`, `uc:toggle-mode`, `uc:scroll`, `uc:export`. diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 8a1b814e8..cf88c1bda 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "ae8ae2053706c96b5c1e842d9c0c66b8403761ac35f7b32855ed80407179c7f8", + "registryDigest": "6009c40ea3e8fcb2e65fc8a7bb11dfd15298941cc6549c5788e9be00dc6c6802", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/scripts/hooks/plan-canvas-pending.js b/scripts/hooks/plan-canvas-pending.js index be94ff2f7..1c64d5936 100644 --- a/scripts/hooks/plan-canvas-pending.js +++ b/scripts/hooks/plan-canvas-pending.js @@ -98,11 +98,20 @@ function isInside(dir, file) { /** * Sessions holding feedback the agent has never seen, oldest activity first. */ +// Save and Finish ends a UI session in the same request that queues the +// final handoff, so an ended UI session still delivers an undelivered finish. +// Other ended sessions only hold stale feedback and stay quiet. +function deliverable(session) { + if (session.status !== 'ended') return true; + return session.mode === 'ui' && session.pendingFeedback.some(item => item && item.kind === 'finish'); +} + function pendingSessions(state, cwd, env = process.env) { const scopeAll = String(env.ECC_PLAN_CANVAS_STOP_SCOPE || '').trim().toLowerCase() === 'all'; return Object.values((state && state.sessions) || {}) - .filter(session => session && validSessionKey(session.key) && typeof session.file === 'string' && session.file.length > 0 && session.status !== 'ended') + .filter(session => session && validSessionKey(session.key) && typeof session.file === 'string' && session.file.length > 0) .filter(session => Array.isArray(session.pendingFeedback) && session.pendingFeedback.length > 0) + .filter(deliverable) .filter(session => (scopeAll ? true : isInside(cwd, session.file))) .sort((a, b) => String(a.updatedAt || '').localeCompare(String(b.updatedAt || ''))); } diff --git a/scripts/lib/plan-canvas/agent-identity.js b/scripts/lib/plan-canvas/agent-identity.js index 4094b9b50..9521be737 100644 --- a/scripts/lib/plan-canvas/agent-identity.js +++ b/scripts/lib/plan-canvas/agent-identity.js @@ -50,4 +50,14 @@ function sanitizeAgentDescriptor(raw) { return descriptor; } -module.exports = { HARNESS_MARKERS, agentDescriptor, detectAgentName, sanitizeAgentDescriptor }; +// The ?agent= query value: a JSON descriptor, or a bare harness name. +function agentFromParam(raw) { + if (!raw) return null; + try { + return sanitizeAgentDescriptor(JSON.parse(raw)); + } catch { + return sanitizeAgentDescriptor({ name: raw }); + } +} + +module.exports = { HARNESS_MARKERS, agentDescriptor, agentFromParam, detectAgentName, sanitizeAgentDescriptor }; diff --git a/scripts/lib/plan-canvas/server.js b/scripts/lib/plan-canvas/server.js index b679c95e0..c873b1fae 100644 --- a/scripts/lib/plan-canvas/server.js +++ b/scripts/lib/plan-canvas/server.js @@ -24,17 +24,13 @@ const { renderMarkdownArtifactHtml, renderSessionListHtml } = require('./ui'); -const { sanitizeAgentDescriptor } = require('./agent-identity'); -const { uiEditorJs } = require('../ui-canvas/editor'); -const { renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('../ui-canvas/ui'); -const { normalizeEdits, writeExport } = require('../ui-canvas/feedback'); +const { agentFromParam } = require('./agent-identity'); +const { exportErrorResponse, materializeUiExports, renderUiCanvasHtml, serveUiAsset } = require('../ui-canvas/server-routes'); const DEFAULT_PORT = 4517; const DEFAULT_HOST = '127.0.0.1'; const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; -// UI Canvas ships a serialized DOM snapshot with its edit batches, and a -// mockup with inline images can run to a few megabytes; the snapshot itself is -// capped separately in ui-canvas/feedback.js. +// Sized for UI Canvas DOM snapshots (capped separately in ui-canvas/feedback.js). const MAX_BODY_BYTES = 8 * 1024 * 1024; // How long the "agent is thinking" indicator survives without the agent // checking back in, before presence decays to the honest queued/waiting. @@ -236,25 +232,6 @@ function readSiblingAsset(baseDir, resolved) { return { data, realTarget }; } -// UI Canvas edit batches arrive with the full DOM snapshot. Write it (and the -// edit log) next to the artifact before the item is queued, and hand the agent -// paths instead of megabytes of markup. Chat items pass through untouched. -function materializeUiExports(session, items) { - return items.map(item => { - if (!item || typeof item !== 'object' || (item.kind !== 'edits' && item.kind !== 'finish')) return item; - // The on-disk log holds the same normalized edits the agent receives. - const edits = normalizeEdits(item.edits); - const written = writeExport(session.file, { - html: item.html, - edits, - viewport: item.viewport || null, - kind: item.kind - }); - const { html: _html, ...rest } = item; - return { ...rest, edits, exportPath: written.exportPath, editsPath: written.editsPath }; - }); -} - function createPlanCanvasServer({ store, host = DEFAULT_HOST, @@ -476,12 +453,8 @@ function createPlanCanvasServer({ const session = keyParam ? store.get(keyParam) : store.findByFile(file); if (!session) return sendJson(res, 200, { status: 'missing' }); const key = session.key; - const agentParam = url.searchParams.get('agent'); - if (agentParam) { - let descriptor = null; - try { descriptor = sanitizeAgentDescriptor(JSON.parse(agentParam)); } catch { descriptor = sanitizeAgentDescriptor({ name: agentParam }); } - if (descriptor) store.setAgent(key, descriptor); - } + const descriptor = agentFromParam(url.searchParams.get('agent')); + if (descriptor) store.setAgent(key, descriptor); const timeoutRaw = url.searchParams.get('timeoutMs'); const timeoutMs = timeoutRaw === null ? null : Math.max(0, Number.parseInt(timeoutRaw, 10) || 0); @@ -564,13 +537,15 @@ function createPlanCanvasServer({ if (action === 'feedback') { const body = await readJsonBody(req); let items = Array.isArray(body.items) ? body.items : []; + // Checked before any export is written: a stale tab must not replace + // the design a finished session already handed over. + if (session.status === 'ended') return sendJson(res, 409, { error: 'session already ended' }); if (session.mode === 'ui') { try { items = materializeUiExports(session, items); } catch (error) { - if (error.code === 'EUI_HTML_TOO_LARGE') return sendJson(res, 413, { error: 'html snapshot too large' }); - if (error.code === 'EUI_HTML_MISSING') return sendJson(res, 400, { error: 'edits and finish items need an html snapshot' }); - return sendJson(res, 500, { error: `could not write the export next to the artifact: ${error.message}` }); + const failure = exportErrorResponse(error); + return sendJson(res, failure.status, { error: failure.error }); } } const result = store.queueFeedback(key, items, { endSession: Boolean(body.endSession) }); @@ -754,18 +729,7 @@ function createPlanCanvasServer({ res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }); return res.end(artifactSdkJs()); } - if (req.method === 'GET' && pathname === '/ui-canvas.css') { - res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' }); - return res.end(uiCanvasCss()); - } - if (req.method === 'GET' && pathname === '/ui-client.js') { - res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }); - return res.end(uiClientJs()); - } - if (req.method === 'GET' && pathname === '/ui-editor.js') { - res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }); - return res.end(uiEditorJs()); - } + if (req.method === 'GET' && serveUiAsset(pathname, res)) return undefined; const canvasMatch = pathname.match(/^\/canvas\/([a-f0-9]{12})$/); if (req.method === 'GET' && canvasMatch) { const session = store.get(canvasMatch[1]); diff --git a/scripts/lib/ui-canvas/editor-gestures.js b/scripts/lib/ui-canvas/editor-gestures.js new file mode 100644 index 000000000..375aa9359 --- /dev/null +++ b/scripts/lib/ui-canvas/editor-gestures.js @@ -0,0 +1,263 @@ +'use strict'; + +/** + * UI Canvas in-page editor gestures: handle resize, drag to reorder, Alt-drag + * and arrow-key nudge, remove, and the inspector's style and size setters. + * A chunk of the editor script (see uiEditorJs in ./editor.js, which inlines + * it inside its closure and provides the selection, edit log, and overlay). + */ + +function editorGesturesJs() { + return String.raw` // ---- gestures: resize, move, nudge ----------------------------------------- + function startResize(dir, event) { + if (!selected) return; + var rect = selected.getBoundingClientRect(); + gesture = { kind: 'resize', dir: dir, el: selected, x0: event.clientX, y0: event.clientY, w0: rect.width, h0: rect.height, inlineBefore: captureInline(selected, ['width', 'height', 'flex', 'max-width']), ratio: rect.height ? rect.width / rect.height : 1, moved: false }; + document.documentElement.style.cursor = getComputedStyle(root.querySelector('.handle[data-dir="' + dir + '"]')).cursor; + document.documentElement.setAttribute('data-ecc-ui-canvas-noselect', ''); + } + function doResize(event) { + var g = gesture; + var dx = event.clientX - g.x0, dy = event.clientY - g.y0; + var width = g.w0, height = g.h0; + if (g.dir.indexOf('e') >= 0) width = g.w0 + dx; + if (g.dir.indexOf('w') >= 0) width = g.w0 - dx; + if (g.dir.indexOf('s') >= 0) height = g.h0 + dy; + if (g.dir.indexOf('n') >= 0) height = g.h0 - dy; + var corner = g.dir.length === 2; + if (g.el.tagName === 'IMG' && corner && !event.shiftKey) { + if (Math.abs(width - g.w0) >= Math.abs(height - g.h0)) height = width / g.ratio; else width = height * g.ratio; + } + width = Math.max(8, Math.round(width)); + height = Math.max(8, Math.round(height)); + var wantsW = g.dir.indexOf('e') >= 0 || g.dir.indexOf('w') >= 0 || (g.el.tagName === 'IMG' && corner && !event.shiftKey); + var wantsH = g.dir.indexOf('n') >= 0 || g.dir.indexOf('s') >= 0 || (g.el.tagName === 'IMG' && corner && !event.shiftKey); + g.width = wantsW ? width : undefined; + g.height = wantsH ? height : undefined; + applyInline(g.el, sizeStyles(g.el, g.width, g.height)); + g.moved = true; + scheduleBoxes(); + } + function endResize(g) { + document.documentElement.style.cursor = ''; + document.documentElement.removeAttribute('data-ecc-ui-canvas-noselect'); + if (!g.moved) return; + var rect = g.el.getBoundingClientRect(); + var edit = newEdit('resize', g.el, { width: g.width !== undefined ? Math.round(rect.width) : undefined, height: g.height !== undefined ? Math.round(rect.height) : undefined, before: { width: Math.round(g.w0), height: Math.round(g.h0) } }); + if (edit.width === undefined) delete edit.width; + if (edit.height === undefined) delete edit.height; + edit._inlineBefore = g.inlineBefore; + edit._el = g.el; + record(edit); + toast('Resized to ' + Math.round(rect.width) + ' × ' + Math.round(rect.height)); + } + + function axisOf(container) { + var cs = getComputedStyle(container); + if (cs.display.indexOf('flex') >= 0) return cs.flexDirection.indexOf('row') === 0 ? 'x' : 'y'; + if (cs.display.indexOf('grid') >= 0) return 'grid'; + var kids = elementChildren(container); + if (kids.length > 1) { + var inlineish = kids.every(function (k) { var d = getComputedStyle(k).display; return d.indexOf('inline') === 0 || k.tagName === 'IMG' || k.tagName === 'BUTTON' || k.tagName === 'A' || k.tagName === 'SPAN'; }); + if (inlineish) return 'x'; + } + return 'y'; + } + function dropPlan(x, y, dragged) { + var under = document.elementFromPoint(x, y); + if (!under || isOurs(under)) return null; + if (under === document.documentElement) under = document.body; + if (!under || under === dragged || dragged.contains(under)) return null; + var container, index, indicator; + if (under === dragged.parentElement || under.contains(dragged)) { + container = under; + var kids = elementChildren(container).filter(function (k) { return k !== dragged; }); + if (!kids.length) { index = 0; indicator = inner(container.getBoundingClientRect()); } + else { + var axis = axisOf(container); + var best = null, bestDist = Infinity; + for (var i = 0; i < kids.length; i++) { + var r = kids[i].getBoundingClientRect(); + var cx = r.left + r.width / 2, cy = r.top + r.height / 2; + var dist = axis === 'x' ? Math.abs(cx - x) : axis === 'y' ? Math.abs(cy - y) : Math.hypot(cx - x, cy - y); + if (dist < bestDist) { bestDist = dist; best = { el: kids[i], i: i, rect: r }; } + } + var after = axis === 'x' ? x > best.rect.left + best.rect.width / 2 : axis === 'y' ? y > best.rect.top + best.rect.height / 2 : (x > best.rect.left + best.rect.width / 2); + index = best.i + (after ? 1 : 0); + indicator = edge(best.rect, axis === 'grid' ? 'x' : axis, after); + } + } else { + container = under.parentElement; + if (!container) return null; + var axis2 = axisOf(container); + var rect = under.getBoundingClientRect(); + var after2 = axis2 === 'y' ? y > rect.top + rect.height / 2 : x > rect.left + rect.width / 2; + var siblings = elementChildren(container).filter(function (k) { return k !== dragged; }); + index = siblings.indexOf(under) + (after2 ? 1 : 0); + indicator = edge(rect, axis2 === 'grid' ? 'x' : axis2, after2); + } + return { container: container, index: index, indicator: indicator }; + } + function edge(rect, axis, after) { + if (axis === 'y') return { left: rect.left, top: (after ? rect.bottom : rect.top) - 1, width: rect.width, height: 3 }; + return { left: (after ? rect.right : rect.left) - 1, top: rect.top, width: 3, height: rect.height }; + } + function inner(rect) { return { left: rect.left + 4, top: rect.top + 4, width: Math.max(0, rect.width - 8), height: 3 }; } + + function startPress(el, event) { + gesture = { kind: 'press', el: el, x0: event.clientX, y0: event.clientY, nudge: event.altKey, started: false }; + } + function beginDrag(event) { + var g = gesture; + g.started = true; + if (g.nudge) { + g.kind = 'nudge'; + g.inlineBefore = captureInline(g.el, ['position', 'left', 'top']); + g.baseLeft = px(g.el.style.left); + g.baseTop = px(g.el.style.top); + if (getComputedStyle(g.el).position === 'static') g.el.style.position = 'relative'; + post({ type: 'uc:status', text: 'Nudging · release to keep the offset' }); + } else { + g.kind = 'move'; + g.fromParent = g.el.parentElement; + g.fromIndex = indexIn(g.fromParent, g.el); + g.el.style.pointerEvents = 'none'; + selBox.classList.add('dragging'); + post({ type: 'uc:status', text: 'Reordering · drop between siblings or into a container · hold Alt to nudge instead' }); + } + document.documentElement.setAttribute('data-ecc-ui-canvas-noselect', ''); + event.preventDefault(); + } + function doDrag(event) { + var g = gesture; + if (g.kind === 'nudge') { + applyInline(g.el, { left: (g.baseLeft + event.clientX - g.x0) + 'px', top: (g.baseTop + event.clientY - g.y0) + 'px' }); + scheduleBoxes(); + return; + } + var rect = g.el.getBoundingClientRect(); + place(ghostEl, { left: rect.left + (event.clientX - g.x0), top: rect.top + (event.clientY - g.y0), width: rect.width, height: rect.height }); + var plan = dropPlan(event.clientX, event.clientY, g.el); + g.plan = plan; + if (plan && plan.indicator) place(dropEl, plan.indicator); else dropEl.style.display = 'none'; + } + function endDrag(g) { + document.documentElement.removeAttribute('data-ecc-ui-canvas-noselect'); + post({ type: 'uc:status', text: '' }); + if (g.kind === 'nudge') { + var dx = px(g.el.style.left) - g.baseLeft, dy = px(g.el.style.top) - g.baseTop; + if (dx === 0 && dy === 0) { applyInline(g.el, g.inlineBefore); return; } + var edit = newEdit('nudge', g.el, { dx: dx, dy: dy }); + edit._inlineBefore = g.inlineBefore; + edit._el = g.el; + record(edit); + toast('Nudged ' + dx + ', ' + dy + 'px'); + return; + } + g.el.style.pointerEvents = ''; + if (!g.el.getAttribute('style')) g.el.removeAttribute('style'); + selBox.classList.remove('dragging'); + ghostEl.style.display = 'none'; + dropEl.style.display = 'none'; + var plan = g.plan; + if (!plan) return; + var sameSpot = plan.container === g.fromParent && (plan.index === g.fromIndex || plan.index === g.fromIndex + 1); + if (sameSpot) return; + var fromSelector = selectorFor(g.el); + var fromParentSelector = selectorFor(g.fromParent); + insertAt(plan.container, g.el, plan.index); + var moveEdit = newEdit('move', g.el, { from: { parent: fromParentSelector, index: g.fromIndex }, to: { parent: selectorFor(plan.container), index: indexIn(plan.container, g.el) } }); + moveEdit.selector = fromSelector; + moveEdit.selectorAfter = selectorFor(g.el); + moveEdit._fromParent = g.fromParent; + moveEdit._fromIndex = g.fromIndex; + moveEdit._el = g.el; + record(moveEdit); + toast('Moved ' + labelFor(g.el)); + } + + function nudgeBy(dx, dy) { + if (!selected) return; + var last = edits.length ? edits[edits.length - 1] : null; + if (last && last.kind === 'nudge' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 1500) { + applyInline(selected, { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' }); + last.dx += dx; + last.dy += dy; + last.at = new Date().toISOString(); + postEdits(); + scheduleBoxes(); + return; + } + var edit = newEdit('nudge', selected, { dx: dx, dy: dy }); + edit._inlineBefore = captureInline(selected, ['position', 'left', 'top']); + edit._el = selected; + var cs = getComputedStyle(selected); + var next = { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' }; + if (cs.position === 'static') next.position = 'relative'; + applyInline(selected, next); + record(edit); + } + + function removeSelected() { + if (!selected || selected === document.body) { toast('Select an element to remove'); return; } + var el = selected; + var parent = el.parentElement; + var edit = newEdit('remove', el, { outerHTML: el.outerHTML.slice(0, 20000), from: { parent: selectorFor(parent), index: indexIn(parent, el) } }); + edit._el = el; + edit._parent = parent; + edit._index = indexIn(parent, el); + el.remove(); + selected = parent && parent !== document.documentElement ? parent : null; + record(edit); + toast('Removed ' + edit.tag + ' · Cmd/Ctrl+Z to undo'); + } + function setStyle(property, value) { + if (!selected) return; + if (!/^[a-z][a-z0-9-]*$/.test(property)) return; + var cs = getComputedStyle(selected); + var before = cs.getPropertyValue(property); + var last = edits.length ? edits[edits.length - 1] : null; + if (last && last.kind === 'style' && last.property === property && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) { + selected.style.setProperty(property, value === null ? RESET_VALUES[property] : value); + last.after = value; + last.at = new Date().toISOString(); + postEdits(); + postSelection(); + scheduleBoxes(); + return; + } + var edit = newEdit('style', selected, { property: property, before: before, after: value }); + edit._inlineBefore = captureInline(selected, [property]); + edit._el = selected; + if (!applyEdit(edit, selected)) { toast('Cannot change ' + property); return; } + record(edit); + } + function setSize(width, height) { + if (!selected) return; + var last = edits.length ? edits[edits.length - 1] : null; + if (last && last.kind === 'resize' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) { + if (width !== null && width !== undefined) last.width = Math.round(width); + if (height !== null && height !== undefined) last.height = Math.round(height); + var next = sizeStyles(selected, last.width, last.height); + // A dimension first touched now still needs its original value for undo. + last._inlineBefore = last._inlineBefore || {}; + for (var key in next) if (!Object.prototype.hasOwnProperty.call(last._inlineBefore, key)) last._inlineBefore[key] = selected.style.getPropertyValue(key); + applyInline(selected, next); + last.at = new Date().toISOString(); + postEdits(); + postSelection(); + scheduleBoxes(); + return; + } + var rect = selected.getBoundingClientRect(); + var edit = newEdit('resize', selected, { before: { width: Math.round(rect.width), height: Math.round(rect.height) } }); + if (width !== null && width !== undefined) edit.width = Math.round(width); + if (height !== null && height !== undefined) edit.height = Math.round(height); + if (edit.width === undefined && edit.height === undefined) return; + edit._el = selected; + applyEdit(edit, selected); + record(edit); + }`; +} + +module.exports = { editorGesturesJs }; diff --git a/scripts/lib/ui-canvas/editor.js b/scripts/lib/ui-canvas/editor.js index b9c67af60..609cac03a 100644 --- a/scripts/lib/ui-canvas/editor.js +++ b/scripts/lib/ui-canvas/editor.js @@ -20,6 +20,8 @@ * design/preview mode split from Onlook (onlook-dev/onlook). */ +const { editorGesturesJs } = require('./editor-gestures'); + function uiEditorJs() { return String.raw`'use strict'; (() => { @@ -197,6 +199,14 @@ function uiEditorJs() { if (px(width) === 0 && px(cs.borderRightWidth) === 0 && px(cs.borderBottomWidth) === 0 && px(cs.borderLeftWidth) === 0) return 'none'; return width + ' ' + cs.borderTopStyle + ' ' + cs.borderTopColor; } + // Corners in shorthand order (top-left, top-right, bottom-right, bottom-left), + // collapsed like the border-radius shorthand when they match. + function radiusSummary(cs) { + var tl = cs.borderTopLeftRadius, tr = cs.borderTopRightRadius, br = cs.borderBottomRightRadius, bl = cs.borderBottomLeftRadius; + if (tl === tr && tr === br && br === bl) return tl; + if (tl === br && tr === bl) return tl + ' ' + tr; + return tl + ' ' + tr + ' ' + br + ' ' + bl; + } function styleReport(el) { var cs = getComputedStyle(el); var isFlexOrGrid = cs.display.indexOf('flex') >= 0 || cs.display.indexOf('grid') >= 0; @@ -205,7 +215,7 @@ function uiEditorJs() { ['background-image', cs.backgroundImage === 'none' ? null : cs.backgroundImage], ['color', cs.color], ['border', borderSummary(cs)], - ['border-radius', sides(cs, 'border', '-radius').replace(/-top-left|-top-right|-bottom-right|-bottom-left/g, '')], + ['border-radius', radiusSummary(cs)], ['box-shadow', cs.boxShadow], ['padding', sides(cs, 'padding', '')], ['margin', sides(cs, 'margin', '')], @@ -465,13 +475,25 @@ function uiEditorJs() { // shell hands back the edit log and we replay it in order. Edits whose // selector no longer resolves stay in the log, flagged stale, so the human // and the agent both see what did not survive. + function copyEdit(source) { + var edit = {}; + for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) edit[key] = source[key]; + return edit; + } function restore(payload) { var incoming = Array.isArray(payload.edits) ? payload.edits : []; + var baked = Array.isArray(payload.baked) ? payload.baked : []; edits = []; redoStack = []; + // Applied but not yet written to the file: re-apply without logging them, + // so the preview keeps showing what the human handed over. + for (var b = 0; b < baked.length; b++) { + applyEdit(copyEdit(baked[b]), null); + var bakedSeq = parseInt(String(baked[b].id).slice(1), 10); + if (bakedSeq > editSeq) editSeq = bakedSeq; + } for (var i = 0; i < incoming.length; i++) { - var edit = {}; - for (var key in incoming[i]) if (Object.prototype.hasOwnProperty.call(incoming[i], key)) edit[key] = incoming[i][key]; + var edit = copyEdit(incoming[i]); delete edit.stale; if (!applyEdit(edit, null)) edit.stale = true; edits.push(edit); @@ -524,259 +546,7 @@ function uiEditorJs() { } function commitTextEdit() { finishTextEdit(false); } - // ---- gestures: resize, move, nudge ----------------------------------------- - function startResize(dir, event) { - if (!selected) return; - var rect = selected.getBoundingClientRect(); - gesture = { kind: 'resize', dir: dir, el: selected, x0: event.clientX, y0: event.clientY, w0: rect.width, h0: rect.height, inlineBefore: captureInline(selected, ['width', 'height', 'flex', 'max-width']), ratio: rect.height ? rect.width / rect.height : 1, moved: false }; - document.documentElement.style.cursor = getComputedStyle(root.querySelector('.handle[data-dir="' + dir + '"]')).cursor; - document.documentElement.setAttribute('data-ecc-ui-canvas-noselect', ''); - } - function doResize(event) { - var g = gesture; - var dx = event.clientX - g.x0, dy = event.clientY - g.y0; - var width = g.w0, height = g.h0; - if (g.dir.indexOf('e') >= 0) width = g.w0 + dx; - if (g.dir.indexOf('w') >= 0) width = g.w0 - dx; - if (g.dir.indexOf('s') >= 0) height = g.h0 + dy; - if (g.dir.indexOf('n') >= 0) height = g.h0 - dy; - var corner = g.dir.length === 2; - if (g.el.tagName === 'IMG' && corner && !event.shiftKey) { - if (Math.abs(width - g.w0) >= Math.abs(height - g.h0)) height = width / g.ratio; else width = height * g.ratio; - } - width = Math.max(8, Math.round(width)); - height = Math.max(8, Math.round(height)); - var wantsW = g.dir.indexOf('e') >= 0 || g.dir.indexOf('w') >= 0 || (g.el.tagName === 'IMG' && corner && !event.shiftKey); - var wantsH = g.dir.indexOf('n') >= 0 || g.dir.indexOf('s') >= 0 || (g.el.tagName === 'IMG' && corner && !event.shiftKey); - g.width = wantsW ? width : undefined; - g.height = wantsH ? height : undefined; - applyInline(g.el, sizeStyles(g.el, g.width, g.height)); - g.moved = true; - scheduleBoxes(); - } - function endResize() { - var g = gesture; - document.documentElement.style.cursor = ''; - document.documentElement.removeAttribute('data-ecc-ui-canvas-noselect'); - if (!g.moved) return; - var rect = g.el.getBoundingClientRect(); - var edit = newEdit('resize', g.el, { width: g.width !== undefined ? Math.round(rect.width) : undefined, height: g.height !== undefined ? Math.round(rect.height) : undefined, before: { width: Math.round(g.w0), height: Math.round(g.h0) } }); - if (edit.width === undefined) delete edit.width; - if (edit.height === undefined) delete edit.height; - edit._inlineBefore = g.inlineBefore; - edit._el = g.el; - record(edit); - toast('Resized to ' + Math.round(rect.width) + ' × ' + Math.round(rect.height)); - } - - function axisOf(container) { - var cs = getComputedStyle(container); - if (cs.display.indexOf('flex') >= 0) return cs.flexDirection.indexOf('row') === 0 ? 'x' : 'y'; - if (cs.display.indexOf('grid') >= 0) return 'grid'; - var kids = elementChildren(container); - if (kids.length > 1) { - var inlineish = kids.every(function (k) { var d = getComputedStyle(k).display; return d.indexOf('inline') === 0 || k.tagName === 'IMG' || k.tagName === 'BUTTON' || k.tagName === 'A' || k.tagName === 'SPAN'; }); - if (inlineish) return 'x'; - } - return 'y'; - } - function dropPlan(x, y, dragged) { - var under = document.elementFromPoint(x, y); - if (!under || isOurs(under)) return null; - if (under === document.documentElement) under = document.body; - if (!under || under === dragged || dragged.contains(under)) return null; - var container, index, indicator; - if (under === dragged.parentElement || under.contains(dragged)) { - container = under; - var kids = elementChildren(container).filter(function (k) { return k !== dragged; }); - if (!kids.length) { index = 0; indicator = inner(container.getBoundingClientRect()); } - else { - var axis = axisOf(container); - var best = null, bestDist = Infinity; - for (var i = 0; i < kids.length; i++) { - var r = kids[i].getBoundingClientRect(); - var cx = r.left + r.width / 2, cy = r.top + r.height / 2; - var dist = axis === 'x' ? Math.abs(cx - x) : axis === 'y' ? Math.abs(cy - y) : Math.hypot(cx - x, cy - y); - if (dist < bestDist) { bestDist = dist; best = { el: kids[i], i: i, rect: r }; } - } - var after = axis === 'x' ? x > best.rect.left + best.rect.width / 2 : axis === 'y' ? y > best.rect.top + best.rect.height / 2 : (x > best.rect.left + best.rect.width / 2); - index = best.i + (after ? 1 : 0); - indicator = edge(best.rect, axis === 'grid' ? 'x' : axis, after); - } - } else { - container = under.parentElement; - if (!container) return null; - var axis2 = axisOf(container); - var rect = under.getBoundingClientRect(); - var after2 = axis2 === 'y' ? y > rect.top + rect.height / 2 : x > rect.left + rect.width / 2; - var siblings = elementChildren(container).filter(function (k) { return k !== dragged; }); - index = siblings.indexOf(under) + (after2 ? 1 : 0); - indicator = edge(rect, axis2 === 'grid' ? 'x' : axis2, after2); - } - return { container: container, index: index, indicator: indicator }; - } - function edge(rect, axis, after) { - if (axis === 'y') return { left: rect.left, top: (after ? rect.bottom : rect.top) - 1, width: rect.width, height: 3 }; - return { left: (after ? rect.right : rect.left) - 1, top: rect.top, width: 3, height: rect.height }; - } - function inner(rect) { return { left: rect.left + 4, top: rect.top + 4, width: Math.max(0, rect.width - 8), height: 3 }; } - - function startPress(el, event) { - gesture = { kind: 'press', el: el, x0: event.clientX, y0: event.clientY, nudge: event.altKey, started: false }; - } - function beginDrag(event) { - var g = gesture; - g.started = true; - if (g.nudge) { - g.kind = 'nudge'; - g.inlineBefore = captureInline(g.el, ['position', 'left', 'top']); - g.baseLeft = px(g.el.style.left); - g.baseTop = px(g.el.style.top); - if (getComputedStyle(g.el).position === 'static') g.el.style.position = 'relative'; - post({ type: 'uc:status', text: 'Nudging · release to keep the offset' }); - } else { - g.kind = 'move'; - g.fromParent = g.el.parentElement; - g.fromIndex = indexIn(g.fromParent, g.el); - g.el.style.pointerEvents = 'none'; - selBox.classList.add('dragging'); - post({ type: 'uc:status', text: 'Reordering · drop between siblings or into a container · hold Alt to nudge instead' }); - } - document.documentElement.setAttribute('data-ecc-ui-canvas-noselect', ''); - event.preventDefault(); - } - function doDrag(event) { - var g = gesture; - if (g.kind === 'nudge') { - applyInline(g.el, { left: (g.baseLeft + event.clientX - g.x0) + 'px', top: (g.baseTop + event.clientY - g.y0) + 'px' }); - scheduleBoxes(); - return; - } - var rect = g.el.getBoundingClientRect(); - place(ghostEl, { left: rect.left + (event.clientX - g.x0), top: rect.top + (event.clientY - g.y0), width: rect.width, height: rect.height }); - var plan = dropPlan(event.clientX, event.clientY, g.el); - g.plan = plan; - if (plan && plan.indicator) place(dropEl, plan.indicator); else dropEl.style.display = 'none'; - } - function endDrag() { - var g = gesture; - document.documentElement.removeAttribute('data-ecc-ui-canvas-noselect'); - post({ type: 'uc:status', text: '' }); - if (g.kind === 'nudge') { - var dx = px(g.el.style.left) - g.baseLeft, dy = px(g.el.style.top) - g.baseTop; - if (dx === 0 && dy === 0) { applyInline(g.el, g.inlineBefore); return; } - var edit = newEdit('nudge', g.el, { dx: dx, dy: dy }); - edit._inlineBefore = g.inlineBefore; - edit._el = g.el; - record(edit); - toast('Nudged ' + dx + ', ' + dy + 'px'); - return; - } - g.el.style.pointerEvents = ''; - if (!g.el.getAttribute('style')) g.el.removeAttribute('style'); - selBox.classList.remove('dragging'); - ghostEl.style.display = 'none'; - dropEl.style.display = 'none'; - var plan = g.plan; - if (!plan) return; - var sameSpot = plan.container === g.fromParent && (plan.index === g.fromIndex || plan.index === g.fromIndex + 1); - if (sameSpot) return; - var fromSelector = selectorFor(g.el); - var fromParentSelector = selectorFor(g.fromParent); - insertAt(plan.container, g.el, plan.index); - var moveEdit = newEdit('move', g.el, { from: { parent: fromParentSelector, index: g.fromIndex }, to: { parent: selectorFor(plan.container), index: indexIn(plan.container, g.el) } }); - moveEdit.selector = fromSelector; - moveEdit.selectorAfter = selectorFor(g.el); - moveEdit._fromParent = g.fromParent; - moveEdit._fromIndex = g.fromIndex; - moveEdit._el = g.el; - record(moveEdit); - toast('Moved ' + labelFor(g.el)); - } - - function nudgeBy(dx, dy) { - if (!selected) return; - var last = edits.length ? edits[edits.length - 1] : null; - if (last && last.kind === 'nudge' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 1500) { - applyInline(selected, { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' }); - last.dx += dx; - last.dy += dy; - last.at = new Date().toISOString(); - postEdits(); - scheduleBoxes(); - return; - } - var edit = newEdit('nudge', selected, { dx: dx, dy: dy }); - edit._inlineBefore = captureInline(selected, ['position', 'left', 'top']); - edit._el = selected; - var cs = getComputedStyle(selected); - var next = { left: (px(selected.style.left) + dx) + 'px', top: (px(selected.style.top) + dy) + 'px' }; - if (cs.position === 'static') next.position = 'relative'; - applyInline(selected, next); - record(edit); - } - - function removeSelected() { - if (!selected || selected === document.body) { toast('Select an element to remove'); return; } - var el = selected; - var parent = el.parentElement; - var edit = newEdit('remove', el, { outerHTML: el.outerHTML.slice(0, 20000), from: { parent: selectorFor(parent), index: indexIn(parent, el) } }); - edit._el = el; - edit._parent = parent; - edit._index = indexIn(parent, el); - el.remove(); - selected = parent && parent !== document.documentElement ? parent : null; - record(edit); - toast('Removed ' + edit.tag + ' · Cmd/Ctrl+Z to undo'); - } - function setStyle(property, value) { - if (!selected) return; - if (!/^[a-z][a-z0-9-]*$/.test(property)) return; - var cs = getComputedStyle(selected); - var before = cs.getPropertyValue(property); - var last = edits.length ? edits[edits.length - 1] : null; - if (last && last.kind === 'style' && last.property === property && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) { - selected.style.setProperty(property, value === null ? RESET_VALUES[property] : value); - last.after = value; - last.at = new Date().toISOString(); - postEdits(); - postSelection(); - scheduleBoxes(); - return; - } - var edit = newEdit('style', selected, { property: property, before: before, after: value }); - edit._inlineBefore = captureInline(selected, [property]); - edit._el = selected; - if (!applyEdit(edit, selected)) { toast('Cannot change ' + property); return; } - record(edit); - } - function setSize(width, height) { - if (!selected) return; - var last = edits.length ? edits[edits.length - 1] : null; - if (last && last.kind === 'resize' && last._el === selected && !last.stale && Date.now() - Date.parse(last.at) < 2500) { - if (width !== null && width !== undefined) last.width = Math.round(width); - if (height !== null && height !== undefined) last.height = Math.round(height); - var next = sizeStyles(selected, last.width, last.height); - // A dimension first touched now still needs its original value for undo. - last._inlineBefore = last._inlineBefore || {}; - for (var key in next) if (!Object.prototype.hasOwnProperty.call(last._inlineBefore, key)) last._inlineBefore[key] = selected.style.getPropertyValue(key); - applyInline(selected, next); - last.at = new Date().toISOString(); - postEdits(); - postSelection(); - scheduleBoxes(); - return; - } - var rect = selected.getBoundingClientRect(); - var edit = newEdit('resize', selected, { before: { width: Math.round(rect.width), height: Math.round(rect.height) } }); - if (width !== null && width !== undefined) edit.width = Math.round(width); - if (height !== null && height !== undefined) edit.height = Math.round(height); - if (edit.width === undefined && edit.height === undefined) return; - edit._el = selected; - applyEdit(edit, selected); - record(edit); - } - +${editorGesturesJs()} // ---- export ------------------------------------------------------------------- function exportHtml() { if (editing) commitTextEdit(); @@ -802,7 +572,8 @@ function uiEditorJs() { if (gesture) { if (gesture.kind === 'resize') { doResize(e); return; } if (gesture.kind === 'press') { - if (Math.hypot(e.clientX - gesture.x0, e.clientY - gesture.y0) > 4) beginDrag(e); + // Track the move that starts the drag too, so a fast flick still drops. + if (Math.hypot(e.clientX - gesture.x0, e.clientY - gesture.y0) > 4) { beginDrag(e); doDrag(e); } return; } doDrag(e); @@ -838,9 +609,9 @@ function uiEditorJs() { if (!gesture) return; var g = gesture; gesture = null; - if (g.kind === 'resize') { endResize(); e.preventDefault(); e.stopPropagation(); return; } + if (g.kind === 'resize') { endResize(g); e.preventDefault(); e.stopPropagation(); return; } if (g.kind === 'press') return; - endDrag(); + endDrag(g); e.preventDefault(); e.stopPropagation(); }, true); diff --git a/scripts/lib/ui-canvas/feedback.js b/scripts/lib/ui-canvas/feedback.js index 5f108c849..996901623 100644 --- a/scripts/lib/ui-canvas/feedback.js +++ b/scripts/lib/ui-canvas/feedback.js @@ -15,6 +15,7 @@ * written next to the artifact and only its path travels with the item. */ +const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); @@ -247,16 +248,23 @@ function normalizeUiFeedbackItem(raw, counter) { return item; } -function exportPathsFor(artifactFile) { +// Finish writes the canonical .edited.html and .edits.json. Each +// Apply batch gets its own .apply-.* pair so a later batch never +// rewrites the snapshot an earlier queued item points at. +function exportPathsFor(artifactFile, batch = '') { const dir = path.dirname(artifactFile); const ext = path.extname(artifactFile); - const base = path.basename(artifactFile, ext); + const base = path.basename(artifactFile, ext) + (batch ? `.apply-${batch}` : ''); return { exportPath: path.join(dir, `${base}.edited${ext || '.html'}`), editsPath: path.join(dir, `${base}.edits.json`) }; } +function newBatchId() { + return `${Date.now().toString(36)}-${crypto.randomBytes(2).toString('hex')}`; +} + function writeAtomic(file, data) { const tmp = `${file}.tmp-${process.pid}`; fs.writeFileSync(tmp, data); @@ -273,7 +281,7 @@ function writeExport(artifactFile, { html, edits = [], viewport = null, kind = ' if (bytes > MAX_HTML_BYTES) { throw Object.assign(new Error(`html snapshot exceeds ${MAX_HTML_BYTES} bytes`), { code: 'EUI_HTML_TOO_LARGE' }); } - const { exportPath, editsPath } = exportPathsFor(artifactFile); + const { exportPath, editsPath } = exportPathsFor(artifactFile, kind === 'finish' ? '' : newBatchId()); writeAtomic(exportPath, html); writeAtomic( editsPath, diff --git a/scripts/lib/ui-canvas/inspector.js b/scripts/lib/ui-canvas/inspector.js new file mode 100644 index 000000000..906cc25e4 --- /dev/null +++ b/scripts/lib/ui-canvas/inspector.js @@ -0,0 +1,587 @@ +'use strict'; + +/** + * UI Canvas inspector: the right-rail property editor, as a chunk of the + * shell client script (see uiClientJs in ./ui.js, which inlines it inside + * its closure and provides $, postToFrame, selection, actual and ended). + * + * Grouped slider rows for size, fill, text, spacing, border and effects. + * Every value can be double-clicked and typed; typed input goes through the + * sanitizers in ./fields.js, which are inlined here verbatim so the tested + * code is the code that runs. + */ + +const { FIELD_HELPERS_JS } = require('./fields'); + +function inspectorClientJs() { + return String.raw` // --- inspector ---------------------------------------------------------------------- + // Parse, sanitize and format helpers, shared verbatim with Node tests + // (scripts/lib/ui-canvas/fields.js). + ${FIELD_HELPERS_JS} + + const FIELD_HINT = 'Drag a slider or double-click a value to type one. Enter applies, Esc cancels, arrow keys step (Shift for 10).'; + const LENGTH_UNITS = ['px', 'rem', 'em', '%']; + // step is typed-value precision (so 1.25rem survives); sliderStep is the drag increment. + const NUMERIC = { + 'font-size': { label: 'Size', unit: 'px', units: LENGTH_UNITS, min: 1, max: 999, step: 0.01, slider: [6, 96], sliderStep: 1 }, + 'font-weight': { label: 'Weight', unit: '', units: [''], min: 1, max: 1000, step: 1, slider: [100, 900], sliderStep: 100 }, + 'line-height': { label: 'Line height', unit: '', units: ['', 'px', 'em', 'rem', '%'], min: 0, max: 999, step: 0.01, slider: [0.8, 3], sliderStep: 0.05 }, + 'border-radius': { label: 'Radius', unit: 'px', units: LENGTH_UNITS, min: 0, max: 9999, step: 0.01, slider: [0, 64], sliderStep: 1, box: true }, + 'opacity': { label: 'Opacity', ratio: true, min: 0, max: 1, step: 0.01, slider: [0, 1] }, + 'padding': { label: 'Padding', unit: 'px', units: LENGTH_UNITS, min: 0, max: 9999, step: 0.01, slider: [0, 96], sliderStep: 1, box: true }, + 'margin': { label: 'Margin', unit: 'px', units: LENGTH_UNITS, min: -9999, max: 9999, step: 0.01, slider: [0, 96], sliderStep: 1, box: true, allowAuto: true }, + 'gap': { label: 'Gap', unit: 'px', units: LENGTH_UNITS, min: 0, max: 9999, step: 0.01, slider: [0, 96], sliderStep: 1, box: true, maxParts: 2 } + }; + const ALIGN_ICONS = { + left: '', + center: '', + right: '', + justify: '' + }; + let fields = []; + let renderedKey = ''; + let current = {}; + const openColors = new Set(); + + function el(tag, cls, text) { + const node = document.createElement(tag); + if (cls) node.className = cls; + if (text !== undefined) node.textContent = text; + return node; + } + function styleMap(sel) { + const out = {}; + (sel.styles || []).forEach(s => { out[s.property] = s; }); + return out; + } + function px(value) { const n = parseFloat(value); return Number.isFinite(n) ? n : 0; } + function setStyle(property, value) { postToFrame({ type: 'uc:style', property, value }); } + function isDefaultish(value) { + return value === 'none' || value === 'normal' || value === 'start' || value === '1' || /^(0px ?)+$/.test(value + ' ') || /^0(px)?$/.test(value) || /rgba\(\s*\d+[, ]+\d+[, ]+\d+[, /]+0\)/.test(value); + } + let hintTimer = null; + function fieldHint(text, isError) { + const hint = $('fieldHint'); + hint.textContent = text || FIELD_HINT; + hint.classList.toggle('err', Boolean(isError)); + clearTimeout(hintTimer); + if (text) hintTimer = setTimeout(() => fieldHint(''), 4000); + } + let probe = null; + // Any CSS color the browser accepts (names included), normalized to rgba parts. + function resolveColor(text) { + const direct = parseColor(text); + if (direct) return direct; + const clean = sanitizeCssText(text, 60); + if (!clean.ok || !(window.CSS && CSS.supports('color', clean.css))) return null; + if (!probe) { probe = el('span'); probe.hidden = true; document.body.appendChild(probe); } + probe.style.color = ''; + probe.style.color = clean.css; + return parseColor(getComputedStyle(probe).color); + } + + // Double-click (or Enter on a focused value) swaps the value for a text box. + // commit(text) returns an error to keep the box open, or '' once applied. + function editableValue(span, field, getText, commit) { + span.tabIndex = 0; + span.title = 'Double-click to type a value'; + const begin = () => { + if (ended || field.editing) return; + field.editing = true; + const box = el('input', 'numedit'); + box.type = 'text'; + box.spellcheck = false; + box.autocomplete = 'off'; + box.value = getText(); + span.replaceWith(box); + box.focus(); + box.select(); + let done = false; + const finish = how => { + if (done) return; + if (how) { + const error = commit(box.value); + if (error) { + box.classList.add('invalid'); + box.title = error; + fieldHint(error, true); + if (how === 'enter') return; + } else fieldHint(''); + } + done = true; + field.editing = false; + box.replaceWith(span); + field.update(current); + if (how !== 'blur') span.focus(); + }; + box.addEventListener('keydown', e => { + e.stopPropagation(); + if (e.key === 'Enter') { e.preventDefault(); finish('enter'); } + else if (e.key === 'Escape') { e.preventDefault(); finish(null); } + }); + box.addEventListener('input', () => box.classList.remove('invalid')); + box.addEventListener('blur', () => finish('blur')); + }; + span.addEventListener('dblclick', e => { e.preventDefault(); begin(); }); + span.addEventListener('keydown', e => { + if (e.key === 'Enter') { e.preventDefault(); begin(); } + else if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && field.nudge) { + e.preventDefault(); + field.nudge((e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1)); + } + }); + } + + // One labelled row: slider, value (double-click to type) and a clear button. + // opts.read(styles) -> { value, text, mixed, range: [min, max], set, clear }. + function sliderField(opts) { + const field = { busy: false, editing: false }; + const row = el('div', 'field' + (opts.sub ? ' sub' : '')); + row.setAttribute('data-prop', opts.prop || ''); + const label = el('span', 'flabel', opts.label); + label.title = opts.title || opts.prop || opts.label; + const range = el('input', 'range' + (opts.rangeClass ? ' ' + opts.rangeClass : '')); + range.type = 'range'; + range.step = String(opts.step); + range.setAttribute('aria-label', opts.label); + const num = el('span', 'num'); + const clear = el('button', 'clear', '×'); + clear.type = 'button'; + clear.title = 'Clear ' + (opts.prop || opts.label); + clear.setAttribute('aria-label', clear.title); + row.append(label, range, num, clear); + let state = { value: 0, text: '' }; + const paint = () => { + const min = Number(range.min), max = Number(range.max); + const pct = max > min ? ((Number(range.value) - min) / (max - min)) * 100 : 0; + range.style.setProperty('--pct', pct.toFixed(2) + '%'); + if (opts.paint) opts.paint(range); + }; + field.update = styles => { + if (field.busy || field.editing) return; + state = opts.read(styles); + const lo = Math.min(state.range[0], state.value); + const hi = Math.max(state.range[1], state.value); + range.min = String(lo); + range.max = String(hi); + range.value = String(state.value); + num.textContent = state.text; + num.classList.toggle('mixed', Boolean(state.mixed)); + row.classList.toggle('set', Boolean(state.set)); + clear.classList.toggle('on', Boolean(state.clear)); + range.disabled = ended; + paint(); + }; + range.addEventListener('pointerdown', () => { field.busy = true; }); + const release = () => { if (!field.busy) return; field.busy = false; field.update(current); }; + range.addEventListener('pointerup', release); + range.addEventListener('change', release); + range.addEventListener('blur', release); + range.addEventListener('input', () => { + const value = Number(range.value); + num.textContent = opts.format ? opts.format(value) : formatNumber(value); + num.classList.remove('mixed'); + paint(); + opts.write(value); + }); + field.nudge = delta => { + const step = Number(range.step) || 1; + const next = Number((state.value + delta * step).toFixed(4)); + opts.write(Math.max(opts.floor === undefined ? -Infinity : opts.floor, next)); + }; + editableValue(num, field, () => (opts.editText ? opts.editText(state) : state.text), text => opts.type(text)); + clear.addEventListener('click', () => { if (opts.clear) opts.clear(); }); + field.el = row; + return field; + } + + function numericField(prop) { + const spec = NUMERIC[prop]; + return sliderField({ + label: spec.label, + prop, + step: spec.sliderStep || spec.step, + floor: spec.min, + read: styles => { + const style = styles[prop]; + const raw = String(style.value); + const out = { range: spec.slider, set: Boolean(style.inline), clear: style.resettable && !isDefaultish(raw) }; + if (spec.ratio) return Object.assign(out, { value: px(raw), text: Math.round(px(raw) * 100) + '%' }); + if (prop === 'line-height') { + if (raw === 'normal') return Object.assign(out, { value: 1.2, text: 'normal', mixed: true }); + const size = styles['font-size'] ? px(styles['font-size'].value) : 16; + const ratio = size ? px(raw) / size : 1; + return Object.assign(out, { value: Number(ratio.toFixed(2)), text: formatNumber(ratio) }); + } + if (spec.box) { + const parts = raw.split(/\s+/).filter(p => p && p !== '/'); + const mixed = parts.some(p => p !== parts[0]); + return Object.assign(out, { value: px(parts[0]), text: mixed ? parts.map(p => (/px$/.test(p) ? formatNumber(px(p)) : p)).join(' ') : formatNumber(px(parts[0])), mixed }); + } + return Object.assign(out, { value: px(raw), text: formatNumber(px(raw)) }); + }, + format: value => (spec.ratio ? Math.round(value * 100) + '%' : formatNumber(value)), + write: value => { + if (spec.ratio || prop === 'line-height') setStyle(prop, formatNumber(value)); + else if (prop === 'font-weight') setStyle(prop, String(Math.round(value))); + else setStyle(prop, formatNumber(value) + 'px'); + }, + type: text => { + const word = String(text).trim().toLowerCase(); + if (prop === 'line-height' && word === 'normal') { setStyle(prop, 'normal'); return ''; } + if (prop === 'font-weight' && (word === 'bold' || word === 'normal')) { setStyle(prop, word === 'bold' ? '700' : '400'); return ''; } + const result = spec.box ? sanitizeBoxList(text, spec) : sanitizeNumber(text, spec); + if (!result.ok) return result.error; + setStyle(prop, result.css); + return ''; + }, + clear: () => setStyle(prop, null) + }); + } + + function sizeField(label, dim) { + const spec = { unit: 'px', units: ['px'], min: 1, max: 20000, step: 1 }; + const send = value => postToFrame({ type: 'uc:size', width: dim === 'width' ? value : null, height: dim === 'height' ? value : null }); + return sliderField({ + label, + prop: dim, + title: dim + ' in CSS pixels', + step: 1, + floor: 1, + read: () => { + const value = selection.size[dim]; + const room = dim === 'width' ? actual.width : actual.height; + return { value, text: String(value), range: [1, Math.max(room, Math.round(value * 1.5))] }; + }, + write: value => send(Math.max(1, Math.round(value))), + type: text => { + const result = sanitizeNumber(text, spec); + if (!result.ok) return result.error; + send(result.value); + return ''; + } + }); + } + + // Swatch + hex + alpha row; the swatch opens hue, saturation, lightness and + // alpha sliders underneath. The exact color is kept beside its HSL view so + // typed or incoming values never drift, and hue survives grays. + function colorField(label, prop, getColor, setColor, clearable) { + const wrap = el('div', 'cfield'); + const field = { editing: false }; + const row = el('div', 'field'); + row.setAttribute('data-prop', prop); + const flabel = el('span', 'flabel', label); + flabel.title = prop; + const cval = el('div', 'cval'); + const swatch = el('button', 'swatch-btn'); + swatch.type = 'button'; + swatch.title = 'Adjust ' + label.toLowerCase() + ' with sliders'; + swatch.setAttribute('aria-label', swatch.title); + const fill = el('i'); + swatch.appendChild(fill); + const hex = el('span', 'num'); + cval.append(swatch, hex); + const alpha = el('span', 'num'); + const clear = el('button', 'clear', '×'); + clear.type = 'button'; + clear.title = 'Clear ' + prop; + clear.setAttribute('aria-label', clear.title); + row.append(flabel, cval, alpha, clear); + const sub = el('div', 'csub'); + wrap.append(row, sub); + let hsl = { h: 0, s: 0, l: 0, a: 0 }; + let exact = { r: 0, g: 0, b: 0, a: 0 }; + let lastCss = ''; + const adopt = color => { + const next = rgbToHsl(color); + if (next.s === 0 && lastCss) next.h = hsl.h; + hsl = next; + exact = { r: color.r, g: color.g, b: color.b, a: color.a }; + }; + const hexField = { editing: false, update: () => field.update(current) }; + const alphaField = { editing: false, update: () => field.update(current) }; + const apply = fromSliders => { + if (fromSliders) exact = hslToRgb(hsl); + else exact.a = hsl.a; + const css = formatColor(exact); + lastCss = css; + paint(); + setColor(css); + }; + const channel = (name, max, rangeClass, key, unit) => sliderField({ + label: name, + sub: true, + step: 1, + floor: 0, + rangeClass, + read: () => ({ value: key === 'a' ? Math.round(hsl.a * 100) : hsl[key], text: (key === 'a' ? Math.round(hsl.a * 100) : hsl[key]) + unit, range: [0, max] }), + format: value => value + unit, + write: value => { + const next = Math.max(0, Math.min(max, Math.round(value))); + if (key === 'a') hsl.a = next / 100; + else { hsl[key] = next; if (hsl.a === 0) hsl.a = 1; } + apply(key !== 'a'); + }, + type: text => { + const result = sanitizeNumber(text, { unit: unit === '%' ? '%' : '', units: unit === '%' ? ['%', ''] : ['', 'deg'], min: 0, max, step: 1 }); + if (!result.ok) return result.error; + if (key === 'a') hsl.a = result.value / 100; + else { hsl[key] = result.value; if (hsl.a === 0) hsl.a = 1; } + apply(key !== 'a'); + return ''; + }, + paint: range => { + const h = hsl.h, s = hsl.s, l = hsl.l; + if (key === 's') range.style.setProperty('--track', 'linear-gradient(to right,hsl(' + h + ',0%,' + l + '%),hsl(' + h + ',100%,' + l + '%))'); + if (key === 'l') range.style.setProperty('--track', 'linear-gradient(to right,#000,hsl(' + h + ',' + s + '%,50%),#fff)'); + if (key === 'a') range.style.setProperty('--swatch', formatColor(hslToRgb({ h, s, l, a: 1 }))); + } + }); + const channels = [channel('H', 360, 'paint hue', 'h', '°'), channel('S', 100, 'paint', 's', '%'), channel('L', 100, 'paint', 'l', '%'), channel('A', 100, 'paint alpha', 'a', '%')]; + channels.forEach(c => sub.appendChild(c.el)); + const busy = () => field.editing || hexField.editing || alphaField.editing || channels.some(c => c.busy || c.editing); + function paint() { + fill.style.background = formatColor(exact); + hex.textContent = hsl.a === 0 ? 'none' : colorHex(exact); + hex.classList.toggle('mixed', hsl.a === 0); + alpha.textContent = Math.round(hsl.a * 100) + '%'; + channels.forEach(c => { if (!c.busy && !c.editing) c.update(current); }); + } + const setOpen = open => { + if (open) openColors.add(prop); else openColors.delete(prop); + sub.hidden = !open; + swatch.setAttribute('aria-expanded', String(open)); + }; + swatch.addEventListener('click', () => setOpen(sub.hidden)); + setOpen(openColors.has(prop)); + field.update = styles => { + const style = styles[prop] || {}; + row.classList.toggle('set', Boolean(style.inline)); + clear.classList.toggle('on', Boolean(clearable && style.resettable && !isDefaultish(String(style.value)))); + if (busy()) return; + const color = getColor(styles) || { r: 0, g: 0, b: 0, a: 0 }; + const css = formatColor(color); + if (css !== lastCss) { + adopt(color); + lastCss = css; + } + paint(); + }; + editableValue(hex, hexField, () => (hsl.a === 0 ? '' : colorHex(exact)), text => { + const color = resolveColor(text); + if (!color) return 'Use a hex like #16A34A, rgb(), or a color name'; + adopt(color); + apply(); + return ''; + }); + editableValue(alpha, alphaField, () => String(Math.round(hsl.a * 100)), text => { + const result = sanitizeNumber(text, { ratio: true, min: 0, max: 1, step: 0.01 }); + if (!result.ok) return result.error; + hsl.a = result.value; + apply(); + return ''; + }); + alphaField.nudge = delta => { hsl.a = Math.max(0, Math.min(1, Number((hsl.a + delta / 100).toFixed(2)))); apply(); }; + clear.addEventListener('click', () => setStyle(prop, null)); + field.el = wrap; + return field; + } + + function borderParts(styles) { + const value = styles.border ? String(styles.border.value) : 'none'; + const match = value.match(/^([\d.]+)px\s+(\S+)\s+(.+)$/); + if (!match) return { width: 0, style: 'solid', color: null }; + return { width: Number(match[1]), style: match[2] === 'none' ? 'solid' : match[2], color: parseColor(match[3]) }; + } + function borderCss(width, style, color) { + return width <= 0 ? 'none' : formatNumber(width) + 'px ' + style + ' ' + color; + } + function borderWidthField() { + const spec = { unit: 'px', units: ['px'], min: 0, max: 64, step: 0.5 }; + const write = width => { + const parts = borderParts(current); + const color = parts.color ? formatColor(parts.color) : (current.color ? current.color.value : '#000000'); + setStyle('border', borderCss(width, parts.style, color)); + }; + return sliderField({ + label: 'Width', + prop: 'border', + title: 'border width', + step: 1, + floor: 0, + read: styles => { + const parts = borderParts(styles); + return { value: parts.width, text: formatNumber(parts.width), range: [0, 16], set: Boolean(styles.border && styles.border.inline), clear: parts.width > 0 }; + }, + write, + type: text => { + const result = sanitizeNumber(text, spec); + if (!result.ok) return result.error; + write(result.value); + return ''; + }, + clear: () => setStyle('border', null) + }); + } + + function alignField() { + const field = { editing: false }; + const row = el('div', 'field'); + row.setAttribute('data-prop', 'text-align'); + const label = el('span', 'flabel', 'Align'); + label.title = 'text-align'; + const group = el('div', 'aligns'); + group.style.gridColumn = 'span 2'; + group.setAttribute('role', 'group'); + group.setAttribute('aria-label', 'Text align'); + const buttons = Object.keys(ALIGN_ICONS).map(name => { + const b = el('button'); + b.type = 'button'; + b.innerHTML = ALIGN_ICONS[name]; + b.title = 'Align ' + name; + b.setAttribute('aria-label', b.title); + b.addEventListener('click', () => setStyle('text-align', name)); + group.appendChild(b); + return { name, b }; + }); + const spacer = el('span'); + row.append(label, group, spacer); + field.update = styles => { + const raw = styles['text-align'] ? String(styles['text-align'].value) : 'start'; + const value = raw === 'start' ? 'left' : raw === 'end' ? 'right' : raw; + row.classList.toggle('set', Boolean(styles['text-align'] && styles['text-align'].inline)); + buttons.forEach(({ name, b }) => b.setAttribute('aria-pressed', String(name === value))); + }; + field.el = row; + return field; + } + + // Free CSS such as box-shadow: shown truncated, typed in full. + function textField(label, prop) { + const field = { editing: false }; + const row = el('div', 'field text'); + row.setAttribute('data-prop', prop); + const flabel = el('span', 'flabel', label); + flabel.title = prop; + const num = el('span', 'num'); + const clear = el('button', 'clear', '×'); + clear.type = 'button'; + clear.title = 'Clear ' + prop; + clear.setAttribute('aria-label', clear.title); + row.append(flabel, num, clear); + let text = ''; + field.update = styles => { + if (field.editing) return; + const style = styles[prop] || { value: 'none' }; + text = String(style.value); + num.textContent = shortValue(text); + num.classList.toggle('mixed', text === 'none'); + row.classList.toggle('set', Boolean(style.inline)); + clear.classList.toggle('on', Boolean(style.resettable && text !== 'none')); + num.title = text + '\nDouble-click to type a value'; + }; + editableValue(num, field, () => text, typed => { + const result = sanitizeCssText(typed, 300); + if (!result.ok) return result.error; + if (window.CSS && !CSS.supports(prop, result.css)) return 'Not a valid ' + prop + ' value'; + setStyle(prop, result.css); + return ''; + }); + clear.addEventListener('click', () => setStyle(prop, null)); + field.el = row; + return field; + } + + function readOnlyField(label, prop) { + const row = el('div', 'field text'); + const flabel = el('span', 'flabel', label); + flabel.title = prop + ' (read-only here; ask the agent to change layout)'; + const value = el('span', 'ro'); + row.append(flabel, value, el('span')); + return { el: row, update: styles => { value.textContent = styles[prop] ? String(styles[prop].value) : ''; } }; + } + + function colorOf(prop) { + return styles => (styles[prop] ? parseColor(styles[prop].value) : null); + } + function buildGroups(styles) { + const has = prop => Boolean(styles[prop]); + const plan = [ + ['Size', [sizeField('Width', 'width'), sizeField('Height', 'height')]], + ['Fill', [ + has('background-color') && colorField('Background', 'background-color', colorOf('background-color'), css => setStyle('background-color', css), true), + has('background-image') && textField('Image', 'background-image') + ]], + ['Text', [ + has('color') && colorField('Color', 'color', colorOf('color'), css => setStyle('color', css), true), + has('font-size') && numericField('font-size'), + has('font-weight') && numericField('font-weight'), + has('line-height') && numericField('line-height'), + has('text-align') && alignField() + ]], + ['Spacing', [has('padding') && numericField('padding'), has('margin') && numericField('margin'), has('gap') && numericField('gap')]], + ['Border', [ + has('border') && borderWidthField(), + has('border') && colorField('Color', 'border', s => borderParts(s).color, css => { + const parts = borderParts(current); + setStyle('border', borderCss(parts.width || 1, parts.style, css)); + }, false), + has('border-radius') && numericField('border-radius') + ]], + ['Effects', [has('opacity') && numericField('opacity'), has('box-shadow') && textField('Shadow', 'box-shadow'), has('display') && readOnlyField('Display', 'display')]] + ]; + const container = $('groups'); + container.innerHTML = ''; + fields = []; + for (const [title, list] of plan) { + const items = list.filter(Boolean); + if (!items.length) continue; + const group = el('div', 'group'); + group.appendChild(el('div', 'gh', title)); + items.forEach(f => { group.appendChild(f.el); fields.push(f); }); + container.appendChild(group); + } + fields.forEach(f => f.update(styles)); + } + + function shortValue(value) { + return String(value).replace(/rgba?\([^)]*\)/g, m => { const c = parseColor(m); return c ? (c.a < 1 ? formatColor(c) : colorHex(c)) : m; }).replace(/(\d+\.\d{2})\d+/g, '$1'); + } + function renderInspector() { + const has = Boolean(selection); + $('noSel').hidden = has; + $('selBody').hidden = !has; + $('deselectBtn').hidden = !has; + if (!has) { renderedKey = ''; fields = []; current = {}; return; } + current = styleMap(selection); + const crumbs = $('crumbs'); + crumbs.innerHTML = ''; + (selection.breadcrumb || []).forEach((crumb, i, arr) => { + const b = document.createElement('button'); + b.type = 'button'; + b.textContent = crumb.label; + b.title = crumb.selector; + if (i === arr.length - 1) b.setAttribute('aria-current', 'true'); + b.addEventListener('click', () => postToFrame({ type: 'uc:select', selector: crumb.selector })); + crumbs.appendChild(b); + if (i < arr.length - 1) { const sep = document.createElement('span'); sep.className = 'sep'; sep.textContent = '›'; crumbs.appendChild(sep); } + }); + $('selTag').textContent = '<' + selection.tag + '>' + (selection.id ? '#' + selection.id : '') + (selection.classes && selection.classes.length ? '.' + selection.classes.join('.') : ''); + $('selTag').title = selection.selector; + $('selSnippet').textContent = selection.snippet || ''; + $('selSnippet').title = selection.snippet || ''; + $('editTextBtn').disabled = ended || !selection.editable; + $('removeBtn').disabled = ended; + const key = selection.selector + '|' + Object.keys(current).join(','); + if (key === renderedKey) { fields.forEach(f => f.update(current)); return; } + renderedKey = key; + buildGroups(current); + } + $('editTextBtn').addEventListener('click', () => postToFrame({ type: 'uc:edit-text' })); + $('removeBtn').addEventListener('click', () => postToFrame({ type: 'uc:remove' })); + $('deselectBtn').addEventListener('click', () => postToFrame({ type: 'uc:deselect' })); + fieldHint('');`; +} + +module.exports = { inspectorClientJs }; diff --git a/scripts/lib/ui-canvas/server-routes.js b/scripts/lib/ui-canvas/server-routes.js new file mode 100644 index 000000000..5f15c6ab6 --- /dev/null +++ b/scripts/lib/ui-canvas/server-routes.js @@ -0,0 +1,55 @@ +'use strict'; + +/** + * UI Canvas pieces of the shared Plan Canvas server: the browser assets it + * serves and the export step that turns an edit batch's DOM snapshot into + * files beside the artifact. Kept here so the shared server only branches on + * session mode. + */ + +const { uiEditorJs } = require('./editor'); +const { renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('./ui'); +const { normalizeEdits, writeExport } = require('./feedback'); + +const UI_ASSETS = { + '/ui-canvas.css': { type: 'text/css; charset=utf-8', body: uiCanvasCss }, + '/ui-client.js': { type: 'text/javascript; charset=utf-8', body: uiClientJs }, + '/ui-editor.js': { type: 'text/javascript; charset=utf-8', body: uiEditorJs } +}; + +// Serve a UI Canvas asset when pathname names one; returns true when handled. +function serveUiAsset(pathname, res) { + const asset = Object.prototype.hasOwnProperty.call(UI_ASSETS, pathname) ? UI_ASSETS[pathname] : null; + if (!asset) return false; + res.writeHead(200, { 'content-type': asset.type, 'cache-control': 'no-store' }); + res.end(asset.body()); + return true; +} + +// UI Canvas edit batches arrive with the full DOM snapshot. Write it (and the +// edit log) next to the artifact before the item is queued, and hand the agent +// paths instead of megabytes of markup. Chat items pass through untouched. +function materializeUiExports(session, items) { + return items.map(item => { + if (!item || typeof item !== 'object' || (item.kind !== 'edits' && item.kind !== 'finish')) return item; + // The on-disk log holds the same normalized edits the agent receives. + const edits = normalizeEdits(item.edits); + const written = writeExport(session.file, { + html: item.html, + edits, + viewport: item.viewport || null, + kind: item.kind + }); + const { html: _html, ...rest } = item; + return { ...rest, edits, exportPath: written.exportPath, editsPath: written.editsPath }; + }); +} + +// Map an export failure to the HTTP status and message the browser shows. +function exportErrorResponse(error) { + if (error.code === 'EUI_HTML_TOO_LARGE') return { status: 413, error: 'html snapshot too large' }; + if (error.code === 'EUI_HTML_MISSING') return { status: 400, error: 'edits and finish items need an html snapshot' }; + return { status: 500, error: `could not write the export next to the artifact: ${error.message}` }; +} + +module.exports = { UI_ASSETS, exportErrorResponse, materializeUiExports, renderUiCanvasHtml, serveUiAsset }; diff --git a/scripts/lib/ui-canvas/ui-css.js b/scripts/lib/ui-canvas/ui-css.js new file mode 100644 index 000000000..f64d80213 --- /dev/null +++ b/scripts/lib/ui-canvas/ui-css.js @@ -0,0 +1,217 @@ +'use strict'; + +/** + * UI Canvas shell stylesheet: Plan Canvas and dashboard tokens with the ECC + * green accent, the device frames, and the inspector rows. + */ + +const { TOKENS_CSS } = require('../plan-canvas/ui'); + +function uiCanvasCss() { + return `${TOKENS_CSS} + :root{--accent:#4acb8a;--accent-glow:rgba(74,203,138,0.15);--accent-dim:#2f9e68;--on-accent:#06130c} + [data-theme="light"]{--accent:#15803d;--accent-glow:rgba(21,128,61,0.1);--accent-dim:#166534;--on-accent:#ffffff} + *{margin:0;padding:0;box-sizing:border-box} + html,body{height:100%} + body{font-family:var(--font);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;line-height:1.4;overflow:hidden} + ::selection{background:var(--accent);color:var(--on-accent)} + ::-webkit-scrollbar{width:8px;height:8px} + ::-webkit-scrollbar-track{background:transparent} + ::-webkit-scrollbar-thumb{background:var(--border);border-radius:4px} + button,input,textarea{font-family:var(--font)} + button{cursor:pointer} + button:disabled{opacity:.45;cursor:default} + code,.mono{font-family:var(--mono)} + [hidden]{display:none!important} + + .bar{display:flex;align-items:center;gap:10px;height:54px;padding:0 14px;background:color-mix(in srgb,var(--bg2) 90%,transparent);border-bottom:1px solid var(--border);backdrop-filter:blur(16px)} + .brand{display:flex;align-items:center;gap:9px;min-width:0;margin-right:6px} + .brand .logo{width:26px;height:26px;flex:none;background:var(--bg3);border:1px solid var(--border-light);border-radius:7px;display:flex;align-items:center;justify-content:center;font-family:var(--mono);font-size:13px;font-weight:700;color:var(--accent)} + .brand .name{font-size:13.5px;font-weight:600;white-space:nowrap} + .brand .file{font-size:11.5px;color:var(--text2);font-family:var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:22vw} + .bar .spacer{flex:1} + .divider{width:1px;height:22px;background:var(--border)} + + .seg{display:inline-flex;align-items:center;background:var(--bg3);border:1px solid var(--border);border-radius:8px;padding:2px;gap:2px} + .seg button{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 10px;border:0;border-radius:6px;background:transparent;color:var(--text2);font-size:11.5px;font-weight:600;transition:all .12s} + .seg button:hover{color:var(--text);background:var(--bg4)} + .seg button[aria-pressed="true"]{background:var(--surface);color:var(--text);box-shadow:var(--shadow);outline:1px solid var(--border-light)} + .seg.viewports button{padding:0 9px} + .seg.viewports svg{display:block} + + .dims{display:flex;align-items:center;gap:5px;font-size:11.5px;color:var(--text2)} + .dims input{width:58px;height:26px;border:1px solid var(--border);border-radius:6px;background:var(--bg3);color:var(--text);font-family:var(--mono);font-size:11.5px;text-align:center;outline:none;-moz-appearance:textfield} + .dims input::-webkit-outer-spin-button,.dims input::-webkit-inner-spin-button{-webkit-appearance:none} + .dims input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-glow)} + .dims .x{color:var(--text3)} + .dims .scale{font-family:var(--mono);font-size:10.5px;color:var(--teal);min-width:34px} + .dims .icon-btn{height:26px;width:26px;padding:0;justify-content:center} + + .presence{display:flex;align-items:center;gap:6px;font-size:11px;font-weight:500;color:var(--text2);background:var(--bg3);border:1px solid var(--border);border-radius:99px;padding:3px 10px 3px 8px;white-space:nowrap;max-width:260px} + .presence .label{overflow:hidden;text-overflow:ellipsis} + .presence .dot{width:7px;height:7px;flex:none;border-radius:99px;background:var(--text3)} + .presence[data-state="listening"] .dot{background:var(--green);box-shadow:0 0 0 3px var(--green-glow);animation:pulse 2s infinite} + .presence[data-state="thinking"] .dot,.presence[data-state="typing"] .dot{background:var(--teal);box-shadow:0 0 0 3px var(--teal-glow);animation:pulse 1.2s infinite} + .presence[data-state="queued"] .dot{background:var(--orange);box-shadow:0 0 0 3px var(--orange-glow)} + .presence[data-state="ended"] .dot{background:var(--text3)} + @keyframes pulse{0%,100%{opacity:1}50%{opacity:.45}} + + .icon-btn{height:28px;padding:0 10px;border-radius:6px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-size:11.5px;font-weight:500;display:inline-flex;align-items:center;gap:5px;transition:all .12s;white-space:nowrap} + .icon-btn:hover:not(:disabled){border-color:var(--border-light);color:var(--text);background:var(--bg4)} + .icon-btn.danger:hover:not(:disabled){border-color:var(--red);color:var(--red);background:var(--red-glow)} + .icon-btn[aria-pressed="true"]{border-color:var(--accent);color:var(--accent);background:var(--accent-glow)} + .icon-btn.confirm{border-color:var(--orange);color:var(--orange);background:var(--orange-glow)} + .icon-btn.square{width:28px;padding:0;justify-content:center} + .primary{height:30px;padding:0 14px;border:1px solid var(--accent-dim);border-radius:7px;background:var(--accent);color:var(--on-accent);font-size:12px;font-weight:600;display:inline-flex;align-items:center;gap:7px;box-shadow:var(--shadow);transition:background .12s,transform .12s} + .primary:hover:not(:disabled){background:color-mix(in srgb,var(--accent) 86%,#fff)} + .primary:active:not(:disabled){transform:translateY(1px)} + + .layout{display:flex;height:calc(100% - 54px)} + .stage{flex:1;min-width:0;position:relative;display:flex;flex-direction:column;background:var(--bg);background-image:radial-gradient(color-mix(in srgb,var(--border-light) 70%,transparent) 1px,transparent 1px);background-size:18px 18px} + .stage .viewport{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;overflow:auto;padding:24px} + .sizer{position:relative;flex:none} + .device{position:absolute;top:0;left:0;transform-origin:top left;background:#fff;border-radius:6px;box-shadow:0 12px 40px rgba(0,0,0,.35),0 0 0 1px color-mix(in srgb,var(--border-light) 80%,transparent);overflow:hidden;transition:border-radius .15s} + .device iframe{display:block;width:100%;height:100%;border:0;background:#fff} + .device.mobile{border-radius:44px;border:12px solid #0b0c10;box-shadow:0 20px 60px rgba(0,0,0,.5),0 0 0 1px #2a2d38,inset 0 0 0 1px #000} + .device.mobile iframe{border-radius:32px} + .device.desktop{border-radius:8px} + .stage[data-mode="interact"] .device{outline:2px solid color-mix(in srgb,var(--green) 55%,transparent);outline-offset:3px} + + .statusbar{height:30px;flex:none;display:flex;align-items:center;gap:14px;padding:0 14px;border-top:1px solid var(--border);background:color-mix(in srgb,var(--bg2) 85%,transparent);font-size:11px;color:var(--text2);white-space:nowrap;overflow:hidden} + .statusbar .hint{flex:1;overflow:hidden;text-overflow:ellipsis} + .statusbar .hint.live{color:var(--accent)} + .statusbar kbd{font-family:var(--mono);font-size:10px;background:var(--bg3);border:1px solid var(--border);border-bottom-width:2px;border-radius:4px;padding:0 5px;color:var(--text)} + .statusbar .readout{font-family:var(--mono);font-size:10.5px;color:var(--text3)} + + .panel{width:372px;flex:none;display:flex;flex-direction:column;border-left:1px solid var(--border);background:var(--bg2);min-height:0} + .panel section{display:flex;flex-direction:column;min-height:0} + .panel h2{display:flex;align-items:center;gap:8px;font-size:11px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--text3);padding:12px 14px 8px} + .panel h2 .count{font-family:var(--mono);font-size:10px;color:var(--text2);background:var(--bg3);border:1px solid var(--border);border-radius:99px;padding:1px 7px;letter-spacing:0;text-transform:none} + .panel h2 .grow{flex:1} + .mini{height:22px;padding:0 8px;border-radius:5px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-size:10.5px;font-weight:600;letter-spacing:0;text-transform:none;display:inline-flex;align-items:center;gap:4px} + .mini:hover:not(:disabled){color:var(--text);border-color:var(--border-light)} + .mini.danger:hover:not(:disabled){color:var(--red);border-color:var(--red);background:var(--red-glow)} + .mini.go:not(:disabled){color:var(--accent);border-color:color-mix(in srgb,var(--accent) 55%,transparent);background:var(--accent-glow)} + .mini.go:hover:not(:disabled){color:var(--on-accent);background:var(--accent);border-color:var(--accent)} + .mini.confirm{color:var(--orange);border-color:var(--orange);background:var(--orange-glow)} + + .panel .inspector{flex:0 1 auto;min-height:140px;border-bottom:1px solid var(--border);max-height:56%;overflow-y:auto} + .inspector .muted{padding:0 14px 14px;font-size:12px;color:var(--text3);line-height:1.55} + .crumbs{display:flex;flex-wrap:wrap;gap:3px;padding:0 14px 8px} + .crumbs button{height:20px;padding:0 7px;border-radius:4px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-family:var(--mono);font-size:10px} + .crumbs button:hover{color:var(--text);border-color:var(--border-light)} + .crumbs button[aria-current="true"]{color:var(--accent);border-color:var(--accent);background:var(--accent-glow)} + .crumbs .sep{color:var(--text3);font-size:10px;align-self:center} + .selhead{display:flex;align-items:center;gap:8px;padding:0 14px 10px;min-width:0} + .selhead .tag{font-family:var(--mono);font-size:12px;color:var(--accent);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;flex:0 1 auto} + .selhead .snippet{font-size:11.5px;color:var(--text2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1} + .selhead .mini{flex:none} + .inspector .hint{padding:2px 14px 12px;font-size:10px;color:var(--text3);line-height:1.5} + .inspector .hint.err{color:var(--red)} + + .groups{display:flex;flex-direction:column;padding:0 0 4px} + .group{padding:6px 14px 8px;border-top:1px solid var(--border)} + .group .gh{font-size:9.5px;font-weight:600;letter-spacing:.07em;text-transform:uppercase;color:var(--text3);padding:2px 0 6px} + .field{display:grid;grid-template-columns:78px minmax(0,1fr) 56px 18px;align-items:center;gap:8px;min-height:26px} + .field .flabel{font-size:11px;color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .field.set .flabel{color:var(--text)} + .field.set .flabel::after{content:'';display:inline-block;width:5px;height:5px;margin:0 0 1px 5px;border-radius:99px;background:var(--accent);vertical-align:middle} + .field.sub .flabel{padding-left:10px;color:var(--text3);font-family:var(--mono);font-size:10px} + .field .ro{font-family:var(--mono);font-size:10.5px;color:var(--text2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} + .field .clear{width:18px;height:18px;padding:0;border:0;border-radius:4px;background:none;color:var(--text3);font-size:13px;line-height:1;visibility:hidden} + .field:hover .clear.on,.field .clear.on:focus-visible{visibility:visible} + .field .clear:hover{color:var(--red);background:var(--red-glow)} + .csub{display:flex;flex-direction:column;gap:1px;margin:2px 0 6px 4px;padding:2px 0 2px 0;border-left:2px solid var(--border-light)} + .cval{display:flex;align-items:center;gap:6px;min-width:0} + .cval .num{flex:1;justify-content:flex-start} + .num{height:22px;min-width:0;display:flex;align-items:center;justify-content:flex-end;padding:0 6px;border:1px solid transparent;border-radius:5px;font-family:var(--mono);font-size:10.5px;color:var(--text);cursor:text;user-select:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .num:hover,.num:focus-visible{border-color:var(--border);background:var(--bg3);outline:none} + .num.mixed{color:var(--text2);font-style:italic} + .numedit{height:22px;width:100%;min-width:0;border:1px solid var(--accent);border-radius:5px;background:var(--bg);color:var(--text);font-family:var(--mono);font-size:10.5px;text-align:right;padding:0 6px;outline:none;box-shadow:0 0 0 3px var(--accent-glow)} + .cval .numedit,.field.text .numedit{text-align:left} + .field.text{grid-template-columns:78px minmax(0,1fr) 18px} + .field.text .num{justify-content:flex-start} + .numedit.invalid{border-color:var(--red);box-shadow:0 0 0 3px var(--red-glow)} + .swatch-btn{position:relative;width:22px;height:22px;flex:none;padding:0;border-radius:5px;border:1px solid var(--border-light);overflow:hidden;background-color:#fff;background-image:repeating-conic-gradient(#c9ccd3 0 25%,#fff 0 50%);background-size:8px 8px} + .swatch-btn i{position:absolute;inset:0;display:block} + .swatch-btn:hover{border-color:var(--text2)} + .swatch-btn[aria-expanded="true"]{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-glow)} + .range{-webkit-appearance:none;appearance:none;width:100%;height:18px;margin:0;background:transparent;cursor:pointer;--pct:0%;--fill:var(--accent);--track:linear-gradient(to right,var(--fill) var(--pct),var(--bg4) var(--pct))} + .range:focus{outline:none} + .range::-webkit-slider-runnable-track{height:4px;border-radius:99px;background:var(--track);box-shadow:inset 0 0 0 1px var(--border)} + .range::-moz-range-track{height:4px;border-radius:99px;background:var(--track);box-shadow:inset 0 0 0 1px var(--border)} + .range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:12px;height:12px;margin-top:-4px;border-radius:99px;background:var(--text);border:2px solid var(--bg2);box-shadow:0 0 0 1px var(--border-light),0 1px 3px rgba(0,0,0,.4)} + .range::-moz-range-thumb{width:8px;height:8px;border-radius:99px;background:var(--text);border:2px solid var(--bg2);box-shadow:0 0 0 1px var(--border-light)} + .range:hover::-webkit-slider-thumb{box-shadow:0 0 0 1px var(--accent),0 1px 3px rgba(0,0,0,.4)} + .range:focus-visible::-webkit-slider-thumb{box-shadow:0 0 0 1px var(--accent),0 0 0 4px var(--accent-glow)} + .range:focus-visible::-moz-range-thumb{box-shadow:0 0 0 1px var(--accent),0 0 0 4px var(--accent-glow)} + .range.paint::-webkit-slider-runnable-track{height:8px} + .range.paint::-moz-range-track{height:8px} + .range.paint::-webkit-slider-thumb{margin-top:-2px} + .range.hue{--track:linear-gradient(to right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)} + .range.alpha{--track:linear-gradient(to right,transparent,var(--swatch)),repeating-conic-gradient(#c9ccd3 0 25%,#fff 0 50%) 0 0/8px 8px} + .aligns{display:inline-flex;gap:2px;background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:2px;justify-self:start} + .aligns button{width:24px;height:20px;padding:0;border:0;border-radius:4px;background:transparent;color:var(--text2);display:inline-flex;align-items:center;justify-content:center} + .aligns button:hover{color:var(--text);background:var(--bg4)} + .aligns button[aria-pressed="true"]{color:var(--accent);background:var(--accent-glow)} + + #themeBtn .i-moon,[data-theme="light"] #themeBtn .i-sun{display:none} + [data-theme="light"] #themeBtn .i-moon{display:block} + #pauseBtn .i-play,#pauseBtn[aria-pressed="true"] .i-pause{display:none} + #pauseBtn[aria-pressed="true"] .i-play{display:block} + + .panel .edits{flex:0 1 auto;min-height:96px;border-bottom:1px solid var(--border);max-height:22%;display:flex;flex-direction:column} + .editlist{overflow-y:auto;padding:0 14px 10px;display:flex;flex-direction:column;gap:5px} + .editlist .empty{font-size:11.5px;color:var(--text3);line-height:1.5} + .edit{display:flex;align-items:flex-start;gap:8px;padding:6px 8px;border-radius:6px;background:var(--bg3);border:1px solid var(--border);border-left:2px solid var(--teal);font-size:11px;line-height:1.45;color:var(--text2)} + .edit .k{flex:none;font-family:var(--mono);font-size:9.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--teal);padding-top:2px;width:46px} + .edit .s{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical} + .edit.kind-remove{border-left-color:var(--red)}.edit.kind-remove .k{color:var(--red)} + .edit.kind-text{border-left-color:var(--accent)}.edit.kind-text .k{color:var(--accent)} + .edit.kind-style{border-left-color:var(--pink)}.edit.kind-style .k{color:var(--pink)} + .edit.kind-move,.edit.kind-nudge{border-left-color:var(--orange)}.edit.kind-move .k,.edit.kind-nudge .k{color:var(--orange)} + .edit.stale{opacity:.5;border-style:dashed} + + .panel .convo{flex:1 1 0;min-height:232px} + .chat{flex:1;overflow-y:auto;padding:4px 14px 10px;display:flex;flex-direction:column;gap:8px} + .msg{max-width:92%;padding:7px 10px;border-radius:10px;font-size:12.5px;white-space:pre-wrap;word-break:break-word} + .msg.user{align-self:flex-end;background:var(--accent-glow);border:1px solid color-mix(in srgb,var(--accent) 35%,transparent);color:var(--text);border-bottom-right-radius:3px} + .msg.agent{align-self:flex-start;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-bottom-left-radius:3px} + .msg .meta{display:block;font-size:9.5px;color:var(--text3);margin-top:3px} + .msg.kind-edits,.msg.kind-finish{border-left:2px solid var(--green)} + .chat .empty{color:var(--text3);font-size:12px;text-align:center;margin-top:18px;line-height:1.6;padding:0 10px} + .typing{align-self:flex-start;display:none;align-items:center;gap:8px;background:var(--bg3);border:1px solid var(--border);border-bottom-left-radius:3px;border-radius:10px;padding:9px 12px} + .typing.show{display:flex} + .typing .dots{display:flex;align-items:center;gap:3px} + .typing .dots i{width:6px;height:6px;border-radius:99px;background:var(--text2);animation:typing-bounce 1.4s infinite ease-in-out both} + .typing .dots i:nth-child(1){animation-delay:-.32s} + .typing .dots i:nth-child(2){animation-delay:-.16s} + .typing .label{font-size:11px;color:var(--text3)} + @keyframes typing-bounce{0%,80%,100%{transform:translateY(0);opacity:.4}40%{transform:translateY(-4px);opacity:1}} + .stalled{align-self:flex-start;display:none;gap:8px;background:var(--orange-glow);border:1px solid color-mix(in srgb,var(--orange) 35%,transparent);border-radius:10px;padding:8px 11px;font-size:11.5px;color:var(--text2);line-height:1.5} + .stalled.show{display:flex} + @media (prefers-reduced-motion:reduce){.typing .dots i{animation:none;opacity:.7}.presence .dot{animation:none}} + + .composer{padding:10px 14px 14px;border-top:1px solid var(--border);display:flex;flex-direction:column;gap:8px} + .anchor{display:flex;align-items:center;gap:6px;font-size:10.5px;color:var(--text3)} + .anchor code{font-size:10.5px;color:var(--teal);background:var(--bg3);border:1px solid var(--border);border-radius:4px;padding:1px 6px;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} + .anchor button{border:0;background:none;color:var(--text3);font-size:13px;line-height:1} + .anchor button:hover{color:var(--red)} + .composer textarea{width:100%;min-height:58px;max-height:160px;resize:vertical;background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:8px 10px;color:var(--text);font-size:12.5px;outline:none;transition:all .15s} + .composer textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-glow)} + .composer .row{display:flex;gap:8px;align-items:center} + .composer .send{flex:1;height:32px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg4);color:var(--text);font-size:12.5px;font-weight:600;transition:all .12s} + .composer .send:hover:not(:disabled){border-color:var(--accent);color:var(--accent)} + .composer .status{font-size:10.5px;color:var(--text3);min-height:14px} + + .overlay{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:color-mix(in srgb,var(--bg) 82%,transparent);backdrop-filter:blur(6px);z-index:50} + .overlay.show{display:flex} + .overlay .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-lg);padding:28px 34px;text-align:center;max-width:380px} + .overlay .card .ok{width:40px;height:40px;margin:0 auto 12px;border-radius:99px;background:var(--green-glow);color:var(--green);display:flex;align-items:center;justify-content:center;border:1px solid color-mix(in srgb,var(--green) 40%,transparent)} + .overlay .card h3{font-size:15px;margin-bottom:6px} + .overlay .card p{font-size:12.5px;color:var(--text2);line-height:1.55} + .overlay .card code{font-size:11px;color:var(--teal)} + `; +} + +module.exports = { uiCanvasCss }; diff --git a/scripts/lib/ui-canvas/ui.js b/scripts/lib/ui-canvas/ui.js index edc9892f4..f80b17071 100644 --- a/scripts/lib/ui-canvas/ui.js +++ b/scripts/lib/ui-canvas/ui.js @@ -18,9 +18,9 @@ const path = require('path'); const { escapeHtml } = require('../plan-canvas/markdown'); -const { TOKENS_CSS } = require('../plan-canvas/ui'); const { VIEWPORT_PRESETS } = require('./feedback'); -const { FIELD_HELPERS_JS } = require('./fields'); +const { inspectorClientJs } = require('./inspector'); +const { uiCanvasCss } = require('./ui-css'); const ICONS = { desktop: '', @@ -37,213 +37,6 @@ const ICONS = { check: '' }; -function uiCanvasCss() { - return `${TOKENS_CSS} - :root{--accent:#4acb8a;--accent-glow:rgba(74,203,138,0.15);--accent-dim:#2f9e68;--on-accent:#06130c} - [data-theme="light"]{--accent:#15803d;--accent-glow:rgba(21,128,61,0.1);--accent-dim:#166534;--on-accent:#ffffff} - *{margin:0;padding:0;box-sizing:border-box} - html,body{height:100%} - body{font-family:var(--font);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;line-height:1.4;overflow:hidden} - ::selection{background:var(--accent);color:var(--on-accent)} - ::-webkit-scrollbar{width:8px;height:8px} - ::-webkit-scrollbar-track{background:transparent} - ::-webkit-scrollbar-thumb{background:var(--border);border-radius:4px} - button,input,textarea{font-family:var(--font)} - button{cursor:pointer} - button:disabled{opacity:.45;cursor:default} - code,.mono{font-family:var(--mono)} - [hidden]{display:none!important} - - .bar{display:flex;align-items:center;gap:10px;height:54px;padding:0 14px;background:color-mix(in srgb,var(--bg2) 90%,transparent);border-bottom:1px solid var(--border);backdrop-filter:blur(16px)} - .brand{display:flex;align-items:center;gap:9px;min-width:0;margin-right:6px} - .brand .logo{width:26px;height:26px;flex:none;background:var(--bg3);border:1px solid var(--border-light);border-radius:7px;display:flex;align-items:center;justify-content:center;font-family:var(--mono);font-size:13px;font-weight:700;color:var(--accent)} - .brand .name{font-size:13.5px;font-weight:600;white-space:nowrap} - .brand .file{font-size:11.5px;color:var(--text2);font-family:var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:22vw} - .bar .spacer{flex:1} - .divider{width:1px;height:22px;background:var(--border)} - - .seg{display:inline-flex;align-items:center;background:var(--bg3);border:1px solid var(--border);border-radius:8px;padding:2px;gap:2px} - .seg button{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 10px;border:0;border-radius:6px;background:transparent;color:var(--text2);font-size:11.5px;font-weight:600;transition:all .12s} - .seg button:hover{color:var(--text);background:var(--bg4)} - .seg button[aria-pressed="true"]{background:var(--surface);color:var(--text);box-shadow:var(--shadow);outline:1px solid var(--border-light)} - .seg.viewports button{padding:0 9px} - .seg.viewports svg{display:block} - - .dims{display:flex;align-items:center;gap:5px;font-size:11.5px;color:var(--text2)} - .dims input{width:58px;height:26px;border:1px solid var(--border);border-radius:6px;background:var(--bg3);color:var(--text);font-family:var(--mono);font-size:11.5px;text-align:center;outline:none;-moz-appearance:textfield} - .dims input::-webkit-outer-spin-button,.dims input::-webkit-inner-spin-button{-webkit-appearance:none} - .dims input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-glow)} - .dims .x{color:var(--text3)} - .dims .scale{font-family:var(--mono);font-size:10.5px;color:var(--teal);min-width:34px} - .dims .icon-btn{height:26px;width:26px;padding:0;justify-content:center} - - .presence{display:flex;align-items:center;gap:6px;font-size:11px;font-weight:500;color:var(--text2);background:var(--bg3);border:1px solid var(--border);border-radius:99px;padding:3px 10px 3px 8px;white-space:nowrap;max-width:260px} - .presence .label{overflow:hidden;text-overflow:ellipsis} - .presence .dot{width:7px;height:7px;flex:none;border-radius:99px;background:var(--text3)} - .presence[data-state="listening"] .dot{background:var(--green);box-shadow:0 0 0 3px var(--green-glow);animation:pulse 2s infinite} - .presence[data-state="thinking"] .dot,.presence[data-state="typing"] .dot{background:var(--teal);box-shadow:0 0 0 3px var(--teal-glow);animation:pulse 1.2s infinite} - .presence[data-state="queued"] .dot{background:var(--orange);box-shadow:0 0 0 3px var(--orange-glow)} - .presence[data-state="ended"] .dot{background:var(--text3)} - @keyframes pulse{0%,100%{opacity:1}50%{opacity:.45}} - - .icon-btn{height:28px;padding:0 10px;border-radius:6px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-size:11.5px;font-weight:500;display:inline-flex;align-items:center;gap:5px;transition:all .12s;white-space:nowrap} - .icon-btn:hover:not(:disabled){border-color:var(--border-light);color:var(--text);background:var(--bg4)} - .icon-btn.danger:hover:not(:disabled){border-color:var(--red);color:var(--red);background:var(--red-glow)} - .icon-btn[aria-pressed="true"]{border-color:var(--accent);color:var(--accent);background:var(--accent-glow)} - .icon-btn.confirm{border-color:var(--orange);color:var(--orange);background:var(--orange-glow)} - .icon-btn.square{width:28px;padding:0;justify-content:center} - .primary{height:30px;padding:0 14px;border:1px solid var(--accent-dim);border-radius:7px;background:var(--accent);color:var(--on-accent);font-size:12px;font-weight:600;display:inline-flex;align-items:center;gap:7px;box-shadow:var(--shadow);transition:background .12s,transform .12s} - .primary:hover:not(:disabled){background:color-mix(in srgb,var(--accent) 86%,#fff)} - .primary:active:not(:disabled){transform:translateY(1px)} - - .layout{display:flex;height:calc(100% - 54px)} - .stage{flex:1;min-width:0;position:relative;display:flex;flex-direction:column;background:var(--bg);background-image:radial-gradient(color-mix(in srgb,var(--border-light) 70%,transparent) 1px,transparent 1px);background-size:18px 18px} - .stage .viewport{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;overflow:auto;padding:24px} - .sizer{position:relative;flex:none} - .device{position:absolute;top:0;left:0;transform-origin:top left;background:#fff;border-radius:6px;box-shadow:0 12px 40px rgba(0,0,0,.35),0 0 0 1px color-mix(in srgb,var(--border-light) 80%,transparent);overflow:hidden;transition:border-radius .15s} - .device iframe{display:block;width:100%;height:100%;border:0;background:#fff} - .device.mobile{border-radius:44px;border:12px solid #0b0c10;box-shadow:0 20px 60px rgba(0,0,0,.5),0 0 0 1px #2a2d38,inset 0 0 0 1px #000} - .device.mobile iframe{border-radius:32px} - .device.desktop{border-radius:8px} - .stage[data-mode="interact"] .device{outline:2px solid color-mix(in srgb,var(--green) 55%,transparent);outline-offset:3px} - - .statusbar{height:30px;flex:none;display:flex;align-items:center;gap:14px;padding:0 14px;border-top:1px solid var(--border);background:color-mix(in srgb,var(--bg2) 85%,transparent);font-size:11px;color:var(--text2);white-space:nowrap;overflow:hidden} - .statusbar .hint{flex:1;overflow:hidden;text-overflow:ellipsis} - .statusbar .hint.live{color:var(--accent)} - .statusbar kbd{font-family:var(--mono);font-size:10px;background:var(--bg3);border:1px solid var(--border);border-bottom-width:2px;border-radius:4px;padding:0 5px;color:var(--text)} - .statusbar .readout{font-family:var(--mono);font-size:10.5px;color:var(--text3)} - - .panel{width:372px;flex:none;display:flex;flex-direction:column;border-left:1px solid var(--border);background:var(--bg2);min-height:0} - .panel section{display:flex;flex-direction:column;min-height:0} - .panel h2{display:flex;align-items:center;gap:8px;font-size:11px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--text3);padding:12px 14px 8px} - .panel h2 .count{font-family:var(--mono);font-size:10px;color:var(--text2);background:var(--bg3);border:1px solid var(--border);border-radius:99px;padding:1px 7px;letter-spacing:0;text-transform:none} - .panel h2 .grow{flex:1} - .mini{height:22px;padding:0 8px;border-radius:5px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-size:10.5px;font-weight:600;letter-spacing:0;text-transform:none;display:inline-flex;align-items:center;gap:4px} - .mini:hover:not(:disabled){color:var(--text);border-color:var(--border-light)} - .mini.danger:hover:not(:disabled){color:var(--red);border-color:var(--red);background:var(--red-glow)} - .mini.go:not(:disabled){color:var(--accent);border-color:color-mix(in srgb,var(--accent) 55%,transparent);background:var(--accent-glow)} - .mini.go:hover:not(:disabled){color:var(--on-accent);background:var(--accent);border-color:var(--accent)} - .mini.confirm{color:var(--orange);border-color:var(--orange);background:var(--orange-glow)} - - .panel .inspector{flex:0 1 auto;min-height:140px;border-bottom:1px solid var(--border);max-height:56%;overflow-y:auto} - .inspector .muted{padding:0 14px 14px;font-size:12px;color:var(--text3);line-height:1.55} - .crumbs{display:flex;flex-wrap:wrap;gap:3px;padding:0 14px 8px} - .crumbs button{height:20px;padding:0 7px;border-radius:4px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-family:var(--mono);font-size:10px} - .crumbs button:hover{color:var(--text);border-color:var(--border-light)} - .crumbs button[aria-current="true"]{color:var(--accent);border-color:var(--accent);background:var(--accent-glow)} - .crumbs .sep{color:var(--text3);font-size:10px;align-self:center} - .selhead{display:flex;align-items:center;gap:8px;padding:0 14px 10px;min-width:0} - .selhead .tag{font-family:var(--mono);font-size:12px;color:var(--accent);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;flex:0 1 auto} - .selhead .snippet{font-size:11.5px;color:var(--text2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1} - .selhead .mini{flex:none} - .inspector .hint{padding:2px 14px 12px;font-size:10px;color:var(--text3);line-height:1.5} - .inspector .hint.err{color:var(--red)} - - .groups{display:flex;flex-direction:column;padding:0 0 4px} - .group{padding:6px 14px 8px;border-top:1px solid var(--border)} - .group .gh{font-size:9.5px;font-weight:600;letter-spacing:.07em;text-transform:uppercase;color:var(--text3);padding:2px 0 6px} - .field{display:grid;grid-template-columns:78px minmax(0,1fr) 56px 18px;align-items:center;gap:8px;min-height:26px} - .field .flabel{font-size:11px;color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} - .field.set .flabel{color:var(--text)} - .field.set .flabel::after{content:'';display:inline-block;width:5px;height:5px;margin:0 0 1px 5px;border-radius:99px;background:var(--accent);vertical-align:middle} - .field.sub .flabel{padding-left:10px;color:var(--text3);font-family:var(--mono);font-size:10px} - .field .ro{font-family:var(--mono);font-size:10.5px;color:var(--text2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} - .field .clear{width:18px;height:18px;padding:0;border:0;border-radius:4px;background:none;color:var(--text3);font-size:13px;line-height:1;visibility:hidden} - .field:hover .clear.on,.field .clear.on:focus-visible{visibility:visible} - .field .clear:hover{color:var(--red);background:var(--red-glow)} - .csub{display:flex;flex-direction:column;gap:1px;margin:2px 0 6px 4px;padding:2px 0 2px 0;border-left:2px solid var(--border-light)} - .cval{display:flex;align-items:center;gap:6px;min-width:0} - .cval .num{flex:1;justify-content:flex-start} - .num{height:22px;min-width:0;display:flex;align-items:center;justify-content:flex-end;padding:0 6px;border:1px solid transparent;border-radius:5px;font-family:var(--mono);font-size:10.5px;color:var(--text);cursor:text;user-select:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} - .num:hover,.num:focus-visible{border-color:var(--border);background:var(--bg3);outline:none} - .num.mixed{color:var(--text2);font-style:italic} - .numedit{height:22px;width:100%;min-width:0;border:1px solid var(--accent);border-radius:5px;background:var(--bg);color:var(--text);font-family:var(--mono);font-size:10.5px;text-align:right;padding:0 6px;outline:none;box-shadow:0 0 0 3px var(--accent-glow)} - .cval .numedit,.field.text .numedit{text-align:left} - .field.text{grid-template-columns:78px minmax(0,1fr) 18px} - .field.text .num{justify-content:flex-start} - .numedit.invalid{border-color:var(--red);box-shadow:0 0 0 3px var(--red-glow)} - .swatch-btn{position:relative;width:22px;height:22px;flex:none;padding:0;border-radius:5px;border:1px solid var(--border-light);overflow:hidden;background-color:#fff;background-image:repeating-conic-gradient(#c9ccd3 0 25%,#fff 0 50%);background-size:8px 8px} - .swatch-btn i{position:absolute;inset:0;display:block} - .swatch-btn:hover{border-color:var(--text2)} - .swatch-btn[aria-expanded="true"]{border-color:var(--accent);box-shadow:0 0 0 2px var(--accent-glow)} - .range{-webkit-appearance:none;appearance:none;width:100%;height:18px;margin:0;background:transparent;cursor:pointer;--pct:0%;--fill:var(--accent);--track:linear-gradient(to right,var(--fill) var(--pct),var(--bg4) var(--pct))} - .range:focus{outline:none} - .range::-webkit-slider-runnable-track{height:4px;border-radius:99px;background:var(--track);box-shadow:inset 0 0 0 1px var(--border)} - .range::-moz-range-track{height:4px;border-radius:99px;background:var(--track);box-shadow:inset 0 0 0 1px var(--border)} - .range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:12px;height:12px;margin-top:-4px;border-radius:99px;background:var(--text);border:2px solid var(--bg2);box-shadow:0 0 0 1px var(--border-light),0 1px 3px rgba(0,0,0,.4)} - .range::-moz-range-thumb{width:8px;height:8px;border-radius:99px;background:var(--text);border:2px solid var(--bg2);box-shadow:0 0 0 1px var(--border-light)} - .range:hover::-webkit-slider-thumb{box-shadow:0 0 0 1px var(--accent),0 1px 3px rgba(0,0,0,.4)} - .range:focus-visible::-webkit-slider-thumb{box-shadow:0 0 0 1px var(--accent),0 0 0 4px var(--accent-glow)} - .range:focus-visible::-moz-range-thumb{box-shadow:0 0 0 1px var(--accent),0 0 0 4px var(--accent-glow)} - .range.paint::-webkit-slider-runnable-track{height:8px} - .range.paint::-moz-range-track{height:8px} - .range.paint::-webkit-slider-thumb{margin-top:-2px} - .range.hue{--track:linear-gradient(to right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)} - .range.alpha{--track:linear-gradient(to right,transparent,var(--swatch)),repeating-conic-gradient(#c9ccd3 0 25%,#fff 0 50%) 0 0/8px 8px} - .aligns{display:inline-flex;gap:2px;background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:2px;justify-self:start} - .aligns button{width:24px;height:20px;padding:0;border:0;border-radius:4px;background:transparent;color:var(--text2);display:inline-flex;align-items:center;justify-content:center} - .aligns button:hover{color:var(--text);background:var(--bg4)} - .aligns button[aria-pressed="true"]{color:var(--accent);background:var(--accent-glow)} - - #themeBtn .i-moon,[data-theme="light"] #themeBtn .i-sun{display:none} - [data-theme="light"] #themeBtn .i-moon{display:block} - #pauseBtn .i-play,#pauseBtn[aria-pressed="true"] .i-pause{display:none} - #pauseBtn[aria-pressed="true"] .i-play{display:block} - - .panel .edits{flex:0 1 auto;min-height:96px;border-bottom:1px solid var(--border);max-height:22%;display:flex;flex-direction:column} - .editlist{overflow-y:auto;padding:0 14px 10px;display:flex;flex-direction:column;gap:5px} - .editlist .empty{font-size:11.5px;color:var(--text3);line-height:1.5} - .edit{display:flex;align-items:flex-start;gap:8px;padding:6px 8px;border-radius:6px;background:var(--bg3);border:1px solid var(--border);border-left:2px solid var(--teal);font-size:11px;line-height:1.45;color:var(--text2)} - .edit .k{flex:none;font-family:var(--mono);font-size:9.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--teal);padding-top:2px;width:46px} - .edit .s{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical} - .edit.kind-remove{border-left-color:var(--red)}.edit.kind-remove .k{color:var(--red)} - .edit.kind-text{border-left-color:var(--accent)}.edit.kind-text .k{color:var(--accent)} - .edit.kind-style{border-left-color:var(--pink)}.edit.kind-style .k{color:var(--pink)} - .edit.kind-move,.edit.kind-nudge{border-left-color:var(--orange)}.edit.kind-move .k,.edit.kind-nudge .k{color:var(--orange)} - .edit.stale{opacity:.5;border-style:dashed} - - .panel .convo{flex:1 1 0;min-height:232px} - .chat{flex:1;overflow-y:auto;padding:4px 14px 10px;display:flex;flex-direction:column;gap:8px} - .msg{max-width:92%;padding:7px 10px;border-radius:10px;font-size:12.5px;white-space:pre-wrap;word-break:break-word} - .msg.user{align-self:flex-end;background:var(--accent-glow);border:1px solid color-mix(in srgb,var(--accent) 35%,transparent);color:var(--text);border-bottom-right-radius:3px} - .msg.agent{align-self:flex-start;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-bottom-left-radius:3px} - .msg .meta{display:block;font-size:9.5px;color:var(--text3);margin-top:3px} - .msg.kind-edits,.msg.kind-finish{border-left:2px solid var(--green)} - .chat .empty{color:var(--text3);font-size:12px;text-align:center;margin-top:18px;line-height:1.6;padding:0 10px} - .typing{align-self:flex-start;display:none;align-items:center;gap:8px;background:var(--bg3);border:1px solid var(--border);border-bottom-left-radius:3px;border-radius:10px;padding:9px 12px} - .typing.show{display:flex} - .typing .dots{display:flex;align-items:center;gap:3px} - .typing .dots i{width:6px;height:6px;border-radius:99px;background:var(--text2);animation:typing-bounce 1.4s infinite ease-in-out both} - .typing .dots i:nth-child(1){animation-delay:-.32s} - .typing .dots i:nth-child(2){animation-delay:-.16s} - .typing .label{font-size:11px;color:var(--text3)} - @keyframes typing-bounce{0%,80%,100%{transform:translateY(0);opacity:.4}40%{transform:translateY(-4px);opacity:1}} - .stalled{align-self:flex-start;display:none;gap:8px;background:var(--orange-glow);border:1px solid color-mix(in srgb,var(--orange) 35%,transparent);border-radius:10px;padding:8px 11px;font-size:11.5px;color:var(--text2);line-height:1.5} - .stalled.show{display:flex} - @media (prefers-reduced-motion:reduce){.typing .dots i{animation:none;opacity:.7}.presence .dot{animation:none}} - - .composer{padding:10px 14px 14px;border-top:1px solid var(--border);display:flex;flex-direction:column;gap:8px} - .anchor{display:flex;align-items:center;gap:6px;font-size:10.5px;color:var(--text3)} - .anchor code{font-size:10.5px;color:var(--teal);background:var(--bg3);border:1px solid var(--border);border-radius:4px;padding:1px 6px;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} - .anchor button{border:0;background:none;color:var(--text3);font-size:13px;line-height:1} - .anchor button:hover{color:var(--red)} - .composer textarea{width:100%;min-height:58px;max-height:160px;resize:vertical;background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:8px 10px;color:var(--text);font-size:12.5px;outline:none;transition:all .15s} - .composer textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-glow)} - .composer .row{display:flex;gap:8px;align-items:center} - .composer .send{flex:1;height:32px;border:1px solid var(--border-light);border-radius:6px;background:var(--bg4);color:var(--text);font-size:12.5px;font-weight:600;transition:all .12s} - .composer .send:hover:not(:disabled){border-color:var(--accent);color:var(--accent)} - .composer .status{font-size:10.5px;color:var(--text3);min-height:14px} - - .overlay{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:color-mix(in srgb,var(--bg) 82%,transparent);backdrop-filter:blur(6px);z-index:50} - .overlay.show{display:flex} - .overlay .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-lg);padding:28px 34px;text-align:center;max-width:380px} - .overlay .card .ok{width:40px;height:40px;margin:0 auto 12px;border-radius:99px;background:var(--green-glow);color:var(--green);display:flex;align-items:center;justify-content:center;border:1px solid color-mix(in srgb,var(--green) 40%,transparent)} - .overlay .card h3{font-size:15px;margin-bottom:6px} - .overlay .card p{font-size:12.5px;color:var(--text2);line-height:1.55} - .overlay .card code{font-size:11px;color:var(--teal)} - `; -} - // Client logic for the shell page (runs in the top window). function uiClientJs() { return String.raw`'use strict'; @@ -293,6 +86,9 @@ function uiClientJs() { } const stored = readStore(); let edits = Array.isArray(stored.edits) ? stored.edits : []; + // Applied edits the agent has not written into the file yet. They replay + // silently on any reload until the file itself changes. + let submitted = Array.isArray(stored.submitted) ? stored.submitted : []; // --- theme -------------------------------------------------------------------- const themeKey = 'ecc-plan-canvas:theme'; @@ -312,13 +108,19 @@ function uiClientJs() { }); // --- viewport ------------------------------------------------------------------ + const clampDim = n => Math.max(100, Math.min(20000, Math.round(Number(n)) || 100)); function parseViewport(spec) { const custom = typeof spec === 'string' ? spec.match(/^(\d{2,5})x(\d{2,5})$/) : null; - if (custom) return { preset: 'custom', width: Number(custom[1]), height: Number(custom[2]) }; + if (custom) return { preset: 'custom', width: clampDim(custom[1]), height: clampDim(custom[2]) }; if (spec === 'mobile' || spec === 'custom') return { preset: spec, width: PRESETS[spec].width, height: PRESETS[spec].height }; return { preset: 'desktop', width: PRESETS.desktop.width, height: PRESETS.desktop.height }; } - let vp = stored.viewport && stored.viewport.preset ? stored.viewport : parseViewport(boot.ui && boot.ui.viewport); + // sessionStorage is editable by hand; only trust a well-formed viewport. + function storedViewport(v) { + if (!v || ['desktop', 'mobile', 'custom'].indexOf(v.preset) < 0) return null; + return { preset: v.preset, width: clampDim(v.width), height: clampDim(v.height), rotated: Boolean(v.rotated) }; + } + let vp = storedViewport(stored.viewport) || parseViewport(boot.ui && boot.ui.viewport); let actual = { width: vp.width, height: vp.height, scale: 1 }; function layoutStage() { @@ -432,7 +234,7 @@ function uiClientJs() { case 'uc:ready': frameReady = true; postToFrame({ type: 'uc:set-mode', mode }); - postToFrame({ type: 'uc:restore', edits, scroll: lastScroll, selection: selection ? selection.selector : null }); + postToFrame({ type: 'uc:restore', baked: submitted, edits, scroll: lastScroll, selection: selection ? selection.selector : null }); if (paused) postToFrame({ type: 'uc:pause-animations', paused: true }); break; case 'uc:selection': @@ -463,575 +265,7 @@ function uiClientJs() { if (e.target === viewportEl && mode === 'edit') postToFrame({ type: 'uc:deselect' }); }); - // --- inspector ---------------------------------------------------------------------- - // Parse, sanitize and format helpers, shared verbatim with Node tests - // (scripts/lib/ui-canvas/fields.js). - ${FIELD_HELPERS_JS} - - const FIELD_HINT = 'Drag a slider or double-click a value to type one. Enter applies, Esc cancels, arrow keys step (Shift for 10).'; - const LENGTH_UNITS = ['px', 'rem', 'em', '%']; - // step is typed-value precision (so 1.25rem survives); sliderStep is the drag increment. - const NUMERIC = { - 'font-size': { label: 'Size', unit: 'px', units: LENGTH_UNITS, min: 1, max: 999, step: 0.01, slider: [6, 96], sliderStep: 1 }, - 'font-weight': { label: 'Weight', unit: '', units: [''], min: 1, max: 1000, step: 1, slider: [100, 900], sliderStep: 100 }, - 'line-height': { label: 'Line height', unit: '', units: ['', 'px', 'em', 'rem', '%'], min: 0, max: 999, step: 0.01, slider: [0.8, 3], sliderStep: 0.05 }, - 'border-radius': { label: 'Radius', unit: 'px', units: LENGTH_UNITS, min: 0, max: 9999, step: 0.01, slider: [0, 64], sliderStep: 1, box: true }, - 'opacity': { label: 'Opacity', ratio: true, min: 0, max: 1, step: 0.01, slider: [0, 1] }, - 'padding': { label: 'Padding', unit: 'px', units: LENGTH_UNITS, min: 0, max: 9999, step: 0.01, slider: [0, 96], sliderStep: 1, box: true }, - 'margin': { label: 'Margin', unit: 'px', units: LENGTH_UNITS, min: -9999, max: 9999, step: 0.01, slider: [0, 96], sliderStep: 1, box: true, allowAuto: true }, - 'gap': { label: 'Gap', unit: 'px', units: LENGTH_UNITS, min: 0, max: 9999, step: 0.01, slider: [0, 96], sliderStep: 1, box: true, maxParts: 2 } - }; - const ALIGN_ICONS = { - left: '', - center: '', - right: '', - justify: '' - }; - let fields = []; - let renderedKey = ''; - let current = {}; - const openColors = new Set(); - - function el(tag, cls, text) { - const node = document.createElement(tag); - if (cls) node.className = cls; - if (text !== undefined) node.textContent = text; - return node; - } - function styleMap(sel) { - const out = {}; - (sel.styles || []).forEach(s => { out[s.property] = s; }); - return out; - } - function px(value) { const n = parseFloat(value); return Number.isFinite(n) ? n : 0; } - function setStyle(property, value) { postToFrame({ type: 'uc:style', property, value }); } - function isDefaultish(value) { - return value === 'none' || value === 'normal' || value === 'start' || value === '1' || /^(0px ?)+$/.test(value + ' ') || /^0(px)?$/.test(value) || /rgba\(\s*\d+[, ]+\d+[, ]+\d+[, /]+0\)/.test(value); - } - let hintTimer = null; - function fieldHint(text, isError) { - const hint = $('fieldHint'); - hint.textContent = text || FIELD_HINT; - hint.classList.toggle('err', Boolean(isError)); - clearTimeout(hintTimer); - if (text) hintTimer = setTimeout(() => fieldHint(''), 4000); - } - let probe = null; - // Any CSS color the browser accepts (names included), normalized to rgba parts. - function resolveColor(text) { - const direct = parseColor(text); - if (direct) return direct; - const clean = sanitizeCssText(text, 60); - if (!clean.ok || !(window.CSS && CSS.supports('color', clean.css))) return null; - if (!probe) { probe = el('span'); probe.hidden = true; document.body.appendChild(probe); } - probe.style.color = ''; - probe.style.color = clean.css; - return parseColor(getComputedStyle(probe).color); - } - - // Double-click (or Enter on a focused value) swaps the value for a text box. - // commit(text) returns an error to keep the box open, or '' once applied. - function editableValue(span, field, getText, commit) { - span.tabIndex = 0; - span.title = 'Double-click to type a value'; - const begin = () => { - if (ended || field.editing) return; - field.editing = true; - const box = el('input', 'numedit'); - box.type = 'text'; - box.spellcheck = false; - box.autocomplete = 'off'; - box.value = getText(); - span.replaceWith(box); - box.focus(); - box.select(); - let done = false; - const finish = how => { - if (done) return; - if (how) { - const error = commit(box.value); - if (error) { - box.classList.add('invalid'); - box.title = error; - fieldHint(error, true); - if (how === 'enter') return; - } else fieldHint(''); - } - done = true; - field.editing = false; - box.replaceWith(span); - field.update(current); - if (how !== 'blur') span.focus(); - }; - box.addEventListener('keydown', e => { - e.stopPropagation(); - if (e.key === 'Enter') { e.preventDefault(); finish('enter'); } - else if (e.key === 'Escape') { e.preventDefault(); finish(null); } - }); - box.addEventListener('input', () => box.classList.remove('invalid')); - box.addEventListener('blur', () => finish('blur')); - }; - span.addEventListener('dblclick', e => { e.preventDefault(); begin(); }); - span.addEventListener('keydown', e => { - if (e.key === 'Enter') { e.preventDefault(); begin(); } - else if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && field.nudge) { - e.preventDefault(); - field.nudge((e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1)); - } - }); - } - - // One labelled row: slider, value (double-click to type) and a clear button. - // opts.read(styles) -> { value, text, mixed, range: [min, max], set, clear }. - function sliderField(opts) { - const field = { busy: false, editing: false }; - const row = el('div', 'field' + (opts.sub ? ' sub' : '')); - row.setAttribute('data-prop', opts.prop || ''); - const label = el('span', 'flabel', opts.label); - label.title = opts.title || opts.prop || opts.label; - const range = el('input', 'range' + (opts.rangeClass ? ' ' + opts.rangeClass : '')); - range.type = 'range'; - range.step = String(opts.step); - range.setAttribute('aria-label', opts.label); - const num = el('span', 'num'); - const clear = el('button', 'clear', '×'); - clear.type = 'button'; - clear.title = 'Clear ' + (opts.prop || opts.label); - clear.setAttribute('aria-label', clear.title); - row.append(label, range, num, clear); - let state = { value: 0, text: '' }; - const paint = () => { - const min = Number(range.min), max = Number(range.max); - const pct = max > min ? ((Number(range.value) - min) / (max - min)) * 100 : 0; - range.style.setProperty('--pct', pct.toFixed(2) + '%'); - if (opts.paint) opts.paint(range); - }; - field.update = styles => { - if (field.busy || field.editing) return; - state = opts.read(styles); - const lo = Math.min(state.range[0], state.value); - const hi = Math.max(state.range[1], state.value); - range.min = String(lo); - range.max = String(hi); - range.value = String(state.value); - num.textContent = state.text; - num.classList.toggle('mixed', Boolean(state.mixed)); - row.classList.toggle('set', Boolean(state.set)); - clear.classList.toggle('on', Boolean(state.clear)); - range.disabled = ended; - paint(); - }; - range.addEventListener('pointerdown', () => { field.busy = true; }); - const release = () => { if (!field.busy) return; field.busy = false; field.update(current); }; - range.addEventListener('pointerup', release); - range.addEventListener('change', release); - range.addEventListener('blur', release); - range.addEventListener('input', () => { - const value = Number(range.value); - num.textContent = opts.format ? opts.format(value) : formatNumber(value); - num.classList.remove('mixed'); - paint(); - opts.write(value); - }); - field.nudge = delta => { - const step = Number(range.step) || 1; - const next = Number((state.value + delta * step).toFixed(4)); - opts.write(Math.max(opts.floor === undefined ? -Infinity : opts.floor, next)); - }; - editableValue(num, field, () => (opts.editText ? opts.editText(state) : state.text), text => opts.type(text)); - clear.addEventListener('click', () => { if (opts.clear) opts.clear(); }); - field.el = row; - return field; - } - - function numericField(prop) { - const spec = NUMERIC[prop]; - return sliderField({ - label: spec.label, - prop, - step: spec.sliderStep || spec.step, - floor: spec.min, - read: styles => { - const style = styles[prop]; - const raw = String(style.value); - const out = { range: spec.slider, set: Boolean(style.inline), clear: style.resettable && !isDefaultish(raw) }; - if (spec.ratio) return Object.assign(out, { value: px(raw), text: Math.round(px(raw) * 100) + '%' }); - if (prop === 'line-height') { - if (raw === 'normal') return Object.assign(out, { value: 1.2, text: 'normal', mixed: true }); - const size = styles['font-size'] ? px(styles['font-size'].value) : 16; - const ratio = size ? px(raw) / size : 1; - return Object.assign(out, { value: Number(ratio.toFixed(2)), text: formatNumber(ratio) }); - } - if (spec.box) { - const parts = raw.split(/\s+/).filter(p => p && p !== '/'); - const mixed = parts.some(p => p !== parts[0]); - return Object.assign(out, { value: px(parts[0]), text: mixed ? parts.map(p => (/px$/.test(p) ? formatNumber(px(p)) : p)).join(' ') : formatNumber(px(parts[0])), mixed }); - } - return Object.assign(out, { value: px(raw), text: formatNumber(px(raw)) }); - }, - format: value => (spec.ratio ? Math.round(value * 100) + '%' : formatNumber(value)), - write: value => { - if (spec.ratio || prop === 'line-height') setStyle(prop, formatNumber(value)); - else if (prop === 'font-weight') setStyle(prop, String(Math.round(value))); - else setStyle(prop, formatNumber(value) + 'px'); - }, - type: text => { - const word = String(text).trim().toLowerCase(); - if (prop === 'line-height' && word === 'normal') { setStyle(prop, 'normal'); return ''; } - if (prop === 'font-weight' && (word === 'bold' || word === 'normal')) { setStyle(prop, word === 'bold' ? '700' : '400'); return ''; } - const result = spec.box ? sanitizeBoxList(text, spec) : sanitizeNumber(text, spec); - if (!result.ok) return result.error; - setStyle(prop, result.css); - return ''; - }, - clear: () => setStyle(prop, null) - }); - } - - function sizeField(label, dim) { - const spec = { unit: 'px', units: ['px'], min: 1, max: 20000, step: 1 }; - const send = value => postToFrame({ type: 'uc:size', width: dim === 'width' ? value : null, height: dim === 'height' ? value : null }); - return sliderField({ - label, - prop: dim, - title: dim + ' in CSS pixels', - step: 1, - floor: 1, - read: () => { - const value = selection.size[dim]; - const room = dim === 'width' ? actual.width : actual.height; - return { value, text: String(value), range: [1, Math.max(room, Math.round(value * 1.5))] }; - }, - write: value => send(Math.max(1, Math.round(value))), - type: text => { - const result = sanitizeNumber(text, spec); - if (!result.ok) return result.error; - send(result.value); - return ''; - } - }); - } - - // Swatch + hex + alpha row; the swatch opens hue, saturation, lightness and - // alpha sliders underneath. The exact color is kept beside its HSL view so - // typed or incoming values never drift, and hue survives grays. - function colorField(label, prop, getColor, setColor, clearable) { - const wrap = el('div', 'cfield'); - const field = { editing: false }; - const row = el('div', 'field'); - row.setAttribute('data-prop', prop); - const flabel = el('span', 'flabel', label); - flabel.title = prop; - const cval = el('div', 'cval'); - const swatch = el('button', 'swatch-btn'); - swatch.type = 'button'; - swatch.title = 'Adjust ' + label.toLowerCase() + ' with sliders'; - swatch.setAttribute('aria-label', swatch.title); - const fill = el('i'); - swatch.appendChild(fill); - const hex = el('span', 'num'); - cval.append(swatch, hex); - const alpha = el('span', 'num'); - const clear = el('button', 'clear', '×'); - clear.type = 'button'; - clear.title = 'Clear ' + prop; - clear.setAttribute('aria-label', clear.title); - row.append(flabel, cval, alpha, clear); - const sub = el('div', 'csub'); - wrap.append(row, sub); - let hsl = { h: 0, s: 0, l: 0, a: 0 }; - let exact = { r: 0, g: 0, b: 0, a: 0 }; - let lastCss = ''; - const adopt = color => { - const next = rgbToHsl(color); - if (next.s === 0 && lastCss) next.h = hsl.h; - hsl = next; - exact = { r: color.r, g: color.g, b: color.b, a: color.a }; - }; - const hexField = { editing: false, update: () => field.update(current) }; - const alphaField = { editing: false, update: () => field.update(current) }; - const apply = fromSliders => { - if (fromSliders) exact = hslToRgb(hsl); - else exact.a = hsl.a; - const css = formatColor(exact); - lastCss = css; - paint(); - setColor(css); - }; - const channel = (name, max, rangeClass, key, unit) => sliderField({ - label: name, - sub: true, - step: 1, - floor: 0, - rangeClass, - read: () => ({ value: key === 'a' ? Math.round(hsl.a * 100) : hsl[key], text: (key === 'a' ? Math.round(hsl.a * 100) : hsl[key]) + unit, range: [0, max] }), - format: value => value + unit, - write: value => { - const next = Math.max(0, Math.min(max, Math.round(value))); - if (key === 'a') hsl.a = next / 100; - else { hsl[key] = next; if (hsl.a === 0) hsl.a = 1; } - apply(key !== 'a'); - }, - type: text => { - const result = sanitizeNumber(text, { unit: unit === '%' ? '%' : '', units: unit === '%' ? ['%', ''] : ['', 'deg'], min: 0, max, step: 1 }); - if (!result.ok) return result.error; - if (key === 'a') hsl.a = result.value / 100; - else { hsl[key] = result.value; if (hsl.a === 0) hsl.a = 1; } - apply(key !== 'a'); - return ''; - }, - paint: range => { - const h = hsl.h, s = hsl.s, l = hsl.l; - if (key === 's') range.style.setProperty('--track', 'linear-gradient(to right,hsl(' + h + ',0%,' + l + '%),hsl(' + h + ',100%,' + l + '%))'); - if (key === 'l') range.style.setProperty('--track', 'linear-gradient(to right,#000,hsl(' + h + ',' + s + '%,50%),#fff)'); - if (key === 'a') range.style.setProperty('--swatch', formatColor(hslToRgb({ h, s, l, a: 1 }))); - } - }); - const channels = [channel('H', 360, 'paint hue', 'h', '°'), channel('S', 100, 'paint', 's', '%'), channel('L', 100, 'paint', 'l', '%'), channel('A', 100, 'paint alpha', 'a', '%')]; - channels.forEach(c => sub.appendChild(c.el)); - const busy = () => field.editing || hexField.editing || alphaField.editing || channels.some(c => c.busy || c.editing); - function paint() { - fill.style.background = formatColor(exact); - hex.textContent = hsl.a === 0 ? 'none' : colorHex(exact); - hex.classList.toggle('mixed', hsl.a === 0); - alpha.textContent = Math.round(hsl.a * 100) + '%'; - channels.forEach(c => { if (!c.busy && !c.editing) c.update(current); }); - } - const setOpen = open => { - if (open) openColors.add(prop); else openColors.delete(prop); - sub.hidden = !open; - swatch.setAttribute('aria-expanded', String(open)); - }; - swatch.addEventListener('click', () => setOpen(sub.hidden)); - setOpen(openColors.has(prop)); - field.update = styles => { - const style = styles[prop] || {}; - row.classList.toggle('set', Boolean(style.inline)); - clear.classList.toggle('on', Boolean(clearable && style.resettable && !isDefaultish(String(style.value)))); - if (busy()) return; - const color = getColor(styles) || { r: 0, g: 0, b: 0, a: 0 }; - const css = formatColor(color); - if (css !== lastCss) { - adopt(color); - lastCss = css; - } - paint(); - }; - editableValue(hex, hexField, () => (hsl.a === 0 ? '' : colorHex(exact)), text => { - const color = resolveColor(text); - if (!color) return 'Use a hex like #16A34A, rgb(), or a color name'; - adopt(color); - apply(); - return ''; - }); - editableValue(alpha, alphaField, () => String(Math.round(hsl.a * 100)), text => { - const result = sanitizeNumber(text, { ratio: true, min: 0, max: 1, step: 0.01 }); - if (!result.ok) return result.error; - hsl.a = result.value; - apply(); - return ''; - }); - alphaField.nudge = delta => { hsl.a = Math.max(0, Math.min(1, Number((hsl.a + delta / 100).toFixed(2)))); apply(); }; - clear.addEventListener('click', () => setStyle(prop, null)); - field.el = wrap; - return field; - } - - function borderParts(styles) { - const value = styles.border ? String(styles.border.value) : 'none'; - const match = value.match(/^([\d.]+)px\s+(\S+)\s+(.+)$/); - if (!match) return { width: 0, style: 'solid', color: null }; - return { width: Number(match[1]), style: match[2] === 'none' ? 'solid' : match[2], color: parseColor(match[3]) }; - } - function borderCss(width, style, color) { - return width <= 0 ? 'none' : formatNumber(width) + 'px ' + style + ' ' + color; - } - function borderWidthField() { - const spec = { unit: 'px', units: ['px'], min: 0, max: 64, step: 0.5 }; - const write = width => { - const parts = borderParts(current); - const color = parts.color ? formatColor(parts.color) : (current.color ? current.color.value : '#000000'); - setStyle('border', borderCss(width, parts.style, color)); - }; - return sliderField({ - label: 'Width', - prop: 'border', - title: 'border width', - step: 1, - floor: 0, - read: styles => { - const parts = borderParts(styles); - return { value: parts.width, text: formatNumber(parts.width), range: [0, 16], set: Boolean(styles.border && styles.border.inline), clear: parts.width > 0 }; - }, - write, - type: text => { - const result = sanitizeNumber(text, spec); - if (!result.ok) return result.error; - write(result.value); - return ''; - }, - clear: () => setStyle('border', null) - }); - } - - function alignField() { - const field = { editing: false }; - const row = el('div', 'field'); - row.setAttribute('data-prop', 'text-align'); - const label = el('span', 'flabel', 'Align'); - label.title = 'text-align'; - const group = el('div', 'aligns'); - group.style.gridColumn = 'span 2'; - group.setAttribute('role', 'group'); - group.setAttribute('aria-label', 'Text align'); - const buttons = Object.keys(ALIGN_ICONS).map(name => { - const b = el('button'); - b.type = 'button'; - b.innerHTML = ALIGN_ICONS[name]; - b.title = 'Align ' + name; - b.setAttribute('aria-label', b.title); - b.addEventListener('click', () => setStyle('text-align', name)); - group.appendChild(b); - return { name, b }; - }); - const spacer = el('span'); - row.append(label, group, spacer); - field.update = styles => { - const raw = styles['text-align'] ? String(styles['text-align'].value) : 'start'; - const value = raw === 'start' ? 'left' : raw === 'end' ? 'right' : raw; - row.classList.toggle('set', Boolean(styles['text-align'] && styles['text-align'].inline)); - buttons.forEach(({ name, b }) => b.setAttribute('aria-pressed', String(name === value))); - }; - field.el = row; - return field; - } - - // Free CSS such as box-shadow: shown truncated, typed in full. - function textField(label, prop) { - const field = { editing: false }; - const row = el('div', 'field text'); - row.setAttribute('data-prop', prop); - const flabel = el('span', 'flabel', label); - flabel.title = prop; - const num = el('span', 'num'); - const clear = el('button', 'clear', '×'); - clear.type = 'button'; - clear.title = 'Clear ' + prop; - clear.setAttribute('aria-label', clear.title); - row.append(flabel, num, clear); - let text = ''; - field.update = styles => { - if (field.editing) return; - const style = styles[prop] || { value: 'none' }; - text = String(style.value); - num.textContent = shortValue(text); - num.classList.toggle('mixed', text === 'none'); - row.classList.toggle('set', Boolean(style.inline)); - clear.classList.toggle('on', Boolean(style.resettable && text !== 'none')); - num.title = text + '\nDouble-click to type a value'; - }; - editableValue(num, field, () => text, typed => { - const result = sanitizeCssText(typed, 300); - if (!result.ok) return result.error; - if (window.CSS && !CSS.supports(prop, result.css)) return 'Not a valid ' + prop + ' value'; - setStyle(prop, result.css); - return ''; - }); - clear.addEventListener('click', () => setStyle(prop, null)); - field.el = row; - return field; - } - - function readOnlyField(label, prop) { - const row = el('div', 'field text'); - const flabel = el('span', 'flabel', label); - flabel.title = prop + ' (read-only here; ask the agent to change layout)'; - const value = el('span', 'ro'); - row.append(flabel, value, el('span')); - return { el: row, update: styles => { value.textContent = styles[prop] ? String(styles[prop].value) : ''; } }; - } - - function colorOf(prop) { - return styles => (styles[prop] ? parseColor(styles[prop].value) : null); - } - function buildGroups(styles) { - const has = prop => Boolean(styles[prop]); - const plan = [ - ['Size', [sizeField('Width', 'width'), sizeField('Height', 'height')]], - ['Fill', [ - has('background-color') && colorField('Background', 'background-color', colorOf('background-color'), css => setStyle('background-color', css), true), - has('background-image') && textField('Image', 'background-image') - ]], - ['Text', [ - has('color') && colorField('Color', 'color', colorOf('color'), css => setStyle('color', css), true), - has('font-size') && numericField('font-size'), - has('font-weight') && numericField('font-weight'), - has('line-height') && numericField('line-height'), - has('text-align') && alignField() - ]], - ['Spacing', [has('padding') && numericField('padding'), has('margin') && numericField('margin'), has('gap') && numericField('gap')]], - ['Border', [ - has('border') && borderWidthField(), - has('border') && colorField('Color', 'border', s => borderParts(s).color, css => { - const parts = borderParts(current); - setStyle('border', borderCss(parts.width || 1, parts.style, css)); - }, false), - has('border-radius') && numericField('border-radius') - ]], - ['Effects', [has('opacity') && numericField('opacity'), has('box-shadow') && textField('Shadow', 'box-shadow'), has('display') && readOnlyField('Display', 'display')]] - ]; - const container = $('groups'); - container.innerHTML = ''; - fields = []; - for (const [title, list] of plan) { - const items = list.filter(Boolean); - if (!items.length) continue; - const group = el('div', 'group'); - group.appendChild(el('div', 'gh', title)); - items.forEach(f => { group.appendChild(f.el); fields.push(f); }); - container.appendChild(group); - } - fields.forEach(f => f.update(styles)); - } - - function shortValue(value) { - return String(value).replace(/rgba?\([^)]*\)/g, m => { const c = parseColor(m); return c ? (c.a < 1 ? formatColor(c) : colorHex(c)) : m; }).replace(/(\d+\.\d{2})\d+/g, '$1'); - } - function renderInspector() { - const has = Boolean(selection); - $('noSel').hidden = has; - $('selBody').hidden = !has; - $('deselectBtn').hidden = !has; - if (!has) { renderedKey = ''; fields = []; current = {}; return; } - current = styleMap(selection); - const crumbs = $('crumbs'); - crumbs.innerHTML = ''; - (selection.breadcrumb || []).forEach((crumb, i, arr) => { - const b = document.createElement('button'); - b.type = 'button'; - b.textContent = crumb.label; - b.title = crumb.selector; - if (i === arr.length - 1) b.setAttribute('aria-current', 'true'); - b.addEventListener('click', () => postToFrame({ type: 'uc:select', selector: crumb.selector })); - crumbs.appendChild(b); - if (i < arr.length - 1) { const sep = document.createElement('span'); sep.className = 'sep'; sep.textContent = '›'; crumbs.appendChild(sep); } - }); - $('selTag').textContent = '<' + selection.tag + '>' + (selection.id ? '#' + selection.id : '') + (selection.classes && selection.classes.length ? '.' + selection.classes.join('.') : ''); - $('selTag').title = selection.selector; - $('selSnippet').textContent = selection.snippet || ''; - $('selSnippet').title = selection.snippet || ''; - $('editTextBtn').disabled = ended || !selection.editable; - $('removeBtn').disabled = ended; - const key = selection.selector + '|' + Object.keys(current).join(','); - if (key === renderedKey) { fields.forEach(f => f.update(current)); return; } - renderedKey = key; - buildGroups(current); - } - $('editTextBtn').addEventListener('click', () => postToFrame({ type: 'uc:edit-text' })); - $('removeBtn').addEventListener('click', () => postToFrame({ type: 'uc:remove' })); - $('deselectBtn').addEventListener('click', () => postToFrame({ type: 'uc:deselect' })); - fieldHint(''); - +${inspectorClientJs()} // --- edit log ----------------------------------------------------------------------- function summarize(edit) { const target = edit.selector + (edit.snippet ? ' “' + edit.snippet.slice(0, 40) + (edit.snippet.length > 40 ? '…' : '') + '”' : ''); @@ -1228,8 +462,9 @@ function uiClientJs() { markEnded('finished'); } else { postToFrame({ type: 'uc:forget' }); + submitted = submitted.concat((snapshot.edits || edits).filter(e => !e.stale)); edits = []; - writeStore({ edits: [] }); + writeStore({ edits: [], submitted }); renderEdits(); statusEl.textContent = describeDelivery(body) + ' The preview updates when it writes the file.'; if (body.presence) applyPresence(body.presence, agent); @@ -1302,7 +537,13 @@ function uiClientJs() { const es = new EventSource('/events/' + key); es.addEventListener('chat-sync', e => renderChat(JSON.parse(e.data).chat || [])); es.addEventListener('presence', e => { const data = JSON.parse(e.data); applyPresence(data.state, data.agent); }); - es.addEventListener('reload', reloadArtifact); + // The file changed on disk: the agent has written the applied edits in, + // so they must not replay on top of the new markup. + es.addEventListener('reload', () => { + submitted = []; + writeStore({ submitted: [] }); + reloadArtifact(); + }); es.addEventListener('ended', e => { markEnded(JSON.parse(e.data).endedBy); es.close(); }); es.onerror = () => { if (ended) return; diff --git a/scripts/plan-canvas.js b/scripts/plan-canvas.js index 113d3ac8d..a76933aae 100755 --- a/scripts/plan-canvas.js +++ b/scripts/plan-canvas.js @@ -348,7 +348,7 @@ function cmdPending({ stateDir }) { status: waiting.length ? 'pending' : 'clear', sessions: waiting, next_step: waiting.length - ? 'Run `ecc-plan-canvas await ` for each file above to receive the messages.' + ? 'Run the `resume` command of each session above to receive its messages.' : 'No canvas feedback is waiting.' }; } diff --git a/scripts/ui-canvas.js b/scripts/ui-canvas.js index 8f9f4b018..976942137 100755 --- a/scripts/ui-canvas.js +++ b/scripts/ui-canvas.js @@ -45,7 +45,8 @@ function usage() { ' typing: --state Defaults to typing', ' server: --port --host ', '', - 'Finish payloads name .edited.html (final markup) and .edits.json (edit log) next to the artifact.', + 'Finish payloads name .edited.html (final markup) and .edits.json (edit log) next to the artifact;', + 'each Apply batch writes its own .apply-.edited.html and .edits.json pair.', 'Environment: ECC_PLAN_CANVAS_PORT, ECC_PLAN_CANVAS_STATE_DIR, ECC_PLAN_CANVAS_IDLE_MS, ECC_CANVAS_AGENT' ].join('\n'); } diff --git a/skills/ui-canvas/SKILL.md b/skills/ui-canvas/SKILL.md index e7a500c78..9296cd2e6 100644 --- a/skills/ui-canvas/SKILL.md +++ b/skills/ui-canvas/SKILL.md @@ -106,15 +106,17 @@ listening" so the human knows you are connected. ```json { "kind": "edits", "editCount": 3, "edits": [ { "kind": "resize", "selector": "img.art", "width": 220, "height": 220, "before": { "width": 260, "height": 260 } } ], "viewport": { "preset": "mobile", "width": 393, "height": 852 }, - "exportPath": "/abs/.claude/previews/pricing-card.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.edits.json" } + "exportPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edited.html", "editsPath": "/abs/.claude/previews/pricing-card.apply-mf3k2x-9a1c.edits.json" } ``` - `edits` means the human clicked **Apply to file**: they want their hand edits written into the mockup now. Replace the mockup file with the contents of `exportPath` (it is the full DOM they are looking at, with their inline-style changes), tidy it into real CSS if it is messy, keep it - self-contained, and reply. The canvas clears its pending list, so nothing - is applied twice. + self-contained, and reply. Each Apply writes its own + `.apply-.*` pair, so a queued earlier batch keeps its own + snapshot. The canvas keeps showing the applied edits until your write to + the mockup reloads it, then drops them, so nothing is applied twice. ```json { "kind": "finish", "editCount": 5, "edits": [ "…" ], "viewport": { "preset": "desktop", "width": 1412, "height": 806 }, @@ -179,8 +181,10 @@ never the other way, so media queries are honest. only from an `edits` or `finish` payload, from `exportPath`. - Reply in the canvas (`await --reply`), not only in the terminal, while the session is open. -- The exported `.edited.html` and `.edits.json` are review artifacts, not - production code. Do not commit them unless the repo keeps previews. +- The exported `.edited.html` and `.edits.json` files (including the + per-Apply `.apply-.*` pairs) are review artifacts, not production + code. Do not commit them unless the repo keeps previews; delete the + `.apply-*` pairs once the mockup is updated. - The server is loopback-only, idles out after 30 minutes (`ECC_PLAN_CANVAS_IDLE_MS`), and keeps state in `~/.claude/plan-canvas/` (`ECC_PLAN_CANVAS_STATE_DIR`). `ECC_CANVAS_AGENT` overrides the detected diff --git a/tests/fixtures/ui-canvas/pricing-card.edited.html b/tests/fixtures/ui-canvas/pricing-card.edited.html deleted file mode 100644 index 6cf334f3d..000000000 --- a/tests/fixtures/ui-canvas/pricing-card.edited.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - -Pricing card mockup - - - -
- Plan illustration -
- Most posdlkfjhlskjdfklsfpular -

Team plan

-

Everything in Starter, plus shared memory, hosted CI tiers, and priority support for up to 25 seats.

-
-
$49/ seat / month
-
- - -
-
-
- - - - - diff --git a/tests/fixtures/ui-canvas/pricing-card.edits.json b/tests/fixtures/ui-canvas/pricing-card.edits.json deleted file mode 100644 index c83b9bc00..000000000 --- a/tests/fixtures/ui-canvas/pricing-card.edits.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "artifact": "/Users/hira/Documents/ECC/ecc-ui-canvas/tests/fixtures/ui-canvas/pricing-card.html", - "kind": "finish", - "at": "2026-10-16T22:17:40.722Z", - "viewport": { - "preset": "desktop", - "width": 1034, - "height": 666 - }, - "edits": [ - { - "id": "e1-mvbj1riu", - "kind": "text", - "selector": "#pricing-card > div.body:nth-of-type(1) > span.badge:nth-of-type(1)", - "tag": "span", - "snippet": "MOST POSDLKFJHLSKJDFKLSFPULAR", - "at": "2026-10-16T22:16:25.494Z", - "before": "MOST POPULAR", - "after": "MOST POSDLKFJHLSKJDFKLSFPULAR", - "htmlAfter": "Most posdlkfjhlskjdfklsfpular" - }, - { - "id": "e2-mvbj1utl", - "kind": "style", - "selector": "#pricing-card > div.body:nth-of-type(1) > div.actions:nth-of-type(3) > button.btn.primary:nth-of-type(1)", - "tag": "button", - "snippet": "Start free trial", - "at": "2026-10-16T22:16:29.770Z", - "property": "background-color", - "before": "rgb(104, 133, 232)", - "after": "#6885e8" - }, - { - "id": "e3-mvbj203j", - "kind": "style", - "selector": "#pricing-card > div.body:nth-of-type(1) > div.actions:nth-of-type(3) > button.btn.primary:nth-of-type(1)", - "tag": "button", - "snippet": "Start free trial", - "at": "2026-10-16T22:16:36.607Z", - "property": "background-color", - "before": "rgb(104, 133, 232)", - "after": "rgb(0,0,0)" - } - ] -} diff --git a/tests/hooks/plan-canvas-pending-hook.test.js b/tests/hooks/plan-canvas-pending-hook.test.js index 0a3d82688..cfacc8ba0 100644 --- a/tests/hooks/plan-canvas-pending-hook.test.js +++ b/tests/hooks/plan-canvas-pending-hook.test.js @@ -159,6 +159,33 @@ async function runTests() { assert.strictEqual((await hook.run(input)).stdout, input); })) passed++; else failed++; + if (await test('an ended UI session still hands over an undelivered Save and Finish', async () => { + const stateDir = freshStateDir(); + const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'plan-canvas-project-')); + const state = { + eeeeeeeeeeee: sessionRecord( + 'eeeeeeeeeeee', + path.join(projectDir, 'card.html'), + [{ id: 'fb-1', kind: 'finish', editCount: 2, exportPath: path.join(projectDir, 'card.edited.html'), at: '2026-01-01T00:00:00.000Z' }], + { status: 'ended', endedBy: 'user', mode: 'ui' } + ), + ffffffffffff: sessionRecord( + 'ffffffffffff', + path.join(projectDir, 'stale.html'), + [{ id: 'fb-1', kind: 'chat', text: 'stale', at: '2026-01-01T00:00:00.000Z' }], + { status: 'ended', endedBy: 'user', mode: 'ui' } + ) + }; + writeState(stateDir, state); + const hook = loadHook(stateDir); + assert.deepStrictEqual(hook.pendingSessions({ sessions: state }, projectDir, {}).map(s => s.key), ['eeeeeeeeeeee']); + const result = await hook.run(JSON.stringify({ cwd: projectDir })); + const reason = JSON.parse(result.stdout).reason; + assert.ok(reason.includes('SAVED AND FINISHED (2 edits)'), reason); + assert.ok(reason.includes('saved and finished (or ended) this preview'), 'ended UI guidance, no reopen'); + assert.strictEqual(readPending(stateDir, 'eeeeeeeeeeee').length, 0, 'drained once'); + })) passed++; else failed++; + if (await test('renders annotations and verdicts readably', async () => { const hook = loadHook(freshStateDir()); assert.strictEqual( diff --git a/tests/lib/plan-canvas-agent-identity.test.js b/tests/lib/plan-canvas-agent-identity.test.js index f03049736..bf624bcdf 100644 --- a/tests/lib/plan-canvas-agent-identity.test.js +++ b/tests/lib/plan-canvas-agent-identity.test.js @@ -48,6 +48,14 @@ test('agentDescriptor reports the name and the project basename only', () => { assert.deepStrictEqual(descriptor, { name: 'Codex', project: 'shop' }); }); +test('agentFromParam reads a JSON descriptor or a bare harness name', () => { + assert.strictEqual(identity.agentFromParam(null), null); + assert.strictEqual(identity.agentFromParam(''), null); + assert.deepStrictEqual(identity.agentFromParam('{"name":"Codex","project":"ecc"}'), { name: 'Codex', project: 'ecc' }); + assert.deepStrictEqual(identity.agentFromParam('Claude Code'), { name: 'Claude Code' }); + assert.strictEqual(identity.agentFromParam('{"name":""}'), null); +}); + test('sanitizeAgentDescriptor drops junk and clamps lengths', () => { assert.strictEqual(identity.sanitizeAgentDescriptor(null), null); assert.strictEqual(identity.sanitizeAgentDescriptor({ name: ' ' }), null); diff --git a/tests/lib/ui-canvas-feedback.test.js b/tests/lib/ui-canvas-feedback.test.js index 33e49e224..f473c426f 100644 --- a/tests/lib/ui-canvas-feedback.test.js +++ b/tests/lib/ui-canvas-feedback.test.js @@ -143,6 +143,9 @@ test('exportPathsFor keeps the artifact extension and sits beside it', () => { assert.strictEqual(paths.exportPath, path.join('/work/previews', 'card.edited.html')); assert.strictEqual(paths.editsPath, path.join('/work/previews', 'card.edits.json')); assert.strictEqual(feedback.exportPathsFor('/work/card').exportPath, path.join('/work', 'card.edited.html')); + const batch = feedback.exportPathsFor('/work/previews/card.html', 'mf3k2x-9a1c'); + assert.strictEqual(batch.exportPath, path.join('/work/previews', 'card.apply-mf3k2x-9a1c.edited.html')); + assert.strictEqual(batch.editsPath, path.join('/work/previews', 'card.apply-mf3k2x-9a1c.edits.json')); }); test('writeExport writes markup and edit log atomically and rejects bad snapshots', () => { diff --git a/tests/lib/ui-canvas-server-routes.test.js b/tests/lib/ui-canvas-server-routes.test.js new file mode 100644 index 000000000..68d824349 --- /dev/null +++ b/tests/lib/ui-canvas-server-routes.test.js @@ -0,0 +1,86 @@ +/** + * Tests for the UI Canvas server pieces (scripts/lib/ui-canvas/server-routes.js): + * asset serving, export materialization, and export error mapping. + * + * Run with: node tests/lib/ui-canvas-server-routes.test.js + */ + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const routes = require('../../scripts/lib/ui-canvas/server-routes'); + +let passed = 0; +let failed = 0; +function test(name, fn) { + try { + fn(); + passed += 1; + console.log(` PASS ${name}`); + } catch (error) { + failed += 1; + console.log(` FAIL ${name}\n ${error.stack || error.message}`); + } +} + +function fakeRes() { + return { + status: null, + headers: null, + body: null, + writeHead(status, headers) { this.status = status; this.headers = headers; }, + end(body) { this.body = body; } + }; +} + +console.log('ui-canvas server routes'); + +test('serveUiAsset serves the three shell assets uncached and ignores everything else', () => { + for (const [pathname, type] of [['/ui-canvas.css', 'text/css'], ['/ui-client.js', 'text/javascript'], ['/ui-editor.js', 'text/javascript']]) { + const res = fakeRes(); + assert.strictEqual(routes.serveUiAsset(pathname, res), true, pathname); + assert.strictEqual(res.status, 200); + assert.ok(res.headers['content-type'].startsWith(type)); + assert.strictEqual(res.headers['cache-control'], 'no-store'); + assert.ok(res.body.length > 1000); + } + const res = fakeRes(); + assert.strictEqual(routes.serveUiAsset('/toString', res), false, 'prototype keys are not assets'); + assert.strictEqual(routes.serveUiAsset('/client.js', res), false); + assert.strictEqual(res.status, null); +}); + +test('materializeUiExports writes snapshots beside the artifact and strips html', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ui-canvas-routes-')); + try { + const file = path.join(dir, 'card.html'); + const items = routes.materializeUiExports({ file }, [ + { kind: 'chat', text: 'hi' }, + null, + { kind: 'edits', html: 'A', edits: [{ kind: 'nudge', selector: 'h1', dx: 1, dy: 0 }, { kind: 'bogus' }] }, + { kind: 'finish', html: 'F', edits: [], viewport: { preset: 'mobile', width: 393, height: 852 } } + ]); + assert.deepStrictEqual(items[0], { kind: 'chat', text: 'hi' }); + assert.strictEqual(items[1], null); + assert.ok(!('html' in items[2]) && !('html' in items[3])); + assert.strictEqual(items[2].edits.length, 1, 'edits are normalized'); + assert.match(path.basename(items[2].exportPath), /^card\.apply-.+\.edited\.html$/); + assert.strictEqual(fs.readFileSync(items[2].exportPath, 'utf8'), 'A'); + assert.strictEqual(items[3].exportPath, path.join(dir, 'card.edited.html')); + assert.deepStrictEqual(JSON.parse(fs.readFileSync(items[3].editsPath, 'utf8')).viewport, { preset: 'mobile', width: 393, height: 852 }); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('exportErrorResponse maps snapshot failures to HTTP answers', () => { + assert.deepStrictEqual(routes.exportErrorResponse({ code: 'EUI_HTML_TOO_LARGE' }), { status: 413, error: 'html snapshot too large' }); + assert.deepStrictEqual(routes.exportErrorResponse({ code: 'EUI_HTML_MISSING' }), { status: 400, error: 'edits and finish items need an html snapshot' }); + assert.deepStrictEqual(routes.exportErrorResponse(new Error('EACCES')), { status: 500, error: 'could not write the export next to the artifact: EACCES' }); +}); + +console.log(`\nPassed: ${passed}`); +console.log(`Failed: ${failed}`); +process.exitCode = failed > 0 ? 1 : 0; diff --git a/tests/lib/ui-canvas-ui.test.js b/tests/lib/ui-canvas-ui.test.js index 94543293e..91c730639 100644 --- a/tests/lib/ui-canvas-ui.test.js +++ b/tests/lib/ui-canvas-ui.test.js @@ -131,6 +131,47 @@ test('inspector inlines the tested field helpers and drops the old chip strip', assert.ok(!html.includes('type="number"'), 'no browser number spinners remain'); }); +test('gesture release hands the finished gesture to its handler', () => { + // Regression: mouseup cleared the shared gesture before endResize/endDrag + // read it, so every handle resize, reorder and Alt-drag threw on release. + const editor = uiEditorJs(); + assert.ok(editor.includes('function endResize(g) {') && editor.includes('function endDrag(g) {')); + assert.ok(editor.includes('endResize(g);') && editor.includes('endDrag(g);')); + const endResize = editor.slice(editor.indexOf('function endResize(g) {'), editor.indexOf('function axisOf(')); + const endDrag = editor.slice(editor.indexOf('function endDrag(g) {'), editor.indexOf('function nudgeBy(')); + for (const body of [endResize, endDrag]) assert.ok(!/\bgesture\b/.test(body), 'finish handlers must not read the cleared gesture'); +}); + +test('editor reports border-radius from real corner properties', () => { + const editor = uiEditorJs(); + assert.ok(editor.includes("['border-radius', radiusSummary(cs)]")); + assert.ok(editor.includes('cs.borderTopLeftRadius') && !editor.includes("sides(cs, 'border', '-radius')")); +}); + +test('applied edits keep replaying until the agent rewrites the file', () => { + const client = uiClientJs(); + const editor = uiEditorJs(); + assert.ok(client.includes("type: 'uc:restore', baked: submitted, edits"), 'reloads replay submitted edits'); + assert.ok(/addEventListener\('reload', \(\) => \{\s*submitted = \[\];/.test(client), 'a file change drops them'); + assert.ok(editor.includes('var baked = Array.isArray(payload.baked) ? payload.baked : [];')); +}); + +test('viewports from the bootstrap and sessionStorage are clamped', () => { + const client = uiClientJs(); + assert.ok(client.includes('const clampDim = n => Math.max(100, Math.min(20000')); + assert.ok(client.includes('let vp = storedViewport(stored.viewport) || parseViewport(')); +}); + +test('every ui-canvas source file stays under the 800-line limit', () => { + const fs = require('fs'); + const path = require('path'); + const dir = path.join(__dirname, '..', '..', 'scripts', 'lib', 'ui-canvas'); + for (const name of fs.readdirSync(dir)) { + const lines = fs.readFileSync(path.join(dir, name), 'utf8').split('\n').length; + assert.ok(lines <= 800, name + ' has ' + lines + ' lines'); + } +}); + test('theme toggle keeps its icons instead of overwriting them with text', () => { const client = uiClientJs(); assert.ok(!client.includes("$('themeBtn').textContent"), 'textContent would wipe the sun and moon icons'); diff --git a/tests/scripts/ui-canvas.test.js b/tests/scripts/ui-canvas.test.js index 7cf6d47de..d145d4e1f 100644 --- a/tests/scripts/ui-canvas.test.js +++ b/tests/scripts/ui-canvas.test.js @@ -194,8 +194,11 @@ async function main() { assert.strictEqual(item.editCount, 2); assert.ok(!('html' in item), 'html must not travel with the item'); // The session file is canonicalized (realpath), so the export sits beside the real path. - assert.strictEqual(item.exportPath, path.join(fs.realpathSync(tmp), 'card.edited.html')); - assert.strictEqual(item.editsPath, path.join(fs.realpathSync(tmp), 'card.edits.json')); + // Each Apply batch gets its own snapshot pair; only Finish owns card.edited.html. + const real = fs.realpathSync(tmp); + assert.match(path.basename(item.exportPath), /^card\.apply-[a-z0-9]+-[0-9a-f]{4}\.edited\.html$/); + assert.strictEqual(path.dirname(item.exportPath), real); + assert.strictEqual(item.editsPath, item.exportPath.replace(/\.edited\.html$/, '.edits.json')); assert.strictEqual(fs.readFileSync(item.exportPath, 'utf8'), html); const log = JSON.parse(fs.readFileSync(item.editsPath, 'utf8')); assert.strictEqual(log.kind, 'edits'); @@ -205,6 +208,18 @@ async function main() { assert.strictEqual(store.get(key).chat.at(-1).text, 'Applied 2 edits to the preview'); }); + await test('a second queued Apply never rewrites the first batch snapshot', async () => { + const first = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', html: 'A', edits: [] }] }); + const second = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', html: 'B', edits: [] }] }); + assert.strictEqual(first.statusCode, 200); + assert.strictEqual(second.statusCode, 200); + const drained = await request(port, 'GET', `/api/await?key=${key}&timeoutMs=10`); + const [a, b] = drained.body.items; + assert.notStrictEqual(a.exportPath, b.exportPath); + assert.strictEqual(fs.readFileSync(a.exportPath, 'utf8'), 'A'); + assert.strictEqual(fs.readFileSync(b.exportPath, 'utf8'), 'B'); + }); + await test('edits batches without a snapshot or with an oversized one are refused', async () => { const missing = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', edits: [] }] }); assert.strictEqual(missing.statusCode, 400); @@ -231,8 +246,13 @@ async function main() { assert.strictEqual(fs.readFileSync(item.exportPath, 'utf8').trim(), '\ndone'); assert.strictEqual(store.get(key).status, 'ended'); assert.strictEqual(store.get(key).chat.at(-1).text, 'Saved and finished with 1 edit: ship it'); + assert.strictEqual(path.basename(item.exportPath), 'card.edited.html'); const again = await request(port, 'GET', `/api/await?key=${key}&timeoutMs=10`); assert.deepStrictEqual(again.body, { status: 'ended', endedBy: 'user' }); + // A stale tab applying after Finish is refused before anything is written. + const stale = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'finish', html: 'stale', edits: [] }] }); + assert.strictEqual(stale.statusCode, 409); + assert.strictEqual(fs.readFileSync(item.exportPath, 'utf8').trim(), '\ndone'); }); await test('plan sessions still render Plan Canvas and reject ui-only kinds', async () => {