58 lines
1.6 KiB
TypeScript
58 lines
1.6 KiB
TypeScript
import type { QuestBookState, QuestClaimed } from '~/types/game'
|
|
|
|
/** Whether the quest book is open; one book for the whole game shell. */
|
|
export const useQuestBookOpen = () => useState('quest-book-open', () => false)
|
|
|
|
/**
|
|
* The quest book of the village in the header. Claims answer with the fresh village,
|
|
* which goes straight into the shared village state so the stock updates at once.
|
|
*/
|
|
export function useQuests() {
|
|
const v = useVillageContext()
|
|
const book = ref<QuestBookState | null>(null)
|
|
const error = ref<string | null>(null)
|
|
const busy = ref(false)
|
|
const errorText = useErrorText()
|
|
|
|
const villageId = () => v.village.value?.id
|
|
|
|
async function load() {
|
|
const id = villageId()
|
|
if (!id) return
|
|
error.value = null
|
|
try {
|
|
book.value = await ws.send<QuestBookState>('quest.index', { village_id: id })
|
|
} catch (e) {
|
|
error.value = errorText(e)
|
|
}
|
|
}
|
|
|
|
async function run(event: string, data: object) {
|
|
const id = villageId()
|
|
if (!id) return false
|
|
busy.value = true
|
|
error.value = null
|
|
try {
|
|
const res = await ws.send<QuestClaimed>(event, { village_id: id, ...data })
|
|
book.value = res.book
|
|
v.village.value = res.village
|
|
return true
|
|
} catch (e) {
|
|
error.value = errorText(e)
|
|
return false
|
|
} finally {
|
|
busy.value = false
|
|
}
|
|
}
|
|
|
|
return {
|
|
book,
|
|
error,
|
|
busy,
|
|
load,
|
|
claim: (quest: string) => run('quest.claim', { quest }),
|
|
/** Collect the given level rewards, or all of them. */
|
|
collect: (ids?: number[]) => run('quest.collect', ids ? { ids } : {}),
|
|
}
|
|
}
|