Spaces:
Paused
Paused
Download public/script.js from Rachel7/hvac_fable: direct link, hf CLI and curl.
- Browser
- Download file 87.6 kB
-
https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/public/script.js
- Command line
-
hf download hf://spaces/Rachel7/hvac_fable/public/script.js
-
curl -L -o script.js https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/public/script.js
87.6 kB
// script.js
const API_BASE = '/api';
let currentTaskId = null;
let currentAnalysis = null;
// manual-flow / upload-first state
let selectedFile = null;
let uploadTaskId = null;
let uploadPages = 0;
let scheduleRegions = []; // [{page, x0, y0, x1, y1}] hand-drawn schedule tables
let scheduleGroups = []; // [{page, region, units:[{tag,type,qty,model,...}]}] from read
let floorPages = []; // [{page_num, name}] hand-picked floor plans
// DOM Elements
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const analyzeBtn = document.getElementById('analyzeBtn');
const loadingSection = document.getElementById('loadingSection');
const resultsSection = document.getElementById('resultsSection');
const errorSection = document.getElementById('errorSection');
const tabs = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');
// ===== FILE UPLOAD =====
uploadArea.addEventListener('click', () => fileInput.click());
// Note under the file info when this exact file already has results on disk
// (content-hash match) — Analyze will reuse them free instead of re-paying.
function showReuseNote(prev) {
let el = document.getElementById('reuseNote');
if (!el) {
el = document.createElement('div');
el.id = 'reuseNote';
el.style.cssText = 'margin:6px 0 0;font-size:0.85em;';
document.getElementById('fileInfo')?.appendChild(el);
}
if (prev && prev.found && prev.reusable) {
el.style.color = '#15803d';
el.textContent = `✓ Previous results found (${prev.floors} floor(s)) — ` +
`Analyze will reuse them free. Tick "force re-detect" to re-run instead.`;
} else if (prev && prev.found) {
el.style.color = '#92400e';
el.textContent = 'A different version of this file was analyzed before — ' +
'Analyze will re-detect fresh.';
} else {
el.textContent = '';
}
}
// Free text-layer scan: point the user at likely schedule pages so step ①
// isn't a 29-page hunt (round-1 focus group: Sal bounced right here).
async function loadScheduleHints() {
if (!uploadTaskId) return;
try {
const res = await fetch(`${API_BASE}/schedule-hints/${uploadTaskId}`);
const d = await res.json();
let el = document.getElementById('scheduleHints');
if (!el) {
el = document.createElement('div');
el.id = 'scheduleHints';
el.style.cssText = 'margin-top:4px;font-size:0.85em;color:#4338ca;';
document.getElementById('addScheduleBtn')?.parentElement?.appendChild(el);
}
el.textContent = (d.schedule_pages || []).length
? `💡 Pages ${d.schedule_pages.join(', ')} look like schedule sheets — start there.`
: '';
} catch (e) { /* advisory */ }
}
// ===== RECENT BUILDINGS (reopen results after a restart / new session) =====
async function loadRecentBuildings() {
try {
const res = await fetch(`${API_BASE}/recent`);
const data = await res.json();
const items = data.recent || [];
if (!items.length) return;
let box = document.getElementById('recentBuildings');
if (!box) {
box = document.createElement('div');
box.id = 'recentBuildings';
box.style.cssText = 'margin-top:14px;padding:10px 12px;background:#f8fafc;'
+ 'border:1px solid #e2e8f0;border-radius:8px;font-size:0.9em;';
uploadArea.parentElement.insertBefore(box, uploadArea.nextSibling);
}
box.innerHTML = '<b>Recent buildings</b> — click to reopen previous results (free):<br>';
items.forEach(it => {
const a = document.createElement('a');
a.href = '#';
a.textContent = `${it.name} (${it.floors} floor(s), ${it.updated})`;
a.style.cssText = 'display:inline-block;margin:4px 12px 0 0;color:#4338ca;';
a.addEventListener('click', async e => {
e.preventDefault();
a.textContent += ' …';
try {
const r = await fetch(`${API_BASE}/reopen`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: it.name })
});
const d = await r.json();
if (d.task_id) {
currentTaskId = uploadTaskId = d.task_id;
uploadPages = d.pages || 0;
currentAnalysis = d.result;
// Enable the step ① pickers — a reopened building skips the
// upload path that normally turns these on, so "Add schedule
// region" / "Add floor page" were dead after a reopen (the
// flag's call-to-action then did nothing).
['addScheduleBtn', 'addFloorBtn'].forEach(id => {
const b = document.getElementById(id); if (b) b.disabled = false;
});
loadScheduleHints(); updateReadBtn();
displayResults(d.result);
resultsSection.style.display = 'block';
loadReview(currentTaskId);
resultsSection.scrollIntoView({ behavior: 'smooth' });
} else {
showError(d.message || d.error || 'Could not reopen — re-upload the PDF (results reload free).');
}
} catch (err) { showError('Reopen failed: ' + err.message); }
a.textContent = a.textContent.replace(' …', '');
});
box.appendChild(a);
});
} catch (e) { /* advisory only — never block the landing page */ }
}
loadRecentBuildings();
// ===== PRODUCT MODE (hide developer surfaces from end users) =====
async function applyGuiConfig() {
try {
const res = await fetch(`${API_BASE}/config`);
const cfg = await res.json();
if (cfg.product_mode) {
// The Symbol Bank tab is a developer tool full of internal
// training data (other buildings' crops) — never show it to
// an end user (round-1 focus group: "somebody else's building?").
document.querySelectorAll('[data-tab="bank"], #bank-tab').forEach(el => {
el.style.display = 'none';
});
[...document.querySelectorAll('.tab-btn')].forEach(b => {
if (/bank/i.test(b.textContent)) b.style.display = 'none';
});
}
} catch (e) { /* config is advisory */ }
}
applyGuiConfig();
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', (e) => {
handleFiles(e.target.files);
});
// Third way in: paste a PDF from the clipboard (Ctrl/⌘+V). Copy a PDF file in
// the OS file manager (or copy a PDF out of another app), then paste anywhere
// on the page. Chromium exposes the copied file via clipboardData.files /
// .items. A plain-text paste (into the tag/floor-name inputs) carries no file,
// so we return early WITHOUT preventDefault — normal text pasting is untouched.
document.addEventListener('paste', (e) => {
const dt = e.clipboardData;
if (!dt) return;
let file = (dt.files && dt.files.length) ? dt.files[0] : null;
if (!file && dt.items) {
for (const it of dt.items) {
if (it.kind === 'file') { file = it.getAsFile(); break; }
}
}
if (!file) return; // no file on the clipboard — ignore
e.preventDefault();
const isPdf = /\.pdf$/i.test(file.name || '') || file.type === 'application/pdf';
if (!isPdf) {
showError('That clipboard item isn’t a PDF — copy a PDF file, then paste.');
return;
}
// Brief green flash so the user sees the paste landed.
uploadArea.classList.add('pasted');
setTimeout(() => uploadArea.classList.remove('pasted'), 700);
handleFiles([file]);
});
// Make the NATIVE right-click ▸ Paste work too. Browsers only put "Paste" in
// the context menu — and only hand a copied FILE to the paste event — on an
// editable element. So mark the drop zone contenteditable, but block every real
// edit (typing, text paste, deletes). A right-click Paste of a PDF then arrives
// as an ordinary paste event and is handled above; nothing is ever typed into
// the box. caret-color:transparent + clearing the selection keep it from
// looking or behaving like a text field.
uploadArea.setAttribute('contenteditable', 'true');
uploadArea.setAttribute('spellcheck', 'false');
uploadArea.setAttribute('aria-label', 'Upload area — drag, click, right-click ▸ Paste, or Ctrl/⌘+V a PDF');
uploadArea.addEventListener('beforeinput', (e) => e.preventDefault()); // no text/edit ever enters
uploadArea.addEventListener('mouseup', () => {
const s = window.getSelection && window.getSelection();
if (s) s.removeAllRanges(); // don't leave a caret/selection after a click
});
function handleFiles(files) {
const file = files[0];
if (!file) return;
if (!/\.pdf$/i.test(file.name || '') && file.type !== 'application/pdf') {
showError('Please upload a PDF file');
return;
}
// Show file info
fileInfo.style.display = 'block';
document.getElementById('fileName').textContent = file.name;
document.getElementById('fileSize').textContent = `(${(file.size / 1024 / 1024).toFixed(2)} MB)`;
// Reset the manual-flow state for a new file.
selectedFile = file;
uploadTaskId = null;
scheduleRegions = []; scheduleGroups = []; floorPages = [];
renderScheduleChips(); renderUnitGroups(); renderFloorChips();
document.getElementById('unitsSection').style.display = 'none';
analyzeBtn.disabled = true;
analyzeBtn.onclick = () => analyzeBlueprint(file);
// Pre-upload so the pickers can render pages before analysis runs.
uploadPdf(file);
}
async function uploadPdf(file) {
const fd = new FormData();
fd.append('file', file);
try {
const res = await fetch(`${API_BASE}/upload`, { method: 'POST', body: fd });
const data = await res.json();
uploadTaskId = data.task_id;
uploadPages = data.pages || 0;
['addScheduleBtn', 'addFloorBtn'].forEach(id => {
const b = document.getElementById(id); if (b) b.disabled = false;
});
// Same file analyzed before (content-hash match) → Analyze reuses the
// cached detections for free; tell the user before they worry about cost.
showReuseNote(data.previous_results);
loadScheduleHints();
updateReadBtn(); updateAnalyzeBtn(); updateFindUnitBtn();
// If this PDF was analyzed before (cached outputs/<name>/ results),
// surface the saved boxes in the Review tab immediately — the user
// shouldn't need to re-run analysis just to review existing floors.
currentTaskId = uploadTaskId;
loadReview(uploadTaskId);
} catch (e) { showError('Upload failed: ' + e.message); }
}
// Enable "Read schedules" once at least one region has been added.
function updateReadBtn() {
const b = document.getElementById('readSchedulesBtn');
if (b) b.disabled = !(uploadTaskId && scheduleRegions.length);
}
// Enable "Analyze" once we have ≥1 floor page. A confirmed schedule is
// OPTIONAL — with no confirmed tags the engine detects every unit tag it finds
// on the drawings (the schedule is a hint/filter, not a prerequisite). Reading
// a schedule first still improves capacity + tag accuracy.
function updateAnalyzeBtn() {
analyzeBtn.disabled = !(uploadTaskId && floorPages.length);
const hint = document.getElementById('analyzeHint');
if (hint) {
const haveTags = getConfirmedTags().length;
hint.textContent = haveTags
? 'Looking for the units you confirmed above.'
: 'No schedule needed — with no units confirmed above, this finds every unit tag on the floors you added. Reading a schedule first improves capacity & tag accuracy.';
}
}
// ===== SCHEDULE REGIONS (chips) =====
function renderScheduleChips() {
const wrap = document.getElementById('scheduleChips');
if (!wrap) return;
wrap.innerHTML = '';
scheduleRegions.forEach((r, i) => {
const whole = (r.x1 - r.x0 > 0.98 && r.y1 - r.y0 > 0.98);
const chip = document.createElement('span');
chip.style.cssText = 'display:inline-flex;align-items:center;gap:6px;background:#e0e7ff;'
+ 'color:#3730a3;border-radius:14px;padding:3px 10px;font-size:0.85em;';
chip.innerHTML = `📐 p${r.page}${whole ? ' (whole)' : ''} `
+ `<a href="#" data-i="${i}" class="chip-x" style="color:#3730a3;text-decoration:none;font-weight:bold;">✕</a>`;
wrap.appendChild(chip);
});
wrap.querySelectorAll('.chip-x').forEach(a => a.addEventListener('click', e => {
e.preventDefault();
scheduleRegions.splice(+a.dataset.i, 1);
renderScheduleChips(); updateReadBtn();
}));
updateReadBtn();
}
// ===== READ SCHEDULES → confirm units =====
async function readSchedules() {
if (!uploadTaskId || !scheduleRegions.length) return;
const btn = document.getElementById('readSchedulesBtn');
const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Reading…';
resultsSection.style.display = 'none';
errorSection.style.display = 'none';
loadingSection.style.display = 'block';
const lt = document.getElementById('loadingText');
if (lt) lt.textContent = 'Reading the selected schedule region(s)…';
setProgress(5, 'Starting…');
try {
const res = await fetch(`${API_BASE}/read-schedules`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task_id: uploadTaskId, regions: scheduleRegions })
});
if (!res.ok) throw new Error((await res.json()).detail || 'Could not read schedules');
scheduleGroups = await pollUntilPrepared(uploadTaskId);
loadingSection.style.display = 'none';
renderUnitGroups();
document.getElementById('unitsSection').style.display =
scheduleGroups.length ? 'block' : 'none';
if (!scheduleGroups.some(g => (g.units || []).length))
showError('No units were read from the selected region(s). Try drawing the box '
+ 'tighter around the table, or add another region.');
// Post-run schedule add: if results already exist (e.g. the flags said
// "AH units aren't in your schedule — it's on p15"), rebuild them from
// the enlarged schedule so capacities update — NO re-detection cost.
if (currentAnalysis && currentTaskId) {
try {
const rr = await fetch(`${API_BASE}/refresh-result`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task_id: currentTaskId })
});
if (rr.ok) {
currentAnalysis = await rr.json();
displayResults(currentAnalysis);
resultsSection.style.display = 'block';
}
} catch (e) { /* advisory */ }
}
} catch (e) {
loadingSection.style.display = 'none';
showError('Read schedules failed: ' + e.message);
} finally { btn.disabled = false; btn.textContent = orig; }
}
async function pollUntilPrepared(taskId) {
while (true) {
await new Promise(r => setTimeout(r, 2000));
const res = await fetch(`${API_BASE}/status/${taskId}`);
if (!res.ok) throw new Error('Lost track of the schedule task');
const job = await res.json();
setProgress(job.percent || 0, `${(job.phase || '').toUpperCase()} — ${job.message || ''}`);
if (job.status === 'prepared') return job.schedule_groups || [];
if (job.status === 'error') throw new Error(job.error || 'Schedule read failed');
}
}
// ===== UNIT CONFIRM LIST (neat table, grouped per schedule region) =====
function renderUnitGroups() {
const wrap = document.getElementById('unitGroups');
if (!wrap) return;
let html = '<table class="units-table" style="width:100%;max-width:560px;border-collapse:collapse;font-size:0.88em;text-align:left;">'
+ '<thead><tr style="border-bottom:2px solid #e2e8f0;color:#475569;">'
+ '<th style="padding:4px 8px;width:36px;text-align:center;">✓</th>'
+ '<th style="padding:4px 8px;">Tag</th>'
+ '<th style="padding:4px 8px;">Type</th>'
+ '<th style="padding:4px 8px;width:48px;text-align:right;">Qty</th>'
+ '<th style="padding:4px 8px;">Model</th></tr></thead><tbody>';
scheduleGroups.forEach((g, gi) => {
const units = g.units || [];
html += `<tr style="background:#f8fafc;"><td colspan="5" style="padding:4px 8px;font-weight:600;color:#334155;">`
+ `Schedule p${g.page} — ${units.length} unit(s)</td></tr>`;
if (!units.length) {
html += '<tr><td colspan="5" style="padding:4px 8px;color:#94a3b8;">No units read from this region.</td></tr>';
}
units.forEach((u, ui) => {
// Word-fragment junk (OCR reads "AIR CONDI-TIONING" as a tag
// "AC-TION" with a huge qty) arrives with no type, no model, and an
// implausible count — default it UNTICKED with a warning so the
// user opts IN instead of having to spot it (round-1 focus group).
const suspicious = looksLikeJunkTag(u);
const cb = `<input type="checkbox" class="unit-cb" data-tag="${u.tag}" id="u_${gi}_${ui}" ${suspicious ? '' : 'checked'}>`;
const warn = suspicious
? ` <span title="No type, no model, and an implausible quantity — usually a text fragment misread as a tag. Tick it only if it's a real unit." style="color:#b45309;">⚠ looks like a text fragment</span>`
: '';
html += `<tr style="border-bottom:1px solid #f1f5f9;${suspicious ? 'opacity:0.65;' : ''}">`
+ `<td style="padding:3px 8px;text-align:center;">${cb}</td>`
+ `<td style="padding:3px 8px;font-weight:600;">${u.tag}${warn}</td>`
+ `<td style="padding:3px 8px;color:#64748b;">${u.type || ''}</td>`
+ `<td style="padding:3px 8px;text-align:right;color:#64748b;">${u.qty != null ? u.qty : ''}</td>`
+ `<td style="padding:3px 8px;color:#64748b;">${u.model || ''}</td></tr>`;
});
});
html += '</tbody></table>';
wrap.innerHTML = html;
wrap.querySelectorAll('.unit-cb').forEach(cb => cb.addEventListener('change', updateAnalyzeBtn));
updateAnalyzeBtn();
}
// Junk heuristic for schedule reads: real units carry a type or a model or a
// sane quantity; hyphenation fragments ("AC-TION" from "AIR CONDI-TIONING")
// carry none and often absurd counts. Conservative on purpose — a real bare
// tag with qty 4 (AH-1) is NOT flagged.
function looksLikeJunkTag(u) {
const bare = !(u.type || '').trim() && !(u.model || '').trim();
if (!bare) return false;
const qty = +u.qty || 0;
const tail = (u.tag || '').split('-').slice(1).join('-');
const fragment = /^(TION|TIONS|MENT|NING|CESS|SION|ANCE|ABLE)$/i.test(tail);
return fragment || qty >= 15;
}
// Unique set of ticked tags across all groups.
function getConfirmedTags() {
const tags = new Set();
document.querySelectorAll('.unit-cb:checked').forEach(cb => tags.add(cb.dataset.tag));
return [...tags];
}
// ===== FLOOR PAGES (chips) =====
function renderFloorChips() {
const wrap = document.getElementById('floorChips');
if (!wrap) return;
wrap.innerHTML = '';
floorPages.forEach((f, i) => {
const chip = document.createElement('span');
chip.style.cssText = 'display:inline-flex;align-items:center;gap:6px;background:#dcfce7;'
+ 'color:#166534;border-radius:14px;padding:3px 10px;font-size:0.85em;';
chip.innerHTML = `🏗️ p${f.page_num} — ${f.name || ('Page ' + f.page_num)} `
+ `<a href="#" data-i="${i}" class="fchip-x" style="color:#166534;text-decoration:none;font-weight:bold;">✕</a>`;
wrap.appendChild(chip);
});
wrap.querySelectorAll('.fchip-x').forEach(a => a.addEventListener('click', e => {
e.preventDefault();
floorPages.splice(+a.dataset.i, 1);
renderFloorChips(); updateAnalyzeBtn();
}));
renderCustomScope();
updateAnalyzeBtn();
}
// ===== FIND A CUSTOM UNIT (not in the schedule) =====
// Scope dropdown: "all selected floors" or one specific floor page.
function renderCustomScope() {
const sel = document.getElementById('customScope');
if (!sel) return;
const prev = sel.value;
sel.innerHTML = '<option value="all">all selected floors</option>'
+ floorPages.map(f => `<option value="${f.page_num}">p${f.page_num} — ${f.name || ('Page ' + f.page_num)}</option>`).join('');
if ([...sel.options].some(o => o.value === prev)) sel.value = prev;
updateFindUnitBtn();
}
function updateFindUnitBtn() {
const tag = (document.getElementById('customTagInput')?.value || '').trim();
const b = document.getElementById('findUnitBtn');
if (b) b.disabled = !(uploadTaskId && floorPages.length && tag);
}
async function findUnit() {
const tag = (document.getElementById('customTagInput')?.value || '').trim();
if (!tag) { showError('Type a unit tag to find.'); return; }
if (!floorPages.length) { showError('Add at least one floor page first (step ③).'); return; }
const scope = document.getElementById('customScope').value;
const scopePages = scope === 'all'
? floorPages
: floorPages.filter(f => String(f.page_num) === String(scope));
const modelChoice = document.querySelector('input[name="model"]:checked').value;
resultsSection.style.display = 'none';
errorSection.style.display = 'none';
loadingSection.style.display = 'block';
const lt = document.getElementById('loadingText');
if (lt) lt.textContent = `Searching for ${tag}…`;
setProgress(2, 'Starting…');
const btn = document.getElementById('findUnitBtn');
const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Searching…';
try {
const res = await fetch(`${API_BASE}/find-unit`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
task_id: uploadTaskId, tags: tag, floor_pages: scopePages,
model_choice: modelChoice
})
});
if (!res.ok) throw new Error((await res.json()).detail || 'Find unit failed');
currentTaskId = (await res.json()).task_id;
const result = await pollUntilDone(currentTaskId);
currentAnalysis = result;
loadingSection.style.display = 'none';
displayResults(result);
resultsSection.style.display = 'block';
loadReview(currentTaskId);
} catch (e) {
loadingSection.style.display = 'none';
showError('Find unit failed: ' + e.message);
} finally { btn.disabled = false; btn.textContent = orig; updateFindUnitBtn(); }
}
document.getElementById('findUnitBtn')?.addEventListener('click', findUnit);
document.getElementById('customTagInput')?.addEventListener('input', updateFindUnitBtn);
// ===== "What to look for" — multi-select checkbox dropdown =====
// Pick one or more categories. Only "indoor" has an active detector today; the
// rest are selectable but flagged "coming soon". The chosen list is sent to the
// backend as look_for so the plumbing is ready as detectors ship.
const LOOKFOR_LABELS = {
indoor: 'Indoor units', diffusers: 'Diffusers', fans: 'Fans',
electric_heaters: 'Electric heaters', dampers: 'Dampers', cav: 'CAV',
rooftop: 'Rooftop units', ptac: 'PTAC', branch_boxes: 'Branch boxes',
condensers: 'Condensers', erv: 'ERVs'
};
// Every category is now wired to the engine. "indoor" is fully tuned; the rest
// are basic (beta) first-pass detectors, flagged so the user knows they're rough.
const LOOKFOR_TUNED = new Set(['indoor']);
function getLookFor() {
return [...document.querySelectorAll('.lookfor-cb:checked')].map(cb => cb.value);
}
function updateLookForUI() {
const sel = getLookFor();
const summary = document.getElementById('lookForSummary');
if (summary) {
summary.textContent = sel.length
? sel.map(v => LOOKFOR_LABELS[v] || v).join(', ')
: 'Choose what to look for…';
}
const note = document.getElementById('lookForNote');
if (note) {
const beta = sel.filter(v => !LOOKFOR_TUNED.has(v));
if (!sel.length) {
note.textContent = 'Pick at least one category to look for.';
note.style.color = '#b45309';
} else if (!beta.length) {
note.textContent = 'Indoor units is fully tuned.';
note.style.color = '#64748b';
} else {
const names = beta.map(v => LOOKFOR_LABELS[v] || v).join(', ');
note.textContent = `${names} ${beta.length > 1 ? 'are' : 'is'} beta (basic detectors) — `
+ `they’ll find symbols to review, but may miss or over-detect until refined.`;
note.style.color = '#b45309';
}
}
}
(function initLookForMulti() {
const multi = document.getElementById('lookForMulti');
const toggle = document.getElementById('lookForToggle');
const panel = document.getElementById('lookForPanel');
if (!multi || !toggle || !panel) return;
const open = () => { panel.hidden = false; multi.classList.add('open'); toggle.setAttribute('aria-expanded', 'true'); };
const close = () => { panel.hidden = true; multi.classList.remove('open'); toggle.setAttribute('aria-expanded', 'false'); };
toggle.addEventListener('click', (e) => {
e.stopPropagation();
panel.hidden ? open() : close();
});
// Ticking a box shouldn't close the panel — let users pick several at once.
panel.addEventListener('click', (e) => e.stopPropagation());
panel.querySelectorAll('.lookfor-cb').forEach(cb => cb.addEventListener('change', updateLookForUI));
document.addEventListener('click', close); // click outside closes
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); });
updateLookForUI();
})();
function formatDuration(totalSeconds) {
const s = Math.max(0, Math.round(totalSeconds || 0));
if (s < 60) return `${s}s`;
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
if (h) return `${h}h ${m}m ${sec}s`;
return `${m}m ${sec}s`;
}
document.getElementById('readSchedulesBtn')?.addEventListener('click', readSchedules);
// ===== ANALYSIS =====
async function analyzeBlueprint(file) {
const modelChoice = document.querySelector('input[name="model"]:checked').value;
const g = id => document.getElementById(id);
// A confirmed schedule is optional. Require only ≥1 floor page; with no
// confirmed tags the engine detects every tag it finds (all-tags mode).
const confirmedTags = getConfirmedTags();
if (!floorPages.length) { showError('Add at least one floor page to analyze.'); return; }
const tagPrefixes = (g('rTagPrefixes')?.value || '').trim();
const recipe = g('rRuns') ? {
runs: +g('rRuns').value, tile: +g('rTile').value, consensus: +g('rConsensus').value,
all_tags: g('rAllTags').checked, fp_filter: g('rFp').checked, force: g('rForce').checked,
...(tagPrefixes ? { tag_prefixes: tagPrefixes } : {})
} : {};
// No schedule confirmed → make sure we sweep for every tag, not a filtered set.
if (!confirmedTags.length) recipe.all_tags = true;
// Show loading
resultsSection.style.display = 'none';
errorSection.style.display = 'none';
loadingSection.style.display = 'block';
const lt2 = document.getElementById('loadingText');
if (lt2) lt2.textContent = 'Detecting units…';
setProgress(2, 'Starting…');
try {
const res = await fetch(`${API_BASE}/detect`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
task_id: uploadTaskId, model_choice: modelChoice, recipe,
floor_pages: floorPages, confirmed_tags: confirmedTags,
look_for: getLookFor()
})
});
if (!res.ok) throw new Error((await res.json()).detail || 'Analysis failed');
const started = await res.json();
currentTaskId = started.task_id;
// Poll status until done/error (real detection is minutes per page)
const result = await pollUntilDone(currentTaskId);
currentAnalysis = result;
loadingSection.style.display = 'none';
displayResults(result);
resultsSection.style.display = 'block';
loadReview(currentTaskId);
} catch (error) {
loadingSection.style.display = 'none';
showError(error.message);
}
}
function setProgress(percent, message) {
const fill = document.getElementById('progressFill');
if (fill) fill.style.width = (percent || 0) + '%';
const msg = document.getElementById('progressMessage');
if (msg && message) msg.textContent = message;
}
async function pollUntilDone(taskId) {
while (true) {
await new Promise(r => setTimeout(r, 2000));
const res = await fetch(`${API_BASE}/status/${taskId}`);
if (!res.ok) throw new Error('Lost track of the analysis task');
const job = await res.json();
setProgress(job.percent || 0,
`${(job.phase || '').toUpperCase()} — ${job.message || ''}`);
if (job.status === 'done') {
if (!job.result) throw new Error(
'Finished but no result returned — restart the server and hard-refresh (Ctrl+F5).');
return job.result;
}
if (job.status === 'error') throw new Error(job.error || 'Analysis failed');
}
}
// ===== DISPLAY RESULTS =====
function displayResults(result) {
if (!result || !result.summary) {
showError('No result to display (the analysis returned nothing — restart the '
+ 'server and hard-refresh the page with Ctrl+F5).');
return;
}
// Summary tab
document.getElementById('totalFloors').textContent = result.summary.total_floors;
// Verified (green/orange) is THE headline number a bid can use. Yellows are
// shown as "to review", gray noise as "rejected" — never mixed into one count.
const vu = result.summary.verified_units;
document.getElementById('totalUnits').textContent =
(vu !== undefined) ? vu : result.summary.total_units;
const bd = document.getElementById('unitsBreakdown');
if (bd) {
const eq = result.summary.equipment_units || 0;
bd.textContent = (vu !== undefined)
? `+${result.summary.review_units || 0} to review · ${result.summary.noise_units || 0} rejected`
+ (eq ? ` · ${eq} equipment (ERV/MUA…)` : '')
: '';
}
// Capacity comes from the schedule (BTU per unit tag). With no schedule
// read, there's no capacity to total — show "—" + a nudge instead of a bare
// "0k BTU" (which reads like "OK" and looks like a real zero).
const btu = result.summary.total_capacity_btu || 0;
const capNote = document.getElementById('capacityNote');
if (btu > 0) {
document.getElementById('totalCapacity').textContent = `${(btu / 1000).toFixed(0)}k BTU`;
if (capNote) capNote.textContent = '';
} else {
document.getElementById('totalCapacity').textContent = '—';
if (capNote) capNote.textContent = 'Add a schedule to see total BTU';
}
document.getElementById('processingTime').textContent =
formatDuration(result.processing_time_seconds);
document.getElementById('modelUsed').textContent = result.model_used;
document.getElementById('fileName2').textContent = result.file_name;
document.getElementById('costUsed').textContent = `$${result.cost_usd.toFixed(4)}`;
// Floors table
populateFloorsTable(result.floors);
// Flags / reconciliation
renderFlags(result.reconciliation);
// Floor Plan tab — real annotated PNGs (colored boxes) from the engine
loadAnnotated(currentTaskId);
// Download buttons
setupDownloadButtons(result.csv_files);
}
function populateFloorsTable(floors) {
const tbody = document.getElementById('floorsTableBody');
tbody.innerHTML = '';
floors.forEach(floor => {
// Show the REAL floor name ("Cellar", "3rd Floor") from the PDF text
// layer, not the raw page ordinal. The multi-floor case carries a
// verbose "(sheet pN: …)" provenance suffix — keep it on hover only.
const fullName = floor.floor_name || `Floor ${floor.floor_number}`;
const floorLabel = fullName.split(' (sheet ')[0];
floor.units.forEach(unit => {
const row = tbody.insertRow();
// ERV/MUA/EF/CU… are real equipment but NOT indoor units — shown
// muted with a badge, excluded from the verified count/capacity.
const isEquip = unit.scope === 'equipment';
if (isEquip) row.style.opacity = '0.6';
row.innerHTML = `
<td title="${fullName.replace(/"/g, '"')}">${floorLabel}</td>
<td><strong>${unit.tag}</strong>${isEquip ? ' <span style="font-size:0.78em;color:#b45309;">equipment</span>' : ''}</td>
<td>${unit.type || '-'}</td>
<td>${unit.model || '-'}</td>
<td>${unit.quantity}</td>
<td>${unit.capacity_btu || '-'}</td>
<td>${unit.capacity_kw || '-'}</td>
<td>${unit.location || '-'}</td>
`;
});
});
}
// Load the engine's annotated floor PNGs (colored bounding boxes) into the
// Floor Plan tab, with a per-floor selector and a download link.
async function loadAnnotated(taskId) {
const sel = document.getElementById('annotatedSelect');
const img = document.getElementById('annotatedImg');
const ctrls = document.getElementById('annotatedControls');
const empty = document.getElementById('annotatedEmpty');
const dl = document.getElementById('annotatedDownload');
if (!sel || !img) return;
try {
const res = await fetch(`${API_BASE}/annotated/${taskId}`);
const data = await res.json();
const floors = (data.floors || []).filter(f => f.url);
if (!floors.length) {
ctrls.style.display = 'none'; img.style.display = 'none';
empty.style.display = 'block';
empty.textContent = 'No annotated images yet for this run.';
return;
}
sel.innerHTML = '';
floors.forEach(f => {
const o = document.createElement('option');
o.value = f.url; o.textContent = `p${f.page_num} — ${f.floor_name}`;
o.dataset.page = f.page_num;
sel.appendChild(o);
});
const show = () => {
const opt = sel.options[sel.selectedIndex];
// cache-bust so re-runs / re-reviews refresh the image
const bust = `?t=${Date.now()}`;
img.src = opt.value + bust;
img.style.display = 'block';
// cache-bust the download too, so re-downloading after a re-review
// fetches the freshly redrawn PNG (kept boxes only) not a cached copy
if (dl) { dl.href = opt.value + bust; dl.setAttribute('download', `floor_${opt.dataset.page}_annotated.png`); }
};
sel.onchange = show;
ctrls.style.display = 'flex';
empty.style.display = 'none';
show();
} catch (e) {
ctrls.style.display = 'none';
empty.style.display = 'block';
empty.textContent = 'Could not load annotated images.';
}
}
function drawFloorPlan(floors) {
const canvas = document.getElementById('floorCanvas');
const ctx = canvas.getContext('2d');
// Clear canvas
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw background
ctx.strokeStyle = '#e2e8f0';
ctx.lineWidth = 1;
for (let i = 0; i < canvas.width; i += 50) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
// Draw floors
const floorHeight = canvas.height / (floors.length + 1);
floors.forEach((floor, floorIndex) => {
const y = 50 + floorIndex * floorHeight;
// Floor label
ctx.fillStyle = '#1e293b';
ctx.font = 'bold 16px Arial';
ctx.fillText(`Floor ${floor.floor_number}`, 20, y);
// Units
let unitX = 150;
floor.units.forEach(unit => {
drawUnit(ctx, unitX, y, unit);
unitX += 120;
});
// Floor line
ctx.strokeStyle = '#cbd5e1';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(0, y + 40);
ctx.lineTo(canvas.width, y + 40);
ctx.stroke();
});
}
function drawUnit(ctx, x, y, unit) {
// Unit box
ctx.fillStyle = '#dbeafe';
ctx.fillRect(x, y, 100, 30);
ctx.strokeStyle = '#2563eb';
ctx.lineWidth = 2;
ctx.strokeRect(x, y, 100, 30);
// Unit text
ctx.fillStyle = '#1e293b';
ctx.font = 'bold 12px Arial';
ctx.textAlign = 'center';
ctx.fillText(unit.tag, x + 50, y + 20);
// Capacity below
ctx.font = '10px Arial';
ctx.fillStyle = '#64748b';
ctx.fillText(`${unit.quantity}x${Math.round(unit.capacity_btu / 1000)}k`, x + 50, y + 35);
}
function setupDownloadButtons(csvFiles) {
csvFiles = csvFiles || {};
// Fall back to building the URL from the task id if csv_files is missing.
const csvUrl = (name) => csvFiles[name] || `${API_BASE}/download/csv/${currentTaskId}/${name}`;
document.getElementById('downloadFloors').onclick = () =>
downloadFile(csvUrl('floors_units'), 'hvac_floors_units.csv');
document.getElementById('downloadSchedule').onclick = () =>
downloadFile(csvUrl('equipment_schedule'), 'hvac_equipment_schedule.csv');
document.getElementById('downloadReconciliation').onclick = () =>
downloadFile(csvUrl('reconciliation'), 'hvac_reconciliation.csv');
document.getElementById('downloadZip').onclick = () =>
downloadFile(`${API_BASE}/download/zip/${currentTaskId}`, 'hvac_analysis.zip');
}
function downloadFile(url, filename) {
// The anchor MUST be in the DOM for the download to fire in several browsers.
const a = document.createElement('a');
a.href = url;
a.download = filename || '';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
setTimeout(() => a.remove(), 0);
}
// ===== TABS =====
tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove active from all
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
// Add active to clicked
tab.classList.add('active');
const tabId = tab.dataset.tab + '-tab';
document.getElementById(tabId).classList.add('active');
});
});
// ===== ERROR HANDLING =====
function showError(message) {
loadingSection.style.display = 'none';
resultsSection.style.display = 'none';
errorSection.style.display = 'block';
document.getElementById('errorMessage').textContent = message;
}
// ===== FLAGS / RECONCILIATION =====
// Flags tab — one plain-English card per flag: a friendly severity badge, a
// "what's going on" title, the specifics, and a highlighted "what to do" step.
const FLAG_META = {
high: { color: '#dc2626', bg: '#fef2f2', label: 'NEEDS ATTENTION', icon: '⚠️' },
medium: { color: '#ca8a04', bg: '#fefce8', label: 'WORTH A LOOK', icon: '🔎' },
low: { color: '#64748b', bg: '#f8fafc', label: 'FYI', icon: 'ℹ️' },
};
const FLAG_RANK = { high: 0, medium: 1, low: 2 };
function esc(s) { const p = document.createElement('div'); p.textContent = s == null ? '' : String(s); return p.innerHTML; }
function renderFlags(rec) {
rec = rec || { issues: [] };
const issues = (rec.issues || []).slice()
.sort((a, b) => (FLAG_RANK[a.severity] ?? 9) - (FLAG_RANK[b.severity] ?? 9));
const hi = rec.high_severity || 0, me = rec.medium_severity || 0, lo = rec.low_severity || 0;
const sum = document.getElementById('flagsSummary');
if (sum) sum.textContent = issues.length
? `${issues.length} thing${issues.length > 1 ? 's' : ''} to check — ${hi} need attention, ${me} worth a look, ${lo} FYI.`
: '';
const list = document.getElementById('flagsList');
if (!list) return;
if (!issues.length) {
list.innerHTML = '<p style="color:#16a34a;font-weight:600;padding:8px 0;">✓ All clear — the counts add up and nothing looks missing.</p>';
return;
}
list.innerHTML = issues.map(i => {
const m = FLAG_META[i.severity] || FLAG_META.low;
const title = esc(i.title || (i.type || 'Flag').replace(/_/g, ' '));
const body = i.message ? `<div style="color:#475569;font-size:0.92em;line-height:1.45;margin-top:3px;">${esc(i.message)}</div>` : '';
const action = i.action ? `<div style="margin-top:9px;padding:8px 11px;background:#fff;border-radius:5px;font-size:0.92em;color:#0f172a;line-height:1.45;"><strong style="color:${m.color};">→ What to do:</strong> ${esc(i.action)}</div>` : '';
// Room-gap flags carry crop PNGs of the exact spot — show them so the
// user sees WHERE, not just which floor. Click to open full-size.
let crops = '';
if (Array.isArray(i.crops) && i.crops.length && currentTaskId) {
const thumbs = i.crops.slice(0, 6).map(c => {
const u = `${API_BASE}/roomgap-crop/${currentTaskId}/${encodeURIComponent(c)}`;
return `<a href="${u}" target="_blank" rel="noopener" title="Open this spot full-size">`
+ `<img src="${u}" loading="lazy" style="width:130px;height:130px;object-fit:cover;`
+ `border:2px solid ${m.color}66;border-radius:6px;background:#fff;"></a>`;
}).join('');
const more = i.crops.length > 6 ? `<span style="align-self:center;color:#64748b;font-size:0.85em;">+${i.crops.length - 6} more</span>` : '';
crops = `<div style="margin-top:10px;display:flex;flex-wrap:wrap;gap:8px;">${thumbs}${more}</div>`
+ `<div style="font-size:0.8em;color:#64748b;margin-top:4px;">👆 The exact spot on the plan — the flagged room is at the center of each. Click to enlarge.</div>`;
}
return `<div style="padding:12px 14px;margin:10px 0;background:${m.bg};border:1px solid ${m.color}33;border-left:4px solid ${m.color};border-radius:6px;">`
+ `<div style="font-size:0.66em;font-weight:700;letter-spacing:.05em;color:${m.color};margin-bottom:5px;">${m.icon} ${m.label}</div>`
+ `<div style="font-weight:650;color:#0f172a;">${title}</div>`
+ body + action + crops + `</div>`;
}).join('');
}
// ===== REVIEW — VISUAL BOX EDITOR (approve / move / resize / relabel / add / delete) =====
const STATE_COLOR = { green: '#16a34a', orange: '#ea580c', yellow: '#ca8a04', purple: '#9333ea', gray: '#9ca3af', blue: '#2563eb' };
let reviewFloors = []; // [{file,floor_name,page_num,width,height,boxes:[...]}]
let edFloorIdx = 0; // index into reviewFloors of the floor being edited
let edBoxes = []; // working copy of the current floor's boxes
let edImg = null; // loaded page Image
let edScale = 1; // canvas px per 300-dpi source px
let edSel = -1; // selected box index (-1 = none)
let edDrag = null; // {mode:'move'|'nw'|..|'new'|'pan', sx, sy, box0}
let edAdd = false; // "add unit" mode armed
let edZoom = 1; // wheel zoom (1 = fit width)
let edPanX = 0, edPanY = 0; // pan offset in canvas px
const ED_MAXW = 1000; // canvas display width cap
const HANDLE = 6;
// combined source(300-dpi)px → canvas px scale, and the inverse mapping
function edS() { return edScale * edZoom; }
function screenToSrc(mx, my) { const s = edS(); return [(mx - edPanX) / s, (my - edPanY) / s]; }
function edClampPan() {
const canvas = document.getElementById('editorCanvas');
if (!canvas) return;
const dw = canvas.width * edZoom, dh = canvas.height * edZoom;
edPanX = Math.min(0, Math.max(canvas.width - dw, edPanX));
edPanY = Math.min(0, Math.max(canvas.height - dh, edPanY));
}
async function loadReview(taskId) {
try {
const res = await fetch(`${API_BASE}/review/${taskId}`);
if (!res.ok) return;
const data = await res.json();
reviewFloors = data.floors || [];
const sel = document.getElementById('reviewFloorSelect');
if (sel) {
sel.innerHTML = reviewFloors.map((f, i) =>
`<option value="${i}">p${f.page_num} — ${f.floor_name || ''} (${(f.boxes || []).length})</option>`).join('');
if (edFloorIdx >= reviewFloors.length) edFloorIdx = 0;
sel.value = edFloorIdx;
}
// Cached results reconnected on upload (no analysis this session):
// the tabs live inside resultsSection which starts hidden, so unhide
// it and land on Review — otherwise the cached floors are unreachable.
if (reviewFloors.length && resultsSection.style.display === 'none') {
resultsSection.style.display = 'block';
document.querySelector('.tab-btn[data-tab="review"]')?.click();
}
loadEditorFloor(edFloorIdx);
} catch (e) { /* review panel is optional */ }
}
function loadEditorFloor(idx) {
edFloorIdx = idx; edSel = -1; edAdd = false; edDrag = null;
edZoom = 1; edPanX = 0; edPanY = 0;
const fl = reviewFloors[idx];
const canvas = document.getElementById('editorCanvas');
if (!fl || !canvas) return;
// deep-copy boxes so edits aren't committed until Save
edBoxes = (fl.boxes || []).map(b => ({ ...b }));
edImg = new Image();
edImg.onload = () => {
edScale = ED_MAXW / (fl.width || edImg.naturalWidth || ED_MAXW);
canvas.width = Math.round((fl.width || edImg.naturalWidth) * edScale);
canvas.height = Math.round((fl.height || edImg.naturalHeight) * edScale);
drawEditor();
};
edImg.src = `${API_BASE}/page-image/${currentTaskId}/${fl.page_num}?dpi=150&max=3000`;
updateSelToolbar(); updateNoiseCount();
}
// ── rotated-box geometry (b.angle = degrees, rotated about the box center) ──
function boxCenterScreen(b) {
const s = edS();
return [(b.x + b.w / 2) * s + edPanX, (b.y + b.h / 2) * s + edPanY];
}
// corner + rotation-handle positions in SCREEN px, honouring b.angle
function boxPtsScreen(b) {
const s = edS();
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const rad = (b.angle || 0) * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad);
const local = {
nw: [b.x, b.y], ne: [b.x + b.w, b.y],
sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h],
rot: [cx, b.y - 22 / s], // 22 screen-px above top-centre
};
const out = {};
for (const k in local) {
const dx = local[k][0] - cx, dy = local[k][1] - cy;
out[k] = [(cx + dx * cos - dy * sin) * s + edPanX,
(cy + dx * sin + dy * cos) * s + edPanY];
}
return out;
}
// map a source-space point into a box's LOCAL (unrotated) frame
function toBoxLocal(b, ix, iy) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const rad = -(b.angle || 0) * Math.PI / 180, cos = Math.cos(rad), sin = Math.sin(rad);
const dx = ix - cx, dy = iy - cy;
return [cx + dx * cos - dy * sin, cy + dx * sin + dy * cos];
}
function drawEditor() {
const canvas = document.getElementById('editorCanvas');
if (!canvas) return;
const ctx = canvas.getContext('2d');
const s = edS();
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (edImg) ctx.drawImage(edImg, edPanX, edPanY, canvas.width * edZoom, canvas.height * edZoom);
edBoxes.forEach((b, i) => {
if (b.deleted) return;
const col = STATE_COLOR[b.color] || (b.status === 'added' ? STATE_COLOR.purple : '#ef4444');
const w = b.w * s, h = b.h * s;
const [ccx, ccy] = boxCenterScreen(b);
ctx.save();
ctx.translate(ccx, ccy);
ctx.rotate((b.angle || 0) * Math.PI / 180);
ctx.lineWidth = i === edSel ? 3 : 2;
ctx.strokeStyle = col;
ctx.setLineDash(b.color === 'gray' ? [5, 4] : []);
ctx.strokeRect(-w / 2, -h / 2, w, h);
ctx.setLineDash([]);
ctx.fillStyle = col;
ctx.font = 'bold 13px sans-serif';
ctx.fillText(b.tag || '?', -w / 2 + 2, -h / 2 - 3);
ctx.restore();
if (i === edSel) {
const pts = boxPtsScreen(b);
['nw', 'ne', 'sw', 'se'].forEach(k => {
const [hx, hy] = pts[k];
ctx.fillStyle = '#000'; ctx.fillRect(hx - HANDLE, hy - HANDLE, HANDLE * 2, HANDLE * 2);
ctx.strokeStyle = col; ctx.strokeRect(hx - HANDLE, hy - HANDLE, HANDLE * 2, HANDLE * 2);
});
// rotation handle: stem from top-centre up to a small circle
const [rx, ry] = pts.rot;
const tx = (pts.nw[0] + pts.ne[0]) / 2, ty = (pts.nw[1] + pts.ne[1]) / 2;
ctx.strokeStyle = col; ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(rx, ry); ctx.stroke();
ctx.beginPath(); ctx.arc(rx, ry, HANDLE, 0, 2 * Math.PI);
ctx.fillStyle = '#fff'; ctx.fill(); ctx.strokeStyle = col; ctx.stroke();
}
});
}
// hit-test the selected box's handles; returns 'nw'|'ne'|'sw'|'se'|'rotate'|null
function hitHandle(mx, my) {
if (edSel < 0) return null;
const pts = boxPtsScreen(edBoxes[edSel]);
if (Math.hypot(mx - pts.rot[0], my - pts.rot[1]) <= HANDLE + 3) return 'rotate';
for (const name of ['nw', 'ne', 'sw', 'se'])
if (Math.abs(mx - pts[name][0]) <= HANDLE && Math.abs(my - pts[name][1]) <= HANDLE) return name;
return null;
}
function boxAt(mx, my) {
const [ix, iy] = screenToSrc(mx, my);
for (let i = edBoxes.length - 1; i >= 0; i--) {
const b = edBoxes[i];
if (b.deleted) continue;
const [lx, ly] = toBoxLocal(b, ix, iy); // into box-local frame for rotated boxes
if (lx >= b.x && lx <= b.x + b.w && ly >= b.y && ly <= b.y + b.h) return i;
}
return -1;
}
function canvasXY(e) {
const canvas = document.getElementById('editorCanvas');
const r = canvas.getBoundingClientRect();
return [(e.clientX - r.left) * (canvas.width / r.width),
(e.clientY - r.top) * (canvas.height / r.height)];
}
function initEditorCanvas() {
const canvas = document.getElementById('editorCanvas');
if (!canvas || canvas._wired) return;
canvas._wired = true;
canvas.addEventListener('wheel', e => {
e.preventDefault();
const [mx, my] = canvasXY(e);
const [sx, sy] = screenToSrc(mx, my);
edZoom = Math.min(10, Math.max(1, edZoom * (e.deltaY < 0 ? 1.2 : 1 / 1.2)));
// keep the source point under the cursor fixed
edPanX = mx - sx * edS(); edPanY = my - sy * edS();
edClampPan(); drawEditor();
}, { passive: false });
canvas.addEventListener('mousedown', e => {
const [mx, my] = canvasXY(e);
if (edAdd) { const [sx, sy] = screenToSrc(mx, my); edDrag = { mode: 'new', sx, sy }; return; }
const handle = hitHandle(mx, my);
if (handle) { edDrag = { mode: handle, box0: { ...edBoxes[edSel] } }; return; }
const hit = boxAt(mx, my);
if (hit >= 0) {
edSel = hit; updateSelToolbar();
const [sx, sy] = screenToSrc(mx, my);
edDrag = { mode: 'move', sx, sy, box0: { ...edBoxes[hit] } };
} else {
edSel = -1; updateSelToolbar();
edDrag = { mode: 'pan', lastx: mx, lasty: my }; // drag empty space to pan
}
drawEditor();
});
canvas.addEventListener('mousemove', e => {
if (!edDrag) return;
const [mx, my] = canvasXY(e);
if (edDrag.mode === 'pan') {
edPanX += mx - edDrag.lastx; edPanY += my - edDrag.lasty;
edDrag.lastx = mx; edDrag.lasty = my; edClampPan(); drawEditor(); return;
}
const [ix, iy] = screenToSrc(mx, my);
if (edDrag.mode === 'new') {
edDrag.cx = ix; edDrag.cy = iy;
drawEditor();
const ctx = canvas.getContext('2d'); const s = edS();
ctx.strokeStyle = STATE_COLOR.purple; ctx.lineWidth = 2;
ctx.strokeRect(Math.min(edDrag.sx, ix) * s + edPanX, Math.min(edDrag.sy, iy) * s + edPanY,
Math.abs(ix - edDrag.sx) * s, Math.abs(iy - edDrag.sy) * s);
return;
}
const b = edBoxes[edSel]; const b0 = edDrag.box0;
if (edDrag.mode === 'rotate') {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
let deg = Math.atan2(iy - cy, ix - cx) * 180 / Math.PI + 90; // handle sits above centre
if (e.shiftKey) deg = Math.round(deg / 15) * 15; // Shift = snap to 15°
b.angle = ((Math.round(deg * 10) / 10) % 360 + 360) % 360;
} else if (edDrag.mode === 'move') {
b.x = Math.round(b0.x + (ix - edDrag.sx)); b.y = Math.round(b0.y + (iy - edDrag.sy));
} else {
// resize in the box's LOCAL (unrotated) frame so it works when rotated
const [lx, ly] = toBoxLocal(b0, ix, iy);
let x0 = b0.x, y0 = b0.y, x1 = b0.x + b0.w, y1 = b0.y + b0.h;
if (edDrag.mode.includes('w')) x0 = lx; if (edDrag.mode.includes('e')) x1 = lx;
if (edDrag.mode.includes('n')) y0 = ly; if (edDrag.mode.includes('s')) y1 = ly;
b.x = Math.round(Math.min(x0, x1)); b.y = Math.round(Math.min(y0, y1));
b.w = Math.max(4, Math.round(Math.abs(x1 - x0))); b.h = Math.max(4, Math.round(Math.abs(y1 - y0)));
}
drawEditor();
});
window.addEventListener('mouseup', () => {
if (!edDrag) return;
if (edDrag.mode === 'new' && edDrag.cx != null) {
const x = Math.round(Math.min(edDrag.sx, edDrag.cx)), y = Math.round(Math.min(edDrag.sy, edDrag.cy));
const w = Math.round(Math.abs(edDrag.cx - edDrag.sx)), h = Math.round(Math.abs(edDrag.cy - edDrag.sy));
edDrag = null; edAdd = false;
// Reset the button fully — label AND highlight — so a second add
// works and the toolbar doesn't lie ("drawing…" while edAdd=false).
const addBtn = document.getElementById('addUnitBtn');
if (addBtn) { addBtn.classList.remove('btn-primary'); addBtn.textContent = '➕ Add unit'; }
if (w > 5 && h > 5) {
const tag = (prompt('Tag for the new unit (e.g. AC-D):') || '').trim().toUpperCase();
if (tag) {
edBoxes.push({ id: '', tag, status: 'added', color: 'purple', action: 'keep', x, y, w, h, angle: 0 });
edSel = edBoxes.length - 1; updateSelToolbar();
}
}
drawEditor();
return;
}
edDrag = null;
});
}
function updateSelToolbar() {
const bar = document.getElementById('selToolbar');
if (!bar) return;
if (edSel < 0) { bar.style.display = 'none'; return; }
bar.style.display = 'flex';
const b = edBoxes[edSel];
document.getElementById('selTagInput').value = b.tag || '';
document.getElementById('selState').textContent = b.status || '';
}
function loadAnnotatedRefresh() {
if (typeof loadAnnotated === 'function') loadAnnotated(currentTaskId);
}
// ── toolbar wiring ──
document.getElementById('reviewFloorSelect')?.addEventListener('change', e =>
loadEditorFloor(+e.target.value));
document.getElementById('addUnitBtn')?.addEventListener('click', e => {
edAdd = !edAdd;
e.target.classList.toggle('btn-primary', edAdd);
e.target.textContent = edAdd ? '✏️ drawing… (drag a box)' : '➕ Add unit';
});
document.getElementById('approveSelBtn')?.addEventListener('click', () => {
if (edSel < 0) return;
edBoxes[edSel].status = 'confirmed'; edBoxes[edSel].color = 'green'; edBoxes[edSel].action = 'keep';
drawEditor(); updateSelToolbar();
});
document.getElementById('deleteSelBtn')?.addEventListener('click', () => {
if (edSel < 0) return;
edBoxes[edSel].action = 'delete'; edBoxes[edSel].deleted = true;
edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();
});
document.getElementById('relabelSelBtn')?.addEventListener('click', () => {
if (edSel < 0) return;
const v = (document.getElementById('selTagInput').value || '').trim().toUpperCase();
if (v) { edBoxes[edSel].tag = v; drawEditor(); }
});
document.getElementById('approveAllBtn')?.addEventListener('click', () => {
// Skip gray noise: the engine judged those NOT-a-unit; approving them
// blindly would turn verify-rejects into confirmed units. Skip deleted
// boxes too — they're marked for removal, not for approval.
edBoxes.forEach(b => {
if (b.color === 'gray' || b.deleted) return;
b.status = 'confirmed'; b.color = 'green'; b.action = 'keep';
});
drawEditor();
});
document.getElementById('deleteNoiseBtn')?.addEventListener('click', () => {
edBoxes.forEach(b => {
if (b.color === 'gray' && !b.deleted) { b.action = 'delete'; b.deleted = true; }
});
edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();
});
// Same idiom for yellows (user feedback: on clean buildings every yellow was
// junk — Mac cellar review). Confirm first: on some buildings real units hide
// in yellow (Queens fl28 had 7), so this is a glance-then-sweep, never blind.
document.getElementById('deleteYellowsBtn')?.addEventListener('click', () => {
const n = edBoxes.filter(b => b.color === 'yellow' && !b.deleted).length;
if (!n) return;
if (!confirm(`Delete all ${n} yellow (unconfirmed) box(es) on this floor?\n`
+ `Make sure none of them is a real unit first.`)) return;
edBoxes.forEach(b => {
if (b.color === 'yellow' && !b.deleted) { b.action = 'delete'; b.deleted = true; }
});
edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();
});
// Blue = auto-suggested extras (gap-hunt / template-sweep). Separate from the
// engine's own yellow "uncertain" reads, so they get their own sweep button.
document.getElementById('deleteSuggestedBtn')?.addEventListener('click', () => {
const n = edBoxes.filter(b => b.color === 'blue' && !b.deleted).length;
if (!n) return;
if (!confirm(`Delete all ${n} blue (auto-suggested) box(es) on this floor?\n`
+ `These are extra candidates the finder proposed — glance first in case a real unit is among them.`)) return;
edBoxes.forEach(b => {
if (b.color === 'blue' && !b.deleted) { b.action = 'delete'; b.deleted = true; }
});
edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();
});
function updateNoiseCount() {
const el = document.getElementById('noiseCount');
if (el) el.textContent = edBoxes.filter(b => b.color === 'gray' && !b.deleted).length;
const yl = document.getElementById('yellowCount');
if (yl) yl.textContent = edBoxes.filter(b => b.color === 'yellow' && !b.deleted).length;
const sg = document.getElementById('suggestedCount');
if (sg) sg.textContent = edBoxes.filter(b => b.color === 'blue' && !b.deleted).length;
}
document.addEventListener('keydown', e => {
if (document.getElementById('review-tab')?.classList.contains('active') !== true) return;
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
if (edSel < 0) return;
if (e.key === 'Delete' || e.key === 'd') {
edBoxes[edSel].action = 'delete'; edBoxes[edSel].deleted = true;
edSel = -1; drawEditor(); updateSelToolbar(); updateNoiseCount();
}
else if (e.key === 'Enter' || e.key === 'c') {
edBoxes[edSel].status = 'confirmed'; edBoxes[edSel].color = 'green'; drawEditor(); updateSelToolbar();
}
// rotate the selected box: [ / ] = ±1°, Shift = ±15°
else if (e.key === '[' || e.key === ']') {
const step = (e.key === ']' ? 1 : -1) * (e.shiftKey ? 15 : 1);
const b = edBoxes[edSel];
b.angle = (((b.angle || 0) + step) % 360 + 360) % 360;
drawEditor();
}
});
document.getElementById('saveFloorBtn')?.addEventListener('click', async () => {
const fl = reviewFloors[edFloorIdx];
if (!fl) return;
const btn = document.getElementById('saveFloorBtn');
btn.disabled = true; const orig = btn.textContent; btn.textContent = 'Saving…';
try {
const res = await fetch(`${API_BASE}/save-review`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ task_id: currentTaskId,
floors: [{ file: fl.file, boxes: edBoxes }] })
});
if (!res.ok) throw new Error((await res.json()).detail || 'Save failed');
const result = await pollUntilDone(currentTaskId);
currentAnalysis = result; displayResults(result);
await loadReview(currentTaskId); // resync ids/colors after re-render
loadAnnotatedRefresh();
} catch (e) {
showError('Save failed: ' + e.message);
} finally { btn.disabled = false; btn.textContent = orig; }
});
initEditorCanvas();
// ===== Wheel-zoom for the schedule / floor picker images (scroll/drag to pan) =====
function enableImageZoom(wrapId, imgId, dragPan) {
const wrap = document.getElementById(wrapId), img = document.getElementById(imgId);
if (!wrap || !img || wrap._zoom) return;
wrap._zoom = true;
let z = 1;
img.addEventListener('load', () => { z = 1; img.style.width = ''; img.style.maxWidth = '100%'; });
if (dragPan) {
let pan = null;
wrap.addEventListener('mousedown', e => {
pan = { x: e.clientX, y: e.clientY, sl: wrap.scrollLeft, st: wrap.scrollTop };
wrap.style.cursor = 'grabbing'; e.preventDefault();
});
window.addEventListener('mousemove', e => {
if (!pan) return;
wrap.scrollLeft = pan.sl - (e.clientX - pan.x);
wrap.scrollTop = pan.st - (e.clientY - pan.y);
});
window.addEventListener('mouseup', () => { pan = null; wrap.style.cursor = ''; });
}
wrap.addEventListener('wheel', e => {
const rect = img.getBoundingClientRect();
if (!rect.width) return;
e.preventDefault();
const relX = (e.clientX - rect.left) / rect.width;
const relY = (e.clientY - rect.top) / rect.height;
z = Math.min(8, Math.max(1, z * (e.deltaY < 0 ? 1.2 : 1 / 1.2)));
const newW = wrap.clientWidth * z;
img.style.maxWidth = 'none';
img.style.width = newW + 'px';
const wrapRect = wrap.getBoundingClientRect();
const newH = img.getBoundingClientRect().height;
wrap.scrollLeft = relX * newW - (e.clientX - wrapRect.left);
wrap.scrollTop = relY * newH - (e.clientY - wrapRect.top);
}, { passive: false });
}
enableImageZoom('schedImgWrap', 'schedImg', false);
enableImageZoom('floorImgWrap', 'floorImg', true);
// ===== SCHEDULE REGION PICKER =====
(function () {
const modal = document.getElementById('schedModal');
if (!modal) return;
const img = document.getElementById('schedImg');
const boxEl = document.getElementById('schedBox');
const pageNum = document.getElementById('schedPageNum');
let page = 1, drag = null, region = null; // region in 0-1 fractions of the page
function loadPage(n) {
page = Math.max(1, uploadPages ? Math.min(n, uploadPages) : n);
pageNum.value = page;
boxEl.style.display = 'none'; region = null;
img.src = `${API_BASE}/page-image/${uploadTaskId}/${page}?dpi=130&max=2000`;
}
function openModal() {
if (!uploadTaskId) return;
document.getElementById('schedPageTotal').textContent = uploadPages || '?';
loadPage(1);
modal.style.display = 'block';
}
function close() { modal.style.display = 'none'; }
document.getElementById('addScheduleBtn')?.addEventListener('click', openModal);
document.getElementById('schedPrev')?.addEventListener('click', () => loadPage(page - 1));
document.getElementById('schedNext')?.addEventListener('click', () => loadPage(page + 1));
pageNum.addEventListener('change', () => loadPage(parseInt(pageNum.value) || 1));
document.getElementById('schedCancel')?.addEventListener('click', close);
document.getElementById('schedClear')?.addEventListener('click', () => {
boxEl.style.display = 'none'; region = null;
});
img.addEventListener('mousedown', e => {
e.preventDefault();
const r = img.getBoundingClientRect();
drag = { x: e.clientX - r.left, y: e.clientY - r.top };
});
window.addEventListener('mousemove', e => {
if (!drag) return;
const r = img.getBoundingClientRect();
const cx = Math.max(0, Math.min(e.clientX - r.left, r.width));
const cy = Math.max(0, Math.min(e.clientY - r.top, r.height));
const x0 = Math.min(drag.x, cx), y0 = Math.min(drag.y, cy);
const w = Math.abs(cx - drag.x), h = Math.abs(cy - drag.y);
boxEl.style.display = 'block';
boxEl.style.left = (img.offsetLeft + x0) + 'px';
boxEl.style.top = (img.offsetTop + y0) + 'px';
boxEl.style.width = w + 'px';
boxEl.style.height = h + 'px';
region = { x0: x0 / r.width, y0: y0 / r.height,
x1: (x0 + w) / r.width, y1: (y0 + h) / r.height };
});
window.addEventListener('mouseup', () => { drag = null; });
function addRegion(reg) {
scheduleRegions.push({ page, x0: +reg.x0.toFixed(4), y0: +reg.y0.toFixed(4),
x1: +reg.x1.toFixed(4), y1: +reg.y1.toFixed(4) });
renderScheduleChips();
boxEl.style.display = 'none'; region = null; // ready to add another
}
document.getElementById('schedUseRegion')?.addEventListener('click', () => {
if (!region || (region.x1 - region.x0) < 0.01 || (region.y1 - region.y0) < 0.01) {
alert('Draw a box around the schedule table first.'); return;
}
addRegion(region);
});
document.getElementById('schedWhole')?.addEventListener('click', () => {
addRegion({ x0: 0, y0: 0, x1: 1, y1: 1 });
});
})();
// ===== 🏦 SYMBOL BANK TAB (approve unit-body crops into the bank) =====
// One exemplar at a time: crop image + adjustable green box (drag body to
// move, corners to resize, nudge buttons / arrows), unit-type dropdown,
// Approve / Reject / Skip (keys a / r / s). Decisions persist server-side.
const BANK_MAXW = 560, BANK_MAXH = 440, BANK_HANDLE = 7;
let bankItems = []; // pending exemplars from /api/bank/queue
let bankPos = 0; // index of the item being shown
let bankImg = null; // loaded crop Image
let bankScale = 1; // canvas px per crop-image px
let bankBox = null; // working {x,y,w,h} in crop-image px
let bankDrag = null; // {mode:'move'|'nw'|'ne'|'sw'|'se', sx, sy, box0}
let bankSession = { approve: 0, reject: 0, skip: 0 };
function bankTabActive() {
return document.getElementById('bank-tab')?.classList.contains('active') === true;
}
let bankTypesLoaded = false;
async function bankLoadTypes() {
const sel = document.getElementById('bankType');
if (!sel) return;
try {
const res = await fetch(`${API_BASE}/bank/types`);
if (!res.ok) throw new Error('types unavailable');
const data = await res.json();
const opts = ['<option value="">— choose type —</option>'];
(data.base || []).forEach(t => {
opts.push(`<option value="${t.id}">${t.label}</option>`);
});
if ((data.custom || []).length) {
opts.push('<optgroup label="Custom">');
data.custom.forEach(t => {
opts.push(`<option value="${t.id}">${t.label}</option>`);
});
opts.push('</optgroup>');
}
sel.innerHTML = opts.join('');
bankTypesLoaded = true;
} catch (e) {
// leave whatever options exist; approve will just fail server-side
}
}
document.getElementById('bankType')?.addEventListener('change', () => {
const sel = document.getElementById('bankType');
const customInput = document.getElementById('bankCustomType');
if (!customInput) return;
customInput.style.display = (sel.value === 'other') ? 'block' : 'none';
if (sel.value !== 'other') customInput.value = '';
});
async function bankLoadQueue(autoShow) {
const empty = document.getElementById('bankEmpty');
try {
const res = await fetch(`${API_BASE}/bank/queue`);
if (!res.ok) throw new Error((await res.json()).detail || 'queue unavailable');
const data = await res.json();
bankItems = data.items || [];
bankPos = 0;
bankSession = { approve: 0, reject: 0, skip: 0 };
bankCounts = data.counts || {};
if (autoShow && bankItems.length) {
// Make the Bank tab reachable without running an analysis first.
resultsSection.style.display = 'block';
document.querySelector('.tab-btn[data-tab="bank"]')?.click();
}
bankShow();
} catch (e) {
if (empty) empty.textContent = 'Bank queue unavailable: ' + e.message;
}
}
let bankCounts = {};
function bankProgressText() {
const total = bankCounts.exemplars || bankItems.length;
const done = (bankCounts.approved || 0) + (bankCounts.rejected || 0)
+ bankSession.approve + bankSession.reject;
return `Exemplar ${Math.min(bankPos + 1, bankItems.length)} of ${bankItems.length} pending`
+ ` · ${done}/${total} decided (bank total)`
+ ` · this session: ✓${bankSession.approve} ✗${bankSession.reject} ↷${bankSession.skip}`;
}
function bankShow() {
const empty = document.getElementById('bankEmpty');
const work = document.getElementById('bankWork');
const summary = document.getElementById('bankSummary');
const prog = document.getElementById('bankProgress');
if (!work) return;
document.getElementById('bankMsg').textContent = '';
if (!bankItems.length || bankPos >= bankItems.length) {
work.style.display = 'none';
empty.style.display = 'none';
summary.style.display = 'block';
prog.textContent = '';
const banked = (bankCounts.approved || 0) + bankSession.approve;
summary.innerHTML = '<div style="padding:14px;background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;">'
+ '<h4 style="margin:0 0 6px;">🎉 Bank queue done</h4>'
+ `<p style="margin:0 0 4px;">This session: <b>${bankSession.approve}</b> approved, `
+ `<b>${bankSession.reject}</b> rejected, <b>${bankSession.skip}</b> skipped.</p>`
+ `<p style="margin:0 0 10px;color:#64748b;">${banked} crop(s) total in the bank `
+ '(analyzer_b/symbol_crops/). Approved crops are registered in symbol_library.json.</p>'
+ '<button class="btn btn-secondary" id="bankReload">↻ Reload queue</button></div>';
document.getElementById('bankReload')?.addEventListener('click', () => bankLoadQueue(false));
return;
}
summary.style.display = 'none';
empty.style.display = 'none';
work.style.display = 'block';
prog.textContent = bankProgressText();
const item = bankItems[bankPos];
document.getElementById('bankMeta').innerHTML =
`<b>${item.tag || '?'}</b> — ${item.building || ''}, page ${item.page}`
+ `<br>confidence ${item.confidence != null ? item.confidence : '?'}`
+ ` · cluster of ${item.cluster_size || 1}`
+ (item.skipped ? ' · <span style="color:#ca8a04;">previously skipped</span>' : '');
document.getElementById('bankType').value = '';
const customInput = document.getElementById('bankCustomType');
if (customInput) { customInput.value = ''; customInput.style.display = 'none'; }
// angle (degrees, clockwise) — rotate the box over a diagonal unit; the
// backend de-rotates the saved crop so the body comes out upright.
bankBox = Object.assign({ x: 0, y: 0, w: 10, h: 10, angle: 0 }, item.proposed_box || {});
bankImg = new Image();
bankImg.onload = () => {
const canvas = document.getElementById('bankCanvas');
if (!canvas) return;
// Fit within the work area; upscale small crops (cap 3x) so the box
// is comfortable to adjust.
bankScale = Math.min(BANK_MAXW / bankImg.naturalWidth,
BANK_MAXH / bankImg.naturalHeight, 3);
canvas.width = Math.round(bankImg.naturalWidth * bankScale);
canvas.height = Math.round(bankImg.naturalHeight * bankScale);
bankDraw();
};
bankImg.src = item.image_url + `?t=${Date.now()}`;
}
function bankClampBox() {
if (!bankBox || !bankImg) return;
const W = bankImg.naturalWidth, H = bankImg.naturalHeight;
bankBox.w = Math.max(4, Math.min(Math.round(bankBox.w), W));
bankBox.h = Math.max(4, Math.min(Math.round(bankBox.h), H));
bankBox.x = Math.max(0, Math.min(Math.round(bankBox.x), W - bankBox.w));
bankBox.y = Math.max(0, Math.min(Math.round(bankBox.y), H - bankBox.h));
}
function bankDraw() {
const canvas = document.getElementById('bankCanvas');
if (!canvas || !bankImg) return;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(bankImg, 0, 0, canvas.width, canvas.height);
if (!bankBox) return;
bankClampBox();
const s = bankScale;
const x = bankBox.x * s, y = bankBox.y * s, w = bankBox.w * s, h = bankBox.h * s;
const cx = x + w / 2, cy = y + h / 2;
const a = (bankBox.angle || 0) * Math.PI / 180;
// dim everything outside the (possibly rotated) box so "body only" is
// easy to judge — canvas rect + rotated inner rect, even-odd fill
ctx.beginPath();
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(cx, cy); ctx.rotate(a);
ctx.rect(-w / 2, -h / 2, w, h);
ctx.restore();
ctx.fillStyle = 'rgba(255,255,255,0.55)';
ctx.fill('evenodd');
// rotated green box + corner handles (drawn in box-local space)
ctx.save();
ctx.translate(cx, cy); ctx.rotate(a);
ctx.strokeStyle = '#16a34a'; ctx.lineWidth = 2;
ctx.strokeRect(-w / 2, -h / 2, w, h);
[[-w / 2, -h / 2], [w / 2, -h / 2], [-w / 2, h / 2], [w / 2, h / 2]].forEach(([hx, hy]) => {
ctx.fillStyle = '#16a34a';
ctx.fillRect(hx - BANK_HANDLE, hy - BANK_HANDLE, BANK_HANDLE * 2, BANK_HANDLE * 2);
ctx.strokeStyle = '#fff'; ctx.lineWidth = 1;
ctx.strokeRect(hx - BANK_HANDLE, hy - BANK_HANDLE, BANK_HANDLE * 2, BANK_HANDLE * 2);
});
ctx.restore();
const angleEl = document.getElementById('bankAngle');
if (angleEl) angleEl.textContent = bankBox.angle ? `${bankBox.angle}°` : '';
}
// Mouse (image px) -> box-local coords (rotation-aware hit testing).
function bankToLocal(ix, iy) {
const b = bankBox;
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
const a = -(b.angle || 0) * Math.PI / 180;
const dx = ix - cx, dy = iy - cy;
return [dx * Math.cos(a) - dy * Math.sin(a),
dx * Math.sin(a) + dy * Math.cos(a)];
}
function bankCanvasXY(e) {
const canvas = document.getElementById('bankCanvas');
const r = canvas.getBoundingClientRect();
return [(e.clientX - r.left) * (canvas.width / r.width),
(e.clientY - r.top) * (canvas.height / r.height)];
}
function bankHitHandle(mx, my) {
if (!bankBox) return null;
const b = bankBox;
// Compare in box-local space so handles stay grabbable at any rotation.
const [lx, ly] = bankToLocal(mx / bankScale, my / bankScale);
const tol = (BANK_HANDLE + 2) / bankScale;
const corners = {
nw: [-b.w / 2, -b.h / 2], ne: [b.w / 2, -b.h / 2],
sw: [-b.w / 2, b.h / 2], se: [b.w / 2, b.h / 2],
};
for (const [name, [hx, hy]] of Object.entries(corners))
if (Math.abs(lx - hx) <= tol && Math.abs(ly - hy) <= tol) return name;
return null;
}
function initBankCanvas() {
const canvas = document.getElementById('bankCanvas');
if (!canvas || canvas._wired) return;
canvas._wired = true;
canvas.addEventListener('mousedown', e => {
if (!bankBox) return;
e.preventDefault();
const [mx, my] = bankCanvasXY(e);
const handle = bankHitHandle(mx, my);
if (handle) { bankDrag = { mode: handle, box0: { ...bankBox } }; return; }
const ix = mx / bankScale, iy = my / bankScale;
const [lx, ly] = bankToLocal(ix, iy); // inside-test in rotated space
if (Math.abs(lx) <= bankBox.w / 2 && Math.abs(ly) <= bankBox.h / 2) {
bankDrag = { mode: 'move', sx: ix, sy: iy, box0: { ...bankBox } };
}
});
window.addEventListener('mousemove', e => {
if (!bankDrag || !bankBox) return;
const [mx, my] = bankCanvasXY(e);
const ix = mx / bankScale, iy = my / bankScale;
const b0 = bankDrag.box0;
if (bankDrag.mode === 'move') {
bankBox.x = b0.x + (ix - bankDrag.sx);
bankBox.y = b0.y + (iy - bankDrag.sy);
} else if (!bankBox.angle) {
// unrotated: classic corner drag (opposite corner stays put)
let x0 = b0.x, y0 = b0.y, x1 = b0.x + b0.w, y1 = b0.y + b0.h;
if (bankDrag.mode.includes('w')) x0 = ix; if (bankDrag.mode.includes('e')) x1 = ix;
if (bankDrag.mode.includes('n')) y0 = iy; if (bankDrag.mode.includes('s')) y1 = iy;
bankBox.x = Math.min(x0, x1); bankBox.y = Math.min(y0, y1);
bankBox.w = Math.abs(x1 - x0); bankBox.h = Math.abs(y1 - y0);
} else {
// rotated: center-anchored resize — the dragged corner tracks the
// mouse in box-local space, the center stays put (keeps the math
// sane at any angle; nudge buttons still fine-tune afterwards)
const cx = b0.x + b0.w / 2, cy = b0.y + b0.h / 2;
const [lx, ly] = bankToLocal(ix, iy);
bankBox.w = Math.max(4, Math.abs(lx) * 2);
bankBox.h = Math.max(4, Math.abs(ly) * 2);
bankBox.x = cx - bankBox.w / 2;
bankBox.y = cy - bankBox.h / 2;
}
bankDraw();
});
window.addEventListener('mouseup', () => { bankDrag = null; });
}
async function bankDecide(action) {
if (bankPos >= bankItems.length) return;
const item = bankItems[bankPos];
const msg = document.getElementById('bankMsg');
msg.textContent = '';
const body = { id: item.id, action };
if (action === 'approve') {
const unitType = document.getElementById('bankType').value;
if (!unitType) { msg.textContent = 'Pick a unit type before approving.'; return; }
if (unitType === 'other') {
const customType = (document.getElementById('bankCustomType')?.value || '').trim();
if (!customType) { msg.textContent = 'Type a custom unit name before approving.'; return; }
body.custom_type = customType;
}
bankClampBox();
body.unit_type = unitType;
body.box = { x: bankBox.x, y: bankBox.y, w: bankBox.w, h: bankBox.h,
angle: bankBox.angle || 0 };
}
['bankApprove', 'bankReject', 'bankSkip'].forEach(id => {
const b = document.getElementById(id); if (b) b.disabled = true;
});
try {
const res = await fetch(`${API_BASE}/bank/decide`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) throw new Error((await res.json()).detail || 'decide failed');
bankSession[action]++;
bankPos++;
bankShow();
} catch (e) {
msg.textContent = e.message;
} finally {
['bankApprove', 'bankReject', 'bankSkip'].forEach(id => {
const b = document.getElementById(id); if (b) b.disabled = false;
});
}
}
document.getElementById('bankApprove')?.addEventListener('click', () => bankDecide('approve'));
document.getElementById('bankReject')?.addEventListener('click', () => bankDecide('reject'));
document.getElementById('bankSkip')?.addEventListener('click', () => bankDecide('skip'));
document.querySelectorAll('.bank-nudge').forEach(btn => btn.addEventListener('click', () => {
if (!bankBox) return;
bankBox[btn.dataset.k] += +btn.dataset.d;
bankDraw();
}));
// Rotate over a diagonal unit (Shift = 15° steps, matching the Review editor).
function bankRotate(deg) {
if (!bankBox) return;
let a = (bankBox.angle || 0) + deg;
a = ((a + 180) % 360 + 360) % 360 - 180; // normalize to (-180, 180]
bankBox.angle = Math.round(a * 10) / 10;
bankDraw();
}
document.querySelectorAll('.bank-rot').forEach(btn => btn.addEventListener('click', e => {
bankRotate(+btn.dataset.d * (e.shiftKey ? 7.5 : 1));
}));
document.getElementById('bankRotReset')?.addEventListener('click', () => {
if (!bankBox) return;
bankBox.angle = 0;
bankDraw();
});
// keyboard: a=approve r=reject s=skip · arrows move · Shift+arrows resize
document.addEventListener('keydown', e => {
if (!bankTabActive()) return;
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(e.target.tagName)) return;
if (e.key === 'a') { bankDecide('approve'); }
else if (e.key === 'r') { bankDecide('reject'); }
else if (e.key === 's') { bankDecide('skip'); }
else if (e.key === '[' || e.key === '{') { bankRotate(e.shiftKey ? -15 : -2); }
else if (e.key === ']' || e.key === '}') { bankRotate(e.shiftKey ? 15 : 2); }
else if (e.key.startsWith('Arrow') && bankBox) {
e.preventDefault();
const d = 2;
if (e.shiftKey) {
if (e.key === 'ArrowRight') bankBox.w += d;
else if (e.key === 'ArrowLeft') bankBox.w -= d;
else if (e.key === 'ArrowDown') bankBox.h += d;
else if (e.key === 'ArrowUp') bankBox.h -= d;
} else {
if (e.key === 'ArrowRight') bankBox.x += d;
else if (e.key === 'ArrowLeft') bankBox.x -= d;
else if (e.key === 'ArrowDown') bankBox.y += d;
else if (e.key === 'ArrowUp') bankBox.y -= d;
}
bankDraw();
}
});
initBankCanvas();
// Load the type dropdown + queue on page open; if there is pending work,
// surface the Bank tab so it is reachable without running an analysis first.
bankLoadTypes();
bankLoadQueue(true);
// ===== FLOOR PAGE PICKER (page-by-page; add each floor plan) =====
(function () {
const modal = document.getElementById('floorModal');
if (!modal) return;
const img = document.getElementById('floorImg');
const pageNum = document.getElementById('floorPageNum');
const nameInput = document.getElementById('floorNameInput');
let page = 1;
function loadPage(n) {
page = Math.max(1, uploadPages ? Math.min(n, uploadPages) : n);
pageNum.value = page;
img.src = `${API_BASE}/page-image/${uploadTaskId}/${page}?dpi=130&max=2000`;
}
function openModal() {
if (!uploadTaskId) return;
document.getElementById('floorPageTotal').textContent = uploadPages || '?';
loadPage(1);
modal.style.display = 'block';
}
function close() { modal.style.display = 'none'; }
document.getElementById('addFloorBtn')?.addEventListener('click', openModal);
document.getElementById('floorPrev')?.addEventListener('click', () => loadPage(page - 1));
document.getElementById('floorNext')?.addEventListener('click', () => loadPage(page + 1));
pageNum.addEventListener('change', () => loadPage(parseInt(pageNum.value) || 1));
document.getElementById('floorDone')?.addEventListener('click', close);
document.getElementById('floorAdd')?.addEventListener('click', () => {
if (floorPages.some(f => f.page_num === page)) {
alert(`Page ${page} is already added.`); return;
}
floorPages.push({ page_num: page, name: (nameInput.value || '').trim() });
nameInput.value = '';
renderFloorChips();
});
})();
// script.js
const API_BASE = '/api';
let currentTaskId = null;
let currentAnalysis = null;
// manual-flow / upload-first state
let selectedFile = null;
let uploadTaskId = null;
let uploadPages = 0;
let scheduleRegions = []; // [{page, x0, y0, x1, y1}] hand-drawn schedule tables
let scheduleGroups = []; // [{page, region, units:[{tag,type,qty,model,...}]}] from read
let floorPages = []; // [{page_num, name}] hand-picked floor plans
// DOM Elements
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const analyzeBtn = document.getElementById('analyzeBtn');
const loadingSection = document.getElementById('loadingSection');
const resultsSection = document.getElementById('resultsSection');
const errorSection = document.getElementById('errorSection');
const tabs = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');
// ===== FILE UPLOAD =====
uploadArea.addEventListener('click', () => fileInput.click());
// Note under the file info when this exact file already has results on disk
// (content-hash match) — Analyze will reuse them free instead of re-paying.
function showReuseNote(prev) {
let el = document.getElementById('reuseNote');
if (!el) {
el = document.createElement('div');
el.id = 'reuseNote';
el.style.cssText = 'margin:6px 0 0;font-size:0.85em;';
document.getElementById('fileInfo')?.appendChild(el);
}
if (prev && prev.found && prev.reusable) {
el.style.color = '#15803d';
el.textContent = `✓ Previous results found (${prev.floors} floor(s)) — ` +
`Analyze will reuse them free. Tick "force re-detect" to re-run instead.`;
} else if (prev && prev.found) {
el.style.color = '#92400e';
el.textContent = 'A different version of this file was analyzed before — ' +
'Analyze will re-detect fresh.';
} else {
el.textContent = '';
}
}
// Free text-layer scan: point the user at likely schedule pages so step ①
// isn't a 29-page hunt (round-1 focus group: Sal bounced right here).
async function loadScheduleHints() {
if (!uploadTaskId) return;
try {
const res = await fetch(`${API_BASE}/schedule-hints/${uploadTaskId}`);
const d = await res.json();
let el = document.getElementById('scheduleHints');
if (!el) {
el = document.createElement('div');
el.id = 'scheduleHints';
el.style.cssText = 'margin-top:4px;font-size:0.85em;color:#4338ca;';
document.getElementById('addScheduleBtn')?.parentElement?.appendChild(el);
}
el.textContent = (d.schedule_pages || []).length
? `💡 Pages ${d.schedule_pages.join(', ')} look like schedule sheets — start there.`
: '';
} catch (e) { /* advisory */ }
}
// ===== RECENT BUILDINGS (reopen results after a restart / new session) =====
async function loadRecentBuildings() {
try {
const res = await fetch(`${API_BASE}/recent`);
const data = await res.json();
const items = data.recent || [];
if (!items.length) return;
let box = document.getElementById('recentBuildings');
if (!box) {
box = document.createElement('div');
box.id = 'recentBuildings';
box.style.cssText = 'margin-top:14px;padding:10px 12px;background:#f8fafc;'
+ 'border:1px solid #e2e8f0;border-radius:8px;font-size:0.9em;';
uploadArea.parentElement.insertBefore(box, uploadArea.nextSibling);
}
box.innerHTML = '<b>Recent buildings</b> — click to reopen previous results (free):<br>';
items.forEach(it => {
const a = document.createElement('a');
a.href = '#';
a.textContent = `${it.name} (${it.floors} floor(s), ${it.updated})`;
a.style.cssText = 'display:inline-block;margin:4px 12px 0 0;color:#4338ca;';
a.addEventListener('click', async e => {
e.preventDefault();
a.textContent += ' …';
try {
const r = await fetch(`${API_BASE}/reopen`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: it.name })
});
const d = await r.json();