Feature 12: Regular dinners and onboarding (#94)
Co-authored-by: dev_agent <dev_agent@cubecraftlabs.com>
This commit was merged in pull request #94.
This commit is contained in:
@@ -0,0 +1,302 @@
|
||||
/* Settings · Regular dinners. */
|
||||
.page {
|
||||
box-sizing: border-box;
|
||||
min-height: 100%;
|
||||
max-width: 560px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.kicker {
|
||||
margin: 0;
|
||||
font-family: var(--font-body);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-accent-700);
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 28px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.shared {
|
||||
margin: 0;
|
||||
padding: 14px 16px;
|
||||
border-radius: 26px;
|
||||
background: var(--color-accent-2-100);
|
||||
color: var(--color-accent-2-900);
|
||||
font-family: var(--font-body);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* The add form: the add row, then the name field a pasted link needs. */
|
||||
.addForm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* The add field: the input fills the row beside the grape + button. */
|
||||
.add {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.add > :first-child {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.add .addInput {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.loading {
|
||||
height: 320px;
|
||||
border-radius: 26px;
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.groupLabel {
|
||||
margin: 0;
|
||||
font-family: var(--font-body);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 6px;
|
||||
border: 1px solid var(--color-neutral-300);
|
||||
}
|
||||
|
||||
.rows {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.item + .item {
|
||||
border-top: 1px solid var(--color-divider);
|
||||
}
|
||||
|
||||
.pending {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.photo {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Beat the Tag's own tones whatever order the sheets load in. */
|
||||
.meta .finding {
|
||||
background: var(--color-neutral-200);
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
.meta .found {
|
||||
background: var(--color-accent-2-200);
|
||||
color: var(--color-accent-2-800);
|
||||
}
|
||||
|
||||
.meta .needs {
|
||||
background: var(--color-accent-100);
|
||||
color: var(--color-accent-800);
|
||||
}
|
||||
|
||||
.filled {
|
||||
color: var(--color-accent);
|
||||
fill: currentColor;
|
||||
}
|
||||
|
||||
.hint,
|
||||
.problem,
|
||||
.status {
|
||||
margin: 0;
|
||||
font-family: var(--font-body);
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
.problem {
|
||||
font-weight: 700;
|
||||
color: var(--color-accent-700);
|
||||
}
|
||||
|
||||
.status {
|
||||
color: var(--color-accent-2-800);
|
||||
}
|
||||
|
||||
.status:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sheet {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
max-width: 560px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.sheetTitle {
|
||||
margin: 0;
|
||||
font-family: var(--font-heading);
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.columns {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
/* Beside a dropdown, a minutes field matches its height. */
|
||||
.columns .paired {
|
||||
width: 100%;
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-family: var(--font-body);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 120px;
|
||||
padding: 14px 18px;
|
||||
border: 1px solid var(--color-neutral-300);
|
||||
border-radius: 22px;
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-body);
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.actions > button {
|
||||
min-height: 52px;
|
||||
}
|
||||
|
||||
.candidatesLoading {
|
||||
height: 200px;
|
||||
border-radius: 22px;
|
||||
}
|
||||
|
||||
.candidates {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.candidate {
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
min-width: 44px;
|
||||
min-height: 72px;
|
||||
padding: 8px 16px 8px 8px;
|
||||
border: 1px solid var(--color-neutral-300);
|
||||
border-radius: 22px;
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
text-align: start;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.candidate:hover {
|
||||
background: var(--color-neutral-200);
|
||||
}
|
||||
|
||||
.candidatePhoto {
|
||||
flex: none;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
.candidateBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.candidateTitle {
|
||||
font-family: var(--font-body);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.candidateSite {
|
||||
font-family: var(--font-body);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--color-neutral-700);
|
||||
}
|
||||
|
||||
/* A form locked while its save is pending. It lays out as if it were not
|
||||
there. */
|
||||
.lock {
|
||||
display: contents;
|
||||
}
|
||||
@@ -0,0 +1,591 @@
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { Route, Routes } from 'react-router'
|
||||
import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
|
||||
import { ApiProvider, createApiClient, createQueryClient, createVerifiedSession } from '../api/index.ts'
|
||||
import { GROUNDING_POLL_MS } from '../dinners/api.ts'
|
||||
import { createNetworkStatus } from '../pwa/networkStatus.ts'
|
||||
import { InDataRouter } from '../test/dataRouter.tsx'
|
||||
import { dinnerBody, type DinnerBody } from '../test/dinners.ts'
|
||||
import { errorResponse, fakeLocation, jsonResponse, ME } from '../test/fetchStub.ts'
|
||||
import { expectMinHitArea } from '../test/hitArea.ts'
|
||||
import { RegularsSettingsPage } from './RegularsSettingsPage.tsx'
|
||||
|
||||
const REGULARS = '/api/v1/dinners?status=regular'
|
||||
|
||||
type Responder = (body: unknown) => Response | Promise<Response>
|
||||
|
||||
// stubServer stands in for the dinners API: GET of the Regulars answers
|
||||
// the current server.regulars, so a test changes what the next read sees;
|
||||
// every other request is answered by responders, keyed "METHOD path" and
|
||||
// called with the request's decoded JSON body. Any other request fails the
|
||||
// test.
|
||||
function stubServer(regulars: DinnerBody[], responders: Record<string, Responder> = {}) {
|
||||
const server = { regulars, fetchMock: undefined as unknown as Mock<typeof fetch> }
|
||||
const all: Record<string, Responder> = {
|
||||
'GET /api/v1/me': () => jsonResponse(200, ME),
|
||||
[`GET ${REGULARS}`]: () => jsonResponse(200, { dinners: server.regulars }),
|
||||
...responders,
|
||||
}
|
||||
server.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}`)
|
||||
const body = typeof init?.body === 'string' ? (JSON.parse(init.body) as unknown) : undefined
|
||||
return Promise.resolve(respond(body))
|
||||
})
|
||||
vi.stubGlobal('fetch', server.fetchMock)
|
||||
return server
|
||||
}
|
||||
|
||||
// sent lists the requests other than GETs, as "METHOD path" and body.
|
||||
function sent(fetchMock: Mock<typeof fetch>) {
|
||||
return fetchMock.mock.calls
|
||||
.filter(([, init]) => (init?.method ?? 'GET') !== 'GET')
|
||||
.map(([input, init]) => ({
|
||||
request: `${init?.method} ${String(input)}`,
|
||||
body: typeof init?.body === 'string' ? (JSON.parse(init.body) as unknown) : undefined,
|
||||
}))
|
||||
}
|
||||
|
||||
function reads(fetchMock: Mock<typeof fetch>) {
|
||||
return fetchMock.mock.calls.filter(([input, init]) => (init?.method ?? 'GET') === 'GET' && String(input) === REGULARS)
|
||||
.length
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
// renderPage loads /me (for the CSRF token every write needs) and renders
|
||||
// the page at /settings/regulars once its Regulars have loaded.
|
||||
async function renderPage() {
|
||||
const api = createApiClient(fakeLocation('/settings/regulars'), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
await api.loadMe()
|
||||
render(
|
||||
<ApiProvider client={api}>
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<InDataRouter path="/settings/regulars">
|
||||
<Routes>
|
||||
<Route path="/settings/regulars" element={<RegularsSettingsPage />} />
|
||||
</Routes>
|
||||
</InDataRouter>
|
||||
</QueryClientProvider>
|
||||
</ApiProvider>,
|
||||
)
|
||||
await screen.findByRole('heading', { level: 2, name: /^On rotation/ })
|
||||
}
|
||||
|
||||
const TACOS = dinnerBody('d1', 'Beef tacos', {
|
||||
method: 'stovetop',
|
||||
minutes_total: 40,
|
||||
difficulty: 'easy',
|
||||
is_favorite: true,
|
||||
photo_url: '/media/photos/p1-400.jpg',
|
||||
})
|
||||
const CHILI = dinnerBody('d2', 'Chili', { method: 'crockpot', minutes_total: 480, grounding_status: 'pending' })
|
||||
const PIZZA = dinnerBody('d3', 'Pizza night', { grounding_status: 'failed', grounding_error: 'no_recipe_found' })
|
||||
const ROAST = dinnerBody('d4', 'Pot roast', { method: 'oven', grounding_status: 'manual' })
|
||||
|
||||
function rows() {
|
||||
return within(screen.getByRole('list', { name: 'Regulars' })).queryAllByRole('listitem')
|
||||
}
|
||||
|
||||
function row(name: string) {
|
||||
const item = rows().find((li) => within(li).queryByText(name) !== null)
|
||||
if (item === undefined) throw new Error(`no Regular row named ${name}`)
|
||||
return item
|
||||
}
|
||||
|
||||
function addField() {
|
||||
return screen.getByRole('textbox', { name: 'Add a Regular' })
|
||||
}
|
||||
|
||||
function add(text: string) {
|
||||
fireEvent.change(addField(), { target: { value: text } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Regular' }))
|
||||
}
|
||||
|
||||
function openRow(name: string) {
|
||||
fireEvent.click(within(row(name)).getByRole('button', { name: new RegExp(`^${name}`) }))
|
||||
}
|
||||
|
||||
describe('RegularsSettingsPage', () => {
|
||||
it('lists each Regular with its photo, method and minutes, favorite heart and grounding badge', async () => {
|
||||
stubServer([TACOS, CHILI, PIZZA, ROAST])
|
||||
await renderPage()
|
||||
|
||||
expect(screen.getByRole('heading', { level: 1, name: 'Regular dinners' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('heading', { level: 2, name: 'On rotation · 4' })).toBeInTheDocument()
|
||||
expect(rows()).toHaveLength(4)
|
||||
|
||||
const tacos = within(row('Beef tacos'))
|
||||
expect(tacos.getByRole('img', { name: 'Beef tacos' })).toHaveAttribute('src', '/media/photos/p1-400.jpg')
|
||||
expect(tacos.getByText('Stovetop · 40 min')).toBeInTheDocument()
|
||||
expect(tacos.getByText('Recipe found')).toBeInTheDocument()
|
||||
expect(tacos.getByRole('button', { name: 'Favorite Beef tacos' })).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
const chili = within(row('Chili'))
|
||||
expect(chili.getByText('Crock pot · 480 min')).toBeInTheDocument()
|
||||
expect(chili.getByText('Finding recipe…')).toBeInTheDocument()
|
||||
expect(chili.getByRole('button', { name: 'Favorite Chili' })).toHaveAttribute('aria-pressed', 'false')
|
||||
|
||||
const pizza = within(row('Pizza night'))
|
||||
// No photo yet: the striped placeholder stands in.
|
||||
expect(pizza.getByRole('img', { name: 'Pizza night' })).toHaveTextContent('dish photo')
|
||||
expect(pizza.getByText('Needs a recipe')).toBeInTheDocument()
|
||||
|
||||
expect(within(row('Pot roast')).getByText('Oven')).toBeInTheDocument()
|
||||
expect(within(row('Pot roast')).getByText('Recipe found')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps every control at least 44 px', async () => {
|
||||
stubServer([TACOS])
|
||||
await renderPage()
|
||||
expectMinHitArea(screen.getByRole('button', { name: 'Add Regular' }))
|
||||
expectMinHitArea(screen.getByRole('button', { name: 'Favorite Beef tacos' }))
|
||||
expectMinHitArea(within(row('Beef tacos')).getByRole('button', { name: /^Beef tacos/ }))
|
||||
expectMinHitArea(screen.getByRole('button', { name: 'Back to Settings' }))
|
||||
})
|
||||
|
||||
it('says so when there are no Regulars yet', async () => {
|
||||
stubServer([])
|
||||
await renderPage()
|
||||
expect(screen.getByRole('heading', { level: 2, name: 'On rotation · 0' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/No Regulars yet/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports Regulars that could not load, and retries', async () => {
|
||||
const server = stubServer([], { [`GET ${REGULARS}`]: () => errorResponse(500, 'internal') })
|
||||
const api = createApiClient(fakeLocation('/settings/regulars'), createNetworkStatus(window), createVerifiedSession(localStorage))
|
||||
render(
|
||||
<ApiProvider client={api}>
|
||||
<QueryClientProvider client={createQueryClient()}>
|
||||
<InDataRouter path="/settings/regulars">
|
||||
<RegularsSettingsPage />
|
||||
</InDataRouter>
|
||||
</QueryClientProvider>
|
||||
</ApiProvider>,
|
||||
)
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Your Regulars could not load: internal message')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(2))
|
||||
})
|
||||
|
||||
it('adds a Regular by name, showing it at once and finding its recipe', async () => {
|
||||
const server = stubServer([TACOS], {
|
||||
'POST /api/v1/dinners': (body) => {
|
||||
const created = dinnerBody('d9', (body as { name: string }).name, { grounding_status: 'pending' })
|
||||
server.regulars = [...server.regulars, created]
|
||||
return jsonResponse(201, { ...created, grounding_job_id: 'job-1' })
|
||||
},
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
add(' Chicken enchiladas ')
|
||||
expect(addField()).toHaveValue('')
|
||||
expect(await screen.findByText('Chicken enchiladas')).toBeInTheDocument()
|
||||
expect(within(row('Chicken enchiladas')).getByText('Finding recipe…')).toBeInTheDocument()
|
||||
expect(sent(server.fetchMock)).toEqual([{ request: 'POST /api/v1/dinners', body: { name: 'Chicken enchiladas' } }])
|
||||
await waitFor(() => expect(row('Chicken enchiladas')).not.toHaveAttribute('aria-busy'))
|
||||
expect(screen.getByRole('heading', { level: 2, name: 'On rotation · 2' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('adds a Regular from a pasted recipe link under the name the household gives it', async () => {
|
||||
const link = 'https://example.com/recipes/stew-key-abcdefghijklmno'
|
||||
const server = stubServer([], {
|
||||
'POST /api/v1/dinners': (body) => {
|
||||
const created = dinnerBody('d9', (body as { name: string }).name, { grounding_status: 'pending' })
|
||||
server.regulars = [created]
|
||||
return jsonResponse(201, { ...created, grounding_job_id: 'job-1' })
|
||||
},
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
fireEvent.change(addField(), { target: { value: ` ${link} ` } })
|
||||
// A link alone cannot be added: it never names a dinner.
|
||||
expect(screen.getByRole('button', { name: 'Add Regular' })).toBeDisabled()
|
||||
const name = screen.getByRole('textbox', { name: 'Dinner name' })
|
||||
expect(name).toHaveAccessibleDescription(/never names a dinner/)
|
||||
fireEvent.change(name, { target: { value: ' Sunday stew ' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add Regular' }))
|
||||
|
||||
expect(addField()).toHaveValue('')
|
||||
expect(screen.queryByRole('textbox', { name: 'Dinner name' })).not.toBeInTheDocument()
|
||||
expect(await screen.findByText('Sunday stew')).toBeInTheDocument()
|
||||
expect(sent(server.fetchMock)).toEqual([
|
||||
{ request: 'POST /api/v1/dinners', body: { name: 'Sunday stew', recipe_url: link } },
|
||||
])
|
||||
expect(within(row('Sunday stew')).getByText('Finding recipe…')).toBeInTheDocument()
|
||||
expect(document.body).not.toHaveTextContent(/example\.com|abcdefghijklmno|key/i)
|
||||
})
|
||||
|
||||
it('takes back an add the server refuses and says why', async () => {
|
||||
stubServer([TACOS], { 'POST /api/v1/dinners': () => errorResponse(409, 'duplicate_dinner') })
|
||||
await renderPage()
|
||||
|
||||
add('Beef tacos!')
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Could not add Beef tacos!: duplicate_dinner message')
|
||||
expect(rows()).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('toggles the favorite heart', async () => {
|
||||
const server = stubServer([TACOS], {
|
||||
'POST /api/v1/dinners/d1/favorite': () => {
|
||||
server.regulars = [{ ...TACOS, is_favorite: false }]
|
||||
return jsonResponse(200, server.regulars[0])
|
||||
},
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Favorite Beef tacos' }))
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('button', { name: 'Favorite Beef tacos' })).toHaveAttribute('aria-pressed', 'false'),
|
||||
)
|
||||
expect(sent(server.fetchMock)).toEqual([{ request: 'POST /api/v1/dinners/d1/favorite', body: undefined }])
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(2))
|
||||
expect(screen.getByRole('button', { name: 'Favorite Beef tacos' })).toHaveAttribute('aria-pressed', 'false')
|
||||
})
|
||||
|
||||
it('edits a Regular: name, method, minutes and difficulty', async () => {
|
||||
const server = stubServer([TACOS], {
|
||||
'PATCH /api/v1/dinners/d1': (body) => {
|
||||
const edited = { ...TACOS, ...(body as object) }
|
||||
server.regulars = [edited]
|
||||
return jsonResponse(200, edited)
|
||||
},
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Beef tacos')
|
||||
const sheet = within(screen.getByRole('dialog', { name: 'Edit Beef tacos' }))
|
||||
expect(sheet.getByLabelText('Name')).toHaveValue('Beef tacos')
|
||||
expect(sheet.getByLabelText('Method')).toHaveValue('stovetop')
|
||||
expect(sheet.getByLabelText('Minutes')).toHaveValue(40)
|
||||
expect(sheet.getByLabelText('Difficulty')).toHaveValue('easy')
|
||||
expect(sheet.getByRole('button', { name: 'Save changes' })).toBeDisabled()
|
||||
|
||||
fireEvent.change(sheet.getByLabelText('Name'), { target: { value: 'Fish tacos' } })
|
||||
fireEvent.change(sheet.getByLabelText('Method'), { target: { value: 'grill' } })
|
||||
fireEvent.change(sheet.getByLabelText('Minutes'), { target: { value: '25' } })
|
||||
fireEvent.change(sheet.getByLabelText('Difficulty'), { target: { value: 'medium' } })
|
||||
fireEvent.click(sheet.getByRole('button', { name: 'Save changes' }))
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(sent(server.fetchMock)).toEqual([
|
||||
{
|
||||
request: 'PATCH /api/v1/dinners/d1',
|
||||
body: { name: 'Fish tacos', method: 'grill', minutes_total: 25, difficulty: 'medium' },
|
||||
},
|
||||
])
|
||||
expect(within(row('Fish tacos')).getByText('Grill · 25 min')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('sends only the changed fields, refuses bad minutes and shows a refused edit', async () => {
|
||||
const server = stubServer([TACOS], { 'PATCH /api/v1/dinners/d1': () => errorResponse(400, 'invalid_dinner') })
|
||||
await renderPage()
|
||||
|
||||
openRow('Beef tacos')
|
||||
const sheet = within(screen.getByRole('dialog', { name: 'Edit Beef tacos' }))
|
||||
fireEvent.change(sheet.getByLabelText('Minutes'), { target: { value: '0' } })
|
||||
expect(sheet.getByText('Minutes must be a whole number from 1 to 1440.')).toBeInTheDocument()
|
||||
expect(sheet.getByRole('button', { name: 'Save changes' })).toBeDisabled()
|
||||
|
||||
fireEvent.change(sheet.getByLabelText('Minutes'), { target: { value: '45' } })
|
||||
fireEvent.click(sheet.getByRole('button', { name: 'Save changes' }))
|
||||
expect(await sheet.findByRole('alert')).toHaveTextContent('Not saved: invalid_dinner message')
|
||||
expect(sent(server.fetchMock)).toEqual([{ request: 'PATCH /api/v1/dinners/d1', body: { minutes_total: 45 } }])
|
||||
})
|
||||
|
||||
it('removes a Regular only once confirmed', async () => {
|
||||
const server = stubServer([TACOS, ROAST], {
|
||||
'DELETE /api/v1/dinners/d1': () => {
|
||||
server.regulars = [ROAST]
|
||||
return jsonResponse(200, { ...TACOS, status: 'archived' })
|
||||
},
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Beef tacos')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove from Regulars' }))
|
||||
const confirm = within(screen.getByRole('dialog', { name: 'Remove Beef tacos?' }))
|
||||
fireEvent.click(confirm.getByRole('button', { name: 'Keep it' }))
|
||||
expect(screen.getByRole('dialog', { name: 'Edit Beef tacos' })).toBeInTheDocument()
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove from Regulars' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove' }))
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
await waitFor(() => expect(rows()).toHaveLength(1))
|
||||
expect(within(rows()[0]!).getByText('Pot roast')).toBeInTheDocument()
|
||||
expect(sent(server.fetchMock)).toEqual([{ request: 'DELETE /api/v1/dinners/d1', body: undefined }])
|
||||
})
|
||||
|
||||
it('puts a refused removal back and says why', async () => {
|
||||
stubServer([TACOS], { 'DELETE /api/v1/dinners/d1': () => errorResponse(500, 'internal') })
|
||||
await renderPage()
|
||||
|
||||
openRow('Beef tacos')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove from Regulars' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Remove' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Could not remove Beef tacos: internal message')
|
||||
expect(rows()).toHaveLength(1)
|
||||
})
|
||||
|
||||
describe('Fix recipe', () => {
|
||||
const CANDIDATES = {
|
||||
candidates: [
|
||||
{
|
||||
candidate_id: 'https://example.com/pizza',
|
||||
title: 'Weeknight pizza',
|
||||
site_name: 'Example Kitchen',
|
||||
photo_url: '/media/photos/p7-400.jpg',
|
||||
minutes: 45,
|
||||
},
|
||||
{ candidate_id: 'https://cook.test/pizza', title: 'Sheet-pan pizza', site_name: 'Cook Test', photo_url: null, minutes: null },
|
||||
{ candidate_id: 'https://food.test/p', title: 'Pizza margherita', site_name: 'Food Test', photo_url: null, minutes: 30 },
|
||||
],
|
||||
}
|
||||
|
||||
function grounded(server: { regulars: DinnerBody[] }, overrides: Partial<DinnerBody>) {
|
||||
const fixed = { ...PIZZA, grounding_error: null, ...overrides }
|
||||
server.regulars = [fixed]
|
||||
return jsonResponse(200, fixed)
|
||||
}
|
||||
|
||||
function fixSheet() {
|
||||
return within(screen.getByRole('dialog', { name: 'Fix recipe' }))
|
||||
}
|
||||
|
||||
it('opens from a Needs a recipe row and picks one of up to three matches', async () => {
|
||||
const server = stubServer([PIZZA], {
|
||||
'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, CANDIDATES),
|
||||
'POST /api/v1/dinners/d3/ground': () =>
|
||||
grounded(server, { grounding_status: 'grounded', photo_url: '/media/photos/p7-400.jpg', method: 'oven', minutes_total: 45 }),
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Pizza night')
|
||||
const matches = within(await fixSheet().findByRole('list', { name: 'Recipe matches' }))
|
||||
const options = matches.getAllByRole('button')
|
||||
expect(options.map((option) => option.getAttribute('aria-label'))).toEqual([
|
||||
'Use Weeknight pizza from Example Kitchen',
|
||||
'Use Sheet-pan pizza from Cook Test',
|
||||
'Use Pizza margherita from Food Test',
|
||||
])
|
||||
expect(within(options[0]!).getByRole('img', { name: 'Weeknight pizza' })).toHaveAttribute('src', '/media/photos/p7-400.jpg')
|
||||
expect(within(options[0]!).getByText('Example Kitchen')).toBeInTheDocument()
|
||||
expectMinHitArea(options[0]!)
|
||||
|
||||
fireEvent.click(options[0]!)
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(sent(server.fetchMock)).toEqual([
|
||||
{ request: 'POST /api/v1/dinners/d3/ground', body: { candidate_id: 'https://example.com/pizza' } },
|
||||
])
|
||||
expect(within(row('Pizza night')).getByText('Recipe found')).toBeInTheDocument()
|
||||
expect(within(row('Pizza night')).getByText('Oven · 45 min')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('says so when no match was found', async () => {
|
||||
stubServer([PIZZA], { 'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, { candidates: [] }) })
|
||||
await renderPage()
|
||||
openRow('Pizza night')
|
||||
expect(await fixSheet().findByText('No matches were found. Paste a recipe link or type it in.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('grounds a pasted recipe link, and says why a link was refused', async () => {
|
||||
let answers = 0
|
||||
const server = stubServer([PIZZA], {
|
||||
'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, CANDIDATES),
|
||||
'POST /api/v1/dinners/d3/ground': () =>
|
||||
++answers === 1 ? errorResponse(422, 'ungroundable') : grounded(server, { grounding_status: 'grounded' }),
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Pizza night')
|
||||
fireEvent.click(fixSheet().getByRole('radio', { name: 'Paste a link' }))
|
||||
fireEvent.change(fixSheet().getByLabelText('Recipe link'), { target: { value: ' https://example.com/blog/pizza ' } })
|
||||
fireEvent.click(fixSheet().getByRole('button', { name: 'Use this recipe' }))
|
||||
expect(await fixSheet().findByRole('alert')).toHaveTextContent('Not fixed: ungroundable message')
|
||||
|
||||
fireEvent.change(fixSheet().getByLabelText('Recipe link'), { target: { value: 'https://example.com/pizza-2' } })
|
||||
fireEvent.click(fixSheet().getByRole('button', { name: 'Use this recipe' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(sent(server.fetchMock)).toEqual([
|
||||
{ request: 'POST /api/v1/dinners/d3/ground', body: { recipe_url: 'https://example.com/blog/pizza' } },
|
||||
{ request: 'POST /api/v1/dinners/d3/ground', body: { recipe_url: 'https://example.com/pizza-2' } },
|
||||
])
|
||||
expect(within(row('Pizza night')).getByText('Recipe found')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('saves ingredients and steps typed in', async () => {
|
||||
const server = stubServer([PIZZA], {
|
||||
'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, CANDIDATES),
|
||||
'POST /api/v1/dinners/d3/ground': () =>
|
||||
grounded(server, { grounding_status: 'manual', method: 'oven', minutes_total: 35 }),
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Pizza night')
|
||||
fireEvent.click(fixSheet().getByRole('radio', { name: 'Type it in' }))
|
||||
const save = fixSheet().getByRole('button', { name: 'Save recipe' })
|
||||
expect(save).toBeDisabled()
|
||||
fireEvent.change(fixSheet().getByLabelText('Ingredients, one per line'), {
|
||||
target: { value: '1 pizza dough\n\n 1 cup tomato sauce \n2 cups mozzarella' },
|
||||
})
|
||||
fireEvent.change(fixSheet().getByLabelText('Steps, one per line'), {
|
||||
target: { value: 'Heat the oven to 250°C.\nTop the dough and bake 12 minutes.\n' },
|
||||
})
|
||||
fireEvent.change(fixSheet().getByLabelText('Method'), { target: { value: 'oven' } })
|
||||
fireEvent.change(fixSheet().getByLabelText('Minutes'), { target: { value: '35' } })
|
||||
fireEvent.click(save)
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(sent(server.fetchMock)).toEqual([
|
||||
{
|
||||
request: 'POST /api/v1/dinners/d3/ground',
|
||||
body: {
|
||||
manual: {
|
||||
ingredients: ['1 pizza dough', '1 cup tomato sauce', '2 cups mozzarella'],
|
||||
steps: ['Heat the oven to 250°C.', 'Top the dough and bake 12 minutes.'],
|
||||
minutes: 35,
|
||||
method: 'oven',
|
||||
},
|
||||
},
|
||||
},
|
||||
])
|
||||
expect(within(row('Pizza night')).getByText('Recipe found')).toBeInTheDocument()
|
||||
expect(within(row('Pizza night')).getByText('Oven · 35 min')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('saves a typed-in recipe only once its method and minutes are set', async () => {
|
||||
const server = stubServer([PIZZA], {
|
||||
'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, CANDIDATES),
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Pizza night')
|
||||
fireEvent.click(fixSheet().getByRole('radio', { name: 'Type it in' }))
|
||||
const save = fixSheet().getByRole('button', { name: 'Save recipe' })
|
||||
fireEvent.change(fixSheet().getByLabelText('Ingredients, one per line'), { target: { value: '1 pizza dough' } })
|
||||
expect(fixSheet().getByText('Choose a method and minutes to save.')).toBeInTheDocument()
|
||||
expect(save).toBeDisabled()
|
||||
|
||||
fireEvent.change(fixSheet().getByLabelText('Method'), { target: { value: 'oven' } })
|
||||
expect(save).toBeDisabled()
|
||||
fireEvent.change(fixSheet().getByLabelText('Method'), { target: { value: '' } })
|
||||
fireEvent.change(fixSheet().getByLabelText('Minutes'), { target: { value: '35' } })
|
||||
expect(save).toBeDisabled()
|
||||
|
||||
// Even a submit that skips the button sends nothing.
|
||||
fireEvent.submit(save.closest('form')!)
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
|
||||
fireEvent.change(fixSheet().getByLabelText('Method'), { target: { value: 'oven' } })
|
||||
expect(fixSheet().queryByText('Choose a method and minutes to save.')).not.toBeInTheDocument()
|
||||
expect(save).toBeEnabled()
|
||||
})
|
||||
|
||||
it('switches to editing the Regular', async () => {
|
||||
stubServer([PIZZA], { 'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, CANDIDATES) })
|
||||
await renderPage()
|
||||
openRow('Pizza night')
|
||||
fireEvent.click(fixSheet().getByRole('button', { name: 'Edit or remove Pizza night' }))
|
||||
expect(screen.getByRole('dialog', { name: 'Edit Pizza night' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('refreshes grounding status while any Regular is finding its recipe, then stops', async () => {
|
||||
// Only intervals are faked: TanStack Query polls with setInterval, and
|
||||
// Testing Library's waits keep their real timers.
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })
|
||||
const server = stubServer([TACOS, CHILI])
|
||||
await renderPage()
|
||||
expect(within(row('Chili')).getByText('Finding recipe…')).toBeInTheDocument()
|
||||
expect(reads(server.fetchMock)).toBe(1)
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS))
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(2))
|
||||
expect(within(row('Chili')).getByText('Finding recipe…')).toBeInTheDocument()
|
||||
|
||||
server.regulars = [TACOS, { ...CHILI, grounding_status: 'grounded', photo_url: '/media/photos/p2-400.jpg' }]
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS))
|
||||
expect(await within(row('Chili')).findByText('Recipe found')).toBeInTheDocument()
|
||||
expect(within(row('Chili')).getByRole('img', { name: 'Chili' })).toHaveAttribute('src', '/media/photos/p2-400.jpg')
|
||||
expect(reads(server.fetchMock)).toBe(3)
|
||||
|
||||
// Nothing is pending any more, so nothing is read again.
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS * 3))
|
||||
expect(reads(server.fetchMock)).toBe(3)
|
||||
})
|
||||
|
||||
// held answers a request only when release is called, so a test can look
|
||||
// at the page while a save is in flight.
|
||||
function held(answer: () => Response) {
|
||||
let release = () => {}
|
||||
const response = new Promise<Response>((resolve) => {
|
||||
release = () => resolve(answer())
|
||||
})
|
||||
return { respond: () => response, release: () => release() }
|
||||
}
|
||||
|
||||
it('pauses the refresh while an edit is being saved, then resumes', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })
|
||||
const edited = { ...TACOS, name: 'Fish tacos' }
|
||||
const patch = held(() => jsonResponse(200, edited))
|
||||
const server = stubServer([TACOS, CHILI], { 'PATCH /api/v1/dinners/d1': patch.respond })
|
||||
await renderPage()
|
||||
|
||||
openRow('Beef tacos')
|
||||
const sheet = within(screen.getByRole('dialog', { name: 'Edit Beef tacos' }))
|
||||
fireEvent.change(sheet.getByLabelText('Name'), { target: { value: 'Fish tacos' } })
|
||||
fireEvent.click(sheet.getByRole('button', { name: 'Save changes' }))
|
||||
await waitFor(() => expect(sent(server.fetchMock)).toHaveLength(1))
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS * 3))
|
||||
expect(reads(server.fetchMock)).toBe(1)
|
||||
|
||||
server.regulars = [edited, CHILI]
|
||||
patch.release()
|
||||
// Settling reads the list once, then the refresh carries on.
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(2))
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS))
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(3))
|
||||
})
|
||||
|
||||
it('pauses the refresh while a recipe fix is being saved, then resumes', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })
|
||||
const fixed = { ...PIZZA, grounding_status: 'grounded' as const, grounding_error: null }
|
||||
const ground = held(() => jsonResponse(200, fixed))
|
||||
const server = stubServer([CHILI, PIZZA], {
|
||||
'GET /api/v1/dinners/d3/recipe-candidates': () => jsonResponse(200, { candidates: [] }),
|
||||
'POST /api/v1/dinners/d3/ground': ground.respond,
|
||||
})
|
||||
await renderPage()
|
||||
|
||||
openRow('Pizza night')
|
||||
const sheet = within(screen.getByRole('dialog', { name: 'Fix recipe' }))
|
||||
fireEvent.click(sheet.getByRole('radio', { name: 'Paste a link' }))
|
||||
fireEvent.change(sheet.getByLabelText('Recipe link'), { target: { value: 'https://example.com/pizza' } })
|
||||
fireEvent.click(sheet.getByRole('button', { name: 'Use this recipe' }))
|
||||
await waitFor(() => expect(sent(server.fetchMock)).toHaveLength(1))
|
||||
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS * 3))
|
||||
expect(reads(server.fetchMock)).toBe(1)
|
||||
|
||||
server.regulars = [CHILI, fixed]
|
||||
ground.release()
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(2))
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS))
|
||||
await waitFor(() => expect(reads(server.fetchMock)).toBe(3))
|
||||
})
|
||||
|
||||
it('does not poll when no Regular is finding its recipe', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })
|
||||
const server = stubServer([TACOS, PIZZA])
|
||||
await renderPage()
|
||||
await act(() => vi.advanceTimersByTimeAsync(GROUNDING_POLL_MS * 3))
|
||||
expect(reads(server.fetchMock)).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,641 @@
|
||||
import { ChevronLeft, Heart, Plus } from 'lucide-react'
|
||||
import { useId, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import {
|
||||
DIFFICULTIES,
|
||||
METHODS,
|
||||
useAddRegular,
|
||||
useEditRegular,
|
||||
useGroundRegular,
|
||||
useRecipeCandidates,
|
||||
useRegulars,
|
||||
useRemoveRegular,
|
||||
useToggleFavorite,
|
||||
type Difficulty,
|
||||
type GroundingStatus,
|
||||
type ManualRecipe,
|
||||
type Method,
|
||||
type NewRegular,
|
||||
type RecipeFix,
|
||||
type Regular,
|
||||
type RegularPatch,
|
||||
} from '../dinners/api.ts'
|
||||
import { useRefusals } from '../dinners/useRefusals.ts'
|
||||
import { Button } from '../ui/Button.tsx'
|
||||
import { Card } from '../ui/Card.tsx'
|
||||
import { ErrorBanner } from '../ui/ErrorBanner.tsx'
|
||||
import { Icon } from '../ui/Icon.tsx'
|
||||
import { IconButton } from '../ui/IconButton.tsx'
|
||||
import { ListRow } from '../ui/ListRow.tsx'
|
||||
import { Photo } from '../ui/Photo.tsx'
|
||||
import { Segmented } from '../ui/Segmented.tsx'
|
||||
import { Select } from '../ui/Select.tsx'
|
||||
import { Sheet } from '../ui/Sheet.tsx'
|
||||
import { Skeleton } from '../ui/Skeleton.tsx'
|
||||
import { Tag } from '../ui/Tag.tsx'
|
||||
import { TextInput } from '../ui/TextInput.tsx'
|
||||
import styles from './RegularsSettingsPage.module.css'
|
||||
|
||||
// The most minutes a dinner may take, as the dinners API allows: a day.
|
||||
const MAX_MINUTES = 1440
|
||||
|
||||
export const methodLabels: Record<Method, string> = {
|
||||
stovetop: 'Stovetop',
|
||||
oven: 'Oven',
|
||||
crockpot: 'Crock pot',
|
||||
grill: 'Grill',
|
||||
other: 'Other',
|
||||
}
|
||||
|
||||
const difficultyLabels: Record<Difficulty, string> = { easy: 'Easy', medium: 'Medium', hard: 'Hard' }
|
||||
|
||||
// A pasted link is added as a recipe link under a name the household gives;
|
||||
// anything else is a dinner name.
|
||||
const LINK = /^https?:\/\//i
|
||||
|
||||
// Settings · Regular dinners: the household's Regulars, each with its photo,
|
||||
// method and minutes, favorite heart and whether its recipe was found. The
|
||||
// field at the top adds one by name, or by pasted recipe link with a name
|
||||
// the household gives it; tapping one
|
||||
// edits or removes it, or fixes its recipe when none was found.
|
||||
export function RegularsSettingsPage() {
|
||||
const navigate = useNavigate()
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<header className={styles.header}>
|
||||
<IconButton label="Back to Settings" onClick={() => void navigate('/settings')}>
|
||||
<Icon icon={ChevronLeft} size="nav" />
|
||||
</IconButton>
|
||||
<div>
|
||||
<p className={styles.kicker}>Settings</p>
|
||||
<h1 className={styles.title}>Regular dinners</h1>
|
||||
</div>
|
||||
</header>
|
||||
<p className={styles.shared}>Changes apply to everyone in the household.</p>
|
||||
<RegularsManager />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Which sheet is open, for which Regular.
|
||||
type Open = { sheet: 'edit' | 'fix'; id: string } | null
|
||||
|
||||
function RegularsManager() {
|
||||
const regulars = useRegulars()
|
||||
const add = useAddRegular()
|
||||
const remove = useRemoveRegular()
|
||||
const favorite = useToggleFavorite()
|
||||
const { refusals, track } = useRefusals()
|
||||
const [draft, setDraft] = useState('')
|
||||
const [linkName, setLinkName] = useState('')
|
||||
const [open, setOpen] = useState<Open>(null)
|
||||
const headingId = useId()
|
||||
const linkHintId = useId()
|
||||
const isLink = LINK.test(draft.trim())
|
||||
const ready = draft.trim() !== '' && (!isLink || linkName.trim() !== '')
|
||||
const list = regulars.data ?? []
|
||||
// A Regular removed meanwhile closes its sheet.
|
||||
const opened = open && list.find((regular) => regular.id === open.id && !regular.pending)
|
||||
|
||||
function onSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
if (!ready) return
|
||||
const text = draft.trim()
|
||||
const body: NewRegular = isLink ? { name: linkName.trim(), recipe_url: text } : { name: text }
|
||||
track(`add:${body.name.toLowerCase()}`, `add ${body.name}`, add.mutateAsync(body))
|
||||
setDraft('')
|
||||
setLinkName('')
|
||||
}
|
||||
|
||||
function onRemove(regular: Regular) {
|
||||
setOpen(null)
|
||||
track(`remove:${regular.id}`, `remove ${regular.name}`, remove.mutateAsync(regular))
|
||||
}
|
||||
|
||||
function onFavorite(regular: Regular) {
|
||||
track(`favorite:${regular.id}`, `change the favorite heart on ${regular.name}`, favorite.mutateAsync(regular))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<form className={styles.addForm} onSubmit={onSubmit}>
|
||||
<div className={styles.add}>
|
||||
<TextInput
|
||||
label="Add a Regular"
|
||||
labelHidden
|
||||
className={styles.addInput}
|
||||
placeholder="Dinner name or recipe link"
|
||||
autoComplete="off"
|
||||
enterKeyHint="done"
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
/>
|
||||
<IconButton type="submit" label="Add Regular" tone="accent" disabled={!ready}>
|
||||
<Icon icon={Plus} size="nav" />
|
||||
</IconButton>
|
||||
</div>
|
||||
{isLink && (
|
||||
<>
|
||||
<TextInput
|
||||
label="Dinner name"
|
||||
placeholder="What do you call this dinner?"
|
||||
autoComplete="off"
|
||||
enterKeyHint="done"
|
||||
aria-describedby={linkHintId}
|
||||
value={linkName}
|
||||
onChange={(event) => setLinkName(event.target.value)}
|
||||
/>
|
||||
<p id={linkHintId} className={styles.hint}>
|
||||
Name it yourself: a link can carry private details, so it never names a dinner.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
{refusals.map((refusal) => (
|
||||
<p key={refusal.key} role="alert" className={styles.problem}>
|
||||
{refusal.text}
|
||||
</p>
|
||||
))}
|
||||
|
||||
{regulars.isPending && <Skeleton className={styles.loading} />}
|
||||
{regulars.isError && (
|
||||
<ErrorBanner onRetry={() => void regulars.refetch()}>
|
||||
Your Regulars could not load: {regulars.error.message}
|
||||
</ErrorBanner>
|
||||
)}
|
||||
{regulars.isSuccess && (
|
||||
<section aria-labelledby={headingId} className={styles.section}>
|
||||
<h2 id={headingId} className={styles.groupLabel}>
|
||||
On rotation · {list.length}
|
||||
</h2>
|
||||
{list.length === 0 ? (
|
||||
<p className={styles.hint}>No Regulars yet. Add the dinners your household makes on repeat.</p>
|
||||
) : (
|
||||
<Card className={styles.card}>
|
||||
<ul className={styles.rows} aria-label="Regulars">
|
||||
{list.map((regular) => (
|
||||
<RegularRow
|
||||
key={regular.id}
|
||||
regular={regular}
|
||||
onOpen={() =>
|
||||
setOpen({ sheet: regular.grounding_status === 'failed' ? 'fix' : 'edit', id: regular.id })
|
||||
}
|
||||
onFavorite={() => onFavorite(regular)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{opened && open.sheet === 'edit' && (
|
||||
<EditRegularSheet
|
||||
key={opened.id}
|
||||
regular={opened}
|
||||
onClose={() => setOpen(null)}
|
||||
onRemove={() => onRemove(opened)}
|
||||
/>
|
||||
)}
|
||||
{opened && open.sheet === 'fix' && (
|
||||
<FixRecipeSheet
|
||||
key={opened.id}
|
||||
regular={opened}
|
||||
onClose={() => setOpen(null)}
|
||||
onEdit={() => setOpen({ sheet: 'edit', id: opened.id })}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// details is a Regular's "method · minutes" line, or null when neither is
|
||||
// known yet.
|
||||
export function details(regular: Regular): string | null {
|
||||
const parts = [
|
||||
regular.method && methodLabels[regular.method],
|
||||
regular.minutes_total !== null && `${regular.minutes_total} min`,
|
||||
].filter((part): part is string => typeof part === 'string')
|
||||
return parts.length === 0 ? null : parts.join(' · ')
|
||||
}
|
||||
|
||||
const badges: Record<GroundingStatus, { text: string; className: string | undefined }> = {
|
||||
pending: { text: 'Finding recipe…', className: styles.finding },
|
||||
grounded: { text: 'Recipe found', className: styles.found },
|
||||
manual: { text: 'Recipe found', className: styles.found },
|
||||
failed: { text: 'Needs a recipe', className: styles.needs },
|
||||
}
|
||||
|
||||
function GroundingBadge({ status }: { status: GroundingStatus }) {
|
||||
const badge = badges[status]
|
||||
return <Tag className={`${styles.badge} ${badge.className}`}>{badge.text}</Tag>
|
||||
}
|
||||
|
||||
type RegularRowProps = {
|
||||
regular: Regular
|
||||
onOpen: () => void
|
||||
onFavorite: () => void
|
||||
}
|
||||
|
||||
function RegularRow({ regular, onOpen, onFavorite }: RegularRowProps) {
|
||||
const line = details(regular)
|
||||
return (
|
||||
<li className={styles.item} aria-busy={regular.pending}>
|
||||
<ListRow
|
||||
className={regular.pending && styles.pending}
|
||||
leading={<Photo id={regular.photo_id} name={regular.name} radius="14px" sizes="48px" className={styles.photo} />}
|
||||
title={regular.name}
|
||||
meta={
|
||||
<span className={styles.meta}>
|
||||
{line && <span>{line}</span>}
|
||||
<GroundingBadge status={regular.grounding_status} />
|
||||
</span>
|
||||
}
|
||||
onClick={regular.pending ? undefined : onOpen}
|
||||
trailing={
|
||||
<IconButton
|
||||
label={`Favorite ${regular.name}`}
|
||||
aria-pressed={regular.is_favorite}
|
||||
disabled={regular.pending}
|
||||
onClick={onFavorite}
|
||||
>
|
||||
<Icon icon={Heart} size="nav" className={regular.is_favorite ? styles.filled : undefined} />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
type SheetFrameProps = {
|
||||
title: string
|
||||
onClose: () => void
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function SheetFrame({ title, onClose, children }: SheetFrameProps) {
|
||||
const titleId = useId()
|
||||
return (
|
||||
<Sheet open onClose={onClose} aria-labelledby={titleId}>
|
||||
<div className={styles.sheet}>
|
||||
<h2 id={titleId} className={styles.sheetTitle}>
|
||||
{title}
|
||||
</h2>
|
||||
{children}
|
||||
</div>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
// minutesProblem is why a typed minutes value cannot be saved, or null.
|
||||
function minutesProblem(text: string): string | null {
|
||||
if (text === '') return null
|
||||
const minutes = Number(text)
|
||||
if (!Number.isInteger(minutes) || minutes < 1 || minutes > MAX_MINUTES) {
|
||||
return `Minutes must be a whole number from 1 to ${MAX_MINUTES}.`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type Draft = { name: string; method: Method | ''; minutes: string; difficulty: Difficulty | '' }
|
||||
|
||||
function draftOf(regular: Regular): Draft {
|
||||
return {
|
||||
name: regular.name,
|
||||
method: regular.method ?? '',
|
||||
minutes: regular.minutes_total === null ? '' : String(regular.minutes_total),
|
||||
difficulty: regular.difficulty ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
// patchOf is the PATCH body for the fields draft changes. A field the
|
||||
// Regular has no value for stays unset until one is chosen.
|
||||
function patchOf(regular: Regular, draft: Draft): RegularPatch {
|
||||
const saved = draftOf(regular)
|
||||
const patch: RegularPatch = {}
|
||||
if (draft.name.trim() !== saved.name) patch.name = draft.name.trim()
|
||||
if (draft.method !== saved.method && draft.method !== '') patch.method = draft.method
|
||||
if (draft.minutes !== saved.minutes && draft.minutes !== '') patch.minutes_total = Number(draft.minutes)
|
||||
if (draft.difficulty !== saved.difficulty && draft.difficulty !== '') patch.difficulty = draft.difficulty
|
||||
return patch
|
||||
}
|
||||
|
||||
type EditRegularSheetProps = {
|
||||
regular: Regular
|
||||
onClose: () => void
|
||||
onRemove: () => void
|
||||
}
|
||||
|
||||
// EditRegularSheet renames a Regular and sets its method, minutes and
|
||||
// difficulty, or removes it from the rotation once confirmed.
|
||||
function EditRegularSheet({ regular, onClose, onRemove }: EditRegularSheetProps) {
|
||||
const [draft, setDraft] = useState(() => draftOf(regular))
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const edit = useEditRegular()
|
||||
const patch = patchOf(regular, draft)
|
||||
const minutesError = minutesProblem(draft.minutes)
|
||||
const nameError = draft.name.trim() === '' ? 'A Regular needs a name.' : null
|
||||
const canSave = Object.keys(patch).length > 0 && minutesError === null && nameError === null
|
||||
|
||||
function change(next: Partial<Draft>) {
|
||||
edit.reset()
|
||||
setDraft((current) => ({ ...current, ...next }))
|
||||
}
|
||||
|
||||
function onSave(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
if (!canSave) return
|
||||
edit.mutate({ id: regular.id, patch }, { onSuccess: onClose })
|
||||
}
|
||||
|
||||
if (confirming) {
|
||||
return (
|
||||
<SheetFrame title={`Remove ${regular.name}?`} onClose={onClose}>
|
||||
<p className={styles.hint}>
|
||||
It leaves your Regulars, so suggestions and plans stop using it. You can add it again later.
|
||||
</p>
|
||||
<div className={styles.actions}>
|
||||
<Button onClick={onRemove}>Remove</Button>
|
||||
<Button variant="outline" onClick={() => setConfirming(false)}>
|
||||
Keep it
|
||||
</Button>
|
||||
</div>
|
||||
</SheetFrame>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SheetFrame title={`Edit ${regular.name}`} onClose={onClose}>
|
||||
<form className={styles.form} onSubmit={onSave}>
|
||||
<fieldset className={styles.lock} disabled={edit.isPending}>
|
||||
<TextInput
|
||||
label="Name"
|
||||
value={draft.name}
|
||||
autoComplete="off"
|
||||
aria-invalid={nameError !== null}
|
||||
onChange={(event) => change({ name: event.target.value })}
|
||||
/>
|
||||
{nameError && <p className={styles.problem}>{nameError}</p>}
|
||||
<div className={styles.columns}>
|
||||
<Select label="Method" value={draft.method} onChange={(event) => change({ method: event.target.value as Method })}>
|
||||
{regular.method === null && (
|
||||
<option value="" disabled>
|
||||
Not set
|
||||
</option>
|
||||
)}
|
||||
{METHODS.map((method) => (
|
||||
<option key={method} value={method}>
|
||||
{methodLabels[method]}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<TextInput
|
||||
label="Minutes"
|
||||
className={styles.paired}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
max={MAX_MINUTES}
|
||||
value={draft.minutes}
|
||||
aria-invalid={minutesError !== null}
|
||||
onChange={(event) => change({ minutes: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
{minutesError && <p className={styles.problem}>{minutesError}</p>}
|
||||
<Select
|
||||
label="Difficulty"
|
||||
value={draft.difficulty}
|
||||
onChange={(event) => change({ difficulty: event.target.value as Difficulty })}
|
||||
>
|
||||
{regular.difficulty === null && (
|
||||
<option value="" disabled>
|
||||
Not set
|
||||
</option>
|
||||
)}
|
||||
{DIFFICULTIES.map((difficulty) => (
|
||||
<option key={difficulty} value={difficulty}>
|
||||
{difficultyLabels[difficulty]}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
{edit.isError && (
|
||||
<p role="alert" className={styles.problem}>
|
||||
Not saved: {edit.error.message}
|
||||
</p>
|
||||
)}
|
||||
<div className={styles.actions}>
|
||||
<Button type="submit" disabled={!canSave}>
|
||||
{edit.isPending ? 'Saving…' : 'Save changes'}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setConfirming(true)}>
|
||||
Remove from Regulars
|
||||
</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</SheetFrame>
|
||||
)
|
||||
}
|
||||
|
||||
type FixPath = 'pick' | 'link' | 'manual'
|
||||
|
||||
const fixPaths = [
|
||||
{ value: 'pick', label: 'Pick one' },
|
||||
{ value: 'link', label: 'Paste a link' },
|
||||
{ value: 'manual', label: 'Type it in' },
|
||||
] as const
|
||||
|
||||
type FixRecipeSheetProps = {
|
||||
regular: Regular
|
||||
onClose: () => void
|
||||
onEdit: () => void
|
||||
}
|
||||
|
||||
// lines is text split into its non-blank lines, trimmed.
|
||||
function lines(text: string): string[] {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line !== '')
|
||||
}
|
||||
|
||||
// FixRecipeSheet grounds a Regular whose recipe was not found: in one of
|
||||
// up to three recipe pages found for its name, in a pasted recipe link, or
|
||||
// in ingredients and steps typed in.
|
||||
function FixRecipeSheet({ regular, onClose, onEdit }: FixRecipeSheetProps) {
|
||||
const [path, setPath] = useState<FixPath>('pick')
|
||||
const ground = useGroundRegular()
|
||||
|
||||
function fix(body: RecipeFix) {
|
||||
ground.mutate({ id: regular.id, fix: body }, { onSuccess: onClose })
|
||||
}
|
||||
|
||||
return (
|
||||
<SheetFrame title="Fix recipe" onClose={onClose}>
|
||||
<p className={styles.hint}>
|
||||
We couldn't find a recipe for {regular.name}. Pick a match below, paste a recipe link or type it in.
|
||||
</p>
|
||||
<Segmented
|
||||
label="How to fix the recipe"
|
||||
options={fixPaths}
|
||||
value={path}
|
||||
onValueChange={(next) => {
|
||||
ground.reset()
|
||||
setPath(next)
|
||||
}}
|
||||
/>
|
||||
<fieldset className={styles.lock} disabled={ground.isPending}>
|
||||
{path === 'pick' && <PickCandidate id={regular.id} onPick={(candidate_id) => fix({ candidate_id })} />}
|
||||
{path === 'link' && <PasteLink onSubmit={(recipe_url) => fix({ recipe_url })} />}
|
||||
{path === 'manual' && <ManualEntry onSubmit={(manual) => fix({ manual })} />}
|
||||
</fieldset>
|
||||
<p role="status" className={styles.status}>
|
||||
{ground.isPending && 'Finding recipe… this can take a minute.'}
|
||||
</p>
|
||||
{ground.isError && (
|
||||
<p role="alert" className={styles.problem}>
|
||||
Not fixed: {ground.error.message}
|
||||
</p>
|
||||
)}
|
||||
<Button variant="outline" disabled={ground.isPending} onClick={onEdit}>
|
||||
Edit or remove {regular.name}
|
||||
</Button>
|
||||
</SheetFrame>
|
||||
)
|
||||
}
|
||||
|
||||
function PickCandidate({ id, onPick }: { id: string; onPick: (candidateId: string) => void }) {
|
||||
const candidates = useRecipeCandidates(id)
|
||||
if (candidates.isPending) return <Skeleton className={styles.candidatesLoading} />
|
||||
if (candidates.isError) {
|
||||
return (
|
||||
<ErrorBanner onRetry={() => void candidates.refetch()}>
|
||||
Recipe matches could not load: {candidates.error.message}
|
||||
</ErrorBanner>
|
||||
)
|
||||
}
|
||||
if (candidates.data.length === 0) {
|
||||
return <p className={styles.hint}>No matches were found. Paste a recipe link or type it in.</p>
|
||||
}
|
||||
return (
|
||||
<ul className={styles.candidates} aria-label="Recipe matches">
|
||||
{candidates.data.map((candidate) => (
|
||||
<li key={candidate.candidate_id}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.candidate}
|
||||
aria-label={`Use ${candidate.title} from ${candidate.site_name}`}
|
||||
onClick={() => onPick(candidate.candidate_id)}
|
||||
>
|
||||
<Photo id={candidate.photo_id} name={candidate.title} radius="14px" sizes="56px" className={styles.candidatePhoto} />
|
||||
<span className={styles.candidateBody}>
|
||||
<span className={styles.candidateTitle}>{candidate.title}</span>
|
||||
<span className={styles.candidateSite}>{candidate.site_name}</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function PasteLink({ onSubmit }: { onSubmit: (recipeUrl: string) => void }) {
|
||||
const [link, setLink] = useState('')
|
||||
const url = link.trim()
|
||||
return (
|
||||
<form
|
||||
className={styles.form}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
if (url !== '') onSubmit(url)
|
||||
}}
|
||||
>
|
||||
<TextInput
|
||||
label="Recipe link"
|
||||
type="url"
|
||||
inputMode="url"
|
||||
placeholder="https://"
|
||||
autoComplete="off"
|
||||
value={link}
|
||||
onChange={(event) => setLink(event.target.value)}
|
||||
/>
|
||||
<Button type="submit" disabled={url === ''}>
|
||||
Use this recipe
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function ManualEntry({ onSubmit }: { onSubmit: (manual: ManualRecipe) => void }) {
|
||||
const [ingredients, setIngredients] = useState('')
|
||||
const [steps, setSteps] = useState('')
|
||||
const [minutes, setMinutes] = useState('')
|
||||
const [method, setMethod] = useState<Method | ''>('')
|
||||
const ingredientsId = useId()
|
||||
const stepsId = useId()
|
||||
const minutesError = minutesProblem(minutes)
|
||||
const ingredientLines = lines(ingredients)
|
||||
const missing = method === '' || minutes === ''
|
||||
const canSave = ingredientLines.length > 0 && !missing && minutesError === null
|
||||
|
||||
function onSave(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
if (!canSave) return
|
||||
onSubmit({ ingredients: ingredientLines, steps: lines(steps), minutes: Number(minutes), method })
|
||||
}
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={onSave}>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={ingredientsId} className={styles.label}>
|
||||
Ingredients, one per line
|
||||
</label>
|
||||
<textarea
|
||||
id={ingredientsId}
|
||||
className={styles.textarea}
|
||||
rows={5}
|
||||
value={ingredients}
|
||||
onChange={(event) => setIngredients(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.field}>
|
||||
<label htmlFor={stepsId} className={styles.label}>
|
||||
Steps, one per line
|
||||
</label>
|
||||
<textarea
|
||||
id={stepsId}
|
||||
className={styles.textarea}
|
||||
rows={5}
|
||||
value={steps}
|
||||
onChange={(event) => setSteps(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.columns}>
|
||||
<Select label="Method" value={method} onChange={(event) => setMethod(event.target.value as Method | '')}>
|
||||
<option value="">Not set</option>
|
||||
{METHODS.map((m) => (
|
||||
<option key={m} value={m}>
|
||||
{methodLabels[m]}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<TextInput
|
||||
label="Minutes"
|
||||
className={styles.paired}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
max={MAX_MINUTES}
|
||||
value={minutes}
|
||||
aria-invalid={minutesError !== null}
|
||||
onChange={(event) => setMinutes(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{minutesError && <p className={styles.problem}>{minutesError}</p>}
|
||||
{ingredientLines.length > 0 && missing && <p className={styles.problem}>Choose a method and minutes to save.</p>}
|
||||
<Button type="submit" disabled={!canSave}>
|
||||
Save recipe
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
+39
-5
@@ -37,13 +37,17 @@ export type HouseholdSettings = {
|
||||
suggestions_time: string
|
||||
chat_autosend_dow: number
|
||||
chat_autosend_time: string
|
||||
// When the household finished onboarding; null until it has, and every
|
||||
// app route sends it to /onboarding. Not editable in settings.
|
||||
onboarding_completed_at: string | null
|
||||
}
|
||||
|
||||
// HouseholdSettingsField is a household setting the settings pages edit.
|
||||
export type HouseholdSettingsField = Exclude<keyof HouseholdSettings, 'onboarding_completed_at'>
|
||||
|
||||
// HouseholdSettingsPatch is the PATCH /api/v1/settings/household body: only
|
||||
// the fields that change.
|
||||
export type HouseholdSettingsPatch = Partial<HouseholdSettings>
|
||||
|
||||
export type HouseholdSettingsField = keyof HouseholdSettings
|
||||
export type HouseholdSettingsPatch = Partial<Pick<HouseholdSettings, HouseholdSettingsField>>
|
||||
|
||||
const householdTimeFields = [
|
||||
'dinner_time',
|
||||
@@ -355,10 +359,13 @@ function parseHouseholdSettings(where: string, body: unknown): HouseholdSettings
|
||||
}
|
||||
days[field] = value
|
||||
}
|
||||
return { timezone: body.timezone, ...times, ...days }
|
||||
if (!isStringOrNull(body.onboarding_completed_at)) {
|
||||
throw new Error(`${where}: onboarding_completed_at ${JSON.stringify(body.onboarding_completed_at)} is not a time or null`)
|
||||
}
|
||||
return { timezone: body.timezone, ...times, ...days, onboarding_completed_at: body.onboarding_completed_at }
|
||||
}
|
||||
|
||||
const HOUSEHOLD_SETTINGS_KEY = ['settings', 'household'] as const
|
||||
export const HOUSEHOLD_SETTINGS_KEY = ['settings', 'household'] as const
|
||||
|
||||
export function useHouseholdSettings() {
|
||||
const { apiFetch } = useApi()
|
||||
@@ -382,6 +389,21 @@ export function useSaveHouseholdSettings() {
|
||||
})
|
||||
}
|
||||
|
||||
// useCompleteOnboarding records that the household finished onboarding: the
|
||||
// server sets onboarding_completed_at, which ends the first-run redirect.
|
||||
export function useCompleteOnboarding() {
|
||||
const { apiFetch } = useApi()
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: async () =>
|
||||
parseHouseholdSettings(
|
||||
`PATCH ${HOUSEHOLD_SETTINGS_PATH}`,
|
||||
await apiFetch<unknown>(HOUSEHOLD_SETTINGS_PATH, { method: 'PATCH', body: { onboarding_completed: true } }),
|
||||
),
|
||||
onSuccess: (settings) => queryClient.setQueryData(HOUSEHOLD_SETTINGS_KEY, settings),
|
||||
})
|
||||
}
|
||||
|
||||
// HouseholdSettingsProblems is a refused household settings save: the reason
|
||||
// for each field the server named, and any reasons that name no field.
|
||||
export type HouseholdSettingsProblems = {
|
||||
@@ -419,6 +441,18 @@ export function householdSettingsProblems(error: Error): HouseholdSettingsProble
|
||||
return problems
|
||||
}
|
||||
|
||||
// needsMoreRegulars reports whether error is the server refusing to finish
|
||||
// onboarding because the household has fewer than three Regulars
|
||||
// (internal/household MinRegulars) — the only refusal of
|
||||
// {"onboarding_completed": true}.
|
||||
export function needsMoreRegulars(error: Error): boolean {
|
||||
return (
|
||||
error instanceof ApiError &&
|
||||
error.code === 'invalid_settings' &&
|
||||
error.message.startsWith(`${invalidHouseholdPrefix}onboarding_completed: `)
|
||||
)
|
||||
}
|
||||
|
||||
// aiStatus is the AI assistant row's status line: the provider and the
|
||||
// model's display name, or that no model is chosen yet (the seed).
|
||||
export function aiStatus(settings: Pick<AISettings, 'provider' | 'model'>): string {
|
||||
|
||||
Reference in New Issue
Block a user