game-village-politics-frontend/app/composables/useCurrentWorld.ts

48 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

export interface CurrentWorld {
worldId: number
/** The player's village there, once known. */
villageId: number | null
}
const KEY = 'vp.world'
function read(): CurrentWorld | null {
try {
const raw = localStorage.getItem(KEY)
return raw ? JSON.parse(raw) : null
} catch {
return null
}
}
/**
* The world the player is in. Inside a world the header only shows that world's
* navigation; remembered across reloads so the Village link stays.
*/
export function useCurrentWorld() {
const current = useState<CurrentWorld | null>('world.current', read)
function enter(worldId: number, villageId: number | null = null) {
const keep = current.value?.worldId === worldId ? current.value.villageId : null
current.value = { worldId, villageId: villageId ?? keep }
try {
localStorage.setItem(KEY, JSON.stringify(current.value))
} catch {
// only the Village link after a reload is lost
}
}
/** Drop a remembered village that no longer exists (a world reset, a conquest). */
function forget(villageId: number) {
if (current.value?.villageId !== villageId) return
current.value = { ...current.value, villageId: null }
try {
localStorage.setItem(KEY, JSON.stringify(current.value))
} catch {
// nothing remembered, nothing to drop
}
}
return { current, enter, forget }
}