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

61 lines
2.0 KiB
TypeScript

import type { Report, ReportPage, ReportType } from '~/types/game'
/** Unread reports on the current world, for the header badge; every village state and report page updates it. */
export const useUnreadReports = () => useState<number>('reports.unread', () => 0)
/** The player's reports on one world: a page of the list, one report, delete and mark read. */
export function useReports(worldId: number) {
const page = ref<ReportPage | null>(null)
/** The kind of reports listed; null for all. */
const type = ref<ReportType | null>(null)
const error = ref<string | null>(null)
const busy = ref(false)
const unread = useUnreadReports()
const errorText = useErrorText()
async function call<T>(event: string, data: object): Promise<T | null> {
busy.value = true
error.value = null
try {
return await ws.send<T>(event, data)
} catch (e) {
error.value = errorText(e)
return null
} finally {
busy.value = false
}
}
async function list(event: string, data: object) {
const result = await call<ReportPage>(event, { world_id: worldId, type: type.value, ...data })
if (result) {
page.value = result
unread.value = result.unread
}
}
return {
page,
type,
error,
busy,
load: (n = 1) => list('report.index', { page: n }),
// Both answer with every kind; a filtered list loads its kind again.
remove: async (ids: number[]) => {
await list('report.delete', { ids })
if (type.value) await list('report.index', { page: 1 })
},
readAll: async () => {
await list('report.readAll', {})
if (type.value) await list('report.index', { page: 1 })
},
/** One report; opening an unread one marks it read. */
show: async (id: number) => {
const report = await call<Report>('report.show', { id })
// Opening it may have read the last unread one; the list knows the new count.
if (report) ws.send<ReportPage>('report.index', { world_id: worldId, page: 1 }).then((p) => (unread.value = p.unread), () => {})
return report
},
}
}