Co-authored-by: orchestrator-agent <20+orchestrator-agent@code.cubecraftcreations.com>
This commit was merged in pull request #176.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { Bell, ChevronRight, Compass, Search, ShoppingCart, Zap, type LucideIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Link, useNavigate } from 'react-router'
|
||||
import { duration } from '../plan/PlanPage.tsx'
|
||||
import { supplyRunScreen } from '../shopping/api.ts'
|
||||
@@ -11,6 +12,7 @@ import { Photo } from '../ui/Photo.tsx'
|
||||
import { Skeleton } from '../ui/Skeleton.tsx'
|
||||
import { useHome, type Home, type Origin, type Tonight } from './api.ts'
|
||||
import styles from './HomePage.module.css'
|
||||
import { UpdatesSheet } from './UpdatesSheet.tsx'
|
||||
|
||||
const ORIGIN_LABEL: Record<Origin, string> = { regular: 'Regular', side_quest: 'Side quest' }
|
||||
|
||||
@@ -108,11 +110,12 @@ function Tiles() {
|
||||
// Quick dinner and Cook from what I have tiles, and the status rows, all
|
||||
// from GET /api/v1/home.
|
||||
//
|
||||
// The bell only shows whether there are unread updates; the Recent updates
|
||||
// sheet it opens is still to come.
|
||||
// The bell carries a grape dot while there are unread updates and opens the
|
||||
// Recent updates sheet, which marks them seen.
|
||||
export function HomePage() {
|
||||
const home = useHome()
|
||||
const data = home.data
|
||||
const [updatesOpen, setUpdatesOpen] = useState(false)
|
||||
return (
|
||||
<div className={styles.page} aria-busy={home.isPending}>
|
||||
<header className={styles.header}>
|
||||
@@ -124,7 +127,11 @@ export function HomePage() {
|
||||
)}
|
||||
<h1 className={styles.title}>Tonight's quest</h1>
|
||||
</div>
|
||||
<IconButton label={data?.unread ? 'Recent updates, unread' : 'Recent updates'} className={styles.bell}>
|
||||
<IconButton
|
||||
label={data?.unread ? 'Recent updates, unread' : 'Recent updates'}
|
||||
className={styles.bell}
|
||||
onClick={() => setUpdatesOpen(true)}
|
||||
>
|
||||
<Icon icon={Bell} className={styles.bellIcon} />
|
||||
{data?.unread && <span data-testid="unread-dot" className={styles.dot} />}
|
||||
</IconButton>
|
||||
@@ -142,6 +149,7 @@ export function HomePage() {
|
||||
</div>
|
||||
)}
|
||||
{data !== undefined && <StatusRows home={data} />}
|
||||
<UpdatesSheet open={updatesOpen} onClose={() => setUpdatesOpen(false)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/* The Recent updates sheet the Home bell opens. */
|
||||
.sheet {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
max-width: 560px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.rows {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: var(--color-accent-700);
|
||||
}
|
||||
|
||||
.time {
|
||||
font-family: var(--font-body);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--color-neutral-700);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.skeletonRow {
|
||||
height: 56px;
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 0;
|
||||
font-family: var(--font-body);
|
||||
font-size: 14px;
|
||||
line-height: 1.45;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { createMemoryRouter, RouterProvider, useLocation } from 'react-router'
|
||||
import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
|
||||
import { ApiProvider, createApiClient, createQueryClient, createVerifiedSession } from '../api/index.ts'
|
||||
import { createNetworkStatus } from '../pwa/networkStatus.ts'
|
||||
import { HOME } from '../test/ApiProviders.tsx'
|
||||
import { errorResponse, fakeLocation, jsonResponse, ME } from '../test/fetchStub.ts'
|
||||
import { HOME_KEY, HOME_PATH, UPDATES_PATH, UPDATES_SEEN_PATH } from './api.ts'
|
||||
import { HomePage } from './HomePage.tsx'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
// minutesAgo is the stored form of the instant n minutes before now.
|
||||
function minutesAgo(n: number): string {
|
||||
return new Date(Date.now() - n * 60_000).toISOString()
|
||||
}
|
||||
|
||||
// UPDATES are a GET /api/v1/updates body, newest first: the week drafted
|
||||
// five minutes ago, new Side quests three hours ago and the Supply run two
|
||||
// days ago.
|
||||
const UPDATES = {
|
||||
updates: [
|
||||
{
|
||||
type: 'plan_ready',
|
||||
title: 'Your week is drafted',
|
||||
body: 'Take a look at the Draft board.',
|
||||
url: '/plan',
|
||||
created_at: minutesAgo(5),
|
||||
},
|
||||
{ type: 'new_suggestions', title: '5 new Side quests', body: '', url: '/discover', created_at: minutesAgo(3 * 60) },
|
||||
{
|
||||
type: 'list_ready',
|
||||
title: 'Supply run ready',
|
||||
body: 'Week 41 · Oct 5 – 11',
|
||||
url: '/plan/shopping?week=2026-10-05',
|
||||
created_at: minutesAgo(2 * 24 * 60),
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
type Responder = (init: RequestInit | undefined) => Response | Promise<Response>
|
||||
|
||||
// stubServer answers "METHOD path" requests from responders, with /me; any
|
||||
// other request fails the test. Home is unread until the updates are marked
|
||||
// seen, as the server answers.
|
||||
function stubServer(responders: Record<string, Responder> = {}) {
|
||||
let seen = false
|
||||
const all: Record<string, Responder> = {
|
||||
'GET /api/v1/me': () => jsonResponse(200, ME),
|
||||
[`GET ${HOME_PATH}`]: () => jsonResponse(200, { ...HOME, recentUpdates: { unread: !seen } }),
|
||||
[`GET ${UPDATES_PATH}`]: () => jsonResponse(200, UPDATES),
|
||||
[`POST ${UPDATES_SEEN_PATH}`]: () => {
|
||||
seen = true
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
...responders,
|
||||
}
|
||||
const fetchMock = vi.fn<typeof fetch>((input, init) => {
|
||||
const key = `${init?.method ?? 'GET'} ${String(input)}`
|
||||
const respond = Object.hasOwn(all, key) ? all[key] : undefined
|
||||
if (respond === undefined) throw new Error(`unexpected fetch: ${key}`)
|
||||
return Promise.resolve(respond(init))
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
return fetchMock
|
||||
}
|
||||
|
||||
// posts lists the bodies of the POST /updates/seen requests sent, each of
|
||||
// which must carry the CSRF token.
|
||||
function posts(fetchMock: Mock<typeof fetch>) {
|
||||
return fetchMock.mock.calls
|
||||
.filter(([input, init]) => init?.method === 'POST' && String(input) === UPDATES_SEEN_PATH)
|
||||
.map(([, init]) => {
|
||||
expect(new Headers(init?.headers).get('X-MealQuest-CSRF')).toBe(ME.csrfToken)
|
||||
return String(init?.body)
|
||||
})
|
||||
}
|
||||
|
||||
function homeReads(fetchMock: Mock<typeof fetch>) {
|
||||
return fetchMock.mock.calls.filter(([input, init]) => String(input) === HOME_PATH && (init?.method ?? 'GET') === 'GET')
|
||||
.length
|
||||
}
|
||||
|
||||
function updatesReads(fetchMock: Mock<typeof fetch>) {
|
||||
return fetchMock.mock.calls.filter(
|
||||
([input, init]) => String(input) === UPDATES_PATH && (init?.method ?? 'GET') === 'GET',
|
||||
).length
|
||||
}
|
||||
|
||||
// Where shows the route a row went to.
|
||||
function Where() {
|
||||
const location = useLocation()
|
||||
return <p data-testid="where">{location.pathname + location.search}</p>
|
||||
}
|
||||
|
||||
// renderHome loads /me (for the CSRF token the POST needs) and renders Home,
|
||||
// answering its query client.
|
||||
async function renderHome() {
|
||||
const api = createApiClient(fakeLocation('/'), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{ path: '/', element: <HomePage /> },
|
||||
{ path: '*', element: <Where /> },
|
||||
],
|
||||
{ initialEntries: ['/'] },
|
||||
)
|
||||
const queryClient = createQueryClient()
|
||||
render(
|
||||
<ApiProvider client={api}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</ApiProvider>,
|
||||
)
|
||||
return queryClient
|
||||
}
|
||||
|
||||
// openSheet taps the unread bell and answers the open sheet.
|
||||
async function openSheet() {
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Recent updates, unread' }))
|
||||
return screen.getByRole('dialog', { name: 'Recent updates' })
|
||||
}
|
||||
|
||||
async function rows(sheet: HTMLElement) {
|
||||
return within(await within(sheet).findByRole('list', { name: 'Recent updates' })).getAllByRole('listitem')
|
||||
}
|
||||
|
||||
describe('Recent updates sheet', () => {
|
||||
it('lists the updates newest first with how long ago each came', async () => {
|
||||
stubServer()
|
||||
await renderHome()
|
||||
const listed = await rows(await openSheet())
|
||||
|
||||
expect(listed).toHaveLength(3)
|
||||
expect(listed[0]).toHaveTextContent('Your week is drafted')
|
||||
expect(listed[0]).toHaveTextContent('Take a look at the Draft board.')
|
||||
expect(listed[0]).toHaveTextContent('5 min ago')
|
||||
expect(listed[1]).toHaveTextContent('5 new Side quests')
|
||||
expect(listed[1]).toHaveTextContent('3 hr ago')
|
||||
expect(listed[2]).toHaveTextContent('Supply run ready')
|
||||
expect(listed[2]).toHaveTextContent('2 days ago')
|
||||
expect(within(listed[0]!).getByText('5 min ago')).toHaveAttribute('dateTime', UPDATES.updates[0]!.created_at)
|
||||
})
|
||||
|
||||
it('marks the updates seen through the newest, and the grape dot clears and stays cleared', async () => {
|
||||
const fetchMock = stubServer()
|
||||
await renderHome()
|
||||
expect(await screen.findByTestId('unread-dot')).toBeInTheDocument()
|
||||
await openSheet()
|
||||
|
||||
await waitFor(() => expect(posts(fetchMock)).toEqual([JSON.stringify({ through: UPDATES.updates[0]!.created_at })]))
|
||||
expect(screen.queryByTestId('unread-dot')).not.toBeInTheDocument()
|
||||
// Home is read again once the mark is saved, and the server says
|
||||
// nothing is unread: the dot does not come back.
|
||||
await waitFor(() => expect(homeReads(fetchMock)).toBe(2))
|
||||
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
|
||||
expect(await screen.findByRole('button', { name: 'Recent updates' })).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('unread-dot')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reads the updates afresh on each opening, so one stored since the last opening is listed and marked seen', async () => {
|
||||
// The server holds the stored events, newest first, and says Home is
|
||||
// unread while the newest is after the time marked seen.
|
||||
const stored = [...UPDATES.updates]
|
||||
let seenThrough = ''
|
||||
const fetchMock = stubServer({
|
||||
[`GET ${HOME_PATH}`]: () => jsonResponse(200, { ...HOME, recentUpdates: { unread: stored[0]!.created_at > seenThrough } }),
|
||||
[`GET ${UPDATES_PATH}`]: () => jsonResponse(200, { updates: stored }),
|
||||
[`POST ${UPDATES_SEEN_PATH}`]: (init) => {
|
||||
seenThrough = (JSON.parse(String(init?.body)) as { through: string }).through
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
})
|
||||
const queryClient = await renderHome()
|
||||
await rows(await openSheet())
|
||||
await waitFor(() => expect(posts(fetchMock)).toHaveLength(1))
|
||||
await waitFor(() => expect(homeReads(fetchMock)).toBe(2))
|
||||
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
|
||||
|
||||
// A new event is stored a moment later, well within the query client's
|
||||
// staleTime, and Home is read again, as on coming back to it.
|
||||
const reminder = {
|
||||
type: 'day_of_reminder',
|
||||
title: 'Tacos tonight',
|
||||
body: 'Dinner at 6:00.',
|
||||
url: '/plan',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
stored.unshift(reminder)
|
||||
await queryClient.invalidateQueries({ queryKey: HOME_KEY })
|
||||
expect(await screen.findByTestId('unread-dot')).toBeInTheDocument()
|
||||
|
||||
const listed = await rows(await openSheet())
|
||||
expect(listed).toHaveLength(4)
|
||||
expect(listed[0]).toHaveTextContent('Tacos tonight')
|
||||
await waitFor(() =>
|
||||
expect(posts(fetchMock)).toEqual([
|
||||
JSON.stringify({ through: UPDATES.updates[0]!.created_at }),
|
||||
JSON.stringify({ through: reminder.created_at }),
|
||||
]),
|
||||
)
|
||||
await waitFor(() => expect(homeReads(fetchMock)).toBe(4))
|
||||
expect(screen.queryByTestId('unread-dot')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('on an immediate reopen waits for that opening’s read, and marks the newer event seen, not the list held from before', async () => {
|
||||
const stored = [...UPDATES.updates]
|
||||
let reads = 0
|
||||
let answer: (() => void) | undefined
|
||||
const fetchMock = stubServer({
|
||||
[`GET ${UPDATES_PATH}`]: () => {
|
||||
const body = { updates: [...stored] }
|
||||
reads++
|
||||
// Every reading after the first is held until the test answers it.
|
||||
if (reads === 1) return jsonResponse(200, body)
|
||||
return new Promise<Response>((resolve) => (answer = () => resolve(jsonResponse(200, body))))
|
||||
},
|
||||
})
|
||||
await renderHome()
|
||||
await rows(await openSheet())
|
||||
await waitFor(() => expect(posts(fetchMock)).toHaveLength(1))
|
||||
|
||||
// Closed and opened again at once, before any cache-collection timer
|
||||
// could run, with a new event stored in between.
|
||||
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
|
||||
const reminder = {
|
||||
type: 'day_of_reminder',
|
||||
title: 'Tacos tonight',
|
||||
body: 'Dinner at 6:00.',
|
||||
url: '/plan',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
stored.unshift(reminder)
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Recent updates/ }))
|
||||
const sheet = screen.getByRole('dialog', { name: 'Recent updates' })
|
||||
|
||||
// The list held from the first opening is neither shown nor marked
|
||||
// seen while this opening's read is in flight.
|
||||
await waitFor(() => expect(updatesReads(fetchMock)).toBe(2))
|
||||
expect(within(sheet).getByLabelText('Updates loading')).toBeInTheDocument()
|
||||
expect(within(sheet).queryByRole('list')).not.toBeInTheDocument()
|
||||
expect(posts(fetchMock)).toHaveLength(1)
|
||||
|
||||
answer!()
|
||||
const listed = await rows(sheet)
|
||||
expect(listed).toHaveLength(4)
|
||||
expect(listed[0]).toHaveTextContent('Tacos tonight')
|
||||
await waitFor(() =>
|
||||
expect(posts(fetchMock)).toEqual([
|
||||
JSON.stringify({ through: UPDATES.updates[0]!.created_at }),
|
||||
JSON.stringify({ through: reminder.created_at }),
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('closing the sheet while its first read is in flight cancels that read, and a reopen reads afresh', async () => {
|
||||
const stored = [...UPDATES.updates]
|
||||
let firstAborted = false
|
||||
let answerFirst: (() => void) | undefined
|
||||
let reads = 0
|
||||
const fetchMock = stubServer({
|
||||
[`GET ${UPDATES_PATH}`]: (init) => {
|
||||
const body = { updates: [...stored] }
|
||||
reads++
|
||||
if (reads > 1) return jsonResponse(200, body)
|
||||
// The first reading is held open, and fails as fetch does if it is
|
||||
// aborted.
|
||||
return new Promise<Response>((resolve, reject) => {
|
||||
answerFirst = () => resolve(jsonResponse(200, body))
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
firstAborted = true
|
||||
reject(init.signal!.reason as Error)
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
await renderHome()
|
||||
await openSheet()
|
||||
await waitFor(() => expect(updatesReads(fetchMock)).toBe(1))
|
||||
|
||||
// Closed before the first read answers, a new event stored, and opened
|
||||
// again at once.
|
||||
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
|
||||
const reminder = {
|
||||
type: 'day_of_reminder',
|
||||
title: 'Tacos tonight',
|
||||
body: 'Dinner at 6:00.',
|
||||
url: '/plan',
|
||||
created_at: new Date().toISOString(),
|
||||
}
|
||||
stored.unshift(reminder)
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Recent updates/ }))
|
||||
const sheet = screen.getByRole('dialog', { name: 'Recent updates' })
|
||||
|
||||
// The first read was cancelled, and the reopen sent its own.
|
||||
await waitFor(() => expect(updatesReads(fetchMock)).toBe(2))
|
||||
expect(firstAborted).toBe(true)
|
||||
// Answering the cancelled read changes nothing.
|
||||
answerFirst!()
|
||||
|
||||
const listed = await rows(sheet)
|
||||
expect(listed).toHaveLength(4)
|
||||
expect(listed[0]).toHaveTextContent('Tacos tonight')
|
||||
await waitFor(() => expect(posts(fetchMock)).toEqual([JSON.stringify({ through: reminder.created_at })]))
|
||||
})
|
||||
|
||||
it.each([
|
||||
[0, '/plan'],
|
||||
[1, '/discover'],
|
||||
[2, '/plan/shopping?week=2026-10-05'],
|
||||
])('row %i goes to %s and closes the sheet', async (i, to) => {
|
||||
stubServer()
|
||||
await renderHome()
|
||||
const listed = await rows(await openSheet())
|
||||
|
||||
fireEvent.click(within(listed[i]!).getByRole('button'))
|
||||
expect(await screen.findByTestId('where')).toHaveTextContent(to)
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('says there are no updates yet, and marks nothing seen', async () => {
|
||||
const fetchMock = stubServer({ [`GET ${UPDATES_PATH}`]: () => jsonResponse(200, { updates: [] }) })
|
||||
await renderHome()
|
||||
const sheet = await openSheet()
|
||||
|
||||
expect(await within(sheet).findByText(/No updates yet/)).toBeInTheDocument()
|
||||
expect(within(sheet).queryByRole('list')).not.toBeInTheDocument()
|
||||
expect(posts(fetchMock)).toEqual([])
|
||||
})
|
||||
|
||||
it('puts the dot back and says so when marking the updates seen fails', async () => {
|
||||
let refuse!: (response: Response) => void
|
||||
const fetchMock = stubServer({
|
||||
[`POST ${UPDATES_SEEN_PATH}`]: () => new Promise<Response>((resolve) => (refuse = resolve)),
|
||||
})
|
||||
await renderHome()
|
||||
const sheet = await openSheet()
|
||||
|
||||
await waitFor(() => expect(posts(fetchMock)).toHaveLength(1))
|
||||
// Cleared at once, while the mark is in flight.
|
||||
expect(screen.queryByTestId('unread-dot')).not.toBeInTheDocument()
|
||||
|
||||
refuse(errorResponse(500, 'internal'))
|
||||
expect(await within(sheet).findByRole('alert')).toHaveTextContent(
|
||||
"Couldn't mark your updates as seen. internal message",
|
||||
)
|
||||
expect(screen.getByTestId('unread-dot')).toBeInTheDocument()
|
||||
// The updates are still listed.
|
||||
expect(within(sheet).getByRole('list', { name: 'Recent updates' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports updates it cannot load, with Retry', async () => {
|
||||
let fail = true
|
||||
stubServer({ [`GET ${UPDATES_PATH}`]: () => (fail ? errorResponse(500, 'internal') : jsonResponse(200, UPDATES)) })
|
||||
await renderHome()
|
||||
const sheet = await openSheet()
|
||||
|
||||
expect(await within(sheet).findByRole('alert')).toHaveTextContent("Couldn't load your updates. internal message")
|
||||
fail = false
|
||||
fireEvent.click(within(sheet).getByRole('button', { name: 'Retry' }))
|
||||
expect(await within(sheet).findByRole('list', { name: 'Recent updates' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports an update that would open another site rather than listing it', async () => {
|
||||
const fetchMock = stubServer({
|
||||
[`GET ${UPDATES_PATH}`]: () => jsonResponse(200, { updates: [{ ...UPDATES.updates[0], url: '//evil.example/plan' }] }),
|
||||
})
|
||||
await renderHome()
|
||||
const sheet = await openSheet()
|
||||
|
||||
expect(await within(sheet).findByRole('alert')).toHaveTextContent(
|
||||
'update url "//evil.example/plan" is not a path on this app',
|
||||
)
|
||||
expect(within(sheet).queryByRole('list')).not.toBeInTheDocument()
|
||||
expect(posts(fetchMock)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
import { CalendarDays, ChefHat, Compass, Repeat, ShoppingCart, type LucideIcon } from 'lucide-react'
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { ago } from '../plan/PlanPage.tsx'
|
||||
import { ErrorBanner } from '../ui/ErrorBanner.tsx'
|
||||
import { Icon } from '../ui/Icon.tsx'
|
||||
import { ListRow } from '../ui/ListRow.tsx'
|
||||
import { Sheet } from '../ui/Sheet.tsx'
|
||||
import { Skeleton } from '../ui/Skeleton.tsx'
|
||||
import { useMarkUpdatesSeen, useUpdates, type Update, type UpdateType } from './api.ts'
|
||||
import styles from './UpdatesSheet.module.css'
|
||||
|
||||
const ICONS: Record<UpdateType, LucideIcon> = {
|
||||
plan_ready: CalendarDays,
|
||||
list_ready: ShoppingCart,
|
||||
day_of_reminder: ChefHat,
|
||||
new_suggestions: Compass,
|
||||
rotation_review: Repeat,
|
||||
}
|
||||
|
||||
// UpdateRow is one update: its icon, title and body, and how long ago it
|
||||
// came. A tap opens its url.
|
||||
function UpdateRow({ update, now, onOpen }: { update: Update; now: Date; onOpen: (url: string) => void }) {
|
||||
return (
|
||||
<li>
|
||||
<ListRow
|
||||
leading={<Icon icon={ICONS[update.type]} className={styles.icon} />}
|
||||
title={update.title}
|
||||
meta={update.body === '' ? undefined : update.body}
|
||||
trailing={
|
||||
<time dateTime={update.created_at} className={styles.time}>
|
||||
{ago(new Date(update.created_at), now)}
|
||||
</time>
|
||||
}
|
||||
onClick={() => onOpen(update.url)}
|
||||
/>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
// Updates lists the Recent updates, newest first, and marks them seen
|
||||
// through the newest once they are shown, so the bell's dot clears.
|
||||
function Updates({ onOpen }: { onOpen: (url: string) => void }) {
|
||||
const updates = useUpdates()
|
||||
const markSeen = useMarkUpdatesSeen()
|
||||
const { mutate } = markSeen
|
||||
// fresh says this opening's read has come back; until then a list still
|
||||
// held from an earlier opening is neither shown nor marked seen.
|
||||
const fresh = updates.isSuccess && updates.isFetchedAfterMount
|
||||
const newest = fresh ? updates.data[0]?.created_at : undefined
|
||||
// The instant the relative times count from, fixed while the sheet is
|
||||
// open.
|
||||
const [now] = useState(() => new Date())
|
||||
|
||||
useEffect(() => {
|
||||
if (newest !== undefined) mutate(newest)
|
||||
}, [newest, mutate])
|
||||
|
||||
if (updates.isError) {
|
||||
return (
|
||||
<ErrorBanner onRetry={() => void updates.refetch()}>Couldn't load your updates. {updates.error.message}</ErrorBanner>
|
||||
)
|
||||
}
|
||||
if (!fresh) {
|
||||
return (
|
||||
<div aria-busy="true" aria-label="Updates loading" className={styles.rows}>
|
||||
{Array.from({ length: 3 }, (_, i) => (
|
||||
<Skeleton key={i} className={styles.skeletonRow} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (updates.data.length === 0) {
|
||||
return <p className={styles.empty}>No updates yet. Plans, Supply runs and new Side quests show up here.</p>
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{markSeen.isError && newest !== undefined && (
|
||||
<ErrorBanner onRetry={() => mutate(newest)}>
|
||||
Couldn't mark your updates as seen. {markSeen.error.message}
|
||||
</ErrorBanner>
|
||||
)}
|
||||
<ul aria-label="Recent updates" className={styles.rows}>
|
||||
{updates.data.map((update, i) => (
|
||||
<UpdateRow key={`${i} ${update.created_at}`} update={update} now={now} onOpen={onOpen} />
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export type UpdatesSheetProps = {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// UpdatesSheet is the Recent updates sheet the Home bell opens: the last
|
||||
// ten notification events with how long ago each came, each opening the
|
||||
// screen it is about. Opening it marks them seen.
|
||||
export function UpdatesSheet({ open, onClose }: UpdatesSheetProps) {
|
||||
const titleId = useId()
|
||||
const navigate = useNavigate()
|
||||
const openUpdate = (url: string) => {
|
||||
onClose()
|
||||
void navigate(url)
|
||||
}
|
||||
return (
|
||||
<Sheet open={open} onClose={onClose} aria-labelledby={titleId}>
|
||||
<div className={styles.sheet}>
|
||||
<h2 id={titleId} className={styles.title}>
|
||||
Recent updates
|
||||
</h2>
|
||||
<Updates onOpen={openUpdate} />
|
||||
</div>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseUpdates } from './api.ts'
|
||||
|
||||
const origin = 'https://mealquest.example'
|
||||
const where = 'GET /api/v1/updates'
|
||||
|
||||
// body is a GET /api/v1/updates body holding one update that opens url.
|
||||
function body(url: string) {
|
||||
return {
|
||||
updates: [{ type: 'plan_ready', title: 'Your week is drafted', body: '', url, created_at: '2026-10-10T16:00:00.000Z' }],
|
||||
}
|
||||
}
|
||||
|
||||
describe('parseUpdates', () => {
|
||||
it('keeps a same-origin path with its query and fragment, as parsed', () => {
|
||||
expect(parseUpdates(where, body('/plan/shopping?week=2026-10-05#tuesday'), origin)[0]!.url).toBe(
|
||||
'/plan/shopping?week=2026-10-05#tuesday',
|
||||
)
|
||||
expect(parseUpdates(where, body('/plan/../discover'), origin)[0]!.url).toBe('/discover')
|
||||
})
|
||||
|
||||
// Each of these would open another site, or run script, once parsed: URL
|
||||
// parsing strips tabs and newlines and reads a backslash as a slash.
|
||||
it.each([
|
||||
['a tab', '/\t/evil.example/x'],
|
||||
['a newline', '/\n/evil.example/x'],
|
||||
['a carriage return', '/\r/evil.example/x'],
|
||||
['a backslash', '/\\evil.example/x'],
|
||||
['dot segments', '/..//evil.example/x'],
|
||||
['a protocol-relative URL', '//evil.example/x'],
|
||||
['an absolute URL', 'https://evil.example/x'],
|
||||
['javascript:', 'javascript:alert(1)'],
|
||||
['a relative path', 'plan'],
|
||||
])('refuses an update url with %s', (_, url) => {
|
||||
expect(() => parseUpdates(where, body(url), origin)).toThrow(
|
||||
`${where}: update url ${JSON.stringify(url)} is not a path on this app`,
|
||||
)
|
||||
})
|
||||
})
|
||||
+103
-1
@@ -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 })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user