Add reusable content sets publication previews and focused input handling
This commit is contained in:
+33
-24
@@ -4,6 +4,8 @@ import { WorldView } from './world-view';
|
||||
import type { Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
||||
import { experienceText, permanentTitles, statPointsText, updateExperienceMeter } from './progression';
|
||||
import { characterPanel } from './character-panel';
|
||||
import { InputActions, isEditing, type InputAction } from './input-actions';
|
||||
import { hasOpenMenu, registerMenu } from './menu-focus';
|
||||
|
||||
type Recipe = { Inputs: Record<string, number>; Outputs: Record<string, number> };
|
||||
type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
|
||||
@@ -43,7 +45,7 @@ function progressSignature(): number | undefined {
|
||||
}
|
||||
const avoidUntil = new Map<string, number>();
|
||||
let requestedClose = false;
|
||||
const keys = new Set<string>();
|
||||
let input: InputActions;
|
||||
let view: WorldView;
|
||||
const selectedWorld = new URLSearchParams(location.search).get('world');
|
||||
const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : '';
|
||||
@@ -94,7 +96,7 @@ function connect() {
|
||||
else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false);
|
||||
};
|
||||
ws.onclose = async () => {
|
||||
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); keys.clear(); walkTo = undefined;
|
||||
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); input.clear(); walkTo = undefined;
|
||||
if (requestedClose || $<HTMLDialogElement>('ending').open) return;
|
||||
let detail = 'The connection ended. Your character state is held by the server.';
|
||||
try { const me = await api<{ character?: Character }>('/api/me'); if (me.character?.entity.state === 'dead') { showEnding('A life, remembered.', 'This character is permanently dead.', false); return; } if (me.character?.remainingSeconds === 0) detail = 'Daily play time is complete. Return after 00:00 UTC.'; } catch { detail = 'Your session ended. Sign in again to continue.'; }
|
||||
@@ -102,7 +104,7 @@ function connect() {
|
||||
};
|
||||
}
|
||||
function showEnding(title: string, detail: string, survivor: boolean) {
|
||||
keys.clear(); walkTo = undefined; pendingAction = undefined;
|
||||
input.clear(); walkTo = undefined; pendingAction = undefined;
|
||||
$('ending-title').textContent = title; $('ending-detail').textContent = detail;
|
||||
$('ending-eyebrow').textContent = survivor ? 'WORLD SURVIVED' : 'JOURNEY PAUSED';
|
||||
if (snapshot?.self.entity.state === 'dead') $('ending-eyebrow').textContent = 'JOURNEY ENDED';
|
||||
@@ -175,11 +177,19 @@ async function boot() {
|
||||
$<HTMLAnchorElement>('login').href = `/auth/login?return=${encodeURIComponent(location.pathname + location.search)}`;
|
||||
createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } });
|
||||
view = new WorldView($<HTMLCanvasElement>('world'));
|
||||
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
|
||||
if(key==='attack'||key==='gather')action(key);
|
||||
else if(key==='inventory')$('inventory-toggle').click();
|
||||
else if(key==='heal'||key==='return')send(key);
|
||||
});
|
||||
view.start(dt => {
|
||||
inputElapsed += dt;
|
||||
if (!snapshot || ws?.readyState !== WebSocket.OPEN || $<HTMLDialogElement>('ending').open) return;
|
||||
let x = Number(keys.has('d') || keys.has('arrowright')) - Number(keys.has('a') || keys.has('arrowleft'));
|
||||
let z = Number(keys.has('s') || keys.has('arrowdown')) - Number(keys.has('w') || keys.has('arrowup'));
|
||||
if(hasOpenMenu()||isEditing(document.activeElement)){
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false;
|
||||
if(inputElapsed>=0.05){send('move');inputElapsed=0;}return;
|
||||
}
|
||||
let {x,z} = input.movement;
|
||||
if (x || z) { walkTo = undefined; pendingAction = undefined; }
|
||||
if (walkTo) {
|
||||
const p = snapshot.self.entity.position, dx = walkTo.x - p.x, dz = walkTo.z - p.z, distance = Math.hypot(dx, dz);
|
||||
@@ -246,9 +256,16 @@ async function boot() {
|
||||
catch (e) { $('arrival-error').textContent = (e as Error).message; }
|
||||
finally { button.disabled = false; }
|
||||
};
|
||||
for (const id of ['inventory', 'settings']) { $(`${id}-toggle`).onclick = () => { visible(id, $(id).hidden); visible('movement', $('inventory').hidden && $('settings').hidden && !!snapshot); if (id === 'inventory' && snapshot) inventory(snapshot.self); }; }
|
||||
document.querySelectorAll<HTMLButtonElement>('[data-close]').forEach(button => button.onclick = () => visible(button.dataset.close!, false));
|
||||
$('attack').onclick = () => action('attack'); $('gather').onclick = () => action('gather'); $('heal').onclick = () => send('heal'); $('keystone').onclick = () => send('return');
|
||||
for (const id of ['inventory', 'settings']) {
|
||||
const menu=registerMenu($(id),()=>{visible(id,false);visible('movement',$('inventory').hidden&&$('settings').hidden&&!!snapshot)});
|
||||
$(`${id}-toggle`).onclick=()=>{
|
||||
if(!$(id).hidden){menu.close();return;}
|
||||
if(id==='inventory'&&snapshot)inventory(snapshot.self);
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;send('move');visible(id,true);visible('movement',false);menu.opened($(`${id}-toggle`));
|
||||
};
|
||||
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
|
||||
}
|
||||
$('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
|
||||
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
|
||||
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
|
||||
$('reconnect').onclick = () => location.reload();
|
||||
@@ -256,28 +273,20 @@ async function boot() {
|
||||
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
|
||||
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
|
||||
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
|
||||
window.addEventListener('keydown', event => {
|
||||
if ((event.target as HTMLElement).matches('input,select,textarea') || $<HTMLDialogElement>('arrival').open) return;
|
||||
const key = event.key.toLowerCase();
|
||||
if (['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', ' '].includes(key)) event.preventDefault();
|
||||
keys.add(key); if (event.repeat) return;
|
||||
if (key === 'e') action('gather'); if (key === ' ') action('attack'); if (key === 'i') $('inventory-toggle').click(); if (key === 'escape') { visible('inventory', false); visible('settings', false); selection(); walkTo = undefined; }
|
||||
});
|
||||
window.addEventListener('keyup', event => keys.delete(event.key.toLowerCase()));
|
||||
window.addEventListener('blur', () => { keys.clear(); walkTo = undefined; send('move'); });
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { keys.clear(); walkTo = undefined; send('move'); } });
|
||||
const movements: Record<string, string> = { up: 'w', down: 's', left: 'a', right: 'd' };
|
||||
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); });
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); } });
|
||||
const movements: Record<string, InputAction> = { up:'north',down:'south',left:'west',right:'east' };
|
||||
document.querySelectorAll<HTMLButtonElement>('[data-move]').forEach(button => {
|
||||
const key = movements[button.dataset.move!];
|
||||
button.onpointerdown = event => { button.setPointerCapture(event.pointerId); keys.add(key); };
|
||||
button.onpointerup = button.onpointercancel = () => keys.delete(key);
|
||||
const key = movements[button.dataset.move!],source=`pointer-${button.dataset.move}`;
|
||||
button.onpointerdown = event => { button.setPointerCapture(event.pointerId); input.press(source,key); };
|
||||
button.onpointerup = button.onpointercancel = button.onlostpointercapture = () => input.release(source);
|
||||
});
|
||||
view.canvas.addEventListener('pointerdown', event => {
|
||||
if (!snapshot || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
|
||||
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
|
||||
const hit = view.pick(event.clientX, event.clientY);
|
||||
if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
||||
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; }
|
||||
});
|
||||
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return [...keys]; } }, configurable: true });
|
||||
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true });
|
||||
}
|
||||
boot().catch(error => { console.error(error); $('arrival-error').textContent = `Unable to enter the world: ${error.message}`; $('connection-status').textContent = 'Unavailable'; });
|
||||
|
||||
Reference in New Issue
Block a user