85 lines
12 KiB
TypeScript
85 lines
12 KiB
TypeScript
import type {Character, HouseInventory, HouseRequest, HouseState} from './generated';
|
||
import {api, APIError} from './portal-shared';
|
||
import {node} from './character-stats';
|
||
import {registerMenu} from './menu-focus';
|
||
import './housing.css';
|
||
import {confirmItemAction} from './item-actions';
|
||
|
||
const permissions:Record<string,string>={moveFurniture:'Move furniture',openFurniture:'Open furniture',placeFurniture:'Place furniture',depositItems:'Put items in furniture',pickupItems:'Pick up items in the house',dropItems:'Drop items in the house'};
|
||
const label=(text:string,control:HTMLElement)=>{const el=node('label',text);el.append(control);return el};
|
||
const button=(text:string,action:()=>void)=>{const b=node('button',text);b.type='button';b.onclick=action;return b};
|
||
const select=(rows:[string,string][])=>{const s=node('select');for(const [id,name] of rows)s.append(new Option(name,id));return s};
|
||
const number=(value:number,min:number,max:number)=>{const n=node('input');n.type='number';n.value=String(value);n.min=String(min);n.max=String(max);n.step='0.5';return n};
|
||
type InventoryView=Pick<HouseInventory,'inventory'|'items'> & {stackNames?:Record<string,string>};
|
||
function choices(v:InventoryView):[string,string][]{return [...v.items.map(i=>[i.id,i.name] as [string,string]),...Object.entries(v.inventory).filter(([,n])=>n>0).map(([id,n])=>[id,`${v.stackNames?.[id]??id} × ${n}`] as [string,string])];}
|
||
|
||
export function createHousingPanel(character:()=>Character|undefined,prefix:string,isHub:()=>boolean,onEnter:()=>void){
|
||
const root=node('section'),open=button('Housing & keys',()=>show());
|
||
const dialog=node('dialog','','housing-dialog'),title=node('h2','Housing'),status=node('p'),body=node('div'),close=button('Close controls',()=>dialog.close());
|
||
const toolbar=node('div','','house-toolbar');toolbar.hidden=true;toolbar.append(button('House controls',()=>show()),button('Return to hub',()=>void leave()));
|
||
const retry=button('Retry pending action',()=>{if(pending)void action(pending,true)});retry.hidden=true;
|
||
status.setAttribute('role','status');root.append(open);dialog.append(title,close,status,retry,body);document.body.append(dialog);
|
||
let entranceContext=false;
|
||
let pending:HouseRequest|undefined,state:HouseState|undefined,busy=false,loading=false,signature='',lastHouse='',selected='',latest:Character|undefined;
|
||
const menu=registerMenu(dialog,()=>dialog.close());dialog.addEventListener('cancel',e=>{e.preventDefault();dialog.close()});
|
||
function show(id='',atEntrance=false){entranceContext=atEntrance;selected=id;if(!dialog.open)dialog.showModal();menu.opened();void refresh(true)}
|
||
async function leave(){if(busy)return;if(character()?.houseId||state?.room)await action({op:'leave'});dialog.close();signature=''}
|
||
async function action(r:Omit<HouseRequest,'requestId'>,retrying=false){
|
||
if(busy)return;if(pending&&!retrying){status.textContent='Resolve the pending action before making another change.';return}busy=true;dialog.classList.add('housing-busy');status.textContent='Saving…';
|
||
pending??={...r,houseId:r.houseId??state?.room?.id,revision:r.revision??state?.room?.revision,requestId:crypto.randomUUID()};
|
||
try{await api(prefix+'/api/housing',pending);pending=undefined;status.textContent=r.op==='destroy-key'?'Destroying key. It remains lootable until the three seconds finish.':'Saved.';signature='';await refresh(true)}
|
||
catch(e){if(e instanceof APIError&&e.status<500)pending=undefined;status.textContent=(e as Error).message+(pending?' Retry the pending action to resolve its result safely.':'');await refresh(true)}
|
||
finally{busy=false;retry.hidden=!pending;dialog.classList.remove('housing-busy')}
|
||
}
|
||
async function refresh(force=false){
|
||
if(loading||!dialog.open)return;loading=true;
|
||
try{state=await api<HouseState>(prefix+'/api/housing');const c=character();if(!c)return;latest=c;
|
||
const next=JSON.stringify([state,c.items,c.inventory]);if(force||signature!==next){signature=next;render()}
|
||
}catch(e){status.textContent=(e as Error).message}finally{loading=false}
|
||
}
|
||
function render(){
|
||
const c=latest,s=state;if(!c||!s)return;body.replaceChildren();const h=s.room;
|
||
title.textContent=h?h.name+' · '+s.role:'Housing & keys';close.textContent=h?'Walk around':'Close';
|
||
const keys=node('section');keys.append(node('h3','Carried keys'),node('p','Destroying a key takes three seconds. Death, dropping the key, leaving the world, or disconnecting cancels the action.'));
|
||
for(const key of c.items.filter(i=>i.houseId)){const row=node('p',key.name+' ');row.append(button('Destroy key',()=>confirmItemAction('Destroy '+key.name+'?','This takes three seconds. The key remains lootable until destruction completes.',()=>void action({op:'destroy-key',item:key.id}))));keys.append(row)}
|
||
const progress=node('p');progress.dataset.keyProgress='';keys.append(progress,button('Cancel key destruction',()=>void action({op:'cancel-key'})));body.append(keys);
|
||
if(!h){
|
||
body.append(node('p',isHub()?'After surviving your first world, walk to the shared housing entrance in this hub to enter a house. A carried key grants owner rights; guests need an invitation.':'Return to a hub to enter housing. Keys can be destroyed here.'));
|
||
if(isHub()){const name=node('input');name.maxLength=80;name.placeholder='House name';body.append(label('New house name',name),button('Create house',()=>void action({op:'create',name:name.value})))}
|
||
for(const entry of s.houses){const row=node('section');row.append(node('h3',entry.name),node('p',`${entry.state} · ${entry.role||'no access'} · ${entry.keys} valid keys`));if(isHub()&&entranceContext&&entry.state==='active'&&entry.role)row.append(button('Enter through housing entrance',()=>void action({op:'enter',houseId:entry.id})));if(isHub()&&entry.creator&&entry.recoveryWorld&&entry.state!=='purged')row.append(button('Recover creator key',()=>void action({op:'recover',houseId:entry.id})));body.append(row)}return;
|
||
}
|
||
body.prepend(node('p','Private house room · click the floor to choose a position, or furniture to select it. No experience is earned here.'));
|
||
const layout=node('div','','house-layout');layout.setAttribute('aria-label','House floor plan');
|
||
const x=number(h.furniture[selected]?.x??0,-h.size/2,h.size/2),z=number(h.furniture[selected]?.z??0,-h.size/2,h.size/2);
|
||
layout.onclick=e=>{if(e.target!==layout)return;const b=layout.getBoundingClientRect();x.value=String(Math.round(((e.clientX-b.left)/b.width*h.size-h.size/2)*2)/2);z.value=String(Math.round(((e.clientY-b.top)/b.height*h.size-h.size/2)*2)/2)};
|
||
const furniture=select([['','Choose furniture'],...Object.values(h.furniture).map(f=>[f.item.id,f.item.name] as [string,string])]);furniture.value=selected;
|
||
const choose=(id:string)=>{selected=id;furniture.value=id;const f=h.furniture[id];if(f){x.value=String(f.x);z.value=String(f.z)}showStorage()};furniture.onchange=()=>choose(furniture.value);
|
||
for(const [id,f] of Object.entries(h.furniture)){const b=button(f.item.name,()=>choose(id)),p=f.item.furniture!;b.className='house-piece';b.style.left=(f.x+h.size/2)/h.size*100+'%';b.style.top=(f.z+h.size/2)/h.size*100+'%';b.style.width=p.width/h.size*100+'%';b.style.height=p.depth/h.size*100+'%';layout.append(b)}
|
||
body.append(layout,label('Selected furniture',furniture),label('East / west',x),label('North / south',z));
|
||
const held=select(c.items.filter(i=>i.furniture).map(i=>[i.id,i.name]));
|
||
if(s.effective.placeFurniture)body.append(label('Furniture in inventory',held),button('Place furniture',()=>void action({op:'place',item:held.value,x:Number(x.value),z:Number(z.value)})));
|
||
if(s.effective.moveFurniture)body.append(button('Move selected furniture',()=>void action({op:'move',target:furniture.value,x:Number(x.value),z:Number(z.value)})));
|
||
if(s.effective.pickupItems)body.append(button('Pick up selected furniture',()=>void action({op:'pickup-furniture',target:furniture.value})));
|
||
const storage=node('section');body.append(storage);showStorage();
|
||
function transfer(parent:HTMLElement,inventory:InventoryView,text:string,op:string,target=''){
|
||
const rows=choices(inventory);if(!rows.length){parent.append(node('p',text+': no items'));return}const item=select(rows),qty=number(1,1,1000);qty.step='1';parent.append(label(text,item),label('Quantity',qty),button(text,()=>void action({op,item:item.value,quantity:Number(qty.value),target})));
|
||
}
|
||
function showStorage(){if(!s||!h||!c)return;storage.replaceChildren();const f=h.furniture[furniture.value];
|
||
if(f?.item.furniture?.container){storage.append(node('h3',f.item.name));if(s.effective.openFurniture){const rows=choices(f.contents);storage.append(node('p',rows.map(([,name])=>name).join(', ')||'Empty'));if(s.effective.pickupItems)transfer(storage,f.contents,'Take from furniture','withdraw',f.item.id)}else storage.append(node('p','You cannot open this furniture.'));if(s.effective.depositItems)transfer(storage,c,'Put in furniture','deposit',f.item.id)}
|
||
}
|
||
const floor=node('section');floor.append(node('h3','Floor items'),node('p',choices(h.floor).map(([,name])=>name).join(', ')||'Nothing on the floor.'));if(s.effective.pickupItems)transfer(floor,h.floor,'Pick up floor item','pickup');if(s.effective.dropItems)transfer(floor,c,'Drop on floor','drop');body.append(floor);
|
||
if(s.role==='owner'||s.role==='co-owner'){
|
||
const management=node('details');management.append(node('summary','Guests & permissions'));body.append(management);
|
||
const names=new Map(s.people.map(p=>[p.id,p.name]));const people=select(s.people.filter(p=>p.id!==c.entity.id).map(p=>[p.id,p.name]));const role=select(s.role==='owner'?[['guest','Guest'],['co-owner','Co-owner']]:[['guest','Guest']]);management.append(label('Player in this hub',people),label('Invitation role',role),button('Invite',()=>void action({op:'invite',target:people.value,role:role.value})));
|
||
for(const [id,roleName] of Object.entries(h.roles)){const row=node('p',(names.get(id)??'Invited character')+' · '+roleName+' ');if(s.role==='owner'||roleName!=='co-owner')row.append(button('Remove invitation',()=>void action({op:'invite',target:id,role:'remove'})));management.append(row)}
|
||
if(s.role==='owner')management.append(button('Create additional owner key',()=>void action({op:'issue-key'})));
|
||
management.append(node('p','Every valid key grants owner rights. Removing an invitation cannot revoke a key. Co-owners can manage guests.'));
|
||
const target=select([['','Baseline for all guests'],...Object.keys(h.roles).map(id=>[id,names.get(id)??'Invited character'] as [string,string])]),fields=node('div');management.append(label('Permission settings for',target),fields);let values:Record<string,HTMLSelectElement>={};
|
||
const show=()=>{fields.replaceChildren();values={};for(const [key,text] of Object.entries(permissions)){const field=select(target.value?[['inherit','Use baseline'],['allow','Allow'],['deny','Deny']]:[['allow','Allow'],['deny','Deny']]);const v=target.value?h.overrides[target.value]?.[key]:h.permissions[key]??false;field.value=v===undefined?'inherit':v?'allow':'deny';values[key]=field;fields.append(label(text,field))}};target.onchange=show;show();
|
||
management.append(button('Save guest permissions',()=>{const permissions:Record<string,boolean>={};for(const [key,field] of Object.entries(values))if(field.value!=='inherit')permissions[key]=field.value==='allow';void action({op:'permissions',target:target.value,permissions})}));
|
||
}
|
||
}
|
||
setInterval(()=>{if(dialog.open&&!busy)void refresh();const a=character()?.destroyKey;const p=dialog.querySelector<HTMLElement>('[data-key-progress]');if(p)p.textContent=a?`Key destruction in progress · ${Math.max(0,a.finishesAt-Date.now()/1000).toFixed(1)}s remaining (server confirmed on completion)`:'No key destruction in progress.'},1000);
|
||
return {root,toolbar,open:show,openEntrance:()=>show('',true),enter:(houseId:string,key:string)=>{show('',true);void action({op:'enter',houseId,item:key})},leave,destroyKey:(id:string)=>{show();void action({op:'destroy-key',item:id})},update(c:Character){latest=c;toolbar.hidden=!c.houseId;open.textContent=c.houseId?'Return to house controls':'Housing & keys';if(c.entity.state==='dead'||c.remainingSeconds<=0){dialog.close();return}if((c.houseId??'')!==lastHouse){lastHouse=c.houseId??'';signature='';if(c.houseId){onEnter();dialog.close()}if(dialog.open)void refresh(true)}}};
|
||
}
|