web/website/control-panel/public/clans.mjs
unimatrixgit 77cdf19faa Checkpoint Alpha 1.0.0.3 graphical menus and moderation evidence
Preserve the current Alpha source and artwork snapshot. See handoff/alpha-1.0.0.3 for actual deployed hashes, checks, staged follow-ups and the production pause. This checkpoint does not claim every source feature is deployed.
2026-11-02 00:05:34 +01:00

71 lines
15 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 {createClanRequestGate} from './clan-request-gate.mjs';
const gate=createClanRequestGate();
let clanPortalEmbedded=false;try{clanPortalEmbedded=parent!==window&&new URL(document.referrer).origin==='https://clans.dunerealms.com';}catch{}
const el=(tag,text)=>{const node=document.createElement(tag);if(text!==undefined)node.textContent=text;return node;};
const dashboard=document.getElementById('dashboard'),nav=dashboard?.querySelector('nav');
const section=el('section');section.id='clans';section.className='clan-center';section.hidden=true;
const hero=el('header'),art=el('img');art.src='https://www.dunerealms.com/assets/nav-clan-v2.webp';art.alt='';art.width=100;art.height=100;
const heroText=el('div');heroText.append(el('p','THE CLAN & QUEST REGISTER'),el('h2','Clans & Quests'),el('p','Raise your banner, manage your clan and plan your next adventure.'));const questArt=el('img');questArt.src='https://www.dunerealms.com/assets/nav-manual-full-v2.webp';questArt.alt='Quest journal';questArt.className='clan-quest-hero-art';hero.append(art,heroText,questArt);
const notice=el('p');notice.role='status';notice.className='clan-notice';const toolbar=el('div');toolbar.className='clan-toolbar';
const refresh=el('button','Refresh clans'),search=el('input');refresh.type='button';search.type='search';search.placeholder='Find a clan by name or tag';search.setAttribute('aria-label','Search clans');toolbar.append(search,refresh);
const summary=el('div'),directory=el('div'),details=el('div');directory.className='clan-grid';details.className='clan-details';details.hidden=true;
const scope=el('p','Website clan roster and applications. In-game clan chat and prefixes are not available yet.');scope.className='clan-scope';section.append(hero,notice,summary,toolbar,directory,details,scope);
let state=null,selected=null,allowed=false,sessionUsername=null,navigation=0;
if(dashboard&&nav){dashboard.append(section);const link=el('a',clanPortalEmbedded?'Clans & Quests':'Quests');link.href=clanPortalEmbedded?'#clans':'#clan-quests';nav.append(link);}
async function api(path='',body){const response=await fetch('/api/clans'+path,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:{},...(body?{body:JSON.stringify(body)}:{}),cache:'no-store'});const data=await response.json();if(!response.ok){const error=new Error(data.message||'The clan request could not be completed.');error.status=response.status;throw error;}return data;}
function button(label,action,className=''){const node=el('button',label);node.type='button';node.className=className;node.onclick=action;return node;}
function badge(role){const node=el('span',role==='owner'?'Clan owner':role==='officer'?'Officer':'Member');node.className='clan-role clan-role-'+role;return node;}
function showDirectory(){if(details.parentElement!==section){section.insertBefore(details,scope);location.hash='#clans';}navigation++;gate.invalidate('detail');selected=null;details.hidden=true;directory.hidden=false;toolbar.hidden=false;renderDirectory();}
async function mutate(button,body,show=true){
const token=gate.begin('mutation');if(!token||!allowed)return false;const originalNavigation=navigation;
button.disabled=true;notice.textContent='Saving clan changes…';
try{
const data=await api('',body);if(!gate.current(token))return false;
if(['archive','leave'].includes(body.action)&&navigation===originalNavigation)showDirectory();
await load();if(!gate.current(token))return false;
if(show&&body.action!=='archive'&&navigation===originalNavigation){await showClan(data.clanId,false);if(!gate.current(token))return false;}
notice.textContent='Clan changes saved.';return true;
}catch(error){
if(!gate.current(token))return false;
if(error.status===409){await load();if(!gate.current(token))return false;}
notice.textContent=error.message+(error.status===409?' Details refreshed; review before submitting again.':'');return false;
}finally{if(gate.current(token))button.disabled=false;}
}
function field(form,label,key,value='',type='text',maxLength){const box=el('label',label),input=el(type==='textarea'?'textarea':'input');input.name=key;if(type!=='textarea')input.type=type;input.value=value;if(maxLength)input.maxLength=maxLength;box.append(input);form.append(box);return input;}
function clanForm(title,record){const form=el('form');form.className='clan-form';form.append(el('h3',title));const name=field(form,'Clan name','name',record?.name||'','text',40);name.minLength=3;name.required=true;const tag=field(form,'Banner tag · 2–6 letters or numbers','tag',record?.tag||'','text',6);tag.minLength=2;tag.pattern='[A-Za-z0-9]{2,6}';tag.required=true;const description=field(form,'Clan description','description',record?.description||'','textarea',1000);const save=el('button',record?'Save clan details':'Create clan');save.type='submit';form.append(save);form.onsubmit=event=>{event.preventDefault();mutate(save,{action:record?'edit':'create',...(record?{clanId:record.id,version:Number(record.version)}:{}),name:name.value,tag:tag.value,description:description.value});};return form;}
function renderDirectory(){directory.replaceChildren();if(!state)return;const query=search.value.trim().toLowerCase(),rows=state.clans.filter(clan=>[clan.name,clan.tag,clan.description].some(value=>String(value).toLowerCase().includes(query)));
for(const clan of rows){const card=el('article');card.className='clan-card';const crest=el('div','['+clan.tag+']');crest.className='clan-banner-tag';card.append(crest,el('h3',clan.name),el('p',clan.description||'This clan has not added an introduction yet.'),el('p',Number(clan.member_count)+' members'),button('View clan',()=>showClan(clan.id)));directory.append(card);}
if(!rows.length)directory.append(el('p',state.clans.length?'No clans match your search.':'No clans have been created yet. Raise the first banner.'));
}
async function load(){const token=gate.begin('directory');if(!allowed||!token)return false;gate.invalidate('detail');refresh.disabled=true;try{const data=await api();if(!gate.current(token)||data.username!==sessionUsername)return false;state=data;summary.replaceChildren();if(!state.linked){const hint=el('aside');hint.className='clan-callout';const link=el('a','Link your Minecraft identity');link.href='#game';hint.append(link,el('p','A verified Minecraft account is required to create, join or manage a clan.'));summary.append(hint);}
if(state.membership){const current=state.clans.find(clan=>clan.id===state.membership.clan_id);const card=el('aside');card.className='clan-callout';card.dataset.ownClanCard='';card.append(el('h3','Your clan · '+(current?.name||'Clan membership')),badge(state.membership.clan_role),button('Open your clan',()=>showClan(state.membership.clan_id)));summary.append(card);}
else if(state.linked){const create=el('details');create.append(el('summary','Create your clan'),clanForm('A new banner'));summary.append(create);}
if(state.applications.length){const applications=el('aside');applications.className='clan-callout';applications.append(el('h3','Your pending join requests'));for(const request of state.applications)applications.append(button('['+request.tag+'] '+request.name,()=>showClan(request.clan_id)));summary.append(applications);}
renderDirectory();if(selected){await showClan(selected,false);if(!gate.current(token))return false;}return true;
}catch(error){if(gate.current(token))notice.textContent=error.message;return false;}finally{if(gate.current(token))refresh.disabled=false;}}
async function showClan(id,userNavigation=true){const token=gate.begin('detail');if(!allowed||!token||!state)return false;if(userNavigation)navigation++;selected=id;try{const data=await api('/'+encodeURIComponent(id));if(!gate.current(token)||selected!==id||!state)return false;const clan=data.clan;directory.hidden=true;toolbar.hidden=true;details.hidden=false;details.replaceChildren();details.append(button('← Clan directory',showDirectory),el('div','['+clan.tag+']'),el('h3',clan.name),el('p',clan.description||'No clan introduction yet.'));
const context={clanId:clan.id,version:Number(clan.version)};if(data.role)details.append(badge(data.role));
if(!data.role&&!state.membership){const pending=state.applications.some(request=>request.clan_id===id);const join=button(pending?'Withdraw join request':'Request to join',()=>mutate(join,{...context,action:pending?'withdraw':'request'}));join.disabled=!data.linked&&!pending;details.append(join,el('p',pending?'Your request is waiting for a clan owner or officer.':'An owner or officer reviews requests before membership is granted.'));}
const table=el('table');table.className='clan-table';const head=el('thead'),tr=el('tr');for(const title of ['Clan member','Role','Joined',...(data.canManage?['Manage']:[])])tr.append(el('th',title));head.append(tr);table.append(head);const tbody=el('tbody');
for(const member of data.members){const row=el('tr'),roleCell=el('td');roleCell.append(badge(member.clan_role));row.append(el('td',member.username),roleCell,el('td',new Date(Number(member.joined_at)).toLocaleDateString()));
if(data.canManage){const actions=el('td');actions.className='clan-member-actions';if(member.username!==state.username){const role=button(member.clan_role==='officer'?'Make member':'Make officer',()=>mutate(role,{...context,action:'role',target:member.username,role:member.clan_role==='officer'?'member':'officer'}));const remove=button('Remove member',()=>mutate(remove,{...context,action:'remove',target:member.username}));actions.append(role,remove);const transfer=el('details');transfer.append(el('summary','Transfer ownership'));const form=el('form');form.append(el('p','Transfer clan ownership to '+member.username+'. You will become an officer.'));const confirm=field(form,'Type the new owner’s username','confirmation');confirm.required=true;const submit=el('button','Transfer to '+member.username);submit.type='submit';form.append(submit);form.onsubmit=event=>{event.preventDefault();if(confirm.value!==member.username){notice.textContent='Type the exact username before transferring ownership.';return;}mutate(submit,{...context,action:'transfer',target:member.username});};transfer.append(form);actions.append(transfer);}row.append(actions);}tbody.append(row);
}table.append(tbody);const scroll=el('div');scroll.className='clan-table-scroll';scroll.append(table);details.append(scroll);
if(data.canReview){const requests=el('section');requests.className='clan-requests';requests.append(el('h3','Pending join requests'));for(const request of data.requests){const row=el('div');row.append(el('strong',request.username),el('span','Requested '+new Date(Number(request.created_at)).toLocaleDateString()));for(const [decision,label]of [['accept','Accept member'],['decline','Decline request']]){const action=button(label,()=>mutate(action,{...context,action:'review',target:request.username,decision}));row.append(action);}requests.append(row);}if(!data.requests.length)requests.append(el('p','No requests are awaiting review.'));details.append(requests);}
if(data.canManage){const edit=el('details');edit.append(el('summary','Edit clan details'),clanForm('Your clan banner',clan));const archive=el('details');archive.className='clan-danger';archive.append(el('summary','Archive this clan'));const form=el('form');form.append(el('p','Archiving closes join requests and releases every member. The name, tag and audit history are retained. This does not change any game balance or staff rank.'));const confirm=field(form,'Type '+clan.tag+' to confirm','confirmTag');confirm.required=true;const submit=el('button','Archive clan');submit.type='submit';form.append(submit);form.onsubmit=event=>{event.preventDefault();mutate(submit,{...context,action:'archive',confirmTag:confirm.value},false);};archive.append(form);details.append(edit,archive);}
else if(data.role&&data.role!=='owner'){const leave=button('Leave clan',()=>{mutate(leave,{...context,action:'leave'},false);});details.append(leave);}
else if(data.role==='owner'&&!data.linked)details.append(el('p','Link your Minecraft identity to manage this clan. Ownership must be transferred or the clan archived before its owner can leave.'));
return true;}catch(error){if(gate.current(token))notice.textContent=error.message;return false;}}
search.oninput=renderDirectory;refresh.onclick=()=>load();
async function session(user){
allowed=typeof user?.username==='string'&&!!user?.permissions?.includes('web.menu.game');sessionUsername=allowed?user.username:null;
// publicUser exposes a unique immutable username, not the private central account ID.
gate.setActor(allowed?String(user.id||user.username):null);navigation++;state=null;selected=null;notice.textContent='';search.value='';refresh.disabled=false;
directory.replaceChildren();details.replaceChildren();summary.replaceChildren();details.hidden=true;directory.hidden=false;toolbar.hidden=false;section.hidden=!allowed;
if(allowed&&location.hash==='#clans')await load();
}
window.addEventListener('dune:session',event=>session(event.detail));window.addEventListener('dune:page',event=>{if(event.detail?.page==='clans')load();});window.addEventListener('hashchange',()=>{if(location.hash!=='#clan-settings'&&details.parentElement!==section){section.insertBefore(details,scope);showDirectory();}if(location.hash==='#clans')load();});
// Only this trusted parent receives layout size; no identity or membership payload is posted.
if(parent!==window){let trusted=false;try{trusted=new URL(document.referrer).origin==='https://clans.dunerealms.com';}catch{}if(trusted){document.documentElement.classList.add('clan-embedded');document.body.classList.add('clan-embedded');const embeddedView=()=>document.body.classList.toggle('clan-embedded-view',(location.hash==='#clans'||location.hash.startsWith('#clan-')));embeddedView();window.addEventListener('hashchange',embeddedView);let previousHeight=0;new ResizeObserver(()=>{const height=Math.max(300,Math.ceil(document.body.getBoundingClientRect().height));if(height===previousHeight)return;previousHeight=height;parent.postMessage({type:'dunerealms-clan-height',height},'https://clans.dunerealms.com');}).observe(document.body);}}
const initialSession=gate.snapshot();try{const initial=await fetch('/api/auth/session',{cache:'no-store'});if(initial.ok){const data=await initial.json();if(gate.sameSession(initialSession))session(data.user);}}catch{if(gate.sameSession(initialSession))notice.textContent='Clan Center sign-in could not be checked. Refresh to try again.';}
export async function mountOwnClanManagement(target){if(!allowed)return false;selected=null;await load();if(!allowed||!state?.membership)return false;const id=state.membership.clan_id;if(!await showClan(id))return false;if(!allowed||state?.membership?.clan_id!==id)return false;target.append(details);details.hidden=false;return true;}