truemap-cli 0.2.0 → 0.3.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 +2 -1
- package/kit/truemap.css +6 -4
- package/package.json +1 -1
- package/src/check.js +32 -1
- package/src/cli.js +31 -7
- package/src/export.js +62 -0
- package/src/guide.md +22 -9
- package/src/server.js +20 -7
- package/src/ui/sdk.js +62 -99
- package/src/ui/wires.js +237 -0
- package/src/ui/workspace.css +15 -0
- package/src/ui/workspace.html +11 -0
- package/src/ui/workspace.js +37 -1
package/README.md
CHANGED
|
@@ -47,7 +47,8 @@ your repo/
|
|
|
47
47
|
| `npx -y truemap-cli outline` | A compact map of the repo, so the first blueprint takes minutes, not an hour |
|
|
48
48
|
| `npx -y truemap-cli listen` | Waits for your next message or comments from the page |
|
|
49
49
|
| `npx -y truemap-cli reply "…" --listen` | Shows the answer in the conversation panel, then keeps listening |
|
|
50
|
-
| `npx -y truemap-cli check` | Checks every `data-src` anchor against the code |
|
|
50
|
+
| `npx -y truemap-cli check` | Checks every `data-src` anchor against the code, and that every map wire has a target |
|
|
51
|
+
| `npx -y truemap-cli export <page>` | Writes the page as one self-contained HTML file to share (also in the workspace ⋮ menu) |
|
|
51
52
|
| `npx -y truemap-cli guide` | The page-writing guide for agents: the map, anchors, decisions, design rules |
|
|
52
53
|
|
|
53
54
|
The checker works for any language. It uses git and a plain-text search:
|
package/kit/truemap.css
CHANGED
|
@@ -113,11 +113,12 @@ hr { border: 0; border-top: 1px solid var(--tm-rule); margin: 40px 0; }
|
|
|
113
113
|
/* --tm-vw is the usable window width (without the scrollbar), set by truemap. */
|
|
114
114
|
html[style*="--tm-vw"] .tm-map, html[style*="--tm-vw"] .tm-blueprint { width: calc(var(--tm-vw) - max(48px, (var(--tm-vw) - 960px) / 2 + 48px) - 16px); min-width: 100%; }
|
|
115
115
|
.tm-map.tm-scrolls { -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 40px), transparent); mask-image: linear-gradient(to right, #000 calc(100% - 40px), transparent); }
|
|
116
|
-
.tm-layer { position: relative; display: grid; grid-template-columns: var(--tm-label-w, 112px)
|
|
116
|
+
.tm-layer { position: relative; display: grid; grid-template-columns: var(--tm-label-w, 112px) minmax(0, 1fr); gap: 20px; align-items: start; }
|
|
117
117
|
.tm-layer + .tm-layer { margin-top: 44px; }
|
|
118
118
|
.tm-layer-label { font-size: 13px; color: var(--tm-pencil); padding-top: 12px; line-height: 1.35; }
|
|
119
119
|
.tm-layer-nodes { display: flex; flex-wrap: nowrap; gap: 18px 26px; }
|
|
120
|
-
|
|
120
|
+
/* Boxes shrink to 168px before the map has to scroll. */
|
|
121
|
+
.tm-layer-nodes > .tm-node { flex: 0 1 var(--tm-node-w, 216px); min-width: var(--tm-node-min, 168px); max-width: none; }
|
|
121
122
|
.tm-map > .tm-layer-nodes { margin-left: 132px; }
|
|
122
123
|
|
|
123
124
|
.tm-node, .tm-step {
|
|
@@ -131,7 +132,7 @@ html[style*="--tm-vw"] .tm-map, html[style*="--tm-vw"] .tm-blueprint { width: ca
|
|
|
131
132
|
}
|
|
132
133
|
a.tm-node:hover, a.tm-step:hover { border-color: var(--tm-graphite); }
|
|
133
134
|
.tm-node-title, .tm-step > b, .tm-step > strong { font-size: 15px; font-weight: 600; color: var(--tm-ink); }
|
|
134
|
-
.tm-node-sub { font-family: var(--tm-code); font-size: 12px; color: var(--tm-pencil); margin-top: 2px; overflow-wrap:
|
|
135
|
+
.tm-node-sub { font-family: var(--tm-code); font-size: 12px; color: var(--tm-pencil); margin-top: 2px; overflow-wrap: break-word; }
|
|
135
136
|
.tm-node-desc { font-size: 13.5px; line-height: 1.45; color: var(--tm-graphite); margin-top: 7px; }
|
|
136
137
|
|
|
137
138
|
/* The survey mark: a box pinned to real code (data-src) carries a small triangle. */
|
|
@@ -166,7 +167,8 @@ a.tm-node:hover, a.tm-step:hover { border-color: var(--tm-graphite); }
|
|
|
166
167
|
|
|
167
168
|
/* ---------- flow: a real sequence ---------- */
|
|
168
169
|
.tm-flow { display: flex; align-items: stretch; gap: 30px; margin: 24px 0 8px; overflow-x: auto; padding: 2px 2px 6px; }
|
|
169
|
-
.tm-flow > .tm-step { flex: 1 1 0; min-width:
|
|
170
|
+
.tm-flow > .tm-step { flex: 1 1 0; min-width: auto; max-width: none; }
|
|
171
|
+
.tm-flow > .tm-step > * { min-width: 132px; }
|
|
170
172
|
.tm-flow > .tm-step + .tm-step::before {
|
|
171
173
|
content: ""; position: absolute; left: -26px; top: 50%; width: 21px; height: 0;
|
|
172
174
|
border-top: 1.5px solid var(--tm-rule-strong);
|
package/package.json
CHANGED
package/src/check.js
CHANGED
|
@@ -223,7 +223,38 @@ export function checkPage(ctx, page) {
|
|
|
223
223
|
});
|
|
224
224
|
const counts = { ok: 0, changed: 0, broken: 0 };
|
|
225
225
|
for (const a of anchors) counts[a.state]++;
|
|
226
|
-
return { page, anchors, counts };
|
|
226
|
+
return { page, anchors, counts, wires: checkWires(html), layout: checkLayout(html) };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Maps that are too big to read at a glance (the guide: at most 12 boxes per map, 4 per layer). */
|
|
230
|
+
export function checkLayout(html) {
|
|
231
|
+
const notes = [];
|
|
232
|
+
const NODE = /class=["'][^"']*\btm-node(?![-\w])/g;
|
|
233
|
+
const maps = html.split(/class=["'][^"']*\btm-(?:map|blueprint)(?![-\w])/).slice(1);
|
|
234
|
+
maps.forEach((body, i) => {
|
|
235
|
+
const total = (body.match(NODE) || []).length;
|
|
236
|
+
if (total > 12) notes.push(`map ${i + 1} has ${total} boxes; 12 or fewer reads at a glance, split the rest into a module page`);
|
|
237
|
+
body.split(/class=["'][^"']*\btm-layer(?![-\w])/).slice(1).forEach((layer, j) => {
|
|
238
|
+
const n = (layer.match(NODE) || []).length;
|
|
239
|
+
if (n > 4) notes.push(`map ${i + 1}, layer ${j + 1} has ${n} boxes; keep it to 4`);
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
return notes;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Map wires whose data-to names an id that is not on the page (they would silently not be drawn). */
|
|
246
|
+
export function checkWires(html) {
|
|
247
|
+
const ID = /\sid\s*=\s*["']([^"']+)["']/i;
|
|
248
|
+
const ids = new Set([...html.matchAll(new RegExp(ID.source, 'gi'))].map((m) => m[1]));
|
|
249
|
+
const problems = [];
|
|
250
|
+
for (const m of html.matchAll(/<[^>]*\sdata-to\s*=\s*["']([^"']*)["'][^>]*>/gi)) {
|
|
251
|
+
const from = (m[0].match(ID) || [])[1] || '(a box without an id)';
|
|
252
|
+
for (const spec of m[1].split(/[\s,]+/).filter(Boolean)) {
|
|
253
|
+
const to = spec.split(':')[0];
|
|
254
|
+
if (!ids.has(to)) problems.push({ from, to, reason: `no element with id="${to}"` });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return problems;
|
|
227
258
|
}
|
|
228
259
|
|
|
229
260
|
export function checkAll(root, pages) {
|
package/src/cli.js
CHANGED
|
@@ -9,6 +9,8 @@ import {
|
|
|
9
9
|
} from './common.js';
|
|
10
10
|
import { checkAll, listPages, markOk, pageInFolder } from './check.js';
|
|
11
11
|
import { outline } from './outline.js';
|
|
12
|
+
import { exportPage } from './export.js';
|
|
13
|
+
import { writeFileSync } from 'node:fs';
|
|
12
14
|
|
|
13
15
|
const CMD = process.env.TRUEMAP_CMD || 'npx -y truemap-cli';
|
|
14
16
|
|
|
@@ -141,6 +143,8 @@ function printCheck(result, indent = '') {
|
|
|
141
143
|
const bad = result.anchors.filter((a) => a.state !== 'ok');
|
|
142
144
|
out(`${indent}check: ${result.counts.ok} ok, ${result.counts.changed} changed, ${result.counts.broken} broken`);
|
|
143
145
|
for (const a of bad) out(`${indent} - ${a.state}: ${q(a.src)} # ${a.reason}`);
|
|
146
|
+
for (const w of result.wires || []) out(`${indent} - wire not drawn: ${q(w.from)} -> ${q(w.to)} # ${w.reason}`);
|
|
147
|
+
for (const l of result.layout || []) out(`${indent} - layout: ${l}`);
|
|
144
148
|
}
|
|
145
149
|
|
|
146
150
|
const SETUP_NOTE = `Visual explanations live in \`${FOLDER}/\` (index.html is the project blueprint). Before explaining architecture, a flow, or options: if a page covers it, update it and run \`${CMD} <page>\`. Create a new page only when the answer has 3+ interacting parts or needs a decision from the user. Always also give a 1-3 line answer in the terminal.`;
|
|
@@ -164,7 +168,7 @@ async function cmdOpen(root, args, opts = {}) {
|
|
|
164
168
|
await call(state, 'POST', '/api/agent/navigate', { page, agent: detectAgent(), ...(opts.annotate !== undefined ? { annotate: opts.annotate } : {}) });
|
|
165
169
|
browser = 'reused the open tab';
|
|
166
170
|
} else if (process.env.TRUEMAP_NO_OPEN || opts.noOpen) {
|
|
167
|
-
browser = 'not opened (--no-open); give the user the url';
|
|
171
|
+
browser = 'not opened (--no-open or TRUEMAP_NO_OPEN); give the user the url';
|
|
168
172
|
} else {
|
|
169
173
|
openBrowser(url);
|
|
170
174
|
browser = 'opened in the default browser (if no window appeared, give the user the url)';
|
|
@@ -187,7 +191,9 @@ async function cmdOpen(root, args, opts = {}) {
|
|
|
187
191
|
if (r.counts.broken) steps.push('Fix the broken anchors first: update the page (or its data-src) to match the code.');
|
|
188
192
|
if (r.counts.changed) steps.push(`Review the changed anchors. If the page needs edits, update it; if it is still accurate, run \`${CMD} check --ok ${page}\`.`);
|
|
189
193
|
}
|
|
190
|
-
steps.push(
|
|
194
|
+
steps.push(detectAgent() === 'codex'
|
|
195
|
+
? `If the user wants to talk about the page: ${agentLoopHint()} If they only wanted to see it, you are done.`
|
|
196
|
+
: agentLoopHint());
|
|
191
197
|
steps.push('Also give the user a 1-3 line answer in the terminal.');
|
|
192
198
|
block('next_step', steps.join('\n'));
|
|
193
199
|
}
|
|
@@ -256,6 +262,8 @@ async function doListen(root, opts) {
|
|
|
256
262
|
].join('\n'));
|
|
257
263
|
} else if (b.status === 'browser_closed') {
|
|
258
264
|
block('next_step', 'The user closed the truemap tab. Stop listening and continue in the terminal. Do not reopen the browser unless the user asks or something important needs their eyes.');
|
|
265
|
+
} else if (b.status === 'ended') {
|
|
266
|
+
block('next_step', 'The user ended the conversation on the page. Stop listening and continue in the terminal. Do not reopen or listen again unless the user asks.');
|
|
259
267
|
} else if (b.status === 'replaced') {
|
|
260
268
|
block('next_step', 'Another listen took over. Stop this one.');
|
|
261
269
|
} else if (b.status === 'timeout') {
|
|
@@ -300,17 +308,20 @@ async function cmdCheck(root, args, opts) {
|
|
|
300
308
|
const pages = args.length ? args.map((a) => resolvePage(root, a)) : undefined;
|
|
301
309
|
const { gitRepo, results } = checkAll(root, pages);
|
|
302
310
|
out(`status: checked ${results.length} page(s)${gitRepo ? '' : ' (no git: only missing paths/names are checked)'}`);
|
|
303
|
-
let changed = 0; let broken = 0;
|
|
311
|
+
let changed = 0; let broken = 0; let wires = 0;
|
|
304
312
|
for (const r of results) {
|
|
305
313
|
out(`- page: ${q(r.page)}`);
|
|
306
314
|
if (r.missing) { out(' missing: true'); continue; }
|
|
307
315
|
printCheck(r, ' ');
|
|
308
|
-
changed += r.counts.changed; broken += r.counts.broken;
|
|
316
|
+
changed += r.counts.changed; broken += r.counts.broken; wires += (r.wires || []).length;
|
|
309
317
|
}
|
|
310
318
|
const steps = [];
|
|
311
319
|
if (broken) steps.push('Broken anchors: the code moved or was removed. Update those pages (content and data-src).');
|
|
312
320
|
if (changed) steps.push(`Changed anchors: review the code. Update the page if needed, otherwise run \`${CMD} check --ok <page>\`.`);
|
|
313
|
-
if (
|
|
321
|
+
if (wires) steps.push('Some map wires point at ids that are not on the page, so they are not drawn. Fix the data-to values (ids separated by spaces).');
|
|
322
|
+
const layout = results.reduce((n, r) => n + (r.layout || []).length, 0);
|
|
323
|
+
if (layout) steps.push('Layout notes: a map over 12 boxes (or a layer over 4) is hard to read. Keep the main parts on the map and move the detail to a module page.');
|
|
324
|
+
if (!broken && !changed && !wires && !layout) steps.push('All pages match the code.');
|
|
314
325
|
block('next_step', steps.join('\n'));
|
|
315
326
|
}
|
|
316
327
|
|
|
@@ -321,6 +332,17 @@ async function cmdStop(root) {
|
|
|
321
332
|
out('status: stopped');
|
|
322
333
|
}
|
|
323
334
|
|
|
335
|
+
function cmdExport(root, args, opts) {
|
|
336
|
+
const page = resolvePage(root, args[0] || 'index.html');
|
|
337
|
+
const html = exportPage(root, page);
|
|
338
|
+
const outPath = resolve(opts.out || `${page.split('/').pop().replace(/\.html?$/i, '')}-truemap.html`);
|
|
339
|
+
writeFileSync(outPath, html);
|
|
340
|
+
out(`status: exported`);
|
|
341
|
+
out(`file: ${q(outPath)}`);
|
|
342
|
+
out(`size_kb: ${Math.round(Buffer.byteLength(html) / 1024)}`);
|
|
343
|
+
block('next_step', 'One self-contained file: kit, fonts and wires are inside. Links to other pages only work next to the .truemap folder.');
|
|
344
|
+
}
|
|
345
|
+
|
|
324
346
|
function cmdOutline(root) {
|
|
325
347
|
const o = outline(root);
|
|
326
348
|
out(`root: ${q(o.name)}`);
|
|
@@ -330,7 +352,7 @@ function cmdOutline(root) {
|
|
|
330
352
|
out('tree: # folder, files, approx lines, biggest files');
|
|
331
353
|
for (const d of o.dirs) out(` - ${q(d.path)} files=${d.files} lines=${d.lines} ${d.top.join(', ')}`);
|
|
332
354
|
if (o.entries.length) out(`likely_entry_points: ${o.entries.map(q).join(', ')}`);
|
|
333
|
-
block('next_step', `Read the manifests and entry points (not every file), then write ${FOLDER}/index.html: one layer per role (entry points, modules, storage, external), 5-12 boxes, data-to wires
|
|
355
|
+
block('next_step', `Read the manifests and entry points (not every file), then write ${FOLDER}/index.html: one layer per role (entry points, modules, storage, external), 5-12 boxes, data-to wires with labels, data-src on every box that stands for code. Run \`${CMD} guide\` for the kit if you have not.`);
|
|
334
356
|
}
|
|
335
357
|
|
|
336
358
|
function cmdGuide() {
|
|
@@ -350,6 +372,7 @@ usage:
|
|
|
350
372
|
${CMD} check --ok <page> mark a page as reviewed after its code changed
|
|
351
373
|
${CMD} outline a compact map of the repo (folders, sizes, entry points) for a fast first blueprint
|
|
352
374
|
${CMD} guide how to write pages: folder rules, data-src, page kit, decisions
|
|
375
|
+
${CMD} export <page> [--out f] write the page as one self-contained HTML file to share
|
|
353
376
|
${CMD} progress "<text>" show a short status line in the chat while you work
|
|
354
377
|
${CMD} stop stop the background server
|
|
355
378
|
|
|
@@ -371,6 +394,7 @@ function parseArgs(argv) {
|
|
|
371
394
|
else if (a === '--timeout') opts.timeout = argv[++i];
|
|
372
395
|
else if (a === '--file') opts.file = argv[++i];
|
|
373
396
|
else if (a === '--ok') opts.ok = argv[++i];
|
|
397
|
+
else if (a === '--out') opts.out = argv[++i];
|
|
374
398
|
else if (a === '--help' || a === '-h') opts.help = true;
|
|
375
399
|
else if (a === '--version' || a === '-v') opts.version = true;
|
|
376
400
|
else args.push(a);
|
|
@@ -381,7 +405,7 @@ function parseArgs(argv) {
|
|
|
381
405
|
export async function main(argv) {
|
|
382
406
|
const { args, opts } = parseArgs(argv);
|
|
383
407
|
if (opts.version) return out(VERSION);
|
|
384
|
-
const commands = { listen: cmdListen, reply: cmdReply, check: cmdCheck, stop: cmdStop, guide: cmdGuide, progress: cmdProgress, outline: cmdOutline, help };
|
|
408
|
+
const commands = { listen: cmdListen, reply: cmdReply, check: cmdCheck, stop: cmdStop, guide: cmdGuide, progress: cmdProgress, outline: cmdOutline, export: cmdExport, help };
|
|
385
409
|
const name = args[0] && commands[args[0]] ? args.shift() : null;
|
|
386
410
|
if (opts.help || name === 'help') return help();
|
|
387
411
|
const root = findRoot();
|
package/src/export.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Turns a .truemap page into one self-contained HTML file: the kit, fonts, local images and the
|
|
2
|
+
// wire drawing are inlined, so it opens anywhere (email, a PR, a shared drive) without truemap running.
|
|
3
|
+
import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { dirname, extname, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { FOLDER, PKG_DIR, VERSION } from './common.js';
|
|
6
|
+
|
|
7
|
+
const KIT_DIR = join(PKG_DIR, 'kit');
|
|
8
|
+
const UI_DIR = join(PKG_DIR, 'src', 'ui');
|
|
9
|
+
const IMG = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml' };
|
|
10
|
+
|
|
11
|
+
/** A file inside dir, refusing traversal and symlinks that lead out. */
|
|
12
|
+
export function insideFile(dir, rel) {
|
|
13
|
+
try {
|
|
14
|
+
if (lstatSync(dir).isSymbolicLink()) return null;
|
|
15
|
+
const full = resolve(dir, '.' + sep + String(rel).replace(/\//g, sep));
|
|
16
|
+
if (full !== dir && !full.startsWith(dir + sep)) return null;
|
|
17
|
+
if (!existsSync(full)) return null;
|
|
18
|
+
const real = realpathSync(full); const realDir = realpathSync(dir);
|
|
19
|
+
if (!real.startsWith(realDir + sep) || statSync(real).isDirectory()) return null;
|
|
20
|
+
return real;
|
|
21
|
+
} catch { return null; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The page kit as served: a repo's own assets/truemap.css wins; assets/theme.css is appended. */
|
|
25
|
+
export function kitCss(root) {
|
|
26
|
+
const folder = join(root, FOLDER);
|
|
27
|
+
const own = insideFile(folder, 'assets/truemap.css');
|
|
28
|
+
let css = readFileSync(own || join(KIT_DIR, 'truemap.css'), 'utf8');
|
|
29
|
+
const theme = insideFile(folder, 'assets/theme.css');
|
|
30
|
+
if (theme) css += `\n/* .truemap/assets/theme.css */\n${readFileSync(theme, 'utf8')}`;
|
|
31
|
+
return css;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function exportPage(root, page) {
|
|
35
|
+
const folder = join(root, FOLDER);
|
|
36
|
+
const file = insideFile(folder, page);
|
|
37
|
+
if (!file) throw new Error(`page not found: ${FOLDER}/${page}`);
|
|
38
|
+
let html = readFileSync(file, 'utf8');
|
|
39
|
+
const pageDir = dirname(file);
|
|
40
|
+
|
|
41
|
+
// Fonts become data URIs so the export looks the same offline.
|
|
42
|
+
const css = kitCss(root).replace(/url\("\/__truemap\/fonts\/([\w.-]+\.woff2)"\)/g, (m, name) => {
|
|
43
|
+
const f = join(KIT_DIR, 'fonts', name);
|
|
44
|
+
return existsSync(f) ? `url("data:font/woff2;base64,${readFileSync(f).toString('base64')}")` : m;
|
|
45
|
+
});
|
|
46
|
+
const kitLink = /<link\b[^>]*href=["'](?:\.\.\/)*assets\/truemap\.css["'][^>]*>/i;
|
|
47
|
+
html = kitLink.test(html) ? html.replace(kitLink, () => `<style>\n${css}\n</style>`) : html.replace(/<\/head>/i, () => `<style>\n${css}\n</style>\n</head>`);
|
|
48
|
+
|
|
49
|
+
// Local images next to the page.
|
|
50
|
+
html = html.replace(/(<img\b[^>]*\bsrc=["'])([^"':]+?)(["'])/gi, (m, a, src, b) => {
|
|
51
|
+
const type = IMG[extname(src).toLowerCase()];
|
|
52
|
+
const f = type && insideFile(folder, relative(folder, join(pageDir, src)).split(sep).join('/'));
|
|
53
|
+
return f ? `${a}data:${type};base64,${readFileSync(f).toString('base64')}${b}` : m;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const wires = readFileSync(join(UI_DIR, 'wires.js'), 'utf8');
|
|
57
|
+
const boot = `<script>\n${wires}\n(() => { const d = () => window.truemapWires.draw(); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', d); else d(); addEventListener('resize', d); document.fonts && document.fonts.ready.then(d); })();\n</script>`;
|
|
58
|
+
const stamp = `<!-- Exported by truemap ${VERSION} from ${FOLDER}/${page} on ${new Date().toISOString().slice(0, 10)}. Links to other pages need the .truemap folder. -->`;
|
|
59
|
+
const note = `<p style="max-width:960px;margin:0 auto;padding:0 48px 40px;font:13px/1.5 var(--tm-font);color:var(--tm-pencil)">Exported from <code>${FOLDER}/${page}</code> with truemap. Links to other pages work inside the project's ${FOLDER} folder.</p>`;
|
|
60
|
+
html = /<\/body>/i.test(html) ? html.replace(/<\/body>(?![\s\S]*<\/body>)/i, () => `${note}\n${boot}\n</body>`) : html + note + boot;
|
|
61
|
+
return /<!doctype[^>]*>/i.test(html) ? html.replace(/<!doctype[^>]*>/i, (d) => `${d}\n${stamp}`) : `${stamp}\n${html}`;
|
|
62
|
+
}
|
package/src/guide.md
CHANGED
|
@@ -8,7 +8,7 @@ WHEN TO USE
|
|
|
8
8
|
|
|
9
9
|
THE FIRST BLUEPRINT (be fast)
|
|
10
10
|
- Run `{{CMD}} outline`. Read the manifests and entry points it lists, not every file.
|
|
11
|
-
- Write .truemap/index.html with 5-12 boxes in 3-
|
|
11
|
+
- Write .truemap/index.html with 5-12 boxes in 3-5 layers, open it, then go deeper only where the user asks.
|
|
12
12
|
A rough true map in two minutes beats a perfect one in twenty.
|
|
13
13
|
|
|
14
14
|
FOLDER RULES
|
|
@@ -27,6 +27,7 @@ ANCHORS (this is what keeps pages true)
|
|
|
27
27
|
<a class="tm-node" href="payments.html" data-src="src/pay/charge.ts#chargeCard">...</a>
|
|
28
28
|
path = file or folder relative to the repo root (exact case). #name = a function/class/route/config key that
|
|
29
29
|
literally appears in that file (whole word, case-sensitive). #name is optional; folders take no #name.
|
|
30
|
+
#name may be any literal text in the file, e.g. a route: data-src="server/api.ts#/api/orders".
|
|
30
31
|
- Anchored boxes get a small triangle mark automatically: "this box is pinned to code".
|
|
31
32
|
- Only anchor code you have actually read. Never invent paths.
|
|
32
33
|
- `{{CMD}} check` reports broken (path or name gone) and changed (code changed after the page was written).
|
|
@@ -46,8 +47,12 @@ Pages are working documents for engineers, read next to the code. They are not l
|
|
|
46
47
|
- Colors come only from the kit tokens. Status colors mean status, never decoration.
|
|
47
48
|
- Monospace only for real code: paths, symbols, commands.
|
|
48
49
|
- Boxes: 2-4 word titles taken from the code, one path line, at most one short sentence. At most 4 boxes per
|
|
49
|
-
layer
|
|
50
|
-
|
|
50
|
+
layer and 12 per map. More: split it – overview here, detail on the module's own page.
|
|
51
|
+
- Readability comes from few crossings: order boxes in each layer so wires run straight down, put a box under
|
|
52
|
+
the box that calls it, and prefer wires between neighbouring layers. Real loops (a callback, a reply going
|
|
53
|
+
back up) are fine: draw them, truemap routes them.
|
|
54
|
+
- Label every wire with what travels on it (data-to="runs:postUserMessage"), unless the label would only repeat
|
|
55
|
+
the target's name. The legend explains every line style and mark you used.
|
|
51
56
|
|
|
52
57
|
WRITING RULES
|
|
53
58
|
- Write like a senior engineer explaining to a colleague: plain verbs, concrete names from the code, active voice.
|
|
@@ -67,7 +72,7 @@ PAGE SKELETON
|
|
|
67
72
|
</head>
|
|
68
73
|
<body><main class="tm-page">
|
|
69
74
|
<header class="tm-header">
|
|
70
|
-
<nav class="tm-crumb"><a href="index.html">Shop blueprint</a> / Payments</nav>
|
|
75
|
+
<nav class="tm-crumb"><a href="index.html">Shop blueprint</a> / Payments</nav> (module pages only; index.html has none)
|
|
71
76
|
<h1 class="tm-title">Payments</h1>
|
|
72
77
|
<p class="tm-lede">Charges the card when an order is created and retries failed charges.</p>
|
|
73
78
|
</header>
|
|
@@ -76,8 +81,11 @@ PAGE SKELETON
|
|
|
76
81
|
</html>
|
|
77
82
|
|
|
78
83
|
KIT COMPONENTS
|
|
79
|
-
Map (layered structure with wires – the heart of index.html).
|
|
80
|
-
|
|
84
|
+
Map (layered structure with wires – the heart of index.html). You declare structure; truemap does the geometry.
|
|
85
|
+
Give boxes an id; data-to lists the ids they call or feed, separated by spaces, each with an optional wire label
|
|
86
|
+
after a colon (underscores become spaces; the label is everything after the first colon, so it may contain
|
|
87
|
+
colons): data-to="store:writes runs:postUserMessage db:node:sqlite". `check` reports ids
|
|
88
|
+
that don't exist. Never position boxes or draw wires yourself on a map.
|
|
81
89
|
<div class="tm-map">
|
|
82
90
|
<div class="tm-layer"><div class="tm-layer-label">HTTP routes</div><div class="tm-layer-nodes">
|
|
83
91
|
<div class="tm-node is-key" id="r-orders" data-to="orders" data-src="src/routes/api.ts#/api/orders">
|
|
@@ -95,9 +103,14 @@ call or feed, optionally with a short wire label after a colon (underscores beco
|
|
|
95
103
|
</div></div>
|
|
96
104
|
</div>
|
|
97
105
|
<div class="tm-legend"><span><i></i>Order path</span><span><i class="is-wire"></i>Calls</span><span><i class="is-mark"></i>Pinned to code</span></div>
|
|
98
|
-
Layers top to bottom = the direction requests or data travel.
|
|
99
|
-
|
|
100
|
-
|
|
106
|
+
Layers top to bottom = the direction requests or data travel. Wires may also point up (a reply, an event
|
|
107
|
+
stream) or sideways. A wire between two .is-key boxes is drawn blue.
|
|
108
|
+
Node modifiers: is-key (the main path), is-ext (outside this codebase: services, hosted APIs, databases and
|
|
109
|
+
files you talk to, dashed), is-new (just added), is-risk.
|
|
110
|
+
Legend: <i></i> the blue main path (wires between .is-key boxes), <i class="is-wire"></i> other wires,
|
|
111
|
+
<i class="is-ext"></i> outside the code, <i class="is-mark"></i> pinned to code. Include only the styles the map uses.
|
|
112
|
+
Boxes outside the codebase (is-ext) have no data-src.
|
|
113
|
+
Flow (a real sequence; add is-vertical for top-to-bottom). A step may carry one short sentence in .tm-node-desc:
|
|
101
114
|
<div class="tm-flow"><div class="tm-step" data-src="src/cart.ts#checkout"><b>Checkout</b><span class="tm-node-sub">checkout()</span></div><div class="tm-step">…</div></div>
|
|
102
115
|
Page index (on the blueprint):
|
|
103
116
|
<div class="tm-links"><a class="tm-link" href="payments.html"><strong>Payments</strong>How money moves and what happens on failure</a></div>
|
package/src/server.js
CHANGED
|
@@ -7,6 +7,7 @@ import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, statSync, wa
|
|
|
7
7
|
import { extname, join, resolve, sep } from 'node:path';
|
|
8
8
|
import { FOLDER, PKG_DIR, VERSION, appendPrivate, historyPath, serverStatePath, writePrivate } from './common.js';
|
|
9
9
|
import { checkAll, listPages } from './check.js';
|
|
10
|
+
import { exportPage, kitCss } from './export.js';
|
|
10
11
|
|
|
11
12
|
const root = resolve(process.argv[2] || process.cwd());
|
|
12
13
|
const folder = join(root, FOLDER);
|
|
@@ -33,6 +34,7 @@ let listener = null; // { res, timer } – the single active `lis
|
|
|
33
34
|
let agentState = 'offline'; // offline (never seen) | listening | working | idle (back in the terminal)
|
|
34
35
|
let agentName = ''; // claude-code | codex | ''
|
|
35
36
|
let agentSince = 0; // when the current state began
|
|
37
|
+
let endRequested = false; // the user pressed End conversation while the agent wasn't listening
|
|
36
38
|
let annotateWish; // set by `truemap <page> --annotate` before a tab is open
|
|
37
39
|
let lastAgentActivity = 0;
|
|
38
40
|
let currentPage = null;
|
|
@@ -245,12 +247,7 @@ function serveStatic(res, dir, name, cache = 'no-store') {
|
|
|
245
247
|
// The page kit comes from truemap itself, so every repo gets kit updates. A repo may still keep its own
|
|
246
248
|
// assets/truemap.css (older setups, or a hand-tuned copy): that copy wins. assets/theme.css is appended.
|
|
247
249
|
function serveKit(res) {
|
|
248
|
-
const
|
|
249
|
-
let css = readFileSync(own || join(KIT_DIR, 'truemap.css'), 'utf8');
|
|
250
|
-
const theme = folderIsSafe() ? safeFile(folder, 'assets/theme.css') : null;
|
|
251
|
-
if (theme) css += `
|
|
252
|
-
/* .truemap/assets/theme.css */
|
|
253
|
-
${readFileSync(theme, 'utf8')}`;
|
|
250
|
+
const css = kitCss(root);
|
|
254
251
|
res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
255
252
|
res.end(css);
|
|
256
253
|
}
|
|
@@ -325,6 +322,7 @@ const server = createServer(async (req, res) => {
|
|
|
325
322
|
...(answer ? { answer } : {}),
|
|
326
323
|
};
|
|
327
324
|
queue.push(msg);
|
|
325
|
+
endRequested = false; // a new message means the conversation goes on
|
|
328
326
|
remember({ role: 'user', ...msg });
|
|
329
327
|
deliverQueue();
|
|
330
328
|
return sendJson(res, 200, { ok: true, id: msg.id, delivered: !queue.includes(msg) });
|
|
@@ -336,6 +334,20 @@ const server = createServer(async (req, res) => {
|
|
|
336
334
|
return sendJson(res, 200, { ok: true });
|
|
337
335
|
}
|
|
338
336
|
if (p === '/api/check' && req.method === 'POST') return sendJson(res, 200, runChecks());
|
|
337
|
+
if (p === '/api/export' && req.method === 'GET') {
|
|
338
|
+
const page = url.searchParams.get('page') || '';
|
|
339
|
+
let html;
|
|
340
|
+
try { html = exportPage(root, page); } catch (e) { return sendText(res, 404, String(e.message || e)); }
|
|
341
|
+
const name = page.split('/').pop().replace(/\.html?$/i, '') || 'page';
|
|
342
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}-truemap.html"` });
|
|
343
|
+
return res.end(html);
|
|
344
|
+
}
|
|
345
|
+
if (p === '/api/end' && req.method === 'POST') {
|
|
346
|
+
// The user is done talking on the page: free the agent to go back to the terminal.
|
|
347
|
+
if (listener) finishListen({ status: 'ended' }); else if (agentState === 'working' || agentState === 'listening') endRequested = true;
|
|
348
|
+
setAgentState('idle');
|
|
349
|
+
return sendJson(res, 200, { ok: true });
|
|
350
|
+
}
|
|
339
351
|
|
|
340
352
|
// ----- agent (CLI) side -----
|
|
341
353
|
if (p === '/api/agent/status' && req.method === 'GET') {
|
|
@@ -354,6 +366,7 @@ const server = createServer(async (req, res) => {
|
|
|
354
366
|
if (listener && listener.res === res) { clearTimeout(listener.timer); listener = null; setAgentState('idle'); }
|
|
355
367
|
});
|
|
356
368
|
if (queue.length) return deliverQueue();
|
|
369
|
+
if (endRequested) { endRequested = false; finishListen({ status: 'ended' }); setAgentState('idle'); return; }
|
|
357
370
|
setAgentState('listening');
|
|
358
371
|
if (clients.size === 0) scheduleCloseCheck();
|
|
359
372
|
return;
|
|
@@ -400,7 +413,7 @@ const content = createServer((req, res) => {
|
|
|
400
413
|
const p = new URL(req.url, `http://127.0.0.1:${contentPort}`).pathname;
|
|
401
414
|
try {
|
|
402
415
|
if (p === '/__truemap/sdk.js') {
|
|
403
|
-
const js = readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
|
|
416
|
+
const js = readFileSync(join(UI_DIR, 'wires.js'), 'utf8') + '\n' + readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
|
|
404
417
|
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
405
418
|
return res.end(js);
|
|
406
419
|
}
|
package/src/ui/sdk.js
CHANGED
|
@@ -27,10 +27,8 @@
|
|
|
27
27
|
[data-tm-mark="broken"] { outline: 2px dashed var(--tm-broken, #b03a2e) !important; outline-offset: 3px; }
|
|
28
28
|
svg [data-tm-mark] { outline: none !important; }
|
|
29
29
|
html[data-tm-annotate] body { cursor: default; }
|
|
30
|
-
html[data-tm-annotate] [data-tm-hover] {
|
|
30
|
+
html[data-tm-annotate] [data-tm-hover] { cursor: pointer; }
|
|
31
31
|
html[data-tm-annotate] a, html[data-tm-annotate] label { cursor: pointer; }
|
|
32
|
-
[data-tm-noted] { outline: 1.5px solid color-mix(in oklab, var(--tm-route, #2453c4) 55%, transparent); outline-offset: 3px; }
|
|
33
|
-
[data-tm-active] { outline: 2px solid var(--tm-route, #2453c4) !important; outline-offset: 3px; }
|
|
34
32
|
@keyframes tm-flash { 0%,100% { outline-color: transparent } 35% { outline-color: var(--tm-route, #2453c4) } }
|
|
35
33
|
[data-tm-flash] { outline: 2px solid var(--tm-route, #2453c4) !important; outline-offset: 4px; animation: tm-flash 1.1s ease 2; }
|
|
36
34
|
@media (prefers-reduced-motion: reduce) { [data-tm-flash] { animation: none; } }
|
|
@@ -38,98 +36,7 @@
|
|
|
38
36
|
`;
|
|
39
37
|
(document.head || document.documentElement).appendChild(style);
|
|
40
38
|
|
|
41
|
-
|
|
42
|
-
const SVGNS = 'http://www.w3.org/2000/svg';
|
|
43
|
-
function drawWires() {
|
|
44
|
-
document.documentElement.style.setProperty('--tm-vw', `${document.documentElement.clientWidth}px`);
|
|
45
|
-
for (const map of document.querySelectorAll('.tm-map, .tm-blueprint')) {
|
|
46
|
-
map.querySelector(':scope > svg.tm-wires')?.remove();
|
|
47
|
-
const sources = [...map.querySelectorAll('[data-to]')];
|
|
48
|
-
if (!sources.length) continue;
|
|
49
|
-
// Coordinates live in the map's scroll space, so wires scroll with the boxes.
|
|
50
|
-
const box = map.getBoundingClientRect();
|
|
51
|
-
const ox = box.left + map.clientLeft - map.scrollLeft; const oy = box.top + map.clientTop - map.scrollTop;
|
|
52
|
-
const w = map.scrollWidth; const h = map.scrollHeight;
|
|
53
|
-
const svg = document.createElementNS(SVGNS, 'svg');
|
|
54
|
-
svg.setAttribute('class', 'tm-wires'); svg.setAttribute('aria-hidden', 'true');
|
|
55
|
-
svg.setAttribute('width', w); svg.setAttribute('height', h);
|
|
56
|
-
svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
|
|
57
|
-
const rel = (r) => ({ l: r.left - ox, r: r.right - ox, t: r.top - oy, b: r.bottom - oy, cx: (r.left + r.right) / 2 - ox, cy: (r.top + r.bottom) / 2 - oy });
|
|
58
|
-
// Collect edges first so wires sharing a box get their own exit, entry and track (no merged lines).
|
|
59
|
-
const edges = [];
|
|
60
|
-
for (const src of sources) {
|
|
61
|
-
for (const spec of src.getAttribute('data-to').split(/\s+/).filter(Boolean)) {
|
|
62
|
-
const [id, ...labelParts] = spec.split(':');
|
|
63
|
-
const dst = document.getElementById(id);
|
|
64
|
-
if (!dst || dst === src || !map.contains(dst)) continue;
|
|
65
|
-
edges.push({ src, dst, label: labelParts.join(':').replace(/_/g, ' '), a: rel(src.getBoundingClientRect()), b: rel(dst.getBoundingClientRect()) });
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
const down = (e) => e.b.t >= e.a.b - 2;
|
|
69
|
-
const slot = (list, e) => { const i = list.indexOf(e); return i - (list.length - 1) / 2; };
|
|
70
|
-
const outOf = new Map(); const into = new Map();
|
|
71
|
-
for (const e of edges.filter(down)) {
|
|
72
|
-
(outOf.get(e.src) || outOf.set(e.src, []).get(e.src)).push(e);
|
|
73
|
-
(into.get(e.dst) || into.set(e.dst, []).get(e.dst)).push(e);
|
|
74
|
-
}
|
|
75
|
-
for (const l of [...outOf.values(), ...into.values()]) l.sort((p, q) => p.b.cx - q.b.cx || p.a.cx - q.a.cx);
|
|
76
|
-
for (const e of edges) {
|
|
77
|
-
const { src, dst, a, b } = e;
|
|
78
|
-
const key = src.classList.contains('is-key') && dst.classList.contains('is-key');
|
|
79
|
-
const ext = dst.classList.contains('is-ext') || src.classList.contains('is-ext');
|
|
80
|
-
let d; let head; let mid;
|
|
81
|
-
const r = 7;
|
|
82
|
-
if (down(e)) { // below: leave from the bottom, enter at the top
|
|
83
|
-
const so = slot(outOf.get(src), e); const ti = slot(into.get(dst), e);
|
|
84
|
-
const sx = a.cx + so * 14; const sy = a.b; const tx = b.cx + ti * 14; const ty = b.t - 6;
|
|
85
|
-
const my = sy + Math.max(12, Math.min(22, (ty - sy) / 2)) + ti * 7;
|
|
86
|
-
if (Math.abs(tx - sx) < 2) d = `M${sx},${sy} V${ty}`;
|
|
87
|
-
else {
|
|
88
|
-
const dir = tx > sx ? 1 : -1; const rr = Math.min(r, Math.abs(tx - sx) / 2);
|
|
89
|
-
d = `M${sx},${sy} V${my - rr} Q${sx},${my} ${sx + dir * rr},${my} H${tx - dir * rr} Q${tx},${my} ${tx},${my + rr} V${ty}`;
|
|
90
|
-
}
|
|
91
|
-
head = `M${tx - 4.5},${ty - 1} L${tx + 4.5},${ty - 1} L${tx},${ty + 6} Z`;
|
|
92
|
-
// the label sits by the box the wire leaves, so it is clear which wire it names
|
|
93
|
-
mid = { x: sx - 2, y: Math.min(sy + 10, my - 6) };
|
|
94
|
-
} else if (b.b <= a.t + 2) { // above
|
|
95
|
-
const sx = a.cx; const sy = a.t; const tx = b.cx; const ty = b.b + 6;
|
|
96
|
-
const my = sy - Math.max(12, Math.min(22, (sy - ty) / 2));
|
|
97
|
-
const dir = tx > sx ? 1 : -1;
|
|
98
|
-
d = Math.abs(tx - sx) < 2 ? `M${sx},${sy} V${ty}` : `M${sx},${sy} V${my + r} Q${sx},${my} ${sx + dir * r},${my} H${tx - dir * r} Q${tx},${my} ${tx},${my - r} V${ty}`;
|
|
99
|
-
head = `M${tx - 4.5},${ty + 1} L${tx + 4.5},${ty + 1} L${tx},${ty - 6} Z`;
|
|
100
|
-
mid = { x: tx, y: (my + ty) / 2 };
|
|
101
|
-
} else { // same row: side to side
|
|
102
|
-
const right = b.l >= a.r;
|
|
103
|
-
const sx = right ? a.r : a.l; const tx = right ? b.l - 6 : b.r + 6;
|
|
104
|
-
const sy = a.cy; const ty = b.cy; const mx = (sx + tx) / 2;
|
|
105
|
-
d = Math.abs(ty - sy) < 2 ? `M${sx},${sy} H${tx}` : `M${sx},${sy} H${mx} V${ty} H${tx}`;
|
|
106
|
-
head = right ? `M${tx - 1},${ty - 4.5} L${tx - 1},${ty + 4.5} L${tx + 6},${ty} Z` : `M${tx + 1},${ty - 4.5} L${tx + 1},${ty + 4.5} L${tx - 6},${ty} Z`;
|
|
107
|
-
mid = { x: mx, y: ty - 6 };
|
|
108
|
-
}
|
|
109
|
-
const path = document.createElementNS(SVGNS, 'path');
|
|
110
|
-
path.setAttribute('d', d); path.setAttribute('class', `tm-wire${key ? ' is-key' : ''}${ext ? ' is-ext' : ''}`);
|
|
111
|
-
const arrow = document.createElementNS(SVGNS, 'path');
|
|
112
|
-
arrow.setAttribute('d', head); arrow.setAttribute('class', `tm-wire-head${key ? ' is-key' : ''}`);
|
|
113
|
-
svg.appendChild(path);
|
|
114
|
-
svg.appendChild(arrow);
|
|
115
|
-
if (e.label) {
|
|
116
|
-
const t = document.createElementNS(SVGNS, 'text');
|
|
117
|
-
t.setAttribute('class', 'tm-wire-label'); t.setAttribute('x', mid.x + 8); t.setAttribute('y', mid.y + 4);
|
|
118
|
-
t.textContent = e.label; svg.appendChild(t);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
// key wires on top, labels above every wire
|
|
122
|
-
[...svg.querySelectorAll('.tm-wire.is-key, .tm-wire-head.is-key')].forEach((el) => svg.appendChild(el));
|
|
123
|
-
[...svg.querySelectorAll('.tm-wire-label')].forEach((el) => svg.appendChild(el));
|
|
124
|
-
map.insertBefore(svg, map.firstChild);
|
|
125
|
-
markScroll(map);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
// A map wider than the window fades at the edge it can scroll towards.
|
|
129
|
-
function markScroll(map) {
|
|
130
|
-
map.classList.toggle('tm-scrolls', map.scrollWidth - map.clientWidth - map.scrollLeft > 4);
|
|
131
|
-
if (!map.__tmScroll) { map.__tmScroll = true; map.addEventListener('scroll', () => markScroll(map), { passive: true }); }
|
|
132
|
-
}
|
|
39
|
+
const drawWires = () => window.truemapWires?.draw();
|
|
133
40
|
let wireTimer = null;
|
|
134
41
|
const scheduleWires = () => { clearTimeout(wireTimer); wireTimer = setTimeout(() => { drawWires(); placePins(); }, 40); };
|
|
135
42
|
|
|
@@ -161,15 +68,63 @@
|
|
|
161
68
|
}
|
|
162
69
|
return parts.join(' > ');
|
|
163
70
|
}
|
|
71
|
+
let rings = null;
|
|
164
72
|
function setHover(el) {
|
|
165
73
|
if (hovered === el) return;
|
|
166
74
|
hovered?.removeAttribute('data-tm-hover');
|
|
167
75
|
hovered = el; el?.setAttribute('data-tm-hover', '');
|
|
76
|
+
paintRings();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Highlights are drawn in the top layer, never as CSS outlines, so a scrolling or clipped container
|
|
80
|
+
// can't cut them off. A ring covers the element and everything inside it (a badge that sticks out too).
|
|
81
|
+
function extentOf(el) {
|
|
82
|
+
const r0 = el.getBoundingClientRect();
|
|
83
|
+
let l = r0.left; let t = r0.top; let r = r0.right; let b = r0.bottom;
|
|
84
|
+
const kids = [...el.querySelectorAll('*')].slice(0, 400);
|
|
85
|
+
// Content scrolled out of view inside a scrolling block (a long code line, a map) doesn't count.
|
|
86
|
+
const clips = [el, ...kids].filter((n) => { const s = getComputedStyle(n); return s.overflowX !== 'visible' || s.overflowY !== 'visible'; });
|
|
87
|
+
for (const kid of kids) {
|
|
88
|
+
const k = kid.getBoundingClientRect();
|
|
89
|
+
if (!k.width || !k.height) continue;
|
|
90
|
+
let kl = k.left; let kt = k.top; let kr = k.right; let kb = k.bottom;
|
|
91
|
+
for (const c of clips) {
|
|
92
|
+
if (c === kid || !c.contains(kid)) continue;
|
|
93
|
+
const cr = c.getBoundingClientRect();
|
|
94
|
+
kl = Math.max(kl, cr.left); kt = Math.max(kt, cr.top); kr = Math.min(kr, cr.right); kb = Math.min(kb, cr.bottom);
|
|
95
|
+
}
|
|
96
|
+
if (kr <= kl || kb <= kt) continue;
|
|
97
|
+
l = Math.min(l, kl); t = Math.min(t, kt); r = Math.max(r, kr); b = Math.max(b, kb);
|
|
98
|
+
}
|
|
99
|
+
// An element half scrolled out of its own scrolling parent is cut at that parent's edge too.
|
|
100
|
+
for (let a = el.parentElement; a && a !== document.body; a = a.parentElement) {
|
|
101
|
+
const s = getComputedStyle(a);
|
|
102
|
+
if (s.overflowX === 'visible' && s.overflowY === 'visible') continue;
|
|
103
|
+
const ar = a.getBoundingClientRect();
|
|
104
|
+
l = Math.max(l, ar.left - 2); t = Math.max(t, ar.top - 2); r = Math.min(r, ar.right + 2); b = Math.min(b, ar.bottom + 2);
|
|
105
|
+
}
|
|
106
|
+
return { left: l + scrollX - 4, top: t + scrollY - 4, width: r - l + 8, height: b - t + 8 };
|
|
107
|
+
}
|
|
108
|
+
function paintRings() {
|
|
109
|
+
if (!rings) return;
|
|
110
|
+
rings.innerHTML = '';
|
|
111
|
+
const ring = (el, cls) => {
|
|
112
|
+
if (!el?.isConnected) return;
|
|
113
|
+
mount();
|
|
114
|
+
const x = extentOf(el); const d = document.createElement('div');
|
|
115
|
+
d.className = `ring ${cls}`;
|
|
116
|
+
Object.assign(d.style, { left: `${x.left}px`, top: `${x.top}px`, width: `${x.width}px`, height: `${x.height}px` });
|
|
117
|
+
rings.appendChild(d);
|
|
118
|
+
};
|
|
119
|
+
for (const n of notes.values()) if (n.el && n.el !== card?.target) ring(n.el, 'noted');
|
|
120
|
+
if (card?.target) ring(card.target, 'active');
|
|
121
|
+
else if (annotating && hovered) ring(hovered, 'hover');
|
|
168
122
|
}
|
|
169
123
|
function setAnnotate(on) {
|
|
170
124
|
annotating = !!on;
|
|
171
125
|
document.documentElement.toggleAttribute('data-tm-annotate', annotating);
|
|
172
126
|
if (!annotating) { setHover(null); }
|
|
127
|
+
paintRings();
|
|
173
128
|
}
|
|
174
129
|
|
|
175
130
|
// Shadow layer for the comment card, pins and the selection button: page CSS can't touch it.
|
|
@@ -198,6 +153,10 @@
|
|
|
198
153
|
.btn.primary:hover { background: #1b3f96; }
|
|
199
154
|
.btn.danger { color: #b03a2e; }
|
|
200
155
|
.btn:focus-visible { outline: 2px solid #2453c4; outline-offset: 2px; }
|
|
156
|
+
.ring { position: absolute; border: 1.5px solid #2453c4; border-radius: 8px; pointer-events: none; }
|
|
157
|
+
.ring.active { border-width: 2px; }
|
|
158
|
+
.ring.noted { border-color: rgba(36, 83, 196, .5); }
|
|
159
|
+
@media (prefers-color-scheme: dark) { .ring { border-color: #7ea3ff; } .ring.noted { border-color: rgba(126, 163, 255, .55); } }
|
|
201
160
|
.pin { position: absolute; width: 20px; height: 20px; border-radius: 50%; background: #2453c4; color: #fff;
|
|
202
161
|
font: 600 11px/20px "IBM Plex Mono", ui-monospace, Consolas, monospace; text-align: center; cursor: pointer; border: 2px solid #fff; box-shadow: 0 1px 3px rgba(23,32,43,.25); }
|
|
203
162
|
.select-btn { position: absolute; all: unset; position: absolute; cursor: pointer; background: #17202b; color: #fff; font: 500 12.5px/1 "IBM Plex Sans", system-ui, sans-serif; padding: 7px 10px; border-radius: 6px; box-shadow: 0 6px 18px -8px rgba(23,32,43,.5); }
|
|
@@ -211,9 +170,10 @@
|
|
|
211
170
|
.btn.primary { background: #2453c4; color: #fff; }
|
|
212
171
|
.pin { border-color: #121519; }
|
|
213
172
|
}
|
|
214
|
-
</style><div id="pins"></div><div id="slot"></div>`;
|
|
173
|
+
</style><div id="rings"></div><div id="pins"></div><div id="slot"></div>`;
|
|
215
174
|
const pinsEl = shadow.getElementById('pins');
|
|
216
175
|
const slot = shadow.getElementById('slot');
|
|
176
|
+
rings = shadow.getElementById('rings');
|
|
217
177
|
const mount = () => { if (!host.isConnected) document.body.appendChild(host); };
|
|
218
178
|
|
|
219
179
|
let card = null; // { el, target, textRange, noteId }
|
|
@@ -228,7 +188,7 @@
|
|
|
228
188
|
if (!card) return;
|
|
229
189
|
card.target?.removeAttribute('data-tm-active');
|
|
230
190
|
card.el.remove(); card = null;
|
|
231
|
-
paintHighlights();
|
|
191
|
+
paintHighlights(); paintRings();
|
|
232
192
|
}
|
|
233
193
|
function docRect(r) { return { left: r.left + scrollX, top: r.top + scrollY, right: r.right + scrollX, bottom: r.bottom + scrollY, width: r.width, height: r.height }; }
|
|
234
194
|
|
|
@@ -265,7 +225,7 @@
|
|
|
265
225
|
el.style.left = `${left}px`; el.style.top = `${top}px`;
|
|
266
226
|
target?.setAttribute('data-tm-active', '');
|
|
267
227
|
card = { el, target, text, noteId, label, src, rect: r, range };
|
|
268
|
-
paintHighlights();
|
|
228
|
+
paintHighlights(); paintRings();
|
|
269
229
|
const finish = (sendNow) => {
|
|
270
230
|
const value = ta.value.trim();
|
|
271
231
|
if (!value) { ta.focus(); return; }
|
|
@@ -310,6 +270,7 @@
|
|
|
310
270
|
paintHighlights();
|
|
311
271
|
pinsEl.innerHTML = '';
|
|
312
272
|
for (const el of document.querySelectorAll('[data-tm-noted]')) el.removeAttribute('data-tm-noted');
|
|
273
|
+
paintRings();
|
|
313
274
|
if (!notes.size) return;
|
|
314
275
|
mount();
|
|
315
276
|
let i = 0;
|
|
@@ -317,7 +278,7 @@
|
|
|
317
278
|
i++;
|
|
318
279
|
let r = null;
|
|
319
280
|
if (n.el && !n.el.isConnected && n.selector) { try { n.el = document.querySelector(n.selector); } catch { n.el = null; } }
|
|
320
|
-
if (n.el?.isConnected) {
|
|
281
|
+
if (n.el?.isConnected) { const x = extentOf(n.el); r = { left: x.left + 4, top: x.top + 4 }; n.el.setAttribute('data-tm-noted', ''); }
|
|
321
282
|
else if (n.rect) r = n.rect;
|
|
322
283
|
if (!r) continue;
|
|
323
284
|
const pin = document.createElement('div');
|
|
@@ -458,6 +419,8 @@
|
|
|
458
419
|
scrollTimer = setTimeout(() => post({ type: 'scroll', page: pagePath(), y: window.scrollY }), 120);
|
|
459
420
|
}, { passive: true });
|
|
460
421
|
window.addEventListener('resize', scheduleWires);
|
|
422
|
+
// Rings follow their element when anything scrolls, including a map scrolling sideways.
|
|
423
|
+
document.addEventListener('scroll', () => { if (rings && (hovered || card || notes.size)) { placePins(); } }, { capture: true, passive: true });
|
|
461
424
|
|
|
462
425
|
const ready = () => {
|
|
463
426
|
drawWires();
|
package/src/ui/wires.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// Draws the wires of every .tm-map from data-to="id id:label". Used by the page SDK and by exported pages.
|
|
2
|
+
// Plain script, no dependencies: defines window.truemapWires.draw().
|
|
3
|
+
//
|
|
4
|
+
// Rules that keep the map honest:
|
|
5
|
+
// - a wire only touches its own two boxes; layers in between are crossed through free columns
|
|
6
|
+
// - every horizontal run in a gap between layers gets its own track (wires from the same box may share one)
|
|
7
|
+
// - a gap grows when it needs more tracks
|
|
8
|
+
// - exits leave from the middle of a box, entries arrive in its left third (upward ones: right third)
|
|
9
|
+
(() => {
|
|
10
|
+
if (window.truemapWires) return;
|
|
11
|
+
const SVGNS = 'http://www.w3.org/2000/svg';
|
|
12
|
+
const LANE = 9; const R = 7;
|
|
13
|
+
|
|
14
|
+
// An orthogonal path through the given points with rounded corners.
|
|
15
|
+
function ortho(points) {
|
|
16
|
+
const pts = points.filter((p, i) => i === 0 || p[0] !== points[i - 1][0] || p[1] !== points[i - 1][1]);
|
|
17
|
+
let d = `M${pts[0][0]},${pts[0][1]}`;
|
|
18
|
+
for (let i = 1; i < pts.length - 1; i++) {
|
|
19
|
+
const [px, py] = pts[i - 1]; const [x, y] = pts[i]; const [nx, ny] = pts[i + 1];
|
|
20
|
+
const l1 = Math.hypot(x - px, y - py); const l2 = Math.hypot(nx - x, ny - y);
|
|
21
|
+
if (!l1 || !l2 || (px === x && x === nx) || (py === y && y === ny)) continue;
|
|
22
|
+
const rr = Math.min(R, l1 / 2, l2 / 2);
|
|
23
|
+
d += ` L${x - ((x - px) / l1) * rr},${y - ((y - py) / l1) * rr} Q${x},${y} ${x + ((nx - x) / l2) * rr},${y + ((ny - y) / l2) * rr}`;
|
|
24
|
+
}
|
|
25
|
+
const last = pts[pts.length - 1];
|
|
26
|
+
return `${d} L${last[0]},${last[1]}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function drawMap(map) {
|
|
30
|
+
map.querySelector(':scope > svg.tm-wires')?.remove();
|
|
31
|
+
const sources = [...map.querySelectorAll('[data-to]')];
|
|
32
|
+
if (!sources.length) return false;
|
|
33
|
+
// Coordinates live in the map's scroll space, so wires scroll with the boxes.
|
|
34
|
+
const box = map.getBoundingClientRect();
|
|
35
|
+
const ox = box.left + map.clientLeft - map.scrollLeft; const oy = box.top + map.clientTop - map.scrollTop;
|
|
36
|
+
const rel = (r) => ({ l: r.left - ox, r: r.right - ox, t: r.top - oy, b: r.bottom - oy, cx: (r.left + r.right) / 2 - ox, cy: (r.top + r.bottom) / 2 - oy });
|
|
37
|
+
const rects = [...map.querySelectorAll('.tm-node, .tm-step')].map((n) => ({ n, ...rel(n.getBoundingClientRect()) }));
|
|
38
|
+
const rectOf = new Map(rects.map((o) => [o.n, o]));
|
|
39
|
+
|
|
40
|
+
// Rows: boxes that overlap vertically. Gap i lies between row i and row i+1.
|
|
41
|
+
const rows = [];
|
|
42
|
+
for (const o of [...rects].sort((p, q) => p.t - q.t)) {
|
|
43
|
+
const row = rows.find((w) => o.t < w.b - 2 && o.b > w.t + 2);
|
|
44
|
+
if (row) { row.t = Math.min(row.t, o.t); row.b = Math.max(row.b, o.b); row.items.push(o); } else rows.push({ t: o.t, b: o.b, items: [o] });
|
|
45
|
+
}
|
|
46
|
+
rows.sort((p, q) => p.t - q.t);
|
|
47
|
+
const rowOf = (o) => rows.findIndex((w) => w.items.includes(o));
|
|
48
|
+
|
|
49
|
+
const edges = [];
|
|
50
|
+
for (const src of sources) {
|
|
51
|
+
for (const spec of src.getAttribute('data-to').split(/[\s,]+/).filter(Boolean)) {
|
|
52
|
+
const [id, ...labelParts] = spec.split(':');
|
|
53
|
+
const dst = document.getElementById(id);
|
|
54
|
+
if (!dst || dst === src || !map.contains(dst) || !rectOf.has(src) || !rectOf.has(dst)) continue;
|
|
55
|
+
const a = rectOf.get(src); const b = rectOf.get(dst);
|
|
56
|
+
const ra = rowOf(a); const rb = rowOf(b);
|
|
57
|
+
edges.push({ src, dst, a, b, ra, rb, dir: rb > ra ? 'down' : rb < ra ? 'up' : 'same', label: labelParts.join(':').replace(/_/g, ' ') });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const group = (key, pick) => {
|
|
61
|
+
const m = new Map();
|
|
62
|
+
for (const e of edges.filter(pick)) (m.get(e[key]) || m.set(e[key], []).get(e[key])).push(e);
|
|
63
|
+
for (const l of m.values()) l.sort((p, q) => (key === 'src' ? p.b.cx - q.b.cx : p.a.cx - q.a.cx));
|
|
64
|
+
return m;
|
|
65
|
+
};
|
|
66
|
+
const downOut = group('src', (e) => e.dir === 'down'); const downIn = group('dst', (e) => e.dir === 'down');
|
|
67
|
+
const upOut = group('src', (e) => e.dir === 'up'); const upIn = group('dst', (e) => e.dir === 'up');
|
|
68
|
+
const slot = (list, e) => list.indexOf(e) - (list.length - 1) / 2;
|
|
69
|
+
|
|
70
|
+
// Free vertical columns through rows lo..hi (exclusive of the wire's own boxes), one wire per column.
|
|
71
|
+
const columns = [];
|
|
72
|
+
function column(e, lo, hi, prefer) {
|
|
73
|
+
const blockers = rects.filter((o) => { const r = rowOf(o); return r > lo && r < hi; });
|
|
74
|
+
const free = (x) => !blockers.some((o) => x > o.l - 7 && x < o.r + 7)
|
|
75
|
+
&& !columns.some((c) => Math.abs(c.x - x) < 8 && c.src !== e.src && c.lo < hi && c.hi > lo);
|
|
76
|
+
const cands = [prefer[0], prefer[1], ...blockers.flatMap((o) => [o.l - 13, o.r + 13])];
|
|
77
|
+
for (const c of [...cands]) for (let k = 1; k <= 4; k++) cands.push(c + k * 9, c - k * 9);
|
|
78
|
+
const x = cands.filter(free).sort((p, q) => Math.abs(p - prefer[0]) + Math.abs(p - prefer[1]) - Math.abs(q - prefer[0]) - Math.abs(q - prefer[1]))[0] ?? prefer[0];
|
|
79
|
+
columns.push({ x, lo, hi, src: e.src });
|
|
80
|
+
return x;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Plan every wire. Horizontal runs in a gap are recorded as lane requests and get their y later.
|
|
84
|
+
const lanes = new Map(); // gap index -> [{x1, x2, src, ref}]
|
|
85
|
+
const lane = (gap, x1, x2, e) => { const ref = { y: null, gap }; ref.item = { x1: Math.min(x1, x2), x2: Math.max(x1, x2), src: e.src, ref }; (lanes.get(gap) || lanes.set(gap, []).get(gap)).push(ref.item); return ref; };
|
|
86
|
+
const plans = [];
|
|
87
|
+
for (const e of edges) {
|
|
88
|
+
const { a, b } = e;
|
|
89
|
+
if (e.dir === 'down') {
|
|
90
|
+
const sx = a.cx + slot(downOut.get(e.src), e) * 14; const sy = a.b; const ty = b.t - 6;
|
|
91
|
+
const ins = downIn.get(e.dst); const ti = ins.indexOf(e);
|
|
92
|
+
const straight = ins.length === 1 && Math.abs(a.cx - b.cx) < 4;
|
|
93
|
+
const tx = straight ? b.cx : Math.min(b.l + 26 + ti * 14, b.cx - 14);
|
|
94
|
+
if (e.rb === e.ra + 1) {
|
|
95
|
+
if (Math.abs(sx - tx) < 1) plans.push({ e, pts: [[sx, sy], [tx, ty]], head: 'down', tx, ty, label: { x: sx + 6, y: sy + 13 } });
|
|
96
|
+
else { const y = lane(e.ra, sx, tx, e); plans.push({ e, pts: [[sx, sy], [sx, y], [tx, y], [tx, ty]], head: 'down', tx, ty, label: { x: sx + 6, y: sy + 13 } }); }
|
|
97
|
+
} else {
|
|
98
|
+
const x = column(e, e.ra, e.rb, [sx, tx]);
|
|
99
|
+
const y1 = lane(e.ra, sx, x, e); const y2 = lane(e.rb - 1, x, tx, e);
|
|
100
|
+
plans.push({ e, pts: [[sx, sy], [sx, y1], [x, y1], [x, y2], [tx, y2], [tx, ty]], head: 'down', tx, ty, label: { x: sx + 6, y: sy + 13 } });
|
|
101
|
+
}
|
|
102
|
+
} else if (e.dir === 'up') {
|
|
103
|
+
const sx = a.r - 26 - (slot(upOut.get(e.src), e) + (upOut.get(e.src).length - 1) / 2) * 14; const sy = a.t;
|
|
104
|
+
const tx = b.r - 26 - upIn.get(e.dst).indexOf(e) * 14; const ty = b.b + 6;
|
|
105
|
+
if (e.rb === e.ra - 1) {
|
|
106
|
+
const y = lane(e.rb, sx, tx, e);
|
|
107
|
+
plans.push({ e, pts: [[sx, sy], [sx, y], [tx, y], [tx, ty]], head: 'up', tx, ty, label: { x: sx + 6, y: sy - 6 } });
|
|
108
|
+
} else {
|
|
109
|
+
const x = column(e, e.rb, e.ra, [sx, tx]);
|
|
110
|
+
const y1 = lane(e.ra - 1, sx, x, e); const y2 = lane(e.rb, x, tx, e);
|
|
111
|
+
plans.push({ e, pts: [[sx, sy], [sx, y1], [x, y1], [x, y2], [tx, y2], [tx, ty]], head: 'up', tx, ty, label: { x: sx + 6, y: sy - 6 } });
|
|
112
|
+
}
|
|
113
|
+
} else {
|
|
114
|
+
const blocked = rects.some((o) => o.n !== e.src && o.n !== e.dst && rowOf(o) === e.ra && o.l >= Math.min(a.r, b.r) - 1 && o.r <= Math.max(a.l, b.l) + 1);
|
|
115
|
+
if (!blocked) { // side by side
|
|
116
|
+
const right = b.l >= a.r; const sx = right ? a.r : a.l; const tx = right ? b.l - 6 : b.r + 6;
|
|
117
|
+
plans.push({ e, pts: [[sx, a.cy], [(sx + tx) / 2, a.cy], [(sx + tx) / 2, b.cy], [tx, b.cy]], head: right ? 'right' : 'left', tx, ty: b.cy, label: { x: (sx + tx) / 2, y: Math.min(a.t, b.t) - 6, middle: true } });
|
|
118
|
+
} else { // boxes in between: over the row (under it for the first row)
|
|
119
|
+
const over = e.ra > 0;
|
|
120
|
+
const sx = a.cx + (b.cx > a.cx ? 18 : -18); const tx = b.cx + (b.cx > a.cx ? -18 : 18);
|
|
121
|
+
const sy = over ? a.t : a.b; const ty = over ? b.t - 6 : b.b + 6;
|
|
122
|
+
const y = lane(over ? e.ra - 1 : e.ra, sx, tx, e);
|
|
123
|
+
plans.push({ e, pts: [[sx, sy], [sx, y], [tx, y], [tx, ty]], head: over ? 'down' : 'up', tx, ty, label: { x: sx + 6, y: over ? sy - 6 : sy + 13 } });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Entries keep clear of unrelated vertical lines in the same gap (at least 18px), sliding within the
|
|
129
|
+
// target box, so an entry never looks like the continuation of another box's exit.
|
|
130
|
+
const stems = [];
|
|
131
|
+
for (const p of plans) {
|
|
132
|
+
const P = p.pts;
|
|
133
|
+
if (P.length === 2 && P[0][0] === P[1][0] && p.head === 'down') { stems.push({ p, kind: 'straight', gap: p.e.ra, x: () => P[0][0] }); continue; }
|
|
134
|
+
if (P.length < 4 || typeof P[1][1] !== 'object') continue;
|
|
135
|
+
stems.push({ p, kind: 'exit', gap: P[1][1].gap, x: () => P[0][0] });
|
|
136
|
+
stems.push({ p, kind: 'entry', gap: P[P.length - 2][1].gap, x: () => P[P.length - 1][0] });
|
|
137
|
+
}
|
|
138
|
+
const shares = (p, q) => [p.e.src, p.e.dst].some((n) => n === q.e.src || n === q.e.dst);
|
|
139
|
+
for (const s of stems.filter((t) => t.kind === 'entry')) {
|
|
140
|
+
const clash = (x) => stems.some((o) => o.p !== s.p && !shares(o.p, s.p) && o.gap === s.gap && Math.abs(o.x() - x) < 18);
|
|
141
|
+
const x0 = s.x(); if (!clash(x0)) continue;
|
|
142
|
+
const b = s.p.e.b; const cands = [];
|
|
143
|
+
for (let k = 1; k <= 16; k++) cands.push(x0 + k * 7, x0 - k * 7);
|
|
144
|
+
const nx = cands.find((x) => x > b.l + 10 && x < b.r - 10 && !clash(x));
|
|
145
|
+
if (nx === undefined) continue;
|
|
146
|
+
const P = s.p.pts; P[P.length - 1][0] = nx; P[P.length - 2][0] = nx; s.p.tx = nx;
|
|
147
|
+
const item = P[P.length - 2][1].item; item.x1 = Math.min(item.x1, nx); item.x2 = Math.max(item.x2, nx);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Tracks: interval colouring per gap. Wires from the same box may share a track.
|
|
151
|
+
let grow = false;
|
|
152
|
+
for (const [gap, items] of lanes) {
|
|
153
|
+
items.sort((p, q) => p.x1 - q.x1);
|
|
154
|
+
const tracks = [];
|
|
155
|
+
for (const it of items) {
|
|
156
|
+
let t = tracks.find((k) => k.srcs.has(it.src) || k.end < it.x1 - 10);
|
|
157
|
+
if (!t) { t = { end: -Infinity, srcs: new Set() }; tracks.push(t); }
|
|
158
|
+
if (!(t.srcs.has(it.src) || t.end < it.x1 - 10)) { t.srcs.clear(); }
|
|
159
|
+
t.end = Math.max(t.end, it.x2); t.srcs.add(it.src); it.track = tracks.indexOf(t);
|
|
160
|
+
}
|
|
161
|
+
const top = gap >= 0 && gap < rows.length - 1 ? rows[gap].b : rows[0].t - 40;
|
|
162
|
+
const bottom = gap >= 0 && gap < rows.length - 1 ? rows[gap + 1].t : rows[0].t;
|
|
163
|
+
const need = tracks.length * LANE + 22;
|
|
164
|
+
if (gap >= 0 && gap < rows.length - 1 && bottom - top < need) {
|
|
165
|
+
// Make room: push the next layer down.
|
|
166
|
+
const layer = rows[gap + 1].items[0].n.closest('.tm-layer');
|
|
167
|
+
if (layer) {
|
|
168
|
+
const cur = parseFloat(getComputedStyle(layer).marginTop) || 0;
|
|
169
|
+
layer.dataset.tmGrown = '1';
|
|
170
|
+
layer.style.marginTop = `${cur + (need - (bottom - top))}px`;
|
|
171
|
+
grow = true;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const mid = (top + bottom) / 2;
|
|
175
|
+
for (const it of items) it.ref.y = mid + (it.track - (tracks.length - 1) / 2) * LANE;
|
|
176
|
+
}
|
|
177
|
+
if (grow) return true; // layout changed: draw again
|
|
178
|
+
|
|
179
|
+
// Draw.
|
|
180
|
+
const w = map.scrollWidth; const h = map.scrollHeight;
|
|
181
|
+
const svg = document.createElementNS(SVGNS, 'svg');
|
|
182
|
+
svg.setAttribute('class', 'tm-wires'); svg.setAttribute('aria-hidden', 'true');
|
|
183
|
+
svg.setAttribute('width', w); svg.setAttribute('height', h); svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
|
|
184
|
+
const placed = []; const labelsBy = new Map();
|
|
185
|
+
for (const p of plans) {
|
|
186
|
+
const { e } = p;
|
|
187
|
+
const key = e.src.classList.contains('is-key') && e.dst.classList.contains('is-key');
|
|
188
|
+
const ext = e.dst.classList.contains('is-ext') || e.src.classList.contains('is-ext');
|
|
189
|
+
const pts = p.pts.map(([x, y]) => [x, typeof y === 'object' ? y.y : y]);
|
|
190
|
+
const path = document.createElementNS(SVGNS, 'path');
|
|
191
|
+
path.setAttribute('d', ortho(pts)); path.setAttribute('class', `tm-wire${key ? ' is-key' : ''}${ext ? ' is-ext' : ''}`);
|
|
192
|
+
const { tx, ty } = p;
|
|
193
|
+
const head = { down: `M${tx - 4.5},${ty - 1} L${tx + 4.5},${ty - 1} L${tx},${ty + 6} Z`, up: `M${tx - 4.5},${ty + 1} L${tx + 4.5},${ty + 1} L${tx},${ty - 6} Z`,
|
|
194
|
+
right: `M${tx - 1},${ty - 4.5} L${tx - 1},${ty + 4.5} L${tx + 6},${ty} Z`, left: `M${tx + 1},${ty - 4.5} L${tx + 1},${ty + 4.5} L${tx - 6},${ty} Z` }[p.head];
|
|
195
|
+
const arrow = document.createElementNS(SVGNS, 'path');
|
|
196
|
+
arrow.setAttribute('d', head); arrow.setAttribute('class', `tm-wire-head${key ? ' is-key' : ''}`);
|
|
197
|
+
svg.appendChild(path); svg.appendChild(arrow);
|
|
198
|
+
// Labels sit by the box the wire leaves; one per text per box; never on another label or a box.
|
|
199
|
+
const used = labelsBy.get(e.src) || labelsBy.set(e.src, { texts: [], x: null }).get(e.src);
|
|
200
|
+
if (e.label && !used.texts.includes(e.label)) {
|
|
201
|
+
const lw = e.label.length * 6.4; const y = p.label.y;
|
|
202
|
+
let x = p.label.middle ? p.label.x - lw / 2 : Math.max(p.label.x, used.x ?? -Infinity);
|
|
203
|
+
const hits = (lx) => placed.some((q) => lx < q.r + 8 && lx + lw > q.l - 8 && Math.abs(q.y - y) < 12)
|
|
204
|
+
|| rects.some((o) => lx < o.r && lx + lw > o.l && y > o.t && y - 10 < o.b);
|
|
205
|
+
for (let i = 0; i < 40 && hits(x); i++) x += 12;
|
|
206
|
+
const t = document.createElementNS(SVGNS, 'text');
|
|
207
|
+
t.setAttribute('class', 'tm-wire-label'); t.setAttribute('x', x); t.setAttribute('y', y);
|
|
208
|
+
t.textContent = e.label; svg.appendChild(t);
|
|
209
|
+
placed.push({ l: x, r: x + lw, y });
|
|
210
|
+
if (!p.label.middle) used.x = x + lw + 12;
|
|
211
|
+
used.texts.push(e.label);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// key wires on top, labels above every wire
|
|
215
|
+
[...svg.querySelectorAll('.tm-wire.is-key, .tm-wire-head.is-key')].forEach((el) => svg.appendChild(el));
|
|
216
|
+
[...svg.querySelectorAll('.tm-wire-label')].forEach((el) => svg.appendChild(el));
|
|
217
|
+
map.insertBefore(svg, map.firstChild);
|
|
218
|
+
markScroll(map);
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function drawWires() {
|
|
223
|
+
document.documentElement.style.setProperty('--tm-vw', `${document.documentElement.clientWidth}px`);
|
|
224
|
+
for (const map of document.querySelectorAll('.tm-map, .tm-blueprint')) {
|
|
225
|
+
// Start from the authored spacing, then let gaps grow as the tracks require.
|
|
226
|
+
for (const l of map.querySelectorAll('.tm-layer[data-tm-grown]')) { l.style.marginTop = ''; delete l.dataset.tmGrown; }
|
|
227
|
+
for (let pass = 0; pass < 4 && drawMap(map); pass++) { /* re-layout */ }
|
|
228
|
+
if (map.querySelector(':scope > svg.tm-wires') === null && map.querySelector('[data-to]')) drawMap(map);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// A map wider than the window fades at the edge it can scroll towards.
|
|
232
|
+
function markScroll(map) {
|
|
233
|
+
map.classList.toggle('tm-scrolls', map.scrollWidth - map.clientWidth - map.scrollLeft > 4);
|
|
234
|
+
if (!map.__tmScroll) { map.__tmScroll = true; map.addEventListener('scroll', () => markScroll(map), { passive: true }); }
|
|
235
|
+
}
|
|
236
|
+
window.truemapWires = { draw: drawWires };
|
|
237
|
+
})();
|
package/src/ui/workspace.css
CHANGED
|
@@ -207,3 +207,18 @@ code { font-family: var(--code); font-size: 0.9em; }
|
|
|
207
207
|
* { animation: none !important; transition: none !important; }
|
|
208
208
|
}
|
|
209
209
|
.app[data-conn="closed"] .empty .primary { display: none; }
|
|
210
|
+
|
|
211
|
+
/* ---------- more menu ---------- */
|
|
212
|
+
.more { position: relative; }
|
|
213
|
+
.icon-btn .dot { fill: currentColor; stroke: none; }
|
|
214
|
+
.more-menu { left: auto; right: 0; width: 300px; padding: 6px; }
|
|
215
|
+
.more-file { padding: 6px 8px 10px; }
|
|
216
|
+
.more-label { display: block; font-size: 12px; color: var(--pencil); margin-bottom: 4px; }
|
|
217
|
+
.more-path { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
|
218
|
+
.more-path code { flex: 1; min-width: 0; font-size: 12px; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; direction: rtl; text-align: left; }
|
|
219
|
+
.more-item { display: flex; align-items: flex-start; gap: 10px; width: 100%; border: 0; background: none; text-align: left; padding: 8px; border-radius: 6px; cursor: pointer; color: var(--ink); }
|
|
220
|
+
.more-item:hover:not(:disabled), .more-item:focus-visible { background: var(--wash); outline: none; }
|
|
221
|
+
.more-item svg { width: 18px; height: 18px; flex: none; margin-top: 1px; fill: none; stroke: var(--graphite); stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; }
|
|
222
|
+
.more-item span { display: grid; gap: 1px; font-weight: 500; }
|
|
223
|
+
.more-item small { font-size: 12px; font-weight: 400; color: var(--pencil); }
|
|
224
|
+
.more-item:disabled { opacity: .45; cursor: default; }
|
package/src/ui/workspace.html
CHANGED
|
@@ -39,6 +39,17 @@
|
|
|
39
39
|
<svg viewBox="0 0 20 20" aria-hidden="true"><rect x="2.75" y="3.75" width="14.5" height="12.5" rx="2"/><path d="M12.25 3.75v12.5"/><path class="panel-fill" d="M12.25 4.5h4.25v11h-4.25z"/></svg>
|
|
40
40
|
<span class="unread" id="unread" hidden></span>
|
|
41
41
|
</button>
|
|
42
|
+
<div class="more">
|
|
43
|
+
<button class="icon-btn" id="moreBtn" type="button" aria-haspopup="menu" aria-expanded="false" aria-label="More" title="More">
|
|
44
|
+
<svg viewBox="0 0 20 20" aria-hidden="true"><circle class="dot" cx="10" cy="4.5" r="1.4"/><circle class="dot" cx="10" cy="10" r="1.4"/><circle class="dot" cx="10" cy="15.5" r="1.4"/></svg>
|
|
45
|
+
</button>
|
|
46
|
+
<div class="menu more-menu" id="moreMenu" role="menu" hidden>
|
|
47
|
+
<div class="more-file"><span class="more-label">This page</span><div class="more-path"><code id="moreFile">No page open</code><button class="text-btn" id="copyPath" type="button">Copy path</button></div></div>
|
|
48
|
+
<button class="more-item" id="exportPage" type="button" role="menuitem"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M10 3.5v9M6 9l4 4 4-4M4 16.5h12"/></svg><span>Export as one HTML file<small>To share it; opens without truemap</small></span></button>
|
|
49
|
+
<div class="menu-gap"></div>
|
|
50
|
+
<button class="more-item" id="endConv" type="button" role="menuitem"><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M8 4.5H5a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h3M12.5 6.5 16 10l-3.5 3.5M16 10H8"/></svg><span>End conversation<small id="endHint">Lets the agent go back to the terminal</small></span></button>
|
|
51
|
+
</div>
|
|
52
|
+
</div>
|
|
42
53
|
</header>
|
|
43
54
|
|
|
44
55
|
<main class="stage">
|
package/src/ui/workspace.js
CHANGED
|
@@ -139,7 +139,7 @@
|
|
|
139
139
|
const typing = e.target.closest?.('input,textarea,select,[contenteditable]');
|
|
140
140
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); menu.hidden ? openMenu() : closeMenu(); }
|
|
141
141
|
else if (e.key === 'Escape' && !menu.hidden) { closeMenu(); $('pageBtn').focus(); }
|
|
142
|
-
else if (e.key === 'Escape' && !typing && state.annotate) setAnnotate(false, { touched: true });
|
|
142
|
+
else if (e.key === 'Escape' && !typing && state.annotate && $('moreMenu').hidden) setAnnotate(false, { touched: true });
|
|
143
143
|
else if (!menu.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
|
144
144
|
const items = [...menu.querySelectorAll('.page-item')]; if (!items.length) return;
|
|
145
145
|
e.preventDefault();
|
|
@@ -151,6 +151,41 @@
|
|
|
151
151
|
});
|
|
152
152
|
$('recheck').onclick = () => { api('/api/check'); closeMenu(); };
|
|
153
153
|
|
|
154
|
+
// ---------- more menu: the page file, export, end the conversation ----------
|
|
155
|
+
const more = $('moreMenu');
|
|
156
|
+
const filePath = () => {
|
|
157
|
+
if (!state.page) return '';
|
|
158
|
+
const sepChar = String(state.root).includes('\\') ? '\\' : '/';
|
|
159
|
+
return [state.root, '.truemap', ...state.page.split('/')].join(sepChar);
|
|
160
|
+
};
|
|
161
|
+
function renderMore() {
|
|
162
|
+
$('moreFile').textContent = state.page ? `.truemap/${state.page}` : 'No page open';
|
|
163
|
+
$('moreFile').title = filePath();
|
|
164
|
+
$('copyPath').disabled = !state.page;
|
|
165
|
+
$('exportPage').disabled = !state.page || state.conn !== 'live';
|
|
166
|
+
const talking = state.conn === 'live' && (state.agent.state === 'listening' || state.agent.state === 'working');
|
|
167
|
+
$('endConv').disabled = !talking;
|
|
168
|
+
$('endHint').textContent = talking ? `Lets ${agentName()} go back to the terminal` : 'No conversation is running';
|
|
169
|
+
}
|
|
170
|
+
const closeMore = () => { more.hidden = true; $('moreBtn').setAttribute('aria-expanded', 'false'); };
|
|
171
|
+
$('moreBtn').onclick = (e) => {
|
|
172
|
+
e.stopPropagation();
|
|
173
|
+
if (!more.hidden) return closeMore();
|
|
174
|
+
closeMenu(); renderMore(); more.hidden = false; $('moreBtn').setAttribute('aria-expanded', 'true');
|
|
175
|
+
};
|
|
176
|
+
document.addEventListener('click', (e) => { if (!more.hidden && !e.target.closest('.more')) closeMore(); });
|
|
177
|
+
window.addEventListener('blur', () => { if (!more.hidden) closeMore(); });
|
|
178
|
+
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !more.hidden) { closeMore(); $('moreBtn').focus(); } });
|
|
179
|
+
$('copyPath').onclick = () => {
|
|
180
|
+
navigator.clipboard?.writeText(filePath()).then(() => { $('copyPath').textContent = 'Copied'; setTimeout(() => { $('copyPath').textContent = 'Copy path'; }, 1400); }).catch(() => {});
|
|
181
|
+
};
|
|
182
|
+
$('exportPage').onclick = () => {
|
|
183
|
+
const a = document.createElement('a');
|
|
184
|
+
a.href = `/api/export?page=${encodeURIComponent(state.page)}&t=${encodeURIComponent(TOKEN)}`;
|
|
185
|
+
a.download = ''; document.body.appendChild(a); a.click(); a.remove(); closeMore();
|
|
186
|
+
};
|
|
187
|
+
$('endConv').onclick = () => { api('/api/end'); closeMore(); };
|
|
188
|
+
|
|
154
189
|
function renderHeader() {
|
|
155
190
|
const p = state.pages.find((x) => x.page === state.page);
|
|
156
191
|
$('pageTitle').textContent = p ? titleOf(p) : (state.pages.length ? 'Pages' : 'No pages yet');
|
|
@@ -434,6 +469,7 @@
|
|
|
434
469
|
state.pages = d.pages || []; state.check = d.check || { results: [] }; state.history = d.history || [];
|
|
435
470
|
state.pending = new Set(d.pending || []);
|
|
436
471
|
if (d.cmd) state.cmd = d.cmd;
|
|
472
|
+
state.root = String(d.root || '');
|
|
437
473
|
if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; $('annotate').setAttribute('aria-checked', String(d.annotate)); }
|
|
438
474
|
$('ver').textContent = `truemap ${d.version}`;
|
|
439
475
|
$('project').textContent = String(d.root || '').split(/[\\/]/).filter(Boolean).pop() || '';
|