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

40 lines
1.3 KiB
TypeScript

import type { TribeListRow, TribePage } from '~/types/game'
/** The player's tribe on one world: its page, every tribe of the world, and the changes. */
export function useTribe(worldId: number) {
const page = ref<TribePage | null>(null)
const tribes = ref<TribeListRow[] | null>(null)
const error = ref<string | null>(null)
const busy = ref(false)
const errorText = useErrorText()
const v = useVillageContextOrNull()
async function call<T>(event: string, data: object = {}): Promise<T | null> {
busy.value = true
error.value = null
try {
return await ws.send<T>(event, { world_id: worldId, ...data })
} catch (e) {
error.value = errorText(e)
return null
} finally {
busy.value = false
}
}
const load = async () => (page.value = (await call<TribePage>('tribe.show')) ?? page.value)
const loadList = async () => (tribes.value = (await call<TribeListRow[]>('tribe.list')) ?? tribes.value)
/** A change answers with the fresh page; the village header learns about it too. */
async function act(intent: string, data: object = {}) {
const next = await call<TribePage>(`tribe.${intent}`, data)
if (!next) return false
page.value = next
v?.refresh()
if (tribes.value) loadList()
return true
}
return { page, tribes, error, busy, load, loadList, act }
}