Remove 60 single-use helper functions by inlining their bodies at their sole call site, keeping top-level shared functions that are referenced by tests, window exports, IPC handlers, or HTML entry points.
1151 lines
45 KiB
JavaScript
1151 lines
45 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// JSROOT-backed floating plot windows for the muSRFlow web application.
|
|
// This file is intentionally browser-only. The Electron path keeps using the
|
|
// native musrview window for now.
|
|
|
|
if (typeof window.MusrfitJSRootURL === "undefined") {
|
|
window.MusrfitJSRootURL = "https://root.cern/js/latest/modules/main.mjs";
|
|
}
|
|
if (typeof window.MusrfitRootModulePromise === "undefined") {
|
|
window.MusrfitRootModulePromise = null;
|
|
}
|
|
|
|
let webRootPlotWindowSequence = 0;
|
|
|
|
// Load JSROOT only when a ROOT plot is actually opened. Keeping one shared
|
|
// promise avoids repeated module downloads when several floating windows exist.
|
|
function loadMusrfitJSRoot() {
|
|
if (!window.MusrfitRootModulePromise) {
|
|
window.MusrfitRootModulePromise = import(window.MusrfitJSRootURL);
|
|
}
|
|
return window.MusrfitRootModulePromise;
|
|
}
|
|
|
|
// musrview names each serialized ROOT canvas fMainCanvas<N>;1, where <N>
|
|
// follows the numbered output filename, e.g. run_0.root -> fMainCanvas0;1.
|
|
// Convert the CGI response into explicit {url, item} pairs. If the CGI did not
|
|
// return an item name, derive the usual musrview canvas name from the filename.
|
|
function normalizeMusrfitRootPlotSpecs(rootUrls, rootItems) {
|
|
let urls = Array.isArray(rootUrls) ? rootUrls : [];
|
|
let items = Array.isArray(rootItems) ? rootItems : [];
|
|
return urls.filter(function(rootUrl) {
|
|
return typeof rootUrl === "string" && rootUrl !== "";
|
|
}).map(function(rootUrl, index) {
|
|
let cleanUrl = String(rootUrl || "").split("?")[0];
|
|
let fileName = cleanUrl.substring(cleanUrl.lastIndexOf("/") + 1);
|
|
let match = fileName.match(/_(\d+)(?:_F)?\.root$/);
|
|
let defaultItem = match ? "fMainCanvas" + match[1] + ";1" : "fMainCanvas0;1";
|
|
return {
|
|
url: rootUrl,
|
|
item: items[index] || defaultItem
|
|
};
|
|
});
|
|
}
|
|
|
|
// Accept both the current multi-plot response and the older single-url shape.
|
|
// This keeps the browser side tolerant while CGI deployments are upgraded. The
|
|
// web platform adapter also consults this helper after rt_alias / msr2data
|
|
// requests, so it stays a shared top-level function.
|
|
function musrfitRootUrlsFromResponse(response) {
|
|
if (!response) {
|
|
return [];
|
|
}
|
|
if (Array.isArray(response.root_urls)) {
|
|
return response.root_urls.filter(function(rootUrl) {
|
|
return typeof rootUrl === "string" && rootUrl !== "";
|
|
});
|
|
}
|
|
if (typeof response.root_url === "string" && response.root_url !== "") {
|
|
return [response.root_url];
|
|
}
|
|
return [];
|
|
}
|
|
|
|
// Arrange minimized plot windows in compact columns at the top-right corner so
|
|
// they do not cover the status bar or drift off-screen after browser resizing.
|
|
function layoutMusrfitRootWindows() {
|
|
let minimizedWindows = document.querySelectorAll(
|
|
'.web-plot-window[data-plot-state="minimized"]'
|
|
);
|
|
let topPosition = 12;
|
|
let rightPosition = 12;
|
|
let columnWidth = 0;
|
|
let bottomLimit = Math.max(120, window.innerHeight - 56);
|
|
|
|
for (let windowIndex = 0; windowIndex < minimizedWindows.length; windowIndex++) {
|
|
let minimizedWindow = minimizedWindows[windowIndex];
|
|
if (topPosition + minimizedWindow.offsetHeight > bottomLimit && topPosition > 12) {
|
|
rightPosition += columnWidth + 8;
|
|
topPosition = 12;
|
|
columnWidth = 0;
|
|
}
|
|
minimizedWindow.style.left = "auto";
|
|
minimizedWindow.style.right = rightPosition + "px";
|
|
minimizedWindow.style.top = topPosition + "px";
|
|
topPosition += minimizedWindow.offsetHeight + 8;
|
|
columnWidth = Math.max(columnWidth, minimizedWindow.offsetWidth);
|
|
}
|
|
}
|
|
|
|
// Bind the global resize handler once even if this file is accidentally loaded
|
|
// more than once by a development page.
|
|
if (!window.MusrfitRootLayoutBound && typeof window.addEventListener === "function") {
|
|
window.addEventListener("resize", layoutMusrfitRootWindows);
|
|
window.MusrfitRootLayoutBound = true;
|
|
}
|
|
|
|
// Time-bound an async operation so a JA-root/JSROOT fetch that never settles
|
|
// degrades to a visible error instead of leaving "Loading ROOT canvas..." up
|
|
// forever on an empty pane. Returns the promise's value when it wins the race
|
|
// and throws a TimeoutError describing the step when the deadline passes.
|
|
// Overridable so tests (and deployments tuning latency) can set a short budget.
|
|
if (typeof window.MusrfitRootFetchTimeoutMs === "undefined") {
|
|
window.MusrfitRootFetchTimeoutMs = 60000;
|
|
}
|
|
|
|
function musrfitRootTimeoutMs() {
|
|
let configured = Number(window.MusrfitRootFetchTimeoutMs);
|
|
return Number.isFinite(configured) && configured > 0 ? configured : 60000;
|
|
}
|
|
|
|
function withMusrfitRootTimeout(promise, step, url) {
|
|
return new Promise(function(resolve, reject) {
|
|
let settled = false;
|
|
let timer = setTimeout(function() {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
let timeoutError = new Error(step + " timed out after "
|
|
+ Math.round(musrfitRootTimeoutMs() / 1000) + "s: " + url);
|
|
timeoutError.name = "TimeoutError";
|
|
reject(timeoutError);
|
|
}, musrfitRootTimeoutMs());
|
|
Promise.resolve(promise).then(function(value) {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
clearTimeout(timer);
|
|
resolve(value);
|
|
}, function(error) {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
clearTimeout(timer);
|
|
reject(error);
|
|
});
|
|
});
|
|
}
|
|
|
|
// JSROOT may expose a ROOT TList either directly as an array or via .arr.
|
|
function musrfitRootCollectionArray(collection) {
|
|
if (Array.isArray(collection)) {
|
|
return collection;
|
|
}
|
|
if (collection && Array.isArray(collection.arr)) {
|
|
return collection.arr;
|
|
}
|
|
return [];
|
|
}
|
|
|
|
// ROOT keeps an option array beside TList contents. When filtering primitives,
|
|
// keep both arrays aligned so JSROOT sees a valid collection afterwards.
|
|
function filterMusrfitRootCollection(collection, keepItem) {
|
|
let items = musrfitRootCollectionArray(collection);
|
|
if (!collection || !items.length) {
|
|
return [];
|
|
}
|
|
if (Array.isArray(collection)) {
|
|
let kept = items.filter(keepItem);
|
|
collection.splice(0, collection.length, ...kept);
|
|
return collection;
|
|
}
|
|
|
|
let options = Array.isArray(collection.opt) ? collection.opt : null;
|
|
let keptItems = [];
|
|
let keptOptions = [];
|
|
for (let index = 0; index < items.length; index++) {
|
|
if (!keepItem(items[index], index)) {
|
|
continue;
|
|
}
|
|
keptItems.push(items[index]);
|
|
if (options) {
|
|
keptOptions.push(options[index]);
|
|
}
|
|
}
|
|
collection.arr = keptItems;
|
|
if (options) {
|
|
collection.opt = keptOptions;
|
|
}
|
|
return keptItems;
|
|
}
|
|
|
|
// ROOT font 13 is a Times/FreeSerif family that blends well with LaTeX output.
|
|
// Precision 2 keeps the text scalable when the JSROOT window is resized.
|
|
const MUSRFIT_ROOT_LATEX_FONT = 132;
|
|
const MUSRFIT_ROOT_SCALE_FONT_SIZE = 0.034;
|
|
const MUSRFIT_ROOT_AXIS_LABEL_FONT_SIZE = 0.040;
|
|
const MUSRFIT_ROOT_LEGEND_FONT_SIZE = 0.028;
|
|
const MUSRFIT_ROOT_LEGEND_ROW_HEIGHT = 0.045;
|
|
const MUSRFIT_ROOT_LEGEND_PADDING = 0.04;
|
|
const MUSRFIT_ROOT_LEGEND_MAX_HEIGHT = 0.80;
|
|
|
|
// ROOT stores CenterTitle as bit 12 in TAxis::fBits. Setting it directly keeps
|
|
// the transformation independent of JSROOT painter internals.
|
|
const MUSRFIT_ROOT_CENTER_TITLE_BIT = 1 << 12;
|
|
|
|
// Axis-bearing ROOT objects can be nested inside pads or a multigraph frame.
|
|
// Walk only the small set of container fields used by musrview/JSROOT rather
|
|
// than traversing graph data arrays.
|
|
function styleMusrfitRootAxes(object, visited = new WeakSet()) {
|
|
if (!object || typeof object !== "object" || visited.has(object)) {
|
|
return;
|
|
}
|
|
visited.add(object);
|
|
|
|
["fXaxis", "fYaxis"].forEach(function(axisName) {
|
|
let axis = object[axisName];
|
|
if (!axis || typeof axis !== "object") {
|
|
return;
|
|
}
|
|
axis.fLabelFont = MUSRFIT_ROOT_LATEX_FONT;
|
|
axis.fTitleFont = MUSRFIT_ROOT_LATEX_FONT;
|
|
axis.fLabelSize = MUSRFIT_ROOT_SCALE_FONT_SIZE;
|
|
axis.fTitleSize = MUSRFIT_ROOT_AXIS_LABEL_FONT_SIZE;
|
|
axis.fBits = (Number.isFinite(axis.fBits) ? axis.fBits : 0)
|
|
| MUSRFIT_ROOT_CENTER_TITLE_BIT;
|
|
});
|
|
|
|
if (object.fHistogram) {
|
|
styleMusrfitRootAxes(object.fHistogram, visited);
|
|
}
|
|
musrfitRootCollectionArray(object.fPrimitives).forEach(function(child) {
|
|
styleMusrfitRootAxes(child, visited);
|
|
});
|
|
}
|
|
|
|
// Use the same serif font for the clean-view title, annotations and legend.
|
|
// Text sizes are otherwise left unchanged so only the requested axis hierarchy
|
|
// is altered.
|
|
function styleMusrfitRootTextFonts(object, visited = new WeakSet()) {
|
|
if (!object || typeof object !== "object" || visited.has(object)) {
|
|
return;
|
|
}
|
|
visited.add(object);
|
|
|
|
if (Object.prototype.hasOwnProperty.call(object, "fTextFont")) {
|
|
object.fTextFont = MUSRFIT_ROOT_LATEX_FONT;
|
|
}
|
|
musrfitRootCollectionArray(object.fPrimitives).forEach(function(child) {
|
|
styleMusrfitRootTextFonts(child, visited);
|
|
});
|
|
musrfitRootCollectionArray(object.fLines).forEach(function(child) {
|
|
styleMusrfitRootTextFonts(child, visited);
|
|
});
|
|
}
|
|
|
|
// Prefer normalized-device coordinates, with the plain ROOT coordinate as fallback.
|
|
function musrfitRootCoordinate(object, ndcName, fallbackName) {
|
|
if (object && Number.isFinite(object[ndcName])) {
|
|
return object[ndcName];
|
|
}
|
|
if (object && Number.isFinite(object[fallbackName])) {
|
|
return object[fallbackName];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// musrview writes labels as run,histograms,T=...,B=...,E=...,setup. Keep only
|
|
// physical metadata in the clean view. If none are available, retain the run
|
|
// identifier so multiple curves do not become anonymous.
|
|
function cleanMusrfitRootLegendLabels(label) {
|
|
let original = String(label || "");
|
|
let fields = original.split(",");
|
|
let metadata = [];
|
|
for (let fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
|
|
let field = fields[fieldIndex].trim();
|
|
let match = field.match(/^(T\d*|B|E)\s*=\s*(.+)$/i);
|
|
if (!match) {
|
|
continue;
|
|
}
|
|
let value = match[2].trim();
|
|
if (!value || value === "??") {
|
|
continue;
|
|
}
|
|
// Add a readable space between a numeric value and its physical unit.
|
|
let trimmedValue = String(value || "").trim();
|
|
let unitMatch = trimmedValue.match(
|
|
/^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(K|G|T|keV|meV|eV)$/i);
|
|
metadata.push(match[1] + "="
|
|
+ (unitMatch ? unitMatch[1] + " " + unitMatch[2] : trimmedValue));
|
|
}
|
|
if (metadata.length) {
|
|
return metadata;
|
|
}
|
|
|
|
let runName = fields.length ? fields[0].trim() : "";
|
|
return [runName.replace(/^\+\+/, "")];
|
|
}
|
|
|
|
// Keep the single-label helper for callers that only need a compact text form.
|
|
function cleanMusrfitRootLegendLabel(label) {
|
|
return cleanMusrfitRootLegendLabels(label).join(", ");
|
|
}
|
|
|
|
// Drop the fit-statistics header and reduce each run entry to T/B/E metadata.
|
|
// Use separate rows while they fit in the side legend so T, B and E have the
|
|
// same font size. If that would exceed the available height, fall back to one
|
|
// compact metadata line per data set; positionMusrfitRootInfoLegend() then
|
|
// reduces the font only if even those compact rows need more vertical space.
|
|
function cleanMusrfitRootInfoLegend(legend) {
|
|
if (!legend || !legend.fPrimitives) {
|
|
return;
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(legend, "fHeader")) {
|
|
legend.fHeader = "";
|
|
}
|
|
|
|
let collection = legend.fPrimitives;
|
|
let entries = musrfitRootCollectionArray(collection);
|
|
let options = !Array.isArray(collection) && Array.isArray(collection.opt)
|
|
? collection.opt : null;
|
|
let dataSets = [];
|
|
|
|
for (let entryIndex = 0; entryIndex < entries.length; entryIndex++) {
|
|
let entry = entries[entryIndex];
|
|
if (!entry) {
|
|
continue;
|
|
}
|
|
let option = String(entry.fOption || "").toLowerCase();
|
|
let label = String(entry.fLabel || "");
|
|
if (option === "h" || label.toLowerCase().indexOf("musrfit:") === 0) {
|
|
continue;
|
|
}
|
|
dataSets.push({
|
|
entry: entry,
|
|
option: options ? options[entryIndex] : null,
|
|
labels: cleanMusrfitRootLegendLabels(label)
|
|
});
|
|
}
|
|
|
|
let multiLineCount = dataSets.reduce(function(total, dataSet) {
|
|
return total + dataSet.labels.length;
|
|
}, 0);
|
|
let multiLineHeight = MUSRFIT_ROOT_LEGEND_ROW_HEIGHT * multiLineCount
|
|
+ MUSRFIT_ROOT_LEGEND_PADDING;
|
|
let compact = multiLineHeight >= MUSRFIT_ROOT_LEGEND_MAX_HEIGHT;
|
|
let cleanEntries = [];
|
|
let cleanOptions = [];
|
|
|
|
dataSets.forEach(function(dataSet) {
|
|
let labels = compact ? [dataSet.labels.join(", ")] : dataSet.labels;
|
|
labels.forEach(function(label, labelIndex) {
|
|
let cleanEntry = labelIndex === 0
|
|
? dataSet.entry : Object.assign({}, dataSet.entry);
|
|
cleanEntry.fLabel = label;
|
|
if (labelIndex > 0) {
|
|
// Continuation rows carry metadata only; the curve marker belongs
|
|
// to the first row of the data set.
|
|
cleanEntry.fOption = "";
|
|
if (Object.prototype.hasOwnProperty.call(cleanEntry, "fObject")) {
|
|
cleanEntry.fObject = null;
|
|
}
|
|
}
|
|
cleanEntries.push(cleanEntry);
|
|
if (options) {
|
|
cleanOptions.push(labelIndex === 0 ? dataSet.option : "");
|
|
}
|
|
});
|
|
});
|
|
|
|
if (Array.isArray(collection)) {
|
|
collection.splice(0, collection.length, ...cleanEntries);
|
|
} else {
|
|
collection.arr = cleanEntries;
|
|
if (options) {
|
|
collection.opt = cleanOptions;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Move the cleaned metadata legend into the right column vacated by the
|
|
// parameter/theory boxes. Keep the data pad geometry unchanged.
|
|
function positionMusrfitRootInfoLegend(legend) {
|
|
if (!legend) {
|
|
return;
|
|
}
|
|
|
|
let lineCount = Math.max(1, musrfitRootCollectionArray(legend.fPrimitives).length);
|
|
let y2 = 0.92;
|
|
let requiredHeight = MUSRFIT_ROOT_LEGEND_ROW_HEIGHT * lineCount
|
|
+ MUSRFIT_ROOT_LEGEND_PADDING;
|
|
let height = Math.min(MUSRFIT_ROOT_LEGEND_MAX_HEIGHT,
|
|
Math.max(0.12, requiredHeight));
|
|
|
|
legend.fX1NDC = 0.76;
|
|
legend.fX2NDC = 0.99;
|
|
legend.fY1NDC = Math.max(0.11, y2 - height);
|
|
legend.fY2NDC = y2;
|
|
|
|
// The original bottom legend may use several columns; the side legend
|
|
// should always remain a single column.
|
|
legend.fNColumns = 1;
|
|
|
|
// Keep the normal readable font while the rows and labels fit. Crowded
|
|
// legends first collapse T/B/E to one line per data set; that line can be
|
|
// substantially wider than the multiline form, so constrain the font by
|
|
// both the available height and the available legend width.
|
|
let rowSpace = Math.max(0.01, height - MUSRFIT_ROOT_LEGEND_PADDING);
|
|
let neededRowSpace = MUSRFIT_ROOT_LEGEND_ROW_HEIGHT * lineCount;
|
|
let heightScale = Math.min(1, rowSpace / neededRowSpace);
|
|
|
|
let legendWidth = Math.max(0.01, legend.fX2NDC - legend.fX1NDC);
|
|
let symbolMargin = Number.isFinite(legend.fMargin) ? legend.fMargin : 0.25;
|
|
symbolMargin = Math.max(0.0, Math.min(0.45, symbolMargin));
|
|
let textWidth = legendWidth * (1.0 - symbolMargin) - 0.01;
|
|
let longestLabel = musrfitRootCollectionArray(legend.fPrimitives).reduce(
|
|
function(longest, entry) {
|
|
let label = entry && entry.fLabel ? String(entry.fLabel) : "";
|
|
return Math.max(longest, label.length);
|
|
}, 0);
|
|
// Times-style legend text averages roughly half an em per character. This
|
|
// deliberately errs slightly on the conservative side so compact labels do
|
|
// not clip against the right edge of the legend.
|
|
let estimatedWidth = longestLabel * MUSRFIT_ROOT_LEGEND_FONT_SIZE * 0.52;
|
|
let widthScale = estimatedWidth > 0
|
|
? Math.min(1, Math.max(0.1, textWidth / estimatedWidth)) : 1;
|
|
|
|
legend.fTextSize = MUSRFIT_ROOT_LEGEND_FONT_SIZE
|
|
* Math.min(heightScale, widthScale);
|
|
}
|
|
|
|
// Apply a presentation-only cleanup to the deserialized musrview canvas. The
|
|
// ROOT file itself is never modified; toggling back simply rereads it.
|
|
function cleanMusrfitRootCanvas(canvasObject) {
|
|
if (!canvasObject || !canvasObject.fPrimitives) {
|
|
return canvasObject;
|
|
}
|
|
|
|
let primitives = musrfitRootCollectionArray(canvasObject.fPrimitives);
|
|
let dataPad = primitives.find(function(object) {
|
|
return object && object._typename === "TPad" && object.fName === "dataTheoryPad";
|
|
});
|
|
if (!dataPad) {
|
|
return canvasObject;
|
|
}
|
|
|
|
// Identify the full-width information legend at the bottom of the canvas.
|
|
let infoLegend = primitives.find(function(object) {
|
|
if (!object || object._typename !== "TLegend") {
|
|
return false;
|
|
}
|
|
let lx1 = musrfitRootCoordinate(object, "fX1NDC", "fX1");
|
|
let lx2 = musrfitRootCoordinate(object, "fX2NDC", "fX2");
|
|
let ly1 = musrfitRootCoordinate(object, "fY1NDC", "fY1");
|
|
let ly2 = musrfitRootCoordinate(object, "fY2NDC", "fY2");
|
|
return lx1 !== null && lx2 !== null && ly1 !== null && ly2 !== null
|
|
&& lx1 <= 0.05 && lx2 >= 0.95 && ly1 <= 0.05 && ly2 <= 0.2;
|
|
});
|
|
// Remove musrview's parameter/theory boxes: TPaveText objects in the right
|
|
// column of the canvas.
|
|
filterMusrfitRootCollection(canvasObject.fPrimitives, function(object) {
|
|
if (!object || object._typename !== "TPaveText") {
|
|
return true;
|
|
}
|
|
let rx1 = musrfitRootCoordinate(object, "fX1NDC", "fX1");
|
|
let rx2 = musrfitRootCoordinate(object, "fX2NDC", "fX2");
|
|
let ry1 = musrfitRootCoordinate(object, "fY1NDC", "fY1");
|
|
let ry2 = musrfitRootCoordinate(object, "fY2NDC", "fY2");
|
|
return !(rx1 !== null && rx2 !== null && ry1 !== null && ry2 !== null
|
|
&& rx1 >= 0.6 && rx2 >= 0.95 && ry1 >= 0.05 && ry2 <= 0.96);
|
|
});
|
|
cleanMusrfitRootInfoLegend(infoLegend);
|
|
positionMusrfitRootInfoLegend(infoLegend);
|
|
// The bottom information strip is removed in clean mode, so use that space
|
|
// for the data pad. Preserve its right edge and top edge.
|
|
if (Number.isFinite(dataPad.fYlowNDC) && Number.isFinite(dataPad.fHNDC)) {
|
|
dataPad.fHNDC += dataPad.fYlowNDC;
|
|
dataPad.fYlowNDC = 0.0;
|
|
}
|
|
if (Number.isFinite(dataPad.fAbsYlowNDC) && Number.isFinite(dataPad.fAbsHNDC)) {
|
|
dataPad.fAbsHNDC += dataPad.fAbsYlowNDC;
|
|
dataPad.fAbsYlowNDC = 0.0;
|
|
}
|
|
styleMusrfitRootAxes(dataPad);
|
|
styleMusrfitRootTextFonts(canvasObject);
|
|
return canvasObject;
|
|
}
|
|
|
|
|
|
// Each redraw replaces canvas elements. Disconnect observers attached to the old
|
|
// canvases first to avoid callbacks after a plot window is closed or reset.
|
|
function disconnectMusrfitRootResizeObservers(container) {
|
|
if (!container || !container.querySelectorAll) {
|
|
return;
|
|
}
|
|
container.querySelectorAll(".web-root-canvas").forEach(function(canvas) {
|
|
if (canvas.__musrfitRootResizeObserver) {
|
|
canvas.__musrfitRootResizeObserver.disconnect();
|
|
canvas.__musrfitRootResizeObserver = null;
|
|
}
|
|
});
|
|
}
|
|
|
|
// Renders are asynchronous (fetch + decode + draw). Rapid toggling of the
|
|
// clean/original view can start several renders on the same container at once;
|
|
// the newest render's replaceChildren() detaches the canvases the older in-flight
|
|
// renders are still drawing into. Guard each container with a generation token so
|
|
// a stale draw aborts instead of throwing "Could not draw ..." on a removed node.
|
|
var musrfitRootContainerGeneration = new WeakMap();
|
|
|
|
// Return a token that strictly increases for every new render on `container`.
|
|
function beginMusrfitRootRender(container) {
|
|
let generation = musrfitRootContainerGeneration.get(container) || 0;
|
|
generation += 1;
|
|
musrfitRootContainerGeneration.set(container, generation);
|
|
return generation;
|
|
}
|
|
|
|
// A render is stale when a newer render replaced it, or when the specific canvas
|
|
// this draw targets has been detached from the document (e.g. window closed).
|
|
function musrfitRootRenderIsStale(container, generation, canvas) {
|
|
if (musrfitRootContainerGeneration.get(container) !== generation) {
|
|
return true;
|
|
}
|
|
return !canvas || !canvas.isConnected;
|
|
}
|
|
|
|
// A decoded musrview canvas is a JSROOT tree; the individual objects carry
|
|
// prototype methods (e.g. TestBit) that jsroot.draw relies on. Reusing the
|
|
// decoded object across clean/original/reset redraws avoids a network
|
|
// round-trip per toggle, the slow and flaky path on mobile. Every render draws
|
|
// its own clone so the clean-view mutation never corrupts the cached pristine
|
|
// copy. Only JSROOT's own clone preserves the object prototypes; JSON cloning
|
|
// is a degraded fallback for environments without it.
|
|
function musrfitRootCloneCanvas(canvasObject, jsroot) {
|
|
if (canvasObject && typeof canvasObject !== "object") {
|
|
return canvasObject;
|
|
}
|
|
if (jsroot && typeof jsroot.clone === "function") {
|
|
try {
|
|
return jsroot.clone(canvasObject);
|
|
} catch (error) {
|
|
// fall through to the structural copy
|
|
}
|
|
}
|
|
try {
|
|
return JSON.parse(JSON.stringify(canvasObject));
|
|
} catch (error) {
|
|
return canvasObject;
|
|
}
|
|
}
|
|
|
|
// Stable per-plot cache key independent of the cache-busting query string, so a
|
|
// clean/original/reset redraw hits the same entry across render versions.
|
|
function musrfitRootCacheKey(plotSpec) {
|
|
let url = String(plotSpec && plotSpec.url || "").split("?")[0];
|
|
return url + "|" + String(plotSpec && plotSpec.item || "");
|
|
}
|
|
|
|
// JSROOT does not automatically know that our floating dialog was resized by
|
|
// CSS or by the user, so explicitly notify it when the canvas has real geometry.
|
|
function resizeMusrfitRootCanvas(jsroot, canvas) {
|
|
if (!jsroot || typeof jsroot.resize !== "function" || !canvas || !canvas.id) {
|
|
return;
|
|
}
|
|
let bounds = canvas.getBoundingClientRect();
|
|
if (bounds.width <= 0 || bounds.height <= 0) {
|
|
return;
|
|
}
|
|
jsroot.resize(canvas.id);
|
|
}
|
|
|
|
// Keep the ROOT canvas fitted to the floating window. requestAnimationFrame
|
|
// coalesces rapid resize events while the user drags the dialog edge.
|
|
function installMusrfitRootResizeObserver(jsroot, canvas) {
|
|
if (typeof ResizeObserver !== "function" || !jsroot
|
|
|| typeof jsroot.resize !== "function" || !canvas) {
|
|
return;
|
|
}
|
|
|
|
let resizeFrame = 0;
|
|
let observer = new ResizeObserver(function() {
|
|
if (resizeFrame) {
|
|
return;
|
|
}
|
|
resizeFrame = window.requestAnimationFrame(function() {
|
|
resizeFrame = 0;
|
|
if (document.body.contains(canvas)) {
|
|
resizeMusrfitRootCanvas(jsroot, canvas);
|
|
}
|
|
});
|
|
});
|
|
observer.observe(canvas);
|
|
canvas.__musrfitRootResizeObserver = observer;
|
|
}
|
|
|
|
// Draw all ROOT canvases returned by musrview. Each PLOT block becomes one pane;
|
|
// errors are shown beside the affected pane rather than failing the whole window.
|
|
async function renderMusrfitRootPlots(container, plotSpecs, renderVersion, viewMode = "clean", decodeCache = null) {
|
|
let renderToken = beginMusrfitRootRender(container);
|
|
disconnectMusrfitRootResizeObservers(container);
|
|
container.replaceChildren();
|
|
if (!plotSpecs.length) {
|
|
let message = document.createElement("div");
|
|
message.className = "web-root-message";
|
|
message.textContent = "No ROOT plot files were returned.";
|
|
container.appendChild(message);
|
|
return;
|
|
}
|
|
|
|
let jsroot = null;
|
|
try {
|
|
jsroot = await withMusrfitRootTimeout(
|
|
loadMusrfitJSRoot(), "Loading JSROOT", window.MusrfitJSRootURL);
|
|
} catch (error) {
|
|
let message = document.createElement("div");
|
|
message.className = "web-root-message web-root-error";
|
|
message.textContent = "Could not load JSROOT: "
|
|
+ (error && error.message ? error.message : String(error));
|
|
container.appendChild(message);
|
|
return;
|
|
}
|
|
if (musrfitRootRenderIsStale(container, renderToken, container)) {
|
|
return;
|
|
}
|
|
|
|
for (let plotIndex = 0; plotIndex < plotSpecs.length; plotIndex++) {
|
|
let plotSpec = plotSpecs[plotIndex];
|
|
let pane = document.createElement("section");
|
|
let canvas = document.createElement("div");
|
|
let status = document.createElement("div");
|
|
let canvasId = "musrfitRootCanvas" + renderVersion + "_" + plotIndex;
|
|
|
|
pane.className = "web-root-plot-pane";
|
|
canvas.className = "web-root-canvas";
|
|
canvas.id = canvasId;
|
|
status.className = "web-root-message";
|
|
status.textContent = "Loading ROOT canvas...";
|
|
|
|
pane.appendChild(canvas);
|
|
pane.appendChild(status);
|
|
container.appendChild(pane);
|
|
|
|
try {
|
|
// musrview reuses predictable filenames inside the same job directory;
|
|
// add a harmless query parameter so redraw/reset requests never show a
|
|
// stale canvas.
|
|
let file = await withMusrfitRootTimeout(
|
|
jsroot.openFile(plotSpec.url
|
|
+ (plotSpec.url.indexOf("?") === -1 ? "?" : "&")
|
|
+ "musrflow_root=" + encodeURIComponent(renderVersion)),
|
|
"Opening ROOT file", plotSpec.url);
|
|
if (musrfitRootRenderIsStale(container, renderToken, canvas)) {
|
|
return;
|
|
}
|
|
|
|
// Reuse a previously decoded canvas for clean/original/reset redraws
|
|
// instead of re-fetching the ROOT file over the network on every toggle.
|
|
// The cached copy is always pristine; each render draws its own clone so
|
|
// clean-view mutation never leaks back into the cache (or the original).
|
|
let cacheKey = decodeCache ? musrfitRootCacheKey(plotSpec) : "";
|
|
let drawObject;
|
|
if (decodeCache) {
|
|
let cached = decodeCache.get(cacheKey);
|
|
if (cached) {
|
|
drawObject = musrfitRootCloneCanvas(cached, jsroot);
|
|
} else {
|
|
let fileObject = await withMusrfitRootTimeout(
|
|
file.readObject(plotSpec.item),
|
|
"Decoding object " + plotSpec.item, plotSpec.url);
|
|
if (musrfitRootRenderIsStale(container, renderToken, canvas)) {
|
|
return;
|
|
}
|
|
drawObject = musrfitRootCloneCanvas(fileObject, jsroot);
|
|
decodeCache.set(cacheKey, fileObject);
|
|
}
|
|
} else {
|
|
drawObject = await withMusrfitRootTimeout(
|
|
file.readObject(plotSpec.item),
|
|
"Decoding object " + plotSpec.item, plotSpec.url);
|
|
if (musrfitRootRenderIsStale(container, renderToken, canvas)) {
|
|
return;
|
|
}
|
|
drawObject = musrfitRootCloneCanvas(drawObject, jsroot);
|
|
}
|
|
|
|
if (viewMode === "clean") {
|
|
cleanMusrfitRootCanvas(drawObject);
|
|
}
|
|
let painter = await withMusrfitRootTimeout(
|
|
jsroot.draw(canvasId, drawObject, ""),
|
|
"Drawing ROOT canvas", plotSpec.url);
|
|
if (musrfitRootRenderIsStale(container, renderToken, canvas)) {
|
|
return;
|
|
}
|
|
|
|
// The normal JSROOT point tooltip contains file/object details and can
|
|
// obscure a large fraction of a multi-run plot. Clean view suppresses
|
|
// it; switching back with `c` restores the original ROOT behaviour.
|
|
if (painter && typeof painter.setTooltipAllowed === "function") {
|
|
painter.setTooltipAllowed(viewMode !== "clean");
|
|
}
|
|
|
|
installMusrfitRootResizeObserver(jsroot, canvas);
|
|
resizeMusrfitRootCanvas(jsroot, canvas);
|
|
status.remove();
|
|
} catch (error) {
|
|
if (musrfitRootRenderIsStale(container, renderToken, canvas)) {
|
|
return;
|
|
}
|
|
status.className = "web-root-message web-root-error";
|
|
status.textContent = "Could not draw " + plotSpec.item + ": "
|
|
+ (error && error.message ? error.message : String(error));
|
|
let retry = document.createElement("button");
|
|
retry.type = "button";
|
|
retry.className = "web-root-retry";
|
|
retry.textContent = "Retry";
|
|
retry.title = "Try loading " + plotSpec.url + " again";
|
|
status.appendChild(document.createTextNode(" "));
|
|
status.appendChild(retry);
|
|
retry.addEventListener("click", function() {
|
|
renderMusrfitRootPlots(container, plotSpecs, renderVersion, viewMode);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Create a non-modal floating JSROOT window for web plots. Electron deliberately
|
|
// keeps using the native musrview window and does not call this function.
|
|
function showWebRootPlotWindow(rootUrls, jobName = "", plotContext = {}) {
|
|
let plotSpecs = normalizeMusrfitRootPlotSpecs(rootUrls, plotContext.rootItems || []);
|
|
if (!plotSpecs.length) {
|
|
return;
|
|
}
|
|
|
|
webRootPlotWindowSequence++;
|
|
|
|
let plotWindow = document.createElement("dialog");
|
|
let plotHeader = document.createElement("div");
|
|
let plotMenuButton = document.createElement("button");
|
|
let plotActionMenu = document.createElement("div");
|
|
let plotDragHandle = document.createElement("div");
|
|
let plotControls = document.createElement("div");
|
|
let minimizeButton = document.createElement("button");
|
|
let maximizeButton = document.createElement("button");
|
|
let closeButton = document.createElement("button");
|
|
let plotContainer = document.createElement("div");
|
|
|
|
plotWindow.className = "web-plot-window web-root-window";
|
|
plotWindow.dataset.plotMode = "spectrum";
|
|
plotWindow.dataset.plotState = "normal";
|
|
plotWindow.setAttribute("aria-label", jobName ? "Plot: " + jobName : "musrview ROOT plot");
|
|
plotWindow.setAttribute("aria-modal", "false");
|
|
plotWindow.tabIndex = -1;
|
|
plotHeader.className = "web-plot-header web-root-plot-header";
|
|
plotMenuButton.type = "button";
|
|
plotMenuButton.className = "web-plot-menu-button";
|
|
plotMenuButton.innerHTML = "☰";
|
|
plotMenuButton.title = "Plot actions";
|
|
plotMenuButton.setAttribute("aria-label", "Plot actions");
|
|
plotMenuButton.setAttribute("aria-haspopup", "menu");
|
|
plotMenuButton.setAttribute("aria-expanded", "false");
|
|
plotActionMenu.className = "web-plot-action-menu";
|
|
plotActionMenu.setAttribute("role", "menu");
|
|
plotActionMenu.hidden = true;
|
|
plotDragHandle.className = "web-plot-drag-handle";
|
|
plotControls.className = "web-plot-controls";
|
|
minimizeButton.type = "button";
|
|
minimizeButton.innerHTML = "−";
|
|
minimizeButton.title = "Minimize plot";
|
|
minimizeButton.setAttribute("aria-label", "Minimize plot");
|
|
maximizeButton.type = "button";
|
|
maximizeButton.innerHTML = "□";
|
|
maximizeButton.title = "Maximize plot";
|
|
maximizeButton.setAttribute("aria-label", "Maximize plot");
|
|
closeButton.type = "button";
|
|
closeButton.innerHTML = "×";
|
|
closeButton.title = "Close plot";
|
|
closeButton.setAttribute("aria-label", "Close plot");
|
|
plotContainer.className = "web-root-plots";
|
|
|
|
plotControls.appendChild(minimizeButton);
|
|
plotControls.appendChild(maximizeButton);
|
|
plotControls.appendChild(closeButton);
|
|
plotHeader.appendChild(plotMenuButton);
|
|
plotHeader.appendChild(plotActionMenu);
|
|
plotHeader.appendChild(plotDragHandle);
|
|
plotHeader.appendChild(plotControls);
|
|
plotWindow.appendChild(plotHeader);
|
|
plotWindow.appendChild(plotContainer);
|
|
|
|
let spectrumSpecs = plotSpecs.slice();
|
|
let currentSpecs = spectrumSpecs.slice();
|
|
let renderVersion = Date.now().toString(36) + "-" + webRootPlotWindowSequence;
|
|
let fftInProgress = false;
|
|
let rootViewMode = "clean";
|
|
plotWindow.dataset.plotView = rootViewMode;
|
|
// Reused across spectrum redraws so clean/original/reset never re-fetch the
|
|
// ROOT file; FFT renders pass no cache and always decode their fresh file.
|
|
let rootDecodeCache = new Map();
|
|
|
|
// Redrawing the same ROOT object is the most robust unzoom/reset operation:
|
|
// it avoids depending on JSROOT painter internals while preserving the file.
|
|
function rerenderCurrentRootPlots(statusMessage) {
|
|
if (!currentSpecs.length) {
|
|
return;
|
|
}
|
|
let resetVersion = Date.now().toString(36) + "-reset-" + webRootPlotWindowSequence;
|
|
renderMusrfitRootPlots(plotContainer, currentSpecs, resetVersion, rootViewMode, rootDecodeCache);
|
|
if (statusMessage && typeof updateJobStatus === "function") {
|
|
updateJobStatus({ message: statusMessage });
|
|
}
|
|
}
|
|
|
|
// The FFT view is generated by musrview on the server, not by JSROOT in the
|
|
// browser. The floating window simply swaps to the newly returned ROOT file.
|
|
async function toggleMusrfitRootFFT() {
|
|
if (!plotContext.msrPath || fftInProgress) {
|
|
return;
|
|
}
|
|
|
|
if (plotWindow.dataset.plotMode === "fft") {
|
|
let restoreVersion = Date.now().toString(36) + "-restore-" + webRootPlotWindowSequence;
|
|
currentSpecs = spectrumSpecs.slice();
|
|
renderMusrfitRootPlots(plotContainer, currentSpecs, restoreVersion, rootViewMode, rootDecodeCache);
|
|
plotWindow.dataset.plotMode = "spectrum";
|
|
if (typeof updateJobStatus === "function") {
|
|
updateJobStatus({
|
|
message: "Original ROOT plot restored",
|
|
plotPath: spectrumSpecs[0].url
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (typeof postToMusrfitCGI !== "function") {
|
|
return;
|
|
}
|
|
|
|
fftInProgress = true;
|
|
if (typeof updateJobStatus === "function") {
|
|
updateJobStatus({
|
|
state: "Running musrview FFT",
|
|
message: "Generating FFT ROOT plot",
|
|
finishedAt: "",
|
|
exitCode: ""
|
|
});
|
|
}
|
|
|
|
let request = await postToMusrfitCGI({
|
|
action: "run",
|
|
fn: plotContext.msrPath,
|
|
use_msr2data: 0,
|
|
runs: plotContext.runs || "",
|
|
template_name: "",
|
|
base_run: "",
|
|
fftv: "y",
|
|
plot_only: 1,
|
|
plot_refresh: 1
|
|
});
|
|
let response = request.payload;
|
|
let fftUrls = musrfitRootUrlsFromResponse(response);
|
|
let fftSpecs = normalizeMusrfitRootPlotSpecs(fftUrls,
|
|
response && Array.isArray(response.root_items) ? response.root_items : []);
|
|
|
|
if (response && response.command_log && typeof appendJobLog === "function") {
|
|
appendJobLog(response.command_log.trim());
|
|
}
|
|
|
|
if (!request.ok || !response || !response.ok || !fftSpecs.length) {
|
|
let errorMessage = request.error || (response ? response.message : "FFT request failed");
|
|
if (response && response.stderr) {
|
|
errorMessage += "\n" + response.stderr.trim();
|
|
}
|
|
if (typeof finishJobStatus === "function") {
|
|
finishJobStatus(0, response && response.code !== undefined ? response.code : 1,
|
|
errorMessage);
|
|
}
|
|
fftInProgress = false;
|
|
return;
|
|
}
|
|
|
|
let fftVersion = Date.now().toString(36) + "-fft-" + webRootPlotWindowSequence;
|
|
currentSpecs = fftSpecs.slice();
|
|
renderMusrfitRootPlots(plotContainer, currentSpecs, fftVersion, rootViewMode);
|
|
plotWindow.dataset.plotMode = "fft";
|
|
if (typeof updateJobStatus === "function") {
|
|
updateJobStatus({ plotPath: fftSpecs[0].url });
|
|
}
|
|
if (typeof finishJobStatus === "function") {
|
|
finishJobStatus(1, response.code !== undefined ? response.code : 0,
|
|
response.message || "FFT ROOT plot completed");
|
|
}
|
|
fftInProgress = false;
|
|
}
|
|
|
|
renderMusrfitRootPlots(plotContainer, spectrumSpecs, renderVersion, rootViewMode, rootDecodeCache);
|
|
|
|
// Build one action, e.g. a menu button, for a plot action. Toggle/stateful
|
|
// actions report their current result through updateJobStatus.
|
|
function rootPlotActionButton(label, title, onClick) {
|
|
let button = document.createElement("button");
|
|
button.type = "button";
|
|
button.className = "web-plot-action";
|
|
button.textContent = label;
|
|
button.setAttribute("role", "menuitem");
|
|
button.tabIndex = -1;
|
|
if (title) {
|
|
button.title = title;
|
|
}
|
|
button.addEventListener("click", function() {
|
|
plotActionMenu.hidden = true;
|
|
plotMenuButton.setAttribute("aria-expanded", "false");
|
|
onClick();
|
|
});
|
|
return button;
|
|
}
|
|
|
|
let fftActionButton = null;
|
|
if (plotContext.msrPath) {
|
|
// FFT is server-side musrview work, so it is only offered when the plot
|
|
// knows the .msr behind it.
|
|
fftActionButton = rootPlotActionButton("FFT", "Toggle Fourier power spectrum", function() {
|
|
toggleMusrfitRootFFT();
|
|
});
|
|
plotActionMenu.appendChild(fftActionButton);
|
|
}
|
|
plotActionMenu.appendChild(rootPlotActionButton(
|
|
"Clean / Original view",
|
|
"alternate between the compact clean view and the full ROOT view",
|
|
function() {
|
|
rootViewMode = rootViewMode === "clean" ? "original" : "clean";
|
|
plotWindow.dataset.plotView = rootViewMode;
|
|
rerenderCurrentRootPlots(rootViewMode === "clean"
|
|
? "Clean ROOT plot view" : "Original ROOT plot view");
|
|
}
|
|
));
|
|
plotActionMenu.appendChild(rootPlotActionButton(
|
|
"Reset view",
|
|
"redraw the current plot to undo pan and zoom",
|
|
function() {
|
|
rerenderCurrentRootPlots("ROOT plot view reset");
|
|
}
|
|
));
|
|
|
|
function toggleRootPlotActionMenu(forceOpen) {
|
|
let open = forceOpen !== undefined ? Boolean(forceOpen) : plotActionMenu.hidden;
|
|
plotActionMenu.hidden = !open;
|
|
plotMenuButton.setAttribute("aria-expanded", open ? "true" : "false");
|
|
}
|
|
|
|
plotMenuButton.addEventListener("click", function(event) {
|
|
event.stopPropagation();
|
|
toggleRootPlotActionMenu();
|
|
});
|
|
|
|
// Close the action menu when interacting anywhere else in the window.
|
|
plotWindow.addEventListener("pointerdown", function(event) {
|
|
if (!plotActionMenu.hidden
|
|
&& event.target !== plotMenuButton
|
|
&& !plotActionMenu.contains(event.target)) {
|
|
toggleRootPlotActionMenu(false);
|
|
}
|
|
});
|
|
|
|
// Minimal musrview-like shortcuts for the focused ROOT plot window.
|
|
plotWindow.addEventListener("keydown", function(event) {
|
|
// Plot shortcuts should not steal keystrokes from inputs, selects, or
|
|
// editable regions that may appear in future plot controls.
|
|
let target = event.target;
|
|
let targetTagName = target && target.tagName ? target.tagName.toLowerCase() : "";
|
|
let editableTarget = target && (target.isContentEditable
|
|
|| targetTagName === "input" || targetTagName === "textarea"
|
|
|| targetTagName === "select");
|
|
if (event.altKey || event.ctrlKey || event.metaKey || editableTarget) {
|
|
return;
|
|
}
|
|
|
|
let shortcut = event.key.length === 1 ? event.key.toLowerCase() : event.key;
|
|
if (shortcut === "f") {
|
|
if (plotContext.msrPath) {
|
|
event.preventDefault();
|
|
toggleMusrfitRootFFT();
|
|
}
|
|
} else if (shortcut === "c") {
|
|
event.preventDefault();
|
|
rootViewMode = rootViewMode === "clean" ? "original" : "clean";
|
|
plotWindow.dataset.plotView = rootViewMode;
|
|
rerenderCurrentRootPlots(rootViewMode === "clean"
|
|
? "Clean ROOT plot view" : "Original ROOT plot view");
|
|
} else if (shortcut === "u") {
|
|
event.preventDefault();
|
|
rerenderCurrentRootPlots("ROOT plot view reset");
|
|
} else if (shortcut === "q" || shortcut === "Escape") {
|
|
event.preventDefault();
|
|
plotWindow.close();
|
|
}
|
|
});
|
|
|
|
let normalBounds = null;
|
|
let stateBeforeMinimize = "normal";
|
|
|
|
// Store the last normal bounds so minimize/maximize/restore are reversible.
|
|
minimizeButton.addEventListener("click", function() {
|
|
if (plotWindow.dataset.plotState === "minimized") {
|
|
plotWindow.dataset.plotState = stateBeforeMinimize;
|
|
minimizeButton.innerHTML = "−";
|
|
minimizeButton.title = "Minimize plot";
|
|
minimizeButton.setAttribute("aria-label", "Minimize plot");
|
|
if (stateBeforeMinimize === "maximized") {
|
|
plotWindow.style.left = "12px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = "12px";
|
|
plotWindow.style.width = "calc(100vw - 24px)";
|
|
plotWindow.style.height = "calc(100vh - var(--mu-status-height) - 36px)";
|
|
} else if (normalBounds) {
|
|
plotWindow.style.left = normalBounds.left + "px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = normalBounds.top + "px";
|
|
plotWindow.style.width = normalBounds.width + "px";
|
|
plotWindow.style.height = normalBounds.height + "px";
|
|
}
|
|
layoutMusrfitRootWindows();
|
|
return;
|
|
}
|
|
|
|
if (plotWindow.dataset.plotState === "normal") {
|
|
let bounds = plotWindow.getBoundingClientRect();
|
|
normalBounds = {
|
|
left: bounds.left,
|
|
top: bounds.top,
|
|
width: bounds.width,
|
|
height: bounds.height
|
|
};
|
|
}
|
|
stateBeforeMinimize = plotWindow.dataset.plotState;
|
|
plotWindow.dataset.plotState = "minimized";
|
|
minimizeButton.innerHTML = "⧉";
|
|
minimizeButton.title = "Restore plot";
|
|
minimizeButton.setAttribute("aria-label", "Restore plot");
|
|
plotWindow.style.width = "";
|
|
plotWindow.style.height = "";
|
|
layoutMusrfitRootWindows();
|
|
});
|
|
|
|
maximizeButton.addEventListener("click", function() {
|
|
if (plotWindow.dataset.plotState === "maximized") {
|
|
plotWindow.dataset.plotState = "normal";
|
|
maximizeButton.innerHTML = "□";
|
|
maximizeButton.title = "Maximize plot";
|
|
maximizeButton.setAttribute("aria-label", "Maximize plot");
|
|
if (normalBounds) {
|
|
plotWindow.style.left = normalBounds.left + "px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = normalBounds.top + "px";
|
|
plotWindow.style.width = normalBounds.width + "px";
|
|
plotWindow.style.height = normalBounds.height + "px";
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (plotWindow.dataset.plotState === "normal") {
|
|
let bounds = plotWindow.getBoundingClientRect();
|
|
normalBounds = {
|
|
left: bounds.left,
|
|
top: bounds.top,
|
|
width: bounds.width,
|
|
height: bounds.height
|
|
};
|
|
}
|
|
plotWindow.dataset.plotState = "maximized";
|
|
minimizeButton.innerHTML = "−";
|
|
minimizeButton.title = "Minimize plot";
|
|
minimizeButton.setAttribute("aria-label", "Minimize plot");
|
|
maximizeButton.innerHTML = "⧉";
|
|
maximizeButton.title = "Restore plot size";
|
|
maximizeButton.setAttribute("aria-label", "Restore plot size");
|
|
plotWindow.style.left = "12px";
|
|
plotWindow.style.right = "auto";
|
|
plotWindow.style.top = "12px";
|
|
plotWindow.style.width = "calc(100vw - 24px)";
|
|
plotWindow.style.height = "calc(100vh - var(--mu-status-height) - 36px)";
|
|
layoutMusrfitRootWindows();
|
|
});
|
|
|
|
closeButton.addEventListener("click", function() {
|
|
plotWindow.close();
|
|
});
|
|
plotWindow.addEventListener("close", function() {
|
|
disconnectMusrfitRootResizeObservers(plotContainer);
|
|
plotWindow.remove();
|
|
layoutMusrfitRootWindows();
|
|
});
|
|
|
|
// Bring the active plot above older plot windows before handling shortcuts or
|
|
// drag operations.
|
|
plotWindow.addEventListener("pointerdown", function() {
|
|
bringMusrfitFloatingWindowToFront(plotWindow);
|
|
try {
|
|
plotWindow.focus({ preventScroll: true });
|
|
} catch (error) {
|
|
plotWindow.focus();
|
|
}
|
|
});
|
|
|
|
let dragPosition = null;
|
|
|
|
// The blank header is intentionally only a drag handle plus window controls.
|
|
plotHeader.addEventListener("pointerdown", function(event) {
|
|
if (plotWindow.dataset.plotState !== "normal"
|
|
|| plotControls.contains(event.target)
|
|
|| plotMenuButton.contains(event.target)
|
|
|| plotActionMenu.contains(event.target)) {
|
|
return;
|
|
}
|
|
let bounds = plotWindow.getBoundingClientRect();
|
|
dragPosition = {
|
|
pointerX: event.clientX,
|
|
pointerY: event.clientY,
|
|
windowX: bounds.left,
|
|
windowY: bounds.top
|
|
};
|
|
plotHeader.setPointerCapture(event.pointerId);
|
|
event.preventDefault();
|
|
});
|
|
plotHeader.addEventListener("pointermove", function(event) {
|
|
if (!dragPosition) {
|
|
return;
|
|
}
|
|
let maximumX = Math.max(0, window.innerWidth - plotWindow.offsetWidth);
|
|
let maximumY = Math.max(0, window.innerHeight - plotHeader.offsetHeight);
|
|
let nextX = dragPosition.windowX + event.clientX - dragPosition.pointerX;
|
|
let nextY = dragPosition.windowY + event.clientY - dragPosition.pointerY;
|
|
plotWindow.style.left = Math.min(maximumX, Math.max(0, nextX)) + "px";
|
|
plotWindow.style.top = Math.min(maximumY, Math.max(0, nextY)) + "px";
|
|
});
|
|
plotHeader.addEventListener("pointerup", function(event) {
|
|
dragPosition = null;
|
|
plotHeader.releasePointerCapture(event.pointerId);
|
|
});
|
|
|
|
document.body.appendChild(plotWindow);
|
|
plotWindow.show();
|
|
bringMusrfitFloatingWindowToFront(plotWindow);
|
|
try {
|
|
plotWindow.focus({ preventScroll: true });
|
|
} catch (error) {
|
|
plotWindow.focus();
|
|
}
|
|
|
|
// Stagger several open plots slightly so their controls remain reachable.
|
|
let cascadeOffset = ((webRootPlotWindowSequence - 1) % 6) * 24;
|
|
let initialX = window.innerWidth - plotWindow.offsetWidth - 12 - cascadeOffset;
|
|
plotWindow.style.left = Math.max(12, initialX) + "px";
|
|
plotWindow.style.top = 12 + cascadeOffset + "px";
|
|
}
|