Recent updates sheet (Feature 21) (#176)
CI / ci (push) Successful in 9m7s

Co-authored-by: orchestrator-agent <20+orchestrator-agent@code.cubecraftcreations.com>
This commit was merged in pull request #176.
This commit is contained in:
2026-10-10 15:48:26 -04:00
committed by approver_agent
parent ea5399098d
commit 837da07f3e
20 changed files with 1387 additions and 10 deletions
+103 -1
View File
@@ -1,11 +1,15 @@
import { useQuery } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useApi } from '../api/index.ts'
import { isRecord } from '../api/errors.ts'
import { oneOf, photoId } from '../dinners/api.ts'
import { weekLabel } from '../plan/week.ts'
import { appPath } from '../push/notification.ts'
export const HOME_PATH = '/api/v1/home'
export const HOME_KEY = ['home'] as const
export const UPDATES_PATH = '/api/v1/updates'
export const UPDATES_SEEN_PATH = '/api/v1/updates/seen'
export const UPDATES_KEY = ['updates'] as const
export const ORIGINS = ['regular', 'side_quest'] as const
export type Origin = (typeof ORIGINS)[number]
@@ -95,3 +99,101 @@ export function useHome() {
queryFn: async () => parseHome(`GET ${HOME_PATH}`, await apiFetch<unknown>(HOME_PATH)),
})
}
export const UPDATE_TYPES = ['plan_ready', 'list_ready', 'day_of_reminder', 'new_suggestions', 'rotation_review'] as const
export type UpdateType = (typeof UPDATE_TYPES)[number]
// Update is one of the Recent updates: a notification event, whatever
// channels it went to. url is the same-origin path it opens; created_at is
// when it was stored, the UTC RFC 3339 instant POST /api/v1/updates/seen
// takes back.
export type Update = { type: UpdateType; title: string; body: string; url: string; created_at: string }
// parseUpdate checks one update. Its url must stay on origin once parsed, as
// the server only ever stores a path on the app's own origin; url is that
// path as parsed.
function parseUpdate(where: string, body: unknown, origin: string): Update {
if (
!isRecord(body) ||
typeof body.title !== 'string' ||
typeof body.body !== 'string' ||
typeof body.url !== 'string' ||
typeof body.created_at !== 'string'
) {
throw new Error(`${where}: an update is not a notification event`)
}
const url = appPath(body.url, origin)
if (url === null) throw new Error(`${where}: update url ${JSON.stringify(body.url)} is not a path on this app`)
if (Number.isNaN(Date.parse(body.created_at))) {
throw new Error(`${where}: update created_at "${body.created_at}" is not a time`)
}
return {
type: oneOf(where, 'type', UPDATE_TYPES, body.type),
title: body.title,
body: body.body,
url,
created_at: body.created_at,
}
}
// parseUpdates checks a GET /api/v1/updates body, from the app at origin:
// the updates, newest first.
export function parseUpdates(where: string, body: unknown, origin: string): Update[] {
if (!isRecord(body) || !Array.isArray(body.updates)) throw new Error(`${where}: response is not the updates`)
return body.updates.map((update) => parseUpdate(where, update, origin))
}
// useUpdates is the Recent updates (GET /api/v1/updates): the last ten
// notification events, newest first. Each opening of the sheet reads it
// afresh (refetchOnMount 'always'), whatever the query client still holds;
// the sheet shows, and marks seen, only the list that opening read. Closing
// the sheet aborts a read still in flight, so a reopen sends its own rather
// than adopt one sent before it.
export function useUpdates() {
const { apiFetch } = useApi()
return useQuery({
queryKey: UPDATES_KEY,
queryFn: async ({ signal }) =>
parseUpdates(`GET ${UPDATES_PATH}`, await apiFetch<unknown>(UPDATES_PATH, { signal }), window.location.origin),
refetchOnMount: 'always',
})
}
const MARK_SEEN_KEY = ['updates', 'seen'] as const
// useMarkUpdatesSeen records that the household has seen its updates
// through the created_at of the newest one shown (POST
// /api/v1/updates/seen). The bell's unread dot clears at once, and a Home
// read in flight is stopped so it cannot bring it back; if the server
// refuses, the dot is put back as it was before the first of the marks in
// flight. Once the last mark in flight settles Home is read again, so the
// dot shows only for an event stored since.
export function useMarkUpdatesSeen() {
const { apiFetch } = useApi()
const queryClient = useQueryClient()
// alone says whether this is the only mark in flight; each counts itself
// until it has settled.
const alone = () => queryClient.isMutating({ mutationKey: MARK_SEEN_KEY }) === 1
return useMutation({
mutationKey: MARK_SEEN_KEY,
mutationFn: async (through: string) => {
await apiFetch<unknown>(UPDATES_SEEN_PATH, { method: 'POST', body: { through } })
},
onMutate: async () => {
// A mark sent while another is in flight would snapshot that one's
// optimistic answer, so only the first snapshots.
const unread = alone() ? queryClient.getQueryData<Home>(HOME_KEY)?.unread : undefined
await queryClient.cancelQueries({ queryKey: HOME_KEY })
queryClient.setQueryData<Home>(HOME_KEY, (home) => home && { ...home, unread: false })
return { unread }
},
onError: (_error, _through, context) => {
if (context?.unread === undefined || !alone()) return
const { unread } = context
queryClient.setQueryData<Home>(HOME_KEY, (home) => home && { ...home, unread })
},
onSettled: () => {
if (alone()) void queryClient.invalidateQueries({ queryKey: HOME_KEY })
},
})
}