intent-prompt-graph 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.
package/web/app.ts ADDED
@@ -0,0 +1,349 @@
1
+ import type { ServerEvent, Turn } from "../src/model";
2
+ import { timelineRows, type Point } from "./layout";
3
+ import {
4
+ applyView,
5
+ clampZoom,
6
+ filterGraph,
7
+ fitView,
8
+ followTarget,
9
+ inspectorSignature,
10
+ isNodeVisible,
11
+ paintChrome,
12
+ paintGraph,
13
+ paintInspector,
14
+ paintSidebar,
15
+ paintTimeline,
16
+ paintTopbar,
17
+ revealView,
18
+ selectedNode,
19
+ stepSelection,
20
+ type Els,
21
+ type FilterMode,
22
+ type State,
23
+ type View,
24
+ type ViewMode,
25
+ } from "./view";
26
+
27
+ type Theme = "ink" | "paper";
28
+
29
+ const VIEW_MODE_KEY = "ipg.viewMode";
30
+ /** Also read by the inline script in index.html, which sets the theme before first paint. */
31
+ const THEME_KEY = "ipg.theme";
32
+ const THEME_NAME: Record<Theme, string> = { ink: "Ink", paper: "Paper" };
33
+
34
+ function byId<T extends Element = HTMLElement>(id: string): T {
35
+ const found = document.querySelector<T>(`#${id}`);
36
+ if (!found) throw new Error(`ipg: missing #${id}`);
37
+ return found;
38
+ }
39
+
40
+ const els: Els = {
41
+ statusDot: byId("status-dot"),
42
+ sessionTitle: byId("session-title"),
43
+ modePill: byId("mode-pill"),
44
+ sidebar: byId("sidebar"),
45
+ viewport: byId("viewport"),
46
+ tlSummary: byId("tl-summary"),
47
+ tlRows: byId("tl-rows"),
48
+ world: byId("world"),
49
+ edges: byId<SVGSVGElement>("edges"),
50
+ nodes: byId("nodes"),
51
+ labels: byId("labels"),
52
+ keyed: new Map(),
53
+ panel: byId("panel"),
54
+ banner: byId("banner"),
55
+ toast: byId("toast"),
56
+ bar: byId("bar"),
57
+ follow: byId("follow"),
58
+ };
59
+ const stage = byId("stage");
60
+ const themeButton = byId("theme");
61
+
62
+ /** The view the reader last chose; the timeline when nothing is stored or storage is unavailable. */
63
+ function storedViewMode(): ViewMode {
64
+ try {
65
+ return localStorage.getItem(VIEW_MODE_KEY) === "graph" ? "graph" : "timeline";
66
+ } catch {
67
+ return "timeline";
68
+ }
69
+ }
70
+
71
+ const state: State = {
72
+ connected: false,
73
+ turns: [],
74
+ graph: { title: "Loading session…", nodes: [], edges: [], mode: "heuristic" },
75
+ filter: "all",
76
+ viewMode: storedViewMode(),
77
+ follow: true,
78
+ };
79
+
80
+ let view: View = fitView(new Map(), 0, 0);
81
+ let lastPositions: Map<string, Point> = new Map();
82
+ let lastInspectorSig = "";
83
+ let opened = false;
84
+
85
+ function glideTo(next: View): void {
86
+ view = next;
87
+ els.world.classList.add("glide");
88
+ applyView(els.world, view);
89
+ window.setTimeout(() => els.world.classList.remove("glide"), 380);
90
+ }
91
+
92
+ /** Fits the graph, or with `zoom` shows the selected node at that zoom. */
93
+ function glideFit(zoom?: number): void {
94
+ const focus = selectedNode(state)?.id;
95
+ glideTo(fitView(lastPositions, els.viewport.clientWidth, els.viewport.clientHeight, focus, zoom));
96
+ }
97
+
98
+ /** Brings the selected node into sight: scrolls the timeline to its row, or pans the graph to its card. */
99
+ function reveal(): void {
100
+ const id = selectedNode(state)?.id;
101
+ if (id === undefined) return;
102
+ if (state.viewMode === "graph") {
103
+ const p = lastPositions.get(id);
104
+ if (!p) return;
105
+ const next = revealView(view, p, els.viewport.clientWidth, els.viewport.clientHeight);
106
+ if (next !== view) glideTo(next);
107
+ return;
108
+ }
109
+ const row = els.tlRows.querySelector<HTMLElement>(`[data-node="${CSS.escape(id)}"]`);
110
+ if (!row) return;
111
+ // Scrolls #tl-rows itself: scrollIntoView would also move every scrollable ancestor.
112
+ const box = els.tlRows;
113
+ const margin = 12;
114
+ const top = row.offsetTop - margin;
115
+ const bottom = row.offsetTop + row.offsetHeight + margin;
116
+ // The floating #bar covers the foot of the list, so only the part above it counts as in sight.
117
+ const sight = els.bar.getBoundingClientRect().top - box.getBoundingClientRect().top;
118
+ if (top < box.scrollTop) box.scrollTo({ top, behavior: "smooth" });
119
+ else if (bottom > box.scrollTop + sight) box.scrollTo({ top: bottom - sight, behavior: "smooth" });
120
+ }
121
+
122
+ function syncHash(): void {
123
+ // Before the first snapshot the hash is still the reader's deep link (#node=…): leave it alone.
124
+ if (!opened) return;
125
+ const sel = selectedNode(state)?.id;
126
+ const next = state.follow ? "#latest" : sel ? `#node=${encodeURIComponent(sel)}` : "";
127
+ if (location.hash === next) return;
128
+ history.replaceState(null, "", `${location.pathname}${location.search}${next}`);
129
+ }
130
+
131
+ function render(): void {
132
+ paintTopbar(state, els);
133
+ paintSidebar(state, els);
134
+ if (state.viewMode === "graph") lastPositions = paintGraph(state, els);
135
+ else paintTimeline(state, els);
136
+ const sig = inspectorSignature(state);
137
+ if (sig !== lastInspectorSig) {
138
+ lastInspectorSig = sig;
139
+ paintInspector(state, els);
140
+ }
141
+ paintChrome(state, els);
142
+ syncHash();
143
+ }
144
+
145
+ /** Renders, then frames the active view: the graph is fitted again, the timeline shows the selected row. */
146
+ function renderAndFrame(): void {
147
+ render();
148
+ if (state.viewMode === "graph") glideFit();
149
+ else reveal();
150
+ }
151
+
152
+ function refollow(): void {
153
+ if (!state.follow) return;
154
+ const latest = followTarget(state.graph);
155
+ state.selected = latest?.id;
156
+ state.seenNodeId = latest?.id;
157
+ }
158
+
159
+ function selectNode(id: string): void {
160
+ state.follow = false;
161
+ state.selected = id;
162
+ if (followTarget(state.graph)?.id === id) state.seenNodeId = id;
163
+ // A node the active filter hides cannot be shown as selected, so the filter gives way.
164
+ const node = state.graph.nodes.find((n) => n.id === id);
165
+ if (node && !isNodeVisible(node, state.filter)) state.filter = "all";
166
+ render();
167
+ reveal();
168
+ }
169
+
170
+ function upsertTurn(t: Turn): void {
171
+ const idx = state.turns.findIndex((x) => x.id === t.id);
172
+ if (idx < 0) state.turns.push(t);
173
+ else state.turns[idx] = t;
174
+ }
175
+
176
+ function onEvent(ev: ServerEvent): void {
177
+ switch (ev.type) {
178
+ case "snapshot": {
179
+ state.turns = ev.turns;
180
+ state.graph = ev.graph;
181
+ state.labelerError = ev.labelerError;
182
+ const hashNode = /^#node=(.+)$/.exec(location.hash);
183
+ if (hashNode && !opened) {
184
+ state.selected = decodeURIComponent(hashNode[1] ?? "");
185
+ state.follow = false;
186
+ }
187
+ refollow();
188
+ if (opened) {
189
+ render();
190
+ } else {
191
+ opened = true;
192
+ renderAndFrame();
193
+ }
194
+ return;
195
+ }
196
+ case "reset":
197
+ state.turns = [];
198
+ state.graph = { title: "Reloading session…", nodes: [], edges: [], mode: "heuristic" };
199
+ state.selected = undefined;
200
+ break;
201
+ case "turn":
202
+ upsertTurn(ev.turn);
203
+ break;
204
+ case "graph": {
205
+ const before = state.selected;
206
+ state.graph = ev.graph;
207
+ refollow();
208
+ render();
209
+ if (state.selected !== before) reveal();
210
+ return;
211
+ }
212
+ case "labeler":
213
+ state.labelerError = ev.error;
214
+ break;
215
+ }
216
+ render();
217
+ }
218
+
219
+ // Click delegation: view switch, filter buttons, sidebar/summary/toast jumps, nodes and timeline rows.
220
+ let dragged = false;
221
+ document.addEventListener("click", (e) => {
222
+ if (dragged) {
223
+ dragged = false;
224
+ return;
225
+ }
226
+ if (!(e.target instanceof Element)) return;
227
+
228
+ const viewBtn = e.target.closest<HTMLElement>("[data-set-view]");
229
+ if (viewBtn) {
230
+ state.viewMode = viewBtn.dataset.setView === "graph" ? "graph" : "timeline";
231
+ try {
232
+ localStorage.setItem(VIEW_MODE_KEY, state.viewMode);
233
+ } catch {
234
+ // Storage is unavailable: the choice lasts for this page load only.
235
+ }
236
+ renderAndFrame();
237
+ return;
238
+ }
239
+
240
+ const filterBtn = e.target.closest<HTMLElement>("[data-filter]");
241
+ if (filterBtn) {
242
+ state.filter = filterBtn.dataset.filter as FilterMode;
243
+ renderAndFrame();
244
+ return;
245
+ }
246
+
247
+ const target = e.target.closest<HTMLElement>("[data-jump], [data-node]");
248
+ const id = target?.dataset.jump ?? target?.dataset.node;
249
+ if (id) selectNode(id);
250
+ });
251
+
252
+ // Up/Down move the selection through the nodes in timeline order, in both views.
253
+ document.addEventListener("keydown", (e) => {
254
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
255
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
256
+ const shown = filterGraph(state.graph, state.filter);
257
+ const ids = timelineRows(shown.nodes, shown.edges).map((r) => r.node.id);
258
+ const next = stepSelection(ids, selectedNode(state)?.id, e.key === "ArrowDown" ? 1 : -1);
259
+ e.preventDefault();
260
+ if (next !== undefined) selectNode(next);
261
+ });
262
+
263
+ els.follow.addEventListener("click", () => {
264
+ state.follow = !state.follow;
265
+ refollow();
266
+ render();
267
+ reveal();
268
+ });
269
+ byId("fit").addEventListener("click", () => glideFit());
270
+ byId("reset").addEventListener("click", () => glideFit(1));
271
+
272
+ /** Starts as the theme index.html put on <html> at load; the button flips it. */
273
+ let theme: Theme = document.documentElement.dataset.theme === "paper" ? "paper" : "ink";
274
+
275
+ function showTheme(): void {
276
+ document.documentElement.dataset.theme = theme;
277
+ themeButton.textContent = THEME_NAME[theme];
278
+ }
279
+
280
+ showTheme();
281
+ themeButton.addEventListener("click", () => {
282
+ theme = theme === "ink" ? "paper" : "ink";
283
+ showTheme();
284
+ try {
285
+ localStorage.setItem(THEME_KEY, theme);
286
+ } catch {
287
+ // Storage is unavailable: the choice lasts for this page load only.
288
+ }
289
+ });
290
+
291
+ // Cursor-anchored wheel zoom.
292
+ stage.addEventListener(
293
+ "wheel",
294
+ (e) => {
295
+ e.preventDefault();
296
+ const rect = stage.getBoundingClientRect();
297
+ const mx = e.clientX - rect.left;
298
+ const my = e.clientY - rect.top;
299
+ const z = clampZoom(view.z * Math.exp(-e.deltaY * 0.0012));
300
+ view = {
301
+ z,
302
+ tx: mx - ((mx - view.tx) / view.z) * z,
303
+ ty: my - ((my - view.ty) / view.z) * z,
304
+ };
305
+ applyView(els.world, view);
306
+ },
307
+ { passive: false },
308
+ );
309
+
310
+ // Pointer drag pan.
311
+ let press: { id: number; x: number; y: number; lastX: number; lastY: number; moving: boolean } | undefined;
312
+ stage.addEventListener("pointerdown", (e) => {
313
+ if (e.button !== 0 || (e.target instanceof Element && e.target.closest(".node"))) return;
314
+ dragged = false;
315
+ press = { id: e.pointerId, x: e.clientX, y: e.clientY, lastX: e.clientX, lastY: e.clientY, moving: false };
316
+ });
317
+ stage.addEventListener("pointermove", (e) => {
318
+ if (!press) return;
319
+ if (!press.moving) {
320
+ if (Math.hypot(e.clientX - press.x, e.clientY - press.y) <= 4) return;
321
+ press.moving = true;
322
+ stage.setPointerCapture(press.id);
323
+ }
324
+ view = { ...view, tx: view.tx + e.clientX - press.lastX, ty: view.ty + e.clientY - press.lastY };
325
+ press.lastX = e.clientX;
326
+ press.lastY = e.clientY;
327
+ applyView(els.world, view);
328
+ });
329
+ const endPress = (): void => {
330
+ if (press?.moving) dragged = true;
331
+ press = undefined;
332
+ };
333
+ stage.addEventListener("pointerup", endPress);
334
+ stage.addEventListener("pointercancel", endPress);
335
+
336
+ const route = /^\/s\/([^/]+)\/([^/]+)$/.exec(location.pathname);
337
+ if (!route) throw new Error("ipg: not a session page");
338
+ const source = new EventSource(`/api/s/${route[1] ?? ""}/${route[2] ?? ""}/events`);
339
+ source.addEventListener("open", () => {
340
+ state.connected = true;
341
+ render();
342
+ });
343
+ source.addEventListener("error", () => {
344
+ state.connected = false;
345
+ render();
346
+ });
347
+ source.addEventListener("message", (m) => onEvent(JSON.parse(String(m.data)) as ServerEvent));
348
+
349
+ render();
package/web/index.html ADDED
@@ -0,0 +1,70 @@
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
+ <title>intent-prompt-graph</title>
7
+ <script>
8
+ // Sets the theme before first paint: the stored choice, else the system colour scheme.
9
+ (function () {
10
+ var theme = null;
11
+ try { theme = localStorage.getItem("ipg.theme"); } catch (e) {}
12
+ if (theme !== "ink" && theme !== "paper") theme = matchMedia("(prefers-color-scheme: light)").matches ? "paper" : "ink";
13
+ document.documentElement.dataset.theme = theme;
14
+ })();
15
+ </script>
16
+ <link rel="stylesheet" href="./style.css">
17
+ </head>
18
+ <body>
19
+ <div id="app">
20
+ <header id="topbar">
21
+ <div class="brand">
22
+ <span id="status-dot" class="dot"></span>
23
+ <span id="session-title">intent-prompt-graph</span>
24
+ <span id="mode-pill" class="pill">heuristic</span>
25
+ </div>
26
+ <div class="top-right">
27
+ <div class="legend">
28
+ <span class="grp-chosen"><i class="swatch"></i>Goal / chosen</span>
29
+ <span class="grp-rejected"><i class="swatch"></i>Rejected / not chosen</span>
30
+ <span class="grp-other"><i class="swatch"></i>Decision / loop / side</span>
31
+ </div>
32
+ <button id="theme" type="button" title="Switch colour theme"></button>
33
+ </div>
34
+ </header>
35
+
36
+ <aside id="sidebar"></aside>
37
+
38
+ <main id="viewport" data-view="timeline">
39
+ <section id="timeline">
40
+ <div id="tl-summary"></div>
41
+ <div id="tl-rows"></div>
42
+ </section>
43
+ <div id="stage">
44
+ <div id="world">
45
+ <svg id="edges"></svg>
46
+ <div id="nodes"></div>
47
+ <div id="labels"></div>
48
+ </div>
49
+ </div>
50
+ <div id="banner" hidden></div>
51
+ <div id="toast" hidden></div>
52
+ <nav id="bar">
53
+ <button type="button" data-set-view="timeline" class="active">Timeline</button>
54
+ <button type="button" data-set-view="graph">Graph</button>
55
+ <span class="sep"></span>
56
+ <button type="button" data-filter="all" class="active">All paths</button>
57
+ <button type="button" data-filter="chosen">Chosen path only</button>
58
+ <button type="button" data-filter="decisions">Decisions &amp; Rejections</button>
59
+ <span class="sep"></span>
60
+ <button id="follow" type="button" aria-pressed="true">Follow: on</button>
61
+ <button id="fit" type="button" class="graph-only">Fit</button>
62
+ <button id="reset" type="button" class="graph-only">100%</button>
63
+ </nav>
64
+ </main>
65
+
66
+ <aside id="panel"></aside>
67
+ </div>
68
+ <script type="module" src="./app.ts"></script>
69
+ </body>
70
+ </html>