truemap-cli 0.3.0 → 0.5.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/src/ui/sdk.js CHANGED
@@ -24,22 +24,143 @@
24
24
  const style = document.createElement('style');
25
25
  style.textContent = `
26
26
  [data-tm-mark="changed"] { outline: 2px dashed var(--tm-changed, #a2690a) !important; outline-offset: 3px; }
27
- [data-tm-mark="broken"] { outline: 2px dashed var(--tm-broken, #b03a2e) !important; outline-offset: 3px; }
27
+ [data-tm-mark="broken"] { outline: 2px dashed var(--tm-broken, #c0392b) !important; outline-offset: 3px; }
28
28
  svg [data-tm-mark] { outline: none !important; }
29
+ .tm-diagram .tm-node[data-tm-mark] { outline: none !important; }
30
+ .tm-diagram .tm-node[data-tm-mark]::before { content: ""; position: absolute; top: 7px; left: -4px; width: 7px; height: 7px; border-radius: 50%; background: var(--tm-changed, #a35f00); box-shadow: 0 0 0 2px var(--tm-paper, #fff); }
31
+ .tm-diagram .tm-node[data-tm-mark="broken"]::before { background: var(--tm-broken, #c0392b); }
29
32
  html[data-tm-annotate] body { cursor: default; }
30
33
  html[data-tm-annotate] [data-tm-hover] { cursor: pointer; }
31
34
  html[data-tm-annotate] a, html[data-tm-annotate] label { cursor: pointer; }
32
- @keyframes tm-flash { 0%,100% { outline-color: transparent } 35% { outline-color: var(--tm-route, #2453c4) } }
33
- [data-tm-flash] { outline: 2px solid var(--tm-route, #2453c4) !important; outline-offset: 4px; animation: tm-flash 1.1s ease 2; }
35
+ @keyframes tm-flash { 0%,100% { outline-color: transparent } 35% { outline-color: var(--tm-route, #141413) } }
36
+ [data-tm-flash] { outline: 2px solid var(--tm-route, #141413) !important; outline-offset: 4px; animation: tm-flash 1.1s ease 2; }
34
37
  @media (prefers-reduced-motion: reduce) { [data-tm-flash] { animation: none; } }
35
- ::highlight(tm-note) { background-color: color-mix(in oklab, var(--tm-route, #2453c4) 20%, transparent); }
38
+ ::highlight(tm-note) { background-color: color-mix(in oklab, var(--tm-route, #141413) 20%, transparent); }
39
+ /* Every box can be opened: click shows its code and connections. */
40
+ .tm-node, .tm-step, [data-src] { cursor: pointer; }
41
+ .tm-node:focus-visible, .tm-step:focus-visible { outline: 2px solid var(--tm-route, #141413); outline-offset: 3px; }
42
+ /* The agent points at the map: everything else steps back. */
43
+ html[data-tm-focusing] .tm-node:not([data-tm-focus]), html[data-tm-focusing] .tm-step:not([data-tm-focus]) { opacity: .34; }
44
+ html[data-tm-focusing] .tm-wire:not(.is-focus), html[data-tm-focusing] .tm-wire-head:not(.is-focus) { opacity: .16; }
45
+ html[data-tm-focusing] .tm-wire-label:not(.is-focus) { opacity: 0; }
46
+ .tm-node, .tm-step, .tm-wire, .tm-wire-head, .tm-wire-label { transition: opacity .18s ease, stroke .12s ease, fill .12s ease; }
47
+ @media (prefers-reduced-motion: reduce) { .tm-node, .tm-step, .tm-wire, .tm-wire-head, .tm-wire-label { transition: none; } }
36
48
  `;
37
49
  (document.head || document.documentElement).appendChild(style);
38
50
 
39
- const drawWires = () => window.truemapWires?.draw();
51
+ const drawWires = () => { window.truemapDiagram?.draw(); window.truemapWires?.draw(); markWires(); };
40
52
  let wireTimer = null;
41
53
  const scheduleWires = () => { clearTimeout(wireTimer); wireTimer = setTimeout(() => { drawWires(); placePins(); }, 40); };
42
54
 
55
+ // ---------- focus: the agent (or a chat link) points at boxes ----------
56
+ let focusSet = []; let focusNote = null; let hotBox = null;
57
+ function findItems(items) {
58
+ const all = [...document.querySelectorAll('[data-src], .tm-node[id], .tm-step[id]')];
59
+ const out = [];
60
+ for (const it of items || []) {
61
+ const s = String(it);
62
+ const el = (/^[\w-]+$/.test(s) && document.getElementById(s))
63
+ || all.find((x) => x.getAttribute('data-src') === s)
64
+ || (!s.includes('#') && all.find((x) => (x.getAttribute('data-src') || '').split('#')[0].replace(/\/$/, '') === s.replace(/\/$/, '')))
65
+ || all.find((x) => (x.getAttribute('data-src') || '').endsWith(`#${s.split('#').pop()}`) && s.includes('#'));
66
+ if (el && !out.includes(el)) out.push(el);
67
+ }
68
+ return out;
69
+ }
70
+ // Classes on wires follow the focused / hovered boxes; re-applied after every redraw.
71
+ function markWires() {
72
+ const ids = new Set(focusSet.map((e) => e.id).filter(Boolean));
73
+ const hot = hotBox?.id;
74
+ for (const w of document.querySelectorAll('.tm-wire, .tm-wire-head')) {
75
+ const { from, to } = w.dataset;
76
+ w.classList.toggle('is-focus', ids.has(from) && ids.has(to));
77
+ w.classList.toggle('is-hot', !!hot && (from === hot || to === hot));
78
+ }
79
+ for (const w of document.querySelectorAll('.tm-dg-edge, .tm-dg-head, .tm-dg-label')) {
80
+ w.classList.toggle('is-focus', ids.has(w.dataset.from) && ids.has(w.dataset.to));
81
+ }
82
+ // labels are placed afresh for what is now visible
83
+ window.truemapWires?.labels?.({ hot: hot || null, focus: [...ids] });
84
+ }
85
+ // Brings elements into view by scrolling the page itself; scrollIntoView would also scroll a map's own
86
+ // clipped box sideways and hide part of it.
87
+ function reveal(els, how = 'center') {
88
+ const rs = els.filter((el) => el.isConnected).map((el) => el.getBoundingClientRect());
89
+ if (!rs.length) return;
90
+ const top = Math.min(...rs.map((r) => r.top)); const bottom = Math.max(...rs.map((r) => r.bottom));
91
+ const smooth = matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth';
92
+ if (how === 'nearest' && top >= 8 && bottom <= innerHeight - 8) return;
93
+ const dy = bottom - top > innerHeight - 80 ? top - 60 : (top + bottom) / 2 - innerHeight / 2;
94
+ window.scrollBy({ top: dy, behavior: smooth });
95
+ }
96
+ function applyFocus(items, note, who, scroll = 'center', transient = false) {
97
+ clearFocus(false);
98
+ for (const btn of document.querySelectorAll('[data-tm-flow]')) btn.setAttribute('aria-pressed', 'false');
99
+ focusSet = findItems(items);
100
+ focusNote = note ? { text: String(note), who: who || 'Agent' } : null;
101
+ if (focusSet.length) {
102
+ document.documentElement.setAttribute('data-tm-focusing', '');
103
+ for (const el of focusSet) el.setAttribute('data-tm-focus', '');
104
+ if (scroll) reveal(focusSet, scroll);
105
+ } else if (focusNote) window.scrollTo({ top: 0 });
106
+ // the page scrolls smoothly to the group: place the note again once it has settled
107
+ markWires(); paintRings(); setTimeout(paintRings, 350); setTimeout(paintRings, 900);
108
+ post({ type: 'focus-state', count: focusSet.length, transient });
109
+ }
110
+ function clearFocus(repaint = true) {
111
+ document.documentElement.removeAttribute('data-tm-focusing');
112
+ for (const el of document.querySelectorAll('[data-tm-focus]')) el.removeAttribute('data-tm-focus');
113
+ if (repaint) for (const btn of document.querySelectorAll('[data-tm-flow]')) btn.setAttribute('aria-pressed', 'false');
114
+ const had = focusSet.length;
115
+ focusSet = []; focusNote = null;
116
+ markWires(); if (repaint) paintRings();
117
+ if (had && repaint) post({ type: 'focus-state', count: 0 });
118
+ }
119
+
120
+ // ---------- peek: click a box to see what it is in the code ----------
121
+ const boxSel = '.tm-node, .tm-step, .tm-card[data-src], [data-src]';
122
+ function boxInfo(el) {
123
+ const txt = (sel) => clean(el.querySelector(sel)?.textContent, 300);
124
+ const nameOf = (n) => clean(n.getAttribute('data-name') || n.querySelector?.('.tm-node-title,b,strong,h3,h4')?.textContent || n.textContent, 60);
125
+ // Same label rules as the map: underscores are spaces, \_ is a real underscore.
126
+ const viaOf = (s) => s.replace(/\\_/g, '\u0001').replace(/_/g, ' ').replace(/\u0001/g, '_');
127
+ const to = [];
128
+ for (const spec of (el.getAttribute('data-to') || '').split(/[\s,]+/).filter(Boolean)) {
129
+ const [id, ...lab] = spec.split(':'); const n = document.getElementById(id);
130
+ if (n) to.push({ id, label: nameOf(n), via: viaOf(lab.join(':')) });
131
+ }
132
+ const from = [];
133
+ if (el.id) {
134
+ for (const n of document.querySelectorAll('[data-to]')) {
135
+ const spec = n.getAttribute('data-to').split(/[\s,]+/).find((x) => x.split(':')[0] === el.id);
136
+ if (spec && n.id) from.push({ id: n.id, label: nameOf(n), via: viaOf(spec.split(':').slice(1).join(':')) });
137
+ }
138
+ }
139
+ const href = el.matches('a[href]') ? el.getAttribute('href') : (el.querySelector('a[href$=".html"], a[href*=".html#"]')?.getAttribute('href') || '');
140
+ const det = el.querySelector(':scope > .tm-detail');
141
+ const detail = det ? [...det.querySelectorAll(':scope > p:not(.tm-why), :scope > ul > li, :scope > ol > li')].slice(0, 14).map((n) => ({ t: n.tagName === 'LI' ? 'li' : 'p', text: clean(n.textContent, 500) })) : [];
142
+ return {
143
+ id: el.id || '', label: clean(el.getAttribute('data-name'), 60) || labelOf(el), tag: clean(el.getAttribute('data-tag'), 60), plan: el.getAttribute('data-plan') || '', detail,
144
+ sub: txt('.tm-node-sub'), desc: det ? '' : txt('.tm-node-desc') || (el.matches('.tm-node,.tm-step') ? '' : clean(el.innerText, 300)),
145
+ src: el.closest('[data-src]')?.getAttribute('data-src') || '', href: /^[\w./-]+\.html?(#[\w-]*)?$/i.test(href) ? href : '',
146
+ ext: el.classList.contains('is-ext'), to, from, mark: el.getAttribute('data-tm-mark') || '', planNote: clean(el.getAttribute('data-plan-note'), 400), why: clean(el.getAttribute('data-why') || det?.querySelector('.tm-why')?.textContent, 600),
147
+ };
148
+ }
149
+ let selected = null;
150
+ function select(el) {
151
+ if (selected === el) return;
152
+ selected?.removeAttribute('data-tm-selected');
153
+ selected = el || null; selected?.setAttribute('data-tm-selected', '');
154
+ // the selected box's own lines stay lit while its inspector is open
155
+ for (const w of document.querySelectorAll('.tm-dg-edge, .tm-dg-head, .tm-dg-label')) w.classList.toggle('is-sel', !!el?.id && (w.dataset.from === el.id || w.dataset.to === el.id));
156
+ if (!el && document.activeElement?.matches?.('.tm-node, .tm-step')) document.activeElement.blur();
157
+ }
158
+ function peek(el) {
159
+ select(el);
160
+ const r = el.getBoundingClientRect();
161
+ post({ type: 'peek', page: pagePath(), box: boxInfo(el), rect: { l: r.left, t: r.top, r: r.right, b: r.bottom }, sy: scrollY });
162
+ }
163
+
43
164
  // ---------- annotate ----------
44
165
  const INTERACTIVE = 'a[href],button,input,select,textarea,label,summary,[contenteditable],[role=button]';
45
166
  let annotating = false;
@@ -117,6 +238,29 @@
117
238
  rings.appendChild(d);
118
239
  };
119
240
  for (const n of notes.values()) if (n.el && n.el !== card?.target) ring(n.el, 'noted');
241
+ for (const el of focusSet) if (!el.closest('.tm-diagram')) ring(el, 'agent'); // diagram boxes get the highlighter instead
242
+ if (focusNote) {
243
+ mount();
244
+ const b = document.createElement('div'); b.className = 'bubble'; b.setAttribute('role', 'note');
245
+ b.innerHTML = '<div class="bubble-who"></div><div class="bubble-text"></div><button class="bubble-x" type="button" aria-label="Dismiss">×</button>';
246
+ b.querySelector('.bubble-who').textContent = focusNote.who;
247
+ b.querySelector('.bubble-text').textContent = focusNote.text;
248
+ b.querySelector('.bubble-x').onclick = (ev) => { ev.stopPropagation(); clearFocus(); post({ type: 'focus-cleared' }); };
249
+ rings.appendChild(b);
250
+ // The note sits beside the whole lit group (never on one of its boxes): right of it, else below it.
251
+ const vw = document.documentElement.clientWidth; const w = 300;
252
+ const live = focusSet.filter((el) => el.isConnected).map(extentOf);
253
+ if (live.length) {
254
+ const g = { l: Math.min(...live.map((x) => x.left)), t: Math.min(...live.map((x) => x.top)), r: Math.max(...live.map((x) => x.left + x.width)), b: Math.max(...live.map((x) => x.top + x.height)) };
255
+ // right of the group if there is room; otherwise above it (the page's own controls usually sit below
256
+ // a map); below it only when there is no room above.
257
+ const fitsRight = g.r + 14 + w < scrollX + vw - 8;
258
+ const bh = b.offsetHeight || 90;
259
+ const above = g.t - bh - 12 > scrollY + 4;
260
+ b.style.left = `${fitsRight ? g.r + 14 : Math.max(scrollX + 8, Math.min(g.l, scrollX + vw - w - 8))}px`;
261
+ b.style.top = `${fitsRight ? g.t : above ? g.t - bh - 12 : g.b + 12}px`;
262
+ } else { b.style.left = `${scrollX + vw - 320}px`; b.style.top = `${scrollY + 16}px`; }
263
+ }
120
264
  if (card?.target) ring(card.target, 'active');
121
265
  else if (annotating && hovered) ring(hovered, 'hover');
122
266
  }
@@ -135,40 +279,46 @@
135
279
  shadow.innerHTML = `<style>
136
280
  :host { all: initial; }
137
281
  * { box-sizing: border-box; }
138
- .card { position: absolute; width: 340px; background: #fff; color: #17202b; border: 1px solid #c2c8c1; border-radius: 10px;
139
- box-shadow: 0 12px 32px -12px rgba(23,32,43,.28); font: 14px/1.45 "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif; padding: 12px; }
282
+ .card { position: absolute; width: 340px; background: #fff; color: #141413; border: 1px solid #d2d2cb; border-radius: 10px;
283
+ box-shadow: 0 12px 32px -12px rgba(20,20,19,.28); font: 14px/1.45 "Instrument Sans", system-ui, -apple-system, "Segoe UI", sans-serif; padding: 12px; }
140
284
  .what { display: flex; align-items: baseline; gap: 8px; min-width: 0; margin: 0 2px 8px; }
141
285
  .what b { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
142
- .what code { font: 11.5px "IBM Plex Mono", ui-monospace, Consolas, monospace; color: #8a939e; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; }
143
- textarea { width: 100%; min-height: 72px; max-height: 220px; resize: none; font: inherit; color: inherit; background: #f6f7f4; border: 1px solid #dde1db; border-radius: 7px; padding: 9px 10px; outline: none; }
144
- textarea:focus { border-color: #2453c4; background: #fff; }
286
+ .what code { font: 11.5px "Commit Mono", ui-monospace, Consolas, monospace; color: #9a9a92; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; }
287
+ textarea { width: 100%; min-height: 72px; max-height: 220px; resize: none; font: inherit; color: inherit; background: #fafaf9; border: 1px solid #e6e6e1; border-radius: 7px; padding: 9px 10px; outline: none; }
288
+ textarea:focus { border-color: #141413; background: #fff; }
145
289
  .suggest { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 8px 2px 0; }
146
- .suggest button { all: unset; cursor: pointer; font-size: 12.5px; color: #2453c4; }
290
+ .suggest button { all: unset; cursor: pointer; font-size: 12.5px; color: #141413; }
147
291
  .suggest button:hover { text-decoration: underline; text-underline-offset: 3px; }
148
292
  .foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
149
- .hint { flex: 1; font-size: 11.5px; color: #8a939e; line-height: 1.3; }
150
- .btn { all: unset; cursor: pointer; font: 500 13px/1 "IBM Plex Sans", system-ui, sans-serif; padding: 8px 11px; border-radius: 6px; color: #5b6573; }
151
- .btn:hover { background: #eef0ec; color: #17202b; }
152
- .btn.primary { background: #2453c4; color: #fff; }
153
- .btn.primary:hover { background: #1b3f96; }
154
- .btn.danger { color: #b03a2e; }
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; }
293
+ .hint { flex: 1; font-size: 11.5px; color: #9a9a92; line-height: 1.3; }
294
+ .btn { all: unset; cursor: pointer; font: 500 13px/1 "Instrument Sans", system-ui, sans-serif; padding: 8px 11px; border-radius: 6px; color: #6c6c65; }
295
+ .btn:hover { background: #f2f2ef; color: #141413; }
296
+ .btn.primary { background: #141413; color: #fff; }
297
+ .btn.primary:hover { background: #3a3a36; }
298
+ .btn.danger { color: #c0392b; }
299
+ .btn:focus-visible { outline: 2px solid #141413; outline-offset: 2px; }
300
+ .ring { position: absolute; border: 1.5px solid #141413; border-radius: 8px; pointer-events: none; }
157
301
  .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); } }
160
- .pin { position: absolute; width: 20px; height: 20px; border-radius: 50%; background: #2453c4; color: #fff;
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); }
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); }
163
- .select-btn:hover { background: #2453c4; }
302
+ .ring.agent { border: 2px solid #141413; border-radius: 9px; }
303
+ .bubble { position: absolute; width: 300px; background: #141413; color: #fafaf9; border-radius: 10px; padding: 10px 30px 11px 12px; box-shadow: 0 14px 34px -14px rgba(20,20,19,.5); font: 13.5px/1.5 "Instrument Sans", system-ui, -apple-system, "Segoe UI", sans-serif; pointer-events: auto; }
304
+ .bubble-who { font-size: 11.5px; font-weight: 600; color: #ffe27a; margin-bottom: 3px; }
305
+ .bubble-text { white-space: pre-wrap; }
306
+ .bubble-x { all: unset; position: absolute; top: 6px; right: 8px; cursor: pointer; color: #a0a098; font-size: 16px; line-height: 1; padding: 2px 4px; border-radius: 4px; }
307
+ .bubble-x:hover { color: #fff; background: rgba(255,255,255,.1); }
308
+ .ring.noted { border-color: rgba(20, 20, 19, .35); }
309
+ @media (prefers-color-scheme: dark) { .ring { border-color: #f2f2ee; } .ring.noted { border-color: rgba(242, 242, 238, .45); } }
310
+ .pin { position: absolute; width: 20px; height: 20px; border-radius: 50%; background: #ffe27a; color: #141413;
311
+ font: 600 11px/20px "Commit Mono", ui-monospace, Consolas, monospace; text-align: center; cursor: pointer; border: 2px solid #fff; box-shadow: 0 1px 3px rgba(20,20,19,.25); }
312
+ .select-btn { position: absolute; all: unset; position: absolute; cursor: pointer; background: #141413; color: #fff; font: 500 12.5px/1 "Instrument Sans", system-ui, sans-serif; padding: 7px 10px; border-radius: 6px; box-shadow: 0 6px 18px -8px rgba(20,20,19,.5); }
313
+ .select-btn:hover { background: #141413; }
164
314
  @media (prefers-color-scheme: dark) {
165
- .card { background: #191d23; color: #edf0f3; border-color: #3d4651; box-shadow: 0 12px 32px -12px rgba(0,0,0,.6); }
166
- textarea { background: #121519; border-color: #2a3039; }
167
- textarea:focus { background: #121519; border-color: #7ea3ff; }
168
- .suggest button { color: #7ea3ff; }
169
- .btn { color: #9ba4af; } .btn:hover { background: #1f242b; color: #edf0f3; }
170
- .btn.primary { background: #2453c4; color: #fff; }
171
- .pin { border-color: #121519; }
315
+ .card { background: #1b1b1a; color: #f2f2ee; border-color: #44443f; box-shadow: 0 12px 32px -12px rgba(0,0,0,.6); }
316
+ textarea { background: #161615; border-color: #2f2f2c; }
317
+ textarea:focus { background: #161615; border-color: #f2f2ee; }
318
+ .suggest button { color: #f2f2ee; }
319
+ .btn { color: #a0a098; } .btn:hover { background: #252523; color: #f2f2ee; }
320
+ .btn.primary { background: #f2f2ee; color: #141413; }
321
+ .pin { border-color: #161615; }
172
322
  }
173
323
  </style><div id="rings"></div><div id="pins"></div><div id="slot"></div>`;
174
324
  const pinsEl = shadow.getElementById('pins');
@@ -309,18 +459,53 @@
309
459
  return t.closest('a.tm-node,a.tm-link') || pickTarget(t);
310
460
  }
311
461
  document.addEventListener('mousemove', (e) => {
312
- if (!annotating || card) return;
313
462
  const t = e.target instanceof Element ? e.target : null;
463
+ if (!annotating) {
464
+ // Reading mode: hovering a box lights up its own wires.
465
+ const box = t?.closest('.tm-map .tm-node, .tm-blueprint .tm-node') || null;
466
+ if (box !== hotBox) { hotBox = box; markWires(); }
467
+ return;
468
+ }
469
+ if (card) return;
314
470
  setHover(annotTarget(t));
315
471
  }, { passive: true });
316
- document.addEventListener('mouseleave', () => setHover(null));
472
+ document.addEventListener('mouseleave', () => { setHover(null); if (hotBox) { hotBox = null; markWires(); } });
317
473
 
318
474
  document.addEventListener('click', (e) => {
319
475
  if (!e.isTrusted) return;
320
476
  if (e.composedPath().includes(host)) return;
321
477
  const t = e.target instanceof Element ? e.target : null;
322
478
  if (card) { closeCard(); if (!annotating) return; }
323
- if (!annotating || !t) return;
479
+ if (!t) return;
480
+ // A flow button lights up a whole path across the map (works in both modes).
481
+ const flow = t.closest('[data-tm-flow]');
482
+ if (flow) {
483
+ e.preventDefault(); e.stopPropagation();
484
+ const ids = flow.getAttribute('data-tm-flow').split(/[\s,]+/).filter(Boolean);
485
+ const same = focusSet.length && ids.every((id) => focusSet.some((el) => el.id === id));
486
+ if (same) clearFocus(); else applyFocus(ids, flow.getAttribute('data-note') || '', clean(flow.textContent, 60));
487
+ for (const b of document.querySelectorAll('[data-tm-flow]')) b.setAttribute('aria-pressed', String(!same && b === flow));
488
+ return;
489
+ }
490
+ if (!annotating) {
491
+ // A box opens the inspector (what it is, its code, its connections). Real links and controls inside work as usual.
492
+ const box = t.closest(boxSel);
493
+ const inner = t.closest('a[href],button,input,select,textarea,label,summary,.tm-ask,[role=tab]');
494
+ if (String(getSelection?.() || '').trim().length > 1) return;
495
+ if (!box) {
496
+ // Empty space: back to the plain map.
497
+ if (!inner) {
498
+ if (focusSet.length || focusNote) { clearFocus(); post({ type: 'focus-cleared' }); }
499
+ if (selected) { select(null); post({ type: 'deselect' }); }
500
+ for (const fig of document.querySelectorAll('figure.tm-diagram[data-flow]')) window.truemapDiagram?.setFlow(fig, null);
501
+ }
502
+ return;
503
+ }
504
+ if (inner && inner !== box && box.contains(inner)) return;
505
+ e.preventDefault(); e.stopPropagation();
506
+ peek(box);
507
+ return;
508
+ }
324
509
  if (String(getSelection?.() || '').trim().length > 1) return;
325
510
  const el = annotTarget(t);
326
511
  if (!el) return;
@@ -341,13 +526,15 @@
341
526
  });
342
527
  document.addEventListener('selectionchange', () => { if (!String(getSelection() || '').trim()) hideSelectBtn(); });
343
528
 
529
+ // Escape anywhere in the page closes the inspector and the workspace's menus.
530
+ document.addEventListener('mouseup', (e) => { if (e.button === 3 || e.button === 4) { e.preventDefault(); post({ type: 'nav', dir: e.button === 3 ? 'back' : 'forward' }); } }, true);
344
531
  document.addEventListener('keydown', (e) => {
532
+ if (e.key === 'Escape') { select(null); post({ type: 'press' }); for (const fig of document.querySelectorAll('figure.tm-diagram[data-flow]')) window.truemapDiagram?.setFlow(fig, null); }
533
+ if (e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) { e.preventDefault(); post({ type: 'nav', dir: e.key === 'ArrowLeft' ? 'back' : 'forward' }); return; }
345
534
  const typing = e.target instanceof Element && e.target.closest('input,textarea,select,[contenteditable]');
346
535
  if (e.key === 'Escape' && card) { closeCard(); return; }
347
- if (e.key === 'Escape' && annotating && !typing && !e.defaultPrevented && !e.composedPath().includes(host)) { post({ type: 'annotate-off' }); return; }
348
- if (!typing && !e.composedPath().includes(host) && !e.ctrlKey && !e.metaKey && !e.altKey && e.key.toLowerCase() === 'a') {
349
- post({ type: 'toggle-annotate' });
350
- }
536
+ if (e.key === 'Escape' && (focusSet.length || focusNote)) { clearFocus(); post({ type: 'focus-cleared' }); return; }
537
+ if ((e.key === 'Enter' || e.key === ' ') && !annotating && e.target instanceof Element && e.target.matches?.('.tm-node, .tm-step') && !typing) { e.preventDefault(); peek(e.target); return; }
351
538
  });
352
539
 
353
540
  // ---------- decisions: <form class="tm-ask" data-tm-ask="question"> ----------
@@ -407,6 +594,48 @@
407
594
  else if (n?.rect) window.scrollTo({ top: n.rect.top - innerHeight / 3, behavior: 'smooth' });
408
595
  } else if (d.type === 'scroll') {
409
596
  window.scrollTo(0, d.y || 0);
597
+ } else if (d.type === 'focus') {
598
+ applyFocus(d.items, d.note, d.who, d.scroll === undefined ? 'center' : d.scroll, !!d.transient);
599
+ } else if (d.type === 'select') {
600
+ select(d.id ? document.getElementById(d.id) : null);
601
+ } else if (d.type === 'plan') {
602
+ // A plan drawn on the map: what it touches, adds (dashed, in its group) and removes.
603
+ for (const el of document.querySelectorAll('[data-plan-overlay], [data-plan-revised]')) { el.removeAttribute('data-plan'); el.removeAttribute('data-plan-note'); el.removeAttribute('data-plan-overlay'); el.removeAttribute('data-plan-revised'); }
604
+ clearFocus();
605
+ const p = d.plan;
606
+ document.documentElement.toggleAttribute('data-tm-plan', !!p);
607
+ const fig = document.querySelector('figure.tm-diagram');
608
+ if (fig && window.truemapDiagram?.setGhosts) window.truemapDiagram.setGhosts(fig, p ? p.add : []);
609
+ else if (p) post({ type: 'plan-unsupported' }); // an old-format map: the plan can't be drawn on it
610
+ const markPlan = (box, kind, note) => {
611
+ const el = findItems([box])[0];
612
+ if (!el || el.getAttribute('data-plan') === 'new') return;
613
+ el.setAttribute('data-plan', kind); el.setAttribute('data-plan-overlay', ''); if (note) el.setAttribute('data-plan-note', note);
614
+ };
615
+ if (p) { for (const t of p.touch || []) markPlan(t.box, 'change', t.what); for (const r of p.remove || []) markPlan(r.box, 'remove', r.why); }
616
+ for (const id of p?.revised || []) findItems([id])[0]?.setAttribute('data-plan-revised', '');
617
+ for (const b of document.querySelectorAll('.tm-node, .tm-step')) { if (!b.hasAttribute('tabindex') && !b.matches('a[href]')) b.setAttribute('tabindex', '0'); }
618
+ markWires();
619
+ } else if (d.type === 'changes') {
620
+ // Review mode: changed boxes carry their +/- lines; the rest of the map goes quiet.
621
+ document.documentElement.toggleAttribute('data-tm-changes', !!d.on);
622
+ for (const el of document.querySelectorAll('[data-tm-change], [data-tm-unbuilt]')) { el.removeAttribute('data-tm-change'); el.removeAttribute('data-tm-delta'); el.removeAttribute('data-tm-unbuilt'); }
623
+ for (const u of d.unbuilt || []) { const el = findItems([u.src || u.box, u.box])[0]; if (el) el.setAttribute('data-tm-unbuilt', ''); }
624
+ const names = [];
625
+ for (const it of d.items || []) {
626
+ for (const el of document.querySelectorAll('[data-src]')) {
627
+ if (el.getAttribute('data-src') !== it.src) continue;
628
+ el.setAttribute('data-tm-change', '');
629
+ el.setAttribute('data-tm-delta', it.add == null ? 'binary' : [it.add ? '+' + it.add : '', it.del ? '−' + it.del : ''].filter(Boolean).join(' ') || '±0');
630
+ names.push({ src: it.src, name: clean(el.getAttribute('data-name'), 60) || labelOf(el) });
631
+ }
632
+ }
633
+ if (names.length) post({ type: 'changes-names', items: names });
634
+ } else if (d.type === 'open-box') {
635
+ const el = d.id ? document.getElementById(d.id) : [...document.querySelectorAll('[data-src]')].find((x) => x.getAttribute('data-src') === d.src);
636
+ if (el) { reveal([el], 'nearest'); peek(el); }
637
+ } else if (d.type === 'clear-focus') {
638
+ clearFocus();
410
639
  } else if (d.type === 'highlight') {
411
640
  const el = [...document.querySelectorAll('[data-src]')].find((x) => x.getAttribute('data-src') === d.src);
412
641
  if (el) { el.scrollIntoView({ block: 'center', behavior: 'smooth' }); el.setAttribute('data-tm-flash', ''); setTimeout(() => el.removeAttribute('data-tm-flash'), 2400); }
@@ -422,8 +651,11 @@
422
651
  // Rings follow their element when anything scrolls, including a map scrolling sideways.
423
652
  document.addEventListener('scroll', () => { if (rings && (hovered || card || notes.size)) { placePins(); } }, { capture: true, passive: true });
424
653
 
654
+ window.truemapDiagram?.interact();
425
655
  const ready = () => {
426
656
  drawWires();
657
+ // Boxes are reachable from the keyboard too.
658
+ for (const b of document.querySelectorAll('.tm-node, .tm-step')) { if (!b.hasAttribute('tabindex') && !b.matches('a[href]')) b.setAttribute('tabindex', '0'); }
427
659
  if ('ResizeObserver' in window) new ResizeObserver(scheduleWires).observe(document.body);
428
660
  document.fonts?.ready?.then(scheduleWires);
429
661
  const meta = document.querySelector('meta[name="truemap-annotate"]')?.getAttribute('content');
package/src/ui/wires.js CHANGED
@@ -54,7 +54,7 @@
54
54
  if (!dst || dst === src || !map.contains(dst) || !rectOf.has(src) || !rectOf.has(dst)) continue;
55
55
  const a = rectOf.get(src); const b = rectOf.get(dst);
56
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, ' ') });
57
+ edges.push({ src, dst, a, b, ra, rb, dir: rb > ra ? 'down' : rb < ra ? 'up' : 'same', label: labelParts.join(':').replace(/\\_/g, '\u0001').replace(/_/g, ' ').replace(/\u0001/g, '_') });
58
58
  }
59
59
  }
60
60
  const group = (key, pick) => {
@@ -181,12 +181,18 @@
181
181
  const svg = document.createElementNS(SVGNS, 'svg');
182
182
  svg.setAttribute('class', 'tm-wires'); svg.setAttribute('aria-hidden', 'true');
183
183
  svg.setAttribute('width', w); svg.setAttribute('height', h); svg.setAttribute('viewBox', `0 0 ${w} ${h}`);
184
- const placed = []; const labelsBy = new Map();
184
+ const segsOf = new Map(); // plan -> its straight segments, for label placement
185
+ for (const p of plans) {
186
+ const pts = p.pts.map(([x, y]) => [x, typeof y === 'object' ? y.y : y]);
187
+ p.resolved = pts;
188
+ segsOf.set(p, pts.slice(1).map((q, i) => [pts[i][0], pts[i][1], q[0], q[1]]));
189
+ }
190
+ const isKey = (p) => p.e.src.classList.contains('is-key') && p.e.dst.classList.contains('is-key');
185
191
  for (const p of plans) {
186
192
  const { e } = p;
187
- const key = e.src.classList.contains('is-key') && e.dst.classList.contains('is-key');
193
+ const key = isKey(p);
188
194
  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]);
195
+ const pts = p.resolved;
190
196
  const path = document.createElementNS(SVGNS, 'path');
191
197
  path.setAttribute('d', ortho(pts)); path.setAttribute('class', `tm-wire${key ? ' is-key' : ''}${ext ? ' is-ext' : ''}`);
192
198
  const { tx, ty } = p;
@@ -194,31 +200,89 @@
194
200
  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
201
  const arrow = document.createElementNS(SVGNS, 'path');
196
202
  arrow.setAttribute('d', head); arrow.setAttribute('class', `tm-wire-head${key ? ' is-key' : ''}`);
203
+ for (const el of [path, arrow]) { el.dataset.from = e.src.id; el.dataset.to = e.dst.id; }
197
204
  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
205
  }
214
- // key wires on top, labels above every wire
206
+ // key wires on top
215
207
  [...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
208
  map.insertBefore(svg, map.firstChild);
209
+ map.__tm = { plans, segsOf, rects, w, h, svg, isKey };
210
+ placeLabels(map, labelState);
218
211
  markScroll(map);
219
212
  return false;
220
213
  }
221
214
 
215
+ // ---------- labels: placed for what is visible right now ----------
216
+ // Only some labels show at a time: the main path's by default; a hovered box's own wires; a lit path's wires.
217
+ // Each time that changes, the visible labels are placed afresh. A label goes on its own wire, at the first spot
218
+ // (walking from where the wire leaves its box) that touches no box, no other shown label and no wire that is
219
+ // drawn strongly at that moment. With no such spot the label is left off the map; the box's peek still lists it.
220
+ let labelState = {};
221
+ const segHits = ([x1, y1, x2, y2], b) => (x1 === x2
222
+ ? x1 > b.l - 2 && x1 < b.r + 2 && Math.max(y1, y2) > b.t && Math.min(y1, y2) < b.b
223
+ : y1 > b.t - 2 && y1 < b.b + 2 && Math.max(x1, x2) > b.l && Math.min(x1, x2) < b.r);
224
+ function placeLabels(map, state) {
225
+ const m = map.__tm; if (!m) return;
226
+ const { plans, segsOf, rects, w, h, svg, isKey } = m;
227
+ for (const el of svg.querySelectorAll('.tm-wire-label, .tm-wire-plate')) el.remove();
228
+ const hot = state.hot || null; const focus = state.focus && state.focus.size ? state.focus : null;
229
+ const isHot = (p) => !!hot && (p.e.src.id === hot || p.e.dst.id === hot);
230
+ const isFocus = (p) => !!focus && focus.has(p.e.src.id) && focus.has(p.e.dst.id);
231
+ const shown = (p) => (focus ? isFocus(p) || isHot(p) : isKey(p) || isHot(p));
232
+ // Wires a label must keep clear of: the ones drawn strongly right now. Faint wires pass under the label's
233
+ // paper plate, which interrupts them the way a map interrupts a road under a place name.
234
+ const strong = (p) => (focus ? isFocus(p) || isHot(p) : isKey(p) || isHot(p));
235
+ const order = focus ? [...plans.filter(isFocus), ...plans.filter((p) => !isFocus(p) && isHot(p))]
236
+ : [...plans.filter(isKey), ...plans.filter((p) => !isKey(p) && isHot(p))];
237
+ const placed = []; const used = new Map();
238
+ for (const p of order) {
239
+ const { e } = p;
240
+ const texts = used.get(e.src) || used.set(e.src, []).get(e.src);
241
+ if (!e.label || texts.includes(e.label)) continue;
242
+ const lw = e.label.length * 6.4;
243
+ const cands = [];
244
+ for (const [x1, y1, x2, y2] of segsOf.get(p)) {
245
+ if (x1 === x2) {
246
+ const lo = Math.min(y1, y2); const hi = Math.max(y1, y2);
247
+ for (let y = lo + 15; y <= hi - 1; y += 7) cands.push({ x: x1 + 6, y, anchor: 'start' }, { x: x1 - 6, y, anchor: 'end' });
248
+ } else {
249
+ const lo = Math.min(x1, x2); const hi = Math.max(x1, x2);
250
+ for (let x = lo + 6; x + lw <= hi - 2; x += 12) cands.push({ x, y: y1 - 5, anchor: 'start' }, { x, y: y1 + 14, anchor: 'start' });
251
+ }
252
+ }
253
+ const boxOf = (c) => { const l = c.anchor === 'end' ? c.x - lw : c.x; return { l, r: l + lw, t: c.y - 10, b: c.y + 3 }; };
254
+ const free = (c) => {
255
+ const b = boxOf(c);
256
+ if (b.l < 2 || b.r > w - 2 || b.t < 0 || b.b > h) return false;
257
+ if (rects.some((o) => b.l < o.r + 3 && b.r > o.l - 3 && b.t < o.b + 3 && b.b > o.t - 3)) return false;
258
+ if (placed.some((q) => b.l < q.r + 6 && b.r > q.l - 6 && b.t < q.b + 2 && b.b > q.t - 2)) return false;
259
+ for (const [q, segs] of segsOf) if (q !== p && strong(q) && segs.some((sg) => segHits(sg, b))) return false;
260
+ return true;
261
+ };
262
+ const c = cands.find(free);
263
+ if (!c) continue;
264
+ placed.push(boxOf(c));
265
+ const cls = `${isKey(p) ? ' is-key' : ''}${isHot(p) ? ' is-hot' : ''}${isFocus(p) ? ' is-focus' : ''}`;
266
+ const t = document.createElementNS(SVGNS, 'text');
267
+ t.setAttribute('class', `tm-wire-label${cls}`);
268
+ t.setAttribute('x', c.x); t.setAttribute('y', c.y);
269
+ if (c.anchor !== 'start') t.setAttribute('text-anchor', c.anchor);
270
+ t.dataset.from = e.src.id; t.dataset.to = e.dst.id;
271
+ t.textContent = e.label;
272
+ // the paper plate under the label: faint wires stop at its edge instead of running through the words
273
+ const bb = boxOf(c); const plate = document.createElementNS(SVGNS, 'rect');
274
+ plate.setAttribute('class', `tm-wire-plate${cls}`);
275
+ plate.setAttribute('x', bb.l - 3); plate.setAttribute('y', bb.t - 1); plate.setAttribute('width', bb.r - bb.l + 6); plate.setAttribute('height', bb.b - bb.t + 3); plate.setAttribute('rx', 3);
276
+ plate.dataset.from = e.src.id; plate.dataset.to = e.dst.id;
277
+ svg.appendChild(plate); svg.appendChild(t);
278
+ texts.push(e.label);
279
+ }
280
+ }
281
+ function labels(state = {}) {
282
+ labelState = { hot: state.hot || null, focus: state.focus ? new Set(state.focus) : null };
283
+ for (const map of document.querySelectorAll('.tm-map, .tm-blueprint')) placeLabels(map, labelState);
284
+ }
285
+
222
286
  function drawWires() {
223
287
  document.documentElement.style.setProperty('--tm-vw', `${document.documentElement.clientWidth}px`);
224
288
  for (const map of document.querySelectorAll('.tm-map, .tm-blueprint')) {
@@ -233,5 +297,33 @@
233
297
  map.classList.toggle('tm-scrolls', map.scrollWidth - map.clientWidth - map.scrollLeft > 4);
234
298
  if (!map.__tmScroll) { map.__tmScroll = true; map.addEventListener('scroll', () => markScroll(map), { passive: true }); }
235
299
  }
236
- window.truemapWires = { draw: drawWires };
300
+ // Hover and path buttons without the truemap workspace (used by exported pages; the SDK has its own).
301
+ function interact() {
302
+ let hot = null; let lit = [];
303
+ const mark = () => {
304
+ const ids = new Set(lit);
305
+ for (const el of document.querySelectorAll('.tm-wire, .tm-wire-head, .tm-wire-label')) {
306
+ el.classList.toggle('is-hot', !!hot && (el.dataset.from === hot.id || el.dataset.to === hot.id));
307
+ el.classList.toggle('is-focus', ids.has(el.dataset.from) && ids.has(el.dataset.to));
308
+ }
309
+ labels({ hot: hot?.id || null, focus: lit });
310
+ };
311
+ document.addEventListener('mousemove', (e) => {
312
+ const box = e.target.closest?.('.tm-map .tm-node, .tm-blueprint .tm-node') || null;
313
+ if (box !== hot) { hot = box; mark(); }
314
+ });
315
+ document.addEventListener('click', (e) => {
316
+ const btn = e.target.closest?.('[data-tm-flow]'); if (!btn) return;
317
+ const ids = btn.getAttribute('data-tm-flow').split(/[\s,]+/).filter(Boolean);
318
+ const same = lit.length && ids.join() === lit.join();
319
+ lit = same ? [] : ids;
320
+ document.documentElement.toggleAttribute('data-tm-focusing', !!lit.length);
321
+ for (const el of document.querySelectorAll('[data-tm-focus]')) el.removeAttribute('data-tm-focus');
322
+ for (const id of lit) document.getElementById(id)?.setAttribute('data-tm-focus', '');
323
+ for (const b of document.querySelectorAll('[data-tm-flow]')) b.setAttribute('aria-pressed', String(!same && b === btn));
324
+ mark();
325
+ });
326
+ window.truemapWires.mark = mark;
327
+ }
328
+ window.truemapWires = { draw: drawWires, interact, labels };
237
329
  })();