51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
import type { Report, ReportPage } 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)
|
|
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, ...data })
|
|
if (result) {
|
|
page.value = result
|
|
unread.value = result.unread
|
|
}
|
|
}
|
|
|
|
return {
|
|
page,
|
|
error,
|
|
busy,
|
|
load: (n = 1) => list('report.index', { page: n }),
|
|
remove: (ids: number[]) => list('report.delete', { ids }),
|
|
readAll: () => list('report.readAll', {}),
|
|
/** 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
|
|
},
|
|
}
|
|
}
|