const $ = (id) => document.getElementById(id); const canvas = $("canvas"), ctx = canvas.getContext("2d"); const MIN = 0.01; // smallest rectangle, as a fraction of the view /** Everything that belongs to one photo. The tray you are not looking at keeps its own copy of all of it in S.tray - the two trays are detected separately, because a label photo is framed and sized differently and the X-ray's boxes do not fit it. Only the lattice (rows, cols), the names and the text areas are shared. */ const OWN = ["imageId", "img", "rects", "centers", "found", "angle", "boxPct", "imgW", "imgH", "frame", "adjust", "pinned", "base"]; /** Where the grid sliders sit when they describe the boxes as detected: shifts add, everything else multiplies. */ const NEUTRAL = { dx: 0, dy: 0, scale: 1, gapx: 1, gapy: 1, rot: 0 }; const blank = () => ({ imageId: null, img: null, rects: [], centers: [], found: [], angle: 0, boxPct: 100, imgW: 0, imgH: 0, frame: [0, 0, 1, 1], adjust: { ...NEUTRAL }, pinned: new Set(), base: null }); const S = { phase: "upload", rows: 2, cols: 3, target: 6, view: "xray", names: [], conf: [], unassigned: [], drag: null, textRects: [], textPinned: new Set(), box: null, seeds: [], focus: null, hover: null, tray: {}, // { xray, label } - whichever one is off screen ...blank(), }; /** One tray's state, on screen or not. */ const trayOf = (view) => (view === S.view ? S : S.tray[view] || blank()); /** A number the operator typed into `id`, or null for an empty box. */ const typed = (id) => clamp(Math.round(+$(id).value) || 0, 0, 50) || null; /** Whether this tray's lattice is the X-ray's rather than its own. */ const heldToXray = () => S.view !== "xray" && trayOf("xray").rects.length > 0; /** The lattice to detect against: the operator's rows and columns if they gave any, otherwise banded off the samples. Tray 2 gets neither - it is held to the X-ray's lattice, because cell (r, c) has to mean the same specimen on both photos: the names and the text areas are shared and indexed by it, so tray 2 inferring its own 3x5 against the X-ray's 4x6 is not a smaller grid, it is a different tray. */ const lattice = () => { if (heldToXray()) return { rows: S.rows, cols: S.cols }; const r = typed("rows"), c = typed("cols"); // one of the two is enough: the other follows from how many specimens there are. // The server infers both unless it gets both, so half an answer would be ignored. return { rows: r || (c && Math.ceil(S.target / c)) || null, cols: c || (r && Math.ceil(S.target / r)) || null }; }; /* ---------- helpers ---------- */ const setStatus = (msg, kind = "") => { $("status").textContent = msg; $("status").className = "status " + kind; }; const clamp = (v, lo, hi) => (hi < lo ? (lo + hi) / 2 : Math.min(Math.max(v, lo), hi)); /** Every method card's start button: nothing runs before a photo is uploaded. */ const enableStart = (on) => ["btnDetect", "btnSeed", "btnUniform"] .forEach((id) => { $(id).disabled = !on; }); /** What the server actually said, as a sentence - FastAPI wraps it in {detail}, and a validation error nests it one deeper. Anything else falls back to raw text. */ async function detail(res) { const text = await res.text(); try { const d = JSON.parse(text).detail; if (typeof d === "string") return d; if (Array.isArray(d)) return d.map((e) => e.msg || JSON.stringify(e)).join("; "); } catch { /* not JSON */ } return text.slice(0, 200); } /** A fetch that never reached the server throws a TypeError with no useful message ("Load failed" in Safari, "Failed to fetch" in Chrome). That is nearly always the connection dropping under a request - the dev server restarts on every file save - so retry once before blaming the operator, and say what happened if it fails again. */ async function send(path, init) { for (let attempt = 0; ; attempt++) { try { const res = await fetch(path, init); if (res.ok) return res; throw new Error(await detail(res)); } catch (e) { if (!(e instanceof TypeError)) throw e; if (attempt) throw new Error("the connection to the server dropped. If it is still " + "restarting, wait a moment and pick the file again."); } } } const api = (path, body, method = "POST") => send(path, { method, headers: body ? { "Content-Type": "application/json" } : {}, body: body ? JSON.stringify(body) : undefined, }); const loadImg = (src) => new Promise((ok, no) => { const im = new Image(); im.onload = () => ok(im); im.onerror = () => no(new Error("image failed to load")); im.src = src; }); const evPos = (e) => { const r = canvas.getBoundingClientRect(); return { x: (e.clientX - r.left) / r.width, y: (e.clientY - r.top) / r.height }; }; /** A blank slot has no dot, but keeps a handle at its rectangle's centre so it can be clicked back on. */ const rectCentre = (r, c) => { const [x0, y0, x1, y1] = S.rects[r][c]; return [(x0 + x1) / 2, (y0 + y1) / 2]; }; const isBlank = (r, c) => S.centers.length > 0 && !S.centers[r]?.[c]; const dotAt = (r, c) => S.centers[r]?.[c] || rectCentre(r, c); const activeCells = () => S.centers.flat().filter(Boolean).length; /** An empty slot is named "-", which is what keeps it out of the export. It does *not* touch the count box. That box is what the operator states about the tray, not a readout of what came back: writing the active-cell count into it let a detect that missed a specimen lower the number, and the next detect then asked for the lower one - a ratchet, down, every press. What was found is in the status line. */ function syncBlanks() { S.names.forEach((row, r) => row.forEach((name, c) => { if (isBlank(r, c)) S.names[r][c] = "-"; else if (name.trim() === "-") S.names[r][c] = ""; })); } /** The four sliding lines, as the quad the server crops to. Everything past them is tray, table and floor - cutting it out is what makes the samples big on screen. */ const frameOf = (view) => { const [x0, y0, x1, y1] = trayOf(view).frame || [0, 0, 1, 1]; return [[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; }; const grid = () => ({ image_id: S.imageId, corners: frameOf(S.view), rows: S.rows, cols: S.cols, angle: S.angle, rects: S.rects, // text_rects deliberately absent: only /api/crop reads them, and every payload is // validated against the rows x cols in the same request. Detection is where the // lattice *changes*, so sending the old shape there is a guaranteed 422. }); /** The cell a text box belongs to: the one it sits in, else the nearest - a label often sits beside its specimen rather than inside its rectangle. */ function ownerCell(x, y) { let best = null, d = Infinity; for (let r = 0; r < S.rows; r++) for (let c = 0; c < S.cols; c++) { if (isBlank(r, c)) continue; // an empty slot is never cropped, text and all const [x0, y0, x1, y1] = S.rects[r][c]; if (x >= x0 && x <= x1 && y >= y0 && y <= y1) return [r, c]; const q = Math.hypot((x0 + x1) / 2 - x, (y0 + y1) / 2 - y); if (q < d) { d = q; best = [r, c]; } } return best; } const textCount = () => S.textRects.flat().filter(Boolean).length; /* ---------- drawing ---------- */ /** Size the canvas to the window, not just to its width. Capping width alone is what made a tall tray run off the bottom of the page: a portrait photo simply became a very tall canvas. Both axes are capped now, by the same scale, so the whole tray is on screen at once and nothing is squashed. The element's pixel size *is* its displayed size - no CSS scaling - because every pointer position is read back through getBoundingClientRect(), and a canvas whose backing store and box disagree puts every dot in the wrong place. Detail lost here costs nothing: cropping happens server-side on the original. */ function room() { const wrap = $("canvasWrap"); const top = wrap.getBoundingClientRect().top; const down = top > 0 && top < window.innerHeight // ...unless the page is scrolled past it ? window.innerHeight - top : window.innerHeight * 0.7; return { w: Math.max(240, wrap.clientWidth - 22), h: Math.max(240, down - 28) }; } function fitCanvas(img) { const { w: maxW, h: maxH } = room(); $("canvasWrap").style.minHeight = `${maxH}px`; // centre in a window that does not resize const scale = Math.min(1, maxW / img.naturalWidth, maxH / img.naturalHeight); canvas.width = Math.round(img.naturalWidth * scale); canvas.height = Math.round(img.naturalHeight * scale); } /** A resized window is a different amount of room; refit rather than scroll. */ let refit; window.addEventListener("resize", () => { clearTimeout(refit); refit = setTimeout(() => { if (!S.img) return paintTray(); // no photo yet: just refit the placeholder fitCanvas(S.img); draw(); drawThumbs(); }, 120); }); function draw() { if (!S.img) return; const { width: W, height: H } = canvas; ctx.drawImage(S.img, 0, 0, W, H); if (S.phase === "frame") { canvas.classList.remove("grid"); const [fx0, fy0, fx1, fy1] = S.frame; ctx.fillStyle = "rgba(8, 12, 18, .66)"; // everything outside is being cut away ctx.fillRect(0, 0, W, fy0 * H); ctx.fillRect(0, fy1 * H, W, H - fy1 * H); ctx.fillRect(0, fy0 * H, fx0 * W, (fy1 - fy0) * H); ctx.fillRect(fx1 * W, fy0 * H, W - fx1 * W, (fy1 - fy0) * H); ctx.strokeStyle = "#4da3ff"; ctx.lineWidth = 2; ctx.setLineDash([]); ctx.strokeRect(fx0 * W, fy0 * H, (fx1 - fx0) * W, (fy1 - fy0) * H); ctx.fillStyle = "#4da3ff"; // a grab bar in the middle of each line const mx = (fx0 + fx1) / 2 * W, my = (fy0 + fy1) / 2 * H; ctx.fillRect(mx - 16, fy0 * H - 2, 32, 4); ctx.fillRect(mx - 16, fy1 * H - 2, 32, 4); ctx.fillRect(fx0 * W - 2, my - 16, 4, 32); ctx.fillRect(fx1 * W - 2, my - 16, 4, 32); return; } if (S.phase === "seeding") { canvas.classList.remove("grid"); ctx.font = "bold 11px sans-serif"; ctx.textAlign = "center"; S.seeds.forEach(([x, y], i) => { ctx.fillStyle = "#46c07a"; ctx.beginPath(); ctx.arc(x * W, y * H, 9, 0, 7); ctx.fill(); ctx.fillStyle = "#08111c"; ctx.fillText(i + 1, x * W, y * H + 4); }); return; } canvas.classList.toggle("grid", S.phase !== "text" && S.phase !== "draw"); ctx.font = "13px system-ui"; ctx.textAlign = "center"; S.rects.forEach((row, r) => row.forEach(([x0, y0, x1, y1], c) => { const held = S.drag && S.drag.r === r && S.drag.c === c; const conf = S.conf[r]?.[c] ?? 0; ctx.lineWidth = held ? 3 : 2; if (isBlank(r, c)) { // an empty slot: outlined so you can click it back on ctx.setLineDash([5, 5]); ctx.strokeStyle = "#4a5260"; ctx.strokeRect(x0 * W, y0 * H, (x1 - x0) * W, (y1 - y0) * H); ctx.setLineDash([]); return; } ctx.strokeStyle = held ? "#46c07a" : conf && conf < 70 ? "#e0a33a" : "#4da3ff"; ctx.strokeRect(x0 * W, y0 * H, (x1 - x0) * W, (y1 - y0) * H); ctx.fillStyle = held ? "rgba(70,192,122,.12)" : "rgba(77,163,255,.06)"; ctx.fillRect(x0 * W, y0 * H, (x1 - x0) * W, (y1 - y0) * H); const label = (S.names[r]?.[c] || "").trim(); if (!label) return; const px = (x0 + x1) / 2 * W, py = (y0 + y1) / 2 * H, tw = ctx.measureText(label).width; ctx.fillStyle = "rgba(0,0,0,.7)"; ctx.fillRect(px - tw / 2 - 5, py - 11, tw + 10, 18); ctx.fillStyle = conf && conf < 70 ? "#e0a33a" : "#e6e9ef"; ctx.fillText(label, px, py + 3); })); if (S.focus && S.rects[S.focus.r]?.[S.focus.c]) { // the row being typed into const [x0, y0, x1, y1] = S.rects[S.focus.r][S.focus.c]; ctx.strokeStyle = "#46c07a"; ctx.lineWidth = 3; ctx.strokeRect(x0 * W, y0 * H, (x1 - x0) * W, (y1 - y0) * H); } if (S.hover && S.rects[S.hover.r]) { // grips, so the corners are findable const [x0, y0, x1, y1] = S.rects[S.hover.r][S.hover.c]; ctx.fillStyle = "#46c07a"; [[x0, y0], [x1, y0], [x1, y1], [x0, y1]].forEach(([x, y]) => ctx.fillRect(x * W - 4, y * H - 4, 8, 8)); } if (S.centers.length) S.rects.forEach((row, r) => row.forEach((_, c) => { const held = S.drag && S.drag.dot && S.drag.r === r && S.drag.c === c; const [x, y] = dotAt(r, c), blank = isBlank(r, c); ctx.beginPath(); ctx.arc(x * W, y * H, held ? 8 : 5, 0, 7); ctx.fillStyle = blank ? "rgba(20,23,28,.55)" : held ? "#46c07a" : S.found[r]?.[c] === false ? "#e0a33a" : "#4da3ff"; ctx.fill(); ctx.strokeStyle = blank ? "#8b93a1" : "rgba(0,0,0,.6)"; ctx.lineWidth = 1.5; ctx.stroke(); })); ctx.setLineDash([4, 3]); ctx.lineWidth = 2; ctx.strokeStyle = "#e0a33a"; S.textRects.forEach((row, r) => row.forEach((t, c) => { if (t && !isBlank(r, c)) ctx.strokeRect(t[0] * W, t[1] * H, (t[2] - t[0]) * W, (t[3] - t[1]) * H); })); if (S.box) { ctx.strokeStyle = "#46c07a"; ctx.strokeRect(Math.min(S.box.x0, S.box.x1) * W, Math.min(S.box.y0, S.box.y1) * H, Math.abs(S.box.x1 - S.box.x0) * W, Math.abs(S.box.y1 - S.box.y0) * H); } ctx.setLineDash([]); if (S.view === "label") S.unassigned.forEach((u) => { ctx.fillStyle = "#e0a33a"; ctx.beginPath(); ctx.arc(u.x * W, u.y * H, 5, 0, 7); ctx.fill(); }); } /* ---------- upload ---------- */ /** A photo for the tray named. The X-ray is tray 1 and resets everything; the label photo is tray 2 and touches nothing the X-ray found. */ async function handleFile(file, view = "xray") { if (!file) return; switchTray(view); setStatus("Uploading…"); try { const info = await upload(file); if (view === "xray") { // a new X-ray is a new job: tray 2 goes with it S.tray = {}; S.names = []; S.textRects = []; S.textPinned = new Set(); } S.imageId = info.image_id; S.imgW = info.width; S.imgH = info.height; await startTray(); } catch (e) { setStatus("Upload failed: " + e.message, "err"); } } async function upload(file) { const fd = new FormData(); fd.append("file", file); return (await send("/api/upload", { method: "POST", body: fd })).json(); } /** A fresh photo on the tray you are looking at: the whole frame is the grid area. */ async function startTray() { S.phase = "detect"; S.rects = []; S.centers = []; S.found = []; S.angle = 0; S.conf = []; S.unassigned = []; S.frame = [0, 0, 1, 1]; S.boxPct = 100; rebase(); S.img = await loadImg(`/api/image/${S.imageId}`); fitCanvas(S.img); draw(); renderChips(); enableStart(true); $("btnGrow").disabled = true; $("btnGrow").classList.remove("stale"); $("btnCrop").disabled = !trayOf("xray").rects.length; paintTray(); document.querySelectorAll(".boxInfo").forEach((el) => { el.textContent = ""; }); setStatus(`Tray ${S.view === "xray" ? "1" : "2"} loaded. If there is table or floor ` + "around the tray, press Adjust frame and slide the four lines in first — it makes " + "the samples bigger and much easier to find. Then say how many there are and detect."); } /** Four sliding lines on the original photo: everything outside them is cut away before anything else happens, so the samples get the whole working window instead of sharing it with the table the tray is standing on. */ /** Slide one framing line, never past the one facing it. i is 0,1,2,3 = left, top, right, bottom - the same order the rectangle edges use. */ function moveFrameLine(i, v) { v = clamp(v, 0, 1); if (i === 0) S.frame[0] = Math.min(v, S.frame[2] - MIN); else if (i === 1) S.frame[1] = Math.min(v, S.frame[3] - MIN); else if (i === 2) S.frame[2] = Math.max(v, S.frame[0] + MIN); else S.frame[3] = Math.max(v, S.frame[1] + MIN); } async function toggleFrame() { const btn = $("btnFrame"); if (S.phase === "frame") { btn.textContent = "Adjust frame"; btn.classList.remove("stale"); const moved = S.frame.join() !== S.frameWas.join(); if (moved) { // the boxes were placed on a view that no longer exists S.rects = []; S.centers = []; S.found = []; S.conf = []; S.angle = 0; } S.phase = "detect"; S.img = await rectified(S.imageId); fitCanvas(S.img); draw(); paintTray(); setStatus(moved ? "Framed. Detect the samples again on the cropped view." : "Frame unchanged.", moved ? "" : "ok"); return; } S.frameWas = [...S.frame]; S.phase = "frame"; btn.textContent = "Done framing"; btn.classList.add("stale"); S.img = await loadImg(`/api/image/${S.imageId}`); // the original, uncropped fitCanvas(S.img); draw(); setStatus("Drag the four lines in to cut away everything that is not the tray — what " + "is left fills the working window, so the samples come out bigger."); } /* ---------- detect ---------- */ /** The only thing the operator states: how many samples are on this tray. The rows and columns come back from detection, read off where the samples actually are. */ function readGrid() { S.target = clamp(Math.round(+$("count").value) || 6, 1, 2500); $("count").value = S.target; ["rows", "cols"].forEach((id) => { $(id).value = typed(id) || ""; }); $("seedTarget").textContent = S.target; if (S.textRects.length && (S.textRects.length !== S.rows || S.textRects[0].length !== S.cols)) S.textRects = []; // a new lattice: the old text areas no longer address a cell return S.target; } async function detectGrid(fit) { readGrid(); setStatus("Finding specimens…"); try { const det = await (await api("/api/detect", { ...grid(), ...lattice(), rects: [], fit, count: S.target })).json(); S.rows = det.rows; S.cols = det.cols; S.angle = det.angle; S.rects = det.rects; S.found = det.found; S.centers = det.centers; rebase(); await showGrid(); const found = `${det.detected_cells}/${S.target} samples found in a ` + `${det.rows}×${det.cols} grid` + (det.tuned ? ` (the default texture settings found too few, so it retuned to ` + `${det.tuned.map((v) => v.toFixed(2)).join(" / ")})` : ""); if (det.method !== "detected") setStatus("Low contrast — placed an even grid instead. Drag the edges into place."); else if (det.clipped) setStatus(`${found}, but some sit so close the rectangles had to cut between them.`, ""); else setStatus(`${found}` + (fit === "tight" ? ", each rectangle grown from the specimen's centre until it " + "covered the specimen or met its neighbour" : "") + (S.view === "label" ? ". Line the boxes up with the labels, then press Read the names — you can press " + "it again after any change." : ". Drag a centre dot to move a specimen's box, or any edge to adjust it."), "ok"); } catch (e) { setStatus("Detection failed: " + e.message, "err"); } } async function rectified(imageId) { const preview = await api("/api/rectify", { ...grid(), image_id: imageId }); return loadImg(URL.createObjectURL(await preview.blob())); } async function showGrid() { S.img = await rectified(S.imageId); S.phase = "grid"; if (S.centers.length !== S.rows || S.centers[0]?.length !== S.cols) S.centers = S.rects.map((row) => row.map(([x0, y0, x1, y1]) => [(x0 + x1) / 2, (y0 + y1) / 2])); if (S.names.length !== S.rows || S.names[0]?.length !== S.cols) S.names = Array.from({ length: S.rows }, () => Array(S.cols).fill("")); if (S.textRects.length !== S.rows || S.textRects[0]?.length !== S.cols) S.textRects = Array.from({ length: S.rows }, () => Array(S.cols).fill(null)); syncBlanks(); fitCanvas(S.img); draw(); renderTable(); sizeInfo(); $("btnCrop").disabled = !trayOf("xray").rects.length; $("btnGrow").disabled = false; $("btnText").textContent = "Select text areas"; $("btnText").classList.remove("stale"); if (S.view === "label") fillStrips(); paintTray(); } /** Put the X-ray's grid on the label photo, instead of detecting one there. Measured on a real tray: the X-ray gives 21 of 21 specimens, the label photo of the same tray gives 12 - its blocks are light on a light bench and carry no texture the detector can hold on to. But the two photos show the same tray in the same order, so the grid is already known. It comes over as-is and the grid sliders line it up, which is one shift and one scale rather than 21 rectangles dragged by hand. Cell (r, c) means the same specimen either way, which is the whole point: the names and the strips are indexed by it. */ async function inheritGrid() { const xray = trayOf("xray"); if (!xray.rects.length) return setStatus("Detect the X-ray tray first.", "err"); S.rects = xray.rects.map((row) => row.map((q) => [...q])); S.centers = xray.centers.map((row) => row.map((q) => q && [...q])); S.found = xray.found.map((row) => [...row]); rebase(); await showGrid(); fillStrips(); setStatus(`The X-ray's ${S.rows}\u00d7${S.cols} grid is now on this photo. Line it up with ` + "Move the whole grid — shift and scale first — then drag any box that is still off.", "ok"); } /* ---------- the two trays ---------- */ /** Show one tray. The other's boxes are put away untouched, not thrown away. */ function switchTray(view) { if (view === S.view) return; S.tray[S.view] = Object.fromEntries(OWN.map((k) => [k, S[k]])); const held = S.tray[view] || blank(); // a layout from an older lattice cannot be drawn against the current one - every // loop here runs r < S.rows, c < S.cols and would walk off the end of its rows const fits = !held.rects.length || (held.rects.length === S.rows && held.rects[0]?.length === S.cols); OWN.forEach((k) => { S[k] = fits ? held[k] : blank()[k]; }); if (!fits) { S.imageId = held.imageId; S.img = held.img; S.imgW = held.imgW; S.imgH = held.imgH; } S.view = view; S.phase = S.imageId ? (S.rects.length ? "grid" : "detect") : "upload"; S.box = null; S.drag = null; S.hover = null; enableStart(!!S.imageId); $("btnGrow").disabled = !S.centers.length; showBoxPct(); showAdjust(); paintTray(); if (S.img) fitCanvas(S.img); else { canvas.width = 16; canvas.height = 16; } sizeInfo(); draw(); drawThumbs(); } /** The left panel carries the options of the tray on screen, and nothing else. */ /** The two slots hold their space from the start: a photo lands *inside* one, so nothing below it ever moves. A slot is also how you pick which tray you edit. */ function paintTray() { const label = S.view === "label"; // one tray at a time, all the way down: its button, its photo, its options $("modeXray").classList.toggle("on", !label); $("modeLabel").classList.toggle("on", label); // the upload target and the working window are one area: the placeholder is what // that window shows until a photo is in it, at the size the photo will be given const empty = !S.imageId; const zone = $("dropZone"); zone.hidden = !empty; canvas.hidden = empty; if (empty) { const { w, h } = room(); zone.style.width = `${w}px`; zone.style.height = `${h}px`; } $("btnPhoto").textContent = empty ? "Select photo" : "Change photo"; $("outputPanel").hidden = label; // cropping is the X-ray tray's business $("namesPanel").hidden = !label; $("trayTitle").textContent = label ? "label tray" : "X-ray tray"; $("btnText").disabled = $("btnReread").disabled = $("btnDraw").disabled = !S.rects.length; // tray 2 is held to the X-ray's lattice, so typing one here would be ignored $("rows").disabled = $("cols").disabled = heldToXray(); if (!label && S.phase === "draw") toggleDraw(); // it is the names tray's tool $("btnFrame").disabled = !S.imageId; // tray 2's own detection reads its blocks badly; the X-ray's grid is the better start $("btnInherit").hidden = !label; $("btnInherit").disabled = !S.imageId || !trayOf("xray").rects.length; $("hint").textContent = !S.imageId ? (label ? "Click the Tray 2 slot above to upload the shot where the writing is readable." : "Click the Tray 1 slot above to upload the X-ray of the tray.") : !S.rects.length ? "Detect this photo's boxes with one of the methods on the left." : label ? "These boxes belong to this photo alone — the names are read, and the label crops " + "cut, with them. Drag a dot or an edge; the X-ray's boxes do not move." : "Drag a centre dot onto its specimen, or click a dot to empty that slot (dashed = " + "empty, not exported), then press Create rectangles from dots — each one grows until " + "it meets a neighbour's rectangle or the next specimen. Drag an edge to fine-tune; " + "edges stop at their neighbour."; } function sizeInfo() { if (!S.img || !S.rects.length) return; const w = S.img.naturalWidth, h = S.img.naturalHeight; const px = S.rects.flat().map(([x0, y0, x1, y1]) => [Math.round((x1 - x0) * w), Math.round((y1 - y0) * h)]); const same = px.every(([a, b]) => a === px[0][0] && b === px[0][1]); const info = same ? `${px[0][0]}×${px[0][1]} px per crop` + (S.angle ? ` · tilt ${S.angle.toFixed(1)}°` : "") : `${Math.min(...px.map((p) => p[0]))}–${Math.max(...px.map((p) => p[0]))} × ` + `${Math.min(...px.map((p) => p[1]))}–${Math.max(...px.map((p) => p[1]))} px` + (S.angle ? ` · tilt ${S.angle.toFixed(1)}°` : ""); document.querySelectorAll(".boxInfo").forEach((el) => { el.textContent = info; }); if (S.view !== "xray") return; // tray 2's boxes crop labels, not the export $("outW").value = Math.min(2048, Math.max(...px.map((p) => p[0]))); $("outH").value = Math.min(2048, Math.max(...px.map((p) => p[1]))); $("keepAspect").checked = !same; } /* ---------- canvas interaction ---------- */ /** What is under the pointer: a corner, an edge, or the body of a rectangle. ex/ey are -1 (low edge), 0 (neither) or 1 (high edge). Both set is a corner and moves two edges at once; one set is a plain edge; neither, but inside, picks the whole rectangle up. A corner wins over an edge, and an edge over a body, so the finer handle is always reachable. */ function hitHandle(p, tol) { let edge = null, body = null; for (let r = 0; r < S.rows; r++) for (let c = 0; c < S.cols; c++) { const [x0, y0, x1, y1] = S.rects[r][c]; if (p.x < x0 - tol || p.x > x1 + tol || p.y < y0 - tol || p.y > y1 + tol) continue; const ex = Math.abs(p.x - x0) < tol ? -1 : Math.abs(p.x - x1) < tol ? 1 : 0; const ey = Math.abs(p.y - y0) < tol ? -1 : Math.abs(p.y - y1) < tol ? 1 : 0; if (ex && ey) return { r, c, ex, ey }; if ((ex || ey) && !edge) edge = { r, c, ex, ey }; if (!ex && !ey && !body) body = { r, c, ex: 0, ey: 0, move: true }; } return edge || body; } const CURSOR = { "-1,-1": "nwse-resize", "1,1": "nwse-resize", "-1,1": "nesw-resize", "1,-1": "nesw-resize", "-1,0": "ew-resize", "1,0": "ew-resize", "0,-1": "ns-resize", "0,1": "ns-resize", "0,0": "move" }; /** Which centre dot is under the pointer, if any. Dots win over edges: they sit inside the rectangle, the edges are at its rim. */ function hitDot(p) { const box = canvas.getBoundingClientRect(); if (!S.centers.length || !S.rects.length) return null; for (let r = 0; r < S.rows; r++) for (let c = 0; c < S.cols; c++) { const [x, y] = dotAt(r, c); if (Math.hypot((p.x - x) * box.width, (p.y - y) * box.height) < 12) return { r, c, dot: true, x0: p.x, y0: p.y }; } return null; } canvas.addEventListener("pointerdown", (e) => { const p = evPos(e); if (S.phase === "seeding") { if (S.seeds.length >= S.target) return; S.seeds.push([p.x, p.y]); draw(); return seedsLeft(); } if (S.phase === "frame") { const tol = 12 / canvas.getBoundingClientRect().width; const near = [[0, Math.abs(p.x - S.frame[0])], [2, Math.abs(p.x - S.frame[2])], [1, Math.abs(p.y - S.frame[1])], [3, Math.abs(p.y - S.frame[3])]] .filter(([, d]) => d < tol).sort((a, b) => a[1] - b[1])[0]; if (near) { S.drag = { line: near[0] }; canvas.setPointerCapture(e.pointerId); } return; } if (S.phase === "text" || S.phase === "draw") { S.box = { x0: p.x, y0: p.y, x1: p.x, y1: p.y }; canvas.setPointerCapture(e.pointerId); return; } S.drag = hitDot(p) || hitHandle(p, 8 / canvas.getBoundingClientRect().width); if (S.drag) { const [x0, y0] = S.rects[S.drag.r][S.drag.c]; S.drag.grab = { dx: p.x - x0, dy: p.y - y0 }; // where inside the box you took hold canvas.setPointerCapture(e.pointerId); draw(); } }); /** How far an edge may move before its rectangle would touch any other. Checked against every rectangle, not just the lattice neighbour: rows can be cut per column, so the rectangle in your way is not always the obvious one. The layout starts disjoint and every move is clamped, so it stays disjoint. */ function limitEdge(r, c, edge, v) { const me = S.rects[r][c]; const others = S.rects.flatMap((row, rr) => row.filter((_, cc) => rr !== r || cc !== c)); const across = edge === 0 || edge === 2; const hit = across ? others.filter((q) => q[1] < me[3] && me[1] < q[3]) : others.filter((q) => q[0] < me[2] && me[0] < q[2]); const [lo, hi] = edge === 0 ? [Math.max(0, ...hit.filter((q) => q[2] <= me[0]).map((q) => q[2])), me[2] - MIN] : edge === 2 ? [me[0] + MIN, Math.min(1, ...hit.filter((q) => q[0] >= me[2]).map((q) => q[0]))] : edge === 1 ? [Math.max(0, ...hit.filter((q) => q[3] <= me[1]).map((q) => q[3])), me[3] - MIN] : [me[1] + MIN, Math.min(1, ...hit.filter((q) => q[1] >= me[3]).map((q) => q[1]))]; // no room at all - a neighbour is closer than MIN. Stay put rather than take // clamp's midpoint, which would put this edge past the one facing it and hand // the layout back an inverted rectangle the next request refuses to accept. return hi < lo ? me[edge] : clamp(v, lo, hi); } /** How far a whole rectangle may be dragged before it would touch another. Same reasoning as limitEdge, one axis at a time: clamp x against the rectangles that overlap the row band it is moving into, then y against those in the new column band. Pointer moves arrive in small steps, so clamping each step keeps a disjoint layout disjoint. */ function limitMove(r, c, nx0, ny0) { const [x0, y0, x1, y1] = S.rects[r][c]; const w = x1 - x0, h = y1 - y0; const others = S.rects.flatMap((row, rr) => row.filter((_, cc) => rr !== r || cc !== c)); ny0 = clamp(ny0, 0, 1 - h); const yBand = others.filter((q) => q[1] < ny0 + h && ny0 < q[3]); nx0 = clamp(clamp(nx0, 0, 1 - w), Math.max(0, ...yBand.filter((q) => q[2] <= x0).map((q) => q[2])), Math.min(1, ...yBand.filter((q) => q[0] >= x1).map((q) => q[0])) - w); const xBand = others.filter((q) => q[0] < nx0 + w && nx0 < q[2]); ny0 = clamp(ny0, Math.max(0, ...xBand.filter((q) => q[3] <= y0).map((q) => q[3])), Math.min(1, ...xBand.filter((q) => q[1] >= y1).map((q) => q[1])) - h); return [nx0, ny0]; } canvas.addEventListener("pointermove", (e) => { if (S.box) { const q = evPos(e); S.box.x1 = clamp(q.x, 0, 1); S.box.y1 = clamp(q.y, 0, 1); return draw(); } const p = evPos(e); if (S.drag && S.drag.line !== undefined) { moveFrameLine(S.drag.line, S.drag.line % 2 ? p.y : p.x); return draw(); } if (!S.drag) { // hovering: say which handle is under the pointer const tol = 8 / canvas.getBoundingClientRect().width; const h = S.rects.length && S.phase !== "text" ? hitHandle(p, tol) : null; const over = h && !hitDot(p) ? h : null; canvas.style.cursor = over ? CURSOR[`${over.ex},${over.ey}`] : ""; const same = (S.hover && over && S.hover.r === over.r && S.hover.c === over.c) || (!S.hover && !over); S.hover = over ? { r: over.r, c: over.c } : null; if (!same) draw(); return; } const { r, c, ex, ey } = S.drag; if (S.drag.dot) { const box = canvas.getBoundingClientRect(); if (Math.hypot((p.x - S.drag.x0) * box.width, (p.y - S.drag.y0) * box.height) > 3) S.drag.moved = true; // below that it is a click, and a click toggles the slot if (S.drag.moved) { S.pinned.add(`${r},${c}`); // moved by hand, so applyAdjust leaves it alone moveDot(r, c, p.x, p.y); sizeInfo(); drawThumbs(); } return draw(); } if (S.drag.move) { placeRect(r, c, ...limitMove(r, c, p.x - S.drag.grab.dx, p.y - S.drag.grab.dy)); } else { if (ex) S.rects[r][c][ex < 0 ? 0 : 2] = limitEdge(r, c, ex < 0 ? 0 : 2, p.x); if (ey) S.rects[r][c][ey < 0 ? 1 : 3] = limitEdge(r, c, ey < 0 ? 1 : 3, p.y); } sizeInfo(); draw(); drawThumbs(); }); /** Take the dot to (x, y) and its rectangle with it. A dot that walks out of its own rectangle has nothing left to say about which sample it means, so the two travel together and the box keeps its size. The move is clamped like any other, so the box cannot be pushed into a neighbour - and when it is stopped, the dot stops with it rather than sliding out. */ function moveDot(r, c, x, y) { const [ox, oy] = S.centers[r][c], b = [...S.rects[r][c]]; const [nx0, ny0] = placeRect(r, c, ...limitMove( r, c, b[0] + clamp(x, 0, 1) - ox, b[1] + clamp(y, 0, 1) - oy)); S.centers[r][c] = [clamp(ox + nx0 - b[0], 0, 1), clamp(oy + ny0 - b[1], 0, 1)]; } /** Put a rectangle down at (nx0, ny0) keeping its size, inside the view. One place builds a moved rectangle, so one place has to get the far edge right: nx0 + width can land a hair past 1 in floating point, and the next request is validated on 0 <= x0 < x1 <= 1. Returns where it actually went. */ function placeRect(r, c, nx0, ny0) { const [x0, y0, x1, y1] = S.rects[r][c]; const [ax0, ax1] = slide(nx0, nx0 + x1 - x0); const [ay0, ay1] = slide(ny0, ny0 + y1 - y0); S.rects[r][c] = [ax0, ay0, ax1, ay1]; return [ax0, ay0]; } canvas.addEventListener("pointerup", () => { if (S.box) return S.phase === "draw" ? finishDrawnBox() : finishTextBox(); const d = S.drag; S.drag = null; if (d && d.dot) { if (!d.moved) S.centers[d.r][d.c] = isBlank(d.r, d.c) ? rectCentre(d.r, d.c) : null; syncBlanks(); renderTable(); stale(); } else if (d) { S.pinned.add(`${d.r},${d.c}`); // placed by hand: the grid sliders skip it from here if (S.view === "label" && S.names.flat().some(Boolean)) // the names were read through the old boxes; these are different boxes setStatus("Boxes moved — press Read the names again to read them through the new ones."); } draw(); }); /** The rectangles no longer match the dots. Nothing regrows until you say so. */ function stale() { $("btnGrow").classList.add("stale"); $("btnGrow").closest("details").open = true; // the button it names lives in that card setStatus(`${activeCells()} specimens marked. Press Create rectangles from dots ` + "to rebuild them."); } /* ---------- click each specimen ---------- */ async function startSeeding() { readGrid(); S.seeds = []; S.img = await rectified(S.imageId); S.phase = "seeding"; $("btnGrow").disabled = true; $("btnGrow").classList.remove("stale"); fitCanvas(S.img); draw(); setStatus(`Click once on each of the ${S.target} specimens, any order. ` + (S.angle ? `Tilt ${S.angle.toFixed(1)}° already applied.` : "Run Detect first if the tray is tilted.")); } /** All dots down, or how many are still missing. The button only opens on the last one. */ function seedsLeft() { const left = S.target - S.seeds.length; $("btnGrow").disabled = left > 0; $("btnGrow").classList.toggle("stale", !left); setStatus(left ? `${S.seeds.length} marked, ${left} to go. Backspace undoes the last one.` : `All ${S.target} dots placed — press Create rectangles from dots.`, left ? "" : "ok"); } /** Regrow every rectangle from the centre dots. `points` given: the dots moved on an existing layout, so the view is unchanged and only the boxes are redrawn. */ async function applySeeds(points) { setStatus(points ? "Regrowing from the dots…" : "Growing rectangles from your marks…"); try { const det = await (await api("/api/detect", points ? { ...grid(), rects: [], fit: "tight", seeds: points } : { ...grid(), ...lattice(), rects: [], fit: "tight", points: S.seeds })).json(); S.rows = det.rows; S.cols = det.cols; S.angle = det.angle; S.rects = det.rects; S.found = det.found; S.centers = det.centers; rebase(); syncBlanks(); $("btnGrow").classList.remove("stale"); if (points) { sizeInfo(); draw(); renderTable(); } else await showGrid(); const on = activeCells(), off = on - det.detected_cells; setStatus(`${on} rectangles grown from the dots` + (off > 0 ? `, but ${off} dot(s) are not on a specimen (amber) — those stop halfway ` + "to their neighbour instead of at the next specimen" : "") + ". Drag a dot to move it, click one to empty that slot.", off > 0 ? "" : "ok"); } catch (e) { setStatus("Failed: " + e.message, "err"); } } /** Server rects arrive at full size and unmoved: they are the new base layout, so the sliders go back to neutral, nothing is pinned any more, and the operator's size knob is re-applied on top - a fresh detect must not silently hand back bigger boxes. */ const rebase = () => { S.adjust = { ...NEUTRAL }; S.pinned = new Set(); showAdjust(); S.base = { rects: S.rects.map((row) => row.map((q) => [...q])), centers: S.centers.map((row) => row.map((q) => q && [...q])) }; applyAdjust(); }; /** Put a span inside 0..1 by sliding it, never by clamping its ends separately. Clamping each end on its own is what collapsed a box that had been dragged against an edge: shrink it and both ends land on the same boundary, giving a rectangle with no height at all - which the next request refuses, a long way from the slider that caused it. */ function slide(a, b) { const len = Math.min(Math.max(b - a, MIN / 4), 1); const lo = Math.min(Math.max(a, 0), 1 - len); return [lo, lo + len]; } const showBoxPct = () => { document.querySelectorAll(".boxPct").forEach((el) => { el.value = S.boxPct; }); document.querySelectorAll(".boxPctVal").forEach((el) => { el.textContent = S.boxPct + "%"; }); }; /** Shrink every rectangle towards its centre dot. 100% is as grown - all the room there was; less is a tighter crop around the specimen. */ function setBoxPct(pct) { S.boxPct = clamp(Math.round(pct), 10, 100); showBoxPct(); applyAdjust(); } /* ---------- the whole grid at once ---------- */ /** Rebuild every rectangle from the layout as it was detected. Detection puts the boxes where the samples are. On the label photo the writing sits off from where the sample was, and the whole grid is then out by one shift, one spread or one small turn - dragging twelve boxes one at a time is the slow way to say that. Every control is absolute, read off the *base* layout rather than off whatever is on screen: spread, scale, turn, shift, and then the size knob shrinking each box towards its own dot. Deltas were the obvious way and they are wrong - each slider would turn the grid about a centre the one before it had moved, so putting them all back left the grid a few percent from where it started. This way any order of any sliders gives the same layout, and neutral is neutral. A box placed by hand is pinned and skipped: it is the one box already where the operator wants it. ponytail: nothing here is clamped against a neighbour. A global move that clamps one box is no longer a global move, and boxes_px trims lattice-adjacent pairs when it cuts, so even a scaled-up grid still exports disjoint crops. */ function applyAdjust() { const b = S.base, m = S.adjust, p = S.boxPct / 100; if (!b || !S.rects.length || b.rects.length !== S.rects.length) return; // the turn happens in the view's own shape: x and y are both 0..1 here, so rotating // them straight would shear the grid by the photo's aspect ratio const a = canvas.width / canvas.height || 1; const t = m.rot * Math.PI / 180, cos = Math.cos(t), sin = Math.sin(t); const mid = b.rects.flat().map(([x0, y0, x1, y1]) => [(x0 + x1) / 2, (y0 + y1) / 2]); const gx = mid.reduce((sum, q) => sum + q[0], 0) / mid.length; const gy = mid.reduce((sum, q) => sum + q[1], 0) / mid.length; const map = ([x, y]) => { const ox = (x - gx) * a * m.gapx * m.scale, oy = (y - gy) * m.gapy * m.scale; return [gx + (ox * cos - oy * sin) / a + m.dx / 100, gy + (ox * sin + oy * cos) + m.dy / 100]; }; S.rects = b.rects.map((row, r) => row.map(([x0, y0, x1, y1], c) => { if (S.pinned.has(`${r},${c}`)) return S.rects[r][c]; const [cx, cy] = map([(x0 + x1) / 2, (y0 + y1) / 2]); const hw = (x1 - x0) / 2 * m.scale, hh = (y1 - y0) / 2 * m.scale; // the size knob shrinks towards the dot, not the box centre: the dot is the specimen const [dx, dy] = map(b.centers[r]?.[c] || [(x0 + x1) / 2, (y0 + y1) / 2]); if (S.centers[r]?.[c]) S.centers[r][c] = [clamp(dx, 0, 1), clamp(dy, 0, 1)]; const [nx0, nx1] = slide(dx + (cx - hw - dx) * p, dx + (cx + hw - dx) * p); const [ny0, ny1] = slide(dy + (cy - hh - dy) * p, dy + (cy + hh - dy) * p); return [nx0, ny0, nx1, ny1]; })); sizeInfo(); draw(); drawThumbs(); } const adjustGrid = (k, v) => { S.adjust[k] = v; showAdjust(); applyAdjust(); }; const showAdjust = () => { document.querySelectorAll(".adj").forEach((el) => { el.value = S.adjust[el.dataset.k]; }); document.querySelectorAll(".adjVal").forEach((el) => { const v = S.adjust[el.dataset.k]; el.textContent = el.dataset.k === "rot" ? `${v.toFixed(1)}\u00b0` : el.dataset.k[0] === "d" ? `${v.toFixed(1)}%` : `${v.toFixed(2)}\u00d7`; }); }; /** Every slider back to neutral, which is exact - they all read off the base layout. */ const resetAdjust = () => { S.adjust = { ...NEUTRAL }; showAdjust(); applyAdjust(); }; window.addEventListener("keydown", (e) => { if (e.key === "Backspace" && S.phase === "seeding" && S.seeds.length && e.target.tagName !== "INPUT") { e.preventDefault(); S.seeds.pop(); draw(); seedsLeft(); } }); /** Draw a cell's box by hand, anywhere, any size. The detector's grid is a starting point, not a verdict: on a label photo the writing is often nowhere near where the sample was, and dragging four edges into place is slower than drawing the box you want. The box goes to the cell it lands in, or the nearest one - the same rule the text areas use. No clamping: these boxes read names and cut label crops, they never cut a specimen, so two of them overlapping costs nothing. The X-ray's layout is untouched either way. */ function toggleDraw() { const btn = $("btnDraw"); if (S.phase === "draw") { S.phase = "grid"; S.box = null; btn.textContent = "Draw a name box"; btn.classList.remove("stale"); setStatus("Boxes set. Press Read the names to read them through these."); return draw(); } S.phase = "draw"; S.box = null; btn.textContent = "Done drawing"; btn.classList.add("stale"); setStatus("Drag out a box over one label — it replaces the box of the cell it lands " + "in, or the nearest one. Draw as many as you like, then press Read the names."); draw(); } function finishDrawnBox() { const b = S.box; S.box = null; const x0 = Math.min(b.x0, b.x1), x1 = Math.max(b.x0, b.x1); const y0 = Math.min(b.y0, b.y1), y1 = Math.max(b.y0, b.y1); if (x1 - x0 < MIN || y1 - y0 < MIN) return draw(); // a click, not a box const cell = ownerCell((x0 + x1) / 2, (y0 + y1) / 2); if (!cell) return draw(); S.rects[cell[0]][cell[1]] = [x0, y0, x1, y1]; S.pinned.add(`${cell[0]},${cell[1]}`); // drawn by hand, so the sliders leave it alone if (S.centers[cell[0]]?.[cell[1]]) S.centers[cell[0]][cell[1]] = [(x0 + x1) / 2, (y0 + y1) / 2]; sizeInfo(); draw(); drawThumbs(); setStatus(`Box drawn for row ${cell[0] + 1}, column ${cell[1] + 1}. ` + "Press Read the names when the boxes are where you want them."); } /* ---------- label strips ---------- */ /** The strip of each box the writing sits on: the bottom `band`% of it. On a real tray the code is written across the bottom face of every block, so the strip is not a guess - it is where the label is, on all 21 of them. Marking 21 boxes by hand to say so is the work this removes; drag the one it got wrong and the slider leaves that one alone from then on, the same rule the grid sliders follow. Strips are shared by both trays (they are indexed by cell) but only ever cut from the label photo, which is the tray they are marked on. */ function fillStrips() { const lab = trayOf("label"); if (!lab.rects.length || lab.rects.length !== S.rows) return; if (S.textRects.length !== S.rows || S.textRects[0]?.length !== S.cols) S.textRects = Array.from({ length: S.rows }, () => Array(S.cols).fill(null)); const band = clamp(+$("band").value, 5, 100) / 100; $("bandVal").textContent = `${Math.round(band * 100)}%`; S.textRects = S.textRects.map((row, r) => row.map((strip, c) => { if (S.textPinned.has(`${r},${c}`)) return strip; // placed by hand: not ours to move const [x0, y0, x1, y1] = lab.rects[r][c]; return [x0, y1 - (y1 - y0) * band, x1, y1]; })); if (S.view === "label") draw(); drawThumbs(); } /* ---------- text areas ---------- */ /** A second box per cell: the patch of the tray holding that specimen's writing. Cropped at its own scale beside the specimen as {name}_text.jpg. Marked on the label photo when there is one - that is the tray the text is legible on. */ function toggleTextAreas() { if (S.phase === "text") { S.phase = "grid"; S.box = null; $("btnText").textContent = "Select text areas"; $("btnText").classList.remove("stale"); setStatus(`${textCount()} text areas marked — each exported beside its crop as ` + "{name}_text.jpg.", textCount() ? "ok" : ""); return draw(); } S.phase = "text"; S.box = null; $("btnText").textContent = "Done with text areas"; $("btnText").classList.add("stale"); setStatus("Drag a box around the writing of each specimen, one per rectangle" + " on the label photo. A box goes to the rectangle it sits " + "in, or the nearest one if the label sits beside its specimen. Click to clear a box."); draw(); } function finishTextBox() { const b = S.box; S.box = null; const x0 = Math.min(b.x0, b.x1), x1 = Math.max(b.x0, b.x1); const y0 = Math.min(b.y0, b.y1), y1 = Math.max(b.y0, b.y1); const cell = ownerCell((x0 + x1) / 2, (y0 + y1) / 2); if (!cell) return draw(); const tiny = x1 - x0 < MIN || y1 - y0 < MIN; // that was a click, and a click clears S.textRects[cell[0]][cell[1]] = tiny ? null : [x0, y0, x1, y1]; const key = `${cell[0]},${cell[1]}`; if (tiny) S.textPinned.delete(key); else S.textPinned.add(key); draw(); drawThumbs(); setStatus(`${textCount()} of ${activeCells() || S.rows * S.cols} text areas marked.`); } /* ---------- names table ---------- */ // The shape of a label, client-side. namer.GROUPS is the server's copy of the same // statement - a tray on a different one changes both. const CODE = /^\d{8}-\d{3}-\d{2}$/; const prefixDigits = () => ($("prefix").value.match(/\d/g) || []).join(""); /** What is wrong with this name, or "" when nothing is. Confidence says how sure the reader was; this says whether the answer can be right at all - and it holds for a name typed by hand, which no confidence covers. An impossible date is the cheap catch: a misread digit in the year or month makes a code that still has the right shape, and nothing else notices. */ function issue(name) { const v = (name || "").trim(); if (!v) return "nothing read — type it from the crop beside the field"; if (v === "-") return ""; // deliberately empty slot if (!CODE.test(v)) return "does not match XXXXXXXX-XXX-XX"; const month = +v.slice(4, 6), day = +v.slice(6, 8); if (month < 1 || month > 12 || day < 1 || day > 31) return "impossible date"; const head = prefixDigits(); if (head && !v.replace(/-/g, "").startsWith(head)) return "not on the series prefix"; return ""; } const cellClass = (r, c, v) => { if (isBlank(r, c)) return "skip"; if (issue(v)) return "check"; const conf = S.conf[r]?.[c] ?? 0; return conf && conf < 70 ? "low" : ""; }; /** How many cells still want a look before cropping - stays quiet until something has been read or typed, since "every field is empty" before a read is not news. */ function showReview() { const bad = S.names.reduce((n, row, r) => n + row.filter((v, c) => !isBlank(r, c) && issue(v)).length, 0); const el = $("review"); el.hidden = !S.names.flat().some((v) => v.trim()); el.textContent = bad ? `${bad} to check` : "all names OK"; el.className = "badge " + (bad ? "warn" : "ok"); } /** One row per specimen: its X-ray crop, its label strip, its name. The table it replaces was the tray's shape - rows x columns of name boxes - which is the right picture for checking the layout and the wrong one for naming. Naming is a pairing job: this crop, that label, this name. On a real tray the specimens are not in numeric order (04, 06, 03 sit side by side), so every name has to be read off its own block; a row that carries both crops is that job with nothing else in it. Indexing is unchanged - the list is the cells of the same rows x cols flattened into reading order, and #n is only a label. */ function renderTable() { const rows = []; S.names.forEach((row, r) => row.forEach((v, c) => { const wrong = issue(v); rows.push(`