forked from unimatrix/web
17 lines
12 KiB
JavaScript
17 lines
12 KiB
JavaScript
const portalRoot=document.querySelector('#portal-content'),portalMode=document.body.dataset.portal;let playerSession={authenticated:false,staff:false},playerProfile=null,ticketPageOffset=null,currentTicket=null,ticketMessages=[],portalToastTimer;
|
|
const portalEl=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e};
|
|
async function portalRequest(path,options={}){const r=await fetch('/api/'+path,{...options,headers:{'Content-Type':'application/json',...(options.headers||{})},cache:'no-store'});const data=await r.json();if(!r.ok)throw Error(data.message||({not_found:'This ticket is unavailable or does not belong to your account.',forbidden:'This action requires an authorised staff account.'}[data.error]||'The player portal is temporarily unavailable.'));return data}
|
|
function portalNotify(message){const t=document.querySelector('.toast');t.textContent=message;t.classList.add('visible');clearTimeout(portalToastTimer);portalToastTimer=setTimeout(()=>t.classList.remove('visible'),3500)}
|
|
function portalDate(time){return new Date(time).toLocaleString()}
|
|
function portalButton(text,handler,cls='forum-action'){const b=portalEl('button',text,cls);b.type='button';b.addEventListener('click',handler);return b}
|
|
function portalSignIn(){const panel=portalEl('div',undefined,'portal-signin-panel');panel.append(portalEl('h2','Your private player portal'),portalEl('p','Sign in with ChatGPT to save your profile, submit ban appeals and request staff support. Only you and authorised staff can read your tickets.'));const a=portalEl('a','Sign in with ChatGPT ↗','button gold');a.href='/signin-with-chatgpt?return_to='+encodeURIComponent('/'+(portalMode==='profile'?'profile.html':portalMode==='tickets'?'tickets.html':'portal.html'));a.target='_top';panel.append(a);portalRoot.replaceChildren(panel)}
|
|
function portalError(message){portalRoot.replaceChildren(portalEl('div',message,'portal-error'))}
|
|
async function showPortalOverview(){const data=await portalRequest('tickets');const template=document.querySelector('#portal-overview-template').content.cloneNode(true);template.querySelector('[data-profile-name]').textContent=playerProfile?.display_name||'Explorer';template.querySelector('[data-minecraft-name]').textContent=playerProfile?.minecraft_name||'Add your Minecraft name in your profile';template.querySelector('[data-ticket-count]').textContent=String(data.activeCount??data.tickets.filter(t=>!['closed','resolved'].includes(t.status)).length);const recent=template.querySelector('[data-recent-tickets]');for(const ticket of data.tickets.slice(0,5)){const a=portalEl('a',`${ticket.subject} · ${playerSession.ticketStates[ticket.status]}`,'portal-recent-ticket');a.href='tickets.html#ticket='+ticket.id;recent.append(a)}if(!data.tickets.length)recent.append(portalEl('p','You have no support tickets yet.'));const staff=template.querySelector('[data-staff-link]');staff.hidden=!playerSession.staff;portalRoot.replaceChildren(template)}
|
|
function showPlayerProfile(){const template=document.querySelector('#profile-template').content.cloneNode(true),form=template.querySelector('form');for(const [field,key]of [['displayName','display_name'],['minecraftName','minecraft_name'],['discordName','discord_name']])form.elements[field].value=playerProfile?.[key]||'';form.addEventListener('submit',async e=>{e.preventDefault();const button=form.querySelector('button[type="submit"]');button.disabled=true;try{const values=Object.fromEntries(new FormData(form));await portalRequest('profile',{method:'POST',body:JSON.stringify(values)});localStorage.setItem('duneForumName',values.displayName);playerProfile=(await portalRequest('profile')).profile;form.querySelector('[role="status"]').textContent='Your profile has been saved.';portalNotify('Profile saved.')}catch(error){form.querySelector('[role="status"]').textContent=error.message}finally{button.disabled=false}});portalRoot.replaceChildren(template)}
|
|
function staffTicketView(){return playerSession.staff&&new URLSearchParams(location.search).get('view')==='staff'}
|
|
async function showTicketList(append=false){currentTicket=null;const toolbar=document.querySelector('#ticket-controls');toolbar.hidden=false;const staff=staffTicketView(),status=document.querySelector('#ticket-status-filter').value,category=document.querySelector('#ticket-category-filter').value;try{const data=await portalRequest('tickets?'+new URLSearchParams({view:staff?'staff':'mine',status,category,offset:append?ticketPageOffset||0:0}));ticketPageOffset=data.nextOffset;document.querySelector('#ticket-list-heading').textContent=staff?'Staff support queue':'My support tickets';const list=append?document.querySelector('.ticket-list'):portalEl('div',undefined,'ticket-list');if(!append)portalRoot.replaceChildren(list);for(const ticket of data.tickets){const a=portalEl('a',undefined,'ticket-card');a.href='#ticket='+ticket.id;const details=portalEl('div');details.append(portalEl('span',playerSession.ticketCategories[ticket.category]+' · #'+ticket.id.slice(0,8),'forum-tag'),portalEl('h3',ticket.subject),portalEl('p',`${staff?ticket.owner_name+' · ':''}Updated ${portalDate(ticket.updated_at)}`));a.append(details,portalEl('span',playerSession.ticketStates[ticket.status],'ticket-status status-'+ticket.status));list.append(a)}document.querySelector('#ticket-more').hidden=ticketPageOffset===null;if(!append&&!data.tickets.length){const box=portalEl('div',undefined,'portal-empty');box.append(portalEl('h2',staff?'The queue is clear':'No tickets here yet'),portalEl('p',staff?'There are no requests matching these filters.':'Open a ban appeal or request help from staff. Your case stays under your profile.'));portalRoot.replaceChildren(box)}}catch(error){portalError(error.message)}}
|
|
async function updateTicketStatus(status){try{await portalRequest('tickets/'+currentTicket.id+'/status',{method:'POST',body:JSON.stringify({status})});portalNotify('Ticket status updated.');showTicketDetail(currentTicket.id)}catch(error){portalNotify(error.message)}}
|
|
async function showTicketDetail(id,append=false){try{const data=await portalRequest('tickets/'+id+(append?'?offset='+ticketPageOffset:''));currentTicket=data.ticket;ticketMessages=append?[...ticketMessages,...data.messages]:data.messages;ticketPageOffset=data.nextOffset;document.querySelector('#ticket-controls').hidden=true;document.querySelector('#ticket-more').hidden=true;portalRoot.replaceChildren();const back=portalEl('a',staffTicketView()?'← Staff queue':'← My tickets','text-link');back.href='#';portalRoot.append(back);const original=portalEl('article',undefined,'private-ticket');original.append(portalEl('p',playerSession.ticketCategories[currentTicket.category]+' · #'+id.slice(0,8),'eyebrow'),portalEl('h2',currentTicket.subject),portalEl('span',playerSession.ticketStates[currentTicket.status],'ticket-status status-'+currentTicket.status),portalEl('p',`${currentTicket.owner_name} · ${portalDate(currentTicket.created_at)}`,'forum-meta'));const names=portalEl('div',undefined,'ticket-player-details');names.append(portalEl('p','Minecraft: '+(currentTicket.minecraft_name||'Not specified')));if(currentTicket.discord_name)names.append(portalEl('p','Discord handle: '+currentTicket.discord_name));original.append(names,portalEl('div',currentTicket.body,'forum-message'));portalRoot.append(original);const controls=portalEl('div',undefined,'ticket-state-controls');if(playerSession.staff){const select=portalEl('select');select.setAttribute('aria-label','Ticket status');for(const [key,label]of Object.entries(playerSession.ticketStates)){const option=portalEl('option',label);option.value=key;select.append(option)}select.value=currentTicket.status;controls.append(select,portalButton('Update status',()=>updateTicketStatus(select.value)))}else if(currentTicket.isOwner){controls.append(portalButton(currentTicket.status==='closed'?'Reopen my ticket':'Close my ticket',()=>updateTicketStatus(currentTicket.status==='closed'?'open':'closed')))}portalRoot.append(controls);for(const message of ticketMessages){const row=portalEl('article',undefined,'ticket-message role-'+message.author_role);row.append(portalEl('p',`${message.author_name} · ${message.author_role==='staff'?'Staff reply · ':message.author_role==='system'?'Status update · ':''}${portalDate(message.created_at)}`,'forum-meta'),portalEl('div',message.body,'forum-message'));portalRoot.append(row)}if(ticketPageOffset!==null)portalRoot.append(portalButton('Load more replies',()=>showTicketDetail(id,true),'pagination-button'));if(currentTicket.status!=='closed'){const panel=document.querySelector('#ticket-reply-template').content.cloneNode(true),form=panel.querySelector('form');form.querySelector('h3').textContent=playerSession.staff?'Staff reply':'Reply to staff';form.addEventListener('submit',async e=>{e.preventDefault();const b=form.querySelector('button[type="submit"]');b.disabled=true;try{await portalRequest('tickets/'+id+'/replies',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(form)))});portalNotify('Private reply sent.');showTicketDetail(id)}catch(error){portalNotify(error.message)}finally{b.disabled=false}});portalRoot.append(panel)}else portalRoot.append(portalEl('p','This ticket is closed. Reopen it if you need to continue.','small-note'))}catch(error){portalError(error.message)}}
|
|
function navigateTickets(){const match=location.hash.match(/^#ticket=([0-9a-f-]+)$/i);if(match)showTicketDetail(match[1]);else showTicketList()}
|
|
function initTicketControls(){const controls=document.querySelector('#ticket-controls');controls.hidden=false;document.querySelector('#staff-queue-link').hidden=!playerSession.staff;for(const [id,options]of [['ticket-status-filter',playerSession.ticketStates],['ticket-category-filter',playerSession.ticketCategories]]){const select=document.querySelector('#'+id);for(const [key,label]of Object.entries(options)){const option=portalEl('option',label);option.value=key;select.append(option)}select.addEventListener('change',()=>{if(location.hash)location.hash='';else showTicketList()})}const form=document.querySelector('#new-ticket-form'),category=form.elements.category;for(const [key,label]of Object.entries(playerSession.ticketCategories)){const o=portalEl('option',label);o.value=key;category.append(o)}document.querySelector('#new-ticket-button').addEventListener('click',()=>{if(!playerProfile){portalNotify('Save your player profile before opening a ticket.');return}form.reset();document.querySelector('#new-ticket-error').textContent='';document.querySelector('#new-ticket-dialog').showModal()});form.addEventListener('submit',async e=>{e.preventDefault();const b=form.querySelector('button[type="submit"]');b.disabled=true;try{const data=await portalRequest('tickets',{method:'POST',body:JSON.stringify(Object.fromEntries(new FormData(form)))});document.querySelector('#new-ticket-dialog').close();portalNotify('Your private ticket has been opened.');location.hash='ticket='+data.id}catch(error){document.querySelector('#new-ticket-error').textContent=error.message}finally{b.disabled=false}});document.querySelectorAll('[data-close-dialog]').forEach(b=>b.addEventListener('click',()=>b.closest('dialog').close()));document.querySelector('#ticket-more').addEventListener('click',()=>showTicketList(true));window.addEventListener('hashchange',navigateTickets);navigateTickets()}
|
|
portalRequest('portal/session').then(async data=>{playerSession=data;if(!playerSession.authenticated){portalSignIn();return}playerProfile=(await portalRequest('profile')).profile;if(portalMode==='profile')showPlayerProfile();else if(portalMode==='tickets')initTicketControls();else await showPortalOverview()}).catch(error=>portalError(error.message));
|

Staff