Files
muSRFlow/tests/root-plot-clean.test.js
T
salman 8d38d54f52 Preserve JSROOT object prototypes when cloning cached canvases
The JSON deep-clone for clean/original/reset redraws stripped the JSROOT
prototype methods (TestBit et al.) that jsroot.draw depends on, breaking
renders with 'this[#pad].TestBit is not a function' even on desktop. Clone
now prefers JSROOT's own clone(), which keeps the object prototypes intact,
and only falls back to the JSON copy when clone() is unavailable.
2026-09-03 21:53:56 +02:00

415 lines
17 KiB
JavaScript

// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const repoRoot = path.resolve(__dirname, "..");
function loadRootLibrary() {
const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8");
const sandbox = {
console: console,
window: {},
document: {},
setTimeout: setTimeout,
clearTimeout: clearTimeout,
Promise: Promise,
Error: Error
};
sandbox.global = sandbox;
vm.runInNewContext(code, sandbox, { filename: "muSRFitRoot.js" });
return sandbox;
}
function testCleanLegendLabels() {
const lib = loadRootLibrary();
assert.strictEqual(
lib.cleanMusrfitRootLegendLabel("514,h:1/2,T=5.00K,B=100.00G,E=12.00keV,LEM"),
"T=5.00 K, B=100.00 G, E=12.00 keV"
);
assert.strictEqual(
lib.cleanMusrfitRootLegendLabel("515,h:1/2,T=??,B=25.00G,E=??,GPS"),
"B=25.00 G"
);
assert.strictEqual(
lib.cleanMusrfitRootLegendLabel("516,h:1/2,T0=4.20K,T1=4.35K,B=??,E=??,LEM"),
"T0=4.20 K, T1=4.35 K"
);
assert.strictEqual(
lib.cleanMusrfitRootLegendLabel("++517,h:1/2,T=??,B=??,E=??,GPS"),
"517"
);
}
function testCleanCanvasLayout() {
const lib = loadRootLibrary();
const title = {
_typename: "TPaveText",
fX1NDC: 0.0,
fY1NDC: 0.95,
fX2NDC: 1.0,
fY2NDC: 1.0,
fTextFont: 42,
fLines: {
arr: [{ _typename: "TText", fTextFont: 42 }]
}
};
const frame = {
_typename: "TH1F",
fXaxis: {
_typename: "TAxis",
fBits: 0,
fLabelFont: 42,
fTitleFont: 42,
fLabelSize: 0.03,
fTitleSize: 0.04
},
fYaxis: {
_typename: "TAxis",
fBits: 0,
fLabelFont: 42,
fTitleFont: 42,
fLabelSize: 0.03,
fTitleSize: 0.04
}
};
const dataPad = {
_typename: "TPad",
fName: "dataTheoryPad",
fXlowNDC: 0.0,
fYlowNDC: 0.1,
fWNDC: 0.75,
fHNDC: 0.85,
fAbsXlowNDC: 0.0,
fAbsYlowNDC: 0.1,
fAbsWNDC: 0.75,
fAbsHNDC: 0.85,
fPrimitives: {
arr: [frame]
}
};
const parameterPad = {
_typename: "TPaveText",
fX1NDC: 0.75,
fY1NDC: 0.5,
fX2NDC: 1.0,
fY2NDC: 0.95
};
const theoryPad = {
_typename: "TPaveText",
fX1NDC: 0.75,
fY1NDC: 0.1,
fX2NDC: 1.0,
fY2NDC: 0.5
};
const infoLegend = {
_typename: "TLegend",
fX1NDC: 0.0,
fY1NDC: 0.0,
fX2NDC: 1.0,
fY2NDC: 0.1,
fHeader: "musrfit: date, chisq = 1, NDF = 1",
fTextFont: 42,
fPrimitives: {
arr: [
{ _typename: "TLegendEntry", fLabel: "musrfit: date, chisq = 1", fOption: "h" },
{ _typename: "TLegendEntry", fLabel: "514,h:1/2,T=5.00K,B=100.00G,E=12.00keV,LEM", fOption: "p" },
{ _typename: "TLegendEntry", fLabel: "515,h:1/2,T=??,B=25.00G,E=??,GPS", fOption: "p" }
],
opt: ["", "p", "p"]
}
};
const canvas = {
_typename: "TCanvas",
fPrimitives: {
arr: [title, dataPad, parameterPad, theoryPad, infoLegend],
opt: ["", "", "", "", ""]
}
};
lib.cleanMusrfitRootCanvas(canvas);
assert.strictEqual(canvas.fPrimitives.arr.length, 3);
assert.strictEqual(canvas.fPrimitives.opt.length, 3);
assert.strictEqual(canvas.fPrimitives.arr[0], title);
assert.strictEqual(canvas.fPrimitives.arr[1], dataPad);
assert.strictEqual(canvas.fPrimitives.arr[2], infoLegend);
// Clean mode keeps the original width but uses the space freed by the
// removed bottom legend to stretch the data pad vertically.
assert.strictEqual(dataPad.fWNDC, 0.75);
assert.strictEqual(dataPad.fAbsWNDC, 0.75);
assert.strictEqual(dataPad.fYlowNDC, 0.0);
assert.strictEqual(dataPad.fHNDC, 0.95);
assert.strictEqual(dataPad.fAbsYlowNDC, 0.0);
assert.strictEqual(dataPad.fAbsHNDC, 0.95);
assert.strictEqual(infoLegend.fX1NDC, 0.76);
assert.strictEqual(infoLegend.fX2NDC, 0.99);
assert.strictEqual(infoLegend.fY2NDC, 0.92);
assert.ok(infoLegend.fY1NDC >= 0.11);
assert.strictEqual(infoLegend.fNColumns, 1);
assert.strictEqual(infoLegend.fTextSize, 0.028);
assert.strictEqual(infoLegend.fHeader, "");
assert.strictEqual(infoLegend.fPrimitives.arr.length, 4);
assert.strictEqual(infoLegend.fPrimitives.opt.length, 4);
assert.deepStrictEqual(
Array.from(infoLegend.fPrimitives.arr, function(entry) { return entry.fLabel; }),
["T=5.00 K", "B=100.00 G", "E=12.00 keV", "B=25.00 G"]
);
assert.deepStrictEqual(Array.from(infoLegend.fPrimitives.opt), ["p", "", "", "p"]);
assert.strictEqual(infoLegend.fPrimitives.arr[0].fOption, "p");
assert.strictEqual(infoLegend.fPrimitives.arr[1].fOption, "");
assert.strictEqual(infoLegend.fPrimitives.arr[2].fOption, "");
assert.strictEqual(infoLegend.fPrimitives.arr[3].fOption, "p");
// Clean mode uses a LaTeX-friendly serif font throughout the retained
// annotations and gives centered axis titles a clear size hierarchy.
assert.strictEqual(title.fTextFont, 132);
assert.strictEqual(title.fLines.arr[0].fTextFont, 132);
assert.strictEqual(infoLegend.fTextFont, 132);
[frame.fXaxis, frame.fYaxis].forEach(function(axis) {
assert.strictEqual(axis.fLabelFont, 132);
assert.strictEqual(axis.fTitleFont, 132);
assert.strictEqual(axis.fLabelSize, 0.034);
assert.strictEqual(axis.fTitleSize, 0.040);
assert.ok((axis.fBits & (1 << 12)) !== 0);
});
}
function testCrowdedLegendFallsBackAndShrinks() {
const lib = loadRootLibrary();
const legend = {
_typename: "TLegend",
fHeader: "musrfit: date",
fPrimitives: {
arr: [{ _typename: "TLegendEntry", fLabel: "musrfit: date", fOption: "h" }],
opt: [""]
}
};
for (let run = 0; run < 20; run++) {
legend.fPrimitives.arr.push({
_typename: "TLegendEntry",
fLabel: String(500 + run) + ",h:1/2,T=5.00K,B=100.00G,E=12.00keV,LEM",
fOption: "p"
});
legend.fPrimitives.opt.push("p");
}
lib.cleanMusrfitRootInfoLegend(legend);
lib.positionMusrfitRootInfoLegend(legend);
// Sixty separate T/B/E rows would exceed the side column, so crowded
// legends return to one metadata line per data set.
assert.strictEqual(legend.fPrimitives.arr.length, 20);
assert.strictEqual(
legend.fPrimitives.arr[0].fLabel,
"T=5.00 K, B=100.00 G, E=12.00 keV"
);
assert.strictEqual(legend.fY2NDC, 0.92);
assert.ok(Math.abs(legend.fY1NDC - 0.12) < 1e-12);
// The compact metadata line is also much wider than the side legend. The
// final font therefore has to satisfy both the vertical and horizontal
// constraints, not just the row-count constraint.
assert.ok(legend.fTextSize < 0.012);
const legendWidth = legend.fX2NDC - legend.fX1NDC;
const textWidth = legendWidth * 0.75 - 0.01;
const estimatedLabelWidth = legend.fPrimitives.arr[0].fLabel.length
* legend.fTextSize * 0.52;
assert.ok(estimatedLabelWidth <= textWidth + 1e-12);
}
function testCleanViewIsDefaultAndToggleExists() {
const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8");
assert.match(code, /viewMode = "clean"/);
assert.match(code, /let rootViewMode = "clean"/);
assert.match(code, /shortcut === "c"/);
assert.match(code, /rootViewMode === "clean" \? "original" : "clean"/);
// Hover details belong to the original ROOT view. Clean mode should keep
// the canvas interactive while disabling only JSROOT's verbose tooltip.
assert.match(code, /setTooltipAllowed\(viewMode !== "clean"\)/);
}
// The plot window must expose its commands on a touch screen, where the musrview
// keyboard shortcuts (f/c/u/q) are unreachable. A hamburger button on the title
// bar opens a dropdown of plot actions that invoke the same handlers.
function testTouchActionMenu() {
const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8");
// Hamburger button created and placed first in the title bar.
assert.match(code, /plotMenuButton.innerHTML = "&#9776;"/);
assert.match(code, /plotHeader\.appendChild\(plotMenuButton\)/);
// The dropdown exists and defaults to hidden; the hamburger toggles it.
assert.match(code, /let plotActionMenu = document\.createElement\("div"\)/);
assert.match(code, /plotActionMenu\.hidden = true/);
assert.match(code, /function toggleRootPlotActionMenu/);
// Each musrview shortcut is mirrored by a menu action wired to the shared
// handler: FFT (f), clean/original (c), reset (u).
assert.match(code, /rootPlotActionButton\("FFT"/);
assert.match(code, /"Clean \/ Original view"/);
assert.match(code, /"Reset view"/);
// FFT is only meaningful when the plot knows its source .msr, matching the
// keyboard guard on the "f" shortcut.
assert.match(code, /if \(plotContext\.msrPath\)\s*\{\s*\/\/[^]*?fftActionButton = rootPlotActionButton/);
assert.match(code, /shortcut === "f"/);
const css = fs.readFileSync(path.join(repoRoot, "ZGUI.css"), "utf8");
// Touch-friendly hit targets and a label that appears only on wider screens.
assert.match(css, /\.web-plot-menu-button/);
assert.match(css, /\.web-plot-action-menu/);
assert.match(css, /\.web-plot-action/);
assert.match(css, /min-height: 44px/);
// The action menu must not begin a window drag and must close on outside tap.
assert.match(code, /plotMenuButton\.contains\(event\.target\)/);
assert.match(code, /!plotActionMenu\.contains\(event\.target\)/);
}
// A ROOT pane can hang on "Loading ROOT canvas..." when JSROOT's openFile /
// readObject / draw never settles (e.g. a ranged fetch against a server that
// never answers). Every await is time-bound so the pane degrades to a visible
// error, and the error carries a Retry button for recovery.
function testLoadTimeout() {
const lib = loadRootLibrary();
// A promise that wins the race resolves through the wrapper unchanged.
return lib.withMusrfitRootTimeout(Promise.resolve(42), "step", "http://u/r.root")
.then(function(value) {
assert.strictEqual(value, 42, "resolved promise passes through");
})
.then(function() {
// A promise that never settles must reject with a TimeoutError that
// names the step and the URL so the stuck pane becomes diagnosable.
lib.window.MusrfitRootFetchTimeoutMs = 30;
return lib.withMusrfitRootTimeout(
new Promise(() => {}), "Opening ROOT file", "http://h/x.root");
})
.then(
() => Promise.reject(new Error("expected the stuck promise to time out")),
(error) => {
assert.strictEqual(error.name, "TimeoutError");
assert.match(String(error.message), /Opening ROOT file/);
assert.match(String(error.message), /http:\/\/h\/x\.root/);
}
);
}
// The three per-pane awaits are each wrapped with the deadline, and a failure
// renders an inline Retry button instead of a bare message.
function testLoadTimeoutSource() {
const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8");
assert.match(code, /withMusrfitRootTimeout\(\s*jsroot\.openFile/);
assert.match(code, /withMusrfitRootTimeout\(\s*file\.readObject/);
assert.match(code, /withMusrfitRootTimeout\(\s*jsroot\.draw/);
assert.match(code, /withMusrfitRootTimeout\(\s*loadMusrfitJSRoot\(\)/);
assert.match(code, /status\.appendChild\(retry\)/);
assert.match(code, /Could not load JSROOT:/);
const css = fs.readFileSync(path.join(repoRoot, "ZGUI.css"), "utf8");
assert.match(css, /\.web-root-retry/);
}
// Toggling clean/original starts a fresh render on the same container while the
// previous one may still be fetching/drawing. A generation token lets the stale
// render abort instead of drawing into a canvas that a newer render already
// removed, which previously surfaced as "Could not draw ..." on Firefox.
function testRenderGenerationGuard() {
const lib = loadRootLibrary();
const firstContainer = {};
const secondContainer = {};
// Each render advances the generation for its own container only.
assert.strictEqual(lib.beginMusrfitRootRender(firstContainer), 1);
assert.strictEqual(lib.beginMusrfitRootRender(firstContainer), 2);
assert.strictEqual(lib.beginMusrfitRootRender(secondContainer), 1);
// A canvas is stale after the container moves on (a newer render started)
// or once the canvas is detached from the document.
let detachedCanvas = {};
detachedCanvas.isConnected = false;
assert.ok(lib.musrfitRootRenderIsStale(firstContainer, 1, detachedCanvas));
assert.strictEqual(
lib.musrfitRootRenderIsStale(firstContainer, 2, { isConnected: true }),
false,
"current generation + attached canvas is not stale"
);
// An old render token against the current generation is stale.
assert.ok(lib.musrfitRootRenderIsStale(firstContainer, 1, { isConnected: true }));
// Every render path funnels through the tokenized entrypoint and checks
// staleness after each await so stale draws never paint a removed canvas.
const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8");
assert.match(code, /let renderToken = beginMusrfitRootRender\(container\)/);
assert.match(code, /musrfitRootRenderIsStale\(container, renderToken, canvas\)/);
assert.match(code, /musrfitRootRenderIsStale\(container, renderToken, container\)/);
}
// Clean/original/reset redraws reuse a decoded ROOT object instead of re-fetching
// the file each toggle, which is the slow, flaky path on mobile.
function testDecodeCache() {
const lib = loadRootLibrary();
// The cache key is stable despite the cache-busting query string on the URL.
assert.strictEqual(
lib.musrfitRootCacheKey({ url: "/tmp/job/run_0.root?musrflow_root=abc", item: "fMainCanvas0;1" }),
"/tmp/job/run_0.root|fMainCanvas0;1"
);
// The deep clone paints identically but is fully independent, so mutating the
// drawn copy never corrupts the cached pristine original.
const original = {
_typename: "TCanvas",
fName: "c" ,
fTitle: "run",
fPrimitives: {
arr: [ { _typename: "TPad", fName: "p", fX: [1, 2, 3] } ],
opt: [ "p" ]
}
};
const clone = lib.musrfitRootCloneCanvas(original);
assert.notStrictEqual(clone, original, "clone is a distinct object");
// Structural equality (JSON round-trip) avoids cross-realm prototype noise,
// since the vm sandbox builds its own Object.prototype.
assert.strictEqual(JSON.stringify(clone), JSON.stringify(original),
"clone matches the source tree");
clone.fPrimitives.arr[0].fName = "mutated";
assert.strictEqual(original.fPrimitives.arr[0].fName, "p",
"mutating the clone does not affect the source");
const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8");
// renderMusrfitRootPlots accepts a decode cache; clean view draws a clone of
// the cached pristine copy, preferring JSROOT's own clone to preserve the
// object prototypes jsroot.draw relies on (TestBit et al).
assert.match(code, /viewMode = "clean", decodeCache = null/);
assert.match(code, /drawObject = musrfitRootCloneCanvas\(cached, jsroot\)/);
assert.match(code, /decodeCache\.set\(cacheKey, fileObject\)/);
assert.match(code, /if \(jsroot && typeof jsroot\.clone === "function"\)/);
// Spectrum renders reuse the window cache; FFT renders never do.
assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, resetVersion, rootViewMode, rootDecodeCache\)/);
assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, fftVersion, rootViewMode\)/);
assert.match(code, /let rootDecodeCache = new Map\(\)/);
}
function runTests() {
testCleanLegendLabels();
testCleanCanvasLayout();
testCrowdedLegendFallsBackAndShrinks();
testCleanViewIsDefaultAndToggleExists();
testTouchActionMenu();
testLoadTimeoutSource();
testRenderGenerationGuard();
testDecodeCache();
testLoadTimeout();
console.log("ROOT clean-view tests passed.");
}
runTests();