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

37 lines
980 B
TypeScript
Raw 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
}
}
return { current, enter }
}