25 lines
7.6 KiB
JavaScript
25 lines
7.6 KiB
JavaScript
import {ensureElectionRecordStyles} from './election-applications-view.mjs';
|
||
const el=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;};
|
||
const when=n=>new Date(n).toLocaleString('en-GB',{timeZone:'UTC',dateStyle:'medium',timeStyle:'short'})+' GMT';
|
||
export function renderVoting(kind){
|
||
ensureElectionRecordStyles();
|
||
const root=el('div',undefined,'politics-content'),overview=el('div',undefined,'politics-election-overview'),calendar=el('article',undefined,'politics-card politics-calendar-card'),leaders=el('article',undefined,'politics-card politics-leaders');overview.append(calendar,leaders);root.append(overview);
|
||
const card=el('article',undefined,'politics-card'),heading=el('h3',kind==='imperial'?'The Throne’s Ballot':'The House Ballot'),status=el('p','Loading the chamber…');status.setAttribute('role','status');card.append(heading,status);root.append(card);
|
||
const filters=el('div',undefined,'politics-ballot-filters'),search=el('input'),sort=el('select');search.type='search';search.placeholder='Search candidates';search.setAttribute('aria-label','Search candidates');sort.setAttribute('aria-label','Sort candidates');for(const [value,text]of [['votes','Most votes'],['name','Name A–Z']]){const option=el('option',text);option.value=value;sort.append(option);}filters.append(search,sort);card.append(filters);
|
||
const candidates=el('div',undefined,'politics-candidates'),pages=el('nav',undefined,'politics-pagination'),consent=el('label',undefined,'politics-accept'),check=el('input');check.type='checkbox';consent.append(check,el('span','I confirm: submitted votes are final and cannot be withdrawn.'));
|
||
const submit=el('button','Cast definitive votes');submit.type='button';submit.disabled=true;const feedback=el('p');feedback.setAttribute('role','status');card.append(candidates,pages,consent,submit,feedback);
|
||
const apply=el('a','View or submit your candidature →');apply.href='#applications';card.append(apply);root.append(el('p','Results are recorded here. Automatic office, rank and seal assignment is still being connected.','politics-demo-note'));
|
||
let data=null,page=0,busy=false,requestId=null;const allocations=new Map();
|
||
const selected=()=>[...allocations.values()].reduce((a,b)=>a+b,0);
|
||
const open=()=>data?.round?.status==='open'&&Date.now()>=data.round.opensAt&&Date.now()<data.round.closesAt;
|
||
function ready(){submit.disabled=busy||!open()||!check.checked||selected()<1||selected()>data.remaining;}
|
||
function candidateRow(c,top=false){const row=el('article',undefined,'politics-candidate politics-live-candidate'),head=el('canvas',undefined,'politics-candidate-head');head.width=head.height=48;head.setAttribute('role','img');head.setAttribute('aria-label',c.username+' Minecraft head');const img=new Image();img.onload=()=>{const ctx=head.getContext('2d');ctx.imageSmoothingEnabled=false;if(img.naturalWidth>=64){const scale=img.naturalWidth/64;ctx.drawImage(img,8*scale,8*scale,8*scale,8*scale,0,0,48,48);ctx.drawImage(img,40*scale,8*scale,8*scale,8*scale,0,0,48,48);}else ctx.drawImage(img,0,0,48,48);};img.onerror=()=>{img.onerror=null;img.src='/api/avatars/fallback';};img.src='/api/avatars/roster/'+encodeURIComponent(c.username.toLowerCase());const identity=el('div',undefined,'politics-candidate-identity');identity.append(el('h4',c.username),el('small',kind==='imperial'?'Candidate for Emperor':data.faction==='veiled_concord'?'Candidate for Reverent Mother':'Candidate for House Leader'));row.append(head,identity);const detail=el('details'),toggle=el('summary','Motivation');detail.append(toggle,el('p',c.motivation));row.append(detail);
|
||
if(top)row.append(el('span',c.votes+' votes','politics-candidate-count'));
|
||
else {const label=el('label','Votes','politics-candidate-votes'),amount=el('input');amount.type='number';amount.min='0';amount.max=String(data.remaining);amount.step='1';amount.value=String(allocations.get(c.id)||0);amount.disabled=!open()||data.remaining===0;amount.setAttribute('aria-label','Votes for '+c.username);amount.oninput=()=>{const n=Number(amount.value);if(Number.isInteger(n)&&n>=0&&n<=data.remaining){allocations.set(c.id,n);requestId=null;}else allocations.delete(c.id);ready();};label.append(amount);row.append(label);}return row;
|
||
}
|
||
function draw(){candidates.replaceChildren();pages.replaceChildren();if(!data)return;const visible=data.candidates.filter(c=>c.username.toLowerCase().includes(search.value.toLowerCase())).sort((a,b)=>sort.value==='name'?a.username.localeCompare(b.username):b.votes-a.votes||a.username.localeCompare(b.username));page=Math.min(page,Math.max(0,Math.ceil(visible.length/9)-1));for(const c of visible.slice(page*9,page*9+9))candidates.append(candidateRow(c));if(!visible.length)candidates.append(el('p','No candidates in this chamber yet.'));if(visible.length>9){for(const [name,delta]of [['Previous',-1],['Next',1]]){const b=el('button',name);b.type='button';b.disabled=delta<0?page===0:(page+1)*9>=visible.length;b.onclick=()=>{page+=delta;draw();};pages.append(b);}pages.append(el('span','Page '+(page+1)));}ready();}
|
||
async function load(){try{const r=await fetch('/api/politics/ballot/'+kind,{cache:'no-store'}),body=await r.json();if(!root.isConnected)return;if(!r.ok)throw Error(body.message||'Chamber unavailable.');data=body;calendar.replaceChildren(el('h3',kind==='imperial'?'Imperial Almanac':'House Almanac'),el('p',data.round?'Round '+(data.round.number+1)+(data.round.number?' · deciding ballot':''):'Applications open'),el('strong',when(data.round?.opensAt||Date.parse(data.start))),el('p','Voting closes '+when(data.round?.closesAt||Date.parse(data.start)+10800000)),el('p','Voting lasts three hours. A tie opens an immediate three-hour office auction.'));leaders.replaceChildren(el('h3','Current Top 3'));for(const c of [...data.candidates].sort((a,b)=>b.votes-a.votes||a.username.localeCompare(b.username)).slice(0,3))leaders.append(candidateRow(c,true));if(!data.candidates.length)leaders.append(el('p','No candidates yet.'));status.textContent=open()?data.remaining+' vote(s) remaining. You may allocate them to one or more candidates.':data.round?.status==='winner'?'Result: '+(data.candidates.find(c=>c.id===data.round.winnerId)?.username||'Winner recorded')+'.':data.round?.status==='no_votes'?'Closed without votes. No winner was selected.':data.round?.status==='auction_required'?'A tied result has opened the office auction. View Auctions on Starport.':'Voting opens at the scheduled time.';draw();}catch(error){status.textContent=error.message;submit.disabled=true;}}
|
||
search.oninput=()=>{page=0;draw();};sort.onchange=()=>{page=0;draw();};check.onchange=ready;
|
||
submit.onclick=async()=>{if(submit.disabled)return;busy=true;ready();requestId||=crypto.randomUUID();feedback.textContent='Recording your definitive votes…';try{const r=await fetch('/api/politics/ballot/'+kind,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({kind,start:data.start,roundId:data.round.id,requestId,confirmed:check.checked,allocations:[...allocations].filter(([,votes])=>votes>0).map(([applicationId,votes])=>({applicationId,votes}))})}),result=await r.json();if(!root.isConnected)return;if(!r.ok)throw Error(result.message||'Vote not accepted.');feedback.textContent='Your participation is listed in the Electoral Roll; candidate choices stay private. Your vote has been recorded. '+result.ballot.remaining+' vote(s) remain.';allocations.clear();requestId=null;check.checked=false;await load();}catch(error){feedback.textContent=error.message;await load();}finally{busy=false;ready();}};
|
||
const refresh=el('button','Refresh standings');refresh.type='button';refresh.onclick=()=>load();filters.append(refresh);queueMicrotask(load);return root;
|
||
}
|

Staff