From 283c16aa4e11188d52eefc6bf0f6e7f4fedcdfad Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:20:44 -0400 Subject: [PATCH] feat(ui-canvas): add hand-editable UI mockup canvas with slider inspector Add UI Canvas: an agent writes a self-contained HTML mockup, the human edits it directly in the browser (select, resize, reorder, nudge, edit text, remove, restyle), checks mobile, desktop, and exact viewports, chats with the agent, and clicks Save and Finish to export the edited markup and an edit log. - skills/ui-canvas, commands/ui-canvas.md, bin ecc-ui-canvas (scripts/ui-canvas.js), a profile over the Plan Canvas server via a session mode of 'ui'. - scripts/lib/ui-canvas/{editor,feedback,ui,fields}.js: in-page editor, feedback normalization, browser shell, and inspector field helpers. - Inspector: grouped slider rows (size, fill, text, spacing, border, effects); double-click any value to type it, sanitized and clamped before it reaches the mockup; HSL plus alpha color sliders; per-property clear. - ECC green accent on near-black, no gradient branding; selection overlay is green. - Plan Canvas: agent identity in presence, mode-aware server and hooks. Editing conventions credit VisBug and Onlook; the review loop credits lavish-axi by @kunchenguid. --- .agents/skills/ui-canvas/SKILL.md | 224 +++ .agents/skills/ui-canvas/agents/openai.yaml | 7 + .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .gemini/GEMINI.md | 2 +- AGENTS.md | 6 +- CHANGELOG.md | 4 + COMMANDS-QUICK-REF.md | 1 + README.md | 10 +- README.zh-CN.md | 2 +- SOUL.md | 2 +- agent.yaml | 2 + commands/ui-canvas.md | 49 + docs/COMMAND-AGENT-MAP.md | 1 + docs/COMMAND-REGISTRY.json | 24 +- docs/design/ui-canvas.md | 111 ++ docs/tr/AGENTS.md | 6 +- docs/zh-CN/AGENTS.md | 6 +- docs/zh-CN/README.md | 10 +- manifests/context-packs/skill-triggers@1.json | 18 +- manifests/install-components.json | 8 + manifests/install-modules.json | 1 + manifests/pi-core.json | 2 + package-lock.json | 1 + package.json | 3 + pi/core/CURATION.md | 2 + scripts/hooks/plan-canvas-pending.js | 29 +- scripts/hooks/plan-canvas-sessions.js | 8 +- scripts/lib/plan-canvas/agent-identity.js | 53 + scripts/lib/plan-canvas/server.js | 88 +- scripts/lib/plan-canvas/sessions.js | 52 +- scripts/lib/plan-canvas/ui.js | 7 +- scripts/lib/ui-canvas/editor.js | 969 +++++++++++ scripts/lib/ui-canvas/feedback.js | 318 ++++ scripts/lib/ui-canvas/fields.js | 190 +++ scripts/lib/ui-canvas/ui.js | 1439 +++++++++++++++++ scripts/plan-canvas.js | 90 +- scripts/ui-canvas.js | 103 ++ skills/ui-canvas/SKILL.md | 224 +++ .../ui-canvas/pricing-card.edited.html | 66 + .../ui-canvas/pricing-card.edits.json | 45 + tests/fixtures/ui-canvas/pricing-card.html | 65 + tests/integration/ui-canvas-e2e.test.js | 197 +++ tests/lib/plan-canvas-agent-identity.test.js | 62 + tests/lib/ui-canvas-feedback.test.js | 175 ++ tests/lib/ui-canvas-fields.test.js | 164 ++ tests/lib/ui-canvas-ui.test.js | 142 ++ tests/scripts/npm-publish-surface.test.js | 1 + tests/scripts/ui-canvas.test.js | 304 ++++ 49 files changed, 5216 insertions(+), 81 deletions(-) create mode 100644 .agents/skills/ui-canvas/SKILL.md create mode 100644 .agents/skills/ui-canvas/agents/openai.yaml create mode 100644 commands/ui-canvas.md create mode 100644 docs/design/ui-canvas.md create mode 100644 scripts/lib/plan-canvas/agent-identity.js create mode 100644 scripts/lib/ui-canvas/editor.js create mode 100644 scripts/lib/ui-canvas/feedback.js create mode 100644 scripts/lib/ui-canvas/fields.js create mode 100644 scripts/lib/ui-canvas/ui.js create mode 100755 scripts/ui-canvas.js create mode 100644 skills/ui-canvas/SKILL.md create mode 100644 tests/fixtures/ui-canvas/pricing-card.edited.html create mode 100644 tests/fixtures/ui-canvas/pricing-card.edits.json create mode 100644 tests/fixtures/ui-canvas/pricing-card.html create mode 100644 tests/integration/ui-canvas-e2e.test.js create mode 100644 tests/lib/plan-canvas-agent-identity.test.js create mode 100644 tests/lib/ui-canvas-feedback.test.js create mode 100644 tests/lib/ui-canvas-fields.test.js create mode 100644 tests/lib/ui-canvas-ui.test.js create mode 100644 tests/scripts/ui-canvas.test.js diff --git a/.agents/skills/ui-canvas/SKILL.md b/.agents/skills/ui-canvas/SKILL.md new file mode 100644 index 000000000..1112e29a0 --- /dev/null +++ b/.agents/skills/ui-canvas/SKILL.md @@ -0,0 +1,224 @@ +--- +name: ui-canvas +description: Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You then turn the exported edited markup into the production component. Use before committing or rebuilding a feature just to check a visual change. +metadata: + origin: ECC +license: MIT +--- + +# UI Canvas + +Approve-before-you-build loop for user interface work: you write a quick, +self-contained HTML mockup of the component, the human opens it in the +browser and adjusts it by hand like a website builder, and **Save and +Finish** hands you the exact result to wire into the real code. Nobody has to +rebuild and rerun the whole app to check a padding change. + +Any component qualifies: a card, a sidebar, a modal, a settings pane, a +single button state, an animation, a page section. Any harness qualifies: +the loop is a CLI that prints JSON. + +Shares its server, state, and hooks with `plan-canvas` (inspired by +[lavish-axi](https://github.com/kunchenguid/lavish-axi) by @kunchenguid). +Editing conventions follow +[VisBug](https://github.com/GoogleChromeLabs/ProjectVisBug) and +[Onlook](https://github.com/onlook-dev/onlook): Enter/Shift+Enter walk the +tree, Delete removes, an edit/interact mode switch. + +## When to Use + +- The user asks to redesign, restyle, or add a UI component and wants to see + it before you commit, rerun, or rebuild. +- Feedback is visual ("make it tighter", "move that up", "lose the border") + and is faster done by hand than typed. +- Mobile and desktop both matter and the user wants to check the component + at exact dimensions. +- The user asks for `/ui-canvas`, a preview, a mockup, "show me first". + +Do NOT use for: plan or document review (`/plan-canvas`), running the real +app, remote URLs, or components you cannot render as plain HTML/CSS/JS in one +file. The canvas serves local files only. + +## How It Works + +Invoke the CLI as `ecc-ui-canvas` (bin from the `ecc-universal` package, on +PATH after a global or plugin install; `node "$CLAUDE_PLUGIN_ROOT/scripts/ui-canvas.js"` +also works). It runs the same detached loopback server as `plan-canvas` +(`127.0.0.1:4517`), keyed by artifact path; there are no session ids. + +### 1. Write the mockup + +Write one self-contained `.html` file (for example `.claude/previews/.html` +or next to the component): markup, a `

Plan Canvas sessions

-${sessions.length ? `${rows}
ArtifactPathStatus
` : '

No sessions yet. Ask your agent to open a plan with the plan-canvas skill.

'} +${sessions.length ? `${rows}
ArtifactPathStatus
` : '

No sessions yet. Ask your agent to open a plan with the plan-canvas skill or a mockup with the ui-canvas skill.

'} `; } module.exports = { + TOKENS_CSS, canvasCss, canvasClientJs, renderCanvasHtml, diff --git a/scripts/lib/ui-canvas/editor.js b/scripts/lib/ui-canvas/editor.js new file mode 100644 index 000000000..b9c67af60 --- /dev/null +++ b/scripts/lib/ui-canvas/editor.js @@ -0,0 +1,969 @@ +'use strict'; + +/** + * UI Canvas in-page editor: the script injected into the mockup iframe. + * + * Runs inside the sandboxed artifact frame (opaque origin, postMessage only) + * and turns the rendered component into something the reviewer can edit + * directly: hover and click to select, drag the eight handles to resize, + * drag the body to reorder, Alt-drag or arrow keys to nudge, double-click to + * edit text, Delete to remove. Every change is recorded as a structured edit + * that can be re-applied after the agent live-reloads the file, undone, and + * exported together with a clean DOM snapshot. + * + * All editor UI lives in a shadow root so it never styles, selects, or + * exports itself. Served as a string so coverage and lint treat it as data; + * it is syntax-checked by tests/lib/ui-canvas-editor.test.js. + * + * Conventions borrowed, with thanks: Enter/Shift+Enter to walk the tree and + * Delete to remove from VisBug (GoogleChromeLabs/ProjectVisBug), the + * design/preview mode split from Onlook (onlook-dev/onlook). + */ + +function uiEditorJs() { + return String.raw`'use strict'; +(() => { + if (window.parent === window) return; + if (window.__eccUiCanvasEditor) return; + window.__eccUiCanvasEditor = true; + + var post = function (msg) { window.parent.postMessage(msg, '*'); }; + + // ---- state ------------------------------------------------------------- + var mode = 'edit'; + var selected = null; + var hovered = null; + var editing = null; + var edits = []; + var redoStack = []; + var editSeq = 0; + var gesture = null; + var animationsPaused = false; + var ACCENT = '#22c55e'; + + var RESET_VALUES = { + 'background-color': 'transparent', 'background-image': 'none', 'color': 'inherit', + 'border': 'none', 'border-radius': '0', 'box-shadow': 'none', 'padding': '0', + 'margin': '0', 'gap': '0', 'font-size': 'inherit', 'font-weight': 'normal', + 'line-height': 'normal', 'opacity': '1', 'text-align': 'start', 'outline': 'none' + }; + var NON_TEXT_TAGS = { IMG: 1, VIDEO: 1, AUDIO: 1, SVG: 1, CANVAS: 1, IFRAME: 1, INPUT: 1, SELECT: 1, TEXTAREA: 1, HR: 1, BR: 1, PICTURE: 1, SOURCE: 1, OBJECT: 1, EMBED: 1 }; + + // ---- overlay host -------------------------------------------------------- + var host = document.createElement('div'); + host.setAttribute('data-ecc-ui-canvas', 'overlay'); + host.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;z-index:2147483647;pointer-events:none'; + var root = host.attachShadow({ mode: 'open' }); + root.innerHTML = '' + + '' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + var hoverBox = root.querySelector('.hover'); + var selBox = root.querySelector('.sel'); + var labelEl = selBox.querySelector('.label'); + var dropEl = root.querySelector('.drop'); + var ghostEl = root.querySelector('.ghost'); + var toastEl = root.querySelector('.toast'); + var pauseStyle = document.createElement('style'); + pauseStyle.setAttribute('data-ecc-ui-canvas', 'pause'); + pauseStyle.textContent = '*,*::before,*::after{animation-play-state:paused!important;transition:none!important}'; + + function attachHost() { if (document.body && !host.isConnected) document.body.appendChild(host); } + attachHost(); + + var toastTimer = null; + function toast(text) { + toastEl.textContent = text; + toastEl.style.display = 'block'; + clearTimeout(toastTimer); + toastTimer = setTimeout(function () { toastEl.style.display = 'none'; }, 1800); + } + + // ---- element helpers --------------------------------------------------------- + function isOurs(node) { + return node === host || (node && node.getRootNode && node.getRootNode() === root) || (node && node.hasAttribute && node.hasAttribute('data-ecc-ui-canvas')); + } + function isElement(node) { return node && node.nodeType === 1; } + function selectable(node) { + return isElement(node) && !isOurs(node) && node !== document.documentElement; + } + function esc(value) { + return (window.CSS && CSS.escape) ? CSS.escape(value) : String(value).replace(/[^a-zA-Z0-9_-]/g, function (c) { return '\\' + c; }); + } + function elementChildren(parent) { + var out = []; + for (var i = 0; i < parent.children.length; i++) if (!isOurs(parent.children[i])) out.push(parent.children[i]); + return out; + } + function indexIn(parent, el) { return elementChildren(parent).indexOf(el); } + function nthOfType(el) { + var n = 1; + var sib = el; + while ((sib = sib.previousElementSibling)) if (sib.tagName === el.tagName) n++; + return n; + } + function stepFor(el) { + var tag = el.tagName.toLowerCase(); + if (tag === 'body' || tag === 'html') return tag; + var classes = Array.prototype.filter.call(el.classList, function (c) { return /^[A-Za-z_][\w-]*$/.test(c); }).slice(0, 2); + var step = tag + classes.map(function (c) { return '.' + esc(c); }).join(''); + return step + ':nth-of-type(' + nthOfType(el) + ')'; + } + // Prefer a unique id, else a type path scoped to the nearest id. Verified + // unique so re-application after a reload lands on the same node. + function selectorFor(el) { + if (!isElement(el)) return 'body'; + if (el.id && /^[A-Za-z_][\w-]*$/.test(el.id) && document.querySelectorAll('#' + esc(el.id)).length === 1) return '#' + esc(el.id); + var parts = []; + var node = el; + while (node && isElement(node) && node !== document.documentElement) { + if (node !== el && node.id && /^[A-Za-z_][\w-]*$/.test(node.id) && document.querySelectorAll('#' + esc(node.id)).length === 1) { + parts.unshift('#' + esc(node.id)); + break; + } + parts.unshift(stepFor(node)); + if (node.tagName === 'BODY') break; + node = node.parentElement; + } + var selector = parts.join(' > '); + try { if (document.querySelectorAll(selector).length === 1) return selector; } catch (_e) { /* fall through */ } + return selector; + } + function resolve(selector) { + try { var el = document.querySelector(selector); return el && !isOurs(el) ? el : null; } catch (_e) { return null; } + } + function snippetFor(el) { + if (!isElement(el)) return ''; + if (el.tagName === 'IMG') return el.getAttribute('alt') || (el.getAttribute('src') || '').split('/').pop().slice(0, 80); + if (el.tagName === 'INPUT') return el.getAttribute('placeholder') || el.value || el.type; + return (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 120); + } + function labelFor(el) { + var tag = el.tagName.toLowerCase(); + var ident = el.id ? '#' + el.id : (el.classList.length ? '.' + Array.prototype.slice.call(el.classList, 0, 2).join('.') : ''); + return tag + ident; + } + function isTextEditable(el) { + if (!isElement(el) || NON_TEXT_TAGS[el.tagName]) return false; + if (el === document.body) return false; + for (var i = 0; i < el.childNodes.length; i++) { + var child = el.childNodes[i]; + if (child.nodeType === 3 && child.textContent.trim()) return true; + } + return el.children.length > 0 && !hasBlockChildren(el) && (el.innerText || '').trim().length > 0; + } + function hasBlockChildren(el) { + for (var i = 0; i < el.children.length; i++) { + var display = getComputedStyle(el.children[i]).display; + if (display !== 'inline' && display !== 'inline-block') return true; + } + return false; + } + function px(value) { var n = parseFloat(value); return isFinite(n) ? n : 0; } + function sides(cs, prefix, suffix) { + var t = cs.getPropertyValue(prefix + '-top' + suffix), r = cs.getPropertyValue(prefix + '-right' + suffix); + var b = cs.getPropertyValue(prefix + '-bottom' + suffix), l = cs.getPropertyValue(prefix + '-left' + suffix); + if (t === r && r === b && b === l) return t; + if (t === b && r === l) return t + ' ' + r; + return t + ' ' + r + ' ' + b + ' ' + l; + } + function borderSummary(cs) { + var width = cs.borderTopWidth; + if (px(width) === 0 && px(cs.borderRightWidth) === 0 && px(cs.borderBottomWidth) === 0 && px(cs.borderLeftWidth) === 0) return 'none'; + return width + ' ' + cs.borderTopStyle + ' ' + cs.borderTopColor; + } + function styleReport(el) { + var cs = getComputedStyle(el); + var isFlexOrGrid = cs.display.indexOf('flex') >= 0 || cs.display.indexOf('grid') >= 0; + var rows = [ + ['background-color', cs.backgroundColor], + ['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, '')], + ['box-shadow', cs.boxShadow], + ['padding', sides(cs, 'padding', '')], + ['margin', sides(cs, 'margin', '')], + ['gap', isFlexOrGrid ? (cs.rowGap === cs.columnGap ? cs.rowGap : cs.rowGap + ' ' + cs.columnGap) : null], + ['font-size', cs.fontSize], + ['font-weight', cs.fontWeight], + ['line-height', cs.lineHeight], + ['text-align', cs.textAlign], + ['opacity', cs.opacity], + ['display', cs.display] + ]; + var out = []; + for (var i = 0; i < rows.length; i++) { + if (rows[i][1] === null || rows[i][1] === undefined || rows[i][1] === '') continue; + out.push({ property: rows[i][0], value: rows[i][1], inline: el.style.getPropertyValue(rows[i][0]) || '', resettable: Object.prototype.hasOwnProperty.call(RESET_VALUES, rows[i][0]) }); + } + return out; + } + function describe(el) { + var rect = el.getBoundingClientRect(); + return { + selector: selectorFor(el), + tag: el.tagName.toLowerCase(), + id: el.id || '', + classes: Array.prototype.slice.call(el.classList, 0, 6), + snippet: snippetFor(el), + size: { width: Math.round(rect.width), height: Math.round(rect.height) }, + editable: isTextEditable(el), + isImage: el.tagName === 'IMG' + }; + } + function breadcrumbFor(el) { + var trail = []; + var node = el; + while (node && isElement(node) && node !== document.documentElement) { + trail.unshift({ selector: selectorFor(node), label: labelFor(node) }); + if (node.tagName === 'BODY') break; + node = node.parentElement; + } + return trail.slice(-6); + } + + // ---- overlay positioning ------------------------------------------------- + function place(box, rect) { + box.style.display = 'block'; + box.style.left = rect.left + 'px'; + box.style.top = rect.top + 'px'; + box.style.width = Math.max(0, rect.width) + 'px'; + box.style.height = Math.max(0, rect.height) + 'px'; + } + function updateBoxes() { + if (mode !== 'edit') { hoverBox.style.display = 'none'; selBox.style.display = 'none'; return; } + if (hovered && hovered.isConnected && hovered !== selected) place(hoverBox, hovered.getBoundingClientRect()); + else hoverBox.style.display = 'none'; + if (selected && selected.isConnected) { + var rect = selected.getBoundingClientRect(); + place(selBox, rect); + labelEl.querySelector('b').textContent = labelFor(selected); + labelEl.querySelector('span').textContent = Math.round(rect.width) + ' × ' + Math.round(rect.height); + labelEl.classList.toggle('inside', rect.top < 30); + } else { + selBox.style.display = 'none'; + if (selected && !selected.isConnected) { selected = null; postSelection(); } + } + } + var rafPending = false; + function scheduleBoxes() { + if (rafPending) return; + rafPending = true; + requestAnimationFrame(function () { rafPending = false; updateBoxes(); }); + } + + // ---- selection ----------------------------------------------------------------- + function postSelection() { + if (!selected || !selected.isConnected) { post({ type: 'uc:selection', selection: null }); return; } + var info = describe(selected); + info.styles = styleReport(selected); + info.breadcrumb = breadcrumbFor(selected); + post({ type: 'uc:selection', selection: info }); + } + function select(el) { + if (editing && editing.el !== el) commitTextEdit(); + selected = selectable(el) ? el : null; + updateBoxes(); + postSelection(); + } + function deselect() { select(null); } + + // ---- edit log ----------------------------------------------------------------- + function newEdit(kind, el, detail) { + editSeq += 1; + var edit = { id: 'e' + editSeq + '-' + Date.now().toString(36), kind: kind, selector: selectorFor(el), tag: el.tagName.toLowerCase(), snippet: snippetFor(el), at: new Date().toISOString() }; + for (var key in detail) if (Object.prototype.hasOwnProperty.call(detail, key)) edit[key] = detail[key]; + return edit; + } + function publicEdit(edit) { + var out = {}; + for (var key in edit) if (Object.prototype.hasOwnProperty.call(edit, key) && key.charAt(0) !== '_') out[key] = edit[key]; + return out; + } + function postEdits() { + post({ type: 'uc:edits', edits: edits.map(publicEdit), canUndo: edits.some(function (e) { return !e.stale; }), canRedo: redoStack.length > 0 }); + } + function record(edit) { + edits.push(edit); + redoStack = []; + postEdits(); + postSelection(); + scheduleBoxes(); + } + function insertAt(parent, el, index) { + var kids = elementChildren(parent).filter(function (k) { return k !== el; }); + var ref = index < kids.length ? kids[index] : null; + parent.insertBefore(el, ref); + } + function applyInline(el, values) { + for (var prop in values) if (Object.prototype.hasOwnProperty.call(values, prop)) { + if (values[prop] === '' || values[prop] === null || values[prop] === undefined) el.style.removeProperty(prop); + else el.style.setProperty(prop, values[prop]); + } + } + function captureInline(el, props) { + var out = {}; + for (var i = 0; i < props.length; i++) out[props[i]] = el.style.getPropertyValue(props[i]); + return out; + } + function contentBoxDelta(el, cs) { + if (cs.boxSizing === 'border-box') return { w: 0, h: 0 }; + return { + w: px(cs.paddingLeft) + px(cs.paddingRight) + px(cs.borderLeftWidth) + px(cs.borderRightWidth), + h: px(cs.paddingTop) + px(cs.paddingBottom) + px(cs.borderTopWidth) + px(cs.borderBottomWidth) + }; + } + function sizeStyles(el, width, height) { + var cs = getComputedStyle(el); + var delta = contentBoxDelta(el, cs); + var out = {}; + if (width !== undefined && width !== null) out.width = Math.max(1, Math.round(width - delta.w)) + 'px'; + if (height !== undefined && height !== null) out.height = Math.max(1, Math.round(height - delta.h)) + 'px'; + var parent = el.parentElement; + if (parent && getComputedStyle(parent).display.indexOf('flex') >= 0 && cs.flexGrow !== '0') out.flex = '0 0 auto'; + if (el.tagName === 'IMG' && (width !== undefined || height !== undefined)) { + if (width !== undefined && height === undefined) out.height = 'auto'; + out['max-width'] = 'none'; + } + return out; + } + + // Apply a recorded edit to the live document. The el argument is the element the + // edit targets (resolved by selector during re-application). Returns false + // when the document no longer matches, so the edit can be flagged stale. + function applyEdit(edit, el) { + el = el || resolve(edit.selector); + if (edit.kind === 'remove') { + if (!el) return false; + var parent = el.parentElement; + edit._el = el; + edit._parent = parent; + edit._index = indexIn(parent, el); + el.remove(); + return true; + } + if (!el) return false; + if (edit.kind === 'text') { + if (edit._htmlBefore === undefined) edit._htmlBefore = el.innerHTML; + el.innerHTML = edit.htmlAfter !== undefined ? edit.htmlAfter : ''; + if (edit.htmlAfter === undefined) el.textContent = edit.after; + edit._el = el; + return true; + } + if (edit.kind === 'resize') { + var styles = sizeStyles(el, edit.width, edit.height); + if (!edit._inlineBefore) edit._inlineBefore = captureInline(el, Object.keys(styles)); + applyInline(el, styles); + edit._el = el; + return true; + } + if (edit.kind === 'nudge') { + var cs = getComputedStyle(el); + if (!edit._inlineBefore) edit._inlineBefore = captureInline(el, ['position', 'left', 'top']); + var baseLeft = px(el.style.left), baseTop = px(el.style.top); + var next = { left: (baseLeft + edit.dx) + 'px', top: (baseTop + edit.dy) + 'px' }; + if (cs.position === 'static') next.position = 'relative'; + applyInline(el, next); + edit._el = el; + return true; + } + if (edit.kind === 'move') { + var target = resolve(edit.to.parent); + if (!target) return false; + edit._fromParent = el.parentElement; + edit._fromIndex = indexIn(el.parentElement, el); + insertAt(target, el, edit.to.index); + edit._el = el; + return true; + } + if (edit.kind === 'style') { + if (!edit._inlineBefore) edit._inlineBefore = captureInline(el, [edit.property]); + var value = edit.after === null ? RESET_VALUES[edit.property] : edit.after; + if (value === undefined) return false; + el.style.setProperty(edit.property, value); + edit._el = el; + return true; + } + return false; + } + function revertEdit(edit) { + if (edit.stale) return false; + var el = edit._el && edit._el.isConnected ? edit._el : (edit.kind === 'remove' ? edit._el : resolve(edit.selector)); + if (edit.kind === 'remove') { + if (!el || !edit._parent) return false; + insertAt(edit._parent, el, edit._index); + return true; + } + if (!el) return false; + if (edit.kind === 'text') { el.innerHTML = edit._htmlBefore !== undefined ? edit._htmlBefore : edit.before; return true; } + if (edit.kind === 'resize' || edit.kind === 'nudge' || edit.kind === 'style') { applyInline(el, edit._inlineBefore || {}); return true; } + if (edit.kind === 'move') { + if (!edit._fromParent) return false; + insertAt(edit._fromParent, el, edit._fromIndex); + return true; + } + return false; + } + function undo() { + for (var i = edits.length - 1; i >= 0; i--) { + if (edits[i].stale) continue; + var edit = edits.splice(i, 1)[0]; + revertEdit(edit); + redoStack.push(edit); + if (edit.kind === 'remove' && edit._el) select(edit._el); + toast('Undid ' + edit.kind); + break; + } + postEdits(); + postSelection(); + scheduleBoxes(); + } + function redo() { + var edit = redoStack.pop(); + if (!edit) return; + if (applyEdit(edit, edit._el && edit._el.isConnected ? edit._el : null)) { edits.push(edit); toast('Redid ' + edit.kind); } + postEdits(); + postSelection(); + scheduleBoxes(); + } + function resetAll() { + for (var i = edits.length - 1; i >= 0; i--) revertEdit(edits[i]); + edits = []; + redoStack = []; + postEdits(); + postSelection(); + scheduleBoxes(); + toast('All edits reverted'); + } + // After the agent rewrites the file the frame reloads from scratch; the + // 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 restore(payload) { + var incoming = Array.isArray(payload.edits) ? payload.edits : []; + edits = []; + redoStack = []; + 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]; + delete edit.stale; + if (!applyEdit(edit, null)) edit.stale = true; + edits.push(edit); + var seq = parseInt(String(edit.id).slice(1), 10); + if (seq > editSeq) editSeq = seq; + } + if (payload.scroll) window.scrollTo(payload.scroll.x || 0, payload.scroll.y || 0); + if (payload.selection) { var el = resolve(payload.selection); if (el) selected = el; } + updateBoxes(); + postEdits(); + postSelection(); + } + + // ---- text editing ---------------------------------------------------------- + function startTextEdit(el) { + if (!isTextEditable(el)) { toast('This element has no editable text'); return; } + if (editing) commitTextEdit(); + editing = { el: el, before: el.innerText, htmlBefore: el.innerHTML }; + el.setAttribute('contenteditable', 'true'); + el.setAttribute('data-ecc-ui-canvas-editing', ''); + el.focus(); + try { + var range = document.createRange(); + range.selectNodeContents(el); + var sel = window.getSelection(); + sel.removeAllRanges(); + sel.addRange(range); + } catch (_e) { /* selection APIs unavailable */ } + selBox.classList.add('editing'); + post({ type: 'uc:status', text: 'Editing text · Enter saves · Shift+Enter for a new line · Esc cancels' }); + } + function finishTextEdit(cancel) { + if (!editing) return; + var el = editing.el; + el.removeAttribute('contenteditable'); + el.removeAttribute('data-ecc-ui-canvas-editing'); + selBox.classList.remove('editing'); + var state = editing; + editing = null; + if (cancel) { el.innerHTML = state.htmlBefore; post({ type: 'uc:status', text: '' }); scheduleBoxes(); return; } + if (el.innerHTML !== state.htmlBefore) { + var edit = newEdit('text', el, { before: state.before, after: el.innerText, htmlAfter: el.innerHTML }); + edit._htmlBefore = state.htmlBefore; + edit._el = el; + record(edit); + toast('Text updated'); + } + post({ type: 'uc:status', text: '' }); + scheduleBoxes(); + } + 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); + } + + // ---- export ------------------------------------------------------------------- + function exportHtml() { + if (editing) commitTextEdit(); + var clone = document.documentElement.cloneNode(true); + var junk = clone.querySelectorAll('[data-ecc-ui-canvas],[data-ecc-plan-canvas]'); + for (var i = 0; i < junk.length; i++) junk[i].remove(); + var scripts = clone.querySelectorAll('script[src*="/ui-editor.js"],script[src*="/sdk.js"]'); + for (var j = 0; j < scripts.length; j++) scripts[j].remove(); + var marked = clone.querySelectorAll('[contenteditable],[data-ecc-ui-canvas-editing]'); + for (var k = 0; k < marked.length; k++) { marked[k].removeAttribute('contenteditable'); marked[k].removeAttribute('data-ecc-ui-canvas-editing'); } + clone.removeAttribute('data-ecc-ui-canvas-noselect'); + var doctype = document.doctype ? '\n' : '\n'; + return doctype + clone.outerHTML + '\n'; + } + + // ---- DOM events ---------------------------------------------------------------- + var noSelectStyle = document.createElement('style'); + noSelectStyle.setAttribute('data-ecc-ui-canvas', 'noselect'); + noSelectStyle.textContent = '[data-ecc-ui-canvas-noselect] *{user-select:none!important;cursor:inherit}'; + document.head && document.head.appendChild(noSelectStyle); + + document.addEventListener('mousemove', function (e) { + 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); + return; + } + doDrag(e); + return; + } + if (mode !== 'edit' || editing) return; + var target = e.target; + hovered = selectable(target) && !(editing && editing.el === target) ? target : null; + scheduleBoxes(); + }, true); + + document.addEventListener('mousedown', function (e) { + if (mode !== 'edit' || e.button !== 0) return; + var path = e.composedPath ? e.composedPath() : [e.target]; + var first = path[0]; + if (first && first.classList && first.classList.contains('handle') && first.getRootNode() === root) { + e.preventDefault(); + e.stopPropagation(); + startResize(first.getAttribute('data-dir'), e); + return; + } + var target = e.target; + if (editing && editing.el.contains(target)) return; + if (editing) commitTextEdit(); + if (!selectable(target)) return; + e.preventDefault(); + e.stopPropagation(); + if (target !== selected) select(target); + if (target !== document.body) startPress(target, e); + }, true); + + document.addEventListener('mouseup', function (e) { + if (!gesture) return; + var g = gesture; + gesture = null; + if (g.kind === 'resize') { endResize(); e.preventDefault(); e.stopPropagation(); return; } + if (g.kind === 'press') return; + endDrag(); + e.preventDefault(); + e.stopPropagation(); + }, true); + + document.addEventListener('click', function (e) { + if (mode !== 'edit') return; + if (editing && editing.el.contains(e.target)) return; + e.preventDefault(); + e.stopPropagation(); + }, true); + + document.addEventListener('dblclick', function (e) { + if (mode !== 'edit') return; + if (editing && editing.el.contains(e.target)) return; + if (!selectable(e.target)) return; + e.preventDefault(); + e.stopPropagation(); + select(e.target); + startTextEdit(e.target); + }, true); + + document.addEventListener('keydown', function (e) { + var meta = e.metaKey || e.ctrlKey; + if (meta && e.key.toLowerCase() === 'i' && !editing) { e.preventDefault(); post({ type: 'uc:toggle-mode' }); return; } + if (editing) { + if (e.key === 'Escape') { e.preventDefault(); finishTextEdit(true); } + else if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); commitTextEdit(); } + return; + } + if (mode !== 'edit') return; + if (meta && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) redo(); else undo(); return; } + if (meta && e.key.toLowerCase() === 'y') { e.preventDefault(); redo(); return; } + if (e.key === 'Escape') { if (selected) { e.preventDefault(); deselect(); } return; } + if (!selected) return; + if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); removeSelected(); return; } + if (e.key === 'Enter') { + e.preventDefault(); + if (e.shiftKey) { if (selected.parentElement && selectable(selected.parentElement)) select(selected.parentElement); } + else { var kids = elementChildren(selected); if (kids.length) select(kids[0]); else startTextEdit(selected); } + return; + } + if (e.key === 'Tab') { + e.preventDefault(); + var next = e.shiftKey ? selected.previousElementSibling : selected.nextElementSibling; + while (next && isOurs(next)) next = e.shiftKey ? next.previousElementSibling : next.nextElementSibling; + if (next) select(next); + return; + } + var step = e.shiftKey ? 10 : 1; + if (e.key === 'ArrowLeft') { e.preventDefault(); nudgeBy(-step, 0); } + else if (e.key === 'ArrowRight') { e.preventDefault(); nudgeBy(step, 0); } + else if (e.key === 'ArrowUp') { e.preventDefault(); nudgeBy(0, -step); } + else if (e.key === 'ArrowDown') { e.preventDefault(); nudgeBy(0, step); } + }, true); + + document.addEventListener('focusout', function (e) { + if (editing && e.target === editing.el) setTimeout(function () { if (editing && editing.el === e.target) commitTextEdit(); }, 0); + }, true); + + var scrollTimer = null; + window.addEventListener('scroll', function () { + scheduleBoxes(); + if (scrollTimer) return; + scrollTimer = setTimeout(function () { scrollTimer = null; post({ type: 'uc:scroll', x: window.scrollX, y: window.scrollY }); }, 120); + }, { passive: true, capture: true }); + window.addEventListener('resize', function () { scheduleBoxes(); post({ type: 'uc:viewport', width: window.innerWidth, height: window.innerHeight }); }); + + if (window.ResizeObserver) { + var observer = new ResizeObserver(function () { scheduleBoxes(); }); + observer.observe(document.documentElement); + } + if (window.MutationObserver) { + var mutations = new MutationObserver(function () { scheduleBoxes(); }); + mutations.observe(document.documentElement, { childList: true, subtree: true, attributes: true }); + } + + // ---- shell bridge --------------------------------------------------------------- + window.addEventListener('message', function (e) { + var msg = e.data || {}; + if (typeof msg.type !== 'string' || msg.type.indexOf('uc:') !== 0) return; + switch (msg.type) { + case 'uc:set-mode': + if (editing) commitTextEdit(); + mode = msg.mode === 'interact' ? 'interact' : 'edit'; + if (mode === 'interact') { hovered = null; } + updateBoxes(); + break; + case 'uc:restore': restore(msg); break; + case 'uc:select': { var el = resolve(msg.selector); if (el) { select(el); try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } catch (_e) { /* older engines */ } } break; } + case 'uc:deselect': deselect(); break; + case 'uc:style': setStyle(msg.property, msg.value === undefined ? null : msg.value); break; + case 'uc:size': setSize(msg.width, msg.height); break; + case 'uc:remove': removeSelected(); break; + case 'uc:edit-text': if (selected) startTextEdit(selected); break; + case 'uc:undo': undo(); break; + case 'uc:redo': redo(); break; + case 'uc:reset': resetAll(); break; + case 'uc:forget': + // The agent baked the current edits into the file: drop the log + // without touching the DOM so nothing is replayed twice. + edits = []; + redoStack = []; + postEdits(); + break; + case 'uc:pause-animations': + animationsPaused = Boolean(msg.paused); + if (animationsPaused) document.head.appendChild(pauseStyle); else pauseStyle.remove(); + break; + case 'uc:export': + post({ type: 'uc:export', requestId: msg.requestId, html: exportHtml(), edits: edits.map(publicEdit) }); + break; + case 'uc:scroll-to': window.scrollTo(msg.x || 0, msg.y || 0); break; + default: break; + } + }); + + function announceReady() { + attachHost(); + post({ type: 'uc:ready', title: document.title || '', viewport: { width: window.innerWidth, height: window.innerHeight }, scroll: { x: window.scrollX, y: window.scrollY } }); + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', announceReady); + else announceReady(); +})();`; +} + +module.exports = { uiEditorJs }; diff --git a/scripts/lib/ui-canvas/feedback.js b/scripts/lib/ui-canvas/feedback.js new file mode 100644 index 000000000..5f108c849 --- /dev/null +++ b/scripts/lib/ui-canvas/feedback.js @@ -0,0 +1,318 @@ +'use strict'; + +/** + * UI Canvas feedback schema. + * + * The browser editor records every change the human makes to a mockup as a + * structured edit and ships the edit log, plus a serialized DOM snapshot, to + * the agent through the same session queue Plan Canvas uses. This module owns + * the shape of that payload: validation of what the browser submits, the + * on-disk export of the snapshot, the one-line summaries agents and hooks + * print, and the viewport presets the shell offers. + * + * Nothing here trusts the browser. Every field is clamped, every kind is + * allow-listed, and the HTML snapshot never enters sessions.json: it is + * written next to the artifact and only its path travels with the item. + */ + +const fs = require('fs'); +const path = require('path'); + +const UI_FEEDBACK_KINDS = new Set(['chat', 'edits', 'finish']); +const EDIT_KINDS = new Set(['text', 'resize', 'move', 'nudge', 'remove', 'style']); +const VIEWPORT_IDS = new Set(['mobile', 'desktop', 'custom']); + +const MAX_EDITS = 500; +const MAX_EDIT_SUMMARIES = 60; +const MAX_HTML_BYTES = 6 * 1024 * 1024; +const MAX_SNIPPET = 200; +const MAX_SELECTOR = 500; +const MAX_TEXT = 4000; +const MAX_MARKUP = 20000; +const MAX_STYLE_VALUE = 500; +const MAX_DIMENSION = 20000; + +// CSS pixel presets. Mobile tracks the current iPhone class; desktop fills the +// stage and only falls back to these numbers when the stage is smaller. +const VIEWPORT_PRESETS = Object.freeze({ + mobile: Object.freeze({ id: 'mobile', label: 'Mobile', width: 393, height: 852 }), + desktop: Object.freeze({ id: 'desktop', label: 'Desktop', width: 1440, height: 900 }), + custom: Object.freeze({ id: 'custom', label: 'Custom', width: 1280, height: 800 }) +}); + +function clampText(value, max) { + if (typeof value !== 'string') return ''; + return value.slice(0, max); +} + +function clampInt(value, { min = 0, max = MAX_DIMENSION } = {}) { + const number = typeof value === 'number' ? value : Number.parseFloat(value); + if (!Number.isFinite(number)) return null; + return Math.min(max, Math.max(min, Math.round(number))); +} + +// A dimension of zero or less is "not provided", never a 1px viewport. +function positiveInt(value) { + const number = typeof value === 'number' ? value : Number.parseFloat(value); + if (!Number.isFinite(number) || number < 1) return null; + return Math.min(MAX_DIMENSION, Math.round(number)); +} + +function nowIso() { + return new Date().toISOString(); +} + +function normalizeAnchor(raw) { + if (!raw || typeof raw !== 'object') return null; + if (typeof raw.selector !== 'string' || !raw.selector.trim()) return null; + const anchor = { + selector: clampText(raw.selector, MAX_SELECTOR), + tag: clampText(raw.tag, 60), + snippet: clampText(raw.snippet, MAX_SNIPPET) + }; + if (raw.size && typeof raw.size === 'object') { + const width = clampInt(raw.size.width); + const height = clampInt(raw.size.height); + if (width !== null && height !== null) anchor.size = { width, height }; + } + return anchor; +} + +function normalizeViewport(raw) { + if (!raw || typeof raw !== 'object') return null; + const preset = VIEWPORT_IDS.has(raw.preset) ? raw.preset : 'custom'; + const fallback = VIEWPORT_PRESETS[preset]; + const width = positiveInt(raw.width) ?? fallback.width; + const height = positiveInt(raw.height) ?? fallback.height; + return { preset, width, height }; +} + +function normalizePosition(raw) { + if (!raw || typeof raw !== 'object') return null; + const index = clampInt(raw.index, { min: 0, max: 100000 }); + if (index === null) return null; + return { parent: clampText(raw.parent, MAX_SELECTOR), index }; +} + +// One browser-recorded edit. Returns null for anything unusable so a single +// malformed record never blocks the batch it arrived in. +function normalizeEdit(raw, position) { + if (!raw || typeof raw !== 'object') return null; + if (!EDIT_KINDS.has(raw.kind)) return null; + if (typeof raw.selector !== 'string' || !raw.selector.trim()) return null; + const edit = { + id: clampText(typeof raw.id === 'string' ? raw.id : `edit-${position + 1}`, 40), + kind: raw.kind, + selector: clampText(raw.selector, MAX_SELECTOR), + tag: clampText(raw.tag, 60), + snippet: clampText(raw.snippet, MAX_SNIPPET), + at: typeof raw.at === 'string' && raw.at ? clampText(raw.at, 40) : nowIso() + }; + if (raw.stale === true) edit.stale = true; + + switch (raw.kind) { + case 'text': { + edit.before = clampText(raw.before, MAX_TEXT); + edit.after = clampText(raw.after, MAX_TEXT); + if (typeof raw.htmlAfter === 'string') edit.htmlAfter = clampText(raw.htmlAfter, MAX_MARKUP); + return edit; + } + case 'resize': { + const width = clampInt(raw.width, { min: 1 }); + const height = clampInt(raw.height, { min: 1 }); + if (width === null && height === null) return null; + if (width !== null) edit.width = width; + if (height !== null) edit.height = height; + if (raw.before && typeof raw.before === 'object') { + edit.before = {}; + const beforeWidth = clampInt(raw.before.width, { min: 0 }); + const beforeHeight = clampInt(raw.before.height, { min: 0 }); + if (beforeWidth !== null) edit.before.width = beforeWidth; + if (beforeHeight !== null) edit.before.height = beforeHeight; + } + return edit; + } + case 'move': { + const from = normalizePosition(raw.from); + const to = normalizePosition(raw.to); + if (!from || !to) return null; + edit.from = from; + edit.to = to; + return edit; + } + case 'nudge': { + const dx = clampInt(raw.dx, { min: -MAX_DIMENSION }); + const dy = clampInt(raw.dy, { min: -MAX_DIMENSION }); + if (dx === null || dy === null) return null; + edit.dx = dx; + edit.dy = dy; + return edit; + } + case 'remove': { + edit.outerHTML = clampText(raw.outerHTML, MAX_MARKUP); + const position = normalizePosition(raw.from); + if (position) edit.from = position; + return edit; + } + case 'style': { + if (typeof raw.property !== 'string' || !/^[a-z][a-z0-9-]{0,59}$/.test(raw.property)) return null; + edit.property = raw.property; + edit.before = clampText(raw.before, MAX_STYLE_VALUE); + edit.after = raw.after === null || raw.after === undefined ? null : clampText(String(raw.after), MAX_STYLE_VALUE); + return edit; + } + default: + return null; + } +} + +function normalizeEdits(rawEdits) { + const edits = []; + for (const raw of Array.isArray(rawEdits) ? rawEdits.slice(0, MAX_EDITS) : []) { + const edit = normalizeEdit(raw, edits.length); + if (edit) edits.push(edit); + } + return edits; +} + +function where(edit) { + const label = edit.snippet ? `"${edit.snippet.slice(0, 48)}${edit.snippet.length > 48 ? '…' : ''}"` : ''; + const target = edit.tag ? `<${edit.tag}>` : ''; + return [edit.selector, target, label].filter(Boolean).join(' '); +} + +// Human-readable one-liner for an edit, used by chat transcripts, the Stop +// hook, and the agent-facing summary. Never includes markup. +function summarizeEdit(edit) { + if (!edit || typeof edit !== 'object') return ''; + const target = where(edit); + const stale = edit.stale ? ' (could not be re-applied after the last reload)' : ''; + switch (edit.kind) { + case 'text': + return `text of ${target}: "${edit.before}" → "${edit.after}"${stale}`; + case 'resize': { + const size = [edit.width !== undefined ? `${edit.width}px wide` : null, edit.height !== undefined ? `${edit.height}px tall` : null] + .filter(Boolean) + .join(', '); + const before = edit.before && (edit.before.width !== undefined || edit.before.height !== undefined) + ? ` (was ${edit.before.width ?? '?'}×${edit.before.height ?? '?'})` + : ''; + return `resized ${target} to ${size}${before}${stale}`; + } + case 'move': + return `moved ${target} from ${edit.from.parent || 'its parent'}[${edit.from.index}] to ${edit.to.parent || 'its parent'}[${edit.to.index}]${stale}`; + case 'nudge': + return `nudged ${target} by ${edit.dx}px, ${edit.dy}px${stale}`; + case 'remove': + return `removed ${target}${stale}`; + case 'style': + return edit.after === null + ? `removed ${edit.property} from ${target} (was ${edit.before || 'unset'})${stale}` + : `set ${edit.property} on ${target} to ${edit.after} (was ${edit.before || 'unset'})${stale}`; + default: + return ''; + } +} + +// Normalize one browser-submitted UI Canvas feedback item into the shape the +// agent receives. Mirrors plan-canvas's normalizeFeedbackItem contract: null +// for unusable input, never a throw. +function normalizeUiFeedbackItem(raw, counter) { + if (!raw || typeof raw !== 'object') return null; + if (!UI_FEEDBACK_KINDS.has(raw.kind)) return null; + const item = { + id: `fb-${counter}`, + kind: raw.kind, + text: clampText(raw.text, MAX_TEXT).trim(), + at: nowIso() + }; + if (raw.kind === 'chat') { + if (!item.text) return null; + const anchor = normalizeAnchor(raw.anchor); + if (anchor) item.anchor = anchor; + if (Array.isArray(raw.pendingEdits) && raw.pendingEdits.length) { + item.pendingEdits = raw.pendingEdits + .slice(0, MAX_EDIT_SUMMARIES) + .map(entry => (typeof entry === 'string' ? clampText(entry, 240) : summarizeEdit(normalizeEdit(entry, 0)))) + .filter(Boolean); + } + return item; + } + item.edits = normalizeEdits(raw.edits); + item.editCount = item.edits.length; + const viewport = normalizeViewport(raw.viewport); + if (viewport) item.viewport = viewport; + if (typeof raw.exportPath === 'string' && raw.exportPath) item.exportPath = raw.exportPath; + if (typeof raw.editsPath === 'string' && raw.editsPath) item.editsPath = raw.editsPath; + return item; +} + +function exportPathsFor(artifactFile) { + const dir = path.dirname(artifactFile); + const ext = path.extname(artifactFile); + const base = path.basename(artifactFile, ext); + return { + exportPath: path.join(dir, `${base}.edited${ext || '.html'}`), + editsPath: path.join(dir, `${base}.edits.json`) + }; +} + +function writeAtomic(file, data) { + const tmp = `${file}.tmp-${process.pid}`; + fs.writeFileSync(tmp, data); + fs.renameSync(tmp, file); +} + +// Persist the reviewer's snapshot next to the artifact so the agent (or a +// Stop hook running with no server) can read the exact DOM the human saw. +function writeExport(artifactFile, { html, edits = [], viewport = null, kind = 'edits' } = {}) { + if (typeof html !== 'string' || !html.trim()) { + throw Object.assign(new Error('html snapshot is required'), { code: 'EUI_HTML_MISSING' }); + } + const bytes = Buffer.byteLength(html, 'utf8'); + 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); + writeAtomic(exportPath, html); + writeAtomic( + editsPath, + `${JSON.stringify({ artifact: artifactFile, kind, at: nowIso(), viewport, edits }, null, 2)}\n` + ); + return { exportPath, editsPath, bytes }; +} + +function uiChatLineFor(item) { + if (item.kind === 'finish') { + const count = item.editCount || 0; + const base = `Saved and finished with ${count} edit${count === 1 ? '' : 's'}`; + return item.text ? `${base}: ${item.text}` : base; + } + if (item.kind === 'edits') { + const count = item.editCount || 0; + const base = `Applied ${count} edit${count === 1 ? '' : 's'} to the preview`; + return item.text ? `${base}: ${item.text}` : base; + } + if (item.anchor) { + const label = item.anchor.snippet || item.anchor.selector; + return `[${label}] ${item.text}`; + } + return item.text; +} + +module.exports = { + EDIT_KINDS, + MAX_EDITS, + MAX_HTML_BYTES, + UI_FEEDBACK_KINDS, + VIEWPORT_PRESETS, + exportPathsFor, + normalizeAnchor, + normalizeEdit, + normalizeEdits, + normalizeUiFeedbackItem, + normalizeViewport, + summarizeEdit, + uiChatLineFor, + writeExport +}; diff --git a/scripts/lib/ui-canvas/fields.js b/scripts/lib/ui-canvas/fields.js new file mode 100644 index 000000000..f8eb6e83f --- /dev/null +++ b/scripts/lib/ui-canvas/fields.js @@ -0,0 +1,190 @@ +'use strict'; + +/** + * UI Canvas inspector field helpers: parse, sanitize, and format the values + * a reviewer types or drags in the inspector (lengths, ratios, colors, free + * CSS text) before they reach the mockup. + * + * These are plain functions with no closure state so the browser shell can + * inline their source (see FIELD_HELPERS_JS) while Node tests exercise the + * exact same code. Keep them self-contained: no requires, no module-level + * constants, and only reference each other by name. + */ + +function clampNumber(value, min, max) { + return Math.min(max, Math.max(min, value)); +} + +function roundToStep(value, step) { + if (!step) return value; + const decimals = (String(step).split('.')[1] || '').length; + const rounded = Math.round(value / step) * step; + return Number(rounded.toFixed(Math.min(decimals, 6))); +} + +// Shortest readable form: 16, 1.5, 0.25 (no trailing zeros, at most 2 decimals). +function formatNumber(value) { + if (!Number.isFinite(value)) return ''; + return String(Number(value.toFixed(2))); +} + +/** + * Sanitize one typed number against a field spec. + * spec: { min, max, step, unit, units, ratio } + * unit default unit when none is typed ('' for unitless) + * units accepted units; anything else is rejected + * ratio value is 0..1 and the human may type 50, 50% or 0.5 + * Returns { ok: true, value, unit, css } or { ok: false, error }. + */ +function sanitizeNumber(raw, spec) { + const text = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().replace(/,/g, '.'); + if (!text) return { ok: false, error: 'Enter a number' }; + const match = text.match(/^([+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*([a-z%]*)$/); + if (!match) return { ok: false, error: 'Not a number' }; + let value = Number(match[1]); + if (!Number.isFinite(value)) return { ok: false, error: 'Not a number' }; + const units = spec.units || [spec.unit || '']; + let unit = match[2]; + if (spec.ratio) { + if (unit === '%' || value > 1) value /= 100; + else if (unit) return { ok: false, error: 'Use a percentage, like 50%' }; + unit = ''; + } else { + if (!unit) unit = spec.unit || ''; + if (units.indexOf(unit) < 0) { + const listed = units.filter(Boolean); + return { ok: false, error: listed.length ? 'Use ' + listed.join(', ') : 'Use a plain number' }; + } + } + const min = spec.min === undefined ? -Infinity : spec.min; + const max = spec.max === undefined ? Infinity : spec.max; + value = roundToStep(clampNumber(value, min, max), spec.step); + return { ok: true, value, unit, css: formatNumber(value) + unit }; +} + +/** + * Sanitize a 1-4 part box value such as padding "8 16" or margin "0 auto". + * spec: sanitizeNumber spec plus { maxParts, allowAuto }. + */ +function sanitizeBoxList(raw, spec) { + const parts = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().split(/[\s,]+/).filter(Boolean); + const maxParts = spec.maxParts || 4; + if (!parts.length) return { ok: false, error: 'Enter a value' }; + if (parts.length > maxParts) return { ok: false, error: 'Use at most ' + maxParts + ' values' }; + const out = []; + for (let i = 0; i < parts.length; i++) { + if (parts[i] === 'auto' && spec.allowAuto) { out.push('auto'); continue; } + const result = sanitizeNumber(parts[i], spec); + if (!result.ok) return result; + out.push(result.value === 0 ? '0' : result.css); + } + return { ok: true, css: out.join(' ') }; +} + +function hexPair(value) { + return Math.round(clampNumber(value, 0, 255)).toString(16).padStart(2, '0'); +} + +// Parse #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba() (comma or space syntax) +// and transparent into { r, g, b, a }. Returns null for anything else. +function parseColor(raw) { + const text = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase(); + if (text === 'transparent') return { r: 0, g: 0, b: 0, a: 0 }; + let hex = text.match(/^#?([0-9a-f]{3,8})$/); + if (hex && [3, 4, 6, 8].indexOf(hex[1].length) >= 0) { + hex = hex[1]; + if (hex.length <= 4) hex = hex.split('').map(c => c + c).join(''); + return { + r: parseInt(hex.slice(0, 2), 16), + g: parseInt(hex.slice(2, 4), 16), + b: parseInt(hex.slice(4, 6), 16), + a: hex.length === 8 ? Number((parseInt(hex.slice(6, 8), 16) / 255).toFixed(3)) : 1 + }; + } + const fn = text.match(/^rgba?\(\s*([^)]*)\)$/); + if (!fn) return null; + const nums = fn[1].split(/[\s,/]+/).filter(Boolean); + if (nums.length < 3 || nums.length > 4) return null; + const channel = part => (/%$/.test(part) ? parseFloat(part) * 2.55 : parseFloat(part)); + const rgb = nums.slice(0, 3).map(channel); + let alpha = nums.length === 4 ? (/%$/.test(nums[3]) ? parseFloat(nums[3]) / 100 : parseFloat(nums[3])) : 1; + if (rgb.some(n => !Number.isFinite(n)) || !Number.isFinite(alpha)) return null; + alpha = clampNumber(alpha, 0, 1); + return { r: Math.round(clampNumber(rgb[0], 0, 255)), g: Math.round(clampNumber(rgb[1], 0, 255)), b: Math.round(clampNumber(rgb[2], 0, 255)), a: Number(alpha.toFixed(3)) }; +} + +// '#rrggbb' when opaque, else rgba() so the mockup CSS stays readable. +function formatColor(color) { + if (color.a >= 1) return '#' + hexPair(color.r) + hexPair(color.g) + hexPair(color.b); + return 'rgba(' + Math.round(color.r) + ', ' + Math.round(color.g) + ', ' + Math.round(color.b) + ', ' + formatNumber(color.a) + ')'; +} + +// Display form for the inspector: uppercase hex, alpha shown separately. +function colorHex(color) { + return ('#' + hexPair(color.r) + hexPair(color.g) + hexPair(color.b)).toUpperCase(); +} + +function rgbToHsl(color) { + const r = color.r / 255, g = color.g / 255, b = color.b / 255; + const max = Math.max(r, g, b), min = Math.min(r, g, b); + const l = (max + min) / 2; + let h = 0, s = 0; + if (max !== min) { + const d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + if (max === r) h = (g - b) / d + (g < b ? 6 : 0); + else if (max === g) h = (b - r) / d + 2; + else h = (r - g) / d + 4; + h *= 60; + } + return { h: Math.round(h) % 360, s: Math.round(s * 100), l: Math.round(l * 100), a: color.a }; +} + +function hslToRgb(hsl) { + const h = (((hsl.h % 360) + 360) % 360) / 360, s = clampNumber(hsl.s, 0, 100) / 100, l = clampNumber(hsl.l, 0, 100) / 100; + if (s === 0) { const v = Math.round(l * 255); return { r: v, g: v, b: v, a: hsl.a }; } + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + const hue = t => { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + }; + return { r: Math.round(hue(h + 1 / 3) * 255), g: Math.round(hue(h) * 255), b: Math.round(hue(h - 1 / 3) * 255), a: hsl.a }; +} + +/** + * Sanitize typed free CSS (box-shadow, background-image, a named color). + * Rejects declaration breakers and markup so a value can never close the + * rule or smuggle another property. The browser additionally checks + * CSS.supports before applying. + */ +function sanitizeCssText(raw, maxLength) { + const text = String(raw === undefined || raw === null ? '' : raw).replace(/\s+/g, ' ').trim(); + if (!text) return { ok: false, error: 'Enter a value' }; + if (text.length > (maxLength || 300)) return { ok: false, error: 'Too long' }; + if (/[;{}<>\\]|\/\*|!important|expression\s*\(|javascript:/i.test(text)) return { ok: false, error: 'Remove ; { } < > and comments' }; + return { ok: true, css: text }; +} + +// Order matters only for readability; every helper is hoisted once inlined. +const FIELD_HELPERS = [clampNumber, roundToStep, formatNumber, sanitizeNumber, sanitizeBoxList, hexPair, parseColor, formatColor, colorHex, rgbToHsl, hslToRgb, sanitizeCssText]; +const FIELD_HELPERS_JS = FIELD_HELPERS.map(fn => fn.toString()).join('\n'); + +module.exports = { + FIELD_HELPERS_JS, + clampNumber, + colorHex, + formatColor, + formatNumber, + hslToRgb, + parseColor, + rgbToHsl, + roundToStep, + sanitizeBoxList, + sanitizeCssText, + sanitizeNumber +}; diff --git a/scripts/lib/ui-canvas/ui.js b/scripts/lib/ui-canvas/ui.js new file mode 100644 index 000000000..edc9892f4 --- /dev/null +++ b/scripts/lib/ui-canvas/ui.js @@ -0,0 +1,1439 @@ +'use strict'; + +/** + * UI Canvas browser shell: the chrome around the mockup iframe. + * + * Top bar: viewport presets (desktop, mobile, exact dimensions), edit versus + * interact mode, agent presence, undo/redo, Save and Finish. Right rail: + * inspector for the selected element (breadcrumb, size, style chips), + * the pending edit log, and the conversation with the agent. The mockup + * renders at its true CSS pixel size inside a sandboxed iframe and is scaled + * down only when the stage is too small, so media queries behave exactly as + * they would in production. + * + * Same design tokens as Plan Canvas and the ECC dashboard. Everything is + * served inline; no CDNs. + */ + +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 ICONS = { + desktop: '', + mobile: '', + custom: '', + rotate: '', + undo: '', + redo: '', + pause: '', + play: '', + reload: '', + sun: '', + moon: '', + 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'; +(() => { + const boot = JSON.parse(document.getElementById('uc-session').textContent); + const key = boot.key; + const PRESETS = boot.presets; + const $ = id => document.getElementById(id); + const frame = $('artifact'); + const device = $('device'); + const sizer = $('sizer'); + const stage = $('stage'); + const viewportEl = $('viewportArea'); + const chatLog = $('chatLog'); + const input = $('chatInput'); + const sendBtn = $('send'); + const statusEl = $('sendStatus'); + const presence = $('presence'); + const hintEl = $('hint'); + const readoutEl = $('readout'); + const STORE = 'ecc-ui-canvas:' + key; + + let ended = boot.status === 'ended'; + let sending = false; + let mode = 'edit'; + let frameReady = false; + let selection = null; + let anchorEnabled = true; + let lastScroll = { x: 0, y: 0 }; + let paused = false; + let agent = boot.agent || null; + let canUndo = false; + let canRedo = false; + let exportSeq = 0; + const exportWaiters = new Map(); + const confirmTimers = new Map(); + + // --- persisted shell state ------------------------------------------------ + function readStore() { + try { return JSON.parse(sessionStorage.getItem(STORE) || 'null') || {}; } catch (_e) { return {}; } + } + function writeStore(patch) { + try { + const next = Object.assign(readStore(), patch); + sessionStorage.setItem(STORE, JSON.stringify(next)); + } catch (_e) { /* storage blocked: the canvas still works for this page load */ } + } + const stored = readStore(); + let edits = Array.isArray(stored.edits) ? stored.edits : []; + + // --- theme -------------------------------------------------------------------- + const themeKey = 'ecc-plan-canvas:theme'; + function applyTheme(t) { + if (t === 'light') document.documentElement.setAttribute('data-theme', 'light'); + else document.documentElement.removeAttribute('data-theme'); + const label = t === 'light' ? 'Switch to dark theme' : 'Switch to light theme'; + $('themeBtn').title = label; + $('themeBtn').setAttribute('aria-label', label); + } + let theme = (() => { try { return localStorage.getItem(themeKey); } catch (_e) { return null; } })() || 'dark'; + applyTheme(theme); + $('themeBtn').addEventListener('click', () => { + theme = theme === 'light' ? 'dark' : 'light'; + try { localStorage.setItem(themeKey, theme); } catch (_e) { /* blocked */ } + applyTheme(theme); + }); + + // --- viewport ------------------------------------------------------------------ + 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 (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); + let actual = { width: vp.width, height: vp.height, scale: 1 }; + + function layoutStage() { + const rect = viewportEl.getBoundingClientRect(); + const pad = 24; + const availW = Math.max(120, rect.width - pad * 2); + const availH = Math.max(120, rect.height - pad * 2); + let width = vp.width; + let height = vp.height; + if (vp.preset === 'desktop') { + width = Math.max(320, Math.floor(availW)); + height = Math.max(240, Math.floor(availH)); + } + const bezel = vp.preset === 'mobile' ? 12 : 0; + const outerW = width + bezel * 2; + const outerH = height + bezel * 2; + const scale = vp.preset === 'desktop' ? 1 : Math.min(1, availW / outerW, availH / outerH); + device.className = 'device ' + vp.preset; + device.style.width = outerW + 'px'; + device.style.height = outerH + 'px'; + device.style.transform = 'scale(' + scale + ')'; + sizer.style.width = Math.round(outerW * scale) + 'px'; + sizer.style.height = Math.round(outerH * scale) + 'px'; + actual = { width, height, scale }; + $('vpW').value = width; + $('vpH').value = height; + $('vpScale').textContent = scale < 0.995 ? Math.round(scale * 100) + '%' : ''; + readoutEl.textContent = width + ' × ' + height + (scale < 0.995 ? ' · shown at ' + Math.round(scale * 100) + '%' : ''); + document.querySelectorAll('.seg.viewports button').forEach(b => b.setAttribute('aria-pressed', String(b.getAttribute('data-vp') === vp.preset))); + $('rotateBtn').disabled = vp.preset === 'desktop'; + writeStore({ viewport: vp }); + } + document.querySelectorAll('.seg.viewports button').forEach(btn => { + btn.addEventListener('click', () => { + const preset = btn.getAttribute('data-vp'); + if (preset === vp.preset) return; + if (preset === 'custom') vp = { preset: 'custom', width: vp.preset === 'desktop' ? actual.width : vp.width, height: vp.preset === 'desktop' ? actual.height : vp.height }; + else vp = parseViewport(preset); + layoutStage(); + }); + }); + function applyDims() { + const width = Math.max(100, Math.min(20000, parseInt($('vpW').value, 10) || actual.width)); + const height = Math.max(100, Math.min(20000, parseInt($('vpH').value, 10) || actual.height)); + vp = { preset: 'custom', width, height }; + layoutStage(); + } + [$('vpW'), $('vpH')].forEach(box => { + box.addEventListener('input', () => { + const clean = box.value.replace(/[^0-9]/g, '').slice(0, 5); + if (clean !== box.value) box.value = clean; + }); + box.addEventListener('change', applyDims); + box.addEventListener('keydown', e => { + if (e.key === 'Enter') { e.preventDefault(); applyDims(); box.blur(); } + else if (e.key === 'Escape') { e.preventDefault(); layoutStage(); box.blur(); } + else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { + e.preventDefault(); + box.value = String((parseInt(box.value, 10) || 0) + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1)); + applyDims(); + } + }); + }); + $('rotateBtn').addEventListener('click', () => { + if (vp.preset === 'desktop') return; + vp = { preset: vp.preset, width: vp.height, height: vp.width, rotated: !vp.rotated }; + layoutStage(); + }); + if (window.ResizeObserver) new ResizeObserver(() => layoutStage()).observe(viewportEl); + window.addEventListener('resize', layoutStage); + layoutStage(); + + // --- mode ----------------------------------------------------------------------- + const HINTS = { + edit: 'Click to select · double-click edits text · drag handles to resize · drag to reorder · Alt-drag or arrows nudge · Delete removes', + interact: 'Interact mode: clicks, hovers and taps reach the component. Switch back to Edit to change things.' + }; + function setMode(next) { + mode = next === 'interact' ? 'interact' : 'edit'; + document.querySelectorAll('.seg.modes button').forEach(b => b.setAttribute('aria-pressed', String(b.getAttribute('data-mode') === mode))); + stage.setAttribute('data-mode', mode); + setHint(''); + postToFrame({ type: 'uc:set-mode', mode }); + } + document.querySelectorAll('.seg.modes button').forEach(btn => btn.addEventListener('click', () => setMode(btn.getAttribute('data-mode')))); + function setHint(text) { + hintEl.classList.toggle('live', Boolean(text)); + hintEl.textContent = text || HINTS[mode]; + } + setHint(''); + + // --- frame bridge ---------------------------------------------------------------- + function postToFrame(msg) { + if (frame.contentWindow) frame.contentWindow.postMessage(msg, '*'); + } + function requestExport() { + return new Promise((resolve, reject) => { + const requestId = 'x' + (++exportSeq); + exportWaiters.set(requestId, resolve); + postToFrame({ type: 'uc:export', requestId }); + setTimeout(() => { + if (exportWaiters.delete(requestId)) reject(new Error('the preview did not answer; reload and try again')); + }, 5000); + }); + } + window.addEventListener('message', e => { + if (e.source !== frame.contentWindow) return; + const msg = e.data || {}; + if (typeof msg.type !== 'string') return; + switch (msg.type) { + case 'uc:ready': + frameReady = true; + postToFrame({ type: 'uc:set-mode', mode }); + postToFrame({ type: 'uc:restore', edits, scroll: lastScroll, selection: selection ? selection.selector : null }); + if (paused) postToFrame({ type: 'uc:pause-animations', paused: true }); + break; + case 'uc:selection': + selection = msg.selection || null; + if (selection) anchorEnabled = true; + renderInspector(); + renderAnchor(); + break; + case 'uc:edits': + edits = Array.isArray(msg.edits) ? msg.edits : []; + canUndo = Boolean(msg.canUndo); + canRedo = Boolean(msg.canRedo); + writeStore({ edits }); + renderEdits(); + break; + case 'uc:status': setHint(msg.text || ''); break; + case 'uc:toggle-mode': setMode(mode === 'edit' ? 'interact' : 'edit'); break; + case 'uc:scroll': lastScroll = { x: msg.x || 0, y: msg.y || 0 }; break; + case 'uc:export': { + const resolve = exportWaiters.get(msg.requestId); + if (resolve) { exportWaiters.delete(msg.requestId); resolve(msg); } + break; + } + default: break; + } + }); + viewportEl.addEventListener('mousedown', e => { + 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(''); + + // --- edit log ----------------------------------------------------------------------- + function summarize(edit) { + const target = edit.selector + (edit.snippet ? ' “' + edit.snippet.slice(0, 40) + (edit.snippet.length > 40 ? '…' : '') + '”' : ''); + switch (edit.kind) { + case 'text': return target + ': “' + (edit.before || '').slice(0, 40) + '” → “' + (edit.after || '').slice(0, 60) + '”'; + case 'resize': return target + ' → ' + (edit.width !== undefined ? edit.width + 'w' : '') + (edit.width !== undefined && edit.height !== undefined ? ' × ' : '') + (edit.height !== undefined ? edit.height + 'h' : '') + (edit.before ? ' (was ' + edit.before.width + ' × ' + edit.before.height + ')' : ''); + case 'move': return target + ' → ' + (edit.to && edit.to.parent ? edit.to.parent : 'parent') + ' at ' + (edit.to ? edit.to.index : '?'); + case 'nudge': return target + ' by ' + edit.dx + ', ' + edit.dy + 'px'; + case 'remove': return target; + case 'style': return target + ' ' + edit.property + (edit.after === null ? ' removed' : ' → ' + edit.after) + (edit.before ? ' (was ' + shortValue(edit.before) + ')' : ''); + default: return target; + } + } + function renderEdits() { + const list = $('editList'); + list.innerHTML = ''; + $('editCount').textContent = String(edits.length); + $('undoBtn').disabled = ended || !canUndo; + $('redoBtn').disabled = ended || !canRedo; + $('applyBtn').disabled = ended || !edits.some(e => !e.stale); + $('resetBtn').disabled = ended || !edits.length; + if (!edits.length) { + const empty = document.createElement('div'); + empty.className = 'empty'; + empty.textContent = 'Your changes to the preview collect here. Apply sends them to the agent to bake into the file; Save and Finish hands over the final design.'; + list.appendChild(empty); + return; + } + for (const edit of edits) { + const row = document.createElement('div'); + row.className = 'edit kind-' + edit.kind + (edit.stale ? ' stale' : ''); + const k = document.createElement('span'); + k.className = 'k'; + k.textContent = edit.kind; + const s = document.createElement('span'); + s.className = 's'; + s.textContent = summarize(edit); + row.title = (edit.stale ? 'Could not be re-applied after the last reload.\n' : '') + summarize(edit); + row.append(k, s); + list.appendChild(row); + } + list.scrollTop = list.scrollHeight; + } + $('undoBtn').addEventListener('click', () => postToFrame({ type: 'uc:undo' })); + $('redoBtn').addEventListener('click', () => postToFrame({ type: 'uc:redo' })); + function twoStep(btn, label, action) { + if (confirmTimers.has(btn)) { + clearTimeout(confirmTimers.get(btn)); + confirmTimers.delete(btn); + btn.classList.remove('confirm'); + btn.textContent = btn.getAttribute('data-label'); + action(); + return; + } + btn.setAttribute('data-label', btn.textContent); + btn.textContent = label; + btn.classList.add('confirm'); + confirmTimers.set(btn, setTimeout(() => { + confirmTimers.delete(btn); + btn.classList.remove('confirm'); + btn.textContent = btn.getAttribute('data-label'); + }, 3000)); + } + $('resetBtn').addEventListener('click', () => twoStep($('resetBtn'), 'Revert all?', () => postToFrame({ type: 'uc:reset' }))); + $('pauseBtn').addEventListener('click', () => { + paused = !paused; + $('pauseBtn').setAttribute('aria-pressed', String(paused)); + postToFrame({ type: 'uc:pause-animations', paused }); + }); + + // --- conversation --------------------------------------------------------------------- + const typingEl = document.createElement('div'); + typingEl.className = 'typing'; + typingEl.setAttribute('role', 'status'); + const dots = document.createElement('span'); + dots.className = 'dots'; + dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i')); + const typingLabel = document.createElement('span'); + typingLabel.className = 'label'; + typingEl.append(dots, typingLabel); + const stalledEl = document.createElement('div'); + stalledEl.className = 'stalled'; + stalledEl.setAttribute('role', 'status'); + + function agentName() { return (agent && agent.name) || 'agent'; } + function renderActivity(state) { + const typingText = state === 'thinking' ? agentName() + ' is working on it…' : state === 'typing' ? agentName() + ' is typing…' : ''; + typingEl.classList.toggle('show', Boolean(typingText)); + if (typingText) typingLabel.textContent = typingText; + const stalled = state === 'queued'; + stalledEl.classList.toggle('show', stalled); + if (stalled) stalledEl.textContent = 'Queued. ' + agentName() + ' is not listening right now and picks this up the moment it checks in.'; + if (typingText || stalled) scrollToEnd(); + } + function atBottom() { return chatLog.scrollHeight - chatLog.scrollTop - chatLog.clientHeight < 40; } + function scrollToEnd() { chatLog.scrollTop = chatLog.scrollHeight; } + function renderChat(entries) { + const pinned = atBottom(); + chatLog.innerHTML = ''; + if (!entries.length) { + const empty = document.createElement('div'); + empty.className = 'empty'; + empty.textContent = 'Select something and describe the change, or just type. Your agent answers here and the preview updates when it edits the file.'; + chatLog.appendChild(empty); + } else { + for (const entry of entries) { + const div = document.createElement('div'); + div.className = 'msg ' + (entry.role === 'agent' ? 'agent' : 'user') + ' kind-' + (entry.kind || 'chat'); + div.textContent = entry.text; + const meta = document.createElement('span'); + meta.className = 'meta'; + meta.textContent = (entry.role === 'agent' ? agentName() : 'you') + ' · ' + new Date(entry.at).toLocaleTimeString(); + div.appendChild(meta); + chatLog.appendChild(div); + } + } + chatLog.appendChild(typingEl); + chatLog.appendChild(stalledEl); + if (pinned) scrollToEnd(); + } + renderChat(boot.chat || []); + + function renderAnchor() { + const show = Boolean(selection) && anchorEnabled; + $('anchorChip').hidden = !show; + if (show) $('anchorText').textContent = selection.selector; + input.placeholder = show ? 'Describe the change to ' + selection.tag + (selection.snippet ? ' “' + selection.snippet.slice(0, 30) + '”' : '') + '…' : 'Ask your agent for a change… Enter to send, Shift+Enter for a new line'; + } + $('anchorClear').addEventListener('click', () => { anchorEnabled = false; renderAnchor(); }); + + async function postFeedback(items, endSession) { + const res = await fetch('/api/session/' + key + '/feedback', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ items, endSession: Boolean(endSession) }) + }); + if (!res.ok) { + const body = await res.json().catch(() => ({})); + throw new Error(body.error || ('HTTP ' + res.status)); + } + return res.json().catch(() => ({})); + } + function pendingSummaries() { + return edits.filter(e => !e.stale).slice(-30).map(summarize); + } + function describeDelivery(body) { + return body.presence === 'thinking' || body.presence === 'typing' || body.presence === 'listening' + ? 'Delivered. ' + agentName() + ' has it.' + : 'Queued. ' + agentName() + ' picks this up the moment it checks in.'; + } + async function sendChat() { + if (ended || sending) return; + const text = input.value.trim(); + if (!text) { statusEl.textContent = 'Type a message first.'; return; } + const item = { kind: 'chat', text }; + if (selection && anchorEnabled) item.anchor = { selector: selection.selector, tag: selection.tag, snippet: selection.snippet, size: selection.size }; + const summaries = pendingSummaries(); + if (summaries.length) item.pendingEdits = summaries; + sending = true; + sendBtn.disabled = true; + statusEl.textContent = 'Sending…'; + try { + const body = await postFeedback([item], false); + input.value = ''; + statusEl.textContent = describeDelivery(body); + if (body.presence) applyPresence(body.presence, agent); + } catch (err) { + statusEl.textContent = 'Send failed (' + err.message + ').'; + } finally { + sending = false; + sendBtn.disabled = ended; + } + } + sendBtn.addEventListener('click', sendChat); + input.addEventListener('keydown', e => { + if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChat(); } + }); + + async function sendEdits(kind) { + if (ended || sending) return; + sending = true; + sendBtn.disabled = true; + $('applyBtn').disabled = true; + $('finishBtn').disabled = true; + statusEl.textContent = kind === 'finish' ? 'Saving the final design…' : 'Capturing the preview…'; + try { + const snapshot = await requestExport(); + const item = { kind, edits: snapshot.edits || edits, html: snapshot.html, viewport: { preset: vp.preset, width: actual.width, height: actual.height } }; + const note = input.value.trim(); + if (note) item.text = note; + const body = await postFeedback([item], kind === 'finish'); + input.value = ''; + if (kind === 'finish') { + markEnded('finished'); + } else { + postToFrame({ type: 'uc:forget' }); + edits = []; + writeStore({ edits: [] }); + renderEdits(); + statusEl.textContent = describeDelivery(body) + ' The preview updates when it writes the file.'; + if (body.presence) applyPresence(body.presence, agent); + } + } catch (err) { + statusEl.textContent = (kind === 'finish' ? 'Save failed (' : 'Apply failed (') + err.message + ').'; + } finally { + sending = false; + sendBtn.disabled = ended; + $('finishBtn').disabled = ended; + renderEdits(); + } + } + $('applyBtn').addEventListener('click', () => sendEdits('edits')); + $('finishBtn').addEventListener('click', () => sendEdits('finish')); + + // --- session controls -------------------------------------------------------------------- + $('endBtn').addEventListener('click', () => twoStep($('endBtn'), 'End without saving?', async () => { + try { await fetch('/api/session/' + key + '/end', { method: 'POST' }); } catch (_e) { /* server gone */ } + })); + function reloadArtifact() { + frameReady = false; + const base = frame.getAttribute('data-artifact-src'); + frame.src = base + '?t=' + Date.now(); + } + $('reloadBtn').addEventListener('click', reloadArtifact); + function markEnded(endedBy) { + ended = true; + sendBtn.disabled = true; + input.disabled = true; + $('finishBtn').disabled = true; + $('applyBtn').disabled = true; + renderActivity('ended'); + presence.setAttribute('data-state', 'ended'); + presence.querySelector('.label').textContent = 'session ended'; + const overlay = $('endedOverlay'); + overlay.classList.add('show'); + const finished = endedBy === 'finished'; + $('endedTitle').textContent = finished ? 'Saved and handed to ' + agentName() : 'Session ended'; + $('endedWho').textContent = finished + ? 'Your edits and the final markup are on their way. The agent wires them into the real component next. You can close this tab.' + : endedBy === 'agent' ? 'Your agent closed this preview.' : 'You ended this preview. Head back to your agent session.'; + $('endedIcon').hidden = !finished; + postToFrame({ type: 'uc:set-mode', mode: 'interact' }); + if (finished) setTimeout(() => { try { window.close(); } catch (_e) { /* not script-opened */ } }, 900); + } + if (ended) markEnded(boot.endedBy); + + // --- server events ---------------------------------------------------------------------- + function presenceLabel(state) { + const name = agentName(); + return { + waiting: name === 'agent' ? 'agent not connected' : name + ' not connected', + listening: name + ' listening', + thinking: name + ' is working…', + typing: name + ' is typing…', + queued: 'queued for ' + name, + ended: 'session ended' + }[state] || state; + } + function applyPresence(state, who) { + if (ended) return; + if (who && who.name) agent = who; + presence.setAttribute('data-state', state); + presence.querySelector('.label').textContent = presenceLabel(state); + presence.title = agent && agent.project ? agentName() + ' in ' + agent.project : ''; + renderActivity(state); + } + function connectEvents() { + 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); + es.addEventListener('ended', e => { markEnded(JSON.parse(e.data).endedBy); es.close(); }); + es.onerror = () => { + if (ended) return; + renderActivity('offline'); + presence.setAttribute('data-state', 'waiting'); + presence.querySelector('.label').textContent = 'canvas server offline'; + }; + } + connectEvents(); + + // --- shell keyboard ------------------------------------------------------------------------- + document.addEventListener('keydown', e => { + const tag = (e.target && e.target.tagName) || ''; + const typing = tag === 'INPUT' || tag === 'TEXTAREA'; + const meta = e.metaKey || e.ctrlKey; + if (meta && e.key.toLowerCase() === 'i') { e.preventDefault(); setMode(mode === 'edit' ? 'interact' : 'edit'); return; } + if (typing) return; + if (meta && e.key.toLowerCase() === 'z') { e.preventDefault(); postToFrame({ type: e.shiftKey ? 'uc:redo' : 'uc:undo' }); return; } + }); + + renderInspector(); + renderEdits(); + renderAnchor(); +})();`; +} + +// The shell page: header bar, staged mockup iframe, inspector + edits + chat rail. +function renderUiCanvasHtml(session, { clientPath = '/ui-client.js', cssPath = '/ui-canvas.css' } = {}) { + const name = path.basename(session.file); + const title = session.ui && session.ui.title ? session.ui.title : name; + const bootstrap = JSON.stringify({ + key: session.key, + file: session.file, + status: session.status, + endedBy: session.endedBy || null, + chat: session.chat, + agent: session.agent || null, + ui: session.ui || { viewport: 'desktop', title: '' }, + presets: VIEWPORT_PRESETS + }).replace(/ + + + + +${escapeHtml(title)} · UI Canvas + + + + + +
+
+ + UI Canvas + ${escapeHtml(name)} +
+
+
+ + + +
+
+ × + + +
+
+
+ + +
+
+
agent not connected
+ + + + + +
+ + +
+
+
+
+
+
+ +
+
+
+
+ + + ⌘Z undo⌘I mode⌫ remove +
+

Session ended

+
+ +
+ + +`; +} + +module.exports = { ICONS, renderUiCanvasHtml, uiCanvasCss, uiClientJs }; diff --git a/scripts/plan-canvas.js b/scripts/plan-canvas.js index bc8f49d45..113d3ac8d 100755 --- a/scripts/plan-canvas.js +++ b/scripts/plan-canvas.js @@ -28,6 +28,7 @@ const { sessionKeyFor } = require('./lib/plan-canvas/sessions'); const { openBrowser } = require('./lib/platform-launch'); +const { agentDescriptor } = require('./lib/plan-canvas/agent-identity'); const { DEFAULT_HOST, createPlanCanvasServer, @@ -78,6 +79,31 @@ function valueAfter(args, name) { return index >= 0 && index + 1 < args.length ? args[index + 1] : null; } +function binForMode(mode) { + return mode === 'ui' ? 'ecc-ui-canvas' : 'ecc-plan-canvas'; +} + +// A profile is the only thing that differs between the Plan Canvas CLI and +// the UI Canvas CLI (scripts/ui-canvas.js): which session mode `open` asks +// for, what the bin is called in agent-facing hints, and the next-step text +// that teaches the agent what to do with each payload. The server, state +// dir, and transport are shared. +const PLAN_PROFILE = { + mode: 'plan', + bin: 'ecc-plan-canvas', + tag: 'plan-canvas', + usage, + nextSteps: { + open: 'Run `ecc-plan-canvas await ` and leave it running; it returns when the human sends feedback, a verdict, or ends the session.', + feedback: result => (result.sessionEnded + ? 'The user sent this feedback and ended the session. Address it and report in chat; do not reopen the canvas uninvited.' + : 'Address the feedback, then run `ecc-plan-canvas await --reply ""` to answer in the canvas and keep listening.'), + ended: result => (result.endedBy === 'user' + ? 'The user ended this review. Stop polling and deliver any remaining updates in chat; do not reopen uninvited.' + : 'Session ended. Stop polling.') + } +}; + function serverInfoPath(stateDir) { return path.join(stateDir, 'server.json'); } @@ -171,9 +197,9 @@ function sleep(ms) { // Start (or reuse) the detached canvas server and return its port. A version // mismatch after an ECC update restarts the server so browser and CLI never // disagree about the protocol. -async function ensureServer({ stateDir, port }) { +async function ensureServer({ stateDir, port, force = false }) { const health = await healthCheck(port); - if (health && health.version === VERSION) return port; + if (health && health.version === VERSION && !force) return port; if (health) { await request(port, 'POST', '/shutdown').catch(() => {}); for (let i = 0; i < 20 && (await healthCheck(port)); i++) await sleep(100); @@ -209,14 +235,24 @@ async function cmdStatus({ stateDir, port }) { return { server: `http://${DEFAULT_HOST}:${port}`, version: health.version, sessions: sessions.body.sessions }; } -async function cmdOpen(file, args, { stateDir, port }) { +async function cmdOpen(file, args, { stateDir, port }, profile = PLAN_PROFILE) { if (!file) throw new Error('open requires a file path'); if (!fs.existsSync(path.resolve(file))) throw new Error(`artifact not found: ${file}`); + if (profile.validateFile) profile.validateFile(file); await ensureServer({ stateDir, port }); - const res = await request(port, 'POST', '/api/sessions', { + const body = { file: path.resolve(file), - reopen: args.includes('--reopen') - }); + reopen: args.includes('--reopen'), + ...(profile.openBody ? profile.openBody(args) : {}) + }; + let res = await request(port, 'POST', '/api/sessions', body); + // A server from an older install reports the same version string but does + // not know this profile's mode (it answers without one). Restart it on the + // current code and open again so the browser never gets the wrong canvas. + if (res.statusCode === 200 && profile.mode !== 'plan' && res.body.mode !== profile.mode) { + await ensureServer({ stateDir, port, force: true }); + res = await request(port, 'POST', '/api/sessions', body); + } if (res.statusCode === 409) return res.body; if (res.statusCode !== 200) throw new Error(res.body.error || `open failed (HTTP ${res.statusCode})`); const url = `http://${DEFAULT_HOST}:${port}${res.body.url}`; @@ -227,15 +263,16 @@ async function cmdOpen(file, args, { stateDir, port }) { url, browser: launched ? 'launch requested' : 'not opened', browserReason: launchResult.reason, - next_step: - 'Run `ecc-plan-canvas await ` and leave it running; it returns when the human sends feedback, a verdict, or ends the session.' + next_step: profile.nextSteps.open }; } -function awaitRequest(port, key, timeoutMs) { +function awaitRequest(port, key, timeoutMs, agent = null) { if (!/^[a-f0-9]{12}$/.test(key)) throw new Error('invalid plan-canvas session key'); const params = new URLSearchParams({ key }); if (timeoutMs !== null) params.set('timeoutMs', String(timeoutMs)); + // Tell the browser who is listening so its presence pill can name the agent. + if (agent) params.set('agent', JSON.stringify(agent)); return new Promise((resolve, reject) => { const req = http.request( requestOptions(port, 'GET', `/api/await?${params}`, {}), @@ -259,7 +296,7 @@ function awaitRequest(port, key, timeoutMs) { }); } -async function cmdAwait(file, args, { stateDir, port }) { +async function cmdAwait(file, args, { stateDir, port }, profile = PLAN_PROFILE) { if (!file) throw new Error('await requires a file path'); if (!(await healthCheck(port))) { return { status: 'no-server', hint: 'no canvas server is running; use `open` first', stateDir }; @@ -271,17 +308,12 @@ async function cmdAwait(file, args, { stateDir, port }) { } const timeoutRaw = valueAfter(args, '--timeout-ms'); const timeoutMs = timeoutRaw === null ? null : Number.parseInt(timeoutRaw, 10) || 0; - process.stderr.write('[plan-canvas] waiting for human feedback... leave this running (re-run if interrupted; queued feedback is never lost)\n'); - const result = await awaitRequest(port, sessionKeyFor(canonicalizeArtifactPath(file)), timeoutMs); + process.stderr.write(`[${profile.tag}] waiting for human feedback... leave this running (re-run if interrupted; queued feedback is never lost)\n`); + const result = await awaitRequest(port, sessionKeyFor(canonicalizeArtifactPath(file)), timeoutMs, agentDescriptor()); if (result.status === 'feedback') { - result.next_step = result.sessionEnded - ? 'The user sent this feedback and ended the session. Address it and report in chat; do not reopen the canvas uninvited.' - : 'Address the feedback, then run `ecc-plan-canvas await --reply ""` to answer in the canvas and keep listening.'; + result.next_step = profile.nextSteps.feedback(result, file); } else if (result.status === 'ended') { - result.next_step = - result.endedBy === 'user' - ? 'The user ended this review. Stop polling and deliver any remaining updates in chat; do not reopen uninvited.' - : 'Session ended. Stop polling.'; + result.next_step = profile.nextSteps.ended(result, file); } return result; } @@ -305,7 +337,13 @@ function cmdPending({ stateDir }) { const waiting = store .list() .filter(session => session.status !== 'ended' && session.pending > 0) - .map(session => ({ file: session.file, pending: session.pending, updatedAt: session.updatedAt })); + .map(session => ({ + file: session.file, + mode: session.mode || 'plan', + pending: session.pending, + updatedAt: session.updatedAt, + resume: `${binForMode(session.mode)} await ${JSON.stringify(session.file)}` + })); return { status: waiting.length ? 'pending' : 'clear', sessions: waiting, @@ -366,10 +404,10 @@ async function cmdServer(args, { stateDir, port }) { return new Promise(() => {}); // run until a signal or idle shutdown } -async function main(argv = process.argv.slice(2)) { +async function main(argv = process.argv.slice(2), profile = PLAN_PROFILE) { const args = argv.slice(); if (args.includes('--help') || args.includes('-h')) { - process.stdout.write(`${usage()}\n`); + process.stdout.write(`${profile.usage()}\n`); return 0; } const command = args[0] && !args[0].startsWith('--') ? args.shift() : null; @@ -379,15 +417,15 @@ async function main(argv = process.argv.slice(2)) { const context = { stateDir, port: (recorded && recorded.port) || resolvePort() }; try { if (command === null) output(await cmdStatus(context)); - else if (command === 'open') output(await cmdOpen(args[0], args, context)); - else if (command === 'await') output(await cmdAwait(args[0], args, context)); + else if (command === 'open') output(await cmdOpen(args[0], args, context, profile)); + else if (command === 'await') output(await cmdAwait(args[0], args, context, profile)); else if (command === 'pending') output(cmdPending(context)); else if (command === 'typing') output(await cmdTyping(args[0], args, context)); else if (command === 'end') output(await cmdEnd(args[0], context)); else if (command === 'stop') output(await cmdStop(context)); else if (command === 'server') await cmdServer(args, context); else { - process.stderr.write(`Unknown command: ${command}\n\n${usage()}\n`); + process.stderr.write(`Unknown command: ${command}\n\n${profile.usage()}\n`); return 1; } return 0; @@ -403,4 +441,4 @@ if (require.main === module) { }); } -module.exports = { main, ensureServer, healthCheck }; +module.exports = { PLAN_PROFILE, binForMode, main, ensureServer, healthCheck, valueAfter }; diff --git a/scripts/ui-canvas.js b/scripts/ui-canvas.js new file mode 100755 index 000000000..8f9f4b018 --- /dev/null +++ b/scripts/ui-canvas.js @@ -0,0 +1,103 @@ +#!/usr/bin/env node +'use strict'; + +/** + * UI Canvas CLI: preview and hand-edit UI component mockups in the browser. + * + * node scripts/ui-canvas.js open components/card.html --viewport mobile + * node scripts/ui-canvas.js await components/card.html + * node scripts/ui-canvas.js await --reply "Background is now brand gray." + * node scripts/ui-canvas.js end + * + * The agent writes a self-contained HTML mockup, `open` shows it in the UI + * Canvas where the human selects, drags, resizes, edits text, deletes, and + * switches viewports, and `await` blocks until they chat, apply edits, or + * click Save and Finish. Finish delivers the edit log plus the path of the + * exported final markup; the agent turns that into the production component. + * + * Shares the Plan Canvas loopback server, state dir, and Stop/SessionStart + * hooks; only the session mode and the agent-facing guidance differ. + */ + +const { PLAN_PROFILE, main, valueAfter } = require('./plan-canvas'); + +function usage() { + return [ + 'UI Canvas - preview, hand-edit, and approve UI component mockups in the browser', + '', + 'Usage:', + ' node scripts/ui-canvas.js Show server status and sessions', + ' node scripts/ui-canvas.js open Open (or resume) a preview session', + ' node scripts/ui-canvas.js await Block until the human chats, applies edits, or finishes', + ' node scripts/ui-canvas.js pending Show feedback queued for no listener', + ' node scripts/ui-canvas.js typing Show a thinking/typing indicator in chat', + ' node scripts/ui-canvas.js end End a session as the agent', + ' node scripts/ui-canvas.js stop Shut down the shared canvas server', + ' node scripts/ui-canvas.js server Run the server in the foreground', + '', + 'Options:', + ' open: --viewport Initial viewport (default desktop)', + ' --title Tab title shown in the browser', + ' --no-open Do not launch a browser window', + ' --reopen Reopen a session the user ended from the browser', + ' await: --reply Show an agent reply in the canvas chat before waiting', + ' --timeout-ms Return {status:"waiting"} after n ms (tests/debug only)', + ' typing: --state Defaults to typing', + ' server: --port --host ', + '', + 'Finish payloads name .edited.html (final markup) and .edits.json (edit log) next to the artifact.', + 'Environment: ECC_PLAN_CANVAS_PORT, ECC_PLAN_CANVAS_STATE_DIR, ECC_PLAN_CANVAS_IDLE_MS, ECC_CANVAS_AGENT' + ].join('\n'); +} + +const UI_PROFILE = { + ...PLAN_PROFILE, + mode: 'ui', + bin: 'ecc-ui-canvas', + tag: 'ui-canvas', + usage, + validateFile(file) { + if (!/\.html?$/i.test(file)) { + throw new Error('ui-canvas opens self-contained .html mockups; write the component to an .html file first'); + } + }, + openBody(args) { + const ui = {}; + const viewport = valueAfter(args, '--viewport'); + if (viewport) ui.viewport = viewport; + const title = valueAfter(args, '--title'); + if (title) ui.title = title; + return { mode: 'ui', ui }; + }, + nextSteps: { + open: 'Run `ecc-ui-canvas await ` in the background and leave it running; it returns when the human chats, applies edits, or clicks Save and Finish.', + feedback(result) { + const items = Array.isArray(result.items) ? result.items : []; + const finish = items.find(item => item.kind === 'finish'); + const applied = items.find(item => item.kind === 'edits'); + if (finish) { + return `The human clicked Save and Finish. Read the final markup at ${finish.exportPath} (edit log: ${finish.editsPath}), reproduce that exact look in the real component with full functionality, and report in chat. Do not reopen the canvas.`; + } + if (applied) { + return `The human applied ${applied.editCount} edit(s) to the preview. Rewrite the mockup file from ${applied.exportPath} (keep it self-contained), then run \`ecc-ui-canvas await --reply ""\` to keep listening.`; + } + if (result.sessionEnded) { + return 'The human sent this and ended the preview. Address it and report in chat; do not reopen the canvas uninvited.'; + } + return 'Make the requested change in the mockup file; the preview live-reloads within a second and re-applies the human\'s pending edits. Then run `ecc-ui-canvas await --reply ""` to answer and keep listening.'; + }, + ended(result) { + return result.endedBy === 'user' + ? 'The human ended the preview without saving. Stop polling and report in chat; do not reopen uninvited.' + : 'Session ended. Stop polling.'; + } + } +}; + +if (require.main === module) { + main(process.argv.slice(2), UI_PROFILE).then(code => { + process.exitCode = code; + }); +} + +module.exports = { UI_PROFILE, main: argv => main(argv, UI_PROFILE), usage }; diff --git a/skills/ui-canvas/SKILL.md b/skills/ui-canvas/SKILL.md new file mode 100644 index 000000000..e7a500c78 --- /dev/null +++ b/skills/ui-canvas/SKILL.md @@ -0,0 +1,224 @@ +--- +name: ui-canvas +description: Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You then turn the exported edited markup into the production component. Use before committing or rebuilding a feature just to check a visual change. +metadata: + origin: ECC +version: "1.0.0" +--- + +# UI Canvas + +Approve-before-you-build loop for user interface work: you write a quick, +self-contained HTML mockup of the component, the human opens it in the +browser and adjusts it by hand like a website builder, and **Save and +Finish** hands you the exact result to wire into the real code. Nobody has to +rebuild and rerun the whole app to check a padding change. + +Any component qualifies: a card, a sidebar, a modal, a settings pane, a +single button state, an animation, a page section. Any harness qualifies: +the loop is a CLI that prints JSON. + +Shares its server, state, and hooks with `plan-canvas` (inspired by +[lavish-axi](https://github.com/kunchenguid/lavish-axi) by @kunchenguid). +Editing conventions follow +[VisBug](https://github.com/GoogleChromeLabs/ProjectVisBug) and +[Onlook](https://github.com/onlook-dev/onlook): Enter/Shift+Enter walk the +tree, Delete removes, an edit/interact mode switch. + +## When to Use + +- The user asks to redesign, restyle, or add a UI component and wants to see + it before you commit, rerun, or rebuild. +- Feedback is visual ("make it tighter", "move that up", "lose the border") + and is faster done by hand than typed. +- Mobile and desktop both matter and the user wants to check the component + at exact dimensions. +- The user asks for `/ui-canvas`, a preview, a mockup, "show me first". + +Do NOT use for: plan or document review (`/plan-canvas`), running the real +app, remote URLs, or components you cannot render as plain HTML/CSS/JS in one +file. The canvas serves local files only. + +## How It Works + +Invoke the CLI as `ecc-ui-canvas` (bin from the `ecc-universal` package, on +PATH after a global or plugin install; `node "$CLAUDE_PLUGIN_ROOT/scripts/ui-canvas.js"` +also works). It runs the same detached loopback server as `plan-canvas` +(`127.0.0.1:4517`), keyed by artifact path; there are no session ids. + +### 1. Write the mockup + +Write one self-contained `.html` file (for example `.claude/previews/.html` +or next to the component): markup, a ` + + +
+ 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 new file mode 100644 index 000000000..c83b9bc00 --- /dev/null +++ b/tests/fixtures/ui-canvas/pricing-card.edits.json @@ -0,0 +1,45 @@ +{ + "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/fixtures/ui-canvas/pricing-card.html b/tests/fixtures/ui-canvas/pricing-card.html new file mode 100644 index 000000000..c553eefd1 --- /dev/null +++ b/tests/fixtures/ui-canvas/pricing-card.html @@ -0,0 +1,65 @@ + + + + + +Pricing card mockup + + + +
+ Plan illustration +
+ Most popular +

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/integration/ui-canvas-e2e.test.js b/tests/integration/ui-canvas-e2e.test.js new file mode 100644 index 000000000..bb8cf32ce --- /dev/null +++ b/tests/integration/ui-canvas-e2e.test.js @@ -0,0 +1,197 @@ +/** + * End-to-end test for UI Canvas through the real CLI (scripts/ui-canvas.js) + * and a real detached canvas server, with the browser side simulated over + * the same HTTP surface the shell uses. + * + * Flow under test: + * agent: open --no-open --viewport mobile → server starts, ui session opens + * agent: open on a markdown file → refused before touching the server + * agent: await (blocking child) → long poll, agent identity recorded + * browser: POST chat with anchor → await resolves with ui guidance + * agent: await --reply + browser finish → export written, finish guidance + * agent: pending / status / end / stop + * + * Run with: node tests/integration/ui-canvas-e2e.test.js + */ + +const assert = require('assert'); +const fs = require('fs'); +const http = require('http'); +const os = require('os'); +const path = require('path'); +const { spawn, spawnSync } = require('child_process'); + +const CLI = path.join(__dirname, '..', '..', 'scripts', 'ui-canvas.js'); + +const results = []; +async function test(name, fn) { + try { + await fn(); + console.log(` ✓ ${name}`); + results.push(true); + } catch (err) { + console.log(` ✗ ${name}`); + console.log(` Error: ${err.stack || err.message}`); + results.push(false); + } +} + +function cli(env, args, { timeoutMs = 15000 } = {}) { + const result = spawnSync('node', [CLI, ...args], { encoding: 'utf8', timeout: timeoutMs, env: { ...process.env, ...env } }); + let parsed = null; + try { parsed = JSON.parse(result.stdout.trim()); } catch { /* callers assert */ } + return { ...result, parsed }; +} + +function request(port, method, requestPath, body = null) { + return new Promise((resolve, reject) => { + const payload = body === null ? null : JSON.stringify(body); + const req = http.request( + { host: '127.0.0.1', port, method, path: requestPath, headers: payload ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) } : {} }, + res => { + let data = ''; + res.on('data', chunk => { data += chunk; }); + res.on('end', () => { + try { resolve({ statusCode: res.statusCode, body: JSON.parse(data.trim() || '{}') }); } catch { resolve({ statusCode: res.statusCode, body: data }); } + }); + } + ); + req.on('error', reject); + if (payload) req.write(payload); + req.end(); + }); +} + +function startAwait(env, file, extra = []) { + const child = spawn('node', [CLI, 'await', file, ...extra], { env: { ...process.env, ...env, ECC_CANVAS_AGENT: 'Test Harness' } }); + let stdout = ''; + child.stdout.on('data', chunk => { stdout += chunk; }); + child.stderr.on('data', () => {}); + const done = new Promise(resolve => child.on('close', () => resolve(stdout))); + return { child, done }; +} + +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +async function main() { + console.log('ui-canvas e2e'); + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ui-canvas-e2e-')); + const stateDir = path.join(tmp, 'state'); + const port = 20000 + Math.floor(Math.random() * 20000); + const env = { ECC_PLAN_CANVAS_STATE_DIR: stateDir, ECC_PLAN_CANVAS_PORT: String(port) }; + const mockup = path.join(tmp, 'card.html'); + fs.writeFileSync(mockup, '

Hi

'); + let key = null; + + try { + await test('open refuses non-HTML before starting a server', async () => { + const plan = path.join(tmp, 'plan.md'); + fs.writeFileSync(plan, '# plan'); + const res = cli(env, ['open', plan, '--no-open']); + assert.ok(res.parsed && /\.html/.test(res.parsed.error), res.stdout); + assert.strictEqual(cli(env, []).parsed.server, 'not running'); + }); + + await test('open starts the shared server and opens a ui session', async () => { + const res = cli(env, ['open', mockup, '--no-open', '--viewport', 'mobile', '--title', 'Card']); + assert.strictEqual(res.parsed.status, 'open', res.stdout); + assert.match(res.parsed.url, new RegExp(`^http://127\\.0\\.0\\.1:${port}/canvas/[a-f0-9]{12}$`)); + assert.match(res.parsed.next_step, /ecc-ui-canvas await/); + key = res.parsed.url.split('/').pop(); + const status = cli(env, []); + assert.strictEqual(status.parsed.sessions[0].mode, 'ui'); + const state = JSON.parse(fs.readFileSync(path.join(stateDir, 'sessions.json'), 'utf8')); + assert.deepStrictEqual(state.sessions[key].ui, { viewport: 'mobile', title: 'Card' }); + }); + + await test('await records the agent and resolves with ui guidance on chat', async () => { + const waiting = startAwait(env, mockup); + await sleep(500); + const sessions = await request(port, 'GET', '/api/sessions'); + assert.strictEqual(sessions.body.sessions[0].agent.name, 'Test Harness'); + await request(port, 'POST', `/api/session/${key}/feedback`, { + items: [{ kind: 'chat', text: 'make it gray', anchor: { selector: '#card', tag: 'article', snippet: 'Hi' }, pendingEdits: ['removed h1'] }] + }); + const out = JSON.parse(await waiting.done); + assert.strictEqual(out.status, 'feedback'); + assert.strictEqual(out.items[0].anchor.selector, '#card'); + assert.match(out.next_step, /live-reloads/); + assert.match(out.next_step, /ecc-ui-canvas await --reply/); + }); + + await test('await --reply lands in chat and finish delivers export paths', async () => { + const waiting = startAwait(env, mockup, ['--reply', 'Gray it is.']); + await sleep(500); + const sessions = await request(port, 'GET', '/api/sessions'); + assert.strictEqual(sessions.body.sessions[0].status, 'open'); + await request(port, 'POST', `/api/session/${key}/feedback`, { + items: [{ kind: 'finish', html: '\n

Hi

\n', edits: [{ kind: 'style', selector: '#card', property: 'background-color', before: 'white', after: '#333' }], viewport: { preset: 'mobile', width: 393, height: 852 } }], + endSession: true + }); + const out = JSON.parse(await waiting.done); + assert.strictEqual(out.sessionEnded, true); + const finish = out.items[0]; + assert.strictEqual(finish.kind, 'finish'); + assert.strictEqual(finish.exportPath, path.join(fs.realpathSync(tmp), 'card.edited.html')); + assert.ok(fs.existsSync(finish.exportPath)); + assert.match(out.next_step, /Save and Finish/); + assert.ok(out.next_step.includes(finish.exportPath)); + const state = JSON.parse(fs.readFileSync(path.join(stateDir, 'sessions.json'), 'utf8')); + const chat = state.sessions[key].chat.map(entry => entry.text); + assert.ok(chat.includes('Gray it is.')); + assert.ok(chat.includes('Saved and finished with 1 edit')); + }); + + await test('a user-finished session refuses a plain reopen and reports ended on await', async () => { + const reopen = cli(env, ['open', mockup, '--no-open']); + assert.strictEqual(reopen.parsed.status, 'user-ended'); + const ended = cli(env, ['await', mockup, '--timeout-ms', '200']); + assert.strictEqual(ended.parsed.status, 'ended'); + assert.match(ended.parsed.next_step, /ended the preview/); + }); + + await test('pending lists ui sessions with a ui-canvas resume command', async () => { + const other = path.join(tmp, 'sidebar.html'); + fs.writeFileSync(other, ''); + const opened = cli(env, ['open', other, '--no-open']); + assert.strictEqual(opened.parsed.status, 'open'); + const otherKey = opened.parsed.url.split('/').pop(); + await request(port, 'POST', `/api/session/${otherKey}/feedback`, { items: [{ kind: 'chat', text: 'queued for nobody' }] }); + const pending = cli(env, ['pending']); + assert.strictEqual(pending.parsed.status, 'pending'); + assert.strictEqual(pending.parsed.sessions[0].mode, 'ui'); + assert.strictEqual(pending.parsed.sessions[0].resume, `ecc-ui-canvas await ${JSON.stringify(fs.realpathSync(other))}`); + const ended = cli(env, ['end', other]); + assert.strictEqual(ended.parsed.status, 'ended'); + }); + + await test('stop shuts the shared server down', async () => { + const stop = cli(env, ['stop']); + assert.strictEqual(stop.parsed.status, 'stopping'); + let gone = false; + for (let i = 0; i < 30 && !gone; i++) { + await sleep(100); + gone = cli(env, []).parsed.server === 'not running'; + } + assert.ok(gone, 'server should stop listening after stop'); + }); + } finally { + cli(env, ['stop']); + fs.rmSync(tmp, { recursive: true, force: true }); + } + + const passed = results.filter(Boolean).length; + const failed = results.length - passed; + console.log('\n' + '='.repeat(40)); + console.log(`Passed: ${passed}`); + console.log(`Failed: ${failed}`); + console.log('='.repeat(40)); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch(err => { + console.error(err); + console.log('Passed: 0'); + console.log('Failed: 1'); + process.exit(1); +}); diff --git a/tests/lib/plan-canvas-agent-identity.test.js b/tests/lib/plan-canvas-agent-identity.test.js new file mode 100644 index 000000000..f03049736 --- /dev/null +++ b/tests/lib/plan-canvas-agent-identity.test.js @@ -0,0 +1,62 @@ +/** + * Tests for harness detection shown in the canvas presence pill + * (scripts/lib/plan-canvas/agent-identity.js). + * + * Run with: node tests/lib/plan-canvas-agent-identity.test.js + */ + +const assert = require('assert'); +const path = require('path'); + +const identity = require('../../scripts/lib/plan-canvas/agent-identity'); + +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}`); + } +} + +console.log('plan-canvas agent identity'); + +test('detectAgentName recognizes each harness marker and falls back to agent', () => { + assert.strictEqual(identity.detectAgentName({}), 'agent'); + assert.strictEqual(identity.detectAgentName({ CLAUDECODE: '1' }), 'Claude Code'); + assert.strictEqual(identity.detectAgentName({ CODEX_SANDBOX: 'seatbelt' }), 'Codex'); + assert.strictEqual(identity.detectAgentName({ CURSOR_TRACE_ID: 'x' }), 'Cursor'); + assert.strictEqual(identity.detectAgentName({ GEMINI_CLI: '1' }), 'Gemini CLI'); + assert.strictEqual(identity.detectAgentName({ OPENCODE: '1' }), 'OpenCode'); + assert.strictEqual(identity.detectAgentName({ COPILOT_AGENT: '1' }), 'Copilot'); + assert.strictEqual(identity.detectAgentName({ KIMI_CLI: '1' }), 'Kimi'); + assert.strictEqual(identity.detectAgentName({ QWEN_CODE: '1' }), 'Qwen Code'); + assert.strictEqual(identity.detectAgentName({ CLAUDECODE: '' }), 'agent', 'empty markers do not count'); +}); + +test('ECC_CANVAS_AGENT overrides detection and is clamped', () => { + assert.strictEqual(identity.detectAgentName({ CLAUDECODE: '1', ECC_CANVAS_AGENT: ' Fleet worker 3 ' }), 'Fleet worker 3'); + assert.strictEqual(identity.detectAgentName({ ECC_CANVAS_AGENT: 'x'.repeat(100) }).length, 60); +}); + +test('agentDescriptor reports the name and the project basename only', () => { + const descriptor = identity.agentDescriptor({ env: { CODEX_THREAD_ID: 't' }, cwd: path.join('/Users', 'someone', 'repos', 'shop') }); + assert.deepStrictEqual(descriptor, { name: 'Codex', project: 'shop' }); +}); + +test('sanitizeAgentDescriptor drops junk and clamps lengths', () => { + assert.strictEqual(identity.sanitizeAgentDescriptor(null), null); + assert.strictEqual(identity.sanitizeAgentDescriptor({ name: ' ' }), null); + assert.deepStrictEqual(identity.sanitizeAgentDescriptor({ name: ' Claude Code ', project: 'ecc', extra: 1 }), { name: 'Claude Code', project: 'ecc' }); + const long = identity.sanitizeAgentDescriptor({ name: 'n'.repeat(80), project: 'p'.repeat(200) }); + assert.strictEqual(long.name.length, 60); + assert.strictEqual(long.project.length, 120); +}); + +console.log(`\nPassed: ${passed}`); +console.log(`Failed: ${failed}`); +process.exitCode = failed > 0 ? 1 : 0; diff --git a/tests/lib/ui-canvas-feedback.test.js b/tests/lib/ui-canvas-feedback.test.js new file mode 100644 index 000000000..33e49e224 --- /dev/null +++ b/tests/lib/ui-canvas-feedback.test.js @@ -0,0 +1,175 @@ +/** + * Unit tests for the UI Canvas feedback schema (scripts/lib/ui-canvas/feedback.js). + * + * Run with: node tests/lib/ui-canvas-feedback.test.js + */ + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const feedback = require('../../scripts/lib/ui-canvas/feedback'); + +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}`); + } +} + +console.log('ui-canvas feedback'); + +test('normalizeEdit accepts every supported kind and clamps fields', () => { + const text = feedback.normalizeEdit({ kind: 'text', selector: '#t', tag: 'h1', snippet: 'x'.repeat(500), before: 'Old', after: 'New', htmlAfter: 'New' }, 0); + assert.strictEqual(text.kind, 'text'); + assert.strictEqual(text.snippet.length, 200); + assert.strictEqual(text.htmlAfter, 'New'); + assert.strictEqual(text.id, 'edit-1'); + + const resize = feedback.normalizeEdit({ kind: 'resize', selector: 'img.art', width: '220.4', height: 180, before: { width: 260, height: 260 } }, 3); + assert.deepStrictEqual([resize.width, resize.height, resize.before], [220, 180, { width: 260, height: 260 }]); + + const move = feedback.normalizeEdit({ kind: 'move', selector: 'button', from: { parent: 'div.a', index: 2 }, to: { parent: 'div.b', index: 0 } }, 0); + assert.deepStrictEqual(move.to, { parent: 'div.b', index: 0 }); + + const nudge = feedback.normalizeEdit({ kind: 'nudge', selector: 'p', dx: -4, dy: 10.6 }, 0); + assert.deepStrictEqual([nudge.dx, nudge.dy], [-4, 11]); + + const remove = feedback.normalizeEdit({ kind: 'remove', selector: 'button.secondary', outerHTML: '', from: { parent: 'div.actions', index: 1 } }, 0); + assert.strictEqual(remove.outerHTML, ''); + assert.strictEqual(remove.from.index, 1); + + const style = feedback.normalizeEdit({ kind: 'style', selector: '#card', property: 'border', before: '2px solid rgb(1, 2, 3)', after: null, stale: true }, 0); + assert.strictEqual(style.after, null); + assert.strictEqual(style.stale, true); +}); + +test('normalizeEdit rejects unknown kinds, bad selectors, and bad properties', () => { + assert.strictEqual(feedback.normalizeEdit({ kind: 'bogus', selector: 'x' }, 0), null); + assert.strictEqual(feedback.normalizeEdit({ kind: 'text', selector: '' }, 0), null); + assert.strictEqual(feedback.normalizeEdit({ kind: 'style', selector: 'x', property: 'Background;drop' }, 0), null); + assert.strictEqual(feedback.normalizeEdit({ kind: 'resize', selector: 'x' }, 0), null); + assert.strictEqual(feedback.normalizeEdit({ kind: 'move', selector: 'x', from: { index: 0 } }, 0), null); + assert.strictEqual(feedback.normalizeEdit(null, 0), null); +}); + +test('normalizeEdits caps the batch and drops unusable records', () => { + const raw = Array.from({ length: feedback.MAX_EDITS + 20 }, (_, i) => ({ kind: i % 2 ? 'nudge' : 'bogus', selector: 'p', dx: 1, dy: 1 })); + const edits = feedback.normalizeEdits(raw); + assert.ok(edits.length <= feedback.MAX_EDITS); + assert.ok(edits.every(edit => edit.kind === 'nudge')); +}); + +test('summarizeEdit renders a readable, markup-free line per kind', () => { + const lines = [ + feedback.summarizeEdit({ kind: 'text', selector: 'h1', tag: 'h1', snippet: 'Team plan', before: 'Team plan', after: 'Team plan+' }), + feedback.summarizeEdit({ kind: 'resize', selector: 'img.art', tag: 'img', width: 220, height: 220, before: { width: 260, height: 260 } }), + feedback.summarizeEdit({ kind: 'move', selector: 'button', from: { parent: 'div.a', index: 1 }, to: { parent: 'div.b', index: 0 } }), + feedback.summarizeEdit({ kind: 'nudge', selector: 'p', dx: 3, dy: -2 }), + feedback.summarizeEdit({ kind: 'remove', selector: 'button.secondary', tag: 'button', stale: true }), + feedback.summarizeEdit({ kind: 'style', selector: '#card', property: 'border', before: '2px solid', after: null }), + feedback.summarizeEdit({ kind: 'style', selector: '#card', property: 'background-color', before: 'white', after: '#333' }) + ]; + assert.match(lines[0], /text of h1

"Team plan": "Team plan" → "Team plan\+"/); + assert.match(lines[1], /resized img\.art to 220px wide, 220px tall \(was 260×260\)/); + assert.match(lines[2], /moved button from div\.a\[1\] to div\.b\[0\]/); + assert.match(lines[3], /nudged p by 3px, -2px/); + assert.match(lines[4], /removed button\.secondary ', from: { parent: '#card', index: 1 } }, + { kind: 'nonsense', selector: 'z' } + ] + }] + }); + assert.strictEqual(fb.statusCode, 200); + const delivered = await parked; + const item = delivered.body.items[0]; + assert.strictEqual(item.kind, 'edits'); + 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')); + assert.strictEqual(fs.readFileSync(item.exportPath, 'utf8'), html); + const log = JSON.parse(fs.readFileSync(item.editsPath, 'utf8')); + assert.strictEqual(log.kind, 'edits'); + assert.strictEqual(log.edits.length, 2); + assert.deepStrictEqual(log.viewport, { preset: 'mobile', width: 393, height: 852 }); + assert.ok(!JSON.stringify(JSON.parse(fs.readFileSync(store.stateFile, 'utf8'))).includes(' { + const missing = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', edits: [] }] }); + assert.strictEqual(missing.statusCode, 400); + const huge = await request(port, 'POST', `/api/session/${key}/feedback`, { items: [{ kind: 'edits', edits: [], html: 'x'.repeat(6 * 1024 * 1024 + 10) }] }); + assert.strictEqual(huge.statusCode, 413); + assert.strictEqual(store.get(key).pendingFeedback.length, 0, 'nothing queued on refusal'); + }); + + await test('finish ends the session for the user and is delivered with export paths', async () => { + const parked = request(port, 'GET', `/api/await?key=${key}`); + await sleep(30); + const fb = await request(port, 'POST', `/api/session/${key}/feedback`, { + items: [{ kind: 'finish', text: 'ship it', html: '\ndone\n', edits: [{ kind: 'nudge', selector: 'h1', dx: 2, dy: 0 }], viewport: { preset: 'desktop', width: 1412, height: 806 } }], + endSession: true + }); + assert.strictEqual(fb.statusCode, 200); + const delivered = await parked; + assert.strictEqual(delivered.body.status, 'feedback'); + assert.strictEqual(delivered.body.sessionEnded, true); + assert.strictEqual(delivered.body.endedBy, 'user'); + const item = delivered.body.items[0]; + assert.strictEqual(item.kind, 'finish'); + assert.strictEqual(item.text, 'ship it'); + 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'); + const again = await request(port, 'GET', `/api/await?key=${key}&timeoutMs=10`); + assert.deepStrictEqual(again.body, { status: 'ended', endedBy: 'user' }); + }); + + await test('plan sessions still render Plan Canvas and reject ui-only kinds', async () => { + const plan = path.join(tmp, 'notes.html'); + fs.writeFileSync(plan, '

plan

'); + const open = await request(port, 'POST', '/api/sessions', { file: plan }); + assert.strictEqual(open.body.mode, 'plan'); + const shell = await request(port, 'GET', `/canvas/${open.body.key}`, null, { raw: true }); + assert.ok(shell.body.includes('Approve plan')); + const art = await request(port, 'GET', `/artifact/${open.body.key}/`, null, { raw: true }); + assert.ok(art.body.includes('/sdk.js') && !art.body.includes('/ui-editor.js')); + const fb = await request(port, 'POST', `/api/session/${open.body.key}/feedback`, { items: [{ kind: 'finish', html: '', edits: [] }] }); + assert.strictEqual(fb.body.accepted, 0, 'finish is not a plan-canvas kind'); + const list = await request(port, 'GET', '/', null, { raw: true }); + assert.ok(list.body.includes('ui canvas'), 'session list tags ui sessions'); + }); + + await test('sanitizeUiOptions keeps known presets and WxH, defaults otherwise', () => { + assert.deepStrictEqual(sanitizeUiOptions({ viewport: 'mobile', title: ' Card ' }), { viewport: 'mobile', title: 'Card' }); + assert.deepStrictEqual(sanitizeUiOptions({ viewport: '800x600' }), { viewport: '800x600', title: '' }); + assert.deepStrictEqual(sanitizeUiOptions({ viewport: 'javascript:alert(1)' }, { viewport: 'custom', title: 'old' }), { viewport: 'custom', title: 'old' }); + assert.deepStrictEqual(sanitizeUiOptions(null), { viewport: 'desktop', title: '' }); + }); + + await test('Stop hook describes ui batches and points at the ui-canvas bin', () => { + assert.strictEqual( + pendingHook.describeItem({ kind: 'finish', editCount: 2, exportPath: '/p/card.edited.html', editsPath: '/p/card.edits.json' }), + 'SAVED AND FINISHED (2 edits) - final markup: /p/card.edited.html, edit log: /p/card.edits.json' + ); + assert.strictEqual(pendingHook.describeItem({ kind: 'edits', edits: [{}], text: 'note' }), 'APPLIED EDITS TO THE PREVIEW (1 edit): note'); + assert.strictEqual(pendingHook.describeItem({ kind: 'chat', text: 'gray', anchor: { snippet: 'Card' } }), 'on "Card": gray'); + const reason = pendingHook.buildReason([{ file: '/p/card.html', mode: 'ui', messages: ['x'], sessionEnded: false }]); + assert.match(reason, /^UI Canvas:/); + assert.match(reason, /ecc-ui-canvas await "\/p\/card\.html" --reply/); + const finished = pendingHook.buildReason([{ file: '/p/card.html', mode: 'ui', messages: ['x'], sessionEnded: true }]); + assert.match(finished, /reproduce that exact design/); + const mixed = pendingHook.buildReason([{ file: '/p/a.md', mode: 'plan', messages: ['x'], sessionEnded: false }, { file: '/p/card.html', mode: 'ui', messages: ['y'], sessionEnded: false }]); + assert.match(mixed, /^Plan Canvas:/); + assert.match(mixed, /ecc-plan-canvas await "\/p\/a\.md"/); + }); + + await test('SessionStart hook tags ui sessions and names the ui-canvas resume command', () => { + const context = sessionsHook.buildContext([ + { file: '/p/plan.md', pendingFeedback: [] }, + { file: '/p/card.html', mode: 'ui', pendingFeedback: [{}, {}] } + ]); + assert.match(context, /\/p\/card\.html \[ui canvas\] \(2 undelivered feedback items\)/); + assert.match(context, /node scripts\/ui-canvas\.js await /); + const planOnly = sessionsHook.buildContext([{ file: '/p/plan.md', pendingFeedback: [] }]); + assert.ok(!planOnly.includes('ui-canvas')); + }); + } finally { + await canvas.close().catch(() => {}); + fs.rmSync(tmp, { recursive: true, force: true }); + } + + const passed = results.filter(Boolean).length; + const failed = results.length - passed; + console.log(`\nPassed: ${passed}`); + console.log(`Failed: ${failed}`); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch(error => { + console.error(error); + console.log('Passed: 0'); + console.log('Failed: 1'); + process.exit(1); +});