Feature 21: Home Dashboard (#181)
Co-authored-by: dev_agent <dev_agent@cubecraftlabs.com>
This commit was merged in pull request #181.
This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
/* Home, handoff mock 1g. */
|
||||
.page {
|
||||
box-sizing: border-box;
|
||||
max-width: 560px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.date {
|
||||
margin: 0;
|
||||
font-family: var(--font-body);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 28px;
|
||||
font-weight: 400;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
/* The bell's 8 px grape unread dot sits on the 40 px face, which is
|
||||
centred in the IconButton's 44 px hit box. */
|
||||
.bell {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.bell .bellIcon {
|
||||
width: 19px;
|
||||
height: 19px;
|
||||
}
|
||||
|
||||
.dot {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 11px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--color-accent);
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 32px;
|
||||
background: var(--color-surface);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.photo {
|
||||
height: 150px;
|
||||
}
|
||||
|
||||
.cardFoot {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 2px 18px 16px;
|
||||
}
|
||||
|
||||
.cardText {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.name {
|
||||
margin: 0;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.meta {
|
||||
font-family: var(--font-body);
|
||||
font-size: 12px;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
/* The dark "Recipe" pill: the mock's 38 px pill at the 44 px tap minimum. */
|
||||
.recipe {
|
||||
flex: none;
|
||||
min-height: 44px;
|
||||
padding: 0 16px;
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.tiles {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.tile {
|
||||
box-sizing: border-box;
|
||||
height: 104px;
|
||||
padding: 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
border-radius: 26px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.quick {
|
||||
background: var(--color-accent);
|
||||
color: var(--on-accent);
|
||||
}
|
||||
|
||||
.pantry {
|
||||
background: var(--color-accent-2-300);
|
||||
color: var(--color-accent-2-900);
|
||||
}
|
||||
|
||||
.tileLabel {
|
||||
font-family: var(--font-heading);
|
||||
font-size: 16px;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.statuses {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.status {
|
||||
box-sizing: border-box;
|
||||
min-height: 44px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 20px;
|
||||
background: var(--color-neutral-100);
|
||||
color: var(--color-text);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.status .statusIcon {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
color: var(--color-accent-700);
|
||||
}
|
||||
|
||||
.statusText {
|
||||
flex: 1;
|
||||
font-family: var(--font-body);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.tile:focus-visible,
|
||||
.status:focus-visible {
|
||||
outline: 3px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.skeletonDate {
|
||||
width: 96px;
|
||||
height: 14px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.skeletonCard {
|
||||
height: 238px;
|
||||
border-radius: 32px;
|
||||
}
|
||||
|
||||
.skeletonStatus {
|
||||
height: 44px;
|
||||
border-radius: 20px;
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { createMemoryRouter, RouterProvider, useLocation } from 'react-router'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ApiProviders, HOME } from '../test/ApiProviders.tsx'
|
||||
import { declaredStyle } from '../test/cssRules.ts'
|
||||
import { errorResponse, jsonResponse, stubFetchByPath } from '../test/fetchStub.ts'
|
||||
import { expectMinHitArea } from '../test/hitArea.ts'
|
||||
import { HOME_PATH } from './api.ts'
|
||||
import { HomePage } from './HomePage.tsx'
|
||||
import { ROTATION_REVIEWS_PATH } from './rotation.ts'
|
||||
|
||||
// NOTHING_YET is the home of a household with no plan, no Side quests, no
|
||||
// Supply run and nothing unread.
|
||||
const NOTHING_YET = {
|
||||
...HOME,
|
||||
tonight: null,
|
||||
sideQuestCount: 0,
|
||||
shoppingList: { weekStart: '2026-09-28', label: 'Week 40 · Sep 28 – Oct 4', ready: false, sentToChatAt: null },
|
||||
recentUpdates: { unread: false },
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
// Where shows the route a link went to.
|
||||
function Where() {
|
||||
const location = useLocation()
|
||||
return <p data-testid="where">{location.pathname + location.search}</p>
|
||||
}
|
||||
|
||||
function renderHome(body: unknown) {
|
||||
stubFetchByPath({ [HOME_PATH]: () => jsonResponse(200, body), [ROTATION_REVIEWS_PATH]: () => jsonResponse(200, { reviews: [] }) })
|
||||
return renderRouter()
|
||||
}
|
||||
|
||||
function renderRouter() {
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{ path: '/', element: <HomePage /> },
|
||||
{ path: '*', element: <Where /> },
|
||||
],
|
||||
{ initialEntries: ['/'] },
|
||||
)
|
||||
render(
|
||||
<ApiProviders>
|
||||
<RouterProvider router={router} />
|
||||
</ApiProviders>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('HomePage', () => {
|
||||
it('renders mock 1g from GET /api/v1/home', async () => {
|
||||
renderHome(HOME)
|
||||
|
||||
expect(await screen.findByText('Friday, Oct 2')).toBeInTheDocument()
|
||||
expect(screen.getByRole('heading', { level: 1, name: "Tonight's quest" })).toBeInTheDocument()
|
||||
|
||||
const tonight = screen.getByRole('region', { name: 'Tonight' })
|
||||
expect(within(tonight).getByRole('heading', { name: 'Pizza night' })).toBeInTheDocument()
|
||||
expect(within(tonight).getByText('Regular · 40 min')).toBeInTheDocument()
|
||||
expect(within(tonight).getByRole('img', { name: 'Pizza night' })).toHaveAttribute('src', '/media/photos/p1-400.jpg')
|
||||
expect(within(tonight).getByRole('link', { name: 'Recipe' })).toHaveAttribute('href', '/dinner/d1')
|
||||
|
||||
expect(screen.getByRole('link', { name: 'Quick dinner' })).toHaveAttribute('href', '/quick')
|
||||
expect(screen.getByRole('link', { name: 'Cook from what I have' })).toHaveAttribute('href', '/cook-from-pantry')
|
||||
expect(screen.getByRole('link', { name: '10 new side quests to swipe' })).toHaveAttribute('href', '/discover')
|
||||
expect(screen.getByRole('link', { name: 'Shopping list ready · Oct 5–11' })).toHaveAttribute(
|
||||
'href',
|
||||
'/plan/shopping?week=2026-10-05',
|
||||
)
|
||||
expect(screen.queryByRole('heading', { name: 'No quest planned tonight' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("reads Home again at the household's next local midnight, so a Home left open moves to the new day", async () => {
|
||||
// setTimeout moves with real time, and the test jumps to midnight.
|
||||
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'], shouldAdvanceTime: true })
|
||||
// 23:58 on Friday Oct 2 in New York, the household's zone.
|
||||
vi.setSystemTime(new Date('2026-10-03T03:58:00Z'))
|
||||
const days = [HOME, { ...HOME, dateLabel: 'Saturday, Oct 3', tonight: null }]
|
||||
let reads = 0
|
||||
stubFetchByPath({
|
||||
[HOME_PATH]: () => jsonResponse(200, days[Math.min(reads++, 1)]),
|
||||
[ROTATION_REVIEWS_PATH]: () => jsonResponse(200, { reviews: [] }),
|
||||
})
|
||||
renderRouter()
|
||||
expect(await screen.findByText('Friday, Oct 2')).toBeInTheDocument()
|
||||
expect(reads).toBe(1)
|
||||
|
||||
// A minute before midnight Home is not read again.
|
||||
await act(() => vi.advanceTimersByTimeAsync(60_000))
|
||||
expect(reads).toBe(1)
|
||||
// At midnight it is, and shows the new day.
|
||||
await act(() => vi.advanceTimersByTimeAsync(60_000))
|
||||
expect(await screen.findByText('Saturday, Oct 3')).toBeInTheDocument()
|
||||
expect(reads).toBe(2)
|
||||
expect(screen.getByRole('heading', { name: 'No quest planned tonight' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the grape unread dot on the bell when there are unread updates', async () => {
|
||||
renderHome(HOME)
|
||||
|
||||
const bell = await screen.findByRole('button', { name: 'Recent updates, unread' })
|
||||
const dot = within(bell).getByTestId('unread-dot')
|
||||
expect(declaredStyle(dot).background).toBe('var(--color-accent)')
|
||||
expect(declaredStyle(dot).width).toBe('8px')
|
||||
expectMinHitArea(bell)
|
||||
})
|
||||
|
||||
it('shows the bell without a dot when every update is seen', async () => {
|
||||
renderHome(NOTHING_YET)
|
||||
|
||||
const bell = await screen.findByRole('button', { name: 'Recent updates' })
|
||||
expect(within(bell).queryByTestId('unread-dot')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels a Side quest tonight "Side quest"', async () => {
|
||||
renderHome({ ...HOME, tonight: { ...HOME.tonight, origin: 'side_quest', minutes_total: 30 } })
|
||||
expect(await screen.findByText('Side quest · 30 min')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows only the origin when tonight has no minutes', async () => {
|
||||
renderHome({ ...HOME, tonight: { ...HOME.tonight, minutes_total: null, photo: null } })
|
||||
const tonight = await screen.findByRole('region', { name: 'Tonight' })
|
||||
expect(within(tonight).getByText('Regular')).toBeInTheDocument()
|
||||
// No photo: the striped placeholder, named for the dinner.
|
||||
expect(within(tonight).getByRole('img', { name: 'Pizza night' })).toHaveTextContent('dish photo')
|
||||
})
|
||||
|
||||
it('offers to plan the week when tonight has no plan, and hides the rows that do not apply', async () => {
|
||||
renderHome(NOTHING_YET)
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'No quest planned tonight' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('region', { name: 'Tonight' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: /side quests? to swipe/ })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: /Shopping list ready/ })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('list', { name: 'Status' })).not.toBeInTheDocument()
|
||||
// The tiles stay.
|
||||
expect(screen.getByRole('link', { name: 'Quick dinner' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Plan this week' }))
|
||||
expect(await screen.findByTestId('where')).toHaveTextContent('/plan')
|
||||
})
|
||||
|
||||
it('hides the Side quests row at zero and keeps a ready Supply run', async () => {
|
||||
renderHome({ ...HOME, sideQuestCount: 0 })
|
||||
|
||||
expect(await screen.findByRole('link', { name: 'Shopping list ready · Oct 5–11' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: /side quests? to swipe/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the Supply run row when no list is ready', async () => {
|
||||
renderHome({ ...HOME, shoppingList: NOTHING_YET.shoppingList })
|
||||
|
||||
expect(await screen.findByRole('link', { name: '10 new side quests to swipe' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: /Shopping list ready/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('counts a single Side quest in the singular', async () => {
|
||||
renderHome({ ...HOME, sideQuestCount: 1 })
|
||||
expect(await screen.findByRole('link', { name: '1 new side quest to swipe' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a week spanning two months in full', async () => {
|
||||
renderHome({ ...HOME, shoppingList: { ...HOME.shoppingList, weekStart: '2026-09-28', label: 'Week 40 · Sep 28 – Oct 4' } })
|
||||
expect(await screen.findByRole('link', { name: 'Shopping list ready · Sep 28–Oct 4' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['Recipe', '/dinner/d1'],
|
||||
['Quick dinner', '/quick'],
|
||||
['Cook from what I have', '/cook-from-pantry'],
|
||||
['10 new side quests to swipe', '/discover'],
|
||||
['Shopping list ready · Oct 5–11', '/plan/shopping?week=2026-10-05'],
|
||||
])('%s goes to %s', async (name, to) => {
|
||||
renderHome(HOME)
|
||||
|
||||
fireEvent.click(await screen.findByRole('link', { name }))
|
||||
expect(await screen.findByTestId('where')).toHaveTextContent(to)
|
||||
})
|
||||
|
||||
it('styles the card, tiles and rows as mock 1g with tap targets of at least 44 px', async () => {
|
||||
renderHome(HOME)
|
||||
|
||||
const tonight = await screen.findByRole('region', { name: 'Tonight' })
|
||||
expect(declaredStyle(tonight).borderRadius).toBe('32px')
|
||||
expect(declaredStyle(within(tonight).getByRole('img')).height).toBe('150px')
|
||||
expect(declaredStyle(within(tonight).getByRole('heading')).fontSize).toBe('22px')
|
||||
|
||||
const quick = screen.getByRole('link', { name: 'Quick dinner' })
|
||||
expect(declaredStyle(quick).height).toBe('104px')
|
||||
expect(declaredStyle(quick).background).toBe('var(--color-accent)')
|
||||
expect(declaredStyle(quick).color).toBe('var(--on-accent)')
|
||||
const pantry = screen.getByRole('link', { name: 'Cook from what I have' })
|
||||
expect(declaredStyle(pantry).height).toBe('104px')
|
||||
expect(declaredStyle(pantry).background).toBe('var(--color-accent-2-300)')
|
||||
|
||||
expect(declaredStyle(screen.getByText('Friday, Oct 2')).fontSize).toBe('12px')
|
||||
|
||||
expectMinHitArea(within(tonight).getByRole('link', { name: 'Recipe' }))
|
||||
// The tiles are 104 px tall (above); the status rows fill the width at 44 px or more.
|
||||
for (const row of within(screen.getByRole('list', { name: 'Status' })).getAllByRole('link')) {
|
||||
expect(declaredStyle(row).minHeight).toBe('44px')
|
||||
}
|
||||
})
|
||||
|
||||
it('shows skeletons while the home loads', async () => {
|
||||
let answer!: (response: Response) => void
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn<typeof fetch>(() => new Promise((resolve) => (answer = resolve))),
|
||||
)
|
||||
renderRouter()
|
||||
|
||||
expect(screen.getByTestId('skeleton-tonight')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('skeleton-date')).toBeInTheDocument()
|
||||
expect(screen.getAllByTestId('skeleton-status')).toHaveLength(2)
|
||||
expect(screen.getByRole('heading', { level: 1, name: "Tonight's quest" })).toBeInTheDocument()
|
||||
|
||||
answer(jsonResponse(200, HOME))
|
||||
expect(await screen.findByText('Friday, Oct 2')).toBeInTheDocument()
|
||||
expect(screen.queryByTestId('skeleton-tonight')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('skeleton-status')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a failure with Retry, and no made-up content', async () => {
|
||||
const homes = [errorResponse(500, 'internal'), jsonResponse(200, HOME)]
|
||||
stubFetchByPath({
|
||||
[HOME_PATH]: () => homes.shift()!,
|
||||
[ROTATION_REVIEWS_PATH]: () => jsonResponse(200, { reviews: [] }),
|
||||
})
|
||||
renderRouter()
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent("Couldn't load tonight's quest. internal message")
|
||||
expect(screen.queryByRole('region', { name: 'Tonight' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: 'No quest planned tonight' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('list', { name: 'Status' })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(await screen.findByRole('heading', { name: 'Pizza night' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a home it cannot read rather than guessing', async () => {
|
||||
renderHome({ ...HOME, tonight: { ...HOME.tonight, origin: 'leftovers' } })
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('origin "leftovers" is not one of regular, side_quest')
|
||||
})
|
||||
|
||||
it.each([0, -1, 2.5])('reports tonight with minutes_total %s rather than showing it', async (minutes) => {
|
||||
renderHome({ ...HOME, tonight: { ...HOME.tonight, minutes_total: minutes } })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
`tonight's minutes_total ${minutes} is not a positive whole number`,
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('region', { name: 'Tonight' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/min$/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports tonight without a minutes_total rather than showing it as unknown', async () => {
|
||||
const { minutes_total: _, ...tonight } = HOME.tonight
|
||||
renderHome({ ...HOME, tonight })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('tonight has no minutes_total')
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('region', { name: 'Tonight' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Regular')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a missing', undefined],
|
||||
['an empty', ''],
|
||||
])('reports a ready Supply run with %s label rather than showing it', async (_, label) => {
|
||||
renderHome({ ...HOME, shoppingList: { ...HOME.shoppingList, label } })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('the ready shoppingList has no label')
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('link', { name: /Shopping list ready/ })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('list', { name: 'Status' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a ready Supply run whose label is not its week rather than showing it', async () => {
|
||||
renderHome({ ...HOME, shoppingList: { ...HOME.shoppingList, label: 'Week 40 · Sep 28 – Oct 4' } })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'shoppingList label "Week 40 · Sep 28 – Oct 4" is not the week of 2026-10-05',
|
||||
)
|
||||
expect(screen.queryByRole('link', { name: /Shopping list ready/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a missing', undefined],
|
||||
['an empty', ''],
|
||||
])('reports an unready Supply run with %s label rather than showing the home', async (_, label) => {
|
||||
renderHome({ ...HOME, shoppingList: { ...NOTHING_YET.shoppingList, label } })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('the unready shoppingList has no label')
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('list', { name: 'Status' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports an unready Supply run whose label is not its week rather than showing the home', async () => {
|
||||
renderHome({ ...HOME, shoppingList: { ...NOTHING_YET.shoppingList, label: 'Week 41 · Oct 5 – 11' } })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'shoppingList label "Week 41 · Oct 5 – 11" is not the week of 2026-09-28',
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('list', { name: 'Status' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a Supply run whose weekStart is not a date rather than showing it', async () => {
|
||||
renderHome({ ...HOME, shoppingList: { ...HOME.shoppingList, weekStart: 'Oct 5' } })
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('not a YYYY-MM-DD date')
|
||||
expect(screen.queryByRole('list', { name: 'Status' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
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'
|
||||
import buttonStyles from '../ui/Button.module.css'
|
||||
import { EmptyState } from '../ui/EmptyState.tsx'
|
||||
import { ErrorBanner } from '../ui/ErrorBanner.tsx'
|
||||
import { Icon } from '../ui/Icon.tsx'
|
||||
import { IconButton } from '../ui/IconButton.tsx'
|
||||
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 { RotationCheck } from './RotationCheck.tsx'
|
||||
import { UpdatesSheet } from './UpdatesSheet.tsx'
|
||||
|
||||
const ORIGIN_LABEL: Record<Origin, string> = { regular: 'Regular', side_quest: 'Side quest' }
|
||||
|
||||
// meta is the Tonight card's "Regular · 40 min" line, the time only when
|
||||
// the recipe says it.
|
||||
function meta({ origin, minutes_total }: Tonight): string {
|
||||
return minutes_total === null ? ORIGIN_LABEL[origin] : `${ORIGIN_LABEL[origin]} · ${duration(minutes_total)}`
|
||||
}
|
||||
|
||||
// TonightCard is the dinner planned for today: its washed photo, name and
|
||||
// meta line, and the dark Recipe pill to its recipe.
|
||||
function TonightCard({ tonight }: { tonight: Tonight }) {
|
||||
return (
|
||||
<section aria-label="Tonight" className={styles.card}>
|
||||
<Photo id={tonight.photo_id} name={tonight.name} inset="10px" sizes="400px" className={styles.photo} />
|
||||
<div className={styles.cardFoot}>
|
||||
<div className={styles.cardText}>
|
||||
<h2 className={styles.name}>{tonight.name}</h2>
|
||||
<span className={styles.meta}>{meta(tonight)}</span>
|
||||
</div>
|
||||
<Link to={`/dinner/${encodeURIComponent(tonight.id)}`} className={[buttonStyles.button, buttonStyles.dark, styles.recipe].join(' ')}>
|
||||
Recipe
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// NoPlan stands in for the Tonight card when today has no plan.
|
||||
function NoPlan() {
|
||||
const navigate = useNavigate()
|
||||
return (
|
||||
<div className={styles.card}>
|
||||
<EmptyState title="No quest planned tonight" action={{ label: 'Plan this week', onClick: () => void navigate('/plan') }}>
|
||||
Draft this week's dinners and tonight's quest shows up here.
|
||||
</EmptyState>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// StatusRow is one neutral row under the tiles: a grape-700 icon, its line
|
||||
// and a chevron, linking to the screen it is about.
|
||||
function StatusRow({ to, icon, children }: { to: string; icon: LucideIcon; children: string }) {
|
||||
return (
|
||||
<li>
|
||||
<Link to={to} className={styles.status}>
|
||||
<Icon icon={icon} className={styles.statusIcon} />
|
||||
<span className={styles.statusText}>{children}</span>
|
||||
<Icon icon={ChevronRight} />
|
||||
</Link>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
// StatusRows are the rows that apply: Side quests waiting in the deck, and
|
||||
// a Supply run ready. With neither, there are no rows.
|
||||
function StatusRows({ home }: { home: Home }) {
|
||||
const count = home.sideQuestCount
|
||||
const list = home.shoppingList
|
||||
if (count === 0 && !list.ready) return null
|
||||
return (
|
||||
<ul aria-label="Status" className={styles.statuses}>
|
||||
{count > 0 && (
|
||||
<StatusRow to="/discover" icon={Compass}>
|
||||
{`${count} new side ${count === 1 ? 'quest' : 'quests'} to swipe`}
|
||||
</StatusRow>
|
||||
)}
|
||||
{list.ready && (
|
||||
<StatusRow to={supplyRunScreen(list.weekStart)} icon={ShoppingCart}>
|
||||
{`Shopping list ready · ${list.dates}`}
|
||||
</StatusRow>
|
||||
)}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
// Tiles are the two shortcuts, Quick dinner and Cook from what I have.
|
||||
function Tiles() {
|
||||
return (
|
||||
<div className={styles.tiles}>
|
||||
<Link to="/quick" className={[styles.tile, styles.quick].join(' ')}>
|
||||
<Icon icon={Zap} size="nav" />
|
||||
<span className={styles.tileLabel}>Quick dinner</span>
|
||||
</Link>
|
||||
<Link to="/cook-from-pantry" className={[styles.tile, styles.pantry].join(' ')}>
|
||||
<Icon icon={Search} size="nav" />
|
||||
<span className={styles.tileLabel}>Cook from what I have</span>
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// HomePage is mock 1g, Home: today's date over "Tonight's quest" and the
|
||||
// Recent updates bell, the Tonight card (or the way to plan the week), the
|
||||
// Quick dinner and Cook from what I have tiles, and the status rows, all
|
||||
// from GET /api/v1/home. Above the tiles is the Rotation check, "Keep it in
|
||||
// rotation?", while a tried dinner waits for the household's answer.
|
||||
//
|
||||
// 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}>
|
||||
<div>
|
||||
{data !== undefined ? (
|
||||
<p className={styles.date}>{data.dateLabel}</p>
|
||||
) : (
|
||||
home.isPending && <Skeleton data-testid="skeleton-date" className={styles.skeletonDate} />
|
||||
)}
|
||||
<h1 className={styles.title}>Tonight's quest</h1>
|
||||
</div>
|
||||
<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>
|
||||
</header>
|
||||
{home.isPending && <Skeleton data-testid="skeleton-tonight" className={styles.skeletonCard} />}
|
||||
{home.isError && (
|
||||
<ErrorBanner onRetry={() => void home.refetch()}>Couldn't load tonight's quest. {home.error.message}</ErrorBanner>
|
||||
)}
|
||||
{data !== undefined && (data.tonight === null ? <NoPlan /> : <TonightCard tonight={data.tonight} />)}
|
||||
<RotationCheck />
|
||||
<Tiles />
|
||||
{home.isPending && (
|
||||
<div className={styles.statuses} aria-hidden="true">
|
||||
<Skeleton data-testid="skeleton-status" className={styles.skeletonStatus} />
|
||||
<Skeleton data-testid="skeleton-status" className={styles.skeletonStatus} />
|
||||
</div>
|
||||
)}
|
||||
{data !== undefined && <StatusRows home={data} />}
|
||||
<UpdatesSheet open={updatesOpen} onClose={() => setUpdatesOpen(false)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/* The Rotation check on Home: "Keep it in rotation?" above the tiles. */
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 32px;
|
||||
background: var(--color-surface);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.photo {
|
||||
height: 120px;
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 4px 18px 12px;
|
||||
}
|
||||
|
||||
.kicker {
|
||||
margin: 0;
|
||||
font-family: var(--font-body);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
.question {
|
||||
margin: 0;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* "We didn't make it": a text link at the 44 px tap minimum. */
|
||||
.notMade {
|
||||
align-self: center;
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
padding: 0 4px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-accent-700);
|
||||
font-family: var(--font-body);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.notMade:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.notMade:focus-visible {
|
||||
outline: 3px solid var(--color-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.confirmation {
|
||||
margin: 0;
|
||||
padding: 12px 14px;
|
||||
border-radius: 20px;
|
||||
background: var(--color-accent-2-300);
|
||||
color: var(--color-accent-2-900);
|
||||
font-family: var(--font-body);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { createMemoryRouter, RouterProvider } from 'react-router'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { clickPath, openNotification, parsePushPayload, type ClickWindow } from '../push/notification.ts'
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { ApiProvider, createApiClient, createQueryClient, createVerifiedSession, ME_PATH } 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 { expectMinHitArea } from '../test/hitArea.ts'
|
||||
import { HOME_PATH } from './api.ts'
|
||||
import { HomePage } from './HomePage.tsx'
|
||||
import { rotationReviewPath, ROTATION_REVIEWS_PATH } from './rotation.ts'
|
||||
|
||||
// SHAKSHUKA and RAMEN are pending Rotation checks, oldest first, as GET
|
||||
// /api/v1/rotation-reviews sends them.
|
||||
const SHAKSHUKA = { dinner: { id: 'd7', name: 'Shakshuka', photo: '/media/photos/p7-400.jpg' }, plan_date: '2026-10-01' }
|
||||
const RAMEN = { dinner: { id: 'd8', name: 'Miso ramen', photo: null }, plan_date: '2026-10-02' }
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
Reflect.deleteProperty(navigator, 'serviceWorker')
|
||||
})
|
||||
|
||||
type Deferred = { resolve: (response: Response) => void; path: string; body: unknown }
|
||||
|
||||
// stubApi answers Home's reads like the server: the pending Rotation checks
|
||||
// are reviews, and each POST /api/v1/dinners/{id}/rotation-review waits in
|
||||
// decisions until the test answers it; a 200 answer takes the check off the
|
||||
// server's list, as the server does.
|
||||
function stubApi(reviews: (typeof SHAKSHUKA | typeof RAMEN)[]) {
|
||||
const server = [...reviews]
|
||||
const decisions: Deferred[] = []
|
||||
const fetchMock = vi.fn<typeof fetch>((input, init) => {
|
||||
const path = String(input)
|
||||
if (path === ME_PATH) return Promise.resolve(jsonResponse(200, ME))
|
||||
if (path === HOME_PATH) return Promise.resolve(jsonResponse(200, HOME))
|
||||
if (path === ROTATION_REVIEWS_PATH) return Promise.resolve(jsonResponse(200, { reviews: server }))
|
||||
const review = server.find((r) => rotationReviewPath(r.dinner.id) === path)
|
||||
if (init?.method === 'POST' && review !== undefined) {
|
||||
expect(new Headers(init.headers).get('X-MealQuest-CSRF')).toBe(ME.csrfToken)
|
||||
const body: unknown = JSON.parse(String(init.body))
|
||||
return new Promise<Response>((resolve) =>
|
||||
decisions.push({
|
||||
path,
|
||||
body,
|
||||
resolve: (response) => {
|
||||
if (response.ok) server.splice(server.indexOf(review), 1)
|
||||
resolve(response)
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
throw new Error(`unexpected fetch: ${init?.method ?? 'GET'} ${path}`)
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
return { fetchMock, decisions, server }
|
||||
}
|
||||
|
||||
// decided is the server's answer to a decision on review.
|
||||
function decided(review: typeof SHAKSHUKA | typeof RAMEN, decision: string, dinnerStatus: string) {
|
||||
return jsonResponse(200, {
|
||||
dinner: review.dinner,
|
||||
plan_date: review.plan_date,
|
||||
decision,
|
||||
dinner_status: dinnerStatus,
|
||||
decided_at: '2026-10-02T13:00:00Z',
|
||||
updated_by: 'sub-1',
|
||||
})
|
||||
}
|
||||
|
||||
// renderHome loads /me (for the CSRF token an answer needs) and renders Home
|
||||
// at path.
|
||||
async function renderHome(path = '/') {
|
||||
const api = createApiClient(fakeLocation(path), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
const router = createMemoryRouter([{ path: '/', element: <HomePage /> }], { initialEntries: [path] })
|
||||
render(
|
||||
<ApiProvider client={api}>
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</ApiProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const card = () => screen.findByRole('region', { name: 'Keep it in rotation?' })
|
||||
const posts = (fetchMock: ReturnType<typeof stubApi>['fetchMock']) =>
|
||||
fetchMock.mock.calls.filter(([, init]) => init?.method === 'POST')
|
||||
|
||||
describe('RotationCheck', () => {
|
||||
it('shows no card when nothing waits for an answer', async () => {
|
||||
const { fetchMock } = stubApi([])
|
||||
await renderHome()
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'Pizza night' })).toBeInTheDocument()
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalledWith(ROTATION_REVIEWS_PATH, expect.anything()))
|
||||
expect(screen.queryByRole('region', { name: 'Keep it in rotation?' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: 'Quick dinner' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('asks about the oldest pending check above the tiles, and decides nothing by itself', async () => {
|
||||
const { fetchMock } = stubApi([SHAKSHUKA, RAMEN])
|
||||
await renderHome()
|
||||
|
||||
const check = await card()
|
||||
expect(within(check).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
expect(within(check).getByRole('heading', { level: 2, name: 'Keep it in rotation?' })).toBeInTheDocument()
|
||||
expect(within(check).getByRole('img', { name: 'Shakshuka' })).toHaveAttribute('src', '/media/photos/p7-400.jpg')
|
||||
expect(screen.queryByText('Last night: Miso ramen')).not.toBeInTheDocument()
|
||||
|
||||
const keep = within(check).getByRole('button', { name: 'Keep it' })
|
||||
const drop = within(check).getByRole('button', { name: 'Not for us' })
|
||||
const notMade = within(check).getByRole('button', { name: "We didn't make it" })
|
||||
expect(keep.className).toMatch(/primary/)
|
||||
expect(drop.className).toMatch(/outline/)
|
||||
expect(notMade.className).toMatch(/notMade/)
|
||||
for (const button of [keep, drop, notMade]) expectMinHitArea(button)
|
||||
|
||||
const tiles = screen.getByRole('link', { name: 'Quick dinner' })
|
||||
expect(check.compareDocumentPosition(tiles) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
expect(screen.getByRole('region', { name: 'Tonight' }).compareDocumentPosition(check) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
|
||||
// The card waits for the household: nothing is sent unasked.
|
||||
await act(() => new Promise((resolve) => setTimeout(resolve, 50)))
|
||||
expect(posts(fetchMock)).toHaveLength(0)
|
||||
expect(await card()).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['Keep it', 'keep', 'regular', 'Added to your Regulars'],
|
||||
['Not for us', 'drop', 'archived', "Got it — we won't suggest it again"],
|
||||
["We didn't make it", 'not_made', 'quest_log', 'Back in your Quest log'],
|
||||
])('"%s" sends %s at once and confirms "%s"', async (label, decision, status, confirmation) => {
|
||||
const { fetchMock, decisions } = stubApi([SHAKSHUKA])
|
||||
await renderHome()
|
||||
|
||||
fireEvent.click(within(await card()).getByRole('button', { name: label }))
|
||||
|
||||
// Applied before the server answers.
|
||||
expect(await screen.findByRole('status')).toHaveTextContent(confirmation)
|
||||
expect(screen.queryByRole('region', { name: 'Keep it in rotation?' })).not.toBeInTheDocument()
|
||||
await waitFor(() => expect(decisions).toHaveLength(1))
|
||||
expect(decisions[0]).toMatchObject({ path: '/api/v1/dinners/d7/rotation-review', body: { decision } })
|
||||
expect(posts(fetchMock)).toHaveLength(1)
|
||||
|
||||
act(() => decisions[0]!.resolve(decided(SHAKSHUKA, decision, status)))
|
||||
// Rotation checks are read again once saved; none is left.
|
||||
await waitFor(() =>
|
||||
expect(fetchMock.mock.calls.filter(([path]) => path === ROTATION_REVIEWS_PATH).length).toBeGreaterThanOrEqual(2),
|
||||
)
|
||||
expect(screen.getByRole('status')).toHaveTextContent(confirmation)
|
||||
expect(screen.queryByRole('region', { name: 'Keep it in rotation?' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reveals the next pending check at once, its answers locked until the first is saved', async () => {
|
||||
const { decisions } = stubApi([SHAKSHUKA, RAMEN])
|
||||
await renderHome()
|
||||
|
||||
fireEvent.click(within(await card()).getByRole('button', { name: 'Keep it' }))
|
||||
|
||||
expect(await screen.findByText('Last night: Miso ramen')).toBeInTheDocument()
|
||||
const next = await card()
|
||||
expect(within(next).getByRole('img', { name: 'Miso ramen' })).toHaveTextContent('dish photo')
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Added to your Regulars')
|
||||
for (const button of within(next).getAllByRole('button')) expect(button).toBeDisabled()
|
||||
|
||||
await waitFor(() => expect(decisions).toHaveLength(1))
|
||||
act(() => decisions[0]!.resolve(decided(SHAKSHUKA, 'keep', 'regular')))
|
||||
await waitFor(() => expect(within(next).getByRole('button', { name: 'Not for us' })).toBeEnabled())
|
||||
|
||||
fireEvent.click(within(next).getByRole('button', { name: 'Not for us' }))
|
||||
expect(await screen.findByRole('status')).toHaveTextContent("Got it — we won't suggest it again")
|
||||
await waitFor(() => expect(decisions).toHaveLength(2))
|
||||
expect(decisions[1]).toMatchObject({ path: '/api/v1/dinners/d8/rotation-review', body: { decision: 'drop' } })
|
||||
act(() => decisions[1]!.resolve(decided(RAMEN, 'drop', 'archived')))
|
||||
await waitFor(() => expect(screen.queryByRole('region', { name: 'Keep it in rotation?' })).not.toBeInTheDocument())
|
||||
expect(screen.queryByText(/Last night:/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('puts the check back with an ErrorBanner when the answer fails', async () => {
|
||||
const { decisions } = stubApi([SHAKSHUKA, RAMEN])
|
||||
await renderHome()
|
||||
|
||||
fireEvent.click(within(await card()).getByRole('button', { name: 'Keep it' }))
|
||||
expect(await screen.findByText('Last night: Miso ramen')).toBeInTheDocument()
|
||||
await waitFor(() => expect(decisions).toHaveLength(1))
|
||||
|
||||
act(() => decisions[0]!.resolve(errorResponse(500, 'internal')))
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent("Couldn't save that answer. internal message")
|
||||
const check = await card()
|
||||
expect(within(check).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
expect(within(check).getByRole('button', { name: 'Keep it' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('reports an answer that is not that check decided that way, and shows what the server has', async () => {
|
||||
const { decisions } = stubApi([SHAKSHUKA])
|
||||
await renderHome()
|
||||
|
||||
fireEvent.click(within(await card()).getByRole('button', { name: 'Keep it' }))
|
||||
await waitFor(() => expect(decisions).toHaveLength(1))
|
||||
act(() => decisions[0]!.resolve(decided(SHAKSHUKA, 'drop', 'archived')))
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('response is not the Rotation check decided keep')
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
// The server closed the check, so the list read again has none.
|
||||
await waitFor(() => expect(screen.queryByRole('region', { name: 'Keep it in rotation?' })).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('reports Rotation checks it cannot load, with Retry', async () => {
|
||||
const answers = [errorResponse(500, 'internal'), jsonResponse(200, { reviews: [SHAKSHUKA] })]
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn<typeof fetch>((input) =>
|
||||
Promise.resolve(
|
||||
String(input) === ME_PATH
|
||||
? jsonResponse(200, ME)
|
||||
: String(input) === HOME_PATH
|
||||
? jsonResponse(200, HOME)
|
||||
: answers.shift()!,
|
||||
),
|
||||
),
|
||||
)
|
||||
await renderHome()
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent("Couldn't load the Rotation check. internal message")
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
expect(within(await card()).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps a card already shown, with an ErrorBanner beside it, when reading the checks again fails', async () => {
|
||||
// navigator.serviceWorker is where the worker's postMessage to this
|
||||
// window arrives; a notification tap there reads the checks again.
|
||||
const container = new EventTarget()
|
||||
Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: container })
|
||||
const answers = [jsonResponse(200, { reviews: [SHAKSHUKA] }), errorResponse(500, 'internal')]
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn<typeof fetch>((input) =>
|
||||
Promise.resolve(
|
||||
String(input) === ME_PATH
|
||||
? jsonResponse(200, ME)
|
||||
: String(input) === HOME_PATH
|
||||
? jsonResponse(200, HOME)
|
||||
: answers.shift()!,
|
||||
),
|
||||
),
|
||||
)
|
||||
await renderHome()
|
||||
expect(within(await card()).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
|
||||
const origin = 'https://mealquest.test'
|
||||
const win = {
|
||||
url: `${origin}/`,
|
||||
focused: true,
|
||||
focus: vi.fn(async () => {}),
|
||||
navigate: vi.fn(async () => {}),
|
||||
postMessage: (message) => container.dispatchEvent(new MessageEvent('message', { data: message })),
|
||||
} satisfies ClickWindow
|
||||
await act(() =>
|
||||
openNotification({ url: '/' }, { matchAll: async () => [win], openWindow: vi.fn(async () => null) }, origin),
|
||||
)
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent("Couldn't load the Rotation check. internal message")
|
||||
const shown = screen.getByRole('region', { name: 'Keep it in rotation?' })
|
||||
expect(within(shown).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
expect(within(shown).getByRole('button', { name: 'Keep it' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('opens Home with the card from a rotation_review push notification', async () => {
|
||||
stubApi([SHAKSHUKA])
|
||||
const origin = 'https://mealquest.test'
|
||||
const { notice } = parsePushPayload(
|
||||
JSON.stringify({ event: 'rotation_review', title: 'Keep it in rotation?', body: 'How was Shakshuka?', url: '/' }),
|
||||
origin,
|
||||
)
|
||||
const path = clickPath({ url: notice.url }, origin)
|
||||
expect(path).toBe('/')
|
||||
|
||||
await renderHome(path)
|
||||
expect(within(await card()).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the card when a rotation_review notification focuses Home already open, without a remount', async () => {
|
||||
// navigator.serviceWorker is where the worker's postMessage to this
|
||||
// window arrives.
|
||||
const container = new EventTarget()
|
||||
Object.defineProperty(navigator, 'serviceWorker', { configurable: true, value: container })
|
||||
const { fetchMock, server } = stubApi([])
|
||||
const reads = () => fetchMock.mock.calls.filter(([path]) => path === ROTATION_REVIEWS_PATH).length
|
||||
await renderHome('/')
|
||||
const home = await screen.findByRole('heading', { name: 'Pizza night' })
|
||||
await waitFor(() => expect(reads()).toBe(1))
|
||||
expect(screen.queryByRole('region', { name: 'Keep it in rotation?' })).not.toBeInTheDocument()
|
||||
|
||||
// Within the cached list's staleTime the Rotation check comes due and
|
||||
// its notification is tapped while Home is open at /.
|
||||
server.push(SHAKSHUKA)
|
||||
const origin = 'https://mealquest.test'
|
||||
const win = {
|
||||
url: `${origin}/`,
|
||||
focused: true,
|
||||
focus: vi.fn(async () => {}),
|
||||
navigate: vi.fn(async () => {}),
|
||||
postMessage: (message) => container.dispatchEvent(new MessageEvent('message', { data: message })),
|
||||
} satisfies ClickWindow
|
||||
await act(() =>
|
||||
openNotification({ url: '/' }, { matchAll: async () => [win], openWindow: vi.fn(async () => null) }, origin),
|
||||
)
|
||||
|
||||
expect(win.navigate).not.toHaveBeenCalled()
|
||||
expect(within(await card()).getByText('Last night: Shakshuka')).toBeInTheDocument()
|
||||
expect(reads()).toBe(2)
|
||||
expect(screen.getByRole('heading', { name: 'Pizza night' })).toBe(home)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Button } from '../ui/Button.tsx'
|
||||
import { ErrorBanner } from '../ui/ErrorBanner.tsx'
|
||||
import { Photo } from '../ui/Photo.tsx'
|
||||
import { useDecideRotationReview, useRotationReviews, type Decision, type RotationReview } from './rotation.ts'
|
||||
import styles from './RotationCheck.module.css'
|
||||
|
||||
// CONFIRMATION is what Home says once the household has answered.
|
||||
const CONFIRMATION: Record<Decision, string> = {
|
||||
keep: 'Added to your Regulars',
|
||||
drop: "Got it — we won't suggest it again",
|
||||
not_made: 'Back in your Quest log',
|
||||
}
|
||||
|
||||
type RotationCardProps = { review: RotationReview; disabled: boolean; onDecide: (decision: Decision) => void }
|
||||
|
||||
// RotationCard asks "Keep it in rotation?" about a tried dinner: its washed
|
||||
// photo, "Last night: {dinner}", and the three answers.
|
||||
function RotationCard({ review, disabled, onDecide }: RotationCardProps) {
|
||||
const { dinner } = review
|
||||
return (
|
||||
<section aria-label="Keep it in rotation?" className={styles.card}>
|
||||
<Photo id={dinner.photo_id} name={dinner.name} inset="10px" sizes="400px" className={styles.photo} />
|
||||
<div className={styles.body}>
|
||||
<p className={styles.kicker}>Last night: {dinner.name}</p>
|
||||
<h2 className={styles.question}>Keep it in rotation?</h2>
|
||||
<div className={styles.actions}>
|
||||
<Button disabled={disabled} onClick={() => onDecide('keep')}>
|
||||
Keep it
|
||||
</Button>
|
||||
<Button variant="outline" disabled={disabled} onClick={() => onDecide('drop')}>
|
||||
Not for us
|
||||
</Button>
|
||||
</div>
|
||||
<button type="button" className={styles.notMade} disabled={disabled} onClick={() => onDecide('not_made')}>
|
||||
We didn't make it
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// RotationCheck is the Rotation check on Home: the card for the oldest
|
||||
// pending check (GET /api/v1/rotation-reviews), which stays until the
|
||||
// household answers it — nothing is decided for them. An answer is applied
|
||||
// at once: Home confirms it and shows the next pending check, if any, while
|
||||
// the answer is saved; the answers are locked until it settles. A failed
|
||||
// answer puts its check back with an ErrorBanner. A failed read shows an
|
||||
// ErrorBanner, beside the checks last read: a card already shown stays
|
||||
// until it is answered.
|
||||
export function RotationCheck() {
|
||||
const reviews = useRotationReviews()
|
||||
const decide = useDecideRotationReview()
|
||||
const deciding = decide.isPending ? decide.variables.review.dinner.id : null
|
||||
const next = reviews.data?.find((review) => review.dinner.id !== deciding)
|
||||
const answered = decide.isPending || decide.isSuccess ? decide.variables : undefined
|
||||
return (
|
||||
<>
|
||||
{answered !== undefined && (
|
||||
<p role="status" className={styles.confirmation}>
|
||||
{CONFIRMATION[answered.decision]}
|
||||
</p>
|
||||
)}
|
||||
{reviews.isError && (
|
||||
<ErrorBanner onRetry={() => void reviews.refetch()}>
|
||||
Couldn't load the Rotation check. {reviews.error.message}
|
||||
</ErrorBanner>
|
||||
)}
|
||||
{decide.isError && <ErrorBanner>Couldn't save that answer. {decide.error.message}</ErrorBanner>}
|
||||
{next !== undefined && (
|
||||
<RotationCard
|
||||
key={next.dinner.id}
|
||||
review={next}
|
||||
disabled={decide.isPending}
|
||||
onDecide={(decision) => decide.mutate({ review: next, decision })}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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,383 @@
|
||||
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 { ROTATION_REVIEWS_PATH } from './rotation.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?week=2026-10-12',
|
||||
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),
|
||||
[`GET ${ROTATION_REVIEWS_PATH}`]: () => jsonResponse(200, { reviews: [] }),
|
||||
[`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?week=2026-10-12'],
|
||||
[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,52 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { HOME } from '../test/ApiProviders.tsx'
|
||||
import { parseHome, 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`,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHome', () => {
|
||||
it("keeps the household's zone, and refuses one that is not an IANA zone", () => {
|
||||
expect(parseHome('GET /api/v1/home', HOME).timezone).toBe('America/New_York')
|
||||
expect(() => parseHome('GET /api/v1/home', { ...HOME, timezone: 'Mars/Olympus' })).toThrow(
|
||||
'GET /api/v1/home: timezone "Mars/Olympus" is not an IANA zone',
|
||||
)
|
||||
expect(() => parseHome('GET /api/v1/home', { ...HOME, timezone: undefined })).toThrow(
|
||||
'GET /api/v1/home: timezone undefined is not an IANA zone',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { useApi } from '../api/index.ts'
|
||||
import { isRecord } from '../api/errors.ts'
|
||||
import { oneOf, photoId } from '../dinners/api.ts'
|
||||
import { untilLocalMidnight, 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]
|
||||
|
||||
// Tonight is the dinner planned for today: photo_id is its stored photo's
|
||||
// id, from photo, and minutes_total its minutes from prep to table, a
|
||||
// positive whole number, or null when the recipe does not say.
|
||||
export type Tonight = { id: string; name: string; photo_id: string | undefined; origin: Origin; minutes_total: number | null }
|
||||
|
||||
// ShoppingListStatus is the Supply run Home points at: next week's once it
|
||||
// has one, otherwise this week's, ready when that week has a list.
|
||||
// weekStart is the week's Monday, YYYY-MM-DD, and dates the week as the
|
||||
// status row shows it, "Oct 5–11" (the API's label is the long "Week 41 ·
|
||||
// Oct 5 – 11").
|
||||
export type ShoppingListStatus = { weekStart: string; dates: string; ready: boolean }
|
||||
|
||||
// Home is GET /api/v1/home: dateLabel is today, household-local, "Friday,
|
||||
// Oct 2"; timezone is the household's IANA zone, whose midnight starts the
|
||||
// next day; tonight is null when today has no plan; sideQuestCount is how
|
||||
// many Side quests wait in the deck; unread says the Recent updates hold
|
||||
// something not yet seen.
|
||||
export type Home = {
|
||||
dateLabel: string
|
||||
timezone: string
|
||||
tonight: Tonight | null
|
||||
sideQuestCount: number
|
||||
shoppingList: ShoppingListStatus
|
||||
unread: boolean
|
||||
}
|
||||
|
||||
function parseTonight(where: string, body: unknown): Tonight | null {
|
||||
if (body === null) return null
|
||||
if (!isRecord(body) || typeof body.id !== 'string' || typeof body.name !== 'string') {
|
||||
throw new Error(`${where}: tonight is not a dinner`)
|
||||
}
|
||||
if (!('minutes_total' in body)) throw new Error(`${where}: tonight has no minutes_total`)
|
||||
const minutes = body.minutes_total
|
||||
if (minutes !== null && (!Number.isInteger(minutes) || (minutes as number) <= 0)) {
|
||||
throw new Error(`${where}: tonight's minutes_total ${String(minutes)} is not a positive whole number`)
|
||||
}
|
||||
return {
|
||||
id: body.id,
|
||||
name: body.name,
|
||||
photo_id: photoId(where, body.photo),
|
||||
origin: oneOf(where, 'origin', ORIGINS, body.origin),
|
||||
minutes_total: minutes as number | null,
|
||||
}
|
||||
}
|
||||
|
||||
// parseShoppingList checks the shoppingList of a GET /api/v1/home body. The
|
||||
// list, ready or not, must carry the API's label for its week, which must be
|
||||
// the label weekStart has, since the status row shows dates from weekStart.
|
||||
function parseShoppingList(where: string, list: unknown): ShoppingListStatus {
|
||||
if (!isRecord(list) || typeof list.weekStart !== 'string' || typeof list.ready !== 'boolean') {
|
||||
throw new Error(`${where}: shoppingList is not a week's Supply run status`)
|
||||
}
|
||||
const week = weekLabel(list.weekStart)
|
||||
if (typeof list.label !== 'string' || list.label === '') {
|
||||
throw new Error(`${where}: the ${list.ready ? 'ready' : 'unready'} shoppingList has no label`)
|
||||
}
|
||||
if (list.label !== `${week.week} · ${week.dates}`) {
|
||||
throw new Error(`${where}: shoppingList label "${list.label}" is not the week of ${list.weekStart}`)
|
||||
}
|
||||
return { weekStart: list.weekStart, dates: week.dates.replace(' – ', '–'), ready: list.ready }
|
||||
}
|
||||
|
||||
// parseHome checks a GET /api/v1/home body.
|
||||
export function parseHome(where: string, body: unknown): Home {
|
||||
if (!isRecord(body) || typeof body.dateLabel !== 'string') throw new Error(`${where}: response is not the home`)
|
||||
if (typeof body.timezone !== 'string' || !isZone(body.timezone)) {
|
||||
throw new Error(`${where}: timezone ${JSON.stringify(body.timezone)} is not an IANA zone`)
|
||||
}
|
||||
if (!Number.isInteger(body.sideQuestCount) || (body.sideQuestCount as number) < 0) {
|
||||
throw new Error(`${where}: sideQuestCount is not a count`)
|
||||
}
|
||||
const updates = body.recentUpdates
|
||||
if (!isRecord(updates) || typeof updates.unread !== 'boolean') throw new Error(`${where}: recentUpdates has no unread flag`)
|
||||
return {
|
||||
dateLabel: body.dateLabel,
|
||||
timezone: body.timezone,
|
||||
tonight: parseTonight(where, body.tonight),
|
||||
sideQuestCount: body.sideQuestCount as number,
|
||||
shoppingList: parseShoppingList(where, body.shoppingList),
|
||||
unread: updates.unread,
|
||||
}
|
||||
}
|
||||
|
||||
// isZone says whether zone is an IANA zone this browser knows.
|
||||
function isZone(zone: string): boolean {
|
||||
try {
|
||||
new Intl.DateTimeFormat('en-US', { timeZone: zone })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// useHome is the Home screen's summary (GET /api/v1/home). Home is read
|
||||
// again at the household's next local midnight, counted from each read, so
|
||||
// a Home left open does not keep yesterday's date and dinner.
|
||||
export function useHome() {
|
||||
const { apiFetch } = useApi()
|
||||
const queryClient = useQueryClient()
|
||||
const home = useQuery({
|
||||
queryKey: HOME_KEY,
|
||||
queryFn: async () => parseHome(`GET ${HOME_PATH}`, await apiFetch<unknown>(HOME_PATH)),
|
||||
})
|
||||
const zone = home.data?.timezone
|
||||
const readAt = home.dataUpdatedAt
|
||||
useEffect(() => {
|
||||
if (zone === undefined) return
|
||||
const timer = setTimeout(
|
||||
() => void queryClient.invalidateQueries({ queryKey: HOME_KEY }),
|
||||
untilLocalMidnight(zone, new Date()),
|
||||
)
|
||||
return () => clearTimeout(timer)
|
||||
}, [queryClient, zone, readAt])
|
||||
return home
|
||||
}
|
||||
|
||||
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 })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { useApi } from '../api/index.ts'
|
||||
import { isRecord } from '../api/errors.ts'
|
||||
import { photoId } from '../dinners/api.ts'
|
||||
import { isNotificationOpened } from '../push/notification.ts'
|
||||
|
||||
export const ROTATION_REVIEWS_PATH = '/api/v1/rotation-reviews'
|
||||
export const ROTATION_REVIEWS_KEY = ['rotation-reviews'] as const
|
||||
const DINNERS_KEY = ['dinners'] as const
|
||||
|
||||
// rotationReviewPath is where the household answers "Keep it in rotation?"
|
||||
// for a tried dinner.
|
||||
export function rotationReviewPath(dinnerId: string): string {
|
||||
return `/api/v1/dinners/${encodeURIComponent(dinnerId)}/rotation-review`
|
||||
}
|
||||
|
||||
// Rotation check answers: keep makes the tried dinner a Regular, drop ("Not
|
||||
// for us") archives it so it is never suggested again, and not_made ("We
|
||||
// didn't make it") returns it to the Quest log. Keep is the only way a tried
|
||||
// dinner becomes a Regular; nothing decides one automatically.
|
||||
export const DECISIONS = ['keep', 'drop', 'not_made'] as const
|
||||
export type Decision = (typeof DECISIONS)[number]
|
||||
|
||||
// RotationReview is a pending Rotation check: the dinner tried, photo_id its
|
||||
// stored photo's id, and the household-local plan date, YYYY-MM-DD, it was
|
||||
// planned on.
|
||||
export type RotationReview = { dinner: { id: string; name: string; photo_id: string | undefined }; plan_date: string }
|
||||
|
||||
function parseReview(where: string, body: unknown): RotationReview {
|
||||
if (!isRecord(body) || typeof body.plan_date !== 'string') throw new Error(`${where}: a review is not a Rotation check`)
|
||||
const dinner = body.dinner
|
||||
if (!isRecord(dinner) || typeof dinner.id !== 'string' || typeof dinner.name !== 'string') {
|
||||
throw new Error(`${where}: a Rotation check has no dinner`)
|
||||
}
|
||||
return { dinner: { id: dinner.id, name: dinner.name, photo_id: photoId(where, dinner.photo) }, plan_date: body.plan_date }
|
||||
}
|
||||
|
||||
// parseRotationReviews checks a GET /api/v1/rotation-reviews body: the
|
||||
// pending Rotation checks, oldest plan date first.
|
||||
export function parseRotationReviews(where: string, body: unknown): RotationReview[] {
|
||||
if (!isRecord(body) || !Array.isArray(body.reviews)) throw new Error(`${where}: response is not the Rotation checks`)
|
||||
return body.reviews.map((review) => parseReview(where, review))
|
||||
}
|
||||
|
||||
// useRotationReviews is the pending Rotation checks (GET
|
||||
// /api/v1/rotation-reviews), oldest plan date first. Each mount of Home
|
||||
// reads them afresh, and so does a notification tap that focuses Home
|
||||
// already open (the service worker's NotificationOpened), so Home opened
|
||||
// from a rotation_review notification shows the check it is about.
|
||||
export function useRotationReviews() {
|
||||
const { apiFetch } = useApi()
|
||||
const query = useQuery({
|
||||
queryKey: ROTATION_REVIEWS_KEY,
|
||||
queryFn: async () =>
|
||||
parseRotationReviews(`GET ${ROTATION_REVIEWS_PATH}`, await apiFetch<unknown>(ROTATION_REVIEWS_PATH)),
|
||||
refetchOnMount: 'always',
|
||||
})
|
||||
const { refetch } = query
|
||||
useEffect(() => {
|
||||
// Without a service worker there are no notifications to tap.
|
||||
if (!('serviceWorker' in navigator)) return
|
||||
const container = navigator.serviceWorker
|
||||
const onMessage = (event: MessageEvent<unknown>) => {
|
||||
if (isNotificationOpened(event.data)) void refetch()
|
||||
}
|
||||
container.addEventListener('message', onMessage)
|
||||
return () => container.removeEventListener('message', onMessage)
|
||||
}, [refetch])
|
||||
return query
|
||||
}
|
||||
|
||||
// useDecideRotationReview answers "Keep it in rotation?" for a pending
|
||||
// Rotation check (POST /api/v1/dinners/{id}/rotation-review). The answer
|
||||
// must be that dinner, decided that way.
|
||||
//
|
||||
// Home leaves the check out while its answer is pending (the mutation's
|
||||
// variables say which), so the next one shows at once; a read in flight is
|
||||
// stopped so it cannot bring the check back meanwhile. Once saved, the check
|
||||
// leaves the cached list; once failed, it is shown again as the list has it.
|
||||
// Either way the Rotation checks and the dinners lists (the Regulars and the
|
||||
// Quest log the answer moved it to) are read again.
|
||||
export function useDecideRotationReview() {
|
||||
const { apiFetch } = useApi()
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation<void, Error, { review: RotationReview; decision: Decision }>({
|
||||
mutationFn: async ({ review, decision }) => {
|
||||
const path = rotationReviewPath(review.dinner.id)
|
||||
const body = await apiFetch<unknown>(path, { method: 'POST', body: { decision } })
|
||||
if (!isRecord(body) || !isRecord(body.dinner) || body.dinner.id !== review.dinner.id || body.decision !== decision) {
|
||||
throw new Error(`POST ${path}: response is not the Rotation check decided ${decision}`)
|
||||
}
|
||||
},
|
||||
onMutate: async () => {
|
||||
await queryClient.cancelQueries({ queryKey: ROTATION_REVIEWS_KEY })
|
||||
},
|
||||
onSuccess: (_data, { review }) => {
|
||||
queryClient.setQueryData<RotationReview[]>(ROTATION_REVIEWS_KEY, (reviews) =>
|
||||
reviews?.filter((r) => r.dinner.id !== review.dinner.id),
|
||||
)
|
||||
},
|
||||
onSettled: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ROTATION_REVIEWS_KEY })
|
||||
void queryClient.invalidateQueries({ queryKey: DINNERS_KEY })
|
||||
},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user