truemap-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,158 @@
1
+ :root {
2
+ --paper: #f6f7f5;
3
+ --sheet: #ffffff;
4
+ --wash: #eef0ed;
5
+ --ink: #1d2733;
6
+ --graphite: #5a6472;
7
+ --pencil: #8a929c;
8
+ --rule: #dfe2dd;
9
+ --rule-strong: #c4c9c3;
10
+ --route: #2c5a8c;
11
+ --route-wash: #e6edf5;
12
+ --changed: #9c6c12;
13
+ --broken: #a23b2c;
14
+ --fine: #2f6b4f;
15
+ --font: system-ui, -apple-system, "Segoe UI", "Helvetica Neue", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
16
+ --code: ui-monospace, "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace;
17
+ --chat-w: 360px;
18
+ color-scheme: light dark;
19
+ }
20
+ @media (prefers-color-scheme: dark) {
21
+ :root {
22
+ --paper: #14181d; --sheet: #1a1f25; --wash: #20262d; --ink: #e3e6e9; --graphite: #a2aab4; --pencil: #77808b;
23
+ --rule: #2a3138; --rule-strong: #3d464f; --route: #8db0dc; --route-wash: #1f2d3d;
24
+ --changed: #d4a24a; --broken: #e07a66; --fine: #74b894;
25
+ }
26
+ }
27
+
28
+ * { box-sizing: border-box; }
29
+ html, body { height: 100%; }
30
+ body { margin: 0; background: var(--paper); color: var(--ink); font: 14px/1.5 var(--font); -webkit-font-smoothing: antialiased; overflow: hidden; }
31
+ button { font: inherit; color: inherit; }
32
+ [hidden] { display: none !important; }
33
+ :focus-visible { outline: 2px solid var(--route); outline-offset: 2px; }
34
+ svg { display: block; }
35
+
36
+ .app { height: 100vh; height: 100dvh; display: grid; grid-template-columns: minmax(0, 1fr) var(--chat-w); }
37
+ .app.chat-closed { grid-template-columns: minmax(0, 1fr) 0; }
38
+ .app.chat-closed .chat { display: none; }
39
+
40
+ /* ---------- top bar ---------- */
41
+ .stage { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
42
+ .bar { height: 44px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px 0 8px; border-bottom: 1px solid var(--rule); background: var(--paper); }
43
+ .switcher { position: relative; min-width: 0; }
44
+ .page-btn { display: flex; align-items: center; gap: 8px; max-width: 46vw; border: 0; background: none; padding: 5px 8px; border-radius: 5px; cursor: pointer; }
45
+ .page-btn:hover, .page-btn[aria-expanded="true"] { background: var(--wash); }
46
+ .mark { width: 18px; height: 18px; flex: none; }
47
+ .mark rect { fill: none; stroke: var(--ink); stroke-width: 2.5; }
48
+ .mark path { fill: var(--route); }
49
+ .page-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
50
+ .chev { width: 14px; height: 14px; flex: none; fill: none; stroke: var(--graphite); stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
51
+ .path { font: 12px var(--code); color: var(--pencil); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
52
+ .spacer { flex: 1; }
53
+ .state-dot { width: 7px; height: 7px; border-radius: 50%; flex: none; }
54
+ .state-dot.changed { background: var(--changed); }
55
+ .state-dot.broken { background: var(--broken); }
56
+
57
+ .menu {
58
+ position: absolute; top: calc(100% + 6px); left: 0; z-index: 30; width: min(340px, 86vw); max-height: min(70vh, 520px);
59
+ display: flex; flex-direction: column; background: var(--sheet); border: 1px solid var(--rule-strong); border-radius: 6px;
60
+ box-shadow: 0 10px 30px -12px rgba(16, 24, 34, .28);
61
+ }
62
+ .menu-head { padding: 10px 12px 6px; display: grid; gap: 8px; }
63
+ .menu-head span { font-size: 12px; color: var(--pencil); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
64
+ .menu-head input { width: 100%; border: 1px solid var(--rule); border-radius: 4px; padding: 6px 8px; background: var(--paper); color: var(--ink); font: inherit; }
65
+ .menu-list { overflow: auto; padding: 2px 6px 6px; }
66
+ .page-item { display: flex; align-items: center; gap: 10px; width: 100%; border: 0; background: none; text-align: left; padding: 7px 8px; border-radius: 4px; cursor: pointer; }
67
+ .page-item:hover, .page-item:focus-visible { background: var(--wash); outline: none; }
68
+ .page-item.active .pi-title { color: var(--route); }
69
+ .pi-text { flex: 1; min-width: 0; }
70
+ .pi-title { display: block; font-weight: 550; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
71
+ .pi-file { display: block; font: 11.5px var(--code); color: var(--pencil); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
72
+ .menu-gap { height: 1px; background: var(--rule); margin: 4px 8px; }
73
+ .menu-foot { display: flex; justify-content: space-between; align-items: center; padding: 8px 14px; border-top: 1px solid var(--rule); font-size: 12px; color: var(--pencil); }
74
+ .text-btn { border: 0; background: none; padding: 0; color: var(--route); cursor: pointer; font-size: 12.5px; }
75
+ .text-btn:hover { text-decoration: underline; text-underline-offset: 3px; }
76
+
77
+ .check-chip { flex: none; border: 0; background: none; padding: 4px 8px; border-radius: 4px; font-size: 12.5px; color: var(--graphite); display: inline-flex; align-items: center; gap: 6px; cursor: default; }
78
+ .check-chip::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--fine); }
79
+ .check-chip[data-state="changed"] { color: var(--changed); cursor: pointer; }
80
+ .check-chip[data-state="changed"]::before { background: var(--changed); }
81
+ .check-chip[data-state="broken"] { color: var(--broken); cursor: pointer; }
82
+ .check-chip[data-state="broken"]::before { background: var(--broken); }
83
+ .check-chip:not([data-state="ok"]):hover { background: var(--wash); }
84
+ .icon-btn { position: relative; flex: none; width: 30px; height: 30px; display: grid; place-items: center; border: 0; background: none; border-radius: 5px; cursor: pointer; }
85
+ .icon-btn:hover { background: var(--wash); }
86
+ .icon-btn svg { width: 18px; height: 18px; fill: none; stroke: var(--ink); stroke-width: 1.5; stroke-linejoin: round; stroke-linecap: round; }
87
+ .icon-btn.quiet svg { stroke: var(--graphite); }
88
+ .unread { position: absolute; top: 5px; right: 5px; width: 7px; height: 7px; border-radius: 50%; background: var(--route); box-shadow: 0 0 0 2px var(--paper); }
89
+
90
+ .frame-wrap { position: relative; flex: 1; min-height: 0; }
91
+ #frame { width: 100%; height: 100%; border: 0; display: block; background: var(--paper); }
92
+ .empty { position: absolute; inset: 0; padding: 18vh 32px 32px; max-width: 560px; margin: 0 auto; }
93
+ .empty h1 { font-size: 22px; letter-spacing: -.01em; margin: 0 0 8px; font-weight: 640; }
94
+ .empty p { margin: 0 0 20px; color: var(--graphite); font-size: 15px; line-height: 1.6; }
95
+ .primary { border: 1px solid var(--ink); background: var(--ink); color: var(--paper); padding: 8px 14px; border-radius: 4px; font-weight: 600; cursor: pointer; }
96
+
97
+ /* ---------- chat ---------- */
98
+ .chat { border-left: 1px solid var(--rule); background: var(--sheet); display: flex; flex-direction: column; min-height: 0; min-width: 0; }
99
+ .chat-head { height: 44px; flex: none; display: flex; align-items: center; justify-content: space-between; padding: 0 6px 0 14px; border-bottom: 1px solid var(--rule); }
100
+ .agent-pill { display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; color: var(--graphite); }
101
+ .agent-pill i { width: 7px; height: 7px; border-radius: 50%; background: var(--pencil); }
102
+ .agent-pill[data-state="listening"] i { background: var(--fine); }
103
+ .agent-pill[data-state="working"] i { background: var(--changed); animation: blink 1.2s ease-in-out infinite; }
104
+ @keyframes blink { 50% { opacity: .3; } }
105
+
106
+ .msgs { flex: 1; overflow: auto; padding: 16px 14px 8px; display: flex; flex-direction: column; gap: 14px; }
107
+ .intro { color: var(--graphite); font-size: 13px; line-height: 1.55; margin: 0; }
108
+ .msg { max-width: 94%; }
109
+ .msg.user { align-self: flex-end; }
110
+ .msg.agent { align-self: stretch; max-width: 100%; }
111
+ .bubble { overflow-wrap: anywhere; }
112
+ .msg.user .bubble { padding: 8px 11px; border-radius: 8px; background: var(--route-wash); white-space: pre-wrap; }
113
+ .msg.agent .bubble { padding: 2px 0; font-size: 14px; line-height: 1.6; }
114
+ .msg.answer .bubble { background: color-mix(in srgb, var(--fine) 12%, var(--sheet)); }
115
+ .msg .meta { font-size: 11px; color: var(--pencil); margin-top: 3px; display: flex; gap: 8px; }
116
+ .msg.user .meta { justify-content: flex-end; }
117
+ .meta .pending { color: var(--changed); }
118
+ .msg .ctx { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 4px; justify-content: flex-end; }
119
+ .msg .ctx span { font-size: 11.5px; padding: 1px 6px; border-radius: 3px; background: var(--wash); color: var(--graphite); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
120
+ .answer-q { display: block; font-size: 12px; color: var(--graphite); margin-top: 2px; }
121
+ .bubble p { margin: 0 0 8px; } .bubble p:last-child { margin-bottom: 0; }
122
+ .bubble ul, .bubble ol { margin: 4px 0 8px; padding-left: 18px; }
123
+ .bubble li { margin: 2px 0; }
124
+ .bubble h4 { margin: 10px 0 4px; font-size: 14px; }
125
+ .bubble code { font: 12.5px var(--code); background: var(--wash); padding: 0 4px; border-radius: 3px; }
126
+ .bubble pre { margin: 6px 0; padding: 9px 11px; background: var(--wash); border-radius: 4px; overflow: auto; font: 12.5px/1.5 var(--code); }
127
+ .bubble pre code { background: none; padding: 0; }
128
+ .bubble a { color: var(--route); }
129
+
130
+ .progress { margin: 0 14px 8px; font-size: 12.5px; color: var(--graphite); }
131
+ .offline-hint { margin: 0 14px 8px; font-size: 12.5px; color: var(--graphite); line-height: 1.5; }
132
+ .offline-hint code { font: 12px var(--code); }
133
+
134
+ .composer { flex: none; padding: 8px 12px 12px; border-top: 1px solid var(--rule); }
135
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; }
136
+ .chips:not(:empty) { margin-bottom: 8px; }
137
+ .chip { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; padding: 2px 4px 2px 8px; border-radius: 4px; background: var(--route-wash); color: var(--route); font-size: 12.5px; }
138
+ .chip-label { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 160px; }
139
+ .chip-src { font: 11.5px var(--code); opacity: .8; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 150px; }
140
+ .chip button { border: 0; background: none; cursor: pointer; color: inherit; opacity: .6; padding: 0 4px; font-size: 15px; line-height: 1; }
141
+ .chip button:hover { opacity: 1; }
142
+ .quick { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 0 0 8px; }
143
+ .quick button { border: 0; background: none; padding: 0; cursor: pointer; font-size: 12.5px; color: var(--route); }
144
+ .quick button:hover { text-decoration: underline; text-underline-offset: 3px; }
145
+ .input-row { display: flex; align-items: flex-end; gap: 6px; border: 1px solid var(--rule-strong); border-radius: 6px; padding: 5px 5px 5px 10px; background: var(--paper); }
146
+ .input-row:focus-within { border-color: var(--route); background: var(--sheet); }
147
+ #input { flex: 1; border: 0; outline: 0; resize: none; overflow: hidden; background: transparent; color: var(--ink); font: inherit; font-size: 14px; line-height: 1.5; max-height: 180px; padding: 4px 0; }
148
+ #input::placeholder { color: var(--pencil); }
149
+ .send { flex: none; width: 28px; height: 28px; border-radius: 4px; border: 0; background: var(--ink); cursor: pointer; display: grid; place-items: center; }
150
+ .send svg { width: 15px; height: 15px; fill: none; stroke: var(--paper); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
151
+
152
+ /* ---------- narrow screens: chat becomes a sheet ---------- */
153
+ @media (max-width: 860px) {
154
+ .app, .app.chat-closed { grid-template-columns: minmax(0, 1fr); }
155
+ .path { display: none; }
156
+ .chat { position: fixed; z-index: 40; inset: auto 0 0 0; height: 72vh; border-left: 0; border-top: 1px solid var(--rule-strong); border-radius: 10px 10px 0 0; box-shadow: 0 -12px 40px -16px rgba(16, 24, 34, .35); }
157
+ }
158
+ @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } }
@@ -0,0 +1,73 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="referrer" content="no-referrer">
7
+ <title>truemap</title>
8
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='4' fill='none' stroke='%231d2733' stroke-width='2.5'/%3E%3Cpath d='M17 3h12v12z' fill='%232c5a8c'/%3E%3C/svg%3E">
9
+ <link rel="stylesheet" href="/__truemap/workspace.css">
10
+ <script>window.TRUEMAP_TOKEN = "__TRUEMAP_TOKEN__"; window.TRUEMAP_CONTENT = "__TRUEMAP_CONTENT__";</script>
11
+ </head>
12
+ <body>
13
+ <div class="app" id="app">
14
+
15
+ <main class="stage">
16
+ <header class="bar">
17
+ <div class="switcher">
18
+ <button class="page-btn" id="pageBtn" type="button" aria-haspopup="menu" aria-expanded="false" title="Pages (Ctrl+K)">
19
+ <svg class="mark" viewBox="0 0 32 32" aria-hidden="true"><rect x="3" y="3" width="26" height="26" rx="4"/><path d="M17 3h12v12z"/></svg>
20
+ <span class="page-name" id="pageTitle">truemap</span>
21
+ <span class="state-dot" id="titleDot" hidden></span>
22
+ <svg class="chev" viewBox="0 0 16 16" aria-hidden="true"><path d="M4 6l4 4 4-4"/></svg>
23
+ </button>
24
+ <div class="menu" id="menu" role="menu" hidden>
25
+ <div class="menu-head"><span id="project"></span><input id="filter" type="search" placeholder="Find a page" autocomplete="off" hidden></div>
26
+ <div class="menu-list" id="pages"></div>
27
+ <div class="menu-foot"><button class="text-btn" id="recheck" type="button">Check against code</button><span id="ver"></span></div>
28
+ </div>
29
+ </div>
30
+ <span class="path" id="pagePath"></span>
31
+ <span class="spacer"></span>
32
+ <button class="check-chip" id="checkChip" type="button" hidden></button>
33
+ <button class="icon-btn" id="toggleChat" type="button" aria-label="Show chat" title="Show chat" hidden>
34
+ <svg viewBox="0 0 20 20" aria-hidden="true"><path d="M4 4.5h12a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1H9l-3.5 3v-3H4a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1z"/></svg>
35
+ <span class="unread" id="unread" hidden></span>
36
+ </button>
37
+ </header>
38
+ <div class="frame-wrap">
39
+ <iframe id="frame" title="Page" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox" referrerpolicy="no-referrer"></iframe>
40
+ <section class="empty" id="empty" hidden>
41
+ <h1>No pages yet</h1>
42
+ <p>Ask the agent to read the code and draw the project’s blueprint. Then select anything on it to ask about it.</p>
43
+ <button class="primary" id="drawBlueprint" type="button">Ask the agent for a blueprint</button>
44
+ </section>
45
+ </div>
46
+ </main>
47
+
48
+ <aside class="chat" id="chat">
49
+ <header class="chat-head">
50
+ <span class="agent-pill" id="agent" data-state="offline"><i></i><span id="agentLabel">Agent not connected</span></span>
51
+ <button class="icon-btn quiet" id="closeChat" type="button" aria-label="Hide chat" title="Hide chat">
52
+ <svg viewBox="0 0 20 20" aria-hidden="true"><path d="M7 5l5 5-5 5"/></svg>
53
+ </button>
54
+ </header>
55
+ <div class="msgs" id="msgs" aria-live="polite"></div>
56
+ <div class="progress" id="progress" hidden></div>
57
+ <div class="offline-hint" id="offlineHint" hidden></div>
58
+ <form class="composer" id="composer" autocomplete="off">
59
+ <div class="chips" id="chips"></div>
60
+ <div class="quick" id="quick" hidden></div>
61
+ <div class="input-row">
62
+ <textarea id="input" rows="1" aria-label="Message"></textarea>
63
+ <button class="send" id="send" type="submit" aria-label="Send">
64
+ <svg viewBox="0 0 20 20" aria-hidden="true"><path d="M10 16V4M5 9l5-5 5 5"/></svg>
65
+ </button>
66
+ </div>
67
+ </form>
68
+ </aside>
69
+
70
+ </div>
71
+ <script src="/__truemap/workspace.js"></script>
72
+ </body>
73
+ </html>
@@ -0,0 +1,339 @@
1
+ (() => {
2
+ const TOKEN = window.TRUEMAP_TOKEN;
3
+ const CONTENT = window.TRUEMAP_CONTENT;
4
+
5
+ const S = {
6
+ listening: 'Agent is listening', working: 'Agent is working', offline: 'Agent not connected',
7
+ placeholder: 'Ask about this project, or select something on the page', placeholderCtx: 'Ask about the selection',
8
+ intro: 'Select a box or some text on the page, then ask about it. The agent receives the code it points to.',
9
+ drawPrompt: 'Read this project and draw its blueprint as .truemap/index.html, then open it for me.',
10
+ quick: [
11
+ ['Explain', 'Explain how this works.'],
12
+ ['What uses it', 'What depends on this, and what does it depend on?'],
13
+ ['Why like this', 'Why is it built this way? What are the trade-offs?'],
14
+ ['Change it…', null],
15
+ ],
16
+ changePrefix: 'Change it so that ',
17
+ ok: 'Matches the code', changed: (n) => `${n} changed in code`, broken: (n) => `${n} out of date`,
18
+ fixPrompt: (p, c, b) => `Check ${p} against the code and update it: ${[b && `${b} anchor(s) no longer match`, c && `${c} anchor(s) whose code changed after the page was written`].filter(Boolean).join(', ')}.`,
19
+ queued: 'Waiting for the agent', answered: 'Chose', fromPage: 'sent by the page', blueprint: 'Blueprint',
20
+ offlineHint: 'Messages wait here until the agent runs <code>truemap listen</code>.',
21
+ };
22
+
23
+ const $ = (id) => document.getElementById(id);
24
+ const app = $('app'); const frame = $('frame'); const msgsEl = $('msgs'); const input = $('input'); const menu = $('menu');
25
+ const state = { pages: [], check: { results: [] }, page: null, chips: [], agent: 'offline', pending: new Set(), scroll: {}, history: [], frameFocusAt: 0 };
26
+
27
+ const store = {
28
+ get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
29
+ set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* ignore */ } },
30
+ };
31
+ const api = (path, body) => fetch(path, {
32
+ method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Truemap-Token': TOKEN }, body: JSON.stringify(body || {}),
33
+ }).then((r) => r.json()).catch(() => ({}));
34
+ const toFrame = (msg) => { if (state.page && !frame.hidden) frame.contentWindow?.postMessage({ __truemap: true, ...msg }, CONTENT); };
35
+
36
+ // ---------- text helpers ----------
37
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
38
+ const timeOf = (iso) => { try { return new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } catch { return ''; } };
39
+ function inline(s) {
40
+ return s
41
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
42
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
43
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, href) => {
44
+ if (/^[\w./-]+\.html?(#[\w-]*)?$/i.test(href)) return `<a href="#" data-page="${href}">${t}</a>`;
45
+ if (/^https:\/\/[^\s"'<>]+$/i.test(href)) return `<a href="${href}" target="_blank" rel="noopener noreferrer">${t}</a>`;
46
+ return t;
47
+ });
48
+ }
49
+ function md(text) {
50
+ const lines = esc(text).split('\n');
51
+ let html = ''; let list = null; let code = null; let para = [];
52
+ const flush = () => { if (para.length) { html += `<p>${inline(para.join('<br>'))}</p>`; para = []; } };
53
+ const close = () => { if (list) { html += `</${list}>`; list = null; } };
54
+ for (const line of lines) {
55
+ if (code !== null) { if (/^```/.test(line)) { html += `<pre><code>${code}</code></pre>`; code = null; } else code += line + '\n'; continue; }
56
+ if (/^```/.test(line)) { flush(); close(); code = ''; continue; }
57
+ let m;
58
+ if ((m = line.match(/^\s*[-*]\s+(.*)/))) { flush(); if (list !== 'ul') { close(); html += '<ul>'; list = 'ul'; } html += `<li>${inline(m[1])}</li>`; continue; }
59
+ if ((m = line.match(/^\s*\d+[.)]\s+(.*)/))) { flush(); if (list !== 'ol') { close(); html += '<ol>'; list = 'ol'; } html += `<li>${inline(m[1])}</li>`; continue; }
60
+ if ((m = line.match(/^#{1,4}\s+(.*)/))) { flush(); close(); html += `<h4>${inline(m[1])}</h4>`; continue; }
61
+ if (!line.trim()) { flush(); close(); continue; }
62
+ close(); para.push(line);
63
+ }
64
+ if (code !== null) html += `<pre><code>${code}</code></pre>`;
65
+ flush(); close();
66
+ return html;
67
+ }
68
+
69
+ // ---------- chat panel open/closed ----------
70
+ const narrow = () => window.matchMedia('(max-width: 860px)').matches;
71
+ function setChat(open, remember = true) {
72
+ app.classList.toggle('chat-closed', !open);
73
+ $('toggleChat').hidden = open;
74
+ if (open) $('unread').hidden = true;
75
+ if (remember && !narrow()) store.set('truemap.chat', open ? 'open' : 'closed');
76
+ }
77
+ setChat(narrow() ? false : store.get('truemap.chat') !== 'closed', false);
78
+ $('toggleChat').onclick = () => { setChat(true); input.focus(); };
79
+ $('closeChat').onclick = () => setChat(false);
80
+ const chatOpen = () => !app.classList.contains('chat-closed');
81
+
82
+ // ---------- page switcher ----------
83
+ const resultFor = (page) => state.check.results?.find((r) => r.page === page);
84
+ const stateOf = (r) => (r?.counts?.broken ? 'broken' : r?.counts?.changed ? 'changed' : '');
85
+ const titleOf = (p) => (p.page === 'index.html' && (!p.title || p.title === 'index') ? S.blueprint : p.title);
86
+
87
+ function renderMenu() {
88
+ const list = $('pages'); list.innerHTML = '';
89
+ const q = $('filter').value.trim().toLowerCase();
90
+ $('filter').hidden = state.pages.length <= 7;
91
+ state.pages
92
+ .filter((p) => !q || `${p.title} ${p.page}`.toLowerCase().includes(q))
93
+ .forEach((p, i, arr) => {
94
+ const st = stateOf(resultFor(p.page));
95
+ const b = document.createElement('button');
96
+ b.type = 'button'; b.className = 'page-item' + (p.page === state.page ? ' active' : ''); b.setAttribute('role', 'menuitem');
97
+ b.innerHTML = `<span class="pi-text"><span class="pi-title">${esc(titleOf(p))}</span><span class="pi-file">${esc(p.page)}</span></span>${st ? `<span class="state-dot ${st}"></span>` : ''}`;
98
+ b.onclick = () => { closeMenu(); go(p.page); };
99
+ list.appendChild(b);
100
+ if (i === 0 && p.page === 'index.html' && arr.length > 1) list.insertAdjacentHTML('beforeend', '<div class="menu-gap"></div>');
101
+ });
102
+ }
103
+ function openMenu() { renderMenu(); menu.hidden = false; $('pageBtn').setAttribute('aria-expanded', 'true'); ($('filter').hidden ? menu.querySelector('.page-item.active, .page-item') : $('filter'))?.focus(); }
104
+ function closeMenu() { menu.hidden = true; $('pageBtn').setAttribute('aria-expanded', 'false'); }
105
+ $('pageBtn').onclick = () => (menu.hidden ? openMenu() : closeMenu());
106
+ $('filter').addEventListener('input', renderMenu);
107
+ document.addEventListener('click', (e) => { if (!menu.hidden && !e.target.closest('.switcher')) closeMenu(); });
108
+ window.addEventListener('blur', () => { if (!menu.hidden) closeMenu(); });
109
+ document.addEventListener('keydown', (e) => {
110
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); menu.hidden ? openMenu() : closeMenu(); }
111
+ else if (e.key === 'Escape' && !menu.hidden) { closeMenu(); $('pageBtn').focus(); }
112
+ else if (!menu.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
113
+ const items = [...menu.querySelectorAll('.page-item')]; if (!items.length) return;
114
+ e.preventDefault();
115
+ const i = items.indexOf(document.activeElement);
116
+ items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length].focus();
117
+ }
118
+ });
119
+ $('recheck').onclick = () => { api('/api/check'); closeMenu(); };
120
+
121
+ function renderHeader() {
122
+ const p = state.pages.find((x) => x.page === state.page);
123
+ $('pageTitle').textContent = p ? titleOf(p) : 'truemap';
124
+ $('pagePath').textContent = state.page ? `.truemap/${state.page}` : '';
125
+ document.title = p ? `${titleOf(p)} – truemap` : 'truemap';
126
+ const r = resultFor(state.page); const st = stateOf(r);
127
+ const dot = $('titleDot'); dot.hidden = !st; dot.className = `state-dot ${st}`;
128
+ const chip = $('checkChip');
129
+ if (!r || r.missing || !r.anchors?.length) { chip.hidden = true; return; }
130
+ chip.hidden = false;
131
+ const { changed, broken } = r.counts;
132
+ chip.dataset.state = st || 'ok';
133
+ chip.textContent = broken ? S.broken(broken) + (changed ? `, ${S.changed(changed)}` : '') : changed ? S.changed(changed) : S.ok;
134
+ chip.title = st ? 'Ask the agent to update this page' : '';
135
+ }
136
+ function sendMarks() {
137
+ const r = resultFor(state.page);
138
+ toFrame({ type: 'marks', items: (r?.anchors || []).filter((a) => a.state !== 'ok').map((a) => ({ src: a.src, state: a.state })) });
139
+ }
140
+
141
+ const pageUrl = (page, bust) => `${CONTENT}/pages/${page.split('/').map(encodeURIComponent).join('/')}${bust ? `?r=${Date.now()}` : ''}`;
142
+ function go(page, { force = false } = {}) {
143
+ if (!page) return showEmpty();
144
+ $('empty').hidden = true; frame.hidden = false;
145
+ if (state.page !== page || force) frame.src = pageUrl(page);
146
+ setCurrent(page);
147
+ }
148
+ function setCurrent(page) {
149
+ if (state.page !== page) { state.chips = []; renderChips(); }
150
+ state.page = page;
151
+ history.replaceState(null, '', `${location.pathname}${location.search}#page=${encodeURIComponent(page)}`);
152
+ api('/api/viewing', { page });
153
+ renderHeader();
154
+ }
155
+ function showEmpty() {
156
+ state.page = null; frame.hidden = true; frame.removeAttribute('src'); $('empty').hidden = false; renderHeader();
157
+ }
158
+ const reloadFrame = () => { if (state.page) frame.src = pageUrl(state.page, true); };
159
+
160
+ // ---------- chat ----------
161
+ function renderAll() {
162
+ msgsEl.innerHTML = `<p class="intro">${esc(S.intro)}</p>`;
163
+ for (const e of state.history) appendEntry(e, false);
164
+ scrollChat();
165
+ }
166
+ function appendEntry(e, scroll = true) {
167
+ const el = document.createElement('div');
168
+ if (e.role === 'agent') {
169
+ el.className = 'msg agent';
170
+ el.innerHTML = `<div class="bubble">${md(e.text)}</div><div class="meta"><span>${timeOf(e.at)}</span></div>`;
171
+ $('progress').hidden = true;
172
+ if (!chatOpen()) $('unread').hidden = false;
173
+ } else {
174
+ const isAnswer = e.kind === 'answer';
175
+ el.className = 'msg user' + (isAnswer ? ' answer' : '');
176
+ el.dataset.id = e.id;
177
+ const ctx = (e.context || []).map((c) => `<span title="${esc(c.src || '')}">${esc(c.label)}</span>`).join('');
178
+ const body = isAnswer
179
+ ? `${esc(S.answered)}: <strong>${esc(e.answer?.choice || '')}</strong>${e.answer?.note ? `<br>${esc(e.answer.note)}` : ''}<span class="answer-q">${esc(e.answer?.question || '')}</span>`
180
+ : esc(e.text);
181
+ const pending = state.pending.has(e.id) ? `<span class="pending">${S.queued}</span>` : '';
182
+ el.innerHTML = `${ctx && !isAnswer ? `<div class="ctx">${ctx}</div>` : ''}<div class="bubble">${body}</div><div class="meta">${pending}${e.from === 'page' ? `<span>${S.fromPage}</span>` : ''}<span>${timeOf(e.at)}</span></div>`;
183
+ }
184
+ msgsEl.appendChild(el);
185
+ if (scroll) scrollChat();
186
+ }
187
+ const scrollChat = () => { msgsEl.scrollTop = msgsEl.scrollHeight; };
188
+ msgsEl.addEventListener('click', (e) => {
189
+ const a = e.target.closest('a[data-page]');
190
+ if (!a) return;
191
+ e.preventDefault();
192
+ const [page] = a.dataset.page.split('#');
193
+ if (state.pages.some((p) => p.page === page)) go(page);
194
+ });
195
+
196
+ function setAgent(s) {
197
+ state.agent = s;
198
+ $('agent').dataset.state = s; $('agentLabel').textContent = S[s] || s;
199
+ $('offlineHint').innerHTML = S.offlineHint; $('offlineHint').hidden = s !== 'offline';
200
+ }
201
+
202
+ function renderChips() {
203
+ const box = $('chips'); box.innerHTML = '';
204
+ state.chips.forEach((c, i) => {
205
+ const chip = document.createElement('span'); chip.className = 'chip';
206
+ chip.innerHTML = `<span class="chip-label">${esc(c.label)}</span>${c.src ? `<span class="chip-src">${esc(c.src)}</span>` : ''}<button type="button" aria-label="Remove">×</button>`;
207
+ chip.querySelector('button').onclick = () => {
208
+ state.chips.splice(i, 1); renderChips();
209
+ if (!state.chips.some((x) => x.kind === 'element')) toFrame({ type: 'clear-selection' });
210
+ };
211
+ box.appendChild(chip);
212
+ });
213
+ const quick = $('quick');
214
+ quick.hidden = state.chips.length === 0;
215
+ if (!quick.childElementCount) {
216
+ for (const [label, prompt] of S.quick) {
217
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = label;
218
+ b.onclick = () => { if (!prompt) { input.value = S.changePrefix; input.focus(); autosize(); return; } send(prompt); };
219
+ quick.appendChild(b);
220
+ }
221
+ }
222
+ input.placeholder = state.chips.length ? S.placeholderCtx : S.placeholder;
223
+ }
224
+
225
+ async function send(text, extra = {}) {
226
+ text = String(text || '').trim();
227
+ const context = extra.context ?? state.chips;
228
+ if (!text && !context.length && !extra.answer) return;
229
+ const r = await api('/api/send', { text, context, page: state.page, ...extra });
230
+ if (r.id && !r.delivered) { state.pending.add(r.id); markPending(r.id, true); }
231
+ if (!extra.keepChips) { state.chips = []; renderChips(); toFrame({ type: 'clear-selection' }); }
232
+ }
233
+ function markPending(id, on) {
234
+ const el = msgsEl.querySelector(`.msg[data-id="${CSS.escape(id)}"] .meta`);
235
+ if (!el) return;
236
+ el.querySelector('.pending')?.remove();
237
+ if (on) el.insertAdjacentHTML('afterbegin', `<span class="pending">${S.queued}</span>`);
238
+ }
239
+
240
+ const autosize = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 180) + 'px'; };
241
+ input.addEventListener('input', autosize);
242
+ input.addEventListener('keydown', (e) => {
243
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && e.keyCode !== 229) { e.preventDefault(); $('composer').requestSubmit(); }
244
+ });
245
+ $('composer').addEventListener('submit', (e) => {
246
+ e.preventDefault();
247
+ const text = input.value;
248
+ if (!text.trim() && !state.chips.length) return;
249
+ input.value = ''; autosize();
250
+ send(text);
251
+ });
252
+ input.placeholder = S.placeholder;
253
+
254
+ $('drawBlueprint').onclick = () => { setChat(true); send(S.drawPrompt, { context: [] }); };
255
+ $('checkChip').onclick = () => {
256
+ const r = resultFor(state.page);
257
+ if (!r || (!r.counts.changed && !r.counts.broken)) return;
258
+ setChat(true);
259
+ send(S.fixPrompt(`.truemap/${state.page}`, r.counts.changed, r.counts.broken), { context: [] });
260
+ };
261
+
262
+ // A decision only counts as the user's if the user actually moved focus into the page.
263
+ window.addEventListener('blur', () => { setTimeout(() => { if (document.activeElement === frame) state.frameFocusAt = Date.now(); }, 0); });
264
+ const userIsInFrame = () => document.activeElement === frame && state.frameFocusAt > 0;
265
+
266
+ // ---------- messages from the page iframe ----------
267
+ window.addEventListener('message', (e) => {
268
+ if (e.source !== frame.contentWindow || e.origin !== CONTENT || !e.data || !e.data.__truemap) return;
269
+ const d = e.data;
270
+ if (d.type === 'loaded') {
271
+ if (d.page && d.page !== state.page) setCurrent(d.page);
272
+ renderHeader(); sendMarks();
273
+ const y = state.scroll[d.page]; if (y) toFrame({ type: 'scroll', y });
274
+ } else if (d.type === 'scroll') {
275
+ state.scroll[d.page] = d.y;
276
+ } else if (d.type === 'select') {
277
+ state.chips = [...state.chips.filter((c) => c.kind === 'text'), ...(d.items || [])].slice(0, 8);
278
+ renderChips();
279
+ if (d.items?.length) { setChat(true, false); input.focus({ preventScroll: true }); }
280
+ } else if (d.type === 'select-text') {
281
+ state.chips = [...state.chips.filter((c) => c.kind !== 'text'), d.item];
282
+ renderChips();
283
+ } else if (d.type === 'answer') {
284
+ const fromUser = d.trusted === true && userIsInFrame();
285
+ send('', {
286
+ kind: 'answer', from: fromUser ? 'user' : 'page', keepChips: true,
287
+ context: d.src ? [{ kind: 'element', label: d.question, src: d.src }] : [],
288
+ answer: { question: d.question, choice: d.choice, note: d.note },
289
+ });
290
+ } else if (d.type === 'page-send') {
291
+ if (d.text) send(d.text, { from: 'page', context: [], keepChips: true });
292
+ }
293
+ });
294
+
295
+ // ---------- live events from the server ----------
296
+ function connect() {
297
+ const es = new EventSource(`/api/events?t=${encodeURIComponent(TOKEN)}`);
298
+ let greeted = false;
299
+ const guard = setTimeout(() => { if (!greeted) { es.close(); connect(); } }, 3000);
300
+ es.onmessage = (ev) => {
301
+ let d; try { d = JSON.parse(ev.data); } catch { return; }
302
+ if (d.type === 'hello') {
303
+ greeted = true; clearTimeout(guard);
304
+ state.pages = d.pages || []; state.check = d.check || { results: [] }; state.history = d.history || [];
305
+ state.pending = new Set(d.pending || []);
306
+ $('ver').textContent = `truemap ${d.version}`;
307
+ $('project').textContent = String(d.root || '').split(/[\\/]/).filter(Boolean).pop() || '';
308
+ setAgent(d.agent);
309
+ renderAll();
310
+ const fromHash = decodeURIComponent((location.hash.match(/page=([^&]+)/) || [])[1] || '');
311
+ const target = [state.page, fromHash, d.current].find((p) => p && state.pages.some((x) => x.page === p)) || state.pages[0]?.page;
312
+ target ? go(target, { force: !frame.getAttribute('src') }) : showEmpty();
313
+ } else if (d.type === 'chat') {
314
+ state.history.push(d.entry); appendEntry(d.entry);
315
+ } else if (d.type === 'agent') {
316
+ setAgent(d.state);
317
+ if (d.state !== 'working') $('progress').hidden = true;
318
+ } else if (d.type === 'delivered') {
319
+ for (const id of d.ids || []) { state.pending.delete(id); markPending(id, false); }
320
+ } else if (d.type === 'progress') {
321
+ const p = $('progress'); p.textContent = d.text; p.hidden = !d.text;
322
+ } else if (d.type === 'pages') {
323
+ state.pages = d.pages || []; renderHeader(); if (!menu.hidden) renderMenu();
324
+ if (!state.page && state.pages[0]) go(state.pages[0].page);
325
+ else if (state.page && !state.pages.some((p) => p.page === state.page)) state.pages[0] ? go(state.pages[0].page) : showEmpty();
326
+ } else if (d.type === 'changed') {
327
+ const files = d.files || [];
328
+ if (state.page && files.some((f) => !f || f === state.page || f.startsWith('assets/'))) reloadFrame();
329
+ } else if (d.type === 'check') {
330
+ state.check = d.check || { results: [] }; renderHeader(); sendMarks(); if (!menu.hidden) renderMenu();
331
+ } else if (d.type === 'navigate') {
332
+ if (d.pages) state.pages = d.pages;
333
+ if (d.page && state.pages.some((p) => p.page === d.page)) go(d.page, { force: true });
334
+ renderHeader();
335
+ }
336
+ };
337
+ }
338
+ connect();
339
+ })();