@flowsilver/algoviz 0.0.0-stage → 0.4.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # AlgoViz
2
+
3
+ **AI-Native Algorithm Execution Inspector**
4
+ *A local runtime for replaying and inspecting recorded algorithm executions.*
5
+
6
+ ## Try the offline preview
7
+
8
+ Download the demo HTML from the [latest release](https://github.com/FlowSilver/AlgoViz/releases/latest) and open it in your browser. Step forward, step backward, or seek. Expand **State** to inspect the recorded values and use **Changes** to compare with the preceding recorded step.
9
+
10
+ To generate the [knapsack preview](examples/knapsack/README.md) from a checkout with Node.js 22 or later:
11
+
12
+ ```sh
13
+ npm ci
14
+ npm run algoviz -- validate examples/knapsack/visualization.json examples/knapsack/trace.jsonl
15
+ npm run algoviz -- preview examples/knapsack/visualization.json examples/knapsack/trace.jsonl
16
+ ```
17
+
18
+ Open the printed `file://` URL. The generated HTML embeds the trace, spec, and inspector for offline use. Pass `--output preview.html` to choose a new file path.
19
+
20
+ ## What ships today
21
+
22
+ - **Local validation and replay.** `validate` checks a JSON visualization spec and its JSONL execution trace. `preview` builds a self-contained inspector with synchronized views and timeline controls. [v1 protocol and replay API](docs/protocol.md)
23
+ - **Side-by-side replay.** `compare` aligns two traces by episode and step in one offline HTML file. The FrozenLake example uses a custom grid renderer to investigate two verified 10,000-transition runs. [Record and compare FrozenLake](examples/frozenlake/README.md#compare-the-runs)
24
+ - **Graph and Array views.** Graph edges support labels, and Array items can bind separate labels and values. The [BFS](examples/upstream-bfs/README.md) and [Dijkstra](examples/weighted-dijkstra/README.md) examples show graph state and frontier order. The [knapsack example](examples/knapsack/README.md#try-your-own-input) accepts a separate JSON input for capacity and items.
25
+ - **Step inspection.** State shows the selected frame as JSON. Changes shows before and after values at the paths that changed from the preceding recorded step.
26
+ - **Agent integration.** The [AlgoViz skill](.agents/skills/algoviz/SKILL.md) guides coding agents through choosing observation points, recording the trace, and verifying the result.
27
+
28
+ ## Positioning
29
+
30
+ **AlgoViz is an extensible algorithm execution inspector and visualization runtime designed for AI coding agents.**
31
+
32
+ A researcher or developer already has an algorithm and can simply ask their preferred coding agent:
33
+
34
+ > “Use AlgoViz to visualize my pathfinding algorithm. Show the search space, frontier queue, and cost evolution.”
35
+
36
+ The agent reads the existing algorithm, identifies meaningful internal states, and creates an adapter with minimal changes to the original implementation. The adapter records the run. AlgoViz validates and replays it with reusable renderers and inspection controls.
37
+
38
+ AlgoViz **does not need a built-in LLM** and is not intended to replace coding agents such as Codex or Claude Code.
39
+
40
+ ## Why not just ask AI to generate a webpage?
41
+
42
+ AlgoViz is designed for researchers and engineers who revisit algorithm runs and need reusable tooling for:
43
+
44
+ - Inspecting state and changes at a known step across synchronized views.
45
+ - Saving and sharing execution traces for offline replay.
46
+ - Reusing the timeline, renderers, and validator across algorithms.
47
+
48
+ The working hypothesis is that AI + AlgoViz reduces the effort to build and revise a reliable viewer. The [BFS pilot](benchmarks/README.md), [timed Dijkstra trial](benchmarks/dijkstra/README.md), and [FrozenLake comparison](benchmarks/frozenlake/README.md) report measurements.
49
+
50
+ ## Target users and use cases
51
+
52
+ The primary audience is algorithm researchers, software engineers, and teams that need repeated access to internal execution state, including:
53
+
54
+ - Graph search and path planning: expanded nodes, frontier queues, distances, and heuristic costs.
55
+ - Dynamic programming and optimization: state tables, iterative convergence, and objective values.
56
+ - Reinforcement learning and simulation: environment states, actions, rewards, and intermediate outcomes.
57
+ - Novel algorithms: AI-generated adapters without requiring the algorithm to fit a predefined category.
58
+
59
+ Educational sorting animations may be supported, but they are not the primary differentiator.
60
+
61
+ ## Adapt an algorithm
62
+
63
+ 1. The user asks an AI coding agent for a visualization in an existing repository.
64
+ 2. The agent inspects the algorithm and available state, then selects Graph, Array, or a locally registered custom renderer.
65
+ 3. The agent creates an **adapter** by reusing callbacks, logs, or iterators where possible and adding observation hooks where needed.
66
+ 4. The instrumented run produces an **Execution Trace**; the agent also generates a **Visualization Specification**.
67
+ 5. AlgoViz validates and loads both inputs, presenting an interactive execution inspector in the browser.
68
+ 6. The user saves or shares the trace and opens the offline HTML to inspect the run.
69
+
70
+ > Principle: visualization should not alter the original algorithm's behavior. If an algorithm exposes only its final result, missing internal steps cannot be reconstructed reliably without additional instrumentation.
71
+
72
+ ## Architecture overview
73
+
74
+ ```text
75
+ Existing algorithm (Python / C++ / Java / Rust / ...)
76
+ │
77
+ ▼
78
+ AI Coding Agent ── AlgoViz docs, schemas, CLI / Skill
79
+ │
80
+ ▼
81
+ Adapter / minimal instrumentation
82
+ │
83
+ ┌──────┴───────────┐
84
+ ▼ ▼
85
+ Execution Trace Visualization Specification
86
+ (states and events) (views, bindings, layout)
87
+ └──────┬───────────┘
88
+ ▼
89
+ AlgoViz Runtime
90
+ validate · reconstruct · replay · sync
91
+ │
92
+ ▼
93
+ Graph and Array views · State and Changes panels
94
+ │
95
+ ▼
96
+ Browser-based Algorithm Inspector
97
+ ```
98
+
99
+ ### Three core abstractions
100
+
101
+ - **State:** observable algorithm data at a particular step, modeled in a serializable way with stable identities.
102
+ - **View:** declarative mapping from recorded data to a Graph, Array, or registered custom component.
103
+ - **Transition:** state changes recorded in the trace, optionally augmented by semantic events for richer animation.
104
+
105
+ ### Two primary inputs
106
+
107
+ | Input | Responsibility |
108
+ | --- | --- |
109
+ | **Visualization Specification** | Describes views, data sources, visual encodings, and layout without hard-coding algorithm names. |
110
+ | **Execution Trace** | Records ordered state changes, optional semantic events, and metadata for deterministic replay. |
111
+
112
+ Generic state updates are the source of truth for reconstruction. Semantic events such as `node.visit` or `array.swap` may enhance animations, but must not create a conflicting second state model.
113
+
114
+ ## Roadmap
115
+
116
+ The [v0.4.0 milestone](https://github.com/FlowSilver/AlgoViz/milestone/4) tracks the FrozenLake comparison and npm publication. See the [development plan](OPEN_SOURCE_DEVELOPMENT.md#12-next-steps) and [open design questions](DECISIONS.md#open-design-questions) for what comes next.
117
+
118
+ ## Minimum viable product (v0.1.0)
119
+
120
+ The first release established deterministic replay, the Graph and Array views, and an end-to-end adaptation of an existing BFS implementation. [v0.1.0 release](https://github.com/FlowSilver/AlgoViz/releases/tag/v0.1.0) · [First release scope](DECISIONS.md#v010-release-scope)
121
+
122
+ ## What success looks like
123
+
124
+ The benchmark must be **asking AI to generate a standalone visualization directly**, not merely writing a frontend by hand. Measure time to first correct result, human interventions, correctness of displayed state, cost of adding views, value for comparing repeated runs, and performance on large traces.
125
+
126
+ **Key question: for complex algorithms and iterative investigation, does AlgoViz actually make visualization easier and more reliable than AI-generated standalone code?**
127
+
128
+ ## Non-goals for now
129
+
130
+ - Replacing AI coding agents or bundling a proprietary language model.
131
+ - Automatically inferring every internal execution step from arbitrary untouched source code.
132
+ - Providing a universal hosted compiler/runtime for all languages in the MVP.
133
+ - Turning the DSL into a full frontend programming language with loops, functions, and arbitrary scripting.
134
+
135
+ ## Contributing
136
+
137
+ Small algorithm examples with expected states and feedback on the [v1 protocol](docs/protocol.md) are welcome.
138
+
139
+ - [Contributing guide](CONTRIBUTING.md) for opening issues and submitting changes.
140
+ - [Design decisions](DECISIONS.md) and [development plan](OPEN_SOURCE_DEVELOPMENT.md) for the release scope and proposed backlog.
141
+ - [Code of conduct](CODE_OF_CONDUCT.md) and [security policy](SECURITY.md) for reporting concerns.
142
+
143
+ ## License
144
+
145
+ AlgoViz is licensed under the [Apache License 2.0](LICENSE).
146
+ The vendored algorithms retain their upstream MIT licenses. [BFS license](examples/upstream-bfs/LICENSE-upstream.md) · [Dijkstra license](benchmarks/dijkstra/LICENSE-upstream.md) · [Knapsack license](examples/knapsack/LICENSE-upstream.md)
2
147
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,95 @@
1
+ import { firstDifferentAction, indexRun } from "../../packages/core/comparison.js";
2
+ import { attachInspection } from "./inspection.js";
3
+ import { attachViews } from "./views.js";
4
+
5
+ function attachRun(container, input, run, renderers, index) {
6
+ const panel = document.getElementById("comparison-run").content.firstElementChild.cloneNode(true);
7
+ const id = run.replay.seek(0).state.run?.id ?? `${index === 0 ? "Left" : "Right"} · ${input.traceSource}`;
8
+ panel.dataset.run = String(id);
9
+ panel.querySelector("h2").textContent = String(id);
10
+ container.append(panel);
11
+
12
+ const status = panel.querySelector("[data-run-status]");
13
+ const content = panel.querySelector("[data-run-content]");
14
+ const renderViews = attachViews(panel.querySelector(".views"), input.specText, renderers, index, "h3");
15
+ const inspect = attachInspection(run.replay, panel);
16
+ return (episode, step) => {
17
+ const entry = run.episodes[episode];
18
+ const available = entry && step < entry.actions.length;
19
+ content.hidden = !available;
20
+ panel.dataset.available = String(Boolean(available));
21
+ if (!available) {
22
+ status.textContent = entry ? `Episode ended at step ${entry.actions.length - 1}` : "Episode unavailable";
23
+ return;
24
+ }
25
+ const frame = run.replay.seek(entry.start + step);
26
+ const { last, status: outcome } = frame.state;
27
+ renderViews(frame);
28
+ inspect(frame);
29
+ status.textContent = last?.action
30
+ ? [last.action, typeof last.reward === "number" && `Reward ${last.reward}`, outcome].filter(Boolean).join(" · ")
31
+ : step === 0 ? "Episode start" : `Trace step ${frame.step}`;
32
+ };
33
+ }
34
+
35
+ export function startComparison(inputs, renderers, { seek, previous, next, stepLabel, error, showError }) {
36
+ const runs = inputs.map(indexRun);
37
+ const container = document.getElementById("comparison");
38
+ const form = document.getElementById("episode-form");
39
+ const episodeField = document.getElementById("episode");
40
+ const difference = document.getElementById("first-difference");
41
+ const lastEpisode = Math.max(...runs.map((run) => run.episodes.length)) - 1;
42
+ const show = inputs.map((input, index) => attachRun(container, input, runs[index], renderers, index));
43
+ let episode = 0;
44
+ let step = 0;
45
+ let differenceStep;
46
+
47
+ document.getElementById("single-run").hidden = true;
48
+ document.getElementById("source").textContent = "Run comparison";
49
+ container.hidden = false;
50
+ form.hidden = false;
51
+ difference.hidden = false;
52
+ episodeField.max = String(lastEpisode);
53
+
54
+ function lastStep(value) {
55
+ return Math.max(...runs.map((run) => run.episodes[value]?.actions.length ?? 0)) - 1;
56
+ }
57
+
58
+ function select(nextEpisode, nextStep) {
59
+ try {
60
+ for (const update of show) update(nextEpisode, nextStep);
61
+ if (nextEpisode !== episode || differenceStep === undefined) {
62
+ differenceStep = firstDifferentAction(runs, nextEpisode);
63
+ }
64
+ episode = nextEpisode;
65
+ step = nextStep;
66
+ const max = lastStep(episode);
67
+ episodeField.value = String(episode);
68
+ seek.max = String(max);
69
+ seek.value = String(step);
70
+ seek.disabled = max === 0;
71
+ previous.disabled = episode === 0 && step === 0;
72
+ next.disabled = episode === lastEpisode && step === max;
73
+ difference.disabled = differenceStep === undefined;
74
+ stepLabel.value = `Episode ${episode} · Step ${step} of ${max}`;
75
+ error.hidden = true;
76
+ } catch (cause) {
77
+ episodeField.value = String(episode);
78
+ seek.value = String(step);
79
+ showError(cause);
80
+ }
81
+ }
82
+
83
+ form.addEventListener("submit", (event) => {
84
+ event.preventDefault();
85
+ const value = episodeField.valueAsNumber;
86
+ if (Number.isInteger(value) && value >= 0 && value <= lastEpisode) select(value, 0);
87
+ });
88
+ difference.addEventListener("click", () => select(episode, differenceStep));
89
+ seek.addEventListener("input", () => select(episode, seek.valueAsNumber));
90
+ previous.addEventListener("click", () => step === 0
91
+ ? select(episode - 1, lastStep(episode - 1)) : select(episode, step - 1));
92
+ next.addEventListener("click", () => step === lastStep(episode)
93
+ ? select(episode + 1, 0) : select(episode, step + 1));
94
+ select(0, 0);
95
+ }
@@ -0,0 +1,71 @@
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>AlgoViz</title>
7
+ <style>%STYLES%</style>
8
+ </head>
9
+ <body>
10
+ <main>
11
+ <header class="header">
12
+ <h1>AlgoViz</h1>
13
+ <span id="source"></span>
14
+ </header>
15
+ <div class="timeline" role="group" aria-label="Replay controls">
16
+ <form id="episode-form" class="episode-form" hidden>
17
+ <label>Episode <input id="episode" type="number" min="0" step="1" value="0" required></label>
18
+ <button type="submit">Go</button>
19
+ </form>
20
+ <div class="buttons">
21
+ <button type="button" id="previous" disabled>Previous</button>
22
+ <button type="button" id="next" disabled>Next</button>
23
+ </div>
24
+ <button type="button" id="first-difference" hidden disabled>First differing action</button>
25
+ <label class="seek" for="seek">
26
+ <span>Seek</span>
27
+ <input id="seek" type="range" min="0" max="0" value="0" disabled>
28
+ </label>
29
+ <output id="step" for="seek" aria-live="polite">Loading trace</output>
30
+ </div>
31
+ <p id="error" role="alert" hidden></p>
32
+ <div id="single-run">
33
+ <div id="views" class="views"></div>
34
+ <section class="inspection" aria-label="Step inspection">
35
+ <details id="state-panel" data-state-panel>
36
+ <summary>State</summary>
37
+ <pre id="state-json" data-state-json tabindex="0"></pre>
38
+ </details>
39
+ <details id="changes-panel" data-changes-panel open>
40
+ <summary>Changes</summary>
41
+ <div id="change-list" data-change-list></div>
42
+ </details>
43
+ </section>
44
+ </div>
45
+ <div id="comparison" hidden></div>
46
+ <template id="comparison-run">
47
+ <section class="comparison-run">
48
+ <header><h2></h2><p data-run-status></p></header>
49
+ <div data-run-content>
50
+ <div class="views"></div>
51
+ <section class="inspection" aria-label="Step inspection">
52
+ <details data-state-panel>
53
+ <summary>State</summary>
54
+ <pre data-state-json tabindex="0"></pre>
55
+ </details>
56
+ <details data-changes-panel open>
57
+ <summary>Changes</summary>
58
+ <div data-change-list></div>
59
+ </details>
60
+ </section>
61
+ </div>
62
+ </section>
63
+ </template>
64
+ </main>
65
+ <script type="application/json" id="preview-data">%DATA%</script>
66
+ <script>%SCRIPT%</script>
67
+ <!--
68
+ %LICENSES%
69
+ -->
70
+ </body>
71
+ </html>
@@ -0,0 +1,61 @@
1
+ import { loadReplay } from "../../packages/core/index.js";
2
+ import { startComparison } from "./comparison.js";
3
+ import { attachInspection } from "./inspection.js";
4
+ import { attachViews } from "./views.js";
5
+
6
+ const error = document.getElementById("error");
7
+ const stepLabel = document.getElementById("step");
8
+ const seek = document.getElementById("seek");
9
+ const previous = document.getElementById("previous");
10
+ const next = document.getElementById("next");
11
+
12
+ function showError(cause) {
13
+ error.textContent = cause.message;
14
+ error.hidden = false;
15
+ }
16
+
17
+ function startSingle(input, renderers) {
18
+ const replay = loadReplay(input.traceText, input);
19
+ const root = document.getElementById("single-run");
20
+ const inspect = attachInspection(replay, root);
21
+ const renderViews = attachViews(document.getElementById("views"), input.specText, renderers, 0);
22
+ document.getElementById("source").textContent = input.traceSource;
23
+ seek.max = String(replay.lastStep);
24
+ seek.disabled = replay.lastStep === 0;
25
+
26
+ function render(frame) {
27
+ const { step } = frame;
28
+ renderViews(frame);
29
+ inspect(frame);
30
+ stepLabel.value = `Step ${step} of ${replay.lastStep}`;
31
+ seek.value = String(step);
32
+ previous.disabled = step === 0;
33
+ next.disabled = step === replay.lastStep;
34
+ error.hidden = true;
35
+ }
36
+
37
+ function navigate(action) {
38
+ try {
39
+ render(action());
40
+ } catch (cause) {
41
+ seek.value = String(replay.current.step);
42
+ showError(cause);
43
+ }
44
+ }
45
+
46
+ previous.addEventListener("click", () => navigate(() => replay.stepBackward()));
47
+ next.addEventListener("click", () => navigate(() => replay.stepForward()));
48
+ seek.addEventListener("input", () => navigate(() => replay.seek(seek.valueAsNumber)));
49
+ render(replay.current);
50
+ }
51
+
52
+ export function start(renderers) {
53
+ try {
54
+ const { runs } = JSON.parse(document.getElementById("preview-data").textContent);
55
+ if (runs.length === 2) startComparison(runs, renderers, { seek, previous, next, stepLabel, error, showError });
56
+ else startSingle(runs[0], renderers);
57
+ } catch (cause) {
58
+ stepLabel.value = "Trace unavailable";
59
+ showError(cause);
60
+ }
61
+ }
@@ -0,0 +1,62 @@
1
+ function textElement(tag, text, className) {
2
+ const element = document.createElement(tag);
3
+ element.textContent = text;
4
+ if (className) element.className = className;
5
+ return element;
6
+ }
7
+
8
+ function changeValue(label, value, side) {
9
+ const field = document.createElement("div");
10
+ const content = value === undefined ? "Absent" : JSON.stringify(value, null, 2);
11
+ const block = textElement("pre", content, value === undefined ? "change-absent" : undefined);
12
+ block.dataset.changeSide = side;
13
+ field.append(textElement("span", label, "change-value-label"), block);
14
+ return field;
15
+ }
16
+
17
+ function renderChanges(changes, step) {
18
+ if (changes.length === 0) {
19
+ return textElement("p", step === 0 ? "Initial state" : "No state changes", "empty");
20
+ }
21
+
22
+ const list = document.createElement("ol");
23
+ list.className = "changes";
24
+ for (const change of changes) {
25
+ const row = document.createElement("li");
26
+ row.dataset.changePath = change.path;
27
+ row.dataset.changeKind = change.kind;
28
+ const heading = document.createElement("div");
29
+ heading.className = "change-heading";
30
+ heading.append(textElement("code", change.path), textElement("span", change.kind, "change-kind"));
31
+ const values = document.createElement("div");
32
+ values.className = "change-values";
33
+ values.append(changeValue("Before", change.before, "before"), changeValue("After", change.after, "after"));
34
+ row.append(heading, values);
35
+ list.append(row);
36
+ }
37
+ return list;
38
+ }
39
+
40
+ export function attachInspection(replay, root) {
41
+ const statePanel = root.querySelector("[data-state-panel]");
42
+ const changesPanel = root.querySelector("[data-changes-panel]");
43
+ const state = root.querySelector("[data-state-json]");
44
+ const changes = root.querySelector("[data-change-list]");
45
+ let frame;
46
+
47
+ function updateState() {
48
+ if (frame && statePanel.open) state.textContent = JSON.stringify(frame.state, null, 2);
49
+ }
50
+
51
+ function updateChanges() {
52
+ if (frame && changesPanel.open) changes.replaceChildren(renderChanges(replay.changes, frame.step));
53
+ }
54
+
55
+ statePanel.addEventListener("toggle", updateState);
56
+ changesPanel.addEventListener("toggle", updateChanges);
57
+ return (nextFrame) => {
58
+ frame = nextFrame;
59
+ updateState();
60
+ updateChanges();
61
+ };
62
+ }