mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 08:15:29 +00:00
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.
This commit is contained in:
49 files changed
+5216
-81
No files matched your search
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Plan Canvas undelivered-feedback guard (Stop)
|
||||
* Plan Canvas and UI Canvas undelivered-feedback guard (Stop)
|
||||
*
|
||||
* Cross-platform (Windows, macOS, Linux)
|
||||
*
|
||||
@@ -193,26 +193,45 @@ function describeItem(item) {
|
||||
const where = anchor.snippet || anchor.selector || 'the artifact';
|
||||
return item.text ? `on "${where}": ${item.text}` : null;
|
||||
}
|
||||
// UI Canvas batches: the snapshot lives on disk; only paths travel here.
|
||||
if (item.kind === 'finish' || item.kind === 'edits') {
|
||||
const count = Number(item.editCount) || (Array.isArray(item.edits) ? item.edits.length : 0);
|
||||
const label = item.kind === 'finish' ? 'SAVED AND FINISHED' : 'APPLIED EDITS TO THE PREVIEW';
|
||||
const where = [item.exportPath ? `final markup: ${item.exportPath}` : null, item.editsPath ? `edit log: ${item.editsPath}` : null]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
return `${label} (${count} edit${count === 1 ? '' : 's'})${where ? ` - ${where}` : ''}${item.text ? `: ${item.text}` : ''}`;
|
||||
}
|
||||
if (item.kind === 'chat' && item.anchor && item.text) {
|
||||
const where = item.anchor.snippet || item.anchor.selector;
|
||||
return where ? `on "${where}": ${item.text}` : item.text;
|
||||
}
|
||||
return item.text || null;
|
||||
}
|
||||
|
||||
function buildReason(delivered) {
|
||||
const allUi = delivered.length > 0 && delivered.every(entry => entry.mode === 'ui');
|
||||
const lines = [
|
||||
'Plan Canvas: the human sent feedback in the browser that was never delivered to you.',
|
||||
`${allUi ? 'UI Canvas' : 'Plan Canvas'}: the human sent feedback in the browser that was never delivered to you.`,
|
||||
'Handle it now instead of ending the turn.',
|
||||
''
|
||||
];
|
||||
for (const entry of delivered) {
|
||||
const bin = entry.mode === 'ui' ? 'ecc-ui-canvas' : 'ecc-plan-canvas';
|
||||
lines.push(`Artifact: ${entry.file}`);
|
||||
for (const text of entry.messages.slice(0, MAX_ITEMS_REPORTED)) lines.push(` - ${text}`);
|
||||
const extra = entry.messages.length - MAX_ITEMS_REPORTED;
|
||||
if (extra > 0) lines.push(` - (+${extra} more)`);
|
||||
if (entry.sessionEnded) {
|
||||
if (entry.sessionEnded && entry.mode === 'ui') {
|
||||
lines.push(' The user saved and finished (or ended) this preview after sending. Read the exported markup');
|
||||
lines.push(' named above, reproduce that exact design in the real component, and report back in your');
|
||||
lines.push(' normal reply; do not reopen the canvas.');
|
||||
} else if (entry.sessionEnded) {
|
||||
lines.push(' The user ended this review after sending. Address the feedback and report back in');
|
||||
lines.push(' your normal reply; do not reopen the canvas.');
|
||||
} else {
|
||||
lines.push(' Reply IN THE CANVAS so the human sees it, and keep listening, with one command:');
|
||||
lines.push(` ecc-plan-canvas await ${JSON.stringify(entry.file)} --reply "<what you did>"`);
|
||||
lines.push(` ${bin} await ${JSON.stringify(entry.file)} --reply "<what you did>"`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
@@ -229,7 +248,7 @@ async function collectDeliveries(sessions, port) {
|
||||
if (!result) continue;
|
||||
const messages = result.items.map(describeItem).filter(Boolean);
|
||||
if (messages.length === 0) continue;
|
||||
delivered.push({ file: session.file, messages, sessionEnded: Boolean(result.sessionEnded) });
|
||||
delivered.push({ file: session.file, mode: session.mode === 'ui' ? 'ui' : 'plan', messages, sessionEnded: Boolean(result.sessionEnded) });
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Plan Canvas open-session surfacing (SessionStart)
|
||||
* Plan Canvas and UI Canvas open-session surfacing (SessionStart)
|
||||
*
|
||||
* Cross-platform (Windows, macOS, Linux)
|
||||
*
|
||||
@@ -58,11 +58,15 @@ function buildContext(sessions) {
|
||||
];
|
||||
for (const session of sessions.slice(0, 5)) {
|
||||
const pending = session.pendingFeedback && session.pendingFeedback.length;
|
||||
lines.push(` - ${session.file}${pending ? ` (${pending} undelivered feedback item${pending === 1 ? '' : 's'})` : ''}`);
|
||||
const tag = session.mode === 'ui' ? ' [ui canvas]' : '';
|
||||
lines.push(` - ${session.file}${tag}${pending ? ` (${pending} undelivered feedback item${pending === 1 ? '' : 's'})` : ''}`);
|
||||
}
|
||||
lines.push(
|
||||
'Resume with `node scripts/plan-canvas.js await <file>` (plan-canvas skill), or `end <file>` if the review is obsolete.'
|
||||
);
|
||||
if (sessions.some(session => session.mode === 'ui')) {
|
||||
lines.push('Sessions tagged [ui canvas] resume with `node scripts/ui-canvas.js await <file>` (ui-canvas skill) instead.');
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Which coding agent is driving a canvas session.
|
||||
*
|
||||
* The browser shows "Claude Code · listening" instead of an anonymous pill so
|
||||
* the human can tell which terminal to look at. Detection is best effort and
|
||||
* environment-based: every harness exports at least one distinctive variable
|
||||
* into the shells it spawns. `ECC_CANVAS_AGENT` overrides the guess outright.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const HARNESS_MARKERS = [
|
||||
['Claude Code', ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_SSE_PORT']],
|
||||
['Codex', ['CODEX_SANDBOX', 'CODEX_SANDBOX_NETWORK_DISABLED', 'CODEX_THREAD_ID', 'CODEX_CI']],
|
||||
['Cursor', ['CURSOR_AGENT', 'CURSOR_TRACE_ID', 'CURSOR_SESSION_ID']],
|
||||
['Gemini CLI', ['GEMINI_CLI', 'GEMINI_CLI_SESSION']],
|
||||
['OpenCode', ['OPENCODE', 'OPENCODE_SESSION_ID', 'OPENCODE_SERVER_URL']],
|
||||
['Copilot', ['COPILOT_AGENT', 'GITHUB_COPILOT_CLI', 'COPILOT_CLI_SESSION']],
|
||||
['Kimi', ['KIMI_CLI', 'KIMI_SESSION_ID']],
|
||||
['Qwen Code', ['QWEN_CODE', 'QWEN_CLI']]
|
||||
];
|
||||
|
||||
function detectAgentName(env = process.env) {
|
||||
const override = env.ECC_CANVAS_AGENT;
|
||||
if (typeof override === 'string' && override.trim()) return override.trim().slice(0, 60);
|
||||
for (const [name, markers] of HARNESS_MARKERS) {
|
||||
if (markers.some(marker => typeof env[marker] === 'string' && env[marker] !== '')) return name;
|
||||
}
|
||||
return 'agent';
|
||||
}
|
||||
|
||||
// Compact descriptor the CLI attaches to `await` so the server can show who
|
||||
// is listening. The cwd is reduced to its basename: enough to tell projects
|
||||
// apart without leaking a full path into the browser.
|
||||
function agentDescriptor({ env = process.env, cwd = process.cwd() } = {}) {
|
||||
return {
|
||||
name: detectAgentName(env),
|
||||
project: path.basename(cwd) || cwd
|
||||
};
|
||||
}
|
||||
|
||||
function sanitizeAgentDescriptor(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const name = typeof raw.name === 'string' ? raw.name.trim().slice(0, 60) : '';
|
||||
if (!name) return null;
|
||||
const descriptor = { name };
|
||||
if (typeof raw.project === 'string' && raw.project.trim()) descriptor.project = raw.project.trim().slice(0, 120);
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
module.exports = { HARNESS_MARKERS, agentDescriptor, detectAgentName, sanitizeAgentDescriptor };
|
||||
@@ -24,11 +24,18 @@ const {
|
||||
renderMarkdownArtifactHtml,
|
||||
renderSessionListHtml
|
||||
} = require('./ui');
|
||||
const { sanitizeAgentDescriptor } = require('./agent-identity');
|
||||
const { uiEditorJs } = require('../ui-canvas/editor');
|
||||
const { renderUiCanvasHtml, uiCanvasCss, uiClientJs } = require('../ui-canvas/ui');
|
||||
const { normalizeEdits, writeExport } = require('../ui-canvas/feedback');
|
||||
|
||||
const DEFAULT_PORT = 4517;
|
||||
const DEFAULT_HOST = '127.0.0.1';
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
const MAX_BODY_BYTES = 1024 * 1024;
|
||||
// UI Canvas ships a serialized DOM snapshot with its edit batches, and a
|
||||
// mockup with inline images can run to a few megabytes; the snapshot itself is
|
||||
// capped separately in ui-canvas/feedback.js.
|
||||
const MAX_BODY_BYTES = 8 * 1024 * 1024;
|
||||
// How long the "agent is thinking" indicator survives without the agent
|
||||
// checking back in, before presence decays to the honest queued/waiting.
|
||||
const DEFAULT_THINKING_STALE_MS = 90 * 1000;
|
||||
@@ -229,6 +236,25 @@ function readSiblingAsset(baseDir, resolved) {
|
||||
return { data, realTarget };
|
||||
}
|
||||
|
||||
// UI Canvas edit batches arrive with the full DOM snapshot. Write it (and the
|
||||
// edit log) next to the artifact before the item is queued, and hand the agent
|
||||
// paths instead of megabytes of markup. Chat items pass through untouched.
|
||||
function materializeUiExports(session, items) {
|
||||
return items.map(item => {
|
||||
if (!item || typeof item !== 'object' || (item.kind !== 'edits' && item.kind !== 'finish')) return item;
|
||||
// The on-disk log holds the same normalized edits the agent receives.
|
||||
const edits = normalizeEdits(item.edits);
|
||||
const written = writeExport(session.file, {
|
||||
html: item.html,
|
||||
edits,
|
||||
viewport: item.viewport || null,
|
||||
kind: item.kind
|
||||
});
|
||||
const { html: _html, ...rest } = item;
|
||||
return { ...rest, edits, exportPath: written.exportPath, editsPath: written.editsPath };
|
||||
});
|
||||
}
|
||||
|
||||
function createPlanCanvasServer({
|
||||
store,
|
||||
host = DEFAULT_HOST,
|
||||
@@ -291,10 +317,15 @@ function createPlanCanvasServer({
|
||||
for (const client of clients) client.write(frameText);
|
||||
}
|
||||
|
||||
function presencePayload(key) {
|
||||
const session = store.get(key);
|
||||
return { state: presenceFor(key), agent: (session && session.agent) || null };
|
||||
}
|
||||
|
||||
function broadcastPresence(key) {
|
||||
const state = presenceFor(key);
|
||||
lastPresence.set(key, state);
|
||||
broadcast(key, 'presence', { state });
|
||||
const payload = presencePayload(key);
|
||||
lastPresence.set(key, payload.state);
|
||||
broadcast(key, 'presence', payload);
|
||||
}
|
||||
|
||||
// Re-broadcast only where an expiry actually changed the answer, so an
|
||||
@@ -406,7 +437,15 @@ function createPlanCanvasServer({
|
||||
if (!fs.existsSync(path.resolve(body.file))) {
|
||||
return sendJson(res, 404, { error: `artifact not found: ${body.file}` });
|
||||
}
|
||||
const { session, refused } = store.open(body.file, { reopen: Boolean(body.reopen) });
|
||||
const mode = body.mode === 'ui' ? 'ui' : 'plan';
|
||||
if (mode === 'ui' && !/\.html?$/i.test(body.file)) {
|
||||
return sendJson(res, 400, { error: 'ui canvas sessions require an .html artifact' });
|
||||
}
|
||||
const { session, refused } = store.open(body.file, {
|
||||
reopen: Boolean(body.reopen),
|
||||
mode,
|
||||
ui: body.ui && typeof body.ui === 'object' ? body.ui : null
|
||||
});
|
||||
if (refused) {
|
||||
return sendJson(res, 409, {
|
||||
status: 'user-ended',
|
||||
@@ -420,6 +459,7 @@ function createPlanCanvasServer({
|
||||
status: 'open',
|
||||
key: session.key,
|
||||
file: session.file,
|
||||
mode: session.mode || 'plan',
|
||||
url: `/canvas/${session.key}`
|
||||
});
|
||||
}
|
||||
@@ -436,6 +476,12 @@ function createPlanCanvasServer({
|
||||
const session = keyParam ? store.get(keyParam) : store.findByFile(file);
|
||||
if (!session) return sendJson(res, 200, { status: 'missing' });
|
||||
const key = session.key;
|
||||
const agentParam = url.searchParams.get('agent');
|
||||
if (agentParam) {
|
||||
let descriptor = null;
|
||||
try { descriptor = sanitizeAgentDescriptor(JSON.parse(agentParam)); } catch { descriptor = sanitizeAgentDescriptor({ name: agentParam }); }
|
||||
if (descriptor) store.setAgent(key, descriptor);
|
||||
}
|
||||
const timeoutRaw = url.searchParams.get('timeoutMs');
|
||||
const timeoutMs = timeoutRaw === null ? null : Math.max(0, Number.parseInt(timeoutRaw, 10) || 0);
|
||||
|
||||
@@ -517,7 +563,17 @@ function createPlanCanvasServer({
|
||||
|
||||
if (action === 'feedback') {
|
||||
const body = await readJsonBody(req);
|
||||
const result = store.queueFeedback(key, body.items, { endSession: Boolean(body.endSession) });
|
||||
let items = Array.isArray(body.items) ? body.items : [];
|
||||
if (session.mode === 'ui') {
|
||||
try {
|
||||
items = materializeUiExports(session, items);
|
||||
} catch (error) {
|
||||
if (error.code === 'EUI_HTML_TOO_LARGE') return sendJson(res, 413, { error: 'html snapshot too large' });
|
||||
if (error.code === 'EUI_HTML_MISSING') return sendJson(res, 400, { error: 'edits and finish items need an html snapshot' });
|
||||
return sendJson(res, 500, { error: `could not write the export next to the artifact: ${error.message}` });
|
||||
}
|
||||
}
|
||||
const result = store.queueFeedback(key, items, { endSession: Boolean(body.endSession) });
|
||||
if (!result) return sendJson(res, 409, { error: 'session already ended' });
|
||||
wake.emit(`wake:${key}`);
|
||||
broadcast(key, 'chat-sync', { chat: store.get(key).chat });
|
||||
@@ -581,7 +637,7 @@ function createPlanCanvasServer({
|
||||
connection: 'keep-alive'
|
||||
});
|
||||
res.write(`event: chat-sync\ndata: ${JSON.stringify({ chat: session.chat })}\n\n`);
|
||||
res.write(`event: presence\ndata: ${JSON.stringify({ state: presenceFor(key) })}\n\n`);
|
||||
res.write(`event: presence\ndata: ${JSON.stringify(presencePayload(key))}\n\n`);
|
||||
if (!sseClients.has(key)) sseClients.set(key, new Set());
|
||||
sseClients.get(key).add(res);
|
||||
lastPresence.set(key, presenceFor(key));
|
||||
@@ -621,7 +677,9 @@ function createPlanCanvasServer({
|
||||
});
|
||||
return sendHtml(res, 200, html, { csp: 'artifact' });
|
||||
}
|
||||
const sdkTag = '<script src="/sdk.js"></script>';
|
||||
const sdkTag = session.mode === 'ui'
|
||||
? '<script src="/ui-editor.js" data-ecc-ui-canvas="editor"></script>'
|
||||
: '<script src="/sdk.js"></script>';
|
||||
const injected = content.includes('</body>')
|
||||
? content.replace('</body>', `${sdkTag}\n</body>`)
|
||||
: `${content}\n${sdkTag}`;
|
||||
@@ -696,11 +754,23 @@ function createPlanCanvasServer({
|
||||
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(artifactSdkJs());
|
||||
}
|
||||
if (req.method === 'GET' && pathname === '/ui-canvas.css') {
|
||||
res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(uiCanvasCss());
|
||||
}
|
||||
if (req.method === 'GET' && pathname === '/ui-client.js') {
|
||||
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(uiClientJs());
|
||||
}
|
||||
if (req.method === 'GET' && pathname === '/ui-editor.js') {
|
||||
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
||||
return res.end(uiEditorJs());
|
||||
}
|
||||
const canvasMatch = pathname.match(/^\/canvas\/([a-f0-9]{12})$/);
|
||||
if (req.method === 'GET' && canvasMatch) {
|
||||
const session = store.get(canvasMatch[1]);
|
||||
if (!session) return sendHtml(res, 404, '<h1>Unknown session</h1>');
|
||||
return sendHtml(res, 200, renderCanvasHtml(session));
|
||||
return sendHtml(res, 200, session.mode === 'ui' ? renderUiCanvasHtml(session) : renderCanvasHtml(session));
|
||||
}
|
||||
const eventsMatch = pathname.match(/^\/events\/([a-f0-9]{12})$/);
|
||||
if (req.method === 'GET' && eventsMatch) {
|
||||
|
||||
@@ -13,8 +13,15 @@ const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const { normalizeUiFeedbackItem, uiChatLineFor } = require('../ui-canvas/feedback');
|
||||
const { sanitizeAgentDescriptor } = require('./agent-identity');
|
||||
|
||||
const FEEDBACK_KINDS = new Set(['chat', 'annotation', 'verdict']);
|
||||
const VERDICTS = new Set(['approve', 'request-changes']);
|
||||
// A session renders either as a Plan Canvas review (markdown or HTML with the
|
||||
// annotation layer) or as a UI Canvas editing surface (HTML mockup with the
|
||||
// in-page editor). Both share one server, one state file, and one queue.
|
||||
const SESSION_MODES = new Set(['plan', 'ui']);
|
||||
|
||||
// The producer and the SessionStart/Stop hooks must land on one directory. The
|
||||
// hooks resolve CLAUDE_CONFIG_DIR (they cannot require this file: managed
|
||||
@@ -138,7 +145,7 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
// Open (or resume) a session. A session the *user* ended from the browser
|
||||
// is sticky: it refuses a plain reopen so agents do not pop the browser
|
||||
// back up uninvited. Pass reopen:true only when the human asked.
|
||||
function open(filePath, { reopen = false } = {}) {
|
||||
function open(filePath, { reopen = false, mode = 'plan', ui = null } = {}) {
|
||||
const canonical = canonicalizeArtifactPath(filePath);
|
||||
const key = sessionKeyFor(canonical);
|
||||
const existing = state.sessions[key];
|
||||
@@ -152,6 +159,12 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
pendingFeedback: [],
|
||||
createdAt: nowIso()
|
||||
};
|
||||
session.mode = SESSION_MODES.has(mode) ? mode : 'plan';
|
||||
if (session.mode === 'ui') {
|
||||
session.ui = sanitizeUiOptions(ui, existing && existing.ui);
|
||||
} else {
|
||||
delete session.ui;
|
||||
}
|
||||
session.status = 'open';
|
||||
delete session.endedBy;
|
||||
session.updatedAt = nowIso();
|
||||
@@ -160,21 +173,36 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
return { session, refused: false };
|
||||
}
|
||||
|
||||
// Record which agent process is (or was last) listening on a session so the
|
||||
// browser can name it. Kept in state so a reconnecting browser sees it too.
|
||||
function setAgent(key, descriptor) {
|
||||
const session = get(key);
|
||||
if (!session) return null;
|
||||
const agent = sanitizeAgentDescriptor(descriptor);
|
||||
if (!agent) return session.agent || null;
|
||||
agent.seenAt = nowIso();
|
||||
session.agent = agent;
|
||||
persist();
|
||||
return agent;
|
||||
}
|
||||
|
||||
// Queue feedback from the browser. Chat-shaped items are mirrored into the
|
||||
// session transcript immediately so the conversation panel stays coherent
|
||||
// across reloads.
|
||||
function queueFeedback(key, rawItems, { endSession = false } = {}) {
|
||||
const session = get(key);
|
||||
if (!session || session.status === 'ended') return null;
|
||||
const normalize = session.mode === 'ui' ? normalizeUiFeedbackItem : normalizeFeedbackItem;
|
||||
const describe = session.mode === 'ui' ? uiChatLineFor : chatLineFor;
|
||||
const accepted = [];
|
||||
for (const raw of Array.isArray(rawItems) ? rawItems : []) {
|
||||
state.feedbackCounter += 1;
|
||||
const item = normalizeFeedbackItem(raw, state.feedbackCounter);
|
||||
const item = normalize(raw, state.feedbackCounter);
|
||||
if (item) accepted.push(item);
|
||||
}
|
||||
session.pendingFeedback.push(...accepted);
|
||||
for (const item of accepted) {
|
||||
session.chat.push({ role: 'user', kind: item.kind, text: chatLineFor(item), at: item.at });
|
||||
session.chat.push({ role: 'user', kind: item.kind, text: describe(item), at: item.at });
|
||||
}
|
||||
if (endSession) {
|
||||
session.status = 'ended';
|
||||
@@ -237,9 +265,11 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
return Object.values(state.sessions).map(session => ({
|
||||
key: session.key,
|
||||
file: session.file,
|
||||
mode: session.mode || 'plan',
|
||||
status: session.status,
|
||||
endedBy: session.endedBy,
|
||||
pending: session.pendingFeedback.length,
|
||||
agent: session.agent || null,
|
||||
updatedAt: session.updatedAt
|
||||
}));
|
||||
}
|
||||
@@ -257,12 +287,26 @@ function createSessionStore({ stateDir = resolveStateDir() } = {}) {
|
||||
queueFeedback,
|
||||
takeFeedback,
|
||||
addAgentReply,
|
||||
setAgent,
|
||||
end,
|
||||
list,
|
||||
hasOpenSessions
|
||||
};
|
||||
}
|
||||
|
||||
// UI Canvas options travel with the session so a reconnecting browser opens
|
||||
// on the viewport the agent asked for. Unknown presets fall back to desktop.
|
||||
function sanitizeUiOptions(raw, previous) {
|
||||
const base = previous && typeof previous === 'object' ? { ...previous } : {};
|
||||
const input = raw && typeof raw === 'object' ? raw : {};
|
||||
const out = { viewport: base.viewport || 'desktop', title: base.title || '' };
|
||||
if (typeof input.viewport === 'string' && /^(mobile|desktop|custom|\d{2,5}x\d{2,5})$/.test(input.viewport.trim())) {
|
||||
out.viewport = input.viewport.trim();
|
||||
}
|
||||
if (typeof input.title === 'string' && input.title.trim()) out.title = sanitizeText(input.title.trim(), 120);
|
||||
return out;
|
||||
}
|
||||
|
||||
// One-line rendering of a feedback item for the conversation transcript.
|
||||
function chatLineFor(item) {
|
||||
if (item.kind === 'verdict') {
|
||||
@@ -277,9 +321,11 @@ function chatLineFor(item) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SESSION_MODES,
|
||||
canonicalizeArtifactPath,
|
||||
createSessionStore,
|
||||
normalizeFeedbackItem,
|
||||
resolveStateDir,
|
||||
sanitizeUiOptions,
|
||||
sessionKeyFor
|
||||
};
|
||||
@@ -589,7 +589,8 @@ function renderSessionListHtml(sessions) {
|
||||
const link = s.status === 'ended'
|
||||
? escapeHtml(path.basename(s.file))
|
||||
: `<a href="/canvas/${escapeHtml(s.key)}">${escapeHtml(path.basename(s.file))}</a>`;
|
||||
return `<tr><td>${link}</td><td class="mono">${escapeHtml(s.file)}</td><td><span class="badge ${escapeHtml(s.status)}">${status}</span></td></tr>`;
|
||||
const mode = s.mode === 'ui' ? '<span class="badge mode">ui canvas</span> ' : '';
|
||||
return `<tr><td>${mode}${link}</td><td class="mono">${escapeHtml(s.file)}</td><td><span class="badge ${escapeHtml(s.status)}">${status}</span></td></tr>`;
|
||||
}).join('\n');
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
@@ -609,17 +610,19 @@ ${TOKENS_CSS}
|
||||
.mono{font-family:var(--mono);font-size:11.5px;color:var(--text2)}
|
||||
.badge{font-size:11px;padding:2px 8px;border-radius:99px;background:var(--bg3);border:1px solid var(--border);color:var(--text2)}
|
||||
.badge.open,.badge.feedback{color:var(--green);border-color:var(--green);background:var(--green-glow)}
|
||||
.badge.mode{color:var(--pink);border-color:var(--pink);background:var(--pink-glow);margin-right:6px}
|
||||
.empty{margin-top:24px;color:var(--text3);font-size:13px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<span class="logo">E</span><h1>Plan Canvas sessions</h1>
|
||||
${sessions.length ? `<table><thead><tr><th>Artifact</th><th>Path</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<p class="empty">No sessions yet. Ask your agent to open a plan with the plan-canvas skill.</p>'}
|
||||
${sessions.length ? `<table><thead><tr><th>Artifact</th><th>Path</th><th>Status</th></tr></thead><tbody>${rows}</tbody></table>` : '<p class="empty">No sessions yet. Ask your agent to open a plan with the plan-canvas skill or a mockup with the ui-canvas skill.</p>'}
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TOKENS_CSS,
|
||||
canvasCss,
|
||||
canvasClientJs,
|
||||
renderCanvasHtml,
|
||||
|
||||
@@ -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 = '' +
|
||||
'<style>' +
|
||||
':host{all:initial}' +
|
||||
'.hover{position:fixed;pointer-events:none;display:none;border:1px dashed ' + ACCENT + ';border-radius:3px;box-sizing:border-box}' +
|
||||
'.sel{position:fixed;pointer-events:none;display:none;outline:2px solid ' + ACCENT + ';outline-offset:-1px;border-radius:3px;box-sizing:border-box}' +
|
||||
'.sel.editing{outline-style:dashed}' +
|
||||
'.sel.dragging{opacity:.35}' +
|
||||
'.handle{position:absolute;width:10px;height:10px;margin:-5px;background:#fff;border:1.5px solid ' + ACCENT + ';border-radius:2.5px;box-sizing:border-box;pointer-events:auto;box-shadow:0 1px 3px rgba(0,0,0,.35)}' +
|
||||
'.sel.editing .handle,.sel.dragging .handle{display:none}' +
|
||||
'.handle[data-dir="n"]{top:0;left:50%;cursor:ns-resize}.handle[data-dir="s"]{top:100%;left:50%;cursor:ns-resize}' +
|
||||
'.handle[data-dir="e"]{top:50%;left:100%;cursor:ew-resize}.handle[data-dir="w"]{top:50%;left:0;cursor:ew-resize}' +
|
||||
'.handle[data-dir="ne"]{top:0;left:100%;cursor:nesw-resize}.handle[data-dir="sw"]{top:100%;left:0;cursor:nesw-resize}' +
|
||||
'.handle[data-dir="nw"]{top:0;left:0;cursor:nwse-resize}.handle[data-dir="se"]{top:100%;left:100%;cursor:nwse-resize}' +
|
||||
'.label{position:absolute;left:-1px;top:-26px;background:#101218;color:#dfe2e9;border:1px solid #272c3e;border-radius:6px;padding:3px 8px;font:600 10.5px/1.3 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;white-space:nowrap;pointer-events:none;box-shadow:0 4px 16px rgba(0,0,0,.45)}' +
|
||||
'.label.inside{top:4px;left:4px}' +
|
||||
'.label b{color:#4acb8a;font-weight:600}.label span{color:#80859a;margin-left:6px;font-weight:500}' +
|
||||
'.drop{position:fixed;pointer-events:none;display:none;background:' + ACCENT + ';border-radius:2px;box-shadow:0 0 0 2px rgba(34,197,94,.25)}' +
|
||||
'.ghost{position:fixed;pointer-events:none;display:none;border:1px solid ' + ACCENT + ';background:rgba(34,197,94,.12);border-radius:3px;box-sizing:border-box}' +
|
||||
'.toast{position:fixed;left:50%;bottom:14px;transform:translateX(-50%);display:none;background:#101218;color:#dfe2e9;border:1px solid #272c3e;border-radius:99px;padding:6px 14px;font:500 11.5px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;box-shadow:0 8px 32px rgba(0,0,0,.5);white-space:nowrap}' +
|
||||
'</style>' +
|
||||
'<div class="hover"></div>' +
|
||||
'<div class="sel">' +
|
||||
'<div class="label"><b></b><span></span></div>' +
|
||||
'<div class="handle" data-dir="n"></div><div class="handle" data-dir="s"></div>' +
|
||||
'<div class="handle" data-dir="e"></div><div class="handle" data-dir="w"></div>' +
|
||||
'<div class="handle" data-dir="ne"></div><div class="handle" data-dir="nw"></div>' +
|
||||
'<div class="handle" data-dir="se"></div><div class="handle" data-dir="sw"></div>' +
|
||||
'</div>' +
|
||||
'<div class="drop"></div><div class="ghost"></div><div class="toast"></div>';
|
||||
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 ? '<!DOCTYPE ' + document.doctype.name + '>\n' : '<!DOCTYPE html>\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 };
|
||||
@@ -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
|
||||
};
|
||||
@@ -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
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
+64
-26
@@ -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 <file>` 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 <file> --reply "<what you changed>"` 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 <file>` 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 <file> --reply "<what you changed>"` 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 };
|
||||
Executable
+103
@@ -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 <file> --reply "Background is now brand gray."
|
||||
* node scripts/ui-canvas.js end <file>
|
||||
*
|
||||
* 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 <file.html> Open (or resume) a preview session',
|
||||
' node scripts/ui-canvas.js await <file.html> 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 <file.html> Show a thinking/typing indicator in chat',
|
||||
' node scripts/ui-canvas.js end <file.html> 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 <mobile|desktop|custom|WxH> Initial viewport (default desktop)',
|
||||
' --title <text> 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 <msg> Show an agent reply in the canvas chat before waiting',
|
||||
' --timeout-ms <n> Return {status:"waiting"} after n ms (tests/debug only)',
|
||||
' typing: --state <thinking|typing|idle> Defaults to typing',
|
||||
' server: --port <n> --host <h>',
|
||||
'',
|
||||
'Finish payloads name <file>.edited.html (final markup) and <file>.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 <file>` 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 <file> --reply "<what you changed>"\` 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 <file> --reply "<what you changed>"` 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 };
|
||||
Reference in new issue
Block a user