From 5cff210f9fae26503c2da45aad6eb80ab4e9095a Mon Sep 17 00:00:00 2001 From: Krishna Penukonda Date: Sat, 28 Nov 2026 18:57:50 +0800 Subject: [PATCH 1/3] Make Stackroom review views shareable through typed URLs --- .github/workflows/bokehforge.yml | 15 + bokehforge/docs/review.md | 6 + bokehforge/src/bokehforge/review/server.py | 1 + .../src/bokehforge/review/static/app.js | 369 +++++++++--- .../src/bokehforge/review/static/index.html | 4 +- .../review/static/score-explanation.js | 39 +- .../bokehforge/review/static/view-state.js | 23 + bokehforge/web/.gitignore | 1 + bokehforge/web/README.md | 13 + bokehforge/web/build.mjs | 26 + bokehforge/web/package-lock.json | 536 ++++++++++++++++++ bokehforge/web/package.json | 18 + bokehforge/web/tsconfig.json | 13 + bokehforge/web/view-state.test.mjs | 86 +++ bokehforge/web/view-state.ts | 224 ++++++++ bokehforge/web/view-state.types.ts | 16 + 16 files changed, 1318 insertions(+), 72 deletions(-) create mode 100644 bokehforge/src/bokehforge/review/static/view-state.js create mode 100644 bokehforge/web/.gitignore create mode 100644 bokehforge/web/README.md create mode 100644 bokehforge/web/build.mjs create mode 100644 bokehforge/web/package-lock.json create mode 100644 bokehforge/web/package.json create mode 100644 bokehforge/web/tsconfig.json create mode 100644 bokehforge/web/view-state.test.mjs create mode 100644 bokehforge/web/view-state.ts create mode 100644 bokehforge/web/view-state.types.ts diff --git a/.github/workflows/bokehforge.yml b/.github/workflows/bokehforge.yml index b236f52..69fd3b8 100644 --- a/.github/workflows/bokehforge.yml +++ b/.github/workflows/bokehforge.yml @@ -19,6 +19,20 @@ defaults: working-directory: bokehforge jobs: + stackroom-url: + name: Stackroom URL state + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c581273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + - run: npm ci --ignore-scripts --prefix web + - run: npm --prefix web run check + - run: npm --prefix web test + scoring: name: BokehForge scoring parity (${{ matrix.os }}) runs-on: ${{ matrix.os }} @@ -80,6 +94,7 @@ jobs: assert files("bokehforge").joinpath("heatmaps.html").is_file() assert files("bokehforge.data").joinpath("sources.json").is_file() assert files("bokehforge.review").joinpath("static", "index.html").is_file() + assert files("bokehforge.review").joinpath("static", "view-state.js").is_file() assert files("bokehforge.review").joinpath("static", "fonts", "SpaceGrotesk-Regular.ttf").is_file() PY - name: Run CPU scoring and parity tests diff --git a/bokehforge/docs/review.md b/bokehforge/docs/review.md index c2f3acf..ad97bce 100644 --- a/bokehforge/docs/review.md +++ b/bokehforge/docs/review.md @@ -34,6 +34,12 @@ Use **Heatmaps** in the output sidebar or the floating controls in the lightbox The overlay, damage type, tile size, and opacity carry over when you switch outputs or move between the main viewer and the lightbox. Heatmaps use the leading placement and load on demand. The lightbox keeps the heatmap aligned during zoom and pan and confines it to the output side of a reference swipe. The full reference stays clear for comparison. +## Share a review view + +Copy Stackroom’s URL to reopen the same scene, evaluation, source frame, reference, and stacker. It also preserves heatmap controls, score details, the open lightbox and its viewport, and open control panels, including an unsent evaluation configuration. Back and Forward restore previous selections. The destination Stackroom server needs the same dataset and saved evaluation for the link to resolve those images. + +Ratings and comments stay in the Stackroom store. Hover previews and held-key comparisons are temporary. Existing links using `#dataset=…&scene=…&run=…` still open. + ## Set up the stackers Choose the stackers in **New evaluation**. When you start the run, Stackroom uses the available open-source stackers and prepares any others you selected before processing scenes. First-time setup may download dependencies. The run banner shows what is being installed, and setup failures include a log for the affected stacker. Other selected stackers can continue when one setup fails. diff --git a/bokehforge/src/bokehforge/review/server.py b/bokehforge/src/bokehforge/review/server.py index 4a894e1..d22d936 100644 --- a/bokehforge/src/bokehforge/review/server.py +++ b/bokehforge/src/bokehforge/review/server.py @@ -36,6 +36,7 @@ STATIC = Path(__file__).with_name("static") ASSETS = {"/": ("index.html", "text/html; charset=utf-8"), "/app.js": ("app.js", "text/javascript; charset=utf-8"), + "/view-state.js": ("view-state.js", "text/javascript; charset=utf-8"), "/rail.js": ("rail.js", "text/javascript; charset=utf-8"), "/rating-autosave.js": ("rating-autosave.js", "text/javascript; charset=utf-8"), "/workspace-socket.js": ("workspace-socket.js", "text/javascript; charset=utf-8"), diff --git a/bokehforge/src/bokehforge/review/static/app.js b/bokehforge/src/bokehforge/review/static/app.js index b54b446..b21757e 100644 --- a/bokehforge/src/bokehforge/review/static/app.js +++ b/bokehforge/src/bokehforge/review/static/app.js @@ -3,12 +3,13 @@ import { ScoreExplanation } from "./score-explanation.js"; import { ScoreOverlay } from "./score-overlay.js"; import { RatingAutosave } from "./rating-autosave.js"; import { WorkspaceSocket } from "./workspace-socket.js"; +import { ViewHistory, readEvaluation, restoreEvaluation } from "./view-state.js"; const $ = (id) => document.getElementById(id); const number = new Intl.NumberFormat(); const date = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }); const savedTime = new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit", second: "2-digit" }); -const parameters = new URLSearchParams(location.hash.slice(1)); +const viewUrl = new ViewHistory(window); const tools = new Map(); const runStates = { running: "Running", completed: "Completed", completed_with_errors: "Completed with failures", @@ -33,7 +34,8 @@ const catalogStages = { }; let scenes = [], visible = [], runs = [], scene = null, details = null; -let sourceIndex = 0, referenceIndex = 0, runId = parameters.get("run") ?? "", stackerId = "", formKey = ""; +let sourceIndex = 0, referenceIndex = 0, runId = "", stackerId = "", formKey = ""; +let restoringView = null, runsLoaded = false, benchmarkTarget = null; let comparisonReference, comparisonHoldKey = ""; let sceneRequest, scoreRevision, stopping = ""; let warmupTimer, warming = []; @@ -48,6 +50,7 @@ const panelImages = new WeakMap(); const LIGHTBOX_HOVER_EXIT_DELAY = 100; const ACCENT_KEY = "bokehforge.review.accent"; const DEFAULT_ACCENT = "#ffffff"; +let localAccent = DEFAULT_ACCENT; const CHANNEL_WEIGHTS = [0.2126, 0.7152, 0.0722]; function luminance(channels) { @@ -76,26 +79,30 @@ function configureAppearance() { const input = $("accent-color"); try { const stored = localStorage.getItem(ACCENT_KEY); - if (/^#[a-f0-9]{6}$/i.test(stored ?? "")) input.value = stored; + if (/^#[a-f0-9]{6}$/i.test(stored ?? "")) localAccent = stored; } catch { // The picker still works for this page if the browser blocks storage. } const save = () => { applyAccent(input.value); + localAccent = input.value; try { localStorage.setItem(ACCENT_KEY, input.value); } catch { // Some browsers disable storage for local origins. } + remember(); + }; + input.oninput = () => { + applyAccent(input.value); + remember("continuous"); }; - input.oninput = () => applyAccent(input.value); input.onchange = save; $("reset-accent").onclick = () => { input.value = DEFAULT_ACCENT; save(); }; - $("open-appearance").onclick = () => $("appearance").showModal(); - applyAccent(input.value); + $("open-appearance").onclick = () => navigate(() => $("appearance").showModal()); } function stackerLabel(id) { @@ -127,12 +134,140 @@ function showMessage(node, message) { node.hidden = !message; } -function remember() { - const params = new URLSearchParams(); - if ($("dataset").value) params.set("dataset", $("dataset").value); - if (scene) params.set("scene", scene.id); - if (runId) params.set("run", runId); - history.replaceState(null, "", "#" + params); +function roundUnit(value) { + return Math.round(Math.min(1, Math.max(0, value)) * 100000) / 100000; +} + +function lightboxViewState() { + if (!activeImage?.gallery.scene || !$("image-dialog").open) return null; + const { params, gallery, actual, scale } = activeImage; + const { u, v } = lightboxAnchor(); + return { + scene: gallery.scene, + run: gallery.run || null, + reference: gallery.referenceFrame?.id ?? null, + image: params.frame ? { kind: "frame", id: params.frame } : { kind: "output", id: params.stacker }, + zoom: Math.round(scale * 100000) / 100000, + pixels: actual, + u: roundUnit(u), + v: roundUnit(v), + swipe: gallery.swipe, + split: roundUnit(gallery.split), + explain: lightboxExplanation.open, + details: lightboxExplanation.expandedDetails(), + benchmark: $("benchmark-details").open ? benchmarkTarget : null, + }; +} + +function remember(mode = "replace") { + if (restoringView) return; + viewUrl.write({ + dataset: $("dataset").value || null, + scene: scene?.id ?? null, + run: runId || null, + stacker: stackerId || null, + source: filmRail.items[sourceIndex]?.frame.id ?? null, + reference: comparisonReference?.id ?? null, + overlay: overlaySettings.mode, + family: overlaySettings.family, + tiles: overlaySettings.side, + opacity: overlaySettings.opacity, + accent: $("accent-color").value, + scenes: $("scene-browser").matches(":popover-open"), + details: candidateExplanation.expandedDetails(), + picker: lightboxOverlay.picker.matches(":popover-open") ? "lightbox" : + candidateOverlay.picker.matches(":popover-open") ? "output" : null, + appearance: $("appearance").open, + evaluation: $("new-run").open ? readEvaluation($("run-form")) : null, + lightbox: lightboxViewState(), + }, mode); +} + +function navigate(action, mode = "push") { + if (restoringView) { + restoringView.controller.abort(); + restoringView = null; + } + if (mode === "push") viewUrl.flush(); + action(); + remember(mode); +} + +function restoreView(state) { + restoringView?.controller.abort(); + restoringView = { state, controller: new AbortController(), started: false, finishing: false }; + for (const id of ["benchmark-details", "image-dialog", "appearance", "new-run"]) { + if ($(id).open) $(id).close(); + } + discardLightbox(); + $("scene-browser").hidePopover(); + candidateOverlay.picker.hidePopover(); + lightboxOverlay.picker.hidePopover(); + $("accent-color").value = state.accent ?? localAccent; + applyAccent($("accent-color").value); + if (state.appearance) $("appearance").showModal(); + candidateExplanation.setExpandedDetails(state.details); + Object.assign(overlaySettings, { mode: state.overlay, family: state.family, side: state.tiles, opacity: state.opacity }); + candidateOverlay.paint(); + lightboxOverlay.paint(); + beginRestore(); +} + +function beginRestore() { + const restore = restoringView; + if (!restore || restore.started || !runsLoaded || !scenes.length) return; + restore.started = true; + const { state } = restore; + const dataset = $("dataset"); + dataset.value = state.dataset ?? ""; + if (dataset.selectedIndex < 0 || (dataset.value && !scenes.some(item => item.dataset === dataset.value))) { + dataset.value = ""; + } + const run = runs.find(item => item.id === state.run)?.id ?? runs[0]?.id ?? ""; + if (run !== runId) { + details = null; + outputLoading = true; + } + runId = run; + stackerId = state.stacker ?? ""; + renderRuns(); + const previousScene = scene?.id; + filterScenes(state.scene); + if (scene?.id !== previousScene) return; + if (!details) { + renderOutput(); + loadScene(); + return; + } + sceneRequest?.abort(); + sceneRequest = null; + restoreScenePicks(state); + renderOutput(); + finishRestore(restore); +} + +function restoreScenePicks(state) { + referenceIndex = Math.max(0, details.references.findIndex(frame => frame.id === state.reference)); + renderReference(); + const index = filmRail.items.findIndex(item => item.frame.id === state.source); + selectSource(index < 0 ? Number(Boolean(comparisonReference)) : index); +} + +async function finishRestore(restore) { + if (restoringView !== restore || restore.finishing) return; + restore.finishing = true; + const { state, controller: { signal } } = restore; + if (state.lightbox) await restoreLightbox(state.lightbox, signal); + if (signal.aborted) return; + if (!$("image-dialog").open && !$("appearance").open) { + if (state.evaluation && !$("open-run").disabled) openRunDialog(state.evaluation); + else if (state.scenes) $("scene-browser").showPopover({ source: $("show-scenes") }); + } + const overlay = state.picker === "output" ? candidateOverlay : + state.picker === "lightbox" && activeImage ? lightboxOverlay : null; + if (overlay && overlaySettings.mode === "damage" && !overlay.root.hidden) overlay.damage.click(); + restoringView = null; + remember(); } function placeholder(well, title, description, log) { @@ -258,7 +393,7 @@ function showImage(well, title, params, priority = "high") { button.classList.add("image-ready"); button.removeAttribute("aria-disabled"); button.setAttribute("aria-label", "Inspect " + request.title); - button.onclick = () => openLightbox(request.title, params, request.shown); + button.onclick = () => navigate(() => openLightbox(request.title, params, request.shown)); if (candidate) { candidatePreview = { src, params, image: ready, host: button, contain: true }; paintCandidateOverlay(); @@ -297,7 +432,7 @@ function lightboxImageKey({ params }) { return params.frame ?? params.stacker; } -function setLightboxGallery(gallery, data) { +function lightboxEntries(gallery, data) { const images = data.frames.map((frame, index) => ({ title: sourceFrameTitle(frame, index), label: String(index + 1), params: { frame: frame.id }, })); @@ -314,6 +449,12 @@ function setLightboxGallery(gallery, data) { }); } if (reference) images.push({ title: referenceTitle(reference), label: "Reference", params: { frame: reference.id } }); + return images; +} + +function setLightboxGallery(gallery, data) { + const images = lightboxEntries(gallery, data); + const reference = data.references[gallery.reference]; const changed = images.length !== gallery.images.length || images.some((entry, index) => lightboxImageKey(entry) !== lightboxImageKey(gallery.images[index]) || entry.title !== gallery.images[index].title || entry.params.rev !== gallery.images[index].params.rev); @@ -336,7 +477,7 @@ function setLightboxGallery(gallery, data) { paintLightboxOverlays(); } -function openLightbox(title, params, previewImage, sceneId = scene?.id) { +function openLightbox(title, params, previewImage, sceneId = scene?.id, options = {}) { releaseComparisonReference(); const previous = activeImage; if (previous) closeLightboxRequests(previous); @@ -352,24 +493,49 @@ function openLightbox(title, params, previewImage, sceneId = scene?.id) { stage.append(surface); $("image-view").replaceChildren(stage); const entry = { title, label: title, params }; - const currentScene = sceneId === scene?.id; + const run = options.run ?? runId; + const currentScene = sceneId === scene?.id && run === runId; const gallery = { - scene: sceneId, run: runId, reference: currentScene ? referenceIndex : 0, images: [entry], + scene: sceneId, run, reference: options.reference ?? (currentScene ? referenceIndex : 0), images: [entry], surface, hoverLayer, hover: null, referenceLayer, referenceImages: {}, - baseEntry: entry, benchmarks: new Map(), swipe: false, split: 0.5, holdKey: "", + baseEntry: entry, benchmarks: new Map(), swipe: options.swipe ?? false, split: options.split ?? 0.5, holdKey: "", }; - if (currentScene && details) { - setLightboxGallery(gallery, details); - } else if (!currentScene && sceneId) { - loadLightboxGallery(gallery); - } + const data = options.data ?? (currentScene ? details : null); + if (data) setLightboxGallery(gallery, data); + else if (sceneId) loadLightboxGallery(gallery); const dialog = $("image-dialog"); if (!dialog.open) dialog.showModal(); - showLightboxImage(entry, gallery, stage, previewImage); + showLightboxImage(entry, gallery, stage, previewImage, options.viewport); fillLightboxStrip(gallery); $("image-view").focus(); } +async function restoreLightbox(saved, signal) { + if (!scenes.some(item => item.id === saved.scene)) return; + const run = saved.run && runs.some(item => item.id === saved.run) ? saved.run : ""; + try { + const data = scene?.id === saved.scene && runId === run && details ? details : + await api(url("/api/scene", { scene: saved.scene, run }), undefined, { signal }); + if (signal.aborted) return; + const reference = Math.max(0, data.references.findIndex(frame => frame.id === saved.reference)); + const entry = lightboxEntries({ scene: saved.scene, run, reference }, data).find(({ params }) => + (saved.image.kind === "frame" ? params.frame : params.stacker) === saved.image.id); + if (!entry) return; + openLightbox(entry.title, entry.params, undefined, saved.scene, { + run, reference, data, swipe: saved.swipe && Boolean(data.references.length), split: saved.split, + viewport: { actual: saved.pixels, scale: saved.zoom, position: { u: saved.u, v: saved.v } }, + }); + lightboxExplanation.setExpandedDetails(saved.details); + lightboxExplanation.setOpen(saved.explain); + const benchmark = data.outputs.find(output => output.stacker === saved.benchmark)?.benchmark; + if (benchmark?.status === "invalid_output" && benchmark.score === 0) { + openBenchmarkReason(saved.benchmark, benchmark.error || invalidDeliveryReason); + } + } catch { + // An unavailable gallery cannot be reconstructed. Keep its workspace view. + } +} + function lightboxScoresPending(gallery) { return [...gallery.benchmarks.values()].some((benchmark) => benchmark?.status === "pending"); } @@ -383,6 +549,7 @@ async function loadLightboxGallery(gallery) { const data = await api(url("/api/scene", { scene: gallery.scene, run: gallery.run }), undefined, { signal }); if (signal.aborted) return; setLightboxGallery(gallery, data); + remember(); if (revision !== scoreRevision && lightboxScoresPending(gallery)) loadLightboxGallery(gallery); } catch { // Keep the current preview available if its scene cannot be loaded. @@ -689,7 +856,7 @@ function paintLightboxOverlays() { const viewingReference = held && showing; const score = lightboxScore(gallery, entry); setLightboxTitle(viewingReference ? referenceTitle(reference) : entry.title); - renderLightboxBenchmark(viewingReference ? null : score.benchmark); + renderLightboxBenchmark(viewingReference ? null : score.benchmark, entry.params.stacker); let status = state.error; if (hover) status = hover.unavailable && shown?.entry !== hover.entry ? "Preview unavailable" : ""; if (comparing && !overlay && fit?.failed && (!native || native.failed)) status = "Reference unavailable"; @@ -743,6 +910,7 @@ function zoomLightbox(scale, x, y) { state.scale = Math.max(1, Math.min(12, scale)); if (state.scale > 1) requestLightbox("native"); paintLightbox(anchor); + remember("continuous"); } function lightboxScale() { @@ -761,6 +929,7 @@ function setPixelMode(actual) { activeImage.actual = true; requestLightbox("native"); paintLightbox(); + remember("continuous"); } function railItem(className) { @@ -782,7 +951,7 @@ function inspectButton(title, params, image, sceneId) { button.type = "button"; button.title = "Inspect " + title; button.setAttribute("aria-label", button.title); - button.onclick = () => openLightbox(title, params, image, sceneId); + button.onclick = () => navigate(() => openLightbox(title, params, image, sceneId)); return button; } @@ -791,7 +960,7 @@ function sceneEntry(item, index) { const button = part("button", undefined, "scene-entry"); button.type = "button"; button.title = item.name; - button.onclick = () => goTo(index); + button.onclick = () => navigate(() => goTo(index)); const params = { frame: item.preview_frame }; const image = createThumbnail(params); const preview = part("span", undefined, "scene-preview preview-thumbnail"); @@ -813,7 +982,7 @@ function sourceEntry({ frame, frameIndex }, index) { const button = part("button", undefined, "thumb preview-thumbnail"); button.type = "button"; button.setAttribute("aria-label", title); - button.onclick = () => selectSource(index); + button.onclick = () => navigate(() => selectSource(index)); const params = { frame: frame.id }; const image = createThumbnail(params); button.append(image, part("span", reference ? "Reference" : String(frameIndex + 1).padStart(3, "0"))); @@ -848,7 +1017,7 @@ function lightboxStripEntry(entry) { } }); button.onclick = () => { - if (activeImage?.gallery === gallery) selectLightboxEntry(entry); + if (activeImage?.gallery === gallery) navigate(() => selectLightboxEntry(entry)); }; tile.append(button); extendThumbnailTarget(tile, button); @@ -880,7 +1049,6 @@ function goTo(position) { $("next").disabled = visible.length <= 1; if (scene?.id === next.id) { scene = next; - remember(); return; } scene = next; @@ -897,7 +1065,6 @@ function goTo(position) { showImage($("source-image"), "source frame 1", { frame: next.first_frame }); setComparisonReference(next.first_reference ? { id: next.first_reference } : null); renderOutput(); - remember(); loadScene(); } @@ -923,17 +1090,23 @@ async function loadScene() { if (gallery?.scene === scene.id && gallery.run === runId) setLightboxGallery(gallery, data); outputLoading = false; showMessage($("scene-error"), ""); - if (firstLoad) { + const restore = restoringView?.started ? restoringView : null; + if (restore) { + restoreScenePicks(restore.state); + } else if (firstLoad) { renderReference(); selectSource(sourceIndex); } renderOutput(); + if (restore) finishRestore(restore); + else remember(); } catch (error) { if (signal.aborted) return; outputLoading = false; renderOutput(); showMessage($("scene-error"), error.message); if (!details) placeholder($("source-image"), "Scene unavailable"); + if (restoringView?.started) finishRestore(restoringView); } finally { if (!signal.aborted) { sceneRequest = null; @@ -1029,6 +1202,7 @@ function renderReference() { $("reference-control").title = details.reference_semantics; $("reference-select").replaceChildren(...refs.map((ref, index) => new Option(`${index + 1} · ${ref.name}`, index))); + $("reference-select").value = String(referenceIndex); selectReference(); } @@ -1042,7 +1216,7 @@ const benchmarkNumber = new Intl.NumberFormat(undefined, { minimumFractionDigits const invalidDeliveryReason = "The delivery failed the benchmark's image requirements."; -function renderLightboxBenchmark(benchmark) { +function renderLightboxBenchmark(benchmark, stacker) { const label = $("lightbox-benchmark"); const line = label.parentElement; const info = label.nextElementSibling; @@ -1062,6 +1236,7 @@ function renderLightboxBenchmark(benchmark) { line.dataset.scored = scored; label.title = [benchmark?.profile, invalid ? null : benchmark?.error].filter(Boolean).join(" · "); info.dataset.reason = invalid ? benchmark.error || invalidDeliveryReason : ""; + info.dataset.stacker = invalid ? stacker : ""; } function renderCandidateScoreStatus(benchmark) { @@ -1077,11 +1252,16 @@ function renderCandidateScoreStatus(benchmark) { if (status.textContent !== text) status.textContent = text; } -function showBenchmarkReason(button) { - $("benchmark-reason").textContent = button.dataset.reason; +function openBenchmarkReason(stacker, reason) { + benchmarkTarget = stacker; + $("benchmark-reason").textContent = reason; $("benchmark-details").showModal(); } +function showBenchmarkReason(button) { + navigate(() => openBenchmarkReason(button.dataset.stacker, button.dataset.reason)); +} + function paintCandidateOverlay() { if (!candidatePreview?.image.isConnected) candidatePreview = null; if (candidatePreview && candidateScore && candidatePreview.src === imageURL(candidateScore.params, "panel")) { @@ -1117,7 +1297,10 @@ function renderOutput() { button.append(badge); } if (output.rating?.grade != null) button.append(part("small", output.rating.grade + "/5")); - button.onclick = () => { stackerId = output.stacker; renderOutput(); }; + button.onclick = () => navigate(() => { + stackerId = output.stacker; + renderOutput(); + }); return button; }); tabStrip.replaceChildren(...tabs); @@ -1208,7 +1391,6 @@ function changeRun(id) { if (details) details.outputs = []; if (scene) { renderOutput(); - remember(); loadScene(); } } @@ -1250,6 +1432,12 @@ function renderRuns() { function applyRuns(history) { const old = runs.find((run) => run.id === runId); runs = history; + runsLoaded = true; + if (restoringView) { + renderRuns(); + beginRestore(); + return; + } if (!runs.some((run) => run.id === runId)) { changeRun(runs[0]?.id ?? ""); } else { @@ -1322,7 +1510,7 @@ function toolOption(tool, prepared) { return card; } -function openRunDialog() { +function openRunDialog(draft = null) { const scope = $("scope"); scope.replaceChildren(new Option("Current scene", "scene"), new Option("Current dataset", "dataset"), new Option("All indexed datasets", "all")); @@ -1340,6 +1528,7 @@ function openRunDialog() { $("available-tools").replaceChildren(...Array.from(tools.values(), (tool) => toolOption(tool, prepared))); $("start-run").disabled = false; showMessage($("run-error"), ""); + if (draft) restoreEvaluation($("run-form"), draft); $("new-run").showModal(); } @@ -1370,8 +1559,10 @@ async function startRun(event) { const result = await api("/api/runs", { scope: $("scope").value, scene: scene.id, dataset: scene.dataset, stackers, options, }); - $("new-run").close(); - changeRun(result.id); + navigate(() => { + $("new-run").close(); + changeRun(result.id); + }); } catch (error) { showMessage($("run-error"), error.message); } finally { @@ -1395,7 +1586,7 @@ async function stopRun() { function applyCatalog(catalog) { ratingAutosave.setReady(catalog.status === "ready" || Boolean(catalog.scenes?.length)); if (catalog.revision === catalogRevision && catalog.image_version === imageVersion) return; - const selectedScene = scene?.id ?? parameters.get("scene"); + const selectedScene = scene?.id; if (imageVersion && catalog.image_version !== imageVersion) { scene = null; details = null; @@ -1410,7 +1601,7 @@ function applyCatalog(catalog) { if (!scenes.length) $("scene-browser").hidePopover?.(); const workspace = $("workspace"); const dataset = $("dataset"); - const selected = workspace.hidden ? parameters.get("dataset") : dataset.value; + const selected = dataset.value; workspace.hidden = !scenes.length; catalogNotice = null; if (scenes.length) { @@ -1418,7 +1609,11 @@ function applyCatalog(catalog) { .map(([id, name]) => new Option(name === id ? id : `${name} (${id})`, id))); dataset.value = selected ?? ""; if (dataset.selectedIndex < 0) dataset.value = ""; - filterScenes(selectedScene); + if (restoringView) beginRestore(); + else { + filterScenes(selectedScene); + remember(); + } } else if (catalog.status === "missing") { catalogNotice = ["Download a dataset to get started", "Scenes appear after their dataset has been downloaded and verified."]; } else if (catalog.error) { @@ -1426,6 +1621,10 @@ function applyCatalog(catalog) { } else if (catalog.status !== "indexing") { catalogNotice = ["No scenes available", "The local datasets contain no usable scenes."]; } + if (!scenes.length && restoringView && catalog.status !== "indexing") { + restoringView = null; + remember(); + } renderCatalogNotice(); renderRuns(); } @@ -1570,13 +1769,15 @@ const sceneRail = new VirtualRail($("scene-list"), "y", 74, sceneEntry); const filmRail = new VirtualRail($("filmstrip"), "x", 112, sourceEntry, { itemPadding: 5 }); const requestScoreOverlay = (mode, params, signal) => api(url(mode === "attention" ? "/api/score-attention" : "/api/score-tiles", params), undefined, { signal }); -const candidateExplanation = new ScoreExplanation($("candidate-explanation")); -const lightboxExplanation = new ScoreExplanation($("lightbox-explanation"), $("lightbox-explain")); +const candidateExplanation = new ScoreExplanation($("candidate-explanation"), null, remember); +const lightboxExplanation = new ScoreExplanation($("lightbox-explanation"), $("lightbox-explain"), remember); const overlaySettings = { mode: "off", family: "all", side: 8, opacity: 100 }; function changeOverlaySettings(changes) { - Object.assign(overlaySettings, changes); - candidateOverlay.paint(); - lightboxOverlay.paint(); + navigate(() => { + Object.assign(overlaySettings, changes); + candidateOverlay.paint(); + lightboxOverlay.paint(); + }, Object.hasOwn(changes, "opacity") ? "continuous" : "push"); } const candidateOverlay = new ScoreOverlay( $("candidate-overlay"), $("candidate-image").parentElement, overlaySettings, changeOverlaySettings, requestScoreOverlay, @@ -1594,38 +1795,47 @@ lightboxStrip.addEventListener("pointerleave", (event) => { $("scene-browser").addEventListener("toggle", ({ newState }) => { if (newState === "open") sceneRail.select(visible.indexOf(scene)); + remember(); }); -$("dataset").onchange = () => filterScenes(scene?.id); -$("previous").onclick = () => moveScene(-1); -$("next").onclick = () => moveScene(1); -$("jump").onchange = () => goTo($("jump").valueAsNumber - 1); -$("reference-select").onchange = (event) => { +for (const overlay of [candidateOverlay, lightboxOverlay]) { + overlay.picker.addEventListener("toggle", () => remember()); + overlay.opacity.addEventListener("change", () => viewUrl.flush()); +} +$("dataset").onchange = () => navigate(() => filterScenes(scene?.id)); +$("previous").onclick = () => navigate(() => moveScene(-1)); +$("next").onclick = () => navigate(() => moveScene(1)); +$("jump").onchange = () => navigate(() => goTo($("jump").valueAsNumber - 1)); +$("reference-select").onchange = (event) => navigate(() => { referenceIndex = Number(event.target.value); selectReference(); selectSource(0); renderOutput(); -}; -$("run-select").onchange = () => changeRun($("run-select").value); +}); +$("run-select").onchange = () => navigate(() => changeRun($("run-select").value)); $("rating-form").oninput = captureDraft; $("rating-form").onsubmit = (event) => event.preventDefault(); -$("open-run").onclick = openRunDialog; +$("open-run").onclick = () => navigate(() => openRunDialog()); $("download-start").onclick = startDownload; $("stop-run").onclick = stopRun; $("run-form").onsubmit = startRun; +$("run-form").addEventListener("input", () => remember("continuous")); +$("run-form").addEventListener("change", () => remember()); +$("run-form").addEventListener("toggle", () => remember(), true); $("pixel-mode").onclick = () => setPixelMode(!activeImage.actual); $("image-fit").onclick = () => zoomLightbox(1); $("zoom-in").onclick = () => zoomLightbox(lightboxScale() * 1.5); $("zoom-out").onclick = () => zoomLightbox(lightboxScale() / 1.5); const lightboxView = $("image-view"); -$("reference-swipe").onclick = () => { +$("reference-swipe").onclick = () => navigate(() => { const gallery = activeImage.gallery; gallery.swipe = !gallery.swipe; paintLightboxOverlays(); -}; +}); const referenceSlider = $("reference-slider"); function setReferenceSplit(split) { activeImage.gallery.split = Math.max(0, Math.min(1, split)); paintLightboxOverlays(); + remember("continuous"); } function dragReference(event) { const { left, right } = visibleLightboxImage(activeImage.gallery); @@ -1641,7 +1851,10 @@ referenceSlider.addEventListener("pointermove", (event) => { dragReference(event); } }); -referenceSlider.addEventListener("pointerup", () => lightboxView.focus({ preventScroll: true })); +referenceSlider.addEventListener("pointerup", () => { + viewUrl.flush(); + lightboxView.focus({ preventScroll: true }); +}); referenceSlider.addEventListener("keydown", (event) => { const { split } = activeImage.gallery; const next = { ArrowLeft: split - 0.05, ArrowRight: split + 0.05, Home: 0, End: 1 }[event.key]; @@ -1650,7 +1863,11 @@ referenceSlider.addEventListener("keydown", (event) => { event.stopPropagation(); setReferenceSplit(next); }); -lightboxView.addEventListener("scroll", paintLightboxOverlays, { passive: true }); +lightboxView.addEventListener("scroll", () => { + if (!activeImage) return; + paintLightboxOverlays(); + remember("continuous"); +}, { passive: true }); lightboxView.addEventListener("wheel", (event) => { if (event.shiftKey) { activeImage.position = null; @@ -1684,7 +1901,7 @@ document.addEventListener("keydown", (event) => { } if (event.key === "ArrowLeft" || event.key === "ArrowRight") { event.preventDefault(); - moveLightbox(event.key === "ArrowLeft" ? -1 : 1); + navigate(() => moveLightbox(event.key === "ArrowLeft" ? -1 : 1), event.repeat ? "continuous" : "push"); return; } if (event.target === lightboxView && @@ -1729,10 +1946,14 @@ function endLightboxPan() { panStart = null; lightboxView.classList.remove("dragging"); } -lightboxView.addEventListener("pointerup", endLightboxPan); +lightboxView.addEventListener("pointerup", () => { + endLightboxPan(); + remember("continuous"); + viewUrl.flush(); +}); lightboxView.addEventListener("lostpointercapture", endLightboxPan); -$("image-dialog").addEventListener("close", (event) => { - if (event.currentTarget.open || !activeImage) return; +function discardLightbox() { + if (!activeImage) return; closeLightboxRequests(activeImage); activeImage = null; lightboxExplanation.close(); @@ -1740,7 +1961,20 @@ $("image-dialog").addEventListener("close", (event) => { endLightboxPan(); lightboxRail.setItems([]); lightboxView.replaceChildren(); +} + +$("image-dialog").addEventListener("close", () => { + if ($("image-dialog").open || !activeImage) return; + discardLightbox(); + remember("push"); }); +for (const id of ["appearance", "new-run", "benchmark-details"]) { + $(id).addEventListener("close", () => { + if ($(id).open) return; + if (id === "benchmark-details") benchmarkTarget = null; + remember("push"); + }); +} new ResizeObserver(() => { if (activeImage) paintLightbox(); }).observe(lightboxView); @@ -1763,10 +1997,11 @@ document.addEventListener("keydown", (event) => { renderOutput(); } else if (event.key === "ArrowLeft" || event.key === "ArrowRight") { event.preventDefault(); - selectSource(sourceIndex + (event.key === "ArrowLeft" ? -1 : 1)); + navigate(() => selectSource(sourceIndex + (event.key === "ArrowLeft" ? -1 : 1)), + event.repeat ? "continuous" : "push"); } else if (event.key === "ArrowUp" || event.key === "ArrowDown") { event.preventDefault(); - moveScene(event.key === "ArrowUp" ? -1 : 1); + navigate(() => moveScene(event.key === "ArrowUp" ? -1 : 1), event.repeat ? "continuous" : "push"); } }); window.addEventListener("beforeunload", (event) => { @@ -1781,4 +2016,6 @@ new ResizeObserver(([entry]) => { document.documentElement.style.setProperty("--command-height", `${height + 4}px`); }).observe(commandBar); configureAppearance(); +window.addEventListener("popstate", () => restoreView(viewUrl.read())); +restoreView(viewUrl.read()); workspaceSocket.connect(); diff --git a/bokehforge/src/bokehforge/review/static/index.html b/bokehforge/src/bokehforge/review/static/index.html index ca1d368..c353dae 100644 --- a/bokehforge/src/bokehforge/review/static/index.html +++ b/bokehforge/src/bokehforge/review/static/index.html @@ -227,7 +227,7 @@

Score details

-
+
How alignment was inferred

     
@@ -236,7 +236,7 @@

Score details

Damage familyObservedWeightContribution
-
+
How to read damage

Zero damage means no measured difference from the reference. Damage can reach 1 before attention weighting and up to 2 with weighting. The six families separate different ways an output can lose fidelity, such as shifting tones or smoothing away detail.

Each contribution is observed damage multiplied by its weight. Overlap quality decays exponentially as their sum increases.

diff --git a/bokehforge/src/bokehforge/review/static/score-explanation.js b/bokehforge/src/bokehforge/review/static/score-explanation.js index f33fd3b..e8dfde7 100644 --- a/bokehforge/src/bokehforge/review/static/score-explanation.js +++ b/bokehforge/src/bokehforge/review/static/score-explanation.js @@ -13,8 +13,9 @@ function damage(value) { return value > 0 && value < 0.0001 ? value.toExponential(1) : number.format(value); } -function familyRow(family) { +function familyRow([id, family]) { const row = element("details", undefined, "damage-family"); + row.dataset.viewDetail = "family:" + id; const summary = element("summary"); const values = [ [family.label, ""], @@ -48,18 +49,31 @@ export function scoreExplanationKey(context) { } export class ScoreExplanation { - constructor(root, trigger) { + constructor(root, trigger, viewChanged) { this.root = root; this.trigger = trigger; root.append(document.querySelector("#score-explanation-template").content.cloneNode(true)); this.key = ""; this.open = !trigger; + this.expanded = new Set(); + root.addEventListener("toggle", ({ target }) => { + if (!(target instanceof HTMLDetailsElement) || !root.contains(target)) return; + const id = target.dataset.viewDetail; + if (!id || this.expanded.has(id) === target.open) return; + if (target.open) this.expanded.add(id); + else this.expanded.delete(id); + viewChanged(); + }, true); const dismiss = root.querySelector(".score-explanation-dismiss"); if (trigger) { - trigger.onclick = () => this.setOpen(!this.open); + trigger.onclick = () => { + this.setOpen(!this.open); + viewChanged("push"); + }; dismiss.onclick = () => { this.setOpen(false); trigger.focus(); + viewChanged("push"); }; } else { dismiss.remove(); @@ -74,8 +88,24 @@ export class ScoreExplanation { this.trigger.textContent = open && this.key ? "Hide explanation" : "Explain score"; } + expandedDetails() { + return [...this.expanded].sort(); + } + + setExpandedDetails(ids) { + this.expanded = new Set(ids); + this.applyExpandedDetails(); + } + + applyExpandedDetails() { + for (const panel of this.root.querySelectorAll("details[data-view-detail]")) { + panel.open = this.expanded.has(panel.dataset.viewDetail); + } + } + close() { this.setOpen(false); + this.setExpandedDetails([]); this.update(null); } @@ -93,7 +123,7 @@ export class ScoreExplanation { showSummary(explanation, placement, alignment) { const comparison = placement?.comparison; - const families = Object.values(comparison?.families ?? {}); + const families = Object.entries(comparison?.families ?? {}); if (this.trigger) { this.root.querySelector("[data-score-heading]").textContent = "Benchmark score " + points.format(explanation.score) + " / 100"; @@ -122,6 +152,7 @@ export class ScoreExplanation { (comparison.inspection_mix == null ? "" : " · Inspection mix " + percent.format(comparison.inspection_mix)) : ""; this.root.querySelector("[data-damage-families]").replaceChildren(...families.map(familyRow)); + this.applyExpandedDetails(); } } diff --git a/bokehforge/src/bokehforge/review/static/view-state.js b/bokehforge/src/bokehforge/review/static/view-state.js new file mode 100644 index 0000000..caed013 --- /dev/null +++ b/bokehforge/src/bokehforge/review/static/view-state.js @@ -0,0 +1,23 @@ +/* Generated by npm run build in bokehforge/web. + +serialize-query-params +ISC License + +Copyright 2019-present Peter Beshai + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +valibot +MIT License + +Copyright (c) Fabian Hiller + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +function q(n){let r=new URLSearchParams,e=Object.entries(n);for(let[i,t]of e)if(t!==void 0&&t!==null)if(Array.isArray(t))for(let s of t)r.append(i,s??"");else r.append(i,t);return r.toString()}var on='{}[],":'.split("").map(n=>[n,encodeURIComponent(n)]);function $(n,r){let e={},i=Object.keys(r);for(let t of i){let s=r[t];n[t]?e[t]=n[t].encode(r[t]):e[t]=s==null?s:String(s)}return e}function F(n,r){let e={},i=Object.keys(n);for(let t of Object.keys(r))n[t]==null&&i.push(t);for(let t of i){let s=r[t];n[t]?e[t]=n[t].decode(s):(console.warn(`Passing through parameter ${t} during decoding since it was not configured.`),e[t]=s)}return e}function D(n){let r=new URLSearchParams(n),e={};for(let[i,t]of r)Object.prototype.hasOwnProperty.call(e,i)?Array.isArray(e[i])?e[i].push(t):e[i]=[e[i],t]:e[i]=t;return e}var z,ze={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Q(n){return!n&&!z?ze:{lang:n?.lang??z?.lang,message:n?.message,abortEarly:n?.abortEarly??z?.abortEarly,abortPipeEarly:n?.abortPipeEarly??z?.abortPipeEarly}}var Te;function Me(n){return Te?.get(n)}var Re;function $e(n){return Re?.get(n)}var Fe;function Ce(n,r){return Fe?.get(n)?.get(r)}function g(n){let r=typeof n;return r==="string"?`"${n}"`:r==="number"||r==="bigint"||r==="boolean"?`${n}`:r==="object"||r==="function"?(n&&Object.getPrototypeOf(n)?.constructor?.name)??"null":r}function a(n,r,e,i,t){let s=t&&"input"in t?t.input:e.value,l=t?.expected??n.expects??null,o=t?.received??g(s),u={kind:n.kind,type:n.type,input:s,expected:l,received:o,message:`Invalid ${r}: ${l?`Expected ${l} but r`:"R"}eceived ${o}`,requirement:n.requirement,path:t?.path,issues:t?.issues,lang:i.lang,abortEarly:i.abortEarly,abortPipeEarly:i.abortPipeEarly},c=n.kind==="schema",f=t?.message??n.message??Ce(n.reference,u.lang)??(c?$e(u.lang):null)??i.message??Me(u.lang);f!==void 0&&(u.message=typeof f=="function"?f(u):f),c&&(e.typed=!1),e.issues?e.issues.push(u):e.issues=[u]}function Le(n,r){return n===r||Number.isNaN(n)&&Number.isNaN(r)}function Ge(n,r){return Object.prototype.hasOwnProperty.call(n,r)&&r!=="__proto__"&&r!=="prototype"&&r!=="constructor"}function C(n,r){let e=[...new Set(n)];return e.length>1?`(${e.join(` ${r} `)})`:e[0]??"never"}function m(n){return n["~standard"]={version:1,vendor:"valibot",validate:r=>n["~run"]({value:r},Q())},n}function L(n,r){return{kind:"validation",type:"check",reference:L,async:!1,expects:null,requirement:n,message:r,"~run"(e,i){return e.typed&&!this.requirement(e.value)&&a(this,"input",e,i),e}}}function G(n){return{kind:"validation",type:"integer",reference:G,async:!1,expects:null,requirement:Number.isInteger,message:n,"~run"(r,e){return r.typed&&!this.requirement(r.value)&&a(this,"integer",r,e),r}}}function S(n,r){return{kind:"validation",type:"max_length",reference:S,async:!1,expects:`<=${n}`,requirement:n,message:r,"~run"(e,i){return e.typed&&e.value.length>this.requirement&&a(this,"length",e,i,{received:`${e.value.length}`}),e}}}function j(n,r){return{kind:"validation",type:"max_value",reference:j,async:!1,expects:`<=${n instanceof Date?n.toJSON():g(n)}`,requirement:n,message:r,"~run"(e,i){return e.typed&&!(e.value<=this.requirement)&&a(this,"value",e,i,{received:e.value instanceof Date?e.value.toJSON():g(e.value)}),e}}}function O(n,r){return{kind:"validation",type:"min_value",reference:O,async:!1,expects:`>=${n instanceof Date?n.toJSON():g(n)}`,requirement:n,message:r,"~run"(e,i){return e.typed&&!(e.value>=this.requirement)&&a(this,"value",e,i,{received:e.value instanceof Date?e.value.toJSON():g(e.value)}),e}}}function w(n,r){return{kind:"validation",type:"regex",reference:w,async:!1,expects:`${n}`,requirement:n,message:r,"~run"(e,i){return e.typed&&!this.requirement.test(e.value)&&a(this,"format",e,i),e}}}var Ve={abortEarly:!0};function Je(n,r,e){return typeof n.fallback=="function"?n.fallback(r,e):n.fallback}function Y(n,r,e){return typeof n.default=="function"?n.default(r,e):n.default}function T(n,r){return m({kind:"schema",type:"array",reference:T,expects:"Array",async:!1,item:n,message:r,"~run"(e,i){let t=e.value;if(Array.isArray(t)){e.typed=!0,e.value=[];for(let s=0;se.expects),"|"),async:!1,options:n,message:r,"~run"(e,i){let t,s,l;for(let o of this.options){let u=o["~run"]({value:e.value},i);if(u.typed)if(u.issues)s?s.push(u):s=[u];else{t=u;break}else l?l.push(u):l=[u]}if(t)return t;if(s){if(s.length===1)return s[0];a(this,"type",e,i,{issues:K(s)}),e.typed=!0}else{if(l?.length===1)return l[0];a(this,"type",e,i,{issues:K(l)})}return e}})}function X(n,r,e){return m({kind:"schema",type:"variant",reference:X,expects:"Object",async:!1,key:n,options:r,message:e,"~run"(i,t){let s=i.value;if(s&&typeof s=="object"){let l,o=0,u=this.key,c=[],f=(b,U)=>{for(let A of b.options){if(A.type==="variant")f(A,new Set(U).add(A.key));else{let H=!0,N=0;for(let v of U){let P=A.entries[v];if(v in s?P["~run"]({typed:!1,value:s[v]},Ve).issues:P.type!=="exact_optional"&&P.type!=="optional"&&P.type!=="nullish"){H=!1,u!==v&&(o!!n.trim())),Be=E(["off","attention","damage"]),Ze=E(["all","tone","color","lost_detail","added_structure","boundary","range"]),We=E([8,32]),Ue=d(I(),G(),O(0),j(100)),B=d(I(),O(0),j(1)),ie=d(T(d(_(),w(/^(?:alignment|damage-method|family:[a-z][a-z0-9_-]{0,39})$/))),S(32)),He=X("kind",[x({kind:M("frame"),id:h}),x({kind:M("output"),id:h})]),Ke=x({scene:h,run:y(h),reference:y(h),image:He,zoom:d(I(),O(1),j(12)),pixels:k(),u:B,v:B,swipe:k(),split:B,explain:k(),details:ie,benchmark:y(h)}),Qe=d(_(),w(/^[a-z][a-z0-9_-]{0,47}$/)),Ye=x({id:h,selected:k(),expanded:k(),settings:V(Qe,J([d(_(),S(128)),k()]))}),te=x({scope:E(["scene","dataset","all"]),tools:d(T(Ye),S(24))});function Z(n){try{return JSON.parse(n)}catch{return}}function ee(n){return/^\d+$/.test(n)?Number(n):NaN}function ne(n){if(n==="1")return!0;if(n==="0")return!1}function p(n,r,e=t=>t,i=t=>String(t)){return{decode(t){if(typeof t!="string")return r;let s=R(n,e(t));return s.success?s.output:r},encode(t){let s=R(n,t);if(!(!s.success||JSON.stringify(s.output)===JSON.stringify(r)))return i(s.output)}}}var W={dataset:p(y(h),null),scene:p(y(h),null),run:p(y(h),null),stacker:p(y(h),null),source:p(y(h),null),reference:p(y(h),null),overlay:p(Be,"off"),family:p(Ze,"all"),tiles:p(We,8,ee),opacity:p(Ue,100,ee),accent:p(y(d(_(),w(/^#[a-f0-9]{6}$/i))),null),scenes:p(k(),!1,ne,n=>n?"1":"0"),details:p(ie,[],Z,JSON.stringify),picker:p(y(E(["output","lightbox"])),null),appearance:p(k(),!1,ne,n=>n?"1":"0"),evaluation:p(y(te),null,Z,JSON.stringify),lightbox:p(y(Ke),null,Z,JSON.stringify)};function se(n){return Object.fromEntries(Object.entries(n).filter(([r])=>Object.hasOwn(W,r)))}function en({search:n,hash:r}){let e=D(r.slice(1));return F(W,se({...e,...D(n)}))}function nn(n){return q($(W,se(n)))}var re=class{#e;#n;#r;#s=-1/0;constructor(r){this.#e=r}read(){return this.#i(),en(this.#e.location)}write(r,e="replace"){let i=nn(r),t=this.#e.location.pathname+(i?"?"+i:"");if(e==="push")this.flush(),this.#t(t,"push");else if(e==="replace")this.#i(),this.#t(t,"replace");else{if(this.#r=t,this.#n!==void 0)return;let s=this.#s+400-this.#e.performance.now();s<=0?this.flush():this.#n=this.#e.setTimeout(()=>this.flush(),s)}}flush(){let r=this.#r;this.#i(),r!==void 0&&this.#t(r,"replace")}#i(){this.#n!==void 0&&this.#e.clearTimeout(this.#n),this.#n=this.#r=void 0}#t(r,e){let{pathname:i,search:t,hash:s}=this.#e.location;r!==i+t+s&&(this.#e.history[e==="push"?"pushState":"replaceState"](null,"",r),this.#s=this.#e.performance.now())}};function Gn(n){let r=n.querySelector("#scope")?.value,e=Array.from(n.querySelectorAll(".tool-option"),t=>{let s=t.querySelector('input[name="stacker"]'),l={};for(let o of t.querySelectorAll("[data-setting]")){let u=o.dataset.setting;u&&(l[u]=o instanceof HTMLInputElement&&o.type==="checkbox"?o.checked:o.value)}return{id:s?.value,selected:s?.checked,expanded:t.querySelector("details")?.open,settings:l}}),i=R(te,{scope:r,tools:e});return i.success?i.output:null}function Vn(n,r){let e=n.querySelector("#scope");e&&Array.from(e.options).some(t=>t.value===r.scope)&&(e.value=r.scope,e.dispatchEvent(new Event("change")));let i=new Map(r.tools.map(t=>[t.id,t]));for(let t of n.querySelectorAll(".tool-option")){let s=t.querySelector('input[name="stacker"]');if(!s)continue;let l=i.get(s.value);if(!l)continue;s.checked=l.selected;let o=t.querySelector("details");o&&(o.open=l.expanded);for(let u of t.querySelectorAll("[data-setting]")){let c=l.settings[u.dataset.setting??""];u instanceof HTMLSelectElement?typeof c=="string"&&Array.from(u.options).some(f=>f.value===c)&&(u.value=c):u.type==="checkbox"?typeof c=="boolean"&&(u.checked=c):typeof c=="string"&&(u.value=c)}o?.dispatchEvent(new Event("change"))}}export{re as ViewHistory,nn as encodeView,Gn as readEvaluation,en as readView,Vn as restoreEvaluation}; diff --git a/bokehforge/web/.gitignore b/bokehforge/web/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/bokehforge/web/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/bokehforge/web/README.md b/bokehforge/web/README.md new file mode 100644 index 0000000..4769948 --- /dev/null +++ b/bokehforge/web/README.md @@ -0,0 +1,13 @@ +# Stackroom URL state + +The Stackroom server serves the checked-in browser bundle. To change its typed +query schema, use Node.js 24 and run these commands from this directory. + +```sh +npm ci +npm run build +npm test +``` + +Commit the source and generated bundle together. `npm run check` verifies +strict TypeScript and checks that the served asset matches the source. diff --git a/bokehforge/web/build.mjs b/bokehforge/web/build.mjs new file mode 100644 index 0000000..ef2af06 --- /dev/null +++ b/bokehforge/web/build.mjs @@ -0,0 +1,26 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; + +const output = new URL("../src/bokehforge/review/static/view-state.js", import.meta.url); +const notices = await Promise.all([ + ["serialize-query-params", "LICENSE"], + ["valibot", "LICENSE.md"], +].map(async ([name, file]) => name + "\n" + + (await readFile(new URL("node_modules/" + name + "/" + file, import.meta.url), "utf8")).trim())); +const result = await build({ + absWorkingDir: fileURLToPath(new URL(".", import.meta.url)), + entryPoints: ["view-state.ts"], + bundle: true, + write: false, + format: "esm", + target: "es2022", + minify: true, + banner: { js: "/* Generated by npm run build in bokehforge/web.\n\n" + notices.join("\n\n") + "\n*/" }, +}); +const code = result.outputFiles[0].text; +if (process.argv.includes("--check")) { + if (code !== await readFile(output, "utf8")) throw new Error("Run npm run build in bokehforge/web."); +} else { + await writeFile(output, code); +} diff --git a/bokehforge/web/package-lock.json b/bokehforge/web/package-lock.json new file mode 100644 index 0000000..8b6cc75 --- /dev/null +++ b/bokehforge/web/package-lock.json @@ -0,0 +1,536 @@ +{ + "name": "bokehforge-stackroom-web", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "bokehforge-stackroom-web", + "dependencies": { + "serialize-query-params": "2.0.4", + "valibot": "1.5.0" + }, + "devDependencies": { + "esbuild": "0.28.2", + "typescript": "6.0.3" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/serialize-query-params": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/serialize-query-params/-/serialize-query-params-2.0.4.tgz", + "integrity": "sha512-y9WzzDj3BsGgKLCh0ugiinufS//YqOfao/yVJjkXA4VLuyNCfHOLU/cbulGPxs3aeCqhvROw7qPL04JSZnCo0w==", + "license": "ISC" + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/valibot": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/valibot/-/valibot-1.5.0.tgz", + "integrity": "sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==", + "license": "MIT", + "peerDependencies": { + "typescript": ">=5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + } + } +} diff --git a/bokehforge/web/package.json b/bokehforge/web/package.json new file mode 100644 index 0000000..e003a81 --- /dev/null +++ b/bokehforge/web/package.json @@ -0,0 +1,18 @@ +{ + "name": "bokehforge-stackroom-web", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit && node build.mjs", + "check": "tsc --noEmit && node build.mjs --check", + "test": "node --test view-state.test.mjs" + }, + "dependencies": { + "serialize-query-params": "2.0.4", + "valibot": "1.5.0" + }, + "devDependencies": { + "esbuild": "0.28.2", + "typescript": "6.0.3" + } +} diff --git a/bokehforge/web/tsconfig.json b/bokehforge/web/tsconfig.json new file mode 100644 index 0000000..8a786a3 --- /dev/null +++ b/bokehforge/web/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noEmit": true + }, + "include": ["view-state.ts", "view-state.types.ts"] +} diff --git a/bokehforge/web/view-state.test.mjs b/bokehforge/web/view-state.test.mjs new file mode 100644 index 0000000..462b3a0 --- /dev/null +++ b/bokehforge/web/view-state.test.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { encodeView, readView, ViewHistory } from "../src/bokehforge/review/static/view-state.js"; + +const defaults = readView({ search: "", hash: "" }); + +function roundTrip(state) { + return readView({ search: encodeView(state), hash: "" }); +} + +test("round-trips the comparison, lightbox and evaluation drafts", () => { + const state = { + dataset: "test dataset", scene: "demo/leaf-1", source: "demo/leaf-1/frame-a", + reference: "demo/leaf-1/ref-b", run: "run:1", stacker: "pancake", + overlay: "damage", family: "tone", tiles: 32, opacity: 0, accent: "#0088cc", + scenes: false, appearance: false, details: ["alignment", "family:tone"], picker: "lightbox", + evaluation: null, + lightbox: { + scene: "demo/leaf-2", run: "run:2", reference: "demo/leaf-2/ref-a", + image: { kind: "output", id: "openfocus" }, zoom: 2.25, pixels: false, + u: 0.3, v: 0.7, swipe: true, split: 0.22, explain: true, + details: ["damage-method"], benchmark: "focus-stack", + }, + }; + assert.deepEqual(roundTrip(state), state); + + const draft = { ...defaults, scene: "demo/leaf-1", evaluation: { + scope: "dataset", tools: [{ + id: "pancake", selected: false, expanded: true, + settings: { fusion: "hybrid", device: "cpu", align: false, threshold: "1.25" }, + }], + } }; + assert.deepEqual(roundTrip(draft), draft); +}); + +test("applies defaults to malformed and duplicate values and discards unrelated fields", () => { + const search = "?overlay=legacy&tiles=4&opacity=31no&accent=%23bad&family=tone&family=range" + + "&lightbox=%7B%22zoom%22%3A0%7D&evaluation=null&rating=5&comment=private&__proto__=bad"; + assert.deepEqual(readView({ search, hash: "" }), defaults); + assert.equal(encodeView({ ...defaults, rating: 5, comment: "private", opacity: "90" }), ""); + assert.equal(roundTrip({ ...defaults, opacity: 100 }).opacity, 100); + assert.equal(roundTrip({ ...defaults, opacity: 0 }).opacity, 0); +}); + +test("legacy fragment links work and query parameters take precedence", () => { + const state = readView({ + search: "?scene=new%2Fleaf&overlay=attention", + hash: "#dataset=demo&scene=old%2Fleaf&run=evaluation", + }); + assert.equal(state.scene, "new/leaf"); + assert.equal(state.dataset, "demo"); + assert.equal(state.run, "evaluation"); + assert.equal(state.overlay, "attention"); +}); + +test("history coalesces range gestures, flushes before pushes, and cancels on back", () => { + let now = 0; + let nextTimer = 0; + const timers = new Map(); + const writes = []; + const page = { + location: new URL("http://localhost/"), + performance: { now: () => now }, + setTimeout(fn) { timers.set(++nextTimer, fn); return nextTimer; }, + clearTimeout(id) { timers.delete(id); }, + history: { + pushState(_state, _title, path) { writes.push(["push", path]); page.location = new URL(path, page.location); }, + replaceState(_state, _title, path) { writes.push(["replace", path]); page.location = new URL(path, page.location); }, + }, + }; + const view = new ViewHistory(page); + view.write({ ...defaults, scene: "one" }, "push"); + now += 40; + view.write({ ...defaults, scene: "one", opacity: 20 }, "continuous"); + view.write({ ...defaults, scene: "one", opacity: 30 }, "continuous"); + assert.equal(timers.size, 1); + view.write({ ...defaults, scene: "two", opacity: 30 }, "push"); + assert.deepEqual(writes, [ + ["push", "/?scene=one"], ["replace", "/?scene=one&opacity=30"], ["push", "/?scene=two&opacity=30"], + ]); + view.write({ ...defaults, scene: "two", opacity: 40 }, "continuous"); + assert.equal(timers.size, 1); + page.location = new URL("http://localhost/?scene=one&opacity=30"); + assert.equal(view.read().opacity, 30); + assert.equal(timers.size, 0); +}); diff --git a/bokehforge/web/view-state.ts b/bokehforge/web/view-state.ts new file mode 100644 index 0000000..71cbbc1 --- /dev/null +++ b/bokehforge/web/view-state.ts @@ -0,0 +1,224 @@ +import { + decodeQueryParams, encodeQueryParams, objectToSearchString, searchStringToObject, + type DecodedValueMap, type QueryParamConfig, +} from "serialize-query-params"; +import * as v from "valibot"; + +const id = v.pipe(v.string(), v.regex(/^[^\u0000-\u001f\u007f]{1,512}$/u), v.check(value => Boolean(value.trim()))); +const mode = v.picklist(["off", "attention", "damage"]); +const family = v.picklist(["all", "tone", "color", "lost_detail", "added_structure", "boundary", "range"]); +const tileSize = v.picklist([8, 32]); +const opacity = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(100)); +const unit = v.pipe(v.number(), v.minValue(0), v.maxValue(1)); +const details = v.pipe(v.array(v.pipe(v.string(), v.regex(/^(?:alignment|damage-method|family:[a-z][a-z0-9_-]{0,39})$/))), v.maxLength(32)); +const image = v.variant("kind", [ + v.object({ kind: v.literal("frame"), id }), + v.object({ kind: v.literal("output"), id }), +]); +const lightbox = v.object({ + scene: id, + run: v.nullable(id), + reference: v.nullable(id), + image, + zoom: v.pipe(v.number(), v.minValue(1), v.maxValue(12)), + pixels: v.boolean(), + u: unit, + v: unit, + swipe: v.boolean(), + split: unit, + explain: v.boolean(), + details, + benchmark: v.nullable(id), +}); +const optionName = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9_-]{0,47}$/)); +const tool = v.object({ + id, + selected: v.boolean(), + expanded: v.boolean(), + settings: v.record(optionName, v.union([v.pipe(v.string(), v.maxLength(128)), v.boolean()])), +}); +const evaluation = v.object({ + scope: v.picklist(["scene", "dataset", "all"]), + tools: v.pipe(v.array(tool), v.maxLength(24)), +}); + +function json(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return undefined; + } +} + +function decimal(text: string): number { + return /^\d+$/.test(text) ? Number(text) : NaN; +} + +function flag(text: string): boolean | undefined { + if (text === "1") return true; + if (text === "0") return false; + return undefined; +} + +function param( + schema: v.GenericSchema, + fallback: T, + parse: (text: string) => unknown = text => text, + format: (value: T) => string = value => String(value), +): QueryParamConfig { + return { + decode(encoded) { + if (typeof encoded !== "string") return fallback; + const result = v.safeParse(schema, parse(encoded)); + return result.success ? result.output : fallback; + }, + encode(value) { + const result = v.safeParse(schema, value); + if (!result.success || JSON.stringify(result.output) === JSON.stringify(fallback)) return undefined; + return format(result.output); + }, + }; +} + +const params = { + dataset: param(v.nullable(id), null), + scene: param(v.nullable(id), null), + run: param(v.nullable(id), null), + stacker: param(v.nullable(id), null), + source: param(v.nullable(id), null), + reference: param(v.nullable(id), null), + overlay: param(mode, "off"), + family: param(family, "all"), + tiles: param(tileSize, 8, decimal), + opacity: param(opacity, 100, decimal), + accent: param(v.nullable(v.pipe(v.string(), v.regex(/^#[a-f0-9]{6}$/i))), null), + scenes: param(v.boolean(), false, flag, value => value ? "1" : "0"), + details: param(details, [], json, JSON.stringify), + picker: param(v.nullable(v.picklist(["output", "lightbox"])), null), + appearance: param(v.boolean(), false, flag, value => value ? "1" : "0"), + evaluation: param(v.nullable(evaluation), null, json, JSON.stringify), + lightbox: param(v.nullable(lightbox), null, json, JSON.stringify), +}; + +export type ViewState = DecodedValueMap; +export type HistoryMode = "push" | "replace" | "continuous"; +type Address = Pick; + +function known(values: Record): Record { + return Object.fromEntries(Object.entries(values).filter(([key]) => Object.hasOwn(params, key))); +} + +export function readView({ search, hash }: Address): ViewState { + // Existing Stackroom links used a fragment with dataset, scene, and run. + const legacy = searchStringToObject(hash.slice(1)); + return decodeQueryParams(params, known({ ...legacy, ...searchStringToObject(search) })); +} + +export function encodeView(state: ViewState): string { + return objectToSearchString(encodeQueryParams(params, known(state))); +} + +export class ViewHistory { + #page: Window; + #timer: number | undefined; + #pending: string | undefined; + #lastWrite = -Infinity; + + constructor(page: Window) { + this.#page = page; + } + + read(): ViewState { + this.#cancel(); + return readView(this.#page.location); + } + + write(state: ViewState, mode: HistoryMode = "replace"): void { + const query = encodeView(state); + const target = this.#page.location.pathname + (query ? "?" + query : ""); + if (mode === "push") { + this.flush(); + this.#write(target, "push"); + } else if (mode === "replace") { + this.#cancel(); + this.#write(target, "replace"); + } else { + this.#pending = target; + if (this.#timer !== undefined) return; + // Range and pan gestures can fire more often than browsers permit history writes. + const wait = this.#lastWrite + 400 - this.#page.performance.now(); + if (wait <= 0) this.flush(); + else this.#timer = this.#page.setTimeout(() => this.flush(), wait); + } + } + + flush(): void { + const target = this.#pending; + this.#cancel(); + if (target !== undefined) this.#write(target, "replace"); + } + + #cancel(): void { + if (this.#timer !== undefined) this.#page.clearTimeout(this.#timer); + this.#timer = this.#pending = undefined; + } + + #write(target: string, mode: "push" | "replace"): void { + const { pathname, search, hash } = this.#page.location; + if (target === pathname + search + hash) return; + this.#page.history[mode === "push" ? "pushState" : "replaceState"](null, "", target); + this.#lastWrite = this.#page.performance.now(); + } +} + +export function readEvaluation(form: HTMLFormElement): ViewState["evaluation"] { + const scope = form.querySelector("#scope")?.value; + const tools = Array.from(form.querySelectorAll(".tool-option"), card => { + const checkbox = card.querySelector('input[name="stacker"]'); + const settings: Record = {}; + for (const control of card.querySelectorAll("[data-setting]")) { + const name = control.dataset.setting; + if (!name) continue; + settings[name] = control instanceof HTMLInputElement && control.type === "checkbox" ? control.checked : control.value; + } + return { + id: checkbox?.value, + selected: checkbox?.checked, + expanded: card.querySelector("details")?.open, + settings, + }; + }); + const result = v.safeParse(evaluation, { scope, tools }); + return result.success ? result.output : null; +} + +export function restoreEvaluation(form: HTMLFormElement, draft: NonNullable): void { + const scope = form.querySelector("#scope"); + if (scope && Array.from(scope.options).some(option => option.value === draft.scope)) { + scope.value = draft.scope; + scope.dispatchEvent(new Event("change")); + } + const tools = new Map(draft.tools.map(tool => [tool.id, tool])); + for (const card of form.querySelectorAll(".tool-option")) { + const checkbox = card.querySelector('input[name="stacker"]'); + if (!checkbox) continue; + const saved = tools.get(checkbox.value); + if (!saved) continue; + checkbox.checked = saved.selected; + const panel = card.querySelector("details"); + if (panel) panel.open = saved.expanded; + for (const control of card.querySelectorAll("[data-setting]")) { + const value = saved.settings[control.dataset.setting ?? ""]; + if (control instanceof HTMLSelectElement) { + if (typeof value === "string" && Array.from(control.options).some(option => option.value === value)) { + control.value = value; + } + } else if (control.type === "checkbox") { + if (typeof value === "boolean") control.checked = value; + } else if (typeof value === "string") { + control.value = value; + } + } + panel?.dispatchEvent(new Event("change")); + } +} diff --git a/bokehforge/web/view-state.types.ts b/bokehforge/web/view-state.types.ts new file mode 100644 index 0000000..ac58fe3 --- /dev/null +++ b/bokehforge/web/view-state.types.ts @@ -0,0 +1,16 @@ +import { encodeView, type ViewState } from "./view-state"; + +type Equal = [A] extends [B] ? [B] extends [A] ? true : false : false; +type Expect = T; + +type Overlay = Expect>; +type Tiles = Expect>; +type Image = Expect["image"], + { kind: "frame"; id: string } | { kind: "output"; id: string }>>; + +declare const state: ViewState; +encodeView(state); +// @ts-expect-error Opacity is a number at the typed boundary. +encodeView({ ...state, opacity: "75" }); +// @ts-expect-error Ratings are not shareable URL state. +encodeView({ ...state, rating: 5 }); From 91ec2a1fa4314a784bc25d744a367ba9aefb0d24 Mon Sep 17 00:00:00 2001 From: Krishna Penukonda Date: Sat, 28 Nov 2026 19:00:19 +0800 Subject: [PATCH 2/3] Run Stackroom URL checks independently of native scoring --- .github/workflows/bokehforge.yml | 14 ------------- .github/workflows/stackroom-web.yml | 31 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/stackroom-web.yml diff --git a/.github/workflows/bokehforge.yml b/.github/workflows/bokehforge.yml index 69fd3b8..cbd646c 100644 --- a/.github/workflows/bokehforge.yml +++ b/.github/workflows/bokehforge.yml @@ -19,20 +19,6 @@ defaults: working-directory: bokehforge jobs: - stackroom-url: - name: Stackroom URL state - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c581273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: "24" - - run: npm ci --ignore-scripts --prefix web - - run: npm --prefix web run check - - run: npm --prefix web test - scoring: name: BokehForge scoring parity (${{ matrix.os }}) runs-on: ${{ matrix.os }} diff --git a/.github/workflows/stackroom-web.yml b/.github/workflows/stackroom-web.yml new file mode 100644 index 0000000..7bee072 --- /dev/null +++ b/.github/workflows/stackroom-web.yml @@ -0,0 +1,31 @@ +name: Stackroom web + +on: + pull_request: + paths: + - bokehforge/web/** + - bokehforge/src/bokehforge/review/static/view-state.js + - .github/workflows/stackroom-web.yml + +permissions: + contents: read + +defaults: + run: + shell: bash + working-directory: bokehforge + +jobs: + stackroom-url: + name: Stackroom URL state + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c581273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + - run: npm ci --ignore-scripts --prefix web + - run: npm --prefix web run check + - run: npm --prefix web test From d49146220525560773a2acb7771bbe9a718a7843 Mon Sep 17 00:00:00 2001 From: Krishna Penukonda Date: Sat, 28 Nov 2026 19:01:32 +0800 Subject: [PATCH 3/3] Use a resolvable pinned checkout for Stackroom web CI --- .github/workflows/stackroom-web.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stackroom-web.yml b/.github/workflows/stackroom-web.yml index 7bee072..187fb89 100644 --- a/.github/workflows/stackroom-web.yml +++ b/.github/workflows/stackroom-web.yml @@ -20,7 +20,7 @@ jobs: name: Stackroom URL state runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c581273ba90b1 # v7.0.1 + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: persist-credentials: false - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0