Files

1533 lines
58 KiB
JavaScript

//**************************************************************************//
// Shared functionality for Mudas: The Midas User interface
//
// ES module holding the parts of the Mudas front end that are shared by
// several SuS instruments. An instrument specific page (usually called Mudas.js)
// imports this module, supplies the instrument specific configuration
// (ODB paths, tabs, name and colors) and drives the page through the
// init() and update() entry points. See
// https://gitea.psi.ch/lin-midas-pages/vms_pages for a real-world example. The
// README has a minimal usage example in section "Using common.js".
//
// Copyright (C) 2020-2025 by Zaher Salman, Jonas Krieger, Stefan Mathis
// zaher.salman@psi.ch
// jonas.krieger@psi.ch
// stefan.mathis@psi.ch
//**************************************************************************//
/**
* Stop the current run, after user confirmation.
*
* Issues a `TR_STOP` cm_transition. Does nothing unless the user confirms;
* logs to the console if the transition does not return status 1.
*/
export function stop_run() {
let flag = confirm('Are you sure you want to stop the run?');
if (flag == true) {
mjsonrpc_call("cm_transition", { "transition": "TR_STOP" }).then(function (rpc) {
if (rpc.result.status !== 1) {
throw new Error("Cannot stop run, cm_transition() status " + rpc.result.status + ", see MIDAS messages");
}
}).catch(function (error) {
console.error(error);
});
}
}
/**
* Pause the current run, after user confirmation.
*
* Issues a `TR_PAUSE` cm_transition. Does nothing unless the user confirms;
* logs to the console if the transition does not return status 1.
*/
export function pause_run() {
let flag = confirm('Are you sure you want to pause the run?');
if (flag == true) {
mjsonrpc_call("cm_transition", { "transition": "TR_PAUSE" }).then(function (rpc) {
if (rpc.result.status !== 1) {
throw new Error("Cannot pause run, cm_transition() status " + rpc.result.status + ", see MIDAS messages");
}
}).catch(function (error) {
console.error(error);
});
}
}
/**
* Resume a paused run, after user confirmation.
*
* Issues a `TR_RESUME` cm_transition. Does nothing unless the user
* confirms; logs to the console if the transition does not return status 1.
*/
export function resume_run() {
let flag = confirm('Are you sure you want to resume the run?');
if (flag == true) {
mjsonrpc_call("cm_transition", { "transition": "TR_RESUME" }).then(function (rpc) {
if (rpc.result.status !== 1) {
throw new Error("Cannot resume run, cm_transition() status " + rpc.result.status + ", see MIDAS messages");
}
}).catch(function (error) {
console.error(error);
});
}
}
/**
* Start a run, after user confirmation.
*
* Issues a `TR_START` cm_transition. Does nothing unless the user confirms;
* logs to the console if the transition does not return status 1.
*/
export function start_run() {
let flag = confirm('Are you sure you want to start the run?');
if (flag == true) {
mjsonrpc_call("cm_transition", { "transition": "TR_START" }).then(function (rpc) {
if (rpc.result.status !== 1) {
throw new Error("Cannot start run, cm_transition() status " + rpc.result.status + ", see MIDAS messages");
}
}).catch(function (error) {
console.error(error);
});
}
}
/**
* ODB prefix for the sequencer. Points to PySequencer so that the
* legacy sequencer.js code transparently talks to PySequencer.
* @type {string}
*/
export var SeqODB = "/PySequencer";
/**
* One-time page setup, called once on page load.
*
* Builds the tab bar and loads every tab's content, then wires up the
* header: the run status display, the ODB-bound values, the elog link,
* the proposal ID check against DUO and the muSRFit/SearchDB links. It
* also resolves the mvar* / frappy_enum* placeholders, and warns for
* non-approved instruments.
*
* @param {object} instrTabs - Tab definitions, keyed by tab name. See
* `fill_tabs` for the expected shape.
* @param {object<string,string>} instrODB - Map of element id to ODB path.
* Each element whose id is a key here gets `data-odb-path` set to the
* value. Must at least provide `run_status`, `runNumber`, `sampleName`,
* `pID`, `pPI` and `pGRP` for the header features to work.
* @param {string} instrName - Instrument name, e.g. "VMS". Used for the
* page title, the header banner and the DUO/muSRFit queries.
* @param {string} instrColor - CSS color used for the header banner and
* the `mtable` borders, e.g. "#53b7d3".
* @param {string} elogLink - URL of the instrument's elog page; an empty
* string hides the elog link.
*/
export async function init(instrTabs, instrODB, instrName, instrColor, elogLink) {
try {
await fill_tabs(instrTabs);
} catch (err) {
// A single broken tab must never stop the rest of the page from loading.
console.error("[tabs] failed to load tabs:", err);
}
// Populate the page with instrument-specific instrument links
fill_odbs(instrODB, instrName, instrColor, elogLink);
// Check proposal ID against DUO
try {
compare_proposal_ids(instrODB, instrName, 0);
} catch (e) { }
// Update link to musrfit
update_musrfit_link(instrODB, instrName);
//init variables by name
mvar_init();
frappy_enum_init()
// Issue warning for non-approved instruments
if ((instrName != "FLAME") && (instrName != "GPS") && (instrName != "VMS")) {
alert(`WARNING\nPlease do not use this page if you do not know what you
are doing.\nThis page is under heavy development and should be
used by experts only.\nBy continuing, you agree to take
responsibility for any damage to the experiment or loss of beam time.`);
};
// Callback for alarms
let alarmsTable = document.getElementById("alarmsTable");
if (alarmsTable) {
function update() {
mjsonrpc_db_get_values(["/Alarms"]).then(function (rpc) {
const alarm = rpc.result.data[0];
if (alarm["alarm system active"]) {
var allAlarms = alarm["alarms"]
for (var element in allAlarms) {
if (allAlarms[element]["triggered"] && allAlarms[element]["active"]) {
if (document.getElementById(element + "Alarm") === null) {
var newAlarm = alarmsTable.insertRow(0);
var bgcol = "var(--mred)";
if (allAlarms[element]["alarm class"] == "Warning") {
bgcol = "var(--morange)";
} else if (allAlarms[element]["alarm class"] == "Message") {
bgcol = "var(--mgreen)";
}
newAlarm.id = element + "Alarm";
newAlarm.className = "alarmRow";
newAlarm.style.backgroundColor = bgcol;
let alarmHTML = "<td align=center style='font-weight: bold;'>\n" + allAlarms[element]["alarm class"] + ":" + allAlarms[element]["alarm message"];
alarmHTML += "<button class='mbutton' type='button' style='float:right;' onclick=\"mhttpd_reset_alarm('" + element + "');\">Reset</button>\n</td>\n";
newAlarm.innerHTML = alarmHTML;
}
} else {
if (document.getElementById(element + "Alarm") != null) {
document.getElementById(element + "Alarm").remove();
}
}
}
}
}).catch(function (error) { console.error(error); });
}
watch_odb(["/Alarms"], update);
update();
}
const run_status_odb_path = instrODB["run_status"];
if (run_status_odb_path) {
function update() {
mjsonrpc_db_get_values([run_status_odb_path]).then(function (rpc) {
let run_state = rpc.result.data[0];
// Change accordingly in GUI
// due to strange behaviour of mjsonrpc I have to send action to different function
if (!document.getElementById("startButton")) return;
let statCol = "";
let statText = "";
// Change accordingly in GUI
if (run_state == 1) {
// Stopped - red, make only Start visible
document.getElementById("startButton").disabled = false;
document.getElementById("stopButton").disabled = true;
document.getElementById("pauseButton").disabled = true;
document.getElementById("resumeButton").disabled = true;
document.getElementById("writeButton").disabled = true;
document.getElementById("zeroButton").disabled = true;
statCol = "var(--mred)";
statText = 'Stopped';
// Insert stop time
document.getElementById("stopTimetd").innerHTML = 'Stop time: ';
} else if (run_state == 2) {
// Paused - orange, make Stop and Resume visible
document.getElementById("startButton").disabled = true;
document.getElementById("stopButton").disabled = false;
document.getElementById("pauseButton").disabled = true;
document.getElementById("resumeButton").disabled = false;
document.getElementById("writeButton").disabled = false;
document.getElementById("zeroButton").disabled = false;
statCol = "var(--morange)";
statText = 'Paused';
// Insert running time
document.getElementById("stopTimetd").innerHTML = 'Run time: ';
set_running_time(run_state);
} else if (run_state == 3) {
// Running - green, make Stop and Pause visible
document.getElementById("startButton").disabled = true;
document.getElementById("stopButton").disabled = false;
document.getElementById("pauseButton").disabled = false;
document.getElementById("resumeButton").disabled = true;
document.getElementById("writeButton").disabled = false;
document.getElementById("zeroButton").disabled = false;
statCol = "var(--mgreen)";
statText = 'Running';
// Insert running time time
document.getElementById("stopTimetd").innerHTML = 'Run time: ';
set_running_time(run_state);
}
update_status_banner("run_statusBanner", statText, statCol);
}).catch(function (error) { console.error(error); });
}
watch_odb([run_status_odb_path], update);
update();
}
}
/**
* Creates / updates a status banner inside a specified container element with
* custom text and background color.
*
* @param {string} elementId - The ID of the container element where the status banner will be appended.
* @param {string} statText - The text content to display inside the status banner.
* @param {string} statCol - The background color for the status banner (e.g., a hex code, rgb value, or color name).
* @returns {void}
*/
export function update_status_banner(elementId, statText, statCol) {
const container = document.getElementById(elementId);
if (!container) return;
// Clear previous contents safely
container.innerHTML = "";
// Create the span element
const statusSpan = document.createElement("span");
statusSpan.id = "statusText";
statusSpan.textContent = statText; // Safely sets text, preventing HTML injection
// Apply styles
statusSpan.style.padding = "0.3em 0.5em";
statusSpan.style.borderRadius = "10px";
statusSpan.style.boxShadow = "5px 5px 5px grey";
statusSpan.style.backgroundColor = statCol;
// Append to container
container.appendChild(statusSpan);
}
/**
* Returns the color associated with the current frontend status text.
*
* @param {string} statusText - Frontend status text ("Ok", "Initializing...", "Driver error", ...).
* @returns {string}
*/
export function status_color_from_fe_status(...statusText) {
const mapping = new Proxy(
{
"Ok": {severity: 0, colour: "var(--mgreen)"},
"Initializing...": {severity: 1, colour: "var(--morange)"},
},
{
get: (target, status) => target[status] ?? {severity: 1000, colour: "var(--mred)"},
}
);
const worst_status = statusText.reduce(
(worst, status) =>
mapping[status].severity > mapping[worst].severity ? status: worst
);
return {
text: worst_status,
colour: mapping[worst_status].colour
};
}
/**
* Show the given PySequencer script line in the AutoRunLine header field.
* @param {number} linenumber - Number of the line to display
* @param {string} element_id - ID of the HTML document element whose text
* should be replaced with the line number. Defaults to "AutoRunLine".
*/
export function update_pysequencer_line(linenumber, element_id = "AutoRunLine") {
if (linenumber > 0) { linenumber -= 1; }
mjsonrpc_db_get_values(["/PySequencer/State/Running", "/PySequencer/Script/Lines[" + linenumber + "]"]).then(function (rpc) {
var running = rpc.result.data[0];
var line = rpc.result.data[1];
if (line) {
document.getElementById(element_id).textContent = line;
} else {
document.getElementById(element_id).textContent = "";
}
}).catch(function (error) {
document.getElementById(element_id).textContent = "";
console.log(error);
});
}
/**
* Replaces the mvar* spans (mvarvalue, mvarbox, mvarcheckbox, mvarselect) with
* their corresponding modb* elements, building each element's ODB path from its
* data attributes (data-equipment, data-varname, data-buffer).
*/
export function mvar_init() {
let mvars = getMElements("mvarvalue").concat(getMElements("mvarbox"), getMElements("mvarcheckbox"),
getMElements("mvarselect"));
for (let i = 0; i < mvars.length; i++) {
let o = mvars[i];
if (o.dataset.equipment !== undefined && o.dataset.varname !== undefined && o.dataset.buffer !== undefined) {
var name_config = "/Equipment/" + o.dataset.equipment + "/Settings/Names " + o.dataset.buffer;
//optional config
var unit_config = "/Equipment/" + o.dataset.equipment + "/Settings/Unit " + o.dataset.buffer;
var format_config = "/Equipment/" + o.dataset.equipment + "/Settings/Format " + o.dataset.buffer;
mjsonrpc_db_get_values([name_config, unit_config, format_config]).then(function (rpc) {
var names = rpc.result.data[0];
var units = rpc.result.data[1];
var formats = rpc.result.data[2];
if (Array.isArray(names)) {
let index = names.indexOf(o.dataset.varname);
o.setAttribute("data-odb-path", "/Equipment/" + o.dataset.equipment + "/Variables/" + o.dataset.buffer + "[" + index.toString() + "]");
if (o.getAttribute('name') == 'mvarvalue') { o.setAttribute("name", "modbvalue"); }
else if (o.getAttribute('name') == 'mvarbox') { o.setAttribute("name", "modbbox"); }
else if (o.getAttribute('name') == 'mvarcheckbox') { o.setAttribute("name", "modbcheckbox"); }
else if (o.getAttribute('name') == 'mvarselect') { o.setAttribute("name", "modbselect"); }
//optional formatting:
if (Array.isArray(formats)) {
o.setAttribute("data-format", formats[index]);
}
if (Array.isArray(units)) {
let unit = document.createElement('span');
unit.innerHTML = ' ' + units[index];
o.parentElement.appendChild(unit);
}
} else {
o.innerHTML = "<div> Variable " + o.dataset.varname + " not found.</div>";
}
})
} else {
o.innerHTML = "<div> Variable ill-defined.</div>";
}
}
// trigger refresh
mhttpd_refresh();
}
/**
* Fills the frappy_enum elements with their options, read from the equipment's
* FrappyNode enum ODB.
*/
export function frappy_enum_init() {
let frappynum = getMElements("frappy_enum");
for (let i = 0; i < frappynum.length; i++) {
let o = frappynum[i];
if (o.dataset.equipment !== undefined && o.dataset.varname !== undefined) {
var enum_config = "/Equipment/" + o.dataset.equipment + "/Settings/Devices/FrappyNode/DD/enums/" + o.dataset.varname;
mjsonrpc_db_get_values([enum_config,]).then(function (rpc) {
var config = rpc.result.data[0];
if (config != null) {
for (key in config) {
if (!key.includes('/')) {
let opt = document.createElement('option');
opt.value = key;
opt.innerHTML = config[key];
o.appendChild(opt);
}
}
} else {
//configuration missing.
}
})
}
}
}
/**
* Show or hide all elements of a class.
* @param {string} clname - Class name to toggle (without the leading dot).
* @param {boolean|HTMLElement} fe - Show state; a boolean, or a frontend
* element whose value (0 = active) decides visibility.
*/
export function show_class(clname, fe) {
let selector = "." + clname;
let flag = false;
if (typeof fe === "boolean") {
// if a boolean was sent use it to determine state
flag = fe;
} else {
// otherwise check the sate of the fe (running ot not)
flag = (fe.value == 0) ? true : false;
}
// Find all elements with the correct class and hide/show
const classEls = document.querySelectorAll(selector);
classEls.forEach((element) => {
if (flag) {
element.style.visibility = "visible";
switch (element.nodeName) {
case "SPAN":
element.style.display = "inline";//JAK 16.5.24 to fix Dolly RunControl
//element.style.display = "inline-block";
break;
case "TR":
element.style.display = "table-row"; break;
default:
console.log(element.nodeName);
element.style.display = "block";
}
} else {
element.style.visibility = "hidden";
element.style.display = "none";
}
});
}
/**
* Enable, disable or toggle the disabled state of all elements of a class.
* @param {string} clname - Class name to target (without the leading dot).
* @param {string} [set="toggle"] - "enable", "disable" or "toggle".
* @param {string} [title] - Optional title to set on each element.
*/
export function enable_class(clname, set = "toggle", title) {
let selector = "." + clname;
// Find all elements with the correct class and hide/show
const btnEls = document.querySelectorAll(selector);
btnEls.forEach((element) => {
switch (set) {
case "enable":
element.disabled = false;
break;
case "disable":
element.disabled = true;
break;
case "toggle":
element.disabled = !element.disabled;
break;
default:
console.log(`Error in chaning disabled value of ${element}.`);
return;
}
if (typeof title !== undefined) {
element.title = title;
}
});
}
/**
* Show, hide or toggle the visibility of all elements of a class.
* @param {string} clname - Class name to target (without the leading dot).
* @param {string} [set="toggle"] - "visible", "hidden" or "toggle".
*/
export function set_class_visibility(clname, set = "toggle") {
let selector = "." + clname;
// Find all elements with the correct class and hide/show
const clEls = document.querySelectorAll(selector);
clEls.forEach((element) => {
switch (set) {
case "visible":
element.style.visibility = 'visible';
break;
case "hidden":
element.style.visibility = 'hidden';
break;
case "toggle":
if (element.style.visibility == 'hidden') {
element.style.visibility = 'visible';
} else {
element.style.visibility = 'hidden';
}
break;
default:
console.log(`Error in changing visibility of ${element}.`);
return;
}
});
}
/**
* Wire up the header from the instrument configuration.
*
* For every key in `instrODB`, sets `data-odb-path` on the element whose
* id equals the key. Also configures the elog link (hidden when
* `elogLink` is empty), the page title, the instrument name banner and
* the `mtable` border color.
*
* @param {object<string,string>} instrODB - Map of element id to ODB path.
* @param {string} instrName - Instrument name for the title and banner.
* @param {string} instrColor - CSS color for the banner and `mtable` borders.
* @param {string} elogLink - Elog URL; an empty string hides the link.
*/
function fill_odbs(instrODB, instrName, instrColor, elogLink) {
for (let key in instrODB) {
var element = document.getElementById(key);
if (element) {
// if the element exists then fill the correct path
element.setAttribute("data-odb-path", instrODB[key]);
}
}
// Elog link
let elogElem = document.getElementById("elogLink");
if (elogLink == "") {
// hide Elog field
elogElem.style.visibility = "hidden";
} else {
// set the correct link
elogElem.setAttribute("href", elogLink);
}
// Title of page and instrument name/color
document.title = instrName + " Mudas";
let instrBanner = document.getElementById("instrName");
instrBanner.innerHTML = "<span style='color: white;width:300px;padding: 0.3em 0.5em 0.3em 0.5em;border-radius:10px;font-style: oblique;font-weight: bold;background-color:" + instrColor + ";'>Mudas " + instrName + "</span>";
let mTables = document.getElementsByClassName("mtable");
for (const mTable of mTables) {
mTable.style.border = '6px solid ' + instrColor;
}
}
/**
* Build the tab buttons and load each tab's content, driven by the instrTabs
* dictionary passed in. Each key is a tab; expected format:
*
* instrTabs = {
* runControl: {
* order: 1, // or according to order
* label: "Run Control", // Label of the tab
* htmlFile: "RunControl_tab.html", // markup file under /tabs/
* style: "Tab", // Tab or Menu
* },
* TDCstatus: {
* order: 2,
* label: "TDC Statistics",
* htmlFile: "TDCstatus_tab.html",
* jsFile: "TDC_tab.js", // optional JS, loaded into this document
* onOpen: ["read_tdc_status", "load_status"], // optional, run on open
* style: "Tab",
* },
* };
*
* Each entry's fields:
* htmlFile : (required) markup file under /tabs/ (pure HTML, no <script>)
* jsFile : (optional) JS file under /tabs/, loaded into THIS document
* (loaded at most once, even if several tabs reference it)
* init : (optional) no-arg function name(s), run once after the
* markup of all tabs using it has been loaded (see also
* load_tab_group and load_module). The function needs to be
* either exported by the jsFile or globally exported (see
* run_tab_inits)
* onOpen : (optional) no-arg function name(s), run on every open. The
* functions need to be either exported by the jsFile or globally
* exported (see run_on_open).
* style : "Tab" (top bar) or "Menu" (under "More ...")
* order/label : placement and caption
*
* Requires the page to contain the elements with ids `tabBtns`, `tabMenu`,
* `tabFrames` and `beforeMenu`.
*
* @param {object} instrTabs - The tab definitions, keyed by tab name.
*/
async function fill_tabs(instrTabs) {
let tabBtns = document.getElementById("tabBtns");
let tabMenu = document.getElementById("tabMenu");
let tabFrames = document.getElementById("tabFrames");
let beforeMenu = document.getElementById("beforeMenu");
let iTab = 0;
let tabs = [];
// Pass 1: create every tab's container and button (in order) so the DOM
// structure is complete before any markup or JS loads.
for (let key in instrTabs) {
iTab++;
let tab = instrTabs[key];
tab.num = iTab;
// content container
let d = document.createElement("div");
d.id = "Tab" + iTab;
d.className = "tabcontent";
tabFrames.appendChild(d);
// tab button
let b = document.createElement(tab.style == "Menu" ? "a" : "button");
b.id = "TabButton" + iTab;
b.dataset.tabLabel = tab.label;
b.dataset.tabHtmlFile = tab.htmlFile;
b.className = "w3-bar-item w3-button w3-round";
b.addEventListener("click", (event) => {
open_tab(event, b.id);
});
b.innerHTML = "<b>" + tab.label + "</b>";
b.dataset.onOpen = as_list(tab.onOpen).join(",");
if (tab.jsFile) b.dataset.jsFile = tab.jsFile;
if (tab.style == "Menu") {
b.href = "#";
tabMenu.append(b);
} else {
tabBtns.insertBefore(b, beforeMenu);
}
tabs.push(tab);
}
// Pass 2: group tabs by JS file. A shared JS file's top-level
// addEventListener wiring runs at import time, so every tab that uses that
// file must already have its markup in the DOM before the module is
// imported; load each group as one unit.
let groups = new Map(); // jsFile (or "") -> [tab, ...]
for (let tab of tabs) {
let g = tab.jsFile || "";
if (!groups.has(g)) groups.set(g, []);
groups.get(g).push(tab);
}
await Promise.all([...groups.entries()].map(([jsFile, group]) => load_tab_group(jsFile, group)));
}
/**
* Normalize a tab-config value (absent, a single name, or a list of names)
* to a list.
* @param {*} x - The value to normalize
* @returns {Array} The value as a list
*/
function as_list(x) { return x == null ? [] : (Array.isArray(x) ? x : [x]); }
let loadedTabModules = new Map(); // jsFile -> import() Promise
let loadedTabNamespaces = new Map(); // jsFile -> module namespace (once resolved)
/**
* Import a tab JS file once; every tab that references it awaits the same
* Promise and receives the same module namespace.
* @param {string} jsFile - The JS file name under ./tabs/ (relative to this module).
* @returns {object} The module namespace.
*/
async function load_module(jsFile) {
if (!loadedTabModules.has(jsFile)) {
loadedTabModules.set(jsFile, import(new URL("tabs/" + jsFile, import.meta.url).href).then((ns) => {
loadedTabNamespaces.set(jsFile, ns);
return ns;
}));
}
return await loadedTabModules.get(jsFile);
}
/**
* Load one group of tabs that share a JS file: fetch and insert every tab's
* markup first, then import the shared module once (its top-level wiring runs
* at import time), then run each tab's init function(s).
* @param {string} jsFile - The shared JS file, or "" for tabs with none.
* @param {object[]} group - The tab definitions in this group.
*/
async function load_tab_group(jsFile, group) {
try {
let ok = await Promise.all(group.map((tab) => load_tab_markup(tab.num, tab)));
let ready = group.filter((tab, i) => ok[i]);
if (!ready.length) return;
if (!jsFile) {
ready.forEach((tab) => run_tab_inits(tab, null));
return;
}
let ns;
try {
ns = await load_module(jsFile);
} catch (err) {
console.error("[tabs] failed to load " + jsFile + ":", err);
ready.forEach((tab) => mark_tab_failed(tab, "failed to load tab"));
return;
}
ready.forEach((tab) => run_tab_inits(tab, ns));
} catch (err) {
// Last-resort guard: a single broken tab must never take down the rest.
console.error("[tabs] error loading tab group " + (jsFile || "(no js file)") + ":", err);
}
}
/**
* Fetch a tab's markup and move the <body> children into the tab container of
* the main page.
* @param {number} tabNum - The tab number (used to build the container id).
* @param {object} tab - The tab definition from instrTabs.
* @returns {boolean} true if the markup loaded successfully.
*/
async function load_tab_markup(tabNum, tab) {
let container = document.getElementById("Tab" + tabNum);
try {
let html = await (await fetch(new URL("tabs/" + tab.htmlFile, import.meta.url), { cache: "no-store" })).text();
let body = new DOMParser().parseFromString(html, "text/html").body;
// guardrail: flag ids that collide with something already in the page
let taken = new Set([...document.querySelectorAll("[id]")].map((e) => e.id));
container.append(...body.children);
body.querySelectorAll("[id]").forEach((el) => {
if (taken.has(el.id)) console.warn('[tabs] duplicate id "' + el.id + '" in ' + tab.htmlFile);
});
return true;
} catch (err) {
console.error("[tabs] failed to load markup " + tab.htmlFile + ":", err);
container.textContent = "failed to load tab";
return false;
}
}
/**
* Flag a tab's container as failed so the user can see which tab is broken
* without the rest of the page being affected.
* @param {object} tab - The tab definition from instrTabs.
* @param {string} msg - The message to show inside the tab.
*/
function mark_tab_failed(tab, msg) {
let container = document.getElementById("Tab" + tab.num);
if (container) container.textContent = msg;
}
/**
* Run a tab's init function(s) once: prefer the named export on the tab's JS
* module, fall back to a global of the same name.
* @param {object} tab - The tab definition from instrTabs.
* @param {object|null} ns - The tab's JS module namespace, or null.
*/
function run_tab_inits(tab, ns) {
as_list(tab.init).forEach((name) => {
let fn = (ns && typeof ns[name] === "function") ? ns[name]
: (typeof globalThis[name] === "function") ? globalThis[name]
: null;
if (fn) {
try {
fn(...(tab.initArgs || []));
} catch (err) {
console.error('[tabs] init "' + name + '" for ' + tab.htmlFile + ' threw:', err);
mark_tab_failed(tab, "tab init failed");
}
}
else console.error('[tabs] init "' + name + '" for ' + tab.htmlFile + ' not found');
});
}
/**
* Run a tab's onOpen handler once: prefer the named export on the tab's JS
* module, fall back to a global of the same name.
* @param {string} name - The handler function name.
* @param {string} jsFile - The tab's JS file (or "" for none).
*/
function run_on_open(name, jsFile) {
let ns = jsFile ? loadedTabNamespaces.get(jsFile) : null;
let fn = (ns && typeof ns[name] === "function") ? ns[name]
: (typeof globalThis[name] === "function") ? globalThis[name]
: null;
if (fn) {
try {
fn();
} catch (err) {
console.error('[tabs] onOpen "' + name + '" threw:', err);
}
}
else console.error('[tabs] onOpen "' + name + '" not found');
}
/**
* Returns a promise which - if awaited upon - blocks until all elements
* specified by the selector(s) are available in the DOM.
* @param {string[]} selectors - CSS selectors to wait for.
* @returns {Promise<HTMLElement[]>} The matched elements.
*/
export async function wait_for_elements(selectors) {
const find = () => selectors.map(selector =>
document.querySelector(selector)
);
let elements = find();
if (elements.every(Boolean)) {
return elements;
}
return new Promise(resolve => {
const observer = new MutationObserver(() => {
elements = find();
if (elements.every(Boolean)) {
observer.disconnect();
resolve(elements);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
/**
* Update the running/stopped time display based on the run state.
* @param {number} run_state - 1 stopped, 2 paused, 3 running.
*/
function set_running_time(run_state) {
let stopTime = document.getElementById("stopTime");
// If running or paused
if (run_state != 1) {
// hide stopped time
stopTime.style.visibility = "hidden";
// show running time
mjsonrpc_db_get_values(["/Runinfo"]).then(function (rpc) {
const runinfo = rpc.result.data[0];
const time = runinfo['start time binary/last_written'];
const difftime = Math.round(new Date().getTime() / 1000) - time;
const h = Math.floor(difftime / 3600);
const m = Math.floor(difftime % 3600 / 60);
const s = Math.floor(difftime % 60);
const runTime = h + "h" + ((m < 10) ? "0" + m : m) + "m" + ((s < 10) ? "0" + s : s) + "s";
document.getElementById("vstopTimetd").innerHTML = runTime;
}).catch(function (error) { console.error(error); });
} else {
// show stopped time
stopTime.style.visibility = "visible";
}
}
/**
* Build the muSRFit and SearchDB hyperlinks from the current run number and
* sample name.
*
* Updates the `href` of the `musrfitRun` and `SearchDBlink` elements,
* scoping the query to the current year and the beamline (the part of
* `instrName` before the first "-", or the entire instrName if there is no "-"").
*
* @param {object<string,string>} instrODB - The instrument ODB map; must
* provide `runNumber` and `sampleName`.
* @param {string} instrName - Instrument name, e.g. "VMS-...".
*/
export function update_musrfit_link(instrODB, instrName) {
// ToDo: check measurement geometry and guess function/histos
let aelement = document.getElementById("musrfitRun");
let fitlink = "http://musruser.psi.ch/muSRFlow?action=plot&";
let belement = document.getElementById("SearchDBlink");
let dblink = "http://musruser.psi.ch/cgi-bin/SearchDB.cgi?";
let year = new Date().getFullYear();
fitlink += "YEAR=" + year;
fitlink += "&BeamLine=" + instrName.split("-")[0];
dblink += "YEAR=" + year;
dblink += "&AREA=" + instrName.split("-")[0];
mjsonrpc_db_get_values([instrODB["runNumber"], instrODB["sampleName"]]).then(function (rpc) {
let runNumber = rpc.result.data[0];
let sampleName = rpc.result.data[1];
if (window.location.href.includes("/CS/Mudas"))
sampleName = sampleName.substring(0, 9);
sampleName = sampleName.replaceAll("(", "\\(").replaceAll(")", "\\)");
sampleName = sampleName.replaceAll("[", "\\[").replaceAll("]", "\\]");
fitlink += "&RunNumbers=" + runNumber;
dblink += "&Phrases=" + sampleName + "&go=Search";
aelement.setAttribute("href", fitlink);
belement.setAttribute("href", dblink);
}).catch(function (error) { console.error(error); });
}
/**
* Toggle a <div></div> section between visible and hidden, and update the
* sender's icon.
* @param {string} iddiv - Id of the div to toggle.
* @param {HTMLElement} sender - The button that triggered the toggle.
*/
export function set_div_visibility(iddiv, sender) {
let totoggle = document.getElementById(iddiv);
if (totoggle === null) return;
let state = totoggle.style.display;
if (state == 'none') {
totoggle.style.display = "block";
} else {
totoggle.style.display = "none";
}
let symbol = sender.innerHTML;
if (symbol == "-") {
sender.innerHTML = "+";
sender.title = "Show information row";
} else if (symbol == "+") {
sender.innerHTML = "-";
sender.title = "Hide information row";
} else if (iddiv == "infoRow" && symbol == "🗖") {
sender.innerHTML = "&#128471;";
sender.title = "Restore";
} else if (iddiv == "infoRow" && symbol == "🗗") {
sender.innerHTML = "&#128470;";
sender.title = "Maximize";
}
}
/**
* Swap the positions of two <div>s and update the arrow indicator.
* @param {string} iddiv1 - Id of the first div.
* @param {string} iddiv2 - Id of the second div.
* @param {HTMLElement} arrow - The arrow element indicating direction.
*/
export function swap_divs(iddiv1, iddiv2, arrow) {
let element1 = document.getElementById(iddiv1);
let element2 = document.getElementById(iddiv2);
if (arrow.innerHTML == "\u2191") {
element1.parentNode.insertBefore(element1, element2);
arrow.innerHTML = "&darr;";
arrow.title = "Move down";
} else {
element2.parentNode.insertBefore(element2, element1);
arrow.innerHTML = "&uarr;";
arrow.title = "Move up";
}
}
/**
* Check the proposal details (ID, PI, P-group) against the DUO schedule and
* highlight a mismatch.
*
* Reads the values from the ODB, then hands them to
* `compare_proposal_ids_impl`.
*
* @param {object<string,string>} instrODB - The instrument ODB map; must
* provide `pID`, `pPI` and `pGRP`.
* @param {string} instrName - Instrument name, used to query DUO.
* @param {number} flag - 0: check and highlight only; 1: also offer to
* adopt the DUO values.
*/
export function compare_proposal_ids(instrODB, instrName, flag) {
mjsonrpc_db_get_values([instrODB["pID"], instrODB["pPI"], instrODB["pGRP"]])
.then(function (rpc) {
let prop_odb = rpc.result.data[0];
let proposer_odb = rpc.result.data[1];
let pgrp_odb = rpc.result.data[2];
compare_proposal_ids_impl(instrODB, instrName, prop_odb, proposer_odb, pgrp_odb, flag);
});
}
/**
* Compare the proposal details with the DUO schedule and, on mismatch,
* highlight them and (optionally) offer to adopt the DUO values.
*
* @param {object<string,string>} instrODB - The instrument ODB map; used
* to write back the DUO values when the user accepts them.
* @param {string} instrName - Instrument name, used to query DUO.
* @param {string} prop_odb - Proposal ID from the ODB.
* @param {string} proposer_odb - Proposer from the ODB.
* @param {string} pgrp_odb - Proposal group from the ODB.
* @param {number} flag - 0: highlight only; 1: also offer to change.
*/
function compare_proposal_ids_impl(instrODB, instrName, prop_odb, proposer_odb, pgrp_odb, flag) {
let d = new Date();
d.setHours(d.getHours() - 6);
let instrument = instrName.toLowerCase();
let web_duo = 'https://duo.psi.ch/duo/api.php/v1/CalendarInfos/scheduled/smus?beamline=' + instrument + '&SECRET=change-bib-eva-grille';
console.log(web_duo);
fetch(web_duo, { method: 'POST' })
.then(data => data.json(), console.error)
.then(data => {
let proposer_duo = "Thomas Prokscha";
let prop_duo = "20210284";
let pgrp_duo = "p18973";
let extratxt = "\ndoes not match the empty schedule!\nShould I use the default values?";
if (data != undefined && data[0] !== undefined) {
proposer_duo = data[0].firstname + " " + data[0].lastname;
prop_duo = data[0].proposal;
pgrp_duo = data[0].pgroup;
extratxt = "\ndoes NOT match schedule!\n" + prop_duo + "/" + proposer_duo + "/" + pgrp_duo + "\nShould I take the details from DUO?";
}
if ((prop_odb != prop_duo) || (proposer_odb != proposer_duo) || (pgrp_odb != pgrp_duo)) {
//console.log('why am i here?', 'in:'+fullname,' out:'+proposer_odb );
document.getElementById("propID").className = "propIDcorrect";
document.getElementById("propGRP").className = "propIDcorrect";
document.getElementById("propPI").className = "propIDcorrect";
document.getElementById("propFromDuo").style.visibility = "visible";
if (flag) {
if (confirm("Proposal ID\n" + prop_odb + "/" + proposer_odb + "/" + pgrp_odb + extratxt)) {
modbset(instrODB["pID"], prop_duo);
modbset(instrODB["pPI"], proposer_duo);
modbset(instrODB["pGRP"], pgrp_duo);
// Then reset highlights/button
document.getElementById("propID").className = "";
document.getElementById("propGRP").className = "";
document.getElementById("propPI").className = "";
document.getElementById("propFromDuo").style.visibility = "hidden";
}
}
} else {
document.getElementById("propID").className = "";
document.getElementById("propGRP").className = "";
document.getElementById("propPI").className = "";
document.getElementById("propFromDuo").style.visibility = "hidden";
}
});
}
/**
* Switch to the selected tab: hide the other tabs' content, clear the
* "active" state from the tab buttons, show the selected tab, sync the
* `tab=` value in the URL and run the tab's onOpen handler(s).
*
* @param {Event} evt - The triggering event.
* @param {string} tab - The tab button id (with or without the "TabButton"
* prefix).
*/
export function open_tab(evt, tab) {
// Remove the "TabButton" prefix to make this compatible with the new button ID naming scheme.
tab = tab.replace("TabButton", "");
// Declare all variables
let i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("w3-bar-item");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
tablinks[i].className = tablinks[i].className.replace(" w3-gray", "");
}
// Default tab
if (tab === undefined) tab = 1;
let tabName = "Tab" + tab;
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
evt.currentTarget.className += " w3-gray";
let reg = /tab=\d+/;
let url = window.location.href;
if (url.search("tab=") == -1) {
// if tab is not in url add it but check which version of midas we are dealing with
if (url.includes("/CS/Mudas")) {
url += "?tab=" + tab;
} else {
url += "&tab=" + tab;
}
} else {
// otherwise replace with new tab value
url = url.replace(reg, "tab=" + tab)
}
if (url !== window.location.href) {
window.history.replaceState({}, "Mudas", url);
}
// run the tab's onOpen handler(s), if any
if (evt && evt.currentTarget) {
let jsFile = evt.currentTarget.dataset.jsFile || "";
(evt.currentTarget.dataset.onOpen || "").split(",").filter(Boolean).forEach((name) => {
run_on_open(name, jsFile);
});
}
}
/**
* Load a Python setup script in PySequencer after user confirmation.
*
* Sets `/PySequencer/State/Filename` and issues a "Load new file" command.
* Does nothing if a script or a measurement is already running.
*
* Requires `dlgParam` and `checkODBValue` (from sequencer.js) to be loaded;
* otherwise it logs an error and returns without doing anything.
*
* @param {string} command - The script name to load (or "Idle").
*/
export function run_pysequencer_script(command) {
if (typeof dlgParam !== 'function' || typeof checkODBValue !== 'function') {
// sequencer.js needs to be loaded
console.error("dlgParam and/or checkODBValue missing. Please ensure that sequencer.js is correctly loaded.");
return;
}
// Get confirmation from user before proceeding
let result = confirm('Are you sure you want to run ' + command + '?');
if (result == false) {
// Abort.
return;
}
// Check whether there is an pysequencer already going
mjsonrpc_db_get_values(["/PySequencer/State/Running", "/PySequencer/State/Running"]).then(function (rpc) {
if (rpc.result.data[0] == false && rpc.result.data[1] !== 1) {
// Set run file name in ODB
modbset('/PySequencer/State/Filename', command);
mjsonrpc_db_paste([`/PySequencer/Command/Load new file`], [true]).then(function (rpc) {
if (rpc.result.status[0] === 1) {
// Wait for Load new file to turn false
checkODBValue(`/PySequencer/Command/Load new file`, false, dlgParam, false);
}
});
} else {
//
alert("Cannot change setup while a pysequencer script or a measurement is running.")
}
}).catch(function (error) { mjsonrpc_error_alert(error); });
}
/**
* Create a modal dialog with general HTML content, replacing any existing
* one with the same id, and optionally position it at (x, y).
* @param {string} iddiv - Id for the modal element.
* @param {number} [x] - Optional x position (only used when y is also set).
* @param {number} [y] - Optional y position (only used when x is also set).
* @returns {HTMLElement} The created modal element.
*/
export function populate_modal(iddiv, x, y) {
// First make sure you removed exisitng iddiv
if (document.getElementById(iddiv)) document.getElementById(iddiv).remove();
let d = document.createElement("div");
d.className = "dlgFrame";
d.id = iddiv;
d.style.zIndex = "30";
d.shouldDestroy = true;
d.innerHTML = `
<div class="dlgTitlebar">Mudas dialog</div>
<div class="dlgPanel" style="padding: 3px;">
<div style="width:fit-content;height:35em;overflow:scroll;text-align: left;" id="popHTML"></div>
<button class="mbutton w3-display-bottomright" type="button" id="popButton"></button>
</div>
`;
document.body.appendChild(d);
dlgShow(d);
if (x !== undefined && y !== undefined)
dlgMove(d, x, y);
return d;
}
/**
* Returns a Promise to the index of a named ODB variable in an equipment buffer.
*
* MIDAS equipment variables are stored as arrays under paths such as
*
* /Equipment/<equipment>/Variables/<buffer>
*
* while the corresponding variable names are stored under
*
* /Equipment/<equipment>/Settings/Names <buffer>
*
* This function reads the variable-name list and returns the index of
* `varname` in that list.
*
* @param {string} equipment
* Name of the MIDAS equipment.
*
* @param {string} buffer
* Variable buffer, e.g. "Input" or "Output".
*
* @param {string} varname
* Name of the variable to find.
*
* @returns {Promise<number>}
* Index of `varname` in the equipment's variable buffer.
*
* @throws {Error}
* If `mjsonrpc_db_get_values()` fails to read the variable-name
* list. Errors from `mjsonrpc_db_get_values()` are propagated
* unchanged.
*
* @throws {Error}
* If the variable-name list cannot be read or is not an array.
*
* @throws {Error}
* If `varname` does not exist in the variable-name list.
*
* @example
* const index = await get_odb_index(
* "He4_cryostat",
* "Input",
* "Pressure"
* );
*
* // If "Pressure" is the 22nd entry:
* // index === 21
*/
export async function get_odb_index(equipment, buffer, varname) {
const namesPath =
`/Equipment/${equipment}/Settings/Names ${buffer}`;
const rpc = await mjsonrpc_db_get_values([namesPath]);
const names = rpc.result.data[0];
if (!Array.isArray(names)) {
throw new Error(
`Could not read variable names for ` +
`${equipment}/${buffer}`
);
}
const index = names.indexOf(varname);
if (index < 0) {
throw new Error(
`Variable "${varname}" not found in ` +
`${equipment}/${buffer}`
);
}
return index;
}
/**
* Watch one or more MIDAS ODB variables and call a callback whenever
* one of their values changes.
*
* Each entry in `specs` can either be:
*
* 1. A complete ODB path:
*
* "/Equipment/He4_cryostat/Variables/Input[22]"
*
* 2. An object identifying a variable by equipment, buffer and name:
*
* {
* equipment: "He4_cryostat",
* buffer: "Input",
* varname: "Pressure"
* }
*
* In this case, the function looks up `varname` in
*
* /Equipment/<equipment>/Settings/Names <buffer>
*
* and constructs the corresponding path
*
* /Equipment/<equipment>/Variables/<buffer>[index]
*
* The resulting elements are created as invisible `modb` elements.
* MIDAS's normal `mhttpd_refresh()` mechanism then monitors their
* ODB values and calls `callback` when a value changes.
*
* The function may be called with a single specification or an array
* of specifications. Path strings and variable objects may be mixed.
*
* Example:
*
* watch_odb([
* "/Equipment/He4_cryostat/Variables/Input[22]",
* {
* equipment: "He3_cryostat",
* buffer: "Input",
* varname: "Pressure"
* }
* ], update_pressure);
*
* The returned array contains the generated `modb` elements.
*
* @param {string|Object|Array<string|Object>} specs
* ODB path(s) or variable descriptor(s).
*
* @param {Function} callback
* Function called when one of the watched ODB values changes. It receives
* the two arguments `this: GlobalEventHandlers, ev: Event` from the span
* when it changes (i.e. when a value in the ODB updates and mhttpd_refresh
* updates the span). `this` is the span, `ev` is the event which triggered
* the `onchange` callback.
*
* @returns {Promise<HTMLElement[]>}
* The generated `modb` watcher elements.
*/
export function watch_odb(specs, callback) {
if (!Array.isArray(specs))
specs = [specs];
const elements = [];
for (const spec of specs) {
const elem = document.createElement("span");
elem.classList.add("modb");
elem.onchange = callback;
if (typeof spec === "string") {
// Direct ODB path
elem.dataset.odbPath = spec;
document.body.appendChild(elem);
elements.push(elem);
} else if (spec &&
spec.equipment !== undefined &&
spec.buffer !== undefined &&
spec.varname !== undefined) {
get_odb_index(
spec.equipment,
spec.buffer,
spec.varname
).then((index) => {
const path =
`/Equipment/${spec.equipment}` +
`/Variables/${spec.buffer}[${index}]`;
elem.dataset.odbPath = path;
document.body.appendChild(elem);
elements.push(elem);
});
} else {
console.error("watch_odb: invalid specification", spec);
continue;
}
}
return elements;
}
/**
* This function has two modes of operation, depending on whether an
* `initValue` is provided or not.
*
* Assuming no `initValue` is provided, it imitates the MIDAS editing behaviour
* for modb/modbvalue by temporarily replacing the contents of the provided
* `elem` when clicked on with an inline input field.
*
* Pressing `Enter` during edit mode runs the specified `update` function with
* the newly provided value passed as an argument.
*
* Pressing `Escape` exits the inline editing mode without running the `update`
* function instead reverting to `elem`'s previous text contents.
*
* If `update` returns `false` (checked strictly `===`) the old value is
* restored.
*
* When `initValue` is provided, the function instead inserts `initValue` as a
* clickable link. When clicked on, this triggers the inline editing behaviour
* specified above.
*
* @param {HTMLAnchorElement} elem - The html element that displays the
* specified value as a link or an inline editing field.
* @param {function(number): void} update - Callback invoked with the edited
* value. If this function returns `false` (the actual boolean, not a
* "falsy" value such as 0 or `undefined`), the old value is restored.
* @param {object} [options] - Optional configuration.
* @param {string} [options.className] - CSS class to apply to the input field.
* @param {number} [options.initValue=''] - Value to place as a clickable
* element within `elem` instead of entering edit mode. Should only be
* provided once for a specified `elem`.
* @param {number} [options.decimalPlaces=2] - Number of decimal places to
* display when the value is restored.
*
* @example
* HTML:
* <span id="StatisticsLimit"></span>
*
* const update = function (value) {
* modbset("/Info/Autorun/StatisticsLimit", value * 1e6);
* };
*
* // Initialize with value read from ODB
* mjsonrpc_db_get_value("/Info/Autorun/StatisticsLimit").then((value) => {
* common.edit_with_callback(
* document.getElementById("StatisticsLimit"),
* update,
* {
* className: "magnet_instr_edit",
* initValue: value.result.data[0] / 1e6,
* }
* );
* });
*/
export function edit_with_callback(
elem,
update,
{ className = undefined, initValue = 'NaN', decimalPlaces = 2 } = {}
) {
function make_clickable(value) {
const clickable = document.createElement("a");
clickable.href = "javascript:void(0)";
clickable.textContent = value;
clickable.onclick = get_user_input;
elem.replaceChildren(clickable);
}
function get_user_input() {
const oldValue = elem.textContent;
const input = document.createElement("input");
input.className = className;
input.type = "text";
input.inputMode = "decimal";
input.value = oldValue;
elem.replaceChildren(input);
input.focus();
input.select();
input.onkeydown = (e) => {
if (e.key === "Enter")
run_update(input.value, oldValue);
if (e.key === "Escape")
make_clickable(oldValue);
};
input.onblur = () => run_update(input.value, oldValue);
}
function run_update(value, oldValue) {
const value_num = Number(value);
const old_value_num = Number(oldValue);
if (update(value_num) === false) {
make_clickable(old_value_num.toFixed(decimalPlaces));
} else {
make_clickable(value_num.toFixed(decimalPlaces));
}
}
make_clickable(Number(initValue).toFixed(decimalPlaces));
}
/**
* Generic data-validate limit checker: rejects values outside bounds
* given provided with data-min and data-max attributes.
*
* Use as:
* <div class="modbvalue" data-odb-editable="1"
* data-validate="validate_elem_limits" data-min="0" data-max="1000" data-unit="K"></div>
*
* A bound is optional: for undefined data-min or data-max that side is
* unbounded. If `value` is out of bounds or cannot be parsed as a float, a
* message box is displayed. Likewise, the unit is also optional
*
* @param {Number} value - value being submitted.
* @param {HTMLElement} element - modbvalue element (carries data-min/data-max).
* @param {String} unit - Optional unit like e.g. "K" which is inserted into the
* error message if given.
* @returns {boolean} true if value is within bounds, false otherwise.
*/
export function validate_elem_limits(value, element) {
return validate_limits(value, element.dataset.min, element.dataset.max, element.dataset.unit);
}
/**
* Generic limit checker: Returns if `value` is within the bounds [`min`, `max`]
* (inclusive).
*
* If one of `min` or `max` is not given or cannot be parsed as a
* float, the corresponding side is seen as unbounded. If `value` is out of
* bounds or cannot be parsed as a float, a message box is displayed.
*
* @param {Number} value - value being submitted.
* @param {Number} min - minimum bound (inclusive).
* @param {Number} max - maximum bound (inclusive).
* @param {String} unit - Optional unit like e.g. "K" which is inserted into the
* error message if given.
* @returns {boolean} true if value is within bounds, false otherwise.
*/
export function validate_limits(value, min, max, unit) {
// dlgMessage is a function provided by MIDAS
let unit_str = ".";
if (unit) {
unit_str = " " + unit;
}
const val = parseFloat(value);
if (isNaN(val)) {
dlgMessage("Undefined value", "Value must be a number", true);
return false;
}
const min_num = parseFloat(min);
const max_num = parseFloat(max);
const is_nan_min = isNaN(min);
const is_nan_max = isNaN(max);
if ((!is_nan_min && val < min_num) || (!is_nan_max && val > max_num)) {
if (is_nan_min) {
dlgMessage("Out of range", "Value must not be larger than " + max_num + unit_str + ".", true);
} else if (is_nan_max) {
dlgMessage("Out of range", "Value must not be smaller than " + min_num + unit_str + ".", true);
} else {
dlgMessage("Out of range", "Value must be between " + min_num + unit_str + " and " + max_num + unit_str + ".", true);
}
return false;
}
return true;
}