comparison-bench-ui.js
Slider, faces, comments, current round, navigation and ranked history.
/* SceneBench's calibrated 0–100 control and editorial faces, kept beside the output. */
(() => {
const CHOICES=[['no',12,'No'],['low',37,'Maybe'],['high',62,'Good'],['heart',87,'Love']];
const FACE={no:'<circle cx="12" cy="12" r="9"/><path d="M8.5 10h.01M15.5 10h.01M8 17q4-4 8 0"/>',low:'<circle cx="12" cy="12" r="9"/><path d="M8.5 10h.01M15.5 10h.01M8 16h8"/>',high:'<circle cx="12" cy="12" r="9"/><path d="M8.5 10h.01M15.5 10h.01M8 15q4 4 8 0"/>',heart:'<path d="M12 20s-8-5.5-8-10a4.3 4.3 0 0 1 8-1.6A4.3 4.3 0 0 1 20 10c0 4.5-8 10-8 10Z"/>'};
const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const tone=n=>{const a=[162,132,91],b=[174,219,233],t=n/100;return 'rgb('+a.map((v,i)=>Math.round(v+(b[i]-v)*t)).join(',')+')';};
const sections=[...document.querySelectorAll('.comparison')], panels=new Map();
let savedEvents=[];
async function loadEvents() {
if(!BENCH.ledger) return;
try {
const response=await fetch(BENCH.ledger,{cache:'no-store'});if(!response.ok)return;
savedEvents=(await response.text()).split(/\r?\n/).filter(Boolean).flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}});
renderLibraries();
} catch { /* Existing API grades and pending browser drafts remain visible. */ }
}
for(const section of sections) {
const panel=section.querySelector('.feedback'), produced=panel.dataset.produced==='true';
panel.innerHTML=`<div class="rating-block">${produced?`<div class="rating-head"><span>Your rating</span><output>Not rated</output></div><div class="scale"><input type="range" min="0" max="100" value="0" aria-label="Rating for ${esc(section.id)}"></div><div class="choices" role="group" aria-label="Rate ${esc(section.id)}">${CHOICES.map(([vote,score,label])=>`<button data-vote="${vote}" data-score="${score}" aria-pressed="false" aria-label="${label}"><svg viewBox="0 0 24 24" aria-hidden="true">${FACE[vote]}</svg><span>${label}</span></button>`).join('')}</div>`:'<div class="rating-head">What should replace this?</div>'}</div><div class="note-block"><label class="feedback-label" for="note-${section.id}">Your feedback</label><textarea id="note-${section.id}" maxlength="2000" placeholder="What should we keep or change?"></textarea><details class="tag-options"><summary>Quick tags</summary><div class="tags">${BENCH.tags.map(tag=>`<button data-tag="${esc(tag)}" aria-pressed="false">${esc(tag)}</button>`).join('')}</div></details></div><div class="save-row"><button data-save>Save feedback</button>${produced?'<button data-clear>Clear rating</button>':''}</div><span class="saved" role="status">Loading saved feedback…</span><div class="prior" hidden></div>`;
panels.set(section.dataset.ratingId,panel);
const check=document.createElement('details');check.className='review-check';
const heading=document.createElement('summary');heading.textContent=panel.dataset.judge;
const explanation=document.createElement('p');explanation.textContent=panel.dataset.review;
check.append(heading,explanation);panel.append(check);
}
const select=document.querySelector('#asset-select'),kind=document.querySelector('#kind'),rated=document.querySelector('#rated'),connection=document.querySelector('#rating-connection');
let active=decodeURIComponent(location.hash.slice(1)) || sections[0].id;
const view=document.querySelector('#view');
view.value=BENCH.view || 'all';
const earlierWork=document.querySelector('#earlier-work');
const filtered=()=>sections.filter(s=>(kind.value==='all'||s.dataset.kind===kind.value)&&(rated.value==='all'||(rated.value==='unrated'?!store.rows[s.dataset.ratingId]?.vote:store.rows[s.dataset.ratingId]?.vote===rated.value)));
const visible=()=>filtered().filter(s=>!s.closest('#earlier-work') || earlierWork.open);
function navigate(id,changeHash=true,openEarlier=true) {
if(openEarlier && earlierWork && document.getElementById(id)?.closest('#earlier-work')) earlierWork.open=true;
const matches=visible(); if(!matches.some(s=>s.id===id)) id=matches[0]?.id;
active=id; sections.forEach(s=>{s.hidden=view.value==='single'?s.id!==id:!matches.includes(s);s.toggleAttribute('data-active',s.id===id);});
const i=matches.findIndex(s=>s.id===id);
document.querySelector('#empty').hidden=matches.length>0;
document.querySelector('#position').textContent=matches.length?`${i+1} / ${matches.length}`:'0 / 0';
select.value=id || '';
[...select.options].forEach(o=>o.hidden=!filtered().some(s=>s.id===o.value));
document.querySelector('#prev').disabled=i<=0;
document.querySelector('#next').disabled=i<0||i>=matches.length-1;
if(changeHash&&id) history.replaceState(null,'','#'+id);
if(changeHash&&id&&view.value==='all') document.getElementById(id).scrollIntoView?.({block:'start',behavior:'instant'});
}
function repaint(changed) {
connection.textContent=store.connected?'Feedback saves to disk.':'Disk saving unavailable · browser drafts retained.';
const batch=BENCH.batch?.id?BENCH.rows.filter(r=>r.batchId===BENCH.batch.id):[],jump=document.querySelector('#batch-jump');
const reviewed=batch.filter(r=>store.rows[r.ratingId]?.score!=null).length;
if(jump) {jump.hidden=!batch.length;jump.href='#'+(batch[0]?.id || sections[0].id);jump.textContent=(BENCH.batch?.shortLabel || 'Current batch')+' · '+reviewed+'/'+batch.length+' rated';}
let progress=document.querySelector('#batch-progress');
if(!progress&&batch.length){progress=document.createElement('p');progress.id='batch-progress';document.querySelector('#current-work').append(progress);}
if(progress)progress.textContent=reviewed+' of '+batch.length+' rated'+(reviewed===batch.length?' · All feedback received.':' · '+(batch.length-reviewed)+' still need your rating.');
for(const [id,panel] of panels) {
if(changed&&changed!==id) continue;
const row=store.rows[id] || {},score=row.score ?? CHOICES.find(c=>c[0]===row.vote)?.[1] ?? null;
const section=panel.closest('.comparison'),state=section.querySelector('.state');
const current=!BENCH.batch?.id || section.dataset.batchId===BENCH.batch.id;
section.classList.toggle('is-new',current && panel.dataset.produced==='true' && score==null);
section.classList.toggle('is-reviewed',score!=null);
section.classList.toggle('is-earlier',!current);
if(state&&panel.dataset.produced==='true')state.textContent=score==null?(current?'New · Not rated':'Earlier · Not rated'):'Rated · '+score+' / 100 · '+(CHOICES.find(c=>c[0]===row.vote)?.[2] || 'Rated');
panel.style.setProperty('--rating-tone',tone(score ?? 0));
const range=panel.querySelector('input[type=range]');
if(range) {range.value=score ?? 0;panel.querySelector('.scale').style.setProperty('--fill',(score ?? 0)+'%');panel.querySelector('output').innerHTML=score==null?'Not rated':`${score}<small> / 100</small>`;}
panel.querySelectorAll('[data-vote]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.vote===row.vote)));
panel.querySelectorAll('[data-tag]').forEach(b=>b.setAttribute('aria-pressed',String((row.tags || []).includes(b.dataset.tag))));
const note=panel.querySelector('textarea'); if(note.value!==(row.note || '')) note.value=row.note || '';
panel.querySelector('.saved').textContent=store.status[id] || (row.pendingDisk?'Unsaved browser draft · retry Save':row.at?'Saved to disk · '+new Date(row.at).toLocaleString():'Not rated · edits save automatically');
const meta=BENCH.rows.find(r=>r.ratingId===id),earlier=(meta?.previousRatingIds || []).filter(pid=>pid!==id).map(pid=>store.rows[pid]).filter(Boolean),prior=panel.querySelector('.prior');
prior.hidden=!earlier.length;
prior.textContent=earlier.length?'Earlier version feedback: '+earlier.map(r=>`${r.score ?? r.vote ?? 'Comment'}${r.note?' · '+r.note:''}`).join(' / '):'';
for(const pid of meta?.previousRatingIds || []) {
const frame=BENCH.history.find(f=>f.id===pid),rating=store.rows[pid];
if(!frame?.file||rating?.score==null)continue;
const a=document.createElement('a');a.href='#history-gallery-'+pid;a.textContent='View '+(frame.reviewLabel?.revision || 'earlier version')+' · '+rating.score+' / 100';prior.append(document.createElement('br'),a);
}
}
// A vote does not move the image out from under the reviewer; apply filters on navigation.
renderLibraries();
}
function renderLibraries() {
const scored=(BENCH.history || []).map(frame=>({...frame,rating:store.rows[frame.id]})).filter(f=>f.rating && f.rating.score!=null)
.sort((a,b)=>b.rating.score-a.rating.score || String(b.rating.at||'').localeCompare(String(a.rating.at||'')) || a.id.localeCompare(b.id));
const card=(f,galleryId)=>{
const item=document.createElement('article');item.className='history-card';item.dataset.frameId=f.id;item.dataset.score=f.rating.score;
item.id=galleryId+'-'+f.id;
const figure=document.createElement('figure');
if(f.file) {
const link=document.createElement('a');link.href=f.file;link.className='visual';link.dataset.zoom='';link.setAttribute('aria-label','Enlarge '+f.title);
const img=document.createElement('img');img.src=f.file;img.alt=f.title;img.loading='lazy';link.append(img);figure.append(link);
} else {const unavailable=document.createElement('p');unavailable.textContent='Original preview unavailable · rating retained';figure.append(unavailable);}
const caption=document.createElement('figcaption');caption.textContent=f.title;figure.append(caption);
const notes=document.createElement('div');notes.className='history-notes';
const score=document.createElement('strong');score.textContent=f.rating.score+' / 100 · '+(CHOICES.find(c=>c[0]===f.rating.vote)?.[2] || 'Rated');
const version=document.createElement('small');version.textContent=[f.current?'Current version':'Earlier version',f.reviewLabel?.revision,f.reviewLabel?.round,f.reviewLabel?.date].filter(Boolean).join(' · ');
const note=document.createElement('p');note.textContent=f.rating.note || 'No written feedback.';
const saved=document.createElement('small');saved.textContent=f.rating.pendingDisk?'Browser draft · not saved to disk':f.rating.at?'Saved '+new Date(f.rating.at).toLocaleString():'';
notes.append(score,version,note,saved);
if(f.current) {const review=document.createElement('a');review.href='#'+f.assetId;review.textContent='Compare / edit feedback';notes.append(review);}
const download=document.createElement('a');if(f.file){download.href=f.file;download.download='';download.textContent='Download this version';notes.append(download);}
const events=savedEvents.filter(e=>e.id===f.id);
if(events.length) {
const details=document.createElement('details'),summary=document.createElement('summary');summary.textContent='Saved history · '+events.length+' saves';details.append(summary);
for(const event of [...events].reverse()) {const p=document.createElement('p');p.textContent=(event.score??'Comment only')+(event.at?' · '+new Date(event.at).toLocaleString():'')+(event.note?'\n'+event.note:'');details.append(p);}
notes.append(details);
}
item.append(figure,notes);return item;
};
for(const [id,items] of [['approved-gallery',scored.filter(f=>f.file&&['high','heart'].includes(f.rating.vote))],['history-gallery',scored]]) {
const gallery=document.getElementById(id);if(!gallery) continue;
gallery.replaceChildren(...items.map(f=>card(f,id)));
if(!items.length){const empty=document.createElement('p');empty.textContent=id==='approved-gallery'?'Rate a piece Good or Love to keep it here.':'No scored versions yet. Comments without a score remain beside the asset.';gallery.append(empty);}
}
}
const store=new RatingStore({storage:localStorage,key:'scene-bench:'+BENCH.key,request:fetch.bind(window),changed:repaint});
for(const [id,panel] of panels) {
panel.addEventListener('click',e=>{const b=e.target.closest('button');if(!b)return;
if(b.hasAttribute('data-score')) store.update(id,{score:Number(b.dataset.score)});
if(b.hasAttribute('data-clear')) store.update(id,{score:null});
if(b.hasAttribute('data-save')) store.save(id);
if(b.hasAttribute('data-tag')) {const tags=new Set(store.rows[id]?.tags || []);tags.has(b.dataset.tag)?tags.delete(b.dataset.tag):tags.add(b.dataset.tag);store.update(id,{tags:[...tags]});}
});
panel.querySelector('textarea').addEventListener('input',e=>store.update(id,{note:e.target.value}));
panel.querySelector('input')?.addEventListener('input',e=>store.update(id,{score:Number(e.target.value)}));
}
select.addEventListener('change',()=>navigate(select.value));
document.querySelector('#batch-jump')?.addEventListener('click',e=>{e.preventDefault();kind.value='all';rated.value='all';if(earlierWork)earlierWork.open=false;navigate(e.currentTarget.hash.slice(1));});
earlierWork?.addEventListener('toggle',()=>navigate(earlierWork.open?active:visible()[0]?.id,false,false));
view.addEventListener('change',()=>navigate(active));
// Keep the sticky arrows relative to the pair being read or edited down the page.
sections.forEach(section=>section.addEventListener('focusin',()=>{if(active!==section.id) navigate(section.id,false);}));
if(window.IntersectionObserver) {
const ratios=new Map();
const observer=new IntersectionObserver(entries=>{
entries.forEach(entry=>ratios.set(entry.target,entry.intersectionRatio));
if(view.value!=='all') return;
const candidate=visible().filter(s=>(ratios.get(s)||0)>0).sort((a,b)=>(ratios.get(b)||0)-(ratios.get(a)||0))[0];
if(candidate&&candidate.id!==active) navigate(candidate.id,false);
},{threshold:[0,.25,.5,.75,1]});
sections.forEach(s=>observer.observe(s));
}
kind.addEventListener('change',()=>navigate(active));rated.addEventListener('change',()=>navigate(active));
for(const [selector,offset] of [['#prev',-1],['#next',1]]) document.querySelector(selector).addEventListener('click',()=>{const matches=visible(),i=matches.findIndex(s=>s.id===active);navigate(matches[Math.max(0,Math.min(matches.length-1,i+offset))]?.id);});
window.addEventListener('hashchange',()=>{const id=decodeURIComponent(location.hash.slice(1));if(id==='earlier-work'&&earlierWork)earlierWork.open=true;if(sections.some(s=>s.id===id)){kind.value='all';rated.value='all';navigate(id,false);}});
document.querySelectorAll('#asset-list a').forEach(a=>a.addEventListener('click',()=>{kind.value='all';rated.value='all';navigate(a.hash.slice(1));document.querySelector('#asset-list').open=false;}));
const zoom=document.querySelector('#zoom');
document.addEventListener('click',e=>{const a=e.target.closest('[data-zoom]');if(!a)return;e.preventDefault();zoom.querySelector('img').src=a.href;zoom.querySelector('img').alt=a.getAttribute('aria-label');zoom.showModal();});
document.querySelector('#refresh-history')?.addEventListener('click',()=>{store.load();loadEvents();});
zoom.querySelector('button').addEventListener('click',()=>zoom.close());zoom.addEventListener('click',e=>{if(e.target===zoom)zoom.close();});
window.addEventListener('online',()=>store.load());
window.addEventListener('beforeunload',e=>{if(Object.values(store.rows).some(r=>r.pendingDisk)){e.preventDefault();e.returnValue='';}});
navigate(active,false);
if(location.hash) document.getElementById(active)?.scrollIntoView?.({block:'start',behavior:'instant'});
store.load();loadEvents();
})();