Next-Signal / nlui.js
Lamapi's picture
Publish Next-Signal space
298a39f verified
Raw History Blame Contribute Delete
5.89 kB
/* nlui.js: small DOM and canvas helpers shared by Next Lab Spaces. */
(function (root) {
"use strict";
const $ = id => document.getElementById(id);
function h(tag, attrs, ...kids) {
const e = document.createElement(tag);
for (const k in attrs || {}) {
if (k === "class") e.className = attrs[k];
else if (k.startsWith("on")) e.addEventListener(k.slice(2), attrs[k]);
else if (k === "html") e.innerHTML = attrs[k];
else e.setAttribute(k, attrs[k]);
}
for (const c of kids.flat()) if (c != null) e.append(c.nodeType ? c : document.createTextNode(String(c)));
return e;
}
const css = name => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
const fmt = (v, d = 3) => (v == null || !isFinite(v) ? "–" : Number(v).toFixed(d));
function grayImage(canvas, data, w, h, scale, opts) {
opts = opts || {};
canvas.width = w * scale; canvas.height = h * scale;
const ctx = canvas.getContext("2d");
const img = ctx.createImageData(w, h);
let lo = opts.lo != null ? opts.lo : 0, hi = opts.hi != null ? opts.hi : 1;
for (let i = 0; i < w * h; i++) {
const v = Math.max(0, Math.min(255, Math.round(255 * (data[i] - lo) / (hi - lo || 1))));
img.data[4 * i] = img.data[4 * i + 1] = img.data[4 * i + 2] = v; img.data[4 * i + 3] = 255;
}
const tmp = document.createElement("canvas"); tmp.width = w; tmp.height = h;
tmp.getContext("2d").putImageData(img, 0, 0);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tmp, 0, 0, w * scale, h * scale);
return ctx;
}
function rgbImage(canvas, data, w, h, scale) { // data: CHW in [0,1]
canvas.width = w * scale; canvas.height = h * scale;
const ctx = canvas.getContext("2d");
const img = ctx.createImageData(w, h), n = w * h;
for (let i = 0; i < n; i++) {
for (let c = 0; c < 3; c++) img.data[4 * i + c] = Math.max(0, Math.min(255, Math.round(255 * data[c * n + i])));
img.data[4 * i + 3] = 255;
}
const tmp = document.createElement("canvas"); tmp.width = w; tmp.height = h;
tmp.getContext("2d").putImageData(img, 0, 0);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tmp, 0, 0, w * scale, h * scale);
return ctx;
}
// series: [{name, color, points: [[x,y],...], dash}]
function lineChart(canvas, series, opts) {
opts = opts || {};
const W = canvas.clientWidth || 600, H = opts.height || 240, dpr = window.devicePixelRatio || 1;
canvas.width = W * dpr; canvas.height = H * dpr; canvas.style.height = H + "px";
const ctx = canvas.getContext("2d"); ctx.scale(dpr, dpr);
const m = { l: 46, r: 10, t: 10, b: 34 };
let xs = [], ys = [];
for (const s of series) for (const [x, y] of s.points) { if (isFinite(y)) { xs.push(x); ys.push(y); } }
if (opts.hlines) for (const hl of opts.hlines) ys.push(hl.y);
let x0 = opts.xmin != null ? opts.xmin : Math.min(...xs), x1 = opts.xmax != null ? opts.xmax : Math.max(...xs);
let y0 = opts.ymin != null ? opts.ymin : Math.min(...ys), y1 = opts.ymax != null ? opts.ymax : Math.max(...ys);
if (y1 - y0 < 1e-9) { y0 -= 1; y1 += 1; }
if (x1 - x0 < 1e-9) x1 = x0 + 1;
const X = x => m.l + (x - x0) / (x1 - x0) * (W - m.l - m.r);
const Y = y => H - m.b - (y - y0) / (y1 - y0) * (H - m.t - m.b);
ctx.font = "11px system-ui"; ctx.fillStyle = css("--muted"); ctx.strokeStyle = css("--line"); ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = y0 + (y1 - y0) * i / 4;
ctx.beginPath(); ctx.moveTo(m.l, Y(y)); ctx.lineTo(W - m.r, Y(y)); ctx.stroke();
ctx.fillText(Math.abs(y) >= 100 ? y.toFixed(0) : y.toFixed(2), 4, Y(y) + 4);
}
for (let i = 0; i <= 4; i++) {
const x = x0 + (x1 - x0) * i / 4;
ctx.fillText(Math.abs(x) >= 100 || Number.isInteger(x) ? x.toFixed(0) : x.toFixed(1), X(x) - 8, H - m.b + 14);
}
if (opts.xlabel) ctx.fillText(opts.xlabel, W / 2 - 30, H - 4);
if (opts.hlines) for (const hl of opts.hlines) {
ctx.setLineDash([4, 4]); ctx.strokeStyle = hl.color || css("--muted");
ctx.beginPath(); ctx.moveTo(m.l, Y(hl.y)); ctx.lineTo(W - m.r, Y(hl.y)); ctx.stroke(); ctx.setLineDash([]);
}
for (const s of series) {
ctx.strokeStyle = s.color; ctx.lineWidth = s.width || 2; ctx.setLineDash(s.dash || []);
ctx.beginPath(); let first = true;
for (const [x, y] of s.points) { if (!isFinite(y)) continue; if (first) ctx.moveTo(X(x), Y(y)); else ctx.lineTo(X(x), Y(y)); first = false; }
ctx.stroke(); ctx.setLineDash([]);
}
return { X, Y, ctx };
}
function legend(el, series) {
el.innerHTML = "";
for (const s of series) el.append(h("span", { class: "small", style: "margin-right:12px;white-space:nowrap" },
h("span", { style: `display:inline-block;width:14px;height:3px;background:${s.color};vertical-align:middle;margin-right:4px` }), s.name));
}
async function loadAssets(core) {
const assets = {};
for (const name of core.ASSETS) {
const r = await fetch(name);
if (!r.ok) throw new Error("cannot load " + name);
assets[name] = await r.json();
}
return assets;
}
// Standard bootstrap: load assets, init core, expose __parity for automated tests.
async function boot(core, start) {
try {
const assets = await loadAssets(core);
const ctx = core.init(assets);
const parity = await (await fetch("parity_cases.json")).json();
root.__parity = () => NLRT.runParity(core, ctx, parity);
await start(ctx, assets);
root.__ready = true;
} catch (e) {
console.error(e); root.__error = String(e && e.stack || e);
const s = document.getElementById("status"); if (s) s.textContent = "Failed to start: " + e;
}
}
root.NLUI = { $, h, css, fmt, grayImage, rgbImage, lineChart, legend, boot };
})(typeof self !== "undefined" ? self : this);