dreative 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/cli/index.js +169 -0
- package/dist/server/agentQueue.js +70 -0
- package/dist/server/ai.js +177 -0
- package/dist/server/diff.js +97 -0
- package/dist/server/index.js +328 -0
- package/dist/server/jobs.js +31 -0
- package/dist/server/preview.js +110 -0
- package/dist/server/store.js +71 -0
- package/dist/shared/design.js +163 -0
- package/dist/shared/types.js +1 -0
- package/dist/ui/assets/index--vztc_MR.js +71 -0
- package/dist/ui/assets/index-y0gVjC7u.css +1 -0
- package/dist/ui/index.html +13 -0
- package/package.json +44 -0
- package/skill/dreative/DESIGN.md +358 -0
- package/skill/dreative/SKILL.md +108 -0
- package/skill/dreative/skills/3d.md +131 -0
- package/skill/dreative/skills/interaction.md +126 -0
- package/skill/dreative/skills/motion.md +125 -0
package/README.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# Dreative
|
|
2
|
+
|
|
3
|
+
Visual round-trip UI editing **skill for coding CLIs** (Claude Code etc.). The CLI agent extracts your app's current UI page-by-page into editable wireframes; you tweak them in the browser (drag-drop, ref images, text prompts); clicking **Finish** hands a compact layout **diff** back to the agent, which rewrites your real code to match.
|
|
4
|
+
|
|
5
|
+
Dreative itself has **no AI** — the web UI is a dumb visual editor plus a request queue. Your coding agent is the intelligence: it services UI prompts via `dreative wait` / `dreative respond` and applies the finish diff. See `skill/dreative/SKILL.md` for the agent workflow (install it into `.claude/skills/dreative/`).
|
|
6
|
+
|
|
7
|
+
## Run
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install
|
|
11
|
+
npm run build
|
|
12
|
+
npm link # once — makes the `dreative` command available globally
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Then in any project folder:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
dreative # starts the local server and opens http://localhost:4820
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
State lives in `.dreative/` in that folder (`project.json`, `refs/`, `generated/`).
|
|
22
|
+
|
|
23
|
+
## Workflow
|
|
24
|
+
|
|
25
|
+
1. **Extract** — the CLI agent reads your app and writes `.dreative/project.json` (wireframe per page, real labels, `source` pointers to owning files), then snapshots it: `dreative baseline`.
|
|
26
|
+
2. **Tweak** — in the browser: drag blocks, add/remove/duplicate, attach reference images and prompts per page/block/element. Prompt-driven actions (propose layouts, block edits, design passes) are queued for your agent, which services them via `dreative wait` → `dreative respond`.
|
|
27
|
+
3. **Finish** — click ✅ Finish; the agent receives only the diff vs the baseline (changed/moved/added/removed blocks + annotations) and applies it to the real codebase using the `source` pointers — token-efficient by construction.
|
|
28
|
+
|
|
29
|
+
CLI: `dreative` / `dreative start` (server+UI) · `dreative install-skill` (copy skill into ./.claude/skills) · `dreative wait` (block for next UI event) · `dreative respond <id> [result.json|--error msg]` · `dreative baseline`.
|
|
30
|
+
|
|
31
|
+
## Dev
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npm run dev # server on :4820 (tsx watch) + Vite UI on :5199 with proxy
|
|
35
|
+
```
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import readline from "node:readline";
|
|
6
|
+
import { createServer } from "../server/index.js";
|
|
7
|
+
import open from "open";
|
|
8
|
+
const port = Number(process.env.DREATIVE_PORT || 4820);
|
|
9
|
+
const base = `http://localhost:${port}`;
|
|
10
|
+
const args = process.argv.slice(2);
|
|
11
|
+
const cmd = args[0] && !args[0].startsWith("-") ? args[0] : "start";
|
|
12
|
+
const USAGE = `usage: dreative [command]
|
|
13
|
+
start serve the visual editor for the current project (default)
|
|
14
|
+
install-skill copy the dreative skill into ./.claude/skills/dreative/
|
|
15
|
+
--list show available specialist skills
|
|
16
|
+
--skills a,b install only these specialist skills (no flag: interactive picker, Enter = all)
|
|
17
|
+
--codex install for Codex CLI instead (.codex/skills/ + AGENTS.md pointer)
|
|
18
|
+
wait (agent) block until the UI needs something; prints one JSON event
|
|
19
|
+
respond <id> [result.json | --error msg] (agent) answer a request
|
|
20
|
+
baseline (agent) snapshot project.json as the finish-diff baseline`;
|
|
21
|
+
async function main() {
|
|
22
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
23
|
+
console.log(USAGE);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
switch (cmd) {
|
|
27
|
+
case "start": {
|
|
28
|
+
const app = createServer(process.cwd());
|
|
29
|
+
const server = app.listen(port, () => {
|
|
30
|
+
console.log(`\n Dreative running for ${process.cwd()}`);
|
|
31
|
+
console.log(` ${base}\n`);
|
|
32
|
+
if (!args.includes("--no-open"))
|
|
33
|
+
open(base).catch(() => { });
|
|
34
|
+
});
|
|
35
|
+
server.on("error", (err) => {
|
|
36
|
+
console.error(`failed to start on :${port} — ${String(err)}\n(set DREATIVE_PORT to use another port)`);
|
|
37
|
+
process.exit(1);
|
|
38
|
+
});
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
case "install-skill": {
|
|
42
|
+
const srcDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "skill", "dreative");
|
|
43
|
+
const skillsDir = path.join(srcDir, "skills");
|
|
44
|
+
const available = fs.existsSync(skillsDir)
|
|
45
|
+
? fs.readdirSync(skillsDir).filter((f) => f.endsWith(".md")).map((f) => f.replace(/\.md$/, ""))
|
|
46
|
+
: [];
|
|
47
|
+
if (args.includes("--list")) {
|
|
48
|
+
console.log(`specialist skills (installed by default, pick with --skills a,b):`);
|
|
49
|
+
for (const s of available) {
|
|
50
|
+
const firstLine = fs.readFileSync(path.join(skillsDir, `${s}.md`), "utf-8").split("\n")[0].replace(/^#\s*/, "");
|
|
51
|
+
console.log(` ${s.padEnd(14)} ${firstLine}`);
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const sArg = args.indexOf("--skills");
|
|
56
|
+
let picked = available;
|
|
57
|
+
if (sArg > -1) {
|
|
58
|
+
picked = (args[sArg + 1] || "").split(",").map((t) => t.trim()).filter(Boolean);
|
|
59
|
+
const unknown = picked.filter((p) => !available.includes(p));
|
|
60
|
+
if (unknown.length)
|
|
61
|
+
throw new Error(`unknown skill(s): ${unknown.join(", ")} — available: ${available.join(", ")}`);
|
|
62
|
+
}
|
|
63
|
+
else if (process.stdin.isTTY && available.length) {
|
|
64
|
+
console.log("specialist skills:");
|
|
65
|
+
available.forEach((s, i) => {
|
|
66
|
+
const firstLine = fs.readFileSync(path.join(skillsDir, `${s}.md`), "utf-8").split("\n")[0].replace(/^#\s*/, "");
|
|
67
|
+
console.log(` ${i + 1}. ${s.padEnd(14)} ${firstLine}`);
|
|
68
|
+
});
|
|
69
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
70
|
+
const answer = (await new Promise((res) => rl.question("install which? (numbers/names, comma-separated; Enter = all): ", res))).trim();
|
|
71
|
+
rl.close();
|
|
72
|
+
if (answer && answer.toLowerCase() !== "all") {
|
|
73
|
+
picked = answer.split(",").map((t) => t.trim()).filter(Boolean).map((t) => {
|
|
74
|
+
const n = Number(t);
|
|
75
|
+
return Number.isInteger(n) && n >= 1 && n <= available.length ? available[n - 1] : t;
|
|
76
|
+
});
|
|
77
|
+
const unknown = picked.filter((p) => !available.includes(p));
|
|
78
|
+
if (unknown.length)
|
|
79
|
+
throw new Error(`unknown skill(s): ${unknown.join(", ")} — available: ${available.join(", ")}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const forCodex = args.includes("--codex");
|
|
83
|
+
const destDir = forCodex
|
|
84
|
+
? path.join(process.cwd(), ".codex", "skills", "dreative")
|
|
85
|
+
: path.join(process.cwd(), ".claude", "skills", "dreative");
|
|
86
|
+
fs.mkdirSync(destDir, { recursive: true });
|
|
87
|
+
for (const f of fs.readdirSync(srcDir)) {
|
|
88
|
+
if (fs.statSync(path.join(srcDir, f)).isFile())
|
|
89
|
+
fs.copyFileSync(path.join(srcDir, f), path.join(destDir, f));
|
|
90
|
+
}
|
|
91
|
+
if (picked.length) {
|
|
92
|
+
fs.mkdirSync(path.join(destDir, "skills"), { recursive: true });
|
|
93
|
+
for (const s of picked) {
|
|
94
|
+
fs.copyFileSync(path.join(skillsDir, `${s}.md`), path.join(destDir, "skills", `${s}.md`));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (forCodex) {
|
|
98
|
+
// Codex may not auto-discover skills — leave a pointer in AGENTS.md (idempotent).
|
|
99
|
+
const agentsMd = path.join(process.cwd(), "AGENTS.md");
|
|
100
|
+
const marker = "<!-- dreative-skill -->";
|
|
101
|
+
const pointer = `\n${marker}\n## Dreative (frontend design skill)\nFor ANY frontend design work (redesign, restyle, build pages, animations, motion, 3D, micro-interactions) or when the user says "open dreative" / wants to edit the UI visually: read \`.codex/skills/dreative/SKILL.md\` first and follow it.\n`;
|
|
102
|
+
const existing = fs.existsSync(agentsMd) ? fs.readFileSync(agentsMd, "utf-8") : "";
|
|
103
|
+
if (!existing.includes(marker))
|
|
104
|
+
fs.writeFileSync(agentsMd, existing + pointer);
|
|
105
|
+
}
|
|
106
|
+
console.log(`installed skill to ${destDir}${forCodex ? " (Codex mode: AGENTS.md pointer added)" : ""}`);
|
|
107
|
+
console.log(` core: SKILL.md, DESIGN.md`);
|
|
108
|
+
console.log(` specialist skills: ${picked.length ? picked.join(", ") : "(none)"}`);
|
|
109
|
+
console.log(`next: ask your coding agent to "open dreative" or "redesign my app's UI visually"`);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
// Agent: block until the UI needs something; print one event as JSON.
|
|
113
|
+
// Output: {"kind":"request",...} | {"kind":"finish","diff":...} | {"kind":"none"}
|
|
114
|
+
case "wait": {
|
|
115
|
+
const tArg = args.indexOf("--timeout");
|
|
116
|
+
const timeoutMs = (tArg > -1 ? Number(args[tArg + 1]) : 480) * 1000;
|
|
117
|
+
const deadline = Date.now() + timeoutMs;
|
|
118
|
+
while (Date.now() < deadline) {
|
|
119
|
+
const res = await fetch(`${base}/api/agent/next`);
|
|
120
|
+
if (res.status === 204)
|
|
121
|
+
continue; // server long-polls 25s per round
|
|
122
|
+
if (!res.ok)
|
|
123
|
+
throw new Error(`server error ${res.status}`);
|
|
124
|
+
console.log(JSON.stringify(await res.json()));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
console.log(JSON.stringify({ kind: "none" }));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
// Agent: answer a request. `dreative respond <id> <result.json>` or --error "msg"
|
|
131
|
+
case "respond": {
|
|
132
|
+
const id = args[1];
|
|
133
|
+
if (!id)
|
|
134
|
+
throw new Error("usage: dreative respond <requestId> [resultFile] [--error msg]");
|
|
135
|
+
const eArg = args.indexOf("--error");
|
|
136
|
+
const body = { id };
|
|
137
|
+
if (eArg > -1)
|
|
138
|
+
body.error = args[eArg + 1] || "agent error";
|
|
139
|
+
else if (args[2])
|
|
140
|
+
body.result = JSON.parse(fs.readFileSync(args[2], "utf-8"));
|
|
141
|
+
else
|
|
142
|
+
body.result = { ok: true };
|
|
143
|
+
const res = await fetch(`${base}/api/agent/respond`, {
|
|
144
|
+
method: "POST",
|
|
145
|
+
headers: { "Content-Type": "application/json" },
|
|
146
|
+
body: JSON.stringify(body),
|
|
147
|
+
});
|
|
148
|
+
if (!res.ok)
|
|
149
|
+
throw new Error(`respond failed: ${await res.text()}`);
|
|
150
|
+
console.log("ok");
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
// Agent: snapshot current project.json as the finish-diff baseline
|
|
154
|
+
case "baseline": {
|
|
155
|
+
const res = await fetch(`${base}/api/baseline`, { method: "POST" });
|
|
156
|
+
if (!res.ok)
|
|
157
|
+
throw new Error(`baseline failed: ${await res.text()}`);
|
|
158
|
+
console.log("ok");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
default:
|
|
162
|
+
console.error(`unknown command: ${cmd}\n${USAGE}`);
|
|
163
|
+
process.exit(1);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
main().catch((err) => {
|
|
167
|
+
console.error(String(err));
|
|
168
|
+
process.exit(1);
|
|
169
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { newId } from "./store.js";
|
|
2
|
+
const queue = [];
|
|
3
|
+
const pending = new Map();
|
|
4
|
+
let waiter = null;
|
|
5
|
+
function deliver(ev) {
|
|
6
|
+
if (waiter) {
|
|
7
|
+
const w = waiter;
|
|
8
|
+
waiter = null;
|
|
9
|
+
w(ev);
|
|
10
|
+
}
|
|
11
|
+
else {
|
|
12
|
+
queue.push(ev);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Enqueue a request for the agent; resolves when the agent responds. */
|
|
16
|
+
export function requestAgent(type, payload, onStatus) {
|
|
17
|
+
const event = { kind: "request", id: newId("req"), type, payload };
|
|
18
|
+
onStatus?.("Waiting for agent… (run `dreative wait` in your coding CLI)");
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
pending.set(event.id, { event, resolve: resolve, reject, onStatus, taken: false });
|
|
21
|
+
deliver(event);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
export function pushFinish(diff) {
|
|
25
|
+
deliver({ kind: "finish", diff });
|
|
26
|
+
}
|
|
27
|
+
/** Long-poll: resolve with the next event, or null after timeoutMs. */
|
|
28
|
+
export function nextEvent(timeoutMs) {
|
|
29
|
+
const ev = queue.shift();
|
|
30
|
+
if (ev) {
|
|
31
|
+
markTaken(ev);
|
|
32
|
+
return Promise.resolve(ev);
|
|
33
|
+
}
|
|
34
|
+
if (waiter)
|
|
35
|
+
waiter(null); // only one agent poller at a time
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
const timer = setTimeout(() => {
|
|
38
|
+
if (waiter === wrapped)
|
|
39
|
+
waiter = null;
|
|
40
|
+
resolve(null);
|
|
41
|
+
}, timeoutMs);
|
|
42
|
+
const wrapped = (e) => {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
if (e)
|
|
45
|
+
markTaken(e);
|
|
46
|
+
resolve(e);
|
|
47
|
+
};
|
|
48
|
+
waiter = wrapped;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function markTaken(ev) {
|
|
52
|
+
if (ev.kind !== "request")
|
|
53
|
+
return;
|
|
54
|
+
const p = pending.get(ev.id);
|
|
55
|
+
if (p && !p.taken) {
|
|
56
|
+
p.taken = true;
|
|
57
|
+
p.onStatus?.("Agent working…");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function respond(id, body) {
|
|
61
|
+
const p = pending.get(id);
|
|
62
|
+
if (!p)
|
|
63
|
+
return false;
|
|
64
|
+
pending.delete(id);
|
|
65
|
+
if (body.error)
|
|
66
|
+
p.reject(new Error(body.error));
|
|
67
|
+
else
|
|
68
|
+
p.resolve(body.result);
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
const BLOCK_SCHEMA = `
|
|
3
|
+
A block is a JSON object:
|
|
4
|
+
{
|
|
5
|
+
"id": "string (short unique id)",
|
|
6
|
+
"type": "section|row|column|nav|hero|card-grid|list|form|footer|text|image|button",
|
|
7
|
+
"label": "short human label, e.g. 'Hero', 'Pricing cards'",
|
|
8
|
+
"direction": "row" | "column" (optional, layout of children),
|
|
9
|
+
"sizeHint": "sm" | "md" | "lg" (optional, relative vertical size),
|
|
10
|
+
"intents": ["optional behavior notes, e.g. 'CTA scrolls to pricing'"],
|
|
11
|
+
"children": [ ...nested blocks ] (optional)
|
|
12
|
+
}
|
|
13
|
+
Keep trees shallow (max depth 3) and wireframe-level: structure, not styling.`;
|
|
14
|
+
/** Run an Agent SDK query and return the final result text, reporting progress. */
|
|
15
|
+
async function run(prompt, opts = {}) {
|
|
16
|
+
let result = "";
|
|
17
|
+
const q = query({
|
|
18
|
+
prompt,
|
|
19
|
+
options: {
|
|
20
|
+
allowedTools: opts.allowRead ? ["Read"] : [],
|
|
21
|
+
permissionMode: "bypassPermissions",
|
|
22
|
+
maxTurns: opts.allowRead ? 6 : 2,
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
for await (const message of q) {
|
|
26
|
+
if (message.type === "assistant") {
|
|
27
|
+
const blocks = message.message?.content ?? [];
|
|
28
|
+
for (const b of blocks) {
|
|
29
|
+
if (b.type === "tool_use")
|
|
30
|
+
opts.progress?.("Looking at the reference image...");
|
|
31
|
+
else if (b.type === "text")
|
|
32
|
+
opts.progress?.("Writing...");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else if (message.type === "result") {
|
|
36
|
+
if (message.subtype === "success")
|
|
37
|
+
result = message.result;
|
|
38
|
+
else
|
|
39
|
+
throw new Error(`AI call failed: ${message.subtype}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (!result)
|
|
43
|
+
throw new Error("AI call returned no result");
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
/** Run + parse, with one retry that feeds the failure back to the model. */
|
|
47
|
+
async function runParsed(prompt, parse, opts = {}) {
|
|
48
|
+
const text = await run(prompt, opts);
|
|
49
|
+
try {
|
|
50
|
+
return parse(text);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
opts.progress?.("Output was malformed - retrying...");
|
|
54
|
+
const retryText = await run(`${prompt}\n\nIMPORTANT: Your previous response could not be parsed (${String(err)}). Respond again, strictly following the output format instructions.`, opts);
|
|
55
|
+
return parse(retryText);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Extract the first JSON value (object or array) from model output. */
|
|
59
|
+
function extractJson(text) {
|
|
60
|
+
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
|
|
61
|
+
const candidate = fenced ? fenced[1] : text;
|
|
62
|
+
const start = candidate.search(/[[{]/);
|
|
63
|
+
if (start === -1)
|
|
64
|
+
throw new Error("No JSON found in AI response");
|
|
65
|
+
for (let end = candidate.length; end > start; end--) {
|
|
66
|
+
const ch = candidate[end - 1];
|
|
67
|
+
if (ch !== "}" && ch !== "]")
|
|
68
|
+
continue;
|
|
69
|
+
try {
|
|
70
|
+
return JSON.parse(candidate.slice(start, end));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
/* keep scanning */
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
throw new Error("Could not parse JSON from AI response");
|
|
77
|
+
}
|
|
78
|
+
function extractCode(text) {
|
|
79
|
+
const fence = text.match(/```(?:tsx|jsx|typescript|ts)?\s*([\s\S]*?)```/);
|
|
80
|
+
const code = fence ? fence[1].trim() : text.trim();
|
|
81
|
+
if (!code.includes("export default"))
|
|
82
|
+
throw new Error("Generated code has no default export");
|
|
83
|
+
return code;
|
|
84
|
+
}
|
|
85
|
+
export async function proposeSkeletons(userPrompt, progress) {
|
|
86
|
+
progress?.("Proposing page layouts...");
|
|
87
|
+
return runParsed(`You are a UX/information-architecture expert. Propose 3 distinct page layout skeletons (wireframe-level) for this request:
|
|
88
|
+
|
|
89
|
+
"${userPrompt}"
|
|
90
|
+
|
|
91
|
+
${BLOCK_SCHEMA}
|
|
92
|
+
|
|
93
|
+
Respond with ONLY a JSON array of 3 items, each: {"name": "page variant name", "layout": <block tree with root type "section">}. No prose.`, (t) => extractJson(t), { progress });
|
|
94
|
+
}
|
|
95
|
+
export async function proposeVariants(pageName, layout, progress) {
|
|
96
|
+
progress?.(`Proposing variants of "${pageName}"...`);
|
|
97
|
+
return runParsed(`You are a UX expert. Here is the current wireframe skeleton for the page "${pageName}":
|
|
98
|
+
|
|
99
|
+
${JSON.stringify(layout, null, 2)}
|
|
100
|
+
|
|
101
|
+
Propose 2 meaningfully different alternative layouts for the SAME content and purpose (e.g. different section order, grid vs list, split vs stacked). Preserve all "intents" values, attached to the equivalent blocks. Use fresh ids.
|
|
102
|
+
|
|
103
|
+
${BLOCK_SCHEMA}
|
|
104
|
+
|
|
105
|
+
Respond with ONLY a JSON array of 2 items: {"name": "<pageName> - <variant descriptor>", "layout": <block tree>}. No prose.`, (t) => extractJson(t), { progress });
|
|
106
|
+
}
|
|
107
|
+
export async function editBlock(block, instruction, progress) {
|
|
108
|
+
progress?.("Editing block...");
|
|
109
|
+
return runParsed(`You are editing one block of a page wireframe. Current block subtree:
|
|
110
|
+
|
|
111
|
+
${JSON.stringify(block, null, 2)}
|
|
112
|
+
|
|
113
|
+
User instruction: "${instruction}"
|
|
114
|
+
|
|
115
|
+
${BLOCK_SCHEMA}
|
|
116
|
+
|
|
117
|
+
Apply the instruction. Structural changes go into the tree; behavior/functionality changes go into "intents" arrays on the relevant blocks. If the instruction replaces an existing behavior, replace the corresponding intent instead of appending. Keep existing ids where blocks are unchanged; give new blocks new ids.
|
|
118
|
+
Respond with ONLY the updated block subtree as JSON. No prose.`, (t) => extractJson(t), { progress });
|
|
119
|
+
}
|
|
120
|
+
export async function designPage(args) {
|
|
121
|
+
const { progress } = args;
|
|
122
|
+
progress?.("Designing page...");
|
|
123
|
+
const refPart = args.refImagePath
|
|
124
|
+
? `First, use the Read tool to view the reference image at: ${args.refImagePath}\nMatch its visual style (colors, typography feel, spacing, mood) closely.`
|
|
125
|
+
: "No page-level reference image provided; choose a distinctive, non-generic visual style appropriate to the content.";
|
|
126
|
+
const blockRefPart = args.blockRefs?.length
|
|
127
|
+
? `These specific blocks have their own style reference images. Use the Read tool to view each, and match that image's style for that block specifically (it overrides the page-level style for that block):\n${args.blockRefs
|
|
128
|
+
.map((r) => `- block "${r.id}" (${r.label}): ${r.path}`)
|
|
129
|
+
.join("\n")}`
|
|
130
|
+
: "";
|
|
131
|
+
const previousPart = args.previousCode
|
|
132
|
+
? `A previous version of this page exists below. The user may have made deliberate element-level edits to it. Where a block from the skeleton already exists in the previous version, PRESERVE its styling and content choices; only restructure/add/remove what the updated skeleton requires.
|
|
133
|
+
|
|
134
|
+
Previous version:
|
|
135
|
+
\`\`\`tsx
|
|
136
|
+
${args.previousCode}
|
|
137
|
+
\`\`\`
|
|
138
|
+
`
|
|
139
|
+
: "";
|
|
140
|
+
const siblingPart = args.siblingPages?.length
|
|
141
|
+
? `Other pages in this project (use these names for nav/footer links, href="#"): ${args.siblingPages.join(", ")}.`
|
|
142
|
+
: "";
|
|
143
|
+
return runParsed(`${refPart}
|
|
144
|
+
${blockRefPart}
|
|
145
|
+
|
|
146
|
+
Then generate a complete React component for the page "${args.pageName}" implementing this wireframe skeleton exactly (same structure and order of blocks):
|
|
147
|
+
|
|
148
|
+
${JSON.stringify(args.layout, null, 2)}
|
|
149
|
+
|
|
150
|
+
${previousPart}
|
|
151
|
+
Every "intents" entry describes required behavior - implement it with React state/handlers (mock data is fine, no network calls).
|
|
152
|
+
${args.designPrompt ? `Additional design direction: "${args.designPrompt}"` : ""}
|
|
153
|
+
${siblingPart}
|
|
154
|
+
|
|
155
|
+
Requirements:
|
|
156
|
+
- Single self-contained .tsx file, default-exporting the page component.
|
|
157
|
+
- Import only from "react". Style with Tailwind CSS utility classes (Tailwind is available globally).
|
|
158
|
+
- Put data-dreative-id="<block id>" on the top-level element rendered for each block from the skeleton.
|
|
159
|
+
- Realistic placeholder copy, no lorem ipsum. For images use https://picsum.photos placeholders or CSS.
|
|
160
|
+
|
|
161
|
+
Respond with ONLY the .tsx source in a single \`\`\`tsx code fence. No prose.`, extractCode, { allowRead: !!args.refImagePath || !!args.blockRefs?.length, progress });
|
|
162
|
+
}
|
|
163
|
+
export async function editDesignedElement(args) {
|
|
164
|
+
args.progress?.("Editing element...");
|
|
165
|
+
const refPart = args.refImagePath
|
|
166
|
+
? `First, use the Read tool to view the style reference image at: ${args.refImagePath}\nMatch its visual style when applying the change.\n\n`
|
|
167
|
+
: "";
|
|
168
|
+
return runParsed(`${refPart}Here is a React+Tailwind page component:
|
|
169
|
+
|
|
170
|
+
\`\`\`tsx
|
|
171
|
+
${args.code}
|
|
172
|
+
\`\`\`
|
|
173
|
+
|
|
174
|
+
Modify ONLY the element (and its contents) marked data-dreative-id="${args.elementId}" according to this instruction: "${args.instruction}". Keep everything else byte-identical where possible, keep all data-dreative-id attributes.
|
|
175
|
+
|
|
176
|
+
Respond with ONLY the full updated .tsx source in a single \`\`\`tsx code fence. No prose.`, extractCode, { allowRead: !!args.refImagePath, progress: args.progress });
|
|
177
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compact layout diff sent to the agent on "finish". Token efficiency is the
|
|
3
|
+
* point: only changed pages/blocks appear, changed blocks list only the props
|
|
4
|
+
* that differ (children compared structurally via the added/removed/moved
|
|
5
|
+
* lists, not by inclusion).
|
|
6
|
+
*/
|
|
7
|
+
const BLOCK_PROPS = ["type", "label", "direction", "sizeHint", "intents", "refImage", "source"];
|
|
8
|
+
function flatten(root) {
|
|
9
|
+
const map = new Map();
|
|
10
|
+
const walk = (b, parentId, index) => {
|
|
11
|
+
map.set(b.id, { block: b, parentId, index });
|
|
12
|
+
b.children?.forEach((c, i) => walk(c, b.id, i));
|
|
13
|
+
};
|
|
14
|
+
walk(root, null, 0);
|
|
15
|
+
return map;
|
|
16
|
+
}
|
|
17
|
+
function diffPage(before, after) {
|
|
18
|
+
const d = { id: after.id, name: after.name, source: after.source };
|
|
19
|
+
let changed = false;
|
|
20
|
+
if (before.name !== after.name) {
|
|
21
|
+
d.renamedFrom = before.name;
|
|
22
|
+
changed = true;
|
|
23
|
+
}
|
|
24
|
+
if (before.refImage !== after.refImage && after.refImage) {
|
|
25
|
+
d.refImage = after.refImage;
|
|
26
|
+
changed = true;
|
|
27
|
+
}
|
|
28
|
+
if (before.designPrompt !== after.designPrompt && after.designPrompt) {
|
|
29
|
+
d.designPrompt = after.designPrompt;
|
|
30
|
+
changed = true;
|
|
31
|
+
}
|
|
32
|
+
const a = flatten(before.layout);
|
|
33
|
+
const b = flatten(after.layout);
|
|
34
|
+
for (const [id, fb] of b) {
|
|
35
|
+
const fa = a.get(id);
|
|
36
|
+
if (!fa) {
|
|
37
|
+
// report only the topmost added block (its subtree comes along)
|
|
38
|
+
if (!fb.parentId || a.has(fb.parentId)) {
|
|
39
|
+
(d.blocksAdded ??= []).push({ parentId: fb.parentId, index: fb.index, block: fb.block });
|
|
40
|
+
changed = true;
|
|
41
|
+
}
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (fa.parentId !== fb.parentId || fa.index !== fb.index) {
|
|
45
|
+
(d.blocksMoved ??= []).push({ id, label: fb.block.label, toParent: fb.parentId, index: fb.index });
|
|
46
|
+
changed = true;
|
|
47
|
+
}
|
|
48
|
+
const delta = {};
|
|
49
|
+
for (const key of BLOCK_PROPS) {
|
|
50
|
+
const va = fa.block[key];
|
|
51
|
+
const vb = fb.block[key];
|
|
52
|
+
if (JSON.stringify(va) !== JSON.stringify(vb))
|
|
53
|
+
delta[key] = vb ?? null;
|
|
54
|
+
}
|
|
55
|
+
if (Object.keys(delta).length) {
|
|
56
|
+
(d.blocksChanged ??= []).push({ id, label: fb.block.label, ...delta });
|
|
57
|
+
changed = true;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
for (const [id, fa] of a) {
|
|
61
|
+
if (!b.has(id)) {
|
|
62
|
+
// report only topmost removed block
|
|
63
|
+
if (!fa.parentId || b.has(fa.parentId)) {
|
|
64
|
+
(d.blocksRemoved ??= []).push({ id, label: fa.block.label });
|
|
65
|
+
changed = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return changed ? d : null;
|
|
70
|
+
}
|
|
71
|
+
export function computeDiff(baseline, current) {
|
|
72
|
+
const beforePages = new Map(baseline.pages.map((p) => [p.id, p]));
|
|
73
|
+
const afterPages = new Map(current.pages.map((p) => [p.id, p]));
|
|
74
|
+
const diff = { pagesAdded: [], pagesRemoved: [], pagesChanged: [] };
|
|
75
|
+
for (const page of current.pages) {
|
|
76
|
+
const before = beforePages.get(page.id);
|
|
77
|
+
if (!before) {
|
|
78
|
+
diff.pagesAdded.push({
|
|
79
|
+
id: page.id,
|
|
80
|
+
name: page.name,
|
|
81
|
+
refImage: page.refImage,
|
|
82
|
+
designPrompt: page.designPrompt,
|
|
83
|
+
layout: page.layout,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
const d = diffPage(before, page);
|
|
88
|
+
if (d)
|
|
89
|
+
diff.pagesChanged.push(d);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const page of baseline.pages) {
|
|
93
|
+
if (!afterPages.has(page.id))
|
|
94
|
+
diff.pagesRemoved.push({ id: page.id, name: page.name, source: page.source });
|
|
95
|
+
}
|
|
96
|
+
return diff;
|
|
97
|
+
}
|