viz: helper for keeping state in browser history (#10830)

This commit is contained in:
qazal 2025-06-16 12:26:10 +03:00 committed by GitHub
commit e8ec3f544b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -38,14 +38,7 @@ async function renderDag(graph, additions, recenter=false) {
const STROKE_WIDTH = 1.4;
const nodes = d3.select("#nodes").selectAll("g").data(g.nodes().map(id => g.node(id)), d => d).join("g")
.attr("transform", d => `translate(${d.x},${d.y})`).classed("clickable", d => d.ref != null)
.on("click", (_,d) => {
if (d.ref != null) {
// NOTE: browser does a structured clone, passing a mutable object is safe.
history.replaceState(state, "");
history.pushState(state, "");
setState({ expandSteps: true, currentCtx:d.ref, currentStep:0, currentRewrite:0 });
}
});
.on("click", (_,d) => setCtxWithHistory(d.ref));
nodes.selectAll("rect").data(d => [d]).join("rect").attr("width", d => d.width).attr("height", d => d.height).attr("fill", d => d.color)
.attr("x", d => -d.width/2).attr("y", d => -d.height/2).attr("style", d => d.style ?? `stroke:#4a4b57; stroke-width:${STROKE_WIDTH}px;`);
nodes.selectAll("g.label").data(d => [d]).join("g").attr("class", "label").attr("transform", d => {
@ -302,6 +295,16 @@ function setState(ns) {
// re-render
main();
}
// set a new context and keep the old one in browser history
function setCtxWithHistory(newCtx) {
if (newCtx == null) return;
// NOTE: browser does a structured clone, passing a mutable object is safe.
history.replaceState(state, "");
history.pushState(state, "");
setState({ expandSteps:true, currentCtx:newCtx, currentStep:0, currentRewrite:0 });
}
window.addEventListener("popstate", (e) => {
if (e.state != null) setState(e.state);
});