MC/website/node/public/passport.js
2026-11-27 23:43:05 +00:00

55 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createOrganisationNetwork} from '/organisation-network.mjs';
const $=id=>document.getElementById(id),el=(tag,value,cls)=>{const n=document.createElement(tag);if(value!=null)n.textContent=value;if(cls)n.className=cls;return n;};
const text=(id,value)=>{const node=$(id);if(node)node.textContent=value??'—';},username=decodeURIComponent(location.pathname.split('/').filter(Boolean)[1]||'');
function sealCard(m){const card=el('figure',null,'profile-seal'),image=el('img');image.src=m.url;image.alt=m.label;image.loading='lazy';image.width=image.height=128;card.append(image,el('figcaption',m.label),el('small',m.group||'Recognition'));return card;}
function renderPoliticalOffices(host,data){
host.replaceChildren();if(!data||data.status!=='unavailable'&&!data.records?.length)return false;
if(data.status==='unavailable'){host.append(el('p','The current political office register is temporarily unavailable.','muted'));return true;}
const date=value=>new Date(value).toLocaleDateString('en-GB',{timeZone:'Europe/Brussels',day:'numeric',month:'short',year:'numeric'});
for(const office of data.records){const card=el('article',null,'profile-political-office');
if(/^https:\/\/www\.dunerealms\.com\/assets\/seals\/[a-z0-9_-]+\.png$/.test(office.seal||'')){const image=el('img');image.src=office.seal;image.alt=office.label+' seal';image.width=image.height=96;image.loading='lazy';card.append(image);}
const description=el('div');description.append(el('small',office.scope),el('h3',office.label),el('strong','Currently in office'),el('p','Term: '+date(office.startsAt)+' — '+date(office.expiresAt)+' · Brussels','muted'));card.append(description);host.append(card);
}
return true;
}
function render(p){
document.title=(p.displayName||p.username)+' | DuneRealms';text('passport-title',p.holdings?.address||p.characterName||p.displayName||p.username);text('handle','@'+p.username+(p.personnelNumber?' · '+p.personnelNumber:''));text('status',p.systemAccount?'DuneRealms system account':p.showcase?'Verified official DuneRealms account':'DuneRealms community member');if(p.showcase){text('recognition-title','Seal & award showcase');text('recognition-description','The general DuneRealms catalogue. Personal seals and the Holy Order of the Crysknife are excluded.');}text('joined',p.joinedAt?new Date(p.joinedAt).toLocaleDateString('en-GB'):null);text('clan',p.clan?.status==='member'?p.clan.name:'No clan listed');if(p.clan?.status==='member'){const link=el('a'),logo=el('img');link.href='https://www.dunerealms.com/clans/'+encodeURIComponent(p.clan.tag);link.title=p.clan.name;link.setAttribute('aria-label','Open '+p.clan.name+' public clan page');logo.src=p.clan.emblem;logo.alt=p.clan.name;logo.width=logo.height=88;logo.className='profile-header-clan-logo';link.append(logo);$('clan').replaceChildren(link);}
const affiliations=$('clan');const entities=p.affiliations?.state==='available'?p.affiliations.records:[...(p.clan?.status==='member'?[{name:p.clan.name,emblem:p.clan.emblem,url:'https://www.dunerealms.com/clans/'+encodeURIComponent(p.clan.tag),type:'Clan',id:p.clan.id}]:[]),...(p.holdings?.companies||[]).map(r=>({...r,type:'Company'})),...(p.holdings?.deeds||[]).filter(r=>r.entityKind==='politics').map(r=>({...r,type:'Political office'}))];if(entities.length){affiliations.replaceChildren();affiliations.className='profile-affiliations';affiliations.parentElement.querySelector('small').textContent='Clan · Company · Political office';for(const record of entities){const link=el('a',null,'profile-affiliation');link.href=record.url;link.title=record.type+' · '+record.name;link.setAttribute('aria-label',link.title);const image=el('img');image.src=record.emblem||'/assets/imperial-seal-128.png';image.alt=record.name;image.width=image.height=56;link.append(image,el('small',record.type),el('strong',record.name));const card=el('article',null,'profile-affiliation-card');card.append(link);addAffiliationStatus(card,record);affiliations.append(card);}}
text('forum',p.forum?.status==='linked'?p.forum.username:'Not linked');
if(p.avatarSprite?.atlas==='https://cp.dunerealms.com/assets/mentat-portraits-atlas-v1.png'&&Number.isInteger(p.avatarSprite.cell)&&p.avatarSprite.cell>=0&&p.avatarSprite.cell<8){const image=$('avatar'),cell=p.avatarSprite.cell;image.src='data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/%3E';image.style.backgroundImage='url('+p.avatarSprite.atlas+')';image.style.backgroundSize='400% 200%';image.style.backgroundPosition=(cell%4*100/3)+'% '+(Math.floor(cell/4)*100)+'%';image.alt=p.displayName+' Minecraft portrait';image.hidden=false;}
else if(typeof p.avatar==='string'&&/^https:\/\/cp\.dunerealms\.com\/api\/avatars\//.test(p.avatar)){$('avatar').src=p.avatar;$('avatar').hidden=false;}
for(const rank of p.ranks||[]){if(rank.label==='Unknown rank')continue;const chip=el('span',rank.label,'chip');chip.dataset.staff=String(rank.key.startsWith('org_'));$('ranks').append(chip);}
const holdingHost=$('holdings');if(holdingHost){holdingHost.replaceChildren();const h=p.holdings||{};for(const [title,rows]of [['Leader of · Clans',h.clans],['Owner of · Companies',h.companies],['Registered deeds',h.deeds],['Daughter entities',h.subhouses]]){const box=el('article',null,'profile-holding-box');box.append(el('h3',title));for(const record of rows||[]){const link=el('a',null,'profile-holding-link profile-register-card');link.href=record.url+(title==='Registered deeds'?'#ownership-deed':'');const type=record.entityKind==='politics'?'Political office':record.entityKind==='company'?'Company':'Clan';if(title==='Registered deeds'&&record.entityKind!=='politics'){const deed=el('span',null,'profile-deed-icon profile-deed-'+record.kind+' profile-deed-entity-'+(record.entityKind||'clan'));deed.setAttribute('aria-hidden','true');link.append(deed);}else{const logo=el('img');logo.src=record.emblem||'/assets/imperial-seal-128.png';logo.alt='';logo.width=logo.height=64;link.append(logo);}const details=el('span',null,'profile-register-details');details.append(el('small',type,'profile-register-type'),el('strong',record.name));if(record.basis)details.append(el('small',record.basis,'profile-register-status'));if(title==='Registered deeds'&&record.kind)details.append(el('small',({royal:'Royal',original:'Keyed',basic:'Basic'})[record.kind]||record.kind,'profile-register-tier'));link.append(details,el('span','›','profile-register-open'));box.append(link);}if(!rows?.length)box.append(el('p',h.state==='unavailable'||(title.includes('Companies')?h.companiesState:h.clansState)==='unavailable'?'Register temporarily unavailable.':'No records in this register.','muted'));holdingHost.append(box);}if(h.appointments?.length){const box=el('article',null,'profile-holding-box');box.append(el('h3','Dynastic appointments'));for(const appointment of h.appointments){const link=el('a',appointment.address,'profile-holding-link');link.href=appointment.url;const seal=el('img');seal.src='https://www.dunerealms.com/assets/imperial-seal-128.png';seal.alt='';seal.width=seal.height=64;seal.className='profile-appointment-seal';link.prepend(seal);box.append(link);}holdingHost.append(box);}}
const functions=p.functions||[];
for(const f of functions){const card=el('article',null,'profile-function');card.append(el('strong',f.roleLabel),el('span',f.scopeLabel));$('department').append(card);}
if(!functions.length)$('department').append(el('p','No staff functions listed.','muted'));
renderRoleplayFunctions(p);renderNetworth(p.networth);if($('profile-network'))$('profile-network').append(createOrganisationNetwork(p.network));renderOfficeHistory(p);$('political-offices-panel').hidden=!renderPoliticalOffices($('political-offices'),p.politicalOffices);
if(p.support?.status==='available')text('tickets',(p.support.closed??0)+' verified support tickets closed');
if(p.bio)text('bio',p.bio);if(p.publicInfo){text('public-info',p.publicInfo);$('public-info').hidden=false;}
for(const [label,value]of Object.entries(p.socials||{})){try{const u=new URL(value);if(u.protocol!=='https:'||u.username||u.password)continue;const a=el('a',label,'chip');a.href=u.href;a.rel='noopener noreferrer';a.target='_blank';$('socials').append(a);}catch{}}
const medals=(p.medals||[]).filter(m=>typeof m.url==='string'&&/^https:\/\/(www|support|forums)\.dunerealms\.com\/assets\/seals\/[a-zA-Z0-9_./-]+\.png$/.test(m.url));
const personal=medals.find(m=>m.key==='personal-role');if(personal){$('personal-seal-panel').hidden=false;$('personal-seal').append(sealCard(personal));}
if(!p.showcase&&(p.ranks||[]).some(r=>r.key==='crysknife'))$('order-panel').hidden=false;
const groups=new Map();for(const m of medals){if(['personal-role','rank-crysknife'].includes(m.key))continue;const group=m.group||'Recognition';if(!groups.has(group))groups.set(group,[]);groups.get(group).push(m);}
for(const [name,items]of groups){const section=el('section'),cards=el('div',null,'profile-awards');section.append(el('h3',name));for(const m of items)cards.append(sealCard(m));section.append(cards);$('seals').append(section);}
if(!groups.size)$('seals').append(el('p','No additional seals or awards recorded.','muted'));
if(/^\/memorial\/[a-z0-9-]+$/.test(p.memorial||'')){const a=el('a','Visit community memorial →','chip');a.href=p.memorial;$('socials').append(a);text('status','Community remembrance profile');}
const community=(heading,value,note,link)=>{const c=el('article');c.append(el('h3',heading),el('strong',value),el('small',note));if(link){const a=el('a','Open →');a.href=link;c.append(el('br'),a);}$('community').append(c);return c;};
if(p.forum?.status==='linked')community('Forum contributions',String(p.forum.posts||0)+' posts',String(p.forum.threads||0)+' threads · '+String(p.forum.reputation||0)+' reputation',p.forum.url);
else community('Forum','Not linked','No linked forum record is available.');
const clanImage=el('img');clanImage.src=p.clan?.emblem||'https://www.dunerealms.com/assets/nav-clan-v2.webp';clanImage.alt=p.clan?.status==='member'?p.clan.name+' clan emblem':'Clan placeholder';clanImage.width=clanImage.height=110;clanImage.className='profile-clan-emblem';
if(p.clan?.status==='member')community('Clan',p.clan.name,(p.clan.role||'Member')+' · '+String(p.clan.members||0)+' members','https://www.dunerealms.com/clans/'+encodeURIComponent(p.clan.tag)).prepend(clanImage);
else community('Clan','No membership listed','Clan membership is maintained by the clan system.').prepend(clanImage);
for(const r of entities.filter(r=>r.type==='Company')){const c=community('Company',r.name,'Registered affiliation',r.url);const logo=el('img');logo.src=r.emblem;logo.alt='';logo.width=logo.height=64;c.prepend(logo);addAffiliationStatus(c,{...r,type:'Company'});}for(const r of entities.filter(r=>r.type==='Political office')){const c=community('Political Office',r.name,'ELECTION',r.url);const logo=el('img');logo.src=r.emblem;logo.alt='';logo.width=logo.height=64;c.prepend(logo);addAffiliationStatus(c,{...r,type:'Political office'});}
community('Adventures',p.quests?.completed==null?'No verified totals':String(p.quests.completed)+' completed',p.quests?.completed==null?'Quest statistics are not connected yet.':'Verified quest progress');
}
async function load(){if(!/^[a-z0-9_]{3,32}$/.test(username)){text('status','Invalid profile name');return;}text('handle','@'+username);try{const response=await fetch('https://cp.dunerealms.com/api/people/'+encodeURIComponent(username),{credentials:'include',cache:'no-store'});if(response.status===401){text('status','Sign in to view this member’s profile.');const a=el('a','Sign in');a.href='https://cp.dunerealms.com/?return_to='+encodeURIComponent('/people/'+username);$('status').append(' ',a);return;}if(!response.ok){text('status',response.status===404?'Profile not found':'Profile temporarily unavailable');return;}render((await response.json()).profile);}catch{text('status','Unable to load the profile. Please try again.');}}
void load();
function renderOfficeHistory(profile){const host=document.getElementById('holdings');if(!host||!profile.officeHistory)return;const section=document.createElement('section');section.id='office-history';section.className='holdings-box';const title=document.createElement('h3');title.textContent='Public office history';section.append(title);if(profile.officeHistory.state!=='available'){const note=document.createElement('p');note.textContent='Office history is unavailable.';section.append(note);}else for(const term of profile.officeHistory.records){const row=document.createElement('p');row.textContent=String(term.office).replaceAll('_',' ')+' · '+new Date(Number(term.starts_at)).toLocaleDateString('en-GB')+' – '+new Date(Number(term.expires_at)).toLocaleDateString('en-GB')+' · '+(term.outcome==='resigned'?'Voluntarily resigned':String(term.outcome).replaceAll('_',' '));section.append(row);}if(profile.officeHistory.state==='available'&&!profile.officeHistory.records.length){const note=document.createElement('p');note.textContent='No previous office terms.';section.append(note);}host.append(section);}
function renderRoleplayFunctions(p){const host=$('roleplay-functions');if(!host)return;host.replaceChildren();const roles=[...(p.holdings?.clans||[]).map(r=>({title:'Clan leader',name:r.name,url:r.url})),...(p.holdings?.companies||[]).filter(r=>['Registered deed owner','Registered founder'].includes(r.basis)).map(r=>({title:'Company owner',name:r.name,url:r.url})),...(p.politicalOffices?.records||[]).map(r=>({title:r.label,name:r.scope,url:'/political-houses/'+r.key})),...(p.politicalAppointments||[]).map(r=>({title:r.title,name:r.officeKey.replaceAll('_',' '),url:'/political-houses/'+r.officeKey}))];for(const role of roles){const card=el('article',null,'profile-function'),link=el('a',role.name);link.href=role.url;card.append(el('strong',role.title),link);host.append(card);}if(!roles.length)host.append(el('p','No current roleplay appointments.','muted'));}
function renderNetworth(data){const host=$('networth-chart');if(!host)return;host.replaceChildren();if(data?.state!=='available'||!data.points?.length){host.append(el('p',data?.state==='empty'?'History begins with your first recorded bank snapshot.':'Bank history is currently unavailable.','muted'));return;}const points=data.points.filter(p=>Number.isFinite(p.at)&&/^-?\d+$/.test(p.minor));if(!points.length)return;const money=value=>{const n=BigInt(value),a=n<0n?-n:n;return(n<0n?'-':'')+(a/100n).toLocaleString('en-GB')+'.'+String(a%100n).padStart(2,'0')+' DM';},last=points.at(-1);host.append(el('strong',money(last.minor)),el('p','Personal account balances minus outstanding personal loans. Reserved funds remain included.','muted'));if(points.length===1){host.append(el('p','One recorded observation; the timeline grows with future bank snapshots.','muted'));}else{const values=points.map(p=>Number(p.minor)),min=Math.min(0,...values),max=Math.max(0,...values),range=max-min||1,start=points[0].at,end=last.at,ns='http://www.w3.org/2000/svg',svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 600 180');svg.setAttribute('role','img');svg.setAttribute('aria-label','Personal net worth over the last 90 days');const title=document.createElementNS(ns,'title');title.textContent='Personal net worth: '+money(last.minor)+' at '+new Date(last.at).toLocaleString('en-GB');svg.append(title);const line=document.createElementNS(ns,'polyline');line.setAttribute('points',points.map((p,i)=>(20+(p.at-start)/(end-start||1)*560)+','+(150-(values[i]-min)/range*125)).join(' '));line.setAttribute('fill','none');line.setAttribute('stroke',Number(last.minor)<0?'#d89483':'#ddc47e');line.setAttribute('stroke-width','3');svg.append(line);for(const [label,y]of [[money(String(Math.round(max))),18],[money(String(Math.round(min))),175]]){const text=document.createElementNS(ns,'text');text.setAttribute('x','20');text.setAttribute('y',String(y));text.setAttribute('fill','#bdcbbf');text.setAttribute('font-size','11');text.textContent=label;svg.append(text);}host.append(svg);}host.append(el('small','Recorded '+new Date(last.at).toLocaleString('en-GB')+' · snapshots every 4 hours'));const details=el('details'),table=el('table');details.append(el('summary','View recorded values'));for(const point of points.slice(-30)){const row=el('tr');row.append(el('td',new Date(point.at).toLocaleString('en-GB')),el('td',money(point.minor)));table.append(row);}details.append(table);host.append(details);}
function addAffiliationStatus(host,record){const info=el('p','Checking membership…','muted');host.append(info);if(record.type==='Political office'){info.textContent='ELECTION';const a=el('a','View election →');a.href='https://cp.dunerealms.com/politics-cp#household/elections';host.append(a);return;}const company=record.type==='Company',slug=record.url.split('/').filter(Boolean).at(-1),path='/api/public/'+(company?'companies/':'clans/')+encodeURIComponent(slug);void fetch(path,{cache:'no-store'}).then(async response=>{if(!response.ok)throw Error();const data=await response.json(),row=company?data.organisation:data.clan,kind=company?row.charter_kind:data.deed.kind,count=Number(company?row.member_count:row.memberCount),limit=({basic:5,original:25,royal:50})[kind];if(!Number.isFinite(count)||!limit)throw Error();if(row.institution_key){info.textContent=count+' members · Protected';return;}info.textContent=count+' / '+limit+' members · '+(count>=limit?'FULL':'OPEN');if(count<limit){const join=el('a','Join →');join.href=company?'https://cp.dunerealms.com/join-company?company='+encodeURIComponent(record.id):'https://cp.dunerealms.com/clan-center.html?clan='+encodeURIComponent(row.id)+'#clans';host.append(join);}}).catch(()=>{info.textContent='Membership details unavailable.';});}