diff --git a/.env.example b/.env.example
index 8b81b33..13bcd95 100644
--- a/.env.example
+++ b/.env.example
@@ -5,5 +5,7 @@ API_PORT=3001
AUTH_TRUST_PROXY=false
# false for localhost/current HTTP VM; true when HTTPS is configured.
AUTH_COOKIE_SECURE=false
+# GraphiQL editor at /graphql is on unless this is false (see README).
+# API_GRAPHIQL=false
# Optional absolute directory for persisted recipe images (default: uploads/ at project root).
# UPLOAD_DIR=/var/lib/recipe-platform/uploads
diff --git a/README.md b/README.md
index 1441d45..f09b705 100644
--- a/README.md
+++ b/README.md
@@ -4,148 +4,104 @@ Prosjekt 2 i **IT2810 Webutvikling** ved NTNU, utviklet av gruppe T31.
Recipe Platform er en responsiv oppskriftsapplikasjon hvor brukere kan utforske offentlige oppskrifter, søke, filtrere og sortere resultater, lagre oppskrifter i sin egen kokebok og opprette egne oppskrifter.
-## Status nå
+**[Åpne demoen](http://it2810-31.idi.ntnu.no/project2/)** · **[Kjør lokalt](#kom-i-gang)** · **[Dokumentasjon](#dokumentasjon)**
-- Registrering, innlogging og utlogging bruker GraphQL, PostgreSQL og HttpOnly-cookies.
-- Explore, My Cookbook og oppskriftsdetaljer henter data fra API-et.
-- Oppretting, redigering, sletting, lagring i kokebok og vurderinger lagres i databasen.
-- Søk i tittel/beskrivelse, kategori- og tidsfilter samt paginering utføres i backend. Resultatene kan sorteres med nyeste først, kortest tilberedningstid eller høyest vurdering.
-- Bildeopplasting støtter JPG, PNG og WebP, med tilgangskontroll og opprydding.
+Demoen kan kreve [NTNU-nett eller VPN](https://i.ntnu.no/wiki/-/wiki/Norsk/Installere+VPN). Hvis du registrerer en egen konto, bruk et testpassord siden demoen bruker HTTP. HTTPS er avklart med foreleser for innleveringen og må på plass før løsningen brukes med ekte brukerdata.
-Applikasjonen bruker ikke lenger prototypeoppskriftene som datakilde. Testene bruker egne fixtures. Valgfri seed oppretter 51 demooppskrifter inkludert bilder; et større eksternt datasett er ikke importert. Se [kjente begrensninger](#kjente-begrensninger).
+## Testbruker for evaluering
-## Oppfølging av tilbakemeldinger i innlevering 3
+Du kan utforske offentlige oppskrifter uten å logge inn. Bruk denne kontoen på [demoen](http://it2810-31.idi.ntnu.no/project2/login) for å teste lagrede oppskrifter, egne oppskrifter og kontofunksjoner.
-I arbeidet med innlevering 3 har vi gått grundig gjennom alle tilbakemeldingene fra de andre gruppene. Vi har vurdert kommentarene, undersøkt de rapporterte problemene og forbedret prosjektet på bakgrunn av dette.
+- **Navn:** Food Lover
+- **E-post:** [test@ntnu.no](mailto:test@ntnu.no)
+- **Passord:** `FoodLover2026!`
-Arbeidet har blant annet ført til:
+Kontoen har allerede lagrede favoritter og egne oppskrifter, slik at du kan prøve **My Cookbook** med en gang.
-- Verifisert tastaturbruk for søk, filtre og sortering på mobil og desktop.
-- Rettet ikonstørrelser og kontrollert at ikonene holder seg innenfor knappene.
-- Redusert datamengden i oppskriftslistene ved å hente detaljinnhold først når en oppskrift åpnes.
-- Lagt til kortlivet caching av oppskriftsdata for å redusere gjentatte API-kall.
-- Utvidet sorteringen med kortest tilberedningstid og høyest vurdering.
-- Utvidet automatiserte tester og dokumentert ytelsestiltak og kjente begrensninger.
+## Innhold
-HTTPS er avklart med foreleser og er ikke et krav for denne innleveringen. Den publiserte løsningen bruker derfor fortsatt HTTP. Dette innebærer at innloggingsdata ikke er kryptert under transport, og løsningen bør bare brukes med testpassord. HTTPS må på plass før løsningen tas i bruk med ekte brukerdata.
-
-Ikke alle forbedringsforslag er implementert. Gjenstående punkter og mulige videre forbedringer er beskrevet under [kjente begrensninger](#kjente-begrensninger) og i dokumentasjonen om [dataoverføring og bildekilder](docs/performance-and-images.md).
-
-## Lenker
-
-- **Repository:** [https://git.ntnu.no/IT2810-H26/T31-Project-2/](https://git.ntnu.no/IT2810-H26/T31-Project-2/)
-- **Publisert applikasjon:** [http://it2810-31.idi.ntnu.no/project2/](http://it2810-31.idi.ntnu.no/project2/)
-
-> **Merk:** Den publiserte applikasjonen kan kreve tilkobling til NTNUs nettverk eller [NTNU VPN](https://i.ntnu.no/wiki/-/wiki/Norsk/Installere+VPN).
+- **Prøv appen:** [Brukerreise og hovedsider](#konsept) · [Demokontoer lokalt](#demodata-og-lokal-innlogging)
+- **Kjør lokalt:** [Docker](#kjør-lokalt-med-docker) · [Uten Docker](#kjør-lokalt-uten-docker) · [Kommandoer](#nyttige-kommandoer)
+- **Vurder løsningen:** [Arkitektur](#arkitektur) · [Tilgjengelighet](#tilgjengelighet) · [Bærekraft](#responsivt-og-bærekraftig-design) · [Testing](#testing-og-kvalitetssikring) · [KI-bruk](#bruk-av-kunstig-intelligens)
+- **Finn detaljer:** [Dokumentasjon](#dokumentasjon) · [Leveranseoppfølging](#oppfølging-til-endelig-innlevering) · [Kjente begrensninger](#kjente-begrensninger)
## Kom i gang
-Uten Docker krever prosjektet Node.js **24.x** og npm **11.x**. `.nvmrc`, `.node-version` og Docker-oppsettet angir den felles referanseversjonen **24.21.0**.
+Klon prosjektet med en [registrert SSH-nøkkel](https://git.ntnu.no/settings/keys). Hvis du bruker HTTPS, finner du kloningsadressen på [prosjektsiden](https://git.ntnu.no/IT2810-H26/T31-Project-2/).
```bash
git clone git@git.ntnu.no:IT2810-H26/T31-Project-2.git
cd T31-Project-2
-git switch dev
-npm ci
```
-Registrer SSH-nøkkelen din på [git.ntnu.no](https://git.ntnu.no/settings/keys) før kloning. Med `nvm` kan riktig Node-versjon velges slik:
-
-```bash
-nvm install
-nvm use
-```
+`main` er leveranse- og deploybranchen. Bruk `dev` for videre utvikling. Den kan inneholde endringer som ennå ikke er publisert på VM-en.
### Kjør lokalt med Docker
-Den enkleste måten å kjøre hele prosjektet lokalt på er med Docker Compose. Dette starter både applikasjonen og en PostgreSQL-database, slik at blant annet innlogging og registrering fungerer uten at PostgreSQL må installeres lokalt.
-
-Docker-oppsettet er **kun ment for lokal utvikling**. Produksjonsmiljøet på den virtuelle maskinen bruker ikke Docker.
-
-Fra prosjektets rotmappe:
+Docker Compose starter React-klienten, GraphQL API-et og PostgreSQL og kjører databasemigrasjoner. Oppsettet brukes lokalt.
```bash
docker compose -f compose.dev.yaml up --build
```
-Dette:
+Åpne [http://localhost:5173/project2/](http://localhost:5173/project2/).
-- bygger utviklingscontaineren fra `Dockerfile.dev`
-- starter PostgreSQL
-- kjører databasemigrasjoner
-- starter GraphQL API-et
-- starter Vite-utviklingsserveren
+#### Fyll databasen med demodata
-Frontend blir tilgjengelig på:
+En ny database er tom: Docker-oppstarten kjører migrasjoner, men legger ikke inn oppskrifter. Når appen har startet, åpne en ny terminal i prosjektroten.
-```text
-http://localhost:5173/project2/
-```
+Opprett `.env` i prosjektroten hvis filen ikke finnes. Legg til en linje med `SEED_PASSWORD=` etterfulgt av et selvvalgt testpassord på minst 12 tegn. Ikke overskriv en eksisterende `.env` eller legg filen i Git. Compose gir containeren riktig `DATABASE_URL`; du trenger ikke sette den for Docker-seeding.
-Etter første bygg kan prosjektet normalt startes med:
+Kjør følgende i Linux/macOS eller PowerShell:
```bash
-docker compose -f compose.dev.yaml up
+docker compose -f compose.dev.yaml exec app npm run db:seed
```
-Containerne stoppes med:
-
-```bash
-docker compose -f compose.dev.yaml down
-```
+Seed-kommandoen leser `.env` fra den monterte prosjektmappen og skriver bildene til containerens vedvarende bildevolum. Oppdater Explore etterpå for å se de offentlige demooppskriftene. Se [demodata og lokal innlogging](#demodata-og-lokal-innlogging) for kontoer og hva gjentatt seeding gjør.
-Databaseinnholdet beholdes mellom omstarter. For å slette den lokale databasen og starte helt på nytt:
-
-```bash
-docker compose -f compose.dev.yaml down -v
-docker compose -f compose.dev.yaml up --build
-```
-
-Docker-oppsettet bruker `Dockerfile.dev` og `compose.dev.yaml` i prosjektets rotmappe.
+Stopp miljøet med `docker compose -f compose.dev.yaml down`. Database og bilder beholdes ved omstart. Kommandoen `docker compose -f compose.dev.yaml down -v` sletter begge deler.
### Kjør lokalt uten Docker
-For å kjøre hele prosjektet uten Docker må PostgreSQL være installert og kjøre lokalt.
+Du trenger PostgreSQL, Node.js **24 eller nyere** og npm **11 eller nyere**. Bruk gjerne versjonen fra `.nvmrc` med `nvm install` og `nvm use`.
-Kopier først miljøvariablene:
+Kopier `.env.example` til `.env` med `cp .env.example .env` eller `Copy-Item .env.example .env` i PowerShell. Fyll inn lokale databaseverdier, installer avhengighetene og kjør migrasjonene.
```bash
-cp .env.example .env
+npm ci
+npm run db:migrate
```
-På Windows PowerShell:
+#### Fyll databasen med demodata
-```powershell
-Copy-Item .env.example .env
-```
-
-Fyll deretter inn riktige lokale databaseverdier i `.env`, og kjør databasemigrasjonene:
+Legg til en linje i den lokale `.env`-filen med `SEED_PASSWORD=` etterfulgt av et selvvalgt testpassord på minst 12 tegn. Kontroller at `DATABASE_URL` peker til den lokale utviklingsdatabasen. Kjør deretter seed fra prosjektroten.
```bash
-npm run db:migrate
+npm run db:seed
```
-Start deretter frontend og API:
+Bruk `npm.cmd run db:seed` i PowerShell hvis kjøring av `npm.ps1` er blokkert. Seed og API må bruke samme `UPLOAD_DIR` for at bildene skal vises. Standard er `uploads/` i prosjektroten.
+
+Start deretter klient og API, med eller uten demodata.
```bash
npm run dev
```
-Frontend blir tilgjengelig på:
+Åpne [http://localhost:5173/project2/](http://localhost:5173/project2/). Du kan starte bare klienten med `npm run dev:web`. Innlogging, kokebok og oppskriftsdata krever API og PostgreSQL.
-```text
-http://127.0.0.1:5173/project2/
-```
+### Demodata og lokal innlogging
-Frontend-serveren kan også startes separat (API og PostgreSQL kreves for data):
+Seeden legger inn 51 oppskrifter med lokale WebP-bilder, inkludert offentlige og private oppskrifter, og vurderinger fra fire demobrukere. Explore viser de offentlige oppskriftene; de private finnes i eierens kokebok.
-```bash
-npm run dev:web
-```
+Etter første seed kan du logge inn lokalt som `demo@example.invalid` med passordet du valgte i `SEED_PASSWORD`. Denne kontoen eier demooppskriftene. For å teste lagring og vurdering av dem, registrer en egen testkonto: brukere kan ikke lagre eller vurdere sine egne oppskrifter.
-Oppskriftsvisning, cookbook og innlogging krever både API-et og PostgreSQL. Se [frontend integration checklist](docs/frontend-integration.md).
+Seeden kjøres eksplisitt, ikke ved vanlig oppstart eller deploy. Gjentatt seeding oppdaterer demooppskriftenes innhold og bildefiler, men endrer ikke eksisterende kontopassord. Den kan derfor overskrive manuelle endringer i demooppskriftene. Flere detaljer finnes i [API-dokumentasjonen](docs/recipe-api.md#demoseed).
-Ikke legg `.env`, passord, tokens eller andre hemmeligheter i Git.
+### Opprett egen testkonto på demoen
+
+Hvis du vil teste registrering eller bruke en egen konto, åpne [registrering på VM](http://it2810-31.idi.ntnu.no/project2/register). Deretter kan du teste **My Cookbook**, lagre og vurdere offentlige oppskrifter og opprette, redigere og slette egne oppskrifter. Bruk et eget testpassord siden VM-en bruker HTTP. Lokal `SEED_PASSWORD` gjelder bare den databasen du seedet; den gir ikke tilgang til demokontoen på VM-en.
## Autentisering
@@ -159,30 +115,26 @@ Cookie-autentiserte POST-forespørsler krever JSON og `X-Requested-With: recipe-
`/cookbook`, `/recipes/new` og redigering krever en validert sesjon. Ved oppdatering venter klienten på sesjonsgjenoppretting før eventuell videresending til innlogging. Etter innlogging returneres brukeren til den forespurte ruten. API-et håndhever autentisering, eierskap og synlighet uavhengig av klienten.
-Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering, feilkoder og rate limiting bak Apache.
-
-## Database
+Se [auth-forbedringer](docs/auth-improvements.md) for delt Zod-validering, feilkoder og trafikkbegrensning bak Apache.
-Se [Recipe API og Delivery 2-status](docs/recipe-api.md) for CRUD-kontrakter,
-cookie-autentisering, Zod-validering, seed og API-integrasjonstester.
+### GraphiQL
-Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen brukes av autentisering, oppskrifts-CRUD, kokebok og vurderinger.
-
-Oppsett for CI-testdatabase, migrasjoner og utrulling er samlet i [drift og testing](docs/operations.md).
+API-et viser GraphiQL, en interaktiv spørreeditor, på `/project2/api/graphql` når adressen åpnes i nettleseren. Den er bevisst tilgjengelig slik at faglærer og medstudenter kan utforske skjemaet og prøve spørringer. GraphiQL gir ingen ekstra tilgang: alle resolvere håndhever innlogging, eierskap og synlighet, og POST-forespørsler krever samme `X-Requested-With`-header som klienten (GraphiQL sender den automatisk). Sett `API_GRAPHIQL=false` for å slå den av.
## Nyttige kommandoer
-| Kommando | Bruk |
-| ---------------------- | ------------------------------------------- |
-| `npm run dev` | Start utviklingsmiljøet |
-| `npm run dev:web` | Start bare React-klienten |
-| `npm run dev:api` | Start bare API-et |
-| `npm run typecheck` | Kontroller TypeScript i frontend og backend |
-| `npm run lint` | Kjør ESLint |
-| `npm run format` | Formater kode med Prettier |
-| `npm run format:check` | Kontroller formatering uten å endre filer |
-| `npm run test` | Kjør Vitest-testene |
-| `npm run build` | Bygg workspaces for produksjon |
+| Kommando | Bruk |
+| --------------------------------- | -------------------------------------------------------- |
+| `npm run dev` | Start utviklingsmiljøet |
+| `npm run dev:web` | Start bare React-klienten |
+| `npm run dev:api` | Start bare API-et |
+| `npm run typecheck` | Kontroller TypeScript i frontend og backend |
+| `npm run lint` | Kjør ESLint |
+| `npm run format` | Formater kode med Prettier |
+| `npm run format:check` | Kontroller formatering uten å endre filer |
+| `npm run test` | Kjør Vitest-testene |
+| `npm run build` | Bygg workspaces for produksjon |
+| `npm run db:seed:large -- 100000` | Last 100 000 testoppskrifter (`-- --remove` fjerner dem) |
Før en Pull Request bør minst følgende kjøres:
@@ -195,51 +147,59 @@ npm run test:e2e
## Konsept
-Applikasjonens viktigste brukerflyt er:
+Explore viser offentlige oppskrifter. Innloggede brukere kan lagre og vurdere andres oppskrifter og opprette, redigere eller slette sine egne. Endringene lagres i databasen.
+
+En typisk brukerreise:
1. Utforsk offentlige oppskrifter.
2. Søk, filtrer, sorter og bla i resultatene.
-3. Åpne en oppskrift og se ingredienser og fremgangsmåte.
+3. Åpne en oppskrift, juster antall porsjoner og se ingredienser og fremgangsmåte.
4. Lagre en offentlig oppskrift i **My Cookbook**.
5. Opprett og administrer egne oppskrifter.
Oppskrifter kan være offentlige eller private. Offentlige oppskrifter finnes gjennom **Explore**, mens private oppskrifter bare skal være tilgjengelige i eierens kokebok.
-### Hovedsider
+### Søk, filtrering og sortering
-| Rute | Formål |
-| -------------- | -------------------------------------------------- |
-| `/` | Explore: søkbar katalog med offentlige oppskrifter |
-| `/cookbook` | My Cookbook: lagrede og egenproduserte oppskrifter |
-| `/recipes/:id` | Detaljvisning av én oppskrift |
-| `/recipes/new` | Skjema for å opprette en oppskrift |
-| `/login` | Innlogging via GraphQL |
-| `/register` | Registrering via GraphQL |
+Søket oppdateres etter 300 ms uten ny inntasting og dekker titler, beskrivelser, ingredienser og tagger. Alle søkeordene må gi treff. API-et filtrerer på kategori og tid før resultatene deles inn i sider.
-### Viktige brukerreiser
+Sorteringen tilbyr nyeste først, kortest samlet tilberedningstid og høyest vurdering. Høyest vurdering bruker et uvektet gjennomsnitt. Antall vurderinger vises sammen med gjennomsnittet.
-```mermaid
-flowchart TD
- Explore["Explore"] --> Search["Søk, filtrer og sorter"]
- Search --> Detail["Recipe Detail"]
- Detail --> Save["Save to Cookbook"]
- Save --> Cookbook["My Cookbook"]
- Cookbook --> Manage["Åpne eller redigere"]
-```
-
-## Leveransehistorikk
+### Hovedsider
-Beskrivelsene av første og andre underveislevering er samlet i [leveransehistorikken](docs/delivery-history.md).
+| Rute | Formål |
+| ------------------- | -------------------------------------------------- |
+| `/` | Explore: søkbar katalog med offentlige oppskrifter |
+| `/cookbook` | My Cookbook: lagrede og egenproduserte oppskrifter |
+| `/recipes/:id` | Detaljvisning av én oppskrift |
+| `/recipes/new` | Skjema for å opprette en oppskrift |
+| `/recipes/:id/edit` | Redigering av egen oppskrift |
+| `/login` | Innlogging via GraphQL |
+| `/register` | Registrering via GraphQL |
+
+Rutene har prefikset `/project2` både lokalt og på VM-en. Søk, filtre, sortering og sidetall beholdes i URL-en.
+
+## Dokumentasjon
+
+| Dokument | Innhold |
+| --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
+| [Arkitektur](docs/architecture.md) og [databasemodell](docs/database-model.md) | Mapper, ansvarsdeling, genererte typer, relasjoner og integritetsregler. |
+| [Recipe API](docs/recipe-api.md) og [frontendintegrasjon](docs/frontend-integration.md) | API-kontrakt, tilgang, input og kobling til brukergrensesnittet. |
+| [Drift og testing](docs/operations.md) | Miljøvariabler, CI, migrasjoner og deploy. |
+| [Lokal testguide](docs/review-test-guide.md) | Manuelle scenarier, Docker og integrasjonstester. |
+| [Dataoverføring og bilder](docs/performance-and-images.md) | Søk, cache, bildevarianter, målinger og avveininger. |
+| [Bildekreditering](docs/CREDITS.md) | Fotosider, fotografer og illustrasjonenes opphav. |
+| [Leveransehistorikk](docs/delivery-history.md) | Tidligere prototype og underveisleveranser. Historikken beskriver ikke dagens funksjonalitet. |
## Arkitektur
```mermaid
flowchart TD
- UI["React-grensesnitt"] --> State["Klientstate"]
- State --> Mock["Mockdata - Delivery 1"]
- State --> Client["Typet GraphQL-klient"]
- Client --> API["Node og TypeScript GraphQL API"]
- API --> DB["Database på NTNU VM"]
+ UI["React-grensesnitt"] --> Client["Typet GraphQL-klient"]
+ Client --> API["Node.js / GraphQL Yoga"]
+ UI -->|"Bildeopplasting og bilder"| API
+ API --> DB[("PostgreSQL")]
+ API --> Files["Bildefiler i UPLOAD_DIR"]
```
Søk, filtrering og sortering holdes adskilt fra presentasjonskomponentene. Søk, filtrering og sortering utføres i databasen før paginering. Se [arkitektur og prosjektstruktur](docs/architecture.md) for ansvarsfordeling og tekniske valg.
@@ -250,24 +210,24 @@ Datamodellen omfatter:
- `Recipe`: tittel, beskrivelse, forfatter, synlighet, bilde, tid, porsjoner, kategorier, ingredienser, steg og vurdering
- `Ingredient`: navn, mengde, enhet og valgfri merknad
-- `User`: identifikator, visningsnavn og valgfri profilinformasjon
+- `User`: identifikator (`id`), visningsnavn (`name`) og e-post (`email`)
- `Rating`: bruker, oppskrift og poengsum
- lagrede oppskrifter og eierskap
- søke-, filter-, sorterings- og pagineringsstate
-## Teknologi
+### Teknologivalg og begrunnelse
-- React og TypeScript
-- Vite
-- React Router
-- Zustand for delt frontend-state
-- Node.js og TypeScript i backend
-- GraphQL
-- backend-database installert direkte på gruppens virtuelle maskin
-- plain CSS med designvariabler og responsive layouts
-- Vitest og Testing Library
-- ESLint og Prettier
-- Playwright for ende-til-ende-tester
+| Valg | Hvordan det brukes og hvorfor det passer |
+| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| React, TypeScript og Vite | Gjenbrukbare komponenter, streng typekontroll og produksjonsbygg med egne filer for sider som lastes ved behov. |
+| GraphQL Yoga og genererte typer | Ett skjema knytter klientoperasjoner og resolvere sammen. Lister henter kortdata, mens detaljer har egen spørring. Yoga integrerer sesjoner, forespørselsgrenser og bilderuting i API-et. |
+| Zustand og en avgrenset cache | Zustand holder sesjonsstatus; `useRecipeQuery` håndterer lesing, avbrudd og cache. Skjemaer bruker lokal React-state. Dette dekker dagens dataflyt uten Apollo/urql, men gruppen må selv vedlikeholde cachetømming og oppfrisking. |
+| PostgreSQL, Drizzle og `pg` | Relasjoner og integritetsregler håndheves i databasen. Drizzle beskriver skjema og migrasjoner; parameterisert SQL gir kontroll over søk, tilgang og transaksjoner. |
+| React Router og paginering | Sider, søk og filtre kan åpnes direkte og gjenfinnes med nettleserhistorikken. Paginering gir en eksplisitt resultatposisjon og begrenser data per kall. Seks kort passer gridets tre, to eller én kolonne; flere resultater krever flere sidebytter. |
+| Native HTML og eget CSS-system | `Select` bygger på ``, og dialoger på ``. Nettleserens kontrolloppførsel kombineres med felles etiketter, fokus og designvariabler fremfor et separat UI-rammeverk. |
+| Zod og Argon2 | Zod validerer input, med delte regler der klient og API trenger samme grenser. Argon2 hasher passord før lagring; sesjoner bruker HttpOnly-cookies. |
+| `react-easy-crop` og `sharp` | Bibliotekene håndterer henholdsvis beskjæring og bildebehandling. API-et normaliserer filene og lager størrelsesvarianter uavhengig av klientens behandling. |
+| Vitest, Testing Library og Playwright | Tester dekker funksjoner og komponenter, mens nettlesertester kontrollerer sammensatte brukerreiser. ESLint og Prettier supplerer med statiske regler og formatering. |
Se [arkitektur og prosjektstruktur](docs/architecture.md) for mapper, genererte typer og valget av SQL sammen med Drizzle.
@@ -283,20 +243,25 @@ Prosjektet utvikles med universell utforming som en del av komponentdesignet:
- meningsfull alternativtekst for oppskriftsbilder
- valgte tilstander og feilmeldinger som ikke formidles med farge alene
- tastaturtesting av de viktigste brukerreisene
+- hopp til hovedinnhold, sidetitler og fokusflytting ved sidenavigering
+
+Playwright inkluderer axe-kontroller av utvalgte sider på mobil og desktop. Automatiserte kontroller erstatter ikke manuell testing med skjermleser, zoom og ulike innholdstilstander; fullt WCAG-samsvar er ikke dokumentert.
## Responsivt og bærekraftig design
-Applikasjonen skal fungere på både mobil og desktop. Oppskriftsgridet går fra flere kolonner på store skjermer til én kolonne på små skjermer. Filter- og sorteringsvalg skal være store nok til berøring og ikke skape horisontal scrolling.
+Grensesnittet bruker kremfarget bakgrunn, hvite kort, mørk tekst og oransje aksenter. Systemfonter og felles CSS-variabler styrer typografi og avstander. Oppskriftsgridet går fra tre kolonner til to og én på mindre skjermer; filtre og sortering vises i dialoger på mobil.
-Vi arbeider for en mer bærekraftig løsning gjennom:
+Konkrete tiltak for å begrense lasting og dataoverføring:
-- paginering eller dynamisk lasting i stedet for å sende hele datasettet til klienten
+- paginering med seks oppskrifter per side
- serverbasert søk, filtrering og sortering
-- optimaliserte bilder i passende størrelser
-- gjenbrukbare komponenter og begrenset unødvendig JavaScript
+- WebP-varianter, `srcset`/`sizes` og lazy loading av kortbilder
+- gjenbrukbare komponenter og utsatt lasting av andre hovedsider enn Explore
- kortlivet minnecache for oppskriftslesinger og mindre listedata
- færre unødvendige nettverkskall
-- enkel og effektiv visuell utforming
+- systemfonter uten eksterne fontnedlastinger
+
+Tiltakene begrenser bestemte typer ressursbruk. Energibruk og utslipp er ikke målt.
Oppskriftsbildene i seed-datasettet er hentet fra [Pexels](https://www.pexels.com/). Se [dataoverføring og bildekilder](docs/performance-and-images.md) for konkrete filstørrelser, caching og kildeopplysninger. Bruk bare testpassord frem til HTTPS er verifisert.
@@ -310,7 +275,7 @@ Enhetstestene bruker kontrollerte testdata. Database- og API-integrasjonstestene
- validering i Add Recipe
- delte UI-komponenter
-I tillegg gjennomføres manuelle kontroller av:
+Automatiske tester bør suppleres med manuelle kontroller av:
- de viktigste brukerreisene
- direkte lasting av alle ruter
@@ -319,14 +284,7 @@ I tillegg gjennomføres manuelle kontroller av:
- konsollfeil og advarsler
- tomme tilstander og feiltilstander
-## Roadmap
-
-| Leveranse | Produktmål | Teknisk mål |
-| ------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------- |
-| **1 - Prototype** | Mockoppskrifter, hovedsider og sentrale brukerflyter | Gjenbrukbare komponenter, routing, state, tilgjengelighet og testmønstre |
-| **2 - Klient og backend** | Reelle data og persistent brukergenerert innhold | GraphQL-backend og database på VM, queries/mutations og eierskap |
-| **3 - Beta** | Komplett søk, filtrering, sortering og paginering | Backendoperasjoner, indeksering, feilhåndtering, skalerbarhet og bærekraft |
-| **4 - Ferdig prosjekt** | Polert og helhetlig produkt | Komponent-, API- og ende-til-ende-testing, dokumentasjon og deploykontroll |
+Testlisten beskriver dekning og anbefalt kontroll, ikke et løfte om beståtte tester. Registrer utførte kontroller og eventuelle feil i den aktuelle PR-en.
## Brancher, commits og Pull Requests
@@ -343,11 +301,11 @@ git commit -m "feature(explore): add recipe search"
git push -u origin feature/recipe-search
```
-Navnekonvensjon:
+Navngivingen har variert gjennom prosjektet, og ikke alle eksisterende brancher, commits og PR-er følger samme mønster. For nye endringer anbefaler vi følgende konvensjon for å gjøre historikken lettere å lese:
- branch: `/-`
- commit og PR: `(): `
-- vanlige typer: `feature`, `fix`, `test`, `comment` og `chore`
+- typer i bruk inkluderer `feature`/`feat`, `fix`, `docs`, `test`, `comment` og `chore`
Eksempler:
@@ -358,6 +316,8 @@ Eksempler:
| `fix/api-copy-schema` | `fix(api): use cross-platform schema copy` |
| `test/recipe-card-actions` | `test(recipe): cover card actions` |
+Ved squash-merge bør den endelige commit-tittelen også følge det anbefalte mønsteret og beskrive endringen konkret.
+
Velg eller opprett et issue før arbeidet starter. PR-en skal oppsummere endringen, liste kommandoene som faktisk er kjørt, forklare krav og KI-bruk og be om review fra et annet gruppemedlem. Bruk for eksempel `Closes #17` for å koble PR-en til et issue.
- Ikke push direkte til `main`.
@@ -374,9 +334,19 @@ Velg eller opprett et issue før arbeidet starter. PR-en skal oppsummere endring
- Eksponer ikke detaljerte interne feilmeldinger til sluttbrukeren.
- Hold avhengigheter oppdatert og vurder sikkerhetsvarsler før oppgradering.
+## Oppfølging til endelig innlevering
+
+- **Brukergrensesnitt:** Rettet ikonstørrelser og forbedret tastaturnavigasjon, sidetitler og fokus ved navigering.
+- **Data og ytelse:** Innført avgrenset minnecache, mindre listedata, WebP-varianter og utsatt lasting av sider.
+- **Søk og sortering:** Innført ordsøk og indeksert sortering, målt lokalt med 100 000 genererte oppskrifter.
+- **Redigering:** Lagt til lokale utkast, varsel ved ulagrede endringer og versjonskontroll ved lagring.
+- **API og tester:** Lagt til ressursgrenser, samlet innsetting av ingredienser og steg og flere nettleserscenarioer mot ekte API.
+
+Se [leveransehistorikken](docs/delivery-history.md) og [kjente begrensninger](#kjente-begrensninger).
+
## Bruk av kunstig intelligens
-Gruppen har brukt KI-verktøy som støtte gjennom utviklingsprosessen. Dette har blant annet omfattet:
+Alle tre i gruppen har brukt KI-verktøy som støtte gjennom utviklingsprosessen.
- idéutvikling og konkretisering av konsept, brukerflyt og leveranseplan
- oppdeling av arbeid i issues, mindre oppgaver og forslag til implementeringsrekkefølge
@@ -387,24 +357,55 @@ Gruppen har brukt KI-verktøy som støtte gjennom utviklingsprosessen. Dette har
- gjennomgang og forbedring av dokumentasjon, issues, commit-meldinger og Pull Request-beskrivelser
- vurdering av hvordan mockimplementasjonen i Delivery 1 kan struktureres slik at den senere kan erstattes av klient-server- og GraphQL-funksjonalitet
+### Claude Code i utviklingsarbeidet
+
+Enkelte gruppemedlem brukte Claude Code fra Anthropic til å gjennomgå og skrive kode og til å utforme og kjøre tester fram mot sluttleveringen. Det var hovedsakelig Claude Opus 5.5 og enkelte ganger agenter med Claude Sonnet 5.5 som ble brukt. I flere PR-er sto agenten for implementasjon og testkjøring. Bidraget er oppgitt under «AI usage» i de aktuelle PR-beskrivelsene.
+
+Tilbakemeldinger fra gruppemedlemmer og fagfellevurderinger ga grunnlag for oppgavene. Issue-beskrivelser, akseptansekriterier og relevant kildekode ga agenten kontekst, og kommentarer i PR-ene førte til nye endringer.
+
+- **Tilgjengelighet.** Claude Code bidro til å forbedre fargekontrasten og gjøre det mulig å flytte ingredienser og steg med tastaturet. PR-ene dokumenterer axe-kontroller ved mobil- og desktopbredde, og tester av fokus og annonsering etter flytting. [PR #86](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/86), [PR #114](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/114)
+- **Oppskriftsredigering.** Claude Code bidro til å bevare lokale utkast, varsle om ulagrede endringer og oppdage lagringskonflikter. Testene sjekket at et utkast kunne gjenopprettes, og at både den lagrede oppskriften og innholdet i skjemaet ble bevart ved en lagringskonflikt. [PR #115](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/115), [PR #124](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/124)
+- **Søk og ytelse.** Claude Code bidro til indeksert ordsøk i PostgreSQL og WebP-varianter for oppskriftsbilder. Søket ble målt lokalt med 100 000 oppskrifter, og API-tester sjekket blant annet at et bilde ble utilgjengelig når oppskriften ble gjort privat. Etter kodegjennomgang ble søke- og vurderingsoppdateringene også testet med samtidige databaseskrivinger. [PR #96](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/96), [PR #98](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/98)
+- **API og nettlesertester.** Claude Code bidro til å innføre ressursgrenser i GraphQL-API-et, samkjøre valideringen i API-et og skjemaet og dele én lang Playwright-test opp i uavhengige scenarioer mot ekte API og database. [PR #122](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/122), [PR #123](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/123), [PR #118](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/118)
+
+### Eksempler med Codex og ChatGPT
+
+| Verktøy | Oppgave og bidrag | Kontroll og avgrensning |
+| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| ChatGPT | Generering av reservebildet for oppskrifter og illustrasjonen på 404-siden. | Filnavn og opphav er oppgitt i [bildekrediteringen](docs/CREDITS.md). Oppskriftsfotografiene har egne Pexels-kilder. |
+| Codex | Forslag til seed-instruksjoner og demotilgang i [#71](https://git.ntnu.no/IT2810-H26/T31-Project-2/issues/71), med endringene i [PR #126](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/126). | Instruksjonene ble kontrollert mot seed-koden, pakkeskriptene og Compose-oppsettet. Lenker og bildefiler ble sjekket. Full oppstart fra en fersk klone ble ikke testet. |
+| Codex | Forslag til API-kommentarer og tydeligere interne hjelpernavn i [#78](https://git.ntnu.no/IT2810-H26/T31-Project-2/issues/78), med endringene i [PR #128](https://git.ntnu.no/IT2810-H26/T31-Project-2/pull/128). | Kodestrukturen ble sammenlignet før og etter navneendringene, og typekontroll, lint og tester ble kjørt. API-testfeil ble også reprodusert på uendret `dev` og dokumentert i PR-en. |
+
+### Felles kontekst og kvalitetssikring
+
+I Codex-oppgavene ble issue-beskrivelsen brukt som spesifikasjon, sammen med den aktuelle kildekoden og prosjektets eksisterende dokumentasjon. Oppgavene ble avgrenset til bestemte filer og formål, og gruppen godkjente endringene og commitmeldingen før commit og push.
+
+To instruksjonsfiler beskriver prosjektets felles regler for UI-arbeid:
+
+- [UI-komponenter](apps/web/src/components/ui/SKILL.md): gjenbruk, native HTML-elementer, tilgjengelighet, komponentansvar og relevante tester.
+- [Stilsystem](apps/web/src/styles/style_guide/SKILL.md): designvariabler, CSS-lag, importrekkefølge, avstander og andre stilkonvensjoner.
+
+Filene ligger ved koden de beskriver og kan gi både utviklere og KI-verktøy felles kontekst. De er ikke en logg over hvilke prompter som ble brukt eller en garanti for at alle forslag følger reglene.
+
KI-genererte forslag brukes som utgangspunkt og utviklingsstøtte, ikke som ferdige løsninger som tas inn ukritisk. Gruppen gjennomgår og tilpasser forslagene til prosjektets krav, eksisterende arkitektur, komponentbibliotek og kodestil.
Generert kode og dokumentasjon blir kontrollert gjennom kodegjennomgang og manuell inspeksjon. Funksjonalitet blir i tillegg verifisert gjennom manuell testing, responsive kontroller og prosjektets automatiserte kvalitetssjekker, blant annet formattering, linting, typekontroll, tester og produksjonsbygg.
+Hvilke kontroller som faktisk er kjørt, og eventuelle feil eller begrensninger, oppgis i den enkelte PR-en. KI kan hjelpe med å finne løsninger og forklare feil, men kan også foreslå feilaktige beskrivelser eller tester som gjentar samme feil som løsningen. Derfor må forslag vurderes mot krav og faktisk oppførsel; gruppen har ansvar for det som leveres.
+
KI-verktøy får ikke ekte passord, tokens, personopplysninger eller andre hemmeligheter.
## Kjente begrensninger
-- Søk dekker tittel og beskrivelse; ingrediens- og tagsøk er videre arbeid.
-- Trending er ikke implementert. Høyest vurdering bruker gjennomsnittet uten vekting etter antall stemmer.
-- Utkast beholdes bare i skjemaet og overlever ikke navigering eller oppdatering.
-- Seed inneholder 51 demooppskrifter og demonstrerer ikke ytelse med store datamengder.
+- Utkast lagres bare i nettleseren (localStorage) per bruker og oppskrift, ikke på serveren, og følger derfor ikke brukeren til en annen enhet. De slettes ved utlogging.
+- Ytelse er målt lokalt med 100 000 genererte oppskrifter (`npm run db:seed:large`) i en egen testdatabase, ikke på VM-en. Se [søk og skalerbarhet](docs/performance-and-images.md#søk-og-skalerbarhet).
+- Treff inni et ord er begrenset til oppskriftstitler og søkeord på minst tre tegn. «Cake» finner «cupcakes» etter treff på ord som begynner med «cake».
- Bildeoperasjoner bruker en global lås for korrekt koordinering. Dette begrenser samtidige skriveoperasjoner.
- Bildekvoter har faste grenser. Registrering har IP-begrensning, men flere kontoer kan fortsatt omgå brukerkvotene. Refererte bilder teller mot totalgrensen og slettes ikke av cleanup.
- VM-en bruker HTTP. Foreleser har avklart at HTTPS ikke er et krav for denne innleveringen, men det er nødvendig for å beskytte innlogging under transport. Bruk bare testpassord.
## Gruppe og samarbeid
-Prosjektet utvikles av IT2810-H26 gruppe T31:
+Prosjektet utvikles av tre medlemmer i IT2810-H26 gruppe T31.
Arbeidet koordineres gjennom issues, prosjektboard, feature-brancher, Pull Requests og kodegjennomgang i [prosjektrepoet](https://git.ntnu.no/IT2810-H26/T31-Project-2/).
diff --git a/apps/api/migrations/0005_recipe_search_and_ratings.sql b/apps/api/migrations/0005_recipe_search_and_ratings.sql
new file mode 100644
index 0000000..24651f1
--- /dev/null
+++ b/apps/api/migrations/0005_recipe_search_and_ratings.sql
@@ -0,0 +1,131 @@
+ALTER TABLE "project2"."recipes" ADD COLUMN "rating_avg" numeric;--> statement-breakpoint
+ALTER TABLE "project2"."recipes" ADD COLUMN "rating_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
+ALTER TABLE "project2"."recipes" ADD COLUMN "search_vector" "tsvector" DEFAULT ''::tsvector NOT NULL;--> statement-breakpoint
+CREATE INDEX "recipes_public_category_created_idx" ON "project2"."recipes" USING btree ("category","created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint
+CREATE INDEX "recipes_public_total_time_idx" ON "project2"."recipes" USING btree (("prep_minutes" + "cook_minutes"),"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint
+CREATE INDEX "recipes_public_rating_idx" ON "project2"."recipes" USING btree ("rating_avg" DESC NULLS LAST,"created_at" DESC NULLS FIRST,"id" DESC NULLS FIRST) WHERE "project2"."recipes"."visibility" = 'public';--> statement-breakpoint
+CREATE INDEX "recipes_search_idx" ON "project2"."recipes" USING gin ("search_vector");
+--> statement-breakpoint
+-- Keep recipes.rating_avg/rating_count in step with ratings for every write
+-- path (API, seed, manual SQL), so the highest-rated sort can use an index.
+-- The recipe row is locked before counting. A concurrent rating of the same
+-- recipe then waits until this one commits, and its count (a new snapshot,
+-- since this is a separate statement) includes this rating instead of
+-- overwriting the cache with a stale value. A rating moved to another recipe
+-- refreshes both recipes, locked in id order so two moves cannot deadlock.
+CREATE FUNCTION "project2"."refresh_recipe_rating"() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE
+ target uuid;
+BEGIN
+ FOR target IN
+ SELECT DISTINCT changed.id FROM unnest(ARRAY[
+ CASE WHEN TG_OP <> 'INSERT' THEN OLD.recipe_id END,
+ CASE WHEN TG_OP <> 'DELETE' THEN NEW.recipe_id END
+ ]) AS changed(id)
+ WHERE changed.id IS NOT NULL ORDER BY changed.id
+ LOOP
+ PERFORM 1 FROM "project2"."recipes" WHERE id = target FOR NO KEY UPDATE;
+ UPDATE "project2"."recipes" r
+ SET rating_avg = s.average, rating_count = s.total
+ FROM (
+ SELECT avg(score) AS average, count(*)::int AS total
+ FROM "project2"."ratings" WHERE recipe_id = target
+ ) s
+ WHERE r.id = target;
+ END LOOP;
+ RETURN NULL;
+END $$;
+--> statement-breakpoint
+CREATE TRIGGER ratings_refresh_recipe_rating
+AFTER INSERT OR UPDATE OF score, recipe_id OR DELETE ON "project2"."ratings"
+FOR EACH ROW EXECUTE FUNCTION "project2"."refresh_recipe_rating"();
+--> statement-breakpoint
+-- Backfill existing ratings.
+UPDATE "project2"."recipes" r
+SET rating_avg = s.average, rating_count = s.total
+FROM (
+ SELECT recipe_id, avg(score) AS average, count(*)::int AS total
+ FROM "project2"."ratings" GROUP BY recipe_id
+) s
+WHERE r.id = s.recipe_id;
+--> statement-breakpoint
+-- A new rating must not change the recipe's "last updated" time: fire the
+-- touch trigger only when recipe content (or updated_at itself) is written.
+DROP TRIGGER recipes_touch_updated_at ON "project2"."recipes";
+--> statement-breakpoint
+CREATE TRIGGER recipes_touch_updated_at
+BEFORE UPDATE OF title, description, image_url, category, cuisine, difficulty,
+ visibility, prep_minutes, cook_minutes, servings, source_recipe_id, author_id,
+ updated_at
+ON "project2"."recipes"
+FOR EACH ROW EXECUTE FUNCTION "project2"."touch_updated_at"();
+--> statement-breakpoint
+-- Full-text search document: title, description, ingredient names and tags.
+CREATE FUNCTION "project2"."recipe_search_document"(recipe uuid, title text, description text)
+RETURNS tsvector LANGUAGE sql STABLE AS $$
+ SELECT to_tsvector('simple', concat_ws(' ', title, description,
+ (SELECT string_agg(i.name, ' ') FROM "project2"."recipe_ingredients" i WHERE i.recipe_id = recipe),
+ (SELECT string_agg(t.tag, ' ') FROM "project2"."recipe_tags" t WHERE t.recipe_id = recipe)))
+$$;
+--> statement-breakpoint
+CREATE FUNCTION "project2"."set_recipe_search_vector"() RETURNS trigger
+LANGUAGE plpgsql AS $$
+BEGIN
+ NEW.search_vector := "project2"."recipe_search_document"(NEW.id, NEW.title, NEW.description);
+ RETURN NEW;
+END $$;
+--> statement-breakpoint
+CREATE TRIGGER recipes_set_search_vector
+BEFORE INSERT OR UPDATE OF title, description ON "project2"."recipes"
+FOR EACH ROW EXECUTE FUNCTION "project2"."set_recipe_search_vector"();
+--> statement-breakpoint
+-- Statement-level: one refresh per INSERT/UPDATE/DELETE statement on
+-- ingredients or tags, for every recipe the statement touched. An UPDATE that
+-- moves rows to another recipe refreshes both the old and the new recipe.
+-- As for ratings, the recipes are locked (in id order, so concurrent writers
+-- cannot deadlock) before the document is rebuilt in a new snapshot, so a
+-- concurrent ingredient or tag write is never overwritten by stale words.
+CREATE FUNCTION "project2"."refresh_recipe_search_vector"() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE
+ targets uuid[];
+BEGIN
+ IF TG_OP = 'INSERT' THEN
+ SELECT array_agg(DISTINCT recipe_id) INTO targets FROM new_rows;
+ ELSIF TG_OP = 'DELETE' THEN
+ SELECT array_agg(DISTINCT recipe_id) INTO targets FROM old_rows;
+ ELSE
+ SELECT array_agg(recipe_id) INTO targets FROM (
+ SELECT recipe_id FROM old_rows UNION SELECT recipe_id FROM new_rows
+ ) touched;
+ END IF;
+ PERFORM 1 FROM "project2"."recipes"
+ WHERE id = ANY(targets) ORDER BY id FOR NO KEY UPDATE;
+ UPDATE "project2"."recipes" r
+ SET search_vector = "project2"."recipe_search_document"(r.id, r.title, r.description)
+ WHERE r.id = ANY(targets);
+ RETURN NULL;
+END $$;
+--> statement-breakpoint
+CREATE TRIGGER recipe_ingredients_search_insert AFTER INSERT ON "project2"."recipe_ingredients"
+REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
+--> statement-breakpoint
+CREATE TRIGGER recipe_ingredients_search_update AFTER UPDATE ON "project2"."recipe_ingredients"
+REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
+--> statement-breakpoint
+CREATE TRIGGER recipe_ingredients_search_delete AFTER DELETE ON "project2"."recipe_ingredients"
+REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
+--> statement-breakpoint
+CREATE TRIGGER recipe_tags_search_insert AFTER INSERT ON "project2"."recipe_tags"
+REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
+--> statement-breakpoint
+CREATE TRIGGER recipe_tags_search_update AFTER UPDATE ON "project2"."recipe_tags"
+REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
+--> statement-breakpoint
+CREATE TRIGGER recipe_tags_search_delete AFTER DELETE ON "project2"."recipe_tags"
+REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION "project2"."refresh_recipe_search_vector"();
+--> statement-breakpoint
+-- Backfill existing recipes.
+UPDATE "project2"."recipes"
+SET search_vector = "project2"."recipe_search_document"(id, title, description);
diff --git a/apps/api/migrations/0006_recipe_title_subwords.sql b/apps/api/migrations/0006_recipe_title_subwords.sql
new file mode 100644
index 0000000..4725121
--- /dev/null
+++ b/apps/api/migrations/0006_recipe_title_subwords.sql
@@ -0,0 +1,16 @@
+-- Ordinary words keep PostgreSQL's default D weight. B marks only fragments
+-- from inside title words, so the same GIN index can find both match groups.
+CREATE OR REPLACE FUNCTION "project2"."recipe_search_document"(recipe uuid, title text, description text)
+RETURNS tsvector LANGUAGE sql STABLE AS $$
+ SELECT to_tsvector('simple', concat_ws(' ', title, description,
+ (SELECT string_agg(i.name, ' ') FROM "project2"."recipe_ingredients" i WHERE i.recipe_id = recipe),
+ (SELECT string_agg(t.tag, ' ') FROM "project2"."recipe_tags" t WHERE t.recipe_id = recipe)))
+ || setweight(to_tsvector('simple', coalesce((
+ SELECT string_agg(substr(word, start_pos), ' ')
+ FROM unnest(tsvector_to_array(to_tsvector('simple', title))) AS words(word)
+ CROSS JOIN LATERAL generate_series(2, char_length(word) - 2) AS offsets(start_pos)
+ ), '')), 'B')
+$$;
+--> statement-breakpoint
+UPDATE "project2"."recipes" r
+SET search_vector = "project2"."recipe_search_document"(r.id, r.title, r.description);
diff --git a/apps/api/migrations/meta/0005_snapshot.json b/apps/api/migrations/meta/0005_snapshot.json
new file mode 100644
index 0000000..1b72c2f
--- /dev/null
+++ b/apps/api/migrations/meta/0005_snapshot.json
@@ -0,0 +1,920 @@
+{
+ "id": "1c6400ab-7455-4e6f-8c2e-a9e6b7053209",
+ "prevId": "ecd5b606-3009-44eb-a2a2-bfc879930465",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "project2.ratings": {
+ "name": "ratings",
+ "schema": "project2",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "score": {
+ "name": "score",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ratings_recipe_idx": {
+ "name": "ratings_recipe_idx",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ratings_user_id_users_id_fk": {
+ "name": "ratings_user_id_users_id_fk",
+ "tableFrom": "ratings",
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ratings_recipe_id_recipes_id_fk": {
+ "name": "ratings_recipe_id_recipes_id_fk",
+ "tableFrom": "ratings",
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsFrom": ["recipe_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "ratings_user_id_recipe_id_pk": {
+ "name": "ratings_user_id_recipe_id_pk",
+ "columns": ["user_id", "recipe_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "ratings_score_valid": {
+ "name": "ratings_score_valid",
+ "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipe_ingredients": {
+ "name": "recipe_ingredients",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "numeric(12, 4)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "unit": {
+ "name": "unit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "recipe_ingredients_recipe_position_unique": {
+ "name": "recipe_ingredients_recipe_position_unique",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "recipe_ingredients_recipe_id_recipes_id_fk": {
+ "name": "recipe_ingredients_recipe_id_recipes_id_fk",
+ "tableFrom": "recipe_ingredients",
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsFrom": ["recipe_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipe_ingredients_name_not_blank": {
+ "name": "recipe_ingredients_name_not_blank",
+ "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0"
+ },
+ "recipe_ingredients_amount_positive": {
+ "name": "recipe_ingredients_amount_positive",
+ "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric"
+ },
+ "recipe_ingredients_position_positive": {
+ "name": "recipe_ingredients_position_positive",
+ "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipe_instructions": {
+ "name": "recipe_instructions",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "recipe_instructions_recipe_position_unique": {
+ "name": "recipe_instructions_recipe_position_unique",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "recipe_instructions_recipe_id_recipes_id_fk": {
+ "name": "recipe_instructions_recipe_id_recipes_id_fk",
+ "tableFrom": "recipe_instructions",
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsFrom": ["recipe_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipe_instructions_text_not_blank": {
+ "name": "recipe_instructions_text_not_blank",
+ "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0"
+ },
+ "recipe_instructions_position_positive": {
+ "name": "recipe_instructions_position_positive",
+ "value": "\"project2\".\"recipe_instructions\".\"position\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipe_tags": {
+ "name": "recipe_tags",
+ "schema": "project2",
+ "columns": {
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tag": {
+ "name": "tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "recipe_tags_recipe_id_recipes_id_fk": {
+ "name": "recipe_tags_recipe_id_recipes_id_fk",
+ "tableFrom": "recipe_tags",
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsFrom": ["recipe_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "recipe_tags_recipe_id_tag_pk": {
+ "name": "recipe_tags_recipe_id_tag_pk",
+ "columns": ["recipe_id", "tag"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipe_tags_normalized": {
+ "name": "recipe_tags_normalized",
+ "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipes": {
+ "name": "recipes",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "author_id": {
+ "name": "author_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_recipe_id": {
+ "name": "source_recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image_url": {
+ "name": "image_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cuisine": {
+ "name": "cuisine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "difficulty": {
+ "name": "difficulty",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "prep_minutes": {
+ "name": "prep_minutes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cook_minutes": {
+ "name": "cook_minutes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "servings": {
+ "name": "servings",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "rating_avg": {
+ "name": "rating_avg",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rating_count": {
+ "name": "rating_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "search_vector": {
+ "name": "search_vector",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''::tsvector"
+ }
+ },
+ "indexes": {
+ "recipes_author_idx": {
+ "name": "recipes_author_idx",
+ "columns": [
+ {
+ "expression": "author_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "recipes_source_idx": {
+ "name": "recipes_source_idx",
+ "columns": [
+ {
+ "expression": "source_recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "recipes_public_created_idx": {
+ "name": "recipes_public_created_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "recipes_public_category_created_idx": {
+ "name": "recipes_public_category_created_idx",
+ "columns": [
+ {
+ "expression": "category",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "recipes_public_total_time_idx": {
+ "name": "recipes_public_total_time_idx",
+ "columns": [
+ {
+ "expression": "(\"prep_minutes\" + \"cook_minutes\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "recipes_public_rating_idx": {
+ "name": "recipes_public_rating_idx",
+ "columns": [
+ {
+ "expression": "rating_avg",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "recipes_search_idx": {
+ "name": "recipes_search_idx",
+ "columns": [
+ {
+ "expression": "search_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "recipes_author_id_users_id_fk": {
+ "name": "recipes_author_id_users_id_fk",
+ "tableFrom": "recipes",
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsFrom": ["author_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "recipes_source_recipe_id_recipes_id_fk": {
+ "name": "recipes_source_recipe_id_recipes_id_fk",
+ "tableFrom": "recipes",
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsFrom": ["source_recipe_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipes_title_not_blank": {
+ "name": "recipes_title_not_blank",
+ "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0"
+ },
+ "recipes_category_valid": {
+ "name": "recipes_category_valid",
+ "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')"
+ },
+ "recipes_cuisine_not_blank": {
+ "name": "recipes_cuisine_not_blank",
+ "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0"
+ },
+ "recipes_difficulty_valid": {
+ "name": "recipes_difficulty_valid",
+ "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')"
+ },
+ "recipes_visibility_valid": {
+ "name": "recipes_visibility_valid",
+ "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')"
+ },
+ "recipes_prep_minutes_nonnegative": {
+ "name": "recipes_prep_minutes_nonnegative",
+ "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0"
+ },
+ "recipes_cook_minutes_nonnegative": {
+ "name": "recipes_cook_minutes_nonnegative",
+ "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0"
+ },
+ "recipes_servings_positive": {
+ "name": "recipes_servings_positive",
+ "value": "\"project2\".\"recipes\".\"servings\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.saved_recipes": {
+ "name": "saved_recipes",
+ "schema": "project2",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "saved_recipes_recipe_idx": {
+ "name": "saved_recipes_recipe_idx",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "saved_recipes_user_id_users_id_fk": {
+ "name": "saved_recipes_user_id_users_id_fk",
+ "tableFrom": "saved_recipes",
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "saved_recipes_recipe_id_recipes_id_fk": {
+ "name": "saved_recipes_recipe_id_recipes_id_fk",
+ "tableFrom": "saved_recipes",
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsFrom": ["recipe_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "saved_recipes_user_id_recipe_id_pk": {
+ "name": "saved_recipes_user_id_recipe_id_pk",
+ "columns": ["user_id", "recipe_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "project2.sessions": {
+ "name": "sessions",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sessions_user_id_users_id_fk": {
+ "name": "sessions_user_id_users_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsFrom": ["user_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "project2.uploaded_images": {
+ "name": "uploaded_images",
+ "schema": "project2",
+ "columns": {
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "byte_size": {
+ "name": "byte_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "uploaded_images_owner_idx": {
+ "name": "uploaded_images_owner_idx",
+ "columns": [
+ {
+ "expression": "owner_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "uploaded_images_owner_id_users_id_fk": {
+ "name": "uploaded_images_owner_id_users_id_fk",
+ "tableFrom": "uploaded_images",
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsFrom": ["owner_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "uploaded_images_size_valid": {
+ "name": "uploaded_images_size_valid",
+ "value": "\"project2\".\"uploaded_images\".\"byte_size\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.users": {
+ "name": "users",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/apps/api/migrations/meta/0006_snapshot.json b/apps/api/migrations/meta/0006_snapshot.json
new file mode 100644
index 0000000..940623f
--- /dev/null
+++ b/apps/api/migrations/meta/0006_snapshot.json
@@ -0,0 +1,920 @@
+{
+ "id": "73928da2-2f00-4213-839e-ef972ec2ba72",
+ "prevId": "1c6400ab-7455-4e6f-8c2e-a9e6b7053209",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "project2.ratings": {
+ "name": "ratings",
+ "schema": "project2",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "score": {
+ "name": "score",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ratings_recipe_idx": {
+ "name": "ratings_recipe_idx",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "ratings_user_id_users_id_fk": {
+ "name": "ratings_user_id_users_id_fk",
+ "tableFrom": "ratings",
+ "columnsFrom": ["user_id"],
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "ratings_recipe_id_recipes_id_fk": {
+ "name": "ratings_recipe_id_recipes_id_fk",
+ "tableFrom": "ratings",
+ "columnsFrom": ["recipe_id"],
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "ratings_user_id_recipe_id_pk": {
+ "name": "ratings_user_id_recipe_id_pk",
+ "columns": ["user_id", "recipe_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "ratings_score_valid": {
+ "name": "ratings_score_valid",
+ "value": "\"project2\".\"ratings\".\"score\" BETWEEN 1 AND 5"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipe_ingredients": {
+ "name": "recipe_ingredients",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "numeric(12, 4)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "unit": {
+ "name": "unit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "recipe_ingredients_recipe_position_unique": {
+ "name": "recipe_ingredients_recipe_position_unique",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "recipe_ingredients_recipe_id_recipes_id_fk": {
+ "name": "recipe_ingredients_recipe_id_recipes_id_fk",
+ "tableFrom": "recipe_ingredients",
+ "columnsFrom": ["recipe_id"],
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipe_ingredients_name_not_blank": {
+ "name": "recipe_ingredients_name_not_blank",
+ "value": "length(trim(\"project2\".\"recipe_ingredients\".\"name\")) > 0"
+ },
+ "recipe_ingredients_amount_positive": {
+ "name": "recipe_ingredients_amount_positive",
+ "value": "\"project2\".\"recipe_ingredients\".\"amount\" > 0 AND \"project2\".\"recipe_ingredients\".\"amount\" <> 'NaN'::numeric"
+ },
+ "recipe_ingredients_position_positive": {
+ "name": "recipe_ingredients_position_positive",
+ "value": "\"project2\".\"recipe_ingredients\".\"position\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipe_instructions": {
+ "name": "recipe_instructions",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "recipe_instructions_recipe_position_unique": {
+ "name": "recipe_instructions_recipe_position_unique",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "recipe_instructions_recipe_id_recipes_id_fk": {
+ "name": "recipe_instructions_recipe_id_recipes_id_fk",
+ "tableFrom": "recipe_instructions",
+ "columnsFrom": ["recipe_id"],
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipe_instructions_text_not_blank": {
+ "name": "recipe_instructions_text_not_blank",
+ "value": "length(trim(\"project2\".\"recipe_instructions\".\"text\")) > 0"
+ },
+ "recipe_instructions_position_positive": {
+ "name": "recipe_instructions_position_positive",
+ "value": "\"project2\".\"recipe_instructions\".\"position\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipe_tags": {
+ "name": "recipe_tags",
+ "schema": "project2",
+ "columns": {
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tag": {
+ "name": "tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "recipe_tags_recipe_id_recipes_id_fk": {
+ "name": "recipe_tags_recipe_id_recipes_id_fk",
+ "tableFrom": "recipe_tags",
+ "columnsFrom": ["recipe_id"],
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "recipe_tags_recipe_id_tag_pk": {
+ "name": "recipe_tags_recipe_id_tag_pk",
+ "columns": ["recipe_id", "tag"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipe_tags_normalized": {
+ "name": "recipe_tags_normalized",
+ "value": "length(\"project2\".\"recipe_tags\".\"tag\") > 0 AND \"project2\".\"recipe_tags\".\"tag\" = lower(trim(\"project2\".\"recipe_tags\".\"tag\"))"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.recipes": {
+ "name": "recipes",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "author_id": {
+ "name": "author_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_recipe_id": {
+ "name": "source_recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image_url": {
+ "name": "image_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cuisine": {
+ "name": "cuisine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "difficulty": {
+ "name": "difficulty",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "prep_minutes": {
+ "name": "prep_minutes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cook_minutes": {
+ "name": "cook_minutes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "servings": {
+ "name": "servings",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "rating_avg": {
+ "name": "rating_avg",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rating_count": {
+ "name": "rating_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "search_vector": {
+ "name": "search_vector",
+ "type": "tsvector",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''::tsvector"
+ }
+ },
+ "indexes": {
+ "recipes_author_idx": {
+ "name": "recipes_author_idx",
+ "columns": [
+ {
+ "expression": "author_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "recipes_source_idx": {
+ "name": "recipes_source_idx",
+ "columns": [
+ {
+ "expression": "source_recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ },
+ "recipes_public_created_idx": {
+ "name": "recipes_public_created_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false
+ },
+ "recipes_public_category_created_idx": {
+ "name": "recipes_public_category_created_idx",
+ "columns": [
+ {
+ "expression": "category",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false
+ },
+ "recipes_public_total_time_idx": {
+ "name": "recipes_public_total_time_idx",
+ "columns": [
+ {
+ "expression": "(\"prep_minutes\" + \"cook_minutes\")",
+ "isExpression": true,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false
+ },
+ "recipes_public_rating_idx": {
+ "name": "recipes_public_rating_idx",
+ "columns": [
+ {
+ "expression": "rating_avg",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "first"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "where": "\"project2\".\"recipes\".\"visibility\" = 'public'",
+ "concurrently": false
+ },
+ "recipes_search_idx": {
+ "name": "recipes_search_idx",
+ "columns": [
+ {
+ "expression": "search_vector",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "gin",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "recipes_author_id_users_id_fk": {
+ "name": "recipes_author_id_users_id_fk",
+ "tableFrom": "recipes",
+ "columnsFrom": ["author_id"],
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "recipes_source_recipe_id_recipes_id_fk": {
+ "name": "recipes_source_recipe_id_recipes_id_fk",
+ "tableFrom": "recipes",
+ "columnsFrom": ["source_recipe_id"],
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "recipes_title_not_blank": {
+ "name": "recipes_title_not_blank",
+ "value": "length(trim(\"project2\".\"recipes\".\"title\")) > 0"
+ },
+ "recipes_category_valid": {
+ "name": "recipes_category_valid",
+ "value": "\"project2\".\"recipes\".\"category\" IN ('breakfast', 'lunch', 'dinner', 'dessert', 'soup')"
+ },
+ "recipes_cuisine_not_blank": {
+ "name": "recipes_cuisine_not_blank",
+ "value": "length(trim(\"project2\".\"recipes\".\"cuisine\")) > 0"
+ },
+ "recipes_difficulty_valid": {
+ "name": "recipes_difficulty_valid",
+ "value": "\"project2\".\"recipes\".\"difficulty\" IN ('easy', 'medium', 'hard')"
+ },
+ "recipes_visibility_valid": {
+ "name": "recipes_visibility_valid",
+ "value": "\"project2\".\"recipes\".\"visibility\" IN ('public', 'private')"
+ },
+ "recipes_prep_minutes_nonnegative": {
+ "name": "recipes_prep_minutes_nonnegative",
+ "value": "\"project2\".\"recipes\".\"prep_minutes\" >= 0"
+ },
+ "recipes_cook_minutes_nonnegative": {
+ "name": "recipes_cook_minutes_nonnegative",
+ "value": "\"project2\".\"recipes\".\"cook_minutes\" >= 0"
+ },
+ "recipes_servings_positive": {
+ "name": "recipes_servings_positive",
+ "value": "\"project2\".\"recipes\".\"servings\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.saved_recipes": {
+ "name": "saved_recipes",
+ "schema": "project2",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipe_id": {
+ "name": "recipe_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "saved_recipes_recipe_idx": {
+ "name": "saved_recipes_recipe_idx",
+ "columns": [
+ {
+ "expression": "recipe_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "saved_recipes_user_id_users_id_fk": {
+ "name": "saved_recipes_user_id_users_id_fk",
+ "tableFrom": "saved_recipes",
+ "columnsFrom": ["user_id"],
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ },
+ "saved_recipes_recipe_id_recipes_id_fk": {
+ "name": "saved_recipes_recipe_id_recipes_id_fk",
+ "tableFrom": "saved_recipes",
+ "columnsFrom": ["recipe_id"],
+ "tableTo": "recipes",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "saved_recipes_user_id_recipe_id_pk": {
+ "name": "saved_recipes_user_id_recipe_id_pk",
+ "columns": ["user_id", "recipe_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "project2.sessions": {
+ "name": "sessions",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sessions_user_id_users_id_fk": {
+ "name": "sessions_user_id_users_id_fk",
+ "tableFrom": "sessions",
+ "columnsFrom": ["user_id"],
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "project2.uploaded_images": {
+ "name": "uploaded_images",
+ "schema": "project2",
+ "columns": {
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "byte_size": {
+ "name": "byte_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "uploaded_images_owner_idx": {
+ "name": "uploaded_images_owner_idx",
+ "columns": [
+ {
+ "expression": "owner_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {
+ "uploaded_images_owner_id_users_id_fk": {
+ "name": "uploaded_images_owner_id_users_id_fk",
+ "tableFrom": "uploaded_images",
+ "columnsFrom": ["owner_id"],
+ "tableTo": "users",
+ "schemaTo": "project2",
+ "columnsTo": ["id"],
+ "onUpdate": "no action",
+ "onDelete": "set null"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "uploaded_images_size_valid": {
+ "name": "uploaded_images_size_valid",
+ "value": "\"project2\".\"uploaded_images\".\"byte_size\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "project2.users": {
+ "name": "users",
+ "schema": "project2",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "with": {},
+ "method": "btree",
+ "concurrently": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "views": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/apps/api/migrations/meta/_journal.json b/apps/api/migrations/meta/_journal.json
index 13c88f1..8389a11 100644
--- a/apps/api/migrations/meta/_journal.json
+++ b/apps/api/migrations/meta/_journal.json
@@ -36,6 +36,20 @@
"when": 1793008961317,
"tag": "0004_uploaded_images",
"breakpoints": true
+ },
+ {
+ "idx": 5,
+ "version": "7",
+ "when": 1794837583052,
+ "tag": "0005_recipe_search_and_ratings",
+ "breakpoints": true
+ },
+ {
+ "idx": 6,
+ "version": "7",
+ "when": 1795176845501,
+ "tag": "0006_recipe_title_subwords",
+ "breakpoints": true
}
]
}
diff --git a/apps/api/package.json b/apps/api/package.json
index 0f04ddc..659e456 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -14,6 +14,7 @@
"graphql": "16.12.0",
"graphql-yoga": "5.16.2",
"pg": "8.16.3",
+ "sharp": "0.34.4",
"zod": "4.6.7"
},
"devDependencies": {
diff --git a/apps/api/src/apiLimits.test.ts b/apps/api/src/apiLimits.test.ts
new file mode 100644
index 0000000..a4fa786
--- /dev/null
+++ b/apps/api/src/apiLimits.test.ts
@@ -0,0 +1,281 @@
+// @vitest-environment node
+import { readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import {
+ buildSchema,
+ getIntrospectionQuery,
+ parse,
+ specifiedRules,
+ validate,
+} from 'graphql';
+import { describe, expect, it } from 'vitest';
+import {
+ createRequestRateLimiter,
+ DEFAULT_API_LIMITS,
+ queryLimitsRule,
+ type QueryLimits,
+} from './apiLimits.js';
+import { createApp } from './app.js';
+
+const schema = buildSchema(
+ readFileSync(new URL('./schema.graphql', import.meta.url), 'utf8'),
+);
+function errors(query: string, limits: QueryLimits = DEFAULT_API_LIMITS.query) {
+ return validate(schema, parse(query), [
+ ...specifiedRules,
+ queryLimitsRule(limits),
+ ]).map((error) => error.message);
+}
+
+describe('query limits', () => {
+ it('accept every operation the web app sends', () => {
+ expect(
+ errors(
+ readFileSync(
+ new URL('../../../contracts/operations.graphql', import.meta.url),
+ 'utf8',
+ ),
+ ),
+ ).toEqual([]);
+ });
+
+ it("accept GraphiQL's introspection query", () => {
+ expect(errors(getIntrospectionQuery())).toEqual([]);
+ });
+
+ it('reject heavily aliased introspection like any other field', () => {
+ const copies = (count: number, field: string) =>
+ Array.from({ length: count }, (_, index) => `a${index}: ${field}`);
+ // Repeating the whole schema through aliases at the top level.
+ expect(
+ errors(`{ ${copies(11, '__schema { types { name } }').join(' ')} }`),
+ ).toEqual([
+ 'The query is too large: more than 10 aliases, more than 3 top-level fields.',
+ ]);
+ expect(
+ errors(`{ ${copies(5, '__type(name: "Recipe") { name }').join(' ')} }`),
+ ).toEqual(['The query is too large: more than 3 top-level fields.']);
+ // Aliases below the introspection field count too.
+ expect(
+ errors(`{ __schema { ${copies(11, 'types { name }').join(' ')} } }`),
+ ).toEqual(['The query is too large: more than 10 aliases.']);
+ // And so does its total size, however deeply it is nested.
+ const deep = `{ __schema { types ${'{ ofType '.repeat(300)}{ name }${' }'.repeat(300)} } }`;
+ expect(errors(deep)).toEqual([
+ 'The query is too large: more than 300 fields.',
+ ]);
+ });
+
+ it('reject repeating a list query through aliases', () => {
+ const aliases = Array.from(
+ { length: 11 },
+ (_, index) =>
+ `a${index}: recipes(input: { pageSize: 50 }) { totalCount }`,
+ );
+ expect(errors(`{ ${aliases.join(' ')} }`)).toEqual([
+ 'The query is too large: more than 10 aliases, more than 3 top-level fields.',
+ ]);
+ });
+
+ it('reject more than three top-level fields', () => {
+ expect(
+ errors('{ a: health b: health c: health d: health }', {
+ ...DEFAULT_API_LIMITS.query,
+ maxAliases: 100,
+ }),
+ ).toEqual(['The query is too large: more than 3 top-level fields.']);
+ });
+
+ it('reject nesting deeper than the limit', () => {
+ const query = '{ recipe(id: "1") { ingredients { name } author { id } } }';
+ expect(errors(query, { ...DEFAULT_API_LIMITS.query, maxDepth: 3 })).toEqual(
+ [],
+ );
+ expect(errors(query, { ...DEFAULT_API_LIMITS.query, maxDepth: 2 })).toEqual(
+ ['The query is too large: nesting is deeper than 2 levels.'],
+ );
+ });
+
+ it('stop counting early when fragments multiply the fields', () => {
+ // Each fragment spreads the next twice: 2^20 fields once expanded.
+ const fragments = Array.from(
+ { length: 20 },
+ (_, index) =>
+ `fragment F${index} on Recipe { ${index === 19 ? 'id title' : `...F${index + 1} ...F${index + 1}`} }`,
+ );
+ const document = parse(
+ `{ recipe(id: "1") { ...F0 } } ${fragments.join(' ')}`,
+ );
+ const started = performance.now();
+ const result = validate(schema, document, [
+ queryLimitsRule(DEFAULT_API_LIMITS.query),
+ ]);
+ expect(result.map((error) => error.message)).toEqual([
+ 'The query is too large: more than 300 fields.',
+ ]);
+ expect(performance.now() - started).toBeLessThan(500);
+ });
+});
+
+describe('__typename in query limits', () => {
+ it('counts __typename toward the field limit, so fragment chains of it are rejected', () => {
+ // Each fragment spreads the next twice: 2^20 __typename fields expanded.
+ const fragments = Array.from(
+ { length: 20 },
+ (_, index) =>
+ `fragment F${index} on Recipe { ${index === 19 ? '__typename' : `...F${index + 1} ...F${index + 1}`} }`,
+ );
+ const started = performance.now();
+ expect(
+ errors(`{ recipe(id: "1") { ...F0 } } ${fragments.join(' ')}`),
+ ).toEqual(['The query is too large: more than 300 fields.']);
+ expect(performance.now() - started).toBeLessThan(500);
+ });
+
+ it('counts aliased __typename toward the alias limit', () => {
+ const aliases = Array.from(
+ { length: 11 },
+ (_, index) => `t${index}: __typename`,
+ );
+ expect(errors(`{ ${aliases.join(' ')} }`)).toEqual([
+ 'The query is too large: more than 10 aliases.',
+ ]);
+ });
+
+ it('still accepts the __typename a client adds to a selection', () => {
+ expect(
+ errors('{ recipes { __typename items { __typename id } } }'),
+ ).toEqual([]);
+ });
+});
+
+describe('request rate limiter', () => {
+ it('limits each client per window and resets after it', () => {
+ let time = 0;
+ const limiter = createRequestRateLimiter(2, 60_000, () => time);
+ expect(limiter.take('a')).toBeNull();
+ expect(limiter.take('a')).toBeNull();
+ expect(limiter.take('a')).toBe(60);
+ // Another client has its own budget.
+ expect(limiter.take('b')).toBeNull();
+ time = 45_000;
+ expect(limiter.take('a')).toBe(15);
+ time = 60_000;
+ expect(limiter.take('a')).toBeNull();
+ });
+});
+
+describe('API limits over HTTP', () => {
+ const post = (
+ app: ReturnType,
+ query: string,
+ headers: Record = {},
+ ) =>
+ app.fetch('http://localhost/graphql', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Requested-With': 'recipe-platform',
+ ...headers,
+ },
+ body: JSON.stringify({ query }),
+ });
+ const app = (limits = {}) =>
+ createApp(undefined, false, false, {}, tmpdir(), false, limits);
+
+ it('answers 429 with Retry-After once a client sends too many requests', async () => {
+ const api = app({ requestsPerMinute: 2 });
+ expect((await post(api, '{ health }')).status).toBe(200);
+ expect((await post(api, '{ health }')).status).toBe(200);
+ const limited = await post(api, '{ health }');
+ expect(limited.status).toBe(429);
+ expect(Number(limited.headers.get('retry-after'))).toBeGreaterThan(0);
+ expect(await limited.json()).toMatchObject({
+ errors: [{ extensions: { code: 'RATE_LIMITED' } }],
+ });
+ });
+
+ it('rejects an alias-repeated query before any resolver runs', async () => {
+ const aliases = Array.from(
+ { length: 11 },
+ (_, index) => `a${index}: health`,
+ );
+ const response = await post(app(), `{ ${aliases.join(' ')} }`);
+ expect(await response.json()).toMatchObject({
+ errors: [{ extensions: { code: 'QUERY_TOO_COMPLEX' } }],
+ });
+ });
+
+ it('does not count rejected requests toward the request limit', async () => {
+ const api = app({ requestsPerMinute: 2 });
+ const bad = (headers: Record) =>
+ post(api, '{ health }', headers);
+ for (let attempt = 0; attempt < 5; attempt++) {
+ expect((await bad({ 'X-Requested-With': 'other' })).status).toBe(403);
+ expect((await bad({ 'Content-Type': 'text/plain' })).status).toBe(403);
+ expect((await bad({ 'Content-Length': '1000001' })).status).toBe(413);
+ }
+ // The client's whole budget is still there.
+ expect((await post(api, '{ health }')).status).toBe(200);
+ expect((await post(api, '{ health }')).status).toBe(200);
+ expect((await post(api, '{ health }')).status).toBe(429);
+ });
+
+ it('does not let GET requests use up the limit, and gives GET queries the same header check', async () => {
+ const api = app({ requestsPerMinute: 2 });
+ const get = (path: string, headers: Record = {}) =>
+ api.fetch(`http://localhost/graphql${path}`, { headers });
+ const query = '?query=%7B%20health%20%7D';
+ for (let attempt = 0; attempt < 5; attempt++) {
+ // A query without the custom header (as from another site): refused.
+ expect((await get(query)).status).toBe(403);
+ // Malformed or operation-less GETs run nothing and are not counted.
+ expect((await get('')).status).toBeLessThan(500);
+ expect((await get('', { Accept: 'text/html' })).status).toBeLessThan(500);
+ }
+ // The whole budget is still there; a GET query with the header is counted.
+ const allowed = { 'X-Requested-With': 'recipe-platform' };
+ expect((await get(query, allowed)).status).toBe(200);
+ expect((await get(query, allowed)).status).toBe(200);
+ expect((await get(query, allowed)).status).toBe(429);
+ });
+
+ it('refuses a request body larger than 1 MB', async () => {
+ const response = await post(app(), '{ health }', {
+ 'Content-Length': '1000001',
+ });
+ expect(response.status).toBe(413);
+ });
+
+ it('counts the bytes of a chunked body that has no Content-Length', async () => {
+ const chunk = new TextEncoder().encode(' '.repeat(100_000));
+ const chunked = (chunks: number) =>
+ app().fetch('http://localhost/graphql', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Requested-With': 'recipe-platform',
+ },
+ body: new ReadableStream({
+ start(controller) {
+ for (let index = 0; index < chunks; index++)
+ controller.enqueue(chunk);
+ controller.enqueue(
+ new TextEncoder().encode('{"query":"{ health }"}'),
+ );
+ controller.close();
+ },
+ }),
+ duplex: 'half',
+ } as RequestInit);
+ const large = await chunked(11);
+ expect(large.status).toBe(413);
+ expect(await large.json()).toMatchObject({
+ errors: [{ extensions: { code: 'PAYLOAD_TOO_LARGE' } }],
+ });
+ // The same kind of request under the limit still works.
+ const small = await chunked(2);
+ expect(small.status).toBe(200);
+ expect(await small.json()).toEqual({ data: { health: 'ok' } });
+ });
+});
diff --git a/apps/api/src/apiLimits.ts b/apps/api/src/apiLimits.ts
new file mode 100644
index 0000000..d7f2a47
--- /dev/null
+++ b/apps/api/src/apiLimits.ts
@@ -0,0 +1,205 @@
+import {
+ GraphQLError,
+ Kind,
+ type ASTVisitor,
+ type FragmentDefinitionNode,
+ type SelectionSetNode,
+ type ValidationContext,
+} from 'graphql';
+
+/*
+ * Resource limits for the GraphQL API. Authentication attempts and image
+ * uploads have their own limits (authRateLimit.ts, imageStore.ts); these
+ * bound what any single client or request can make the server do.
+ */
+export type QueryLimits = {
+ /** Nesting of fields, e.g. recipes { items { ingredients { name } } } is 4. */
+ maxDepth: number;
+ /** Aliased fields, the usual way to repeat an expensive field. */
+ maxAliases: number;
+ /** Field selections after expanding fragments. */
+ maxFields: number;
+ /** Top-level fields, each of which is at least one database query. */
+ maxRootFields: number;
+};
+
+export type ApiLimits = {
+ /** GraphQL requests per client (IP address) per minute. */
+ requestsPerMinute: number;
+ /** Recipes one user may create per hour, and in total. */
+ recipesPerHour: number;
+ recipesPerUser: number;
+ query: QueryLimits;
+};
+
+// Every operation the web app sends stays well inside these (see
+// apiLimits.test.ts); a page load makes a handful of requests.
+export const DEFAULT_API_LIMITS: ApiLimits = {
+ requestsPerMinute: 300,
+ recipesPerHour: 30,
+ recipesPerUser: 1000,
+ query: { maxDepth: 8, maxAliases: 10, maxFields: 300, maxRootFields: 3 },
+};
+
+/** Bodies above this are refused before parsing (a recipe is far smaller). */
+export const MAX_REQUEST_BYTES = 1_000_000;
+
+/**
+ * Passes the request's body through while counting the bytes actually read,
+ * and fails the stream once more than maxBytes arrive. Content-Length is
+ * only a claim by the client: chunked requests have none, and others can
+ * send more than they state. exceeded() tells the caller that a failed read
+ * was caused by the limit.
+ */
+export function limitRequestBody(request: Request, maxBytes: number) {
+ let exceeded = false;
+ if (!request.body) return { request, exceeded: () => exceeded };
+ const reader = request.body.getReader();
+ let received = 0;
+ const body = new ReadableStream({
+ async pull(controller) {
+ const { done, value } = await reader.read();
+ if (done) return controller.close();
+ received += value.byteLength;
+ if (received > maxBytes) {
+ exceeded = true;
+ controller.error(new Error('Request body too large.'));
+ reader.cancel().catch(() => undefined);
+ } else controller.enqueue(value);
+ },
+ cancel: (reason) => reader.cancel(reason),
+ });
+ return {
+ request: new Request(request.url, {
+ method: request.method,
+ headers: request.headers,
+ body,
+ duplex: 'half',
+ } as RequestInit),
+ exceeded: () => exceeded,
+ };
+}
+
+/**
+ * Rejects operations that are too deep, too wide or repeat fields through
+ * aliases, before any resolver runs. Introspection (__schema, __type) is
+ * counted like any other field, so aliases, top-level fields and the total
+ * size stay limited, but its depth is not: GraphiQL's schema query is 15
+ * levels deep and reads no data.
+ */
+export function queryLimitsRule(limits: QueryLimits) {
+ return (context: ValidationContext): ASTVisitor => {
+ const fragments = new Map();
+ for (const definition of context.getDocument().definitions)
+ if (definition.kind === Kind.FRAGMENT_DEFINITION)
+ fragments.set(definition.name.value, definition);
+
+ return {
+ OperationDefinition(operation) {
+ const usage = { fields: 0, aliases: 0, depth: 0, root: 0 };
+ // Stops early once over the field limit, so fragments that spread
+ // each other many times cannot make this check itself expensive.
+ function measure(
+ selections: SelectionSetNode,
+ depth: number,
+ spreading: Set,
+ introspection: boolean,
+ ) {
+ for (const selection of selections.selections) {
+ if (usage.fields > limits.maxFields) return;
+ if (selection.kind === Kind.FIELD) {
+ const name = selection.name.value;
+ usage.fields += 1;
+ if (selection.alias) usage.aliases += 1;
+ // __typename reads no data: it counts toward the total and
+ // alias limits (so a fragment chain of __typename cannot make
+ // the server expand 2^n fields), but not as a top-level field
+ // or as nesting.
+ if (name === '__typename') continue;
+ const inIntrospection =
+ introspection || name === '__schema' || name === '__type';
+ if (depth === 1) usage.root += 1;
+ if (!inIntrospection) usage.depth = Math.max(usage.depth, depth);
+ if (selection.selectionSet)
+ measure(
+ selection.selectionSet,
+ depth + 1,
+ spreading,
+ inIntrospection,
+ );
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) {
+ measure(selection.selectionSet, depth, spreading, introspection);
+ } else {
+ const name = selection.name.value;
+ const fragment = fragments.get(name);
+ // Unknown or cyclic fragments are reported by the standard rules.
+ if (!fragment || spreading.has(name)) continue;
+ spreading.add(name);
+ measure(fragment.selectionSet, depth, spreading, introspection);
+ spreading.delete(name);
+ }
+ }
+ }
+ measure(operation.selectionSet, 1, new Set(), false);
+
+ const exceeded = [
+ usage.depth > limits.maxDepth &&
+ `nesting is deeper than ${limits.maxDepth} levels`,
+ usage.aliases > limits.maxAliases &&
+ `more than ${limits.maxAliases} aliases`,
+ usage.fields > limits.maxFields &&
+ `more than ${limits.maxFields} fields`,
+ usage.root > limits.maxRootFields &&
+ `more than ${limits.maxRootFields} top-level fields`,
+ ].filter(Boolean);
+ if (exceeded.length)
+ context.reportError(
+ new GraphQLError(
+ `The query is too large: ${exceeded.join(', ')}.`,
+ {
+ nodes: operation,
+ extensions: { code: 'QUERY_TOO_COMPLEX' },
+ },
+ ),
+ );
+ },
+ };
+ };
+}
+
+/**
+ * Fixed-window request counter per client. Returns null when the request
+ * is allowed, otherwise the seconds until the client may try again.
+ * Memory is bounded: expired entries are swept (at most once a second),
+ * and when 10 000 clients are already tracked a new one is let through
+ * rather than locking out every new visitor.
+ */
+export function createRequestRateLimiter(
+ limit: number,
+ windowMs = 60_000,
+ now = Date.now,
+) {
+ const clients = new Map();
+ let nextSweep = 0;
+ return {
+ take(client: string): number | null {
+ const time = now();
+ if (time >= nextSweep) {
+ for (const [key, entry] of clients)
+ if (entry.resetAt <= time) clients.delete(key);
+ nextSweep = time + 1000;
+ }
+ const entry = clients.get(client);
+ if (!entry || entry.resetAt <= time) {
+ clients.delete(client);
+ if (clients.size < 10_000)
+ clients.set(client, { count: 1, resetAt: time + windowMs });
+ return null;
+ }
+ if (entry.count >= limit)
+ return Math.max(1, Math.ceil((entry.resetAt - time) / 1000));
+ entry.count += 1;
+ return null;
+ },
+ };
+}
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 26232d3..808e2ce 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -7,6 +7,7 @@ import { createRecipeRepository } from './features/recipes/recipeRepository.js';
import { createRecipeResolvers } from './features/recipes/recipeResolvers.js';
import { readFileSync } from 'node:fs';
import { createSchema, createYoga } from 'graphql-yoga';
+import { GraphQLError, type ValidationRule } from 'graphql';
import type { Resolvers } from './generated.js';
import type { IncomingMessage } from 'node:http';
@@ -15,6 +16,15 @@ import {
type AuthContext,
} from './features/auth/authResolvers.js';
import { authClientKey } from './features/auth/authRateLimit.js';
+import {
+ createRequestRateLimiter,
+ DEFAULT_API_LIMITS,
+ limitRequestBody,
+ MAX_REQUEST_BYTES,
+ queryLimitsRule,
+ type ApiLimits,
+ type QueryLimits,
+} from './apiLimits.js';
import { authService, type AuthService } from './features/auth/authService.js';
import {
readSessionCookie,
@@ -22,6 +32,11 @@ import {
SESSION_COOKIE,
} from './features/auth/sessionCookie.js';
+/**
+ * Wires HTTP guards, session context and GraphQL resolvers into one handler.
+ * Injected auth/database/storage dependencies let tests exercise the same
+ * request flow without sharing production sessions, tables or image files.
+ */
export function createApp(
service: AuthService = authService,
trustProxy = process.env.AUTH_TRUST_PROXY === 'true',
@@ -29,7 +44,25 @@ export function createApp(
database: { pool?: Pool; schema?: string } = {},
uploadDirectory = process.env.UPLOAD_DIR ??
fileURLToPath(new URL('../../../uploads/', import.meta.url)),
+ // GraphiQL (an in-browser query editor at /graphql) is on by default so
+ // reviewers can explore the API; it grants no additional privileges.
+ // Public queries allow anonymous access, while protected operations require
+ // authentication. The recipe repository enforces visibility and ownership.
+ // GraphQL operation requests still need the CSRF header.
+ // Set API_GRAPHIQL=false to turn it off.
+ enableGraphiql = process.env.API_GRAPHIQL !== 'false',
+ // Request, query and recipe-creation limits (apiLimits.ts); tests that
+ // send many requests from one address raise them.
+ limitOverrides: Partial> & {
+ query?: Partial;
+ } = {},
) {
+ const limits: ApiLimits = {
+ ...DEFAULT_API_LIMITS,
+ ...limitOverrides,
+ query: { ...DEFAULT_API_LIMITS.query, ...limitOverrides.query },
+ };
+ const requestLimiter = createRequestRateLimiter(limits.requestsPerMinute);
const images = createImageStore(
database.pool ?? db,
database.schema ?? 'project2',
@@ -37,17 +70,75 @@ export function createApp(
);
const authResolvers = createAuthResolvers(service);
const recipes = createRecipeResolvers(
- createRecipeRepository(database.pool ?? db, database.schema ?? 'project2'),
+ createRecipeRepository(
+ database.pool ?? db,
+ database.schema ?? 'project2',
+ limits,
+ ),
);
+ // Resolvers schedule cookie changes through context.setSession; onResponse
+ // writes them to the matching HTTP response. Request keys keep concurrent
+ // login/logout responses separate without retaining completed requests.
const cookies = new WeakMap();
return createYoga<{ req?: IncomingMessage }, AuthContext>({
+ // The browser uses the same origin through Vite/Apache. Together with the
+ // custom header below, disabling CORS prevents cross-origin operation calls.
cors: false,
- graphiql: {
+ graphiql: enableGraphiql && {
+ // POST requests without this header are rejected (CSRF check below).
defaultHeaders: JSON.stringify({ 'X-Requested-With': 'recipe-platform' }),
},
plugins: [
{
- async onRequest({ request, fetchAPI, endResponse }) {
+ onValidate({
+ addValidationRule,
+ }: {
+ addValidationRule: (rule: ValidationRule) => void;
+ }) {
+ addValidationRule(queryLimitsRule(limits.query));
+ },
+ // The body limit also covers requests that give no Content-Length
+ // (chunked) or send more than they state: the bytes read are counted.
+ onRequestParse({ request, requestParser, setRequestParser }) {
+ if (request.method !== 'POST' || !requestParser) return;
+ const parse = requestParser;
+ setRequestParser(async (received) => {
+ const limited = limitRequestBody(received, MAX_REQUEST_BYTES);
+ try {
+ // Awaited so a failed read can be told from a bad body; the
+ // cast is only because Yoga does not export its parser type.
+ return (await parse(limited.request)) as never;
+ } catch (error) {
+ if (limited.exceeded())
+ throw new GraphQLError('Request too large.', {
+ extensions: {
+ code: 'PAYLOAD_TOO_LARGE',
+ http: { status: 413 },
+ },
+ });
+ throw error;
+ }
+ });
+ },
+ async onRequest({ request, serverContext, fetchAPI, endResponse }) {
+ const blocked = (
+ status: number,
+ message: string,
+ extensions: Record,
+ headers: Record = {},
+ ) =>
+ endResponse(
+ new fetchAPI.Response(
+ JSON.stringify({ errors: [{ message, extensions }] }),
+ {
+ status,
+ headers: { 'Content-Type': 'application/json', ...headers },
+ },
+ ),
+ );
+ // /uploads is handled before GraphQL parsing: it accepts image bytes,
+ // not JSON, and applies its own size, CSRF and session/access checks.
+ // A null response means this request belongs to the GraphQL handler.
const imageResponse = await handleImageRequest(
request,
service,
@@ -57,38 +148,72 @@ export function createApp(
endResponse(imageResponse);
return;
}
+ // Refuse bodies that announce an oversized length before reading
+ // them; onRequestParse counts the bytes of the rest.
+ if (
+ Number(request.headers.get('content-length') ?? 0) >
+ MAX_REQUEST_BYTES
+ ) {
+ blocked(413, 'Request too large.', { code: 'PAYLOAD_TOO_LARGE' });
+ return;
+ }
+ // A request runs an operation if it is a POST or a GET with a
+ // query (the GraphiQL page and malformed GETs run nothing). Both
+ // need the custom header, which a page on another site cannot add
+ // without a CORS preflight; POST also needs a JSON body.
+ const runsOperation =
+ request.method === 'POST' ||
+ (request.method === 'GET' &&
+ new URL(request.url).searchParams.has('query'));
if (
- request.method === 'POST' &&
+ runsOperation &&
(request.headers.get('x-requested-with') !== 'recipe-platform' ||
- request.headers.get('content-type')?.split(';')[0]?.trim() !==
- 'application/json')
+ (request.method === 'POST' &&
+ request.headers.get('content-type')?.split(';')[0]?.trim() !==
+ 'application/json'))
) {
- endResponse(
- new fetchAPI.Response(
- JSON.stringify({
- errors: [
- {
- message: 'Request blocked.',
- extensions: { code: 'FORBIDDEN' },
- },
- ],
- }),
- {
- status: 403,
- headers: { 'Content-Type': 'application/json' },
- },
- ),
+ blocked(403, 'Request blocked.', { code: 'FORBIDDEN' });
+ return;
+ }
+ // Only requests that run an operation are counted, and only now:
+ // refused or operation-less requests cost the server almost nothing
+ // and must not use up a client's budget (a page on another site
+ // could otherwise send them from a visitor's browser).
+ if (!runsOperation) return;
+ const retryAfterSeconds = requestLimiter.take(
+ authClientKey(
+ request,
+ // Node's request, as in the context below.
+ (serverContext as { req?: IncomingMessage } | undefined)?.req
+ ?.socket.remoteAddress,
+ trustProxy,
+ ),
+ );
+ if (retryAfterSeconds !== null) {
+ blocked(
+ 429,
+ 'Too many requests. Please try again shortly.',
+ { code: 'RATE_LIMITED', retryAfterSeconds },
+ { 'Retry-After': String(retryAfterSeconds) },
);
+ return;
}
},
onResponse({ request, response }) {
+ // Includes both new sessions and cookie expiry after logout/invalid auth.
const cookie = cookies.get(request);
if (cookie) response.headers.append('Set-Cookie', cookie);
- response.headers.set('Cache-Control', 'no-store');
+ // GraphQL answers are per-user and never cached. Image responses
+ // set their own policy (imageStorage.ts) and keep it.
+ if (!response.headers.has('Cache-Control'))
+ response.headers.set('Cache-Control', 'no-store');
},
},
],
context: async ({ request, req }) => {
+ // Resolve the cookie against server-side sessions for every operation.
+ // An invalid/expired session clears the cookie; a service error propagates
+ // instead, so a temporary failure does not silently log the user out.
const token = readSessionCookie(request);
const user = token ? await service.currentUser(token) : null;
if (
@@ -104,6 +229,8 @@ export function createApp(
),
user,
sessionToken: user ? token : null,
+ // Auth resolvers call this on login/register/logout. The token stays in
+ // the HttpOnly cookie rather than being returned as GraphQL response data.
setSession: (nextToken) => {
cookies.set(request, sessionCookie(nextToken, secureCookie));
context.sessionToken = nextToken;
diff --git a/apps/api/src/db/demoAccounts.ts b/apps/api/src/db/demoAccounts.ts
new file mode 100644
index 0000000..1376d32
--- /dev/null
+++ b/apps/api/src/db/demoAccounts.ts
@@ -0,0 +1,14 @@
+/*
+ * E-mail addresses of the accounts created by the demo seed (seedData.ts).
+ * They use the reserved .invalid domain, and registration refuses them, so
+ * a real user can never take an address the seed relies on.
+ */
+export const DEMO_COOK_EMAIL = 'demo@example.invalid';
+
+export function demoTasterEmail(taster: number) {
+ return `demo-taster-${taster}@example.invalid`;
+}
+
+export function isReservedDemoEmail(email: string) {
+ return /^demo(-taster-\d+)?@example\.invalid$/i.test(email.trim());
+}
diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts
index 2ac1a59..166d9b6 100644
--- a/apps/api/src/db/schema.ts
+++ b/apps/api/src/db/schema.ts
@@ -2,6 +2,7 @@ import { sql } from 'drizzle-orm';
import {
type AnyPgColumn,
check,
+ customType,
index,
integer,
numeric,
@@ -15,6 +16,11 @@ import {
const project2 = pgSchema('project2');
+// PostgreSQL full-text search document; Drizzle has no built-in type for it.
+const tsvector = customType<{ data: string }>({
+ dataType: () => 'tsvector',
+});
+
export const users = project2.table(
'users',
{
@@ -70,13 +76,54 @@ export const recipes = project2.table(
updatedAt: timestamp('updated_at', { withTimezone: true })
.defaultNow()
.notNull(),
+ /*
+ * Cached rating summary, maintained by a trigger on ratings (migration
+ * 0005) so every write path, including the seed, keeps it correct. Lets
+ * "highest rated" sort on an index instead of averaging all ratings of
+ * every matching recipe per request. NULL means no ratings yet.
+ */
+ ratingAvg: numeric('rating_avg'),
+ ratingCount: integer('rating_count').notNull().default(0),
+ /*
+ * Words of the title, description, ingredient names and tags for
+ * full-text search. Triggers keep it current when the recipe or its
+ * ingredients or tags change (migration 0005). The 'simple'
+ * configuration lowercases words without language-specific stemming,
+ * which suits mixed English and Norwegian.
+ */
+ searchVector: tsvector('search_vector')
+ .notNull()
+ .default(sql`''::tsvector`),
},
(table) => [
index('recipes_author_idx').on(table.authorId),
index('recipes_source_idx').on(table.sourceRecipeId),
+ // One index per public listing order (see recipeRepository list()).
index('recipes_public_created_idx')
.on(table.createdAt, table.id)
.where(sql`${table.visibility} = 'public'`),
+ index('recipes_public_category_created_idx')
+ .on(
+ table.category,
+ table.createdAt.desc().nullsFirst(),
+ table.id.desc().nullsFirst(),
+ )
+ .where(sql`${table.visibility} = 'public'`),
+ index('recipes_public_total_time_idx')
+ .on(
+ sql`(${table.prepMinutes} + ${table.cookMinutes})`,
+ table.createdAt.desc().nullsFirst(),
+ table.id.desc().nullsFirst(),
+ )
+ .where(sql`${table.visibility} = 'public'`),
+ index('recipes_public_rating_idx')
+ .on(
+ table.ratingAvg.desc().nullsLast(),
+ table.createdAt.desc().nullsFirst(),
+ table.id.desc().nullsFirst(),
+ )
+ .where(sql`${table.visibility} = 'public'`),
+ index('recipes_search_idx').using('gin', table.searchVector),
check('recipes_title_not_blank', sql`length(trim(${table.title})) > 0`),
check(
'recipes_category_valid',
diff --git a/apps/api/src/db/seedData.ts b/apps/api/src/db/seedData.ts
index 3bf04a6..508fd76 100644
--- a/apps/api/src/db/seedData.ts
+++ b/apps/api/src/db/seedData.ts
@@ -8,9 +8,14 @@ import { fileURLToPath } from 'node:url';
import type { Pool } from 'pg';
import { seedRecipes } from './seedRecipes.js';
+import { DEMO_COOK_EMAIL, demoTasterEmail } from './demoAccounts.js';
const AUTHOR_ID = '11111111-1111-4111-8111-111111111111';
+// Extra demo accounts that rate the public demo recipes (see seedRatings).
+const TASTER_COUNT = 4;
+const RATING_SCORES = [3, 4, 4, 5, 5] as const;
+
const IMAGE_SOURCE_DIR = fileURLToPath(
new URL('./seed-images/', import.meta.url),
);
@@ -101,7 +106,7 @@ export async function seedDatabase(
(id, name, email, password_hash)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO NOTHING`,
- [AUTHOR_ID, 'Demo Cook', 'demo@example.invalid', passwordHash],
+ [AUTHOR_ID, 'Demo Cook', DEMO_COOK_EMAIL, passwordHash],
);
for (const item of prepared) {
@@ -223,9 +228,61 @@ export async function seedDatabase(
console.log(`Seeded: ${recipe.title}`);
}
+ /*
+ * Demo ratings, so "Highest rated" has data to sort. Four taster
+ * accounts (sharing SEED_PASSWORD) rate about 80 % of the public
+ * recipes with 3–5 stars. Scores come from a hash of recipe and taster,
+ * so every run produces the same data. Existing users and ratings are
+ * kept, as for the rest of the seed. Private recipes are not rated, as
+ * the API also forbids it.
+ */
+ let ratingCount = 0;
+ for (let taster = 1; taster <= TASTER_COUNT; taster += 1) {
+ const tasterId = stableUuid(`taster:${taster}`);
+ const email = demoTasterEmail(taster);
+ await client.query(
+ `INSERT INTO ${schema}.users (id, name, email, password_hash)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT DO NOTHING`,
+ [tasterId, `Demo Taster ${taster}`, email, passwordHash],
+ );
+ // If another account already uses the address (e.g. registered before
+ // it was reserved), the insert was skipped. Rating with tasterId would
+ // then break a foreign key and roll back the whole seed, so skip it.
+ const owner = await client.query<{ id: string }>(
+ `SELECT id FROM ${schema}.users WHERE email = $1`,
+ [email],
+ );
+ if (owner.rows[0]?.id !== tasterId) {
+ console.warn(
+ `Skipping demo ratings from ${email}: the address belongs to another account.`,
+ );
+ continue;
+ }
+ for (const item of prepared) {
+ if (item.recipe.visibility !== 'public') continue;
+ const hash = createHash('sha256')
+ .update(`rating:${item.recipe.slug}:${taster}`)
+ .digest();
+ if (hash[0]! % 5 === 0) continue; // About one in five is left unrated.
+ const result = await client.query(
+ `INSERT INTO ${schema}.ratings (recipe_id, user_id, score)
+ VALUES ($1, $2, $3)
+ ON CONFLICT DO NOTHING`,
+ [
+ item.recipeId,
+ tasterId,
+ RATING_SCORES[hash[1]! % RATING_SCORES.length],
+ ],
+ );
+ ratingCount += result.rowCount ?? 0;
+ }
+ }
+
await client.query('COMMIT');
console.log(`Successfully seeded ${prepared.length} recipes.`);
+ console.log(`Added ${ratingCount} demo ratings.`);
} catch (error) {
await client.query('ROLLBACK');
throw error;
diff --git a/apps/api/src/db/seedRecipes.ts b/apps/api/src/db/seedRecipes.ts
index 5061940..5b6730e 100644
--- a/apps/api/src/db/seedRecipes.ts
+++ b/apps/api/src/db/seedRecipes.ts
@@ -574,17 +574,112 @@ const recipes: Record = {
const PRIVATE_RECIPES = new Set(['raw-egg', 'car-muffin']);
-const DESCRIPTION_OVERRIDES: Record = {
+/*
+ * Hand-written card descriptions, one per recipe (max 200 characters, the
+ * same limit the API enforces). Seeding fails if a recipe has none, so new
+ * demo recipes cannot fall back to generated filler text.
+ */
+const DESCRIPTIONS: Record = {
lasagna:
'A comforting Italian-style lasagna layered with rich beef tomato sauce, pasta sheets, creamy béchamel and melted mozzarella.',
- 'norsk-matpakke':
- 'A traditional Norwegian packed lunch with wholegrain bread, cheese and fresh toppings. Simple, practical and perfect for work or school.',
+ 'fish-burger':
+ 'Breaded white fish fried until crisp, served in a toasted bun with lettuce and a quick lemon mayonnaise.',
+ 'beef-burger':
+ 'A juicy beef patty with melted cheddar, crisp lettuce and tomato in a soft bun. Ready in half an hour.',
+ 'potato-boats':
+ 'Baked potatoes scooped out, mashed with butter and cheddar, refilled and baked until golden. Served with sour cream.',
+ 'baked-potatoes':
+ 'Crisp-skinned oven potatoes with a fluffy inside. Serve with butter and sea salt, or as a side for fish and meat.',
+ shells:
+ 'Pasta shells in a creamy garlic and Parmesan sauce. A quick weeknight dinner made with pantry staples.',
+ salmon:
+ 'Salmon fillets brushed with lemon, dill and garlic, then baked. Light, quick and good with potatoes or vegetables.',
+ cod: 'Tender cod baked in butter with lemon and parsley. A simple Nordic dinner that is ready in under 30 minutes.',
+ 'fried-chicken':
+ 'Chicken thighs marinated in buttermilk, coated in paprika-spiced flour and fried until golden and crunchy.',
+ 'beef-dinner':
+ 'Pan-seared beef steaks with buttery potatoes and green beans. A classic plate for a slightly special evening.',
+ sausage:
+ 'Sausages roasted on one tray with sweet bell peppers and red onion. Few dishes to wash and lots of flavour.',
+ 'fried-sausages':
+ 'Sausages fried with slowly softened onions in butter. A hearty breakfast or a quick lunch.',
+ 'fish-n-chips':
+ 'Cod in a light, crisp batter made with sparkling water, served with thick-cut chips. A British favourite at home.',
+ masala:
+ 'A mild vegetable curry with chickpeas, tomatoes and coconut milk, warmed by garam masala and fresh ginger.',
+ 'tiki-masala':
+ 'Yogurt-marinated chicken simmered in a creamy, spiced tomato sauce. Serve with rice or naan.',
+ 'roasted-chicken':
+ 'A whole chicken roasted with herb butter, lemon and garlic until the skin is golden. Great for Sunday dinner.',
+ 'indian-dish-with-rice':
+ 'Chickpeas simmered in a spiced tomato and onion sauce, served over fluffy basmati rice. Vegetarian and filling.',
+ 'yellow-rice-with-chikcen':
+ 'Chicken and rice cooked together in one pot with turmeric and broth, giving every grain a warm golden colour.',
+ 'peanut-soup':
+ 'A rich soup of sweet potato, peanut butter and tomato, inspired by West African groundnut stews.',
+ 'tomato-soup':
+ 'Ripe tomatoes, onion and garlic simmered and blended into a smooth, creamy soup. Perfect with grilled cheese.',
+ 'sweet-potato-soup':
+ 'Sweet potatoes blended with onion, garlic and broth into a velvety, naturally sweet soup.',
+ 'broth-soup':
+ 'A clear vegetable broth with carrots, celery and egg noodles. Light, warming and easy on the stomach.',
+ pancakes:
+ 'Thin Norwegian pancakes (pannekaker) made from a simple batter of flour, milk and eggs. Serve with jam or sugar.',
+ 'american-pancakes':
+ 'Thick, fluffy pancakes raised with baking powder. Stack them high and finish with syrup or berries.',
+ 'slovenian-pancakes':
+ 'Slovenian palačinke: thin crêpe-like pancakes rolled around jam. A favourite breakfast or dessert.',
+ 'peppered-eggs':
+ 'Softly scrambled eggs cooked slowly in butter with a splash of milk and plenty of black pepper.',
+ 'fried-egg':
+ 'Eggs fried gently in butter until the whites set and the yolks stay runny. Breakfast in ten minutes.',
+ 'english-breakfast':
+ 'Eggs, sausages, baked beans, mushrooms and toast on one plate. A full English breakfast for a slow morning.',
+ 'raw-egg':
+ 'Eggs simmered for 8–10 minutes for firm yolks, then cooled in cold water so they peel easily.',
'roasted-coffee-beans':
'A freshly brewed cup of filter coffee made from aromatic roasted coffee beans.',
+ 'shrimp-salad':
+ 'Cooked shrimp with avocado, cucumber and mixed lettuce, tossed in a light dressing. Fresh and quick.',
+ 'homemade-fries':
+ 'Potato sticks seasoned with paprika and garlic and baked until crisp, using far less oil than deep frying.',
+ 'grilled-cheese':
+ 'Sourdough fried in butter around melted cheddar with a thin layer of Dijon mustard. Crisp outside, gooey inside.',
+ 'norsk-matpakke':
+ 'A traditional Norwegian packed lunch with wholegrain bread, cheese and fresh toppings. Simple, practical and perfect for work or school.',
+ baguette:
+ 'A fresh baguette filled with ham, cheddar and crisp lettuce. A quick lunch to make in ten minutes.',
+ chips:
+ 'Thinly sliced potatoes baked with olive oil, sea salt and paprika until golden and crunchy.',
+ 'plain-rice':
+ 'Fluffy long-grain rice cooked by the absorption method, so the grains stay separate every time.',
+ cake: 'A classic vanilla sponge for birthdays and celebrations, ready to decorate however you like.',
+ 'carrot-cake':
+ 'A moist carrot cake spiced with cinnamon and topped with a smooth cream cheese frosting.',
+ 'orange-cake':
+ 'A soft, buttery sponge cake flavoured with the zest and juice of fresh oranges.',
+ 'vanilla-cake':
+ 'A simple, fluffy vanilla sponge. Good on its own with coffee or as the base for a layered cake.',
'car-cake':
'A colorful homemade birthday cake decorated in the shape of a car.',
'car-wheels-cake':
'A chocolate celebration cake with playful wheel-shaped decorations.',
+ 'oatmeal-muffin':
+ 'Wholesome muffins with rolled oats, lightly sweetened with honey, so they work for breakfast too.',
+ 'chocolate-muffin':
+ 'Rich cocoa muffins with chocolate chips folded into the batter. Soft, moist and quick to make.',
+ 'bringebær-muffins':
+ 'Light muffins packed with fresh raspberries (bringebær). Best eaten warm on the day they are baked.',
+ 'colored-cupcakes':
+ 'Vanilla cupcakes topped with swirls of brightly coloured frosting. Made for parties and birthdays.',
+ 'car-muffin':
+ 'Vanilla birthday muffins piped with buttercream icing and decorated as little cars.',
+ 'white-cookies':
+ 'Simple vanilla sugar cookies, rolled and cut into shapes. Decorate them with icing or enjoy them plain.',
+ 'gingerbread-cookies':
+ 'Traditional Nordic gingerbread (pepperkaker) spiced with ginger and cinnamon and sweetened with golden syrup.',
+ 'chocolate-cookies':
+ 'Soft and chewy cookies with brown sugar and plenty of chocolate chips. Ready in under 30 minutes.',
};
function parseIngredients(
@@ -634,12 +729,13 @@ export const seedRecipes: DemoRecipe[] = Object.entries(recipes).map(
? 'private'
: 'public';
+ const description = DESCRIPTIONS[slug];
+ if (!description) throw new Error(`Missing seed description: ${slug}`);
+
return {
slug,
title,
- description:
- DESCRIPTION_OVERRIDES[slug] ??
- `A homemade ${title.toLowerCase()} recipe featuring flavorful ingredients and straightforward preparation. Suitable for ${category} and inspired by ${cuisine.toLowerCase()} cooking.`,
+ description,
category,
cuisine,
difficulty,
diff --git a/apps/api/src/features/auth/authApp.test.ts b/apps/api/src/features/auth/authApp.test.ts
index e83ddce..0256bd2 100644
--- a/apps/api/src/features/auth/authApp.test.ts
+++ b/apps/api/src/features/auth/authApp.test.ts
@@ -1,6 +1,5 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
-import { print, parse } from 'graphql';
import { createApp } from '../../app.js';
import { createAuthService } from './authService.js';
import type { AuthRepository } from './authRepository.js';
@@ -44,7 +43,8 @@ function setup(secure = false) {
secure,
);
async function request(
- document: Parameters[0],
+ // A generated operation (typed query string) or raw query text.
+ document: { toString(): string },
variables: Record = {},
sentCookie = cookie,
csrf = true,
@@ -56,7 +56,7 @@ function setup(secure = false) {
...(csrf ? { 'X-Requested-With': 'recipe-platform' } : {}),
...(sentCookie ? { Cookie: sentCookie } : {}),
},
- body: JSON.stringify({ query: print(document), variables }),
+ body: JSON.stringify({ query: document.toString(), variables }),
});
const setCookie = response.headers.get('set-cookie');
if (setCookie) cookie = setCookie.split(';')[0]!;
@@ -171,18 +171,13 @@ describe('cookie GraphQL authentication', () => {
it('rejects the old token-bearing GraphQL contract', async () => {
const { request } = setup();
expect(
- (
- await request(
- parse('query { currentUser(sessionToken: "old") { id } }'),
- )
- ).errors,
+ (await request('query { currentUser(sessionToken: "old") { id } }'))
+ .errors,
).toBeDefined();
expect(
(
await request(
- parse(
- 'mutation { login(email:"a@example.com",password:"x") { sessionToken } }',
- ),
+ 'mutation { login(email:"a@example.com",password:"x") { sessionToken } }',
)
).errors,
).toBeDefined();
diff --git a/apps/api/src/features/auth/authService.test.ts b/apps/api/src/features/auth/authService.test.ts
index 609c041..984f6d5 100644
--- a/apps/api/src/features/auth/authService.test.ts
+++ b/apps/api/src/features/auth/authService.test.ts
@@ -106,6 +106,20 @@ describe('authService', () => {
expect(repository.createSession).not.toHaveBeenCalled();
});
+ it('reserves the demo seed addresses', async () => {
+ const repository = createRepository();
+ const service = createAuthService(repository, createPasswordHasher());
+
+ for (const email of [
+ 'demo@example.invalid',
+ 'Demo-Taster-3@example.invalid',
+ ])
+ await expect(
+ service.register('Hasan', email, 'secret123'),
+ ).rejects.toThrow('An account with this email already exists.');
+ expect(repository.createUserWithSession).not.toHaveBeenCalled();
+ });
+
it('logs in with the correct password', async () => {
const repository = createRepository({
findUserByEmail: vi.fn(async () => storedUser),
diff --git a/apps/api/src/features/auth/authService.ts b/apps/api/src/features/auth/authService.ts
index 4034ca6..44ef38b 100644
--- a/apps/api/src/features/auth/authService.ts
+++ b/apps/api/src/features/auth/authService.ts
@@ -1,3 +1,4 @@
+import { isReservedDemoEmail } from '../../db/demoAccounts.js';
import {
loginSchema,
registerSchema,
@@ -54,7 +55,8 @@ export function createAuthService(
const existingUser = await repository.findUserByEmail(normalizedEmail);
- if (existingUser) {
+ // Demo seed addresses are reserved even before the seed has run.
+ if (existingUser || isReservedDemoEmail(normalizedEmail)) {
throw new GraphQLError('An account with this email already exists.', {
extensions: { code: 'EMAIL_TAKEN' },
});
diff --git a/apps/api/src/features/recipes/imageStorage.test.ts b/apps/api/src/features/recipes/imageStorage.test.ts
index e91a3e0..fcf8ded 100644
--- a/apps/api/src/features/recipes/imageStorage.test.ts
+++ b/apps/api/src/features/recipes/imageStorage.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { handleImageRequest } from './imageStorage.js';
import type { AuthService } from '../auth/authService.js';
-import type { ImageStore } from './imageStore.js';
+import { ImageError, type ImageStore } from './imageStore.js';
const token = '11111111-1111-4111-8111-111111111111';
const user = { id: token, name: 'Test Cook', email: 'cook@example.com' };
@@ -15,11 +15,21 @@ const png = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aOioAAAAASUVORK5CYII=',
'base64',
);
-const store: ImageStore = {
+const store = {
upload: vi.fn(async () => `/uploads/${token}.png`),
- read: vi.fn(async () => png),
+ authorize: vi.fn(async () => 'public'),
+ readOriginal: vi.fn(async () => png),
+ readVariant: vi.fn(async () => Buffer.from('variant')),
+ version: vi.fn(async () => '68-1'),
cleanup: vi.fn(async () => 0),
-};
+} satisfies ImageStore;
+function getImage(query = '', headers: Record = {}) {
+ return handleImageRequest(
+ new Request(`http://localhost/uploads/${token}.png${query}`, { headers }),
+ service,
+ store,
+ );
+}
beforeEach(() => vi.clearAllMocks());
function upload(body = png, headers: Record = {}) {
return handleImageRequest(
@@ -40,7 +50,7 @@ function upload(body = png, headers: Record = {}) {
describe('image upload boundary', () => {
it('validates bytes and records the authenticated owner', async () => {
expect((await upload())?.status).toBe(201);
- expect(store.upload).toHaveBeenCalledWith(user.id, png, 'png');
+ expect(store.upload).toHaveBeenCalledWith(user.id, png);
});
it('rejects anonymous, cross-origin-style and invalid uploads before storage', async () => {
expect((await upload(png, { Cookie: '' }))?.status).toBe(401);
@@ -51,7 +61,7 @@ describe('image upload boundary', () => {
expect((await upload(Buffer.alloc(5 * 1024 * 1024 + 1)))?.status).toBe(413);
expect(store.upload).not.toHaveBeenCalled();
});
- it('rejects unsafe paths before looking up files and never caches images', async () => {
+ it('rejects unsafe paths before looking up files', async () => {
expect(
(
await handleImageRequest(
@@ -61,13 +71,64 @@ describe('image upload boundary', () => {
)
)?.status,
).toBe(404);
- expect(store.read).not.toHaveBeenCalled();
- const response = await handleImageRequest(
- new Request(`http://localhost/uploads/${token}.png`),
- service,
- store,
- );
+ expect(store.authorize).not.toHaveBeenCalled();
+ expect(store.readOriginal).not.toHaveBeenCalled();
+ });
+});
+
+describe('image caching', () => {
+ it('lets browsers keep public images but revalidate every time', async () => {
+ const response = await getImage();
+ expect(response?.status).toBe(200);
+ expect(response?.headers.get('cache-control')).toBe('public, no-cache');
+ expect(response?.headers.get('etag')).toBe(`"${token}.png-68-1"`);
+ expect(response?.headers.get('content-type')).toBe('image/png');
+ expect(store.authorize).toHaveBeenCalledWith(`${token}.png`, null);
+ });
+
+ it('marks private images as private so shared caches never store them', async () => {
+ store.authorize.mockResolvedValueOnce('private');
+ const response = await getImage('', {
+ Cookie: `t31_project2_session=${token}`,
+ });
+ expect(response?.headers.get('cache-control')).toBe('private, no-cache');
+ expect(store.authorize).toHaveBeenCalledWith(`${token}.png`, user.id);
+ });
+
+ it('answers a current cached copy with an empty 304 after the access check', async () => {
+ const response = await getImage('', {
+ 'If-None-Match': `W/"other", "${token}.png-68-1"`,
+ });
+ expect(response?.status).toBe(304);
+ expect(await response?.text()).toBe('');
+ expect(store.authorize).toHaveBeenCalled();
+ expect(store.readOriginal).not.toHaveBeenCalled();
+ });
+
+ it('sends the new image when the file was replaced (e.g. re-seeded)', async () => {
+ store.version.mockResolvedValueOnce('70-2');
+ const response = await getImage('', {
+ 'If-None-Match': `"${token}.png-68-1"`,
+ });
+ expect(response?.status).toBe(200);
+ expect(response?.headers.get('etag')).toBe(`"${token}.png-70-2"`);
+ });
+
+ it('does not answer 304 once the viewer may no longer see the image', async () => {
+ store.authorize.mockRejectedValueOnce(new ImageError(404, 'Not found.'));
+ const response = await getImage('', {
+ 'If-None-Match': `"${token}.png-68-1"`,
+ });
+ expect(response?.status).toBe(404);
expect(response?.headers.get('cache-control')).toBe('no-store');
- expect(store.read).toHaveBeenCalledWith(`${token}.png`, null);
+ });
+
+ it('serves resized WebP variants only for the supported widths', async () => {
+ const response = await getImage('?w=480');
+ expect(response?.headers.get('content-type')).toBe('image/webp');
+ expect(response?.headers.get('etag')).toBe(`"${token}.png-68-1-w480"`);
+ expect(store.readVariant).toHaveBeenCalledWith(`${token}.png`, 480);
+ expect((await getImage('?w=123'))?.status).toBe(400);
+ expect(store.readVariant).toHaveBeenCalledTimes(1);
});
});
diff --git a/apps/api/src/features/recipes/imageStorage.ts b/apps/api/src/features/recipes/imageStorage.ts
index e26be81..51af945 100644
--- a/apps/api/src/features/recipes/imageStorage.ts
+++ b/apps/api/src/features/recipes/imageStorage.ts
@@ -1,7 +1,12 @@
import type { AuthService } from '../auth/authService.js';
import { readSessionCookie } from '../auth/sessionCookie.js';
import { imageFilenamePattern } from './imagePaths.js';
-import { ImageError, type ImageStore } from './imageStore.js';
+import {
+ IMAGE_VARIANT_WIDTHS,
+ ImageError,
+ type ImageStore,
+ type ImageVariantWidth,
+} from './imageStore.js';
const MAX_BYTES = 5 * 1024 * 1024;
const contentTypes: Record = {
@@ -31,28 +36,72 @@ function failure(status: number, message: string) {
);
}
+/** Parses ?w=480; null means the original image. */
+function requestedWidth(url: URL): ImageVariantWidth | null | 'invalid' {
+ const value = url.searchParams.get('w');
+ if (value === null) return null;
+ const width = IMAGE_VARIANT_WIDTHS.find(
+ (allowed) => String(allowed) === value,
+ );
+ return width ?? 'invalid';
+}
+
+/** True when the browser's cached copy (If-None-Match) is still current. */
+function isNotModified(request: Request, etag: string) {
+ const header = request.headers.get('if-none-match');
+ if (!header) return false;
+ return header
+ .split(',')
+ .map((tag) => tag.trim().replace(/^W\//, ''))
+ .some((tag) => tag === etag || tag === '*');
+}
+
// A single upload endpoint and a restricted file route; client filenames are never used.
export async function handleImageRequest(
request: Request,
service: AuthService,
store: ImageStore,
): Promise {
- const path = new URL(request.url).pathname;
+ const url = new URL(request.url);
+ const path = url.pathname;
if (path !== '/uploads' && !path.startsWith('/uploads/')) return null;
try {
if (request.method === 'GET' && path.startsWith('/uploads/')) {
const filename = path.slice('/uploads/'.length);
if (!imageFilenamePattern.test(filename))
return failure(404, 'Image not found.');
+ const width = requestedWidth(url);
+ if (width === 'invalid') return failure(400, 'Unsupported image width.');
try {
const token = readSessionCookie(request);
const user = token ? await service.currentUser(token) : null;
- const image = await store.read(filename, user?.id ?? null);
+ const visibility = await store.authorize(filename, user?.id ?? null);
+ /*
+ * Caching: the ETag is the filename plus the original's size and
+ * modification time (and width), so it changes if a file is ever
+ * replaced, as the demo seed does. "no-cache" lets the
+ * browser keep a copy but ask again every time; the access check
+ * above runs on each request and an unchanged image is answered with
+ * an empty 304. A recipe made private therefore stops showing its
+ * image immediately, while repeat visits avoid re-downloading it.
+ */
+ const headers = {
+ ETag: `"${filename}-${await store.version(filename)}${width ? `-w${width}` : ''}"`,
+ 'Cache-Control':
+ visibility === 'public' ? 'public, no-cache' : 'private, no-cache',
+ 'X-Content-Type-Options': 'nosniff',
+ };
+ if (isNotModified(request, headers.ETag))
+ return new Response(null, { status: 304, headers });
+ const image = width
+ ? await store.readVariant(filename, width)
+ : await store.readOriginal(filename);
return new Response(new Uint8Array(image), {
headers: {
- 'Content-Type': contentTypes[filename.split('.').pop()!]!,
- 'X-Content-Type-Options': 'nosniff',
- 'Cache-Control': 'no-store',
+ ...headers,
+ 'Content-Type': width
+ ? 'image/webp'
+ : contentTypes[filename.split('.').pop()!]!,
},
});
} catch (error) {
@@ -95,7 +144,7 @@ export async function handleImageRequest(
const extension = imageExtension(image);
if (!extension || contentTypes[extension] !== type)
return failure(415, 'The file must contain a JPG, PNG, or WebP image.');
- const imageUrl = await store.upload(user.id, image, extension);
+ const imageUrl = await store.upload(user.id, image);
return Response.json({ imageUrl }, { status: 201 });
} catch (error) {
if (error instanceof ImageError)
diff --git a/apps/api/src/features/recipes/imageStore.test.ts b/apps/api/src/features/recipes/imageStore.test.ts
new file mode 100644
index 0000000..192159a
--- /dev/null
+++ b/apps/api/src/features/recipes/imageStore.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment node
+import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Pool } from 'pg';
+import sharp from 'sharp';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createImageStore } from './imageStore.js';
+
+// Variant generation reads files only; the database pool is not used here.
+let directory: string;
+let store: ReturnType;
+const filename = '11111111-1111-4111-8111-111111111111.jpg';
+
+const jpeg = (width: number, height: number, orientation?: number) => {
+ const image = sharp({
+ create: { width, height, channels: 3, background: '#c0603a' },
+ });
+ return (orientation ? image.withMetadata({ orientation }) : image)
+ .jpeg()
+ .toBuffer();
+};
+
+beforeEach(async () => {
+ directory = await mkdtemp(join(tmpdir(), 'image-store-'));
+ store = createImageStore({} as Pool, 'project2', directory);
+});
+afterEach(() => rm(directory, { recursive: true, force: true }));
+
+describe('image variants', () => {
+ it('applies EXIF orientation, so phone photos are not shown sideways', async () => {
+ // Stored landscape pixels with "rotate 90°" metadata, as older uploads.
+ await writeFile(join(directory, filename), await jpeg(200, 100, 6));
+ const variant = await sharp(
+ await store.readVariant(filename, 480),
+ ).metadata();
+ expect([variant.width, variant.height]).toEqual([100, 200]);
+ });
+
+ it('rebuilds variants and changes the version when the original is replaced', async () => {
+ const path = join(directory, filename);
+ await writeFile(path, await jpeg(300, 100));
+ const before = await store.version(filename);
+ expect(
+ (await sharp(await store.readVariant(filename, 480)).metadata()).height,
+ ).toBe(100);
+
+ // Re-seeding writes a different image under the same name.
+ await writeFile(path, await jpeg(100, 300));
+ const later = new Date(Date.now() + 5000);
+ await utimes(path, later, later);
+ expect(await store.version(filename)).not.toBe(before);
+ expect(
+ (await sharp(await store.readVariant(filename, 480)).metadata()).height,
+ ).toBe(300);
+ });
+});
diff --git a/apps/api/src/features/recipes/imageStore.ts b/apps/api/src/features/recipes/imageStore.ts
index a76b17e..d603135 100644
--- a/apps/api/src/features/recipes/imageStore.ts
+++ b/apps/api/src/features/recipes/imageStore.ts
@@ -1,5 +1,6 @@
import {
readdir,
+ rename,
stat,
unlink,
mkdir,
@@ -9,9 +10,40 @@ import {
import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import type { Pool, PoolClient } from 'pg';
+import sharp from 'sharp';
import { imageFilenamePattern } from './imagePaths.js';
import { lockImages } from './imageRepository.js';
+/**
+ * Widths the API can serve as resized WebP variants (?w=480). A fixed list
+ * keeps the variant cache small and stops clients requesting arbitrary sizes.
+ */
+export const IMAGE_VARIANT_WIDTHS = [480, 800] as const;
+export type ImageVariantWidth = (typeof IMAGE_VARIANT_WIDTHS)[number];
+
+/** Public images are referenced by a public recipe; all others are private. */
+export type ImageVisibility = 'public' | 'private';
+
+/** Longest side, in px, of a stored upload after server-side normalisation. */
+export const MAX_UPLOAD_EDGE = 1600;
+
+async function normalizeUpload(original: Buffer) {
+ try {
+ return await sharp(original)
+ .rotate() // Apply EXIF orientation before metadata is dropped.
+ .resize({
+ width: MAX_UPLOAD_EDGE,
+ height: MAX_UPLOAD_EDGE,
+ fit: 'inside',
+ withoutEnlargement: true,
+ })
+ .webp({ quality: 80 })
+ .toBuffer();
+ } catch {
+ throw new ImageError(415, 'The file could not be read as an image.');
+ }
+}
+
export class ImageError extends Error {
constructor(
public status: number,
@@ -78,9 +110,107 @@ export function createImageStore(
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
}
+ /*
+ * Resized variants live in /variants//.webp. The
+ * folder name does not match imageFilenamePattern, so files() lists only
+ * originals; variantBytes() adds the variants to the global storage total.
+ */
+ const variantPath = (filename: string, width: number) =>
+ join(
+ directory,
+ 'variants',
+ String(width),
+ filename.replace(/\.[a-z]+$/, '.webp'),
+ );
+ async function variantBytes() {
+ let total = 0;
+ for (const width of IMAGE_VARIANT_WIDTHS) {
+ const folder = join(directory, 'variants', String(width));
+ let names: string[];
+ try {
+ names = await readdir(folder);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw error;
+ }
+ for (const name of names) {
+ try {
+ total += (await stat(join(folder, name))).size;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ }
+ return total;
+ }
+ /**
+ * A WebP copy resized to `width`, generated on first request and cached on
+ * disk. Callers must authorize() first. Concurrent first requests may both
+ * generate it; the atomic rename makes the last one win harmlessly.
+ */
+ /** Size and modification time of the original; 404 if it is missing. */
+ async function originalStat(filename: string) {
+ try {
+ return await stat(join(directory, filename));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ throw new ImageError(404, 'Image not found.');
+ throw error;
+ }
+ }
+ async function readVariant(filename: string, width: ImageVariantWidth) {
+ const path = variantPath(filename, width);
+ const original = await originalStat(filename);
+ try {
+ // Reuse the cached variant unless the original was replaced after it
+ // was made (the demo seed rewrites its images under the same names).
+ if ((await stat(path)).mtimeMs >= original.mtimeMs)
+ return await readFile(path);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ const variant = await sharp(await readOriginal(filename))
+ .rotate() // Older uploads were stored before EXIF auto-rotation.
+ .resize({ width, withoutEnlargement: true })
+ .webp({ quality: 75 })
+ .toBuffer();
+ await mkdir(join(directory, 'variants', String(width)), {
+ recursive: true,
+ });
+ const temporary = `${path}.${randomUUID()}.tmp`;
+ await writeFile(temporary, variant);
+ await rename(temporary, path);
+ return variant;
+ }
+ async function removeVariants(filename: string) {
+ for (const width of IMAGE_VARIANT_WIDTHS) {
+ try {
+ await unlink(variantPath(filename, width));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ }
+ async function readOriginal(filename: string) {
+ try {
+ return await readFile(join(directory, filename));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ throw new ImageError(404, 'Image not found.');
+ throw error;
+ }
+ }
return {
- async upload(userId: string, bytes: Buffer, extension: string) {
- return locked(async (client) => {
+ /**
+ * Stores an uploaded image for `userId` and returns its /uploads/ URL.
+ * Every upload is normalised on the server, whatever the client did:
+ * rotated upright from its EXIF orientation, scaled to at most
+ * MAX_UPLOAD_EDGE px on its longest side and re-encoded as WebP. Metadata
+ * such as GPS position is not copied. Quotas count the stored size.
+ */
+ async upload(userId: string, original: Buffer) {
+ const bytes = await normalizeUpload(original);
+ const imageUrl = await locked(async (client) => {
const usage = await client.query<{ bytes: string; recent: number }>(
`SELECT coalesce(sum(byte_size),0) AS bytes, count(*) FILTER (WHERE created_at > now()-interval '1 hour')::int AS recent FROM ${images} WHERE owner_id=$1`,
[userId],
@@ -95,16 +225,16 @@ export function createImageStore(
const stored = await files();
if (
stored.length >= limits.totalFiles ||
- stored.reduce((sum, file) => sum + file.size, 0) + bytes.length >
+ stored.reduce((sum, file) => sum + file.size, 0) +
+ (await variantBytes()) +
+ bytes.length >
limits.totalBytes
)
throw new ImageError(
507,
'Image storage is full. Please try again later.',
);
- const filename = `${randomUUID()}.${extension}`;
- if (!imageFilenamePattern.test(filename))
- throw new ImageError(415, 'Unsupported image type.');
+ const filename = `${randomUUID()}.webp`;
let written = false;
try {
await writeFile(join(directory, filename), bytes, { flag: 'wx' });
@@ -119,22 +249,47 @@ export function createImageStore(
}
return `/uploads/${filename}`;
});
+ // Pre-build the card variants now, outside the lock, so the first
+ // visitor does not wait. Best effort: readVariant() retries lazily.
+ const filename = imageUrl.slice('/uploads/'.length);
+ await Promise.all(
+ IMAGE_VARIANT_WIDTHS.map((width) =>
+ readVariant(filename, width).catch(() => undefined),
+ ),
+ );
+ return imageUrl;
},
- async read(filename: string, userId: string | null) {
- const allowed = await pool.query(
- `SELECT 1 FROM ${images} i WHERE i.filename=$1 AND (
+ /**
+ * Checks that the viewer may see an image and reports whether it is
+ * public. Readable: images on a public recipe, images on the viewer's
+ * own recipes, and the viewer's own uploads not yet attached to a recipe.
+ * Runs on every request, including cache revalidations, so an image
+ * stops being served as soon as its recipe becomes private.
+ */
+ async authorize(
+ filename: string,
+ userId: string | null,
+ ): Promise {
+ const allowed = await pool.query<{ public: boolean }>(
+ `SELECT EXISTS(SELECT 1 FROM ${recipes} r WHERE r.image_url='/uploads/' || i.filename AND r.visibility='public') AS public
+ FROM ${images} i WHERE i.filename=$1 AND (
EXISTS(SELECT 1 FROM ${recipes} r WHERE r.image_url='/uploads/' || i.filename AND (r.visibility='public' OR r.author_id=$2::uuid))
OR (i.owner_id=$2::uuid AND NOT ${reference}))`,
[filename, userId],
);
if (!allowed.rowCount) throw new ImageError(404, 'Image not found.');
- try {
- return await readFile(join(directory, filename));
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT')
- throw new ImageError(404, 'Image not found.');
- throw error;
- }
+ return allowed.rows[0]!.public ? 'public' : 'private';
+ },
+ /** Original file bytes. Call authorize() first. */
+ readOriginal,
+ readVariant,
+ /**
+ * Changes whenever the original file is replaced, for use in ETags, so
+ * browsers never keep showing an image that was overwritten (re-seed).
+ */
+ async version(filename: string) {
+ const original = await originalStat(filename);
+ return `${original.size}-${Math.floor(original.mtimeMs)}`;
},
async cleanup() {
return locked(async (client) => {
@@ -153,11 +308,37 @@ export function createImageStore(
);
if (protectedFile.rowCount) continue;
await removeFile(file.name);
+ await removeVariants(file.name);
await client.query(`DELETE FROM ${images} WHERE filename=$1`, [
file.name,
]);
removed += 1;
}
+ // Variants (and interrupted .tmp writes) whose original no longer
+ // exists, e.g. removed by hand or by an earlier cleanup, would
+ // otherwise count against the storage limit forever.
+ const originals = new Set(
+ (await files()).map((file) => file.name.replace(/\.[a-z]+$/, '')),
+ );
+ for (const width of IMAGE_VARIANT_WIDTHS) {
+ const folder = join(directory, 'variants', String(width));
+ let names: string[] = [];
+ try {
+ names = await readdir(folder);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ for (const name of names) {
+ const stem = name.split('.')[0]!;
+ if (originals.has(stem)) continue;
+ try {
+ await unlink(join(folder, name));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
+ throw error;
+ }
+ }
+ }
// Missing files must not leave permanent quota usage behind.
await client.query(
`DELETE FROM ${images} i WHERE NOT ${reference} AND created_at < now()-interval '24 hours' AND NOT (filename=ANY($1::text[]))`,
diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts
index ffd4316..601c560 100644
--- a/apps/api/src/features/recipes/recipeRepository.ts
+++ b/apps/api/src/features/recipes/recipeRepository.ts
@@ -4,16 +4,58 @@ import { db } from '../../db/client.js';
import type { CookbookScope, Recipe } from '../../generated.js';
import type { RecipeInput, ListInput } from './recipeValidation.js';
import { validateImageReference, lockImages } from './imageRepository.js';
+import { DEFAULT_API_LIMITS, type ApiLimits } from '../../apiLimits.js';
-export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
+/**
+ * Turns the user's search text into a PostgreSQL tsquery that matches
+ * recipes containing every word, each as a prefix: "chick rice" becomes
+ * "chick:* & rice:*" and finds "Rice with chicken". Only letters and digits
+ * are kept, so input such as "soup &" or "(" can never break the query
+ * syntax. Every word is used; the 200-character input limit bounds the
+ * query, and repeated words are only searched once. Returns '' when there
+ * is nothing to search for.
+ */
+export function toSearchQuery(search: string, wordStartsOnly = false) {
+ const words = search.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
+ // D matches ordinary words. Longer terms can also match indexed title fragments.
+ return [...new Set(words)]
+ .map(
+ (word) =>
+ `${word}:*${wordStartsOnly || Array.from(word).length < 3 ? 'D' : ''}`,
+ )
+ .join(' & ');
+}
+
+/**
+ * Builds the SQL data layer used by recipeResolvers.ts. Resolvers validate
+ * input and require a signed-in user for writes and Cookbook; this layer
+ * applies row visibility, ownership checks and transactional writes.
+ * An injected pool/schema lets integration tests use isolated database schemas.
+ */
+export function createRecipeRepository(
+ pool: Pool = db,
+ schema = 'project2',
+ limits: Pick<
+ ApiLimits,
+ 'recipesPerHour' | 'recipesPerUser'
+ > = DEFAULT_API_LIMITS,
+) {
if (!/^[a-z_][a-z0-9_]*$/.test(schema))
throw new Error('Invalid database schema.');
- const t = (name: string) => `"${schema}"."${name}"`;
+ // SQL parameters bind values, not identifiers. Validate the injected schema
+ // above and qualify the fixed table names below; user input stays in $n values.
+ const table = (name: string) => `"${schema}"."${name}"`;
+ // In read/list SQL, $1 is the viewer's ID (null for anonymous requests).
const ownedByViewer = 'r.author_id=$1::uuid';
const publicRecipe = "r.visibility='public'";
const visibleToViewer = `(${publicRecipe} OR ${ownedByViewer})`;
- const savedByViewer = `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`;
+ const savedByViewer = `EXISTS(SELECT 1 FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`;
+ /**
+ * Explore exposes only public recipes. Cookbook also requires membership
+ * (created/saved/either), but saving a recipe never grants access after its
+ * owner makes it private. Only the owner can read private recipes.
+ */
function listAccessCondition(scope: 'explore' | CookbookScope) {
if (scope === 'explore') return publicRecipe;
const membership: Record = {
@@ -24,10 +66,12 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
return `${visibleToViewer} AND (${membership[scope]})`;
}
+ /** Uses the same search, category and time predicates for count and page rows. */
function listFilterConditions() {
// Keep filter parameters separate from access rules; shared by count and rows.
+ // $2 is a tsquery from toSearchQuery(); search_vector has a GIN index.
return [
- "($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0)",
+ "($2='' OR r.search_vector @@ to_tsquery('simple',$2))",
'($3::text IS NULL OR r.category=$3)',
'($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)',
];
@@ -40,26 +84,27 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
to_char(r.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt",
json_build_object('id',u.id,'name',u.name) AS author,
coalesce(r.author_id = $1::uuid,false) AS "isCreatedByCurrentUser",
- EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved",
- (SELECT count(*)::int FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount",
- (SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating,
- (SELECT score FROM ${t('ratings')} WHERE recipe_id=r.id AND user_id=$1::uuid) AS "userRating",
- coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${t('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients,
- coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${t('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions,
- coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags
- FROM ${t('recipes')} r JOIN ${t('users')} u ON u.id=r.author_id`;
+ EXISTS(SELECT 1 FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved",
+ (SELECT count(*)::int FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount",
+ json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) AS rating,
+ (SELECT score FROM ${table('ratings')} WHERE recipe_id=r.id AND user_id=$1::uuid) AS "userRating",
+ coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${table('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients,
+ coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${table('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions,
+ coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${table('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags
+ FROM ${table('recipes')} r JOIN ${table('users')} u ON u.id=r.author_id`;
// Card lists do not aggregate ingredients or instructions or join authors.
const summarySelect = `SELECT r.id, r.title, r.description, r.visibility,
r.image_url AS "imageUrl", r.prep_minutes AS "prepMinutes",
r.cook_minutes AS "cookMinutes", r.servings,
coalesce(r.author_id=$1::uuid,false) AS "isCreatedByCurrentUser",
- EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved",
- coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags,
- (SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating
- FROM ${t('recipes')} r`;
+ EXISTS(SELECT 1 FROM ${table('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved",
+ coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${table('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags,
+ json_build_object('average',coalesce(round(r.rating_avg,1),0)::float,'count',r.rating_count) AS rating
+ FROM ${table('recipes')} r`;
- async function transaction(work: (client: PoolClient) => Promise) {
+ /** Runs one transaction attempt and releases its connection on success or failure. */
+ async function attempt(work: (client: PoolClient) => Promise) {
const client = await pool.connect();
try {
await client.query('BEGIN');
@@ -73,6 +118,31 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
client.release();
}
}
+ /**
+ * The API locks a recipe before its ratings, ingredients or tags. Direct
+ * SQL changes to a child table can lock the child row first, then the recipe
+ * through a trigger. Conflicting lock orders can cause a deadlock (40P01),
+ * which PostgreSQL resolves by aborting a transaction.
+ * Lock order cannot be forced on such external writers,
+ * so an API transaction that loses is rolled back and run again, which
+ * then simply waits for the other writer. Serialization failures (40001)
+ * are retried the same way. Work functions only touch the database, so
+ * running them again is safe.
+ */
+ async function transaction(work: (client: PoolClient) => Promise) {
+ for (let tries = 1; ; tries++) {
+ try {
+ return await attempt(work);
+ } catch (error) {
+ const code = (error as { code?: unknown }).code;
+ if (tries >= 3 || (code !== '40P01' && code !== '40001')) throw error;
+ await new Promise((resolve) =>
+ setTimeout(resolve, tries * 20 + Math.random() * 30),
+ );
+ }
+ }
+ }
+ /** Returns full details for a visible recipe, or null for missing/inaccessible IDs. */
async function read(
executor: Pick,
id: string,
@@ -84,14 +154,20 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
);
return result.rows[0] ?? null;
}
+ /** Reads a mutation result in the same transaction; a missing row rolls it back. */
async function readRequired(client: PoolClient, id: string, userId: string) {
const recipe = await read(client, id, userId);
if (!recipe) throw new Error('Recipe could not be read after writing.');
return recipe;
}
- async function owned(client: PoolClient, id: string, userId: string) {
+ /** Locks an owned recipe for writing; missing and non-owned IDs share one error. */
+ async function lockOwnedRecipe(
+ client: PoolClient,
+ id: string,
+ userId: string,
+ ) {
const result = await client.query(
- `SELECT id FROM ${t('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`,
+ `SELECT id FROM ${table('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`,
[id, userId],
);
if (!result.rowCount)
@@ -99,32 +175,80 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
extensions: { code: 'NOT_FOUND' },
});
}
- async function children(client: PoolClient, id: string, input: RecipeInput) {
- for (const [index, ingredient] of input.ingredients.entries()) {
+ /**
+ * Inserts ingredients, instructions and tags within the caller's transaction.
+ * One INSERT per child table keeps query count independent of recipe size;
+ * WITH ORDINALITY preserves input order with positions starting at 1.
+ */
+ async function insertRecipeChildren(
+ client: PoolClient,
+ id: string,
+ input: RecipeInput,
+ ) {
+ await client.query(
+ `INSERT INTO ${table('recipe_ingredients')} (recipe_id,name,amount,unit,note,position)
+ SELECT $1, i.name, i.amount, i.unit, i.note, i.position
+ FROM unnest($2::text[], $3::numeric[], $4::text[], $5::text[]) WITH ORDINALITY AS i(name, amount, unit, note, position)`,
+ [
+ id,
+ input.ingredients.map((ingredient) => ingredient.name),
+ input.ingredients.map((ingredient) => String(ingredient.amount)),
+ input.ingredients.map((ingredient) => ingredient.unit),
+ input.ingredients.map((ingredient) => ingredient.note),
+ ],
+ );
+ await client.query(
+ `INSERT INTO ${table('recipe_instructions')} (recipe_id,text,position)
+ SELECT $1, i.text, i.position
+ FROM unnest($2::text[]) WITH ORDINALITY AS i(text, position)`,
+ [id, input.instructions],
+ );
+ if (input.tags.length)
await client.query(
- `INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,$2,$3,$4,$5,$6)`,
- [
- id,
- ingredient.name,
- ingredient.amount,
- ingredient.unit,
- ingredient.note,
- index + 1,
- ],
+ `INSERT INTO ${table('recipe_tags')} (recipe_id,tag) SELECT $1, unnest($2::text[])`,
+ [id, input.tags],
);
- }
- for (const [index, instruction] of input.instructions.entries())
- await client.query(
- `INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) VALUES ($1,$2,$3)`,
- [id, instruction, index + 1],
+ }
+ /**
+ * Recipe creation quota per user. A per-user lock makes parallel creates
+ * by the same user count one after another, so they cannot all pass the
+ * check together. Recipes created directly in the database (seed, tests)
+ * are not limited.
+ */
+ async function checkCreateQuota(client: PoolClient, userId: string) {
+ await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [
+ `${schema}:recipe-create:${userId}`,
+ ]);
+ const usage = await client.query<{
+ total: number;
+ recent: number;
+ retryAfter: number | null;
+ }>(
+ `SELECT count(*)::int AS total,
+ count(*) FILTER (WHERE created_at > now()-interval '1 hour')::int AS recent,
+ ceil(extract(epoch FROM min(created_at) FILTER (WHERE created_at > now()-interval '1 hour') + interval '1 hour' - now()))::int AS "retryAfter"
+ FROM ${table('recipes')} WHERE author_id=$1`,
+ [userId],
+ );
+ const { total, recent, retryAfter } = usage.rows[0]!;
+ if (total >= limits.recipesPerUser)
+ throw new GraphQLError(
+ `You can have at most ${limits.recipesPerUser} recipes. Delete one to add another.`,
+ { extensions: { code: 'QUOTA_EXCEEDED' } },
);
- for (const tag of input.tags)
- await client.query(
- `INSERT INTO ${t('recipe_tags')} (recipe_id,tag) VALUES ($1,$2)`,
- [id, tag],
+ if (recent >= limits.recipesPerHour)
+ throw new GraphQLError(
+ 'You have created many recipes in the last hour. Please try again later.',
+ {
+ extensions: {
+ code: 'RATE_LIMITED',
+ retryAfterSeconds: Math.max(1, retryAfter ?? 3600),
+ },
+ },
);
}
- const values = (input: RecipeInput) => [
+ /** Keeps create/update parameters in the order of their shared recipe columns. */
+ const recipeColumnValues = (input: RecipeInput) => [
input.title,
input.description,
input.imageUrl,
@@ -137,7 +261,9 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
input.servings,
];
return {
+ /** Reads one public or owned recipe; inaccessible IDs return null. */
get: (id: string, userId: string | null) => read(pool, id, userId),
+ /** Returns a filtered, sorted page of card summaries and its matching count. */
async list(
input: ListInput,
userId: string | null,
@@ -147,30 +273,51 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
newest: 'r.created_at DESC,r.id DESC',
quickest:
'r.prep_minutes+r.cook_minutes ASC,r.created_at DESC,r.id DESC',
- highest_rated: `(SELECT avg(score) FROM ${t('ratings')} WHERE recipe_id=r.id) DESC NULLS LAST,r.created_at DESC,r.id DESC`,
+ highest_rated:
+ 'r.rating_avg DESC NULLS LAST,r.created_at DESC,r.id DESC',
}[input.sort];
const where = ` WHERE ${[listAccessCondition(scope), ...listFilterConditions()].join(' AND ')}`;
+ const searchQuery = toSearchQuery(input.search);
+ const rankByWordStart = searchQuery
+ ? "(r.search_vector @@ to_tsquery('simple',$7)) DESC, "
+ : '';
const args = [
userId,
- input.search,
+ searchQuery,
input.category ?? null,
input.maxCookingMinutes ?? null,
];
- // Count and rows share a snapshot, including when another request creates/deletes recipes.
+ // REPEATABLE READ keeps count and rows on the same snapshot: concurrent
+ // creates/deletes cannot change the result set between these two queries.
return transaction(async (client) => {
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
const count = await client.query<{ total: number }>(
- `SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${t('recipes')} r` +
+ `SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${table('recipes')} r` +
where,
args,
);
const totalCount = count.rows[0]!.total;
const totalPages = Math.ceil(totalCount / input.pageSize);
+ // Filters or deletions may invalidate a bookmarked page. Clamp to the
+ // last available page; empty results use page 1 with totalPages = 0.
const page = Math.min(input.page, Math.max(totalPages, 1));
- const rows = await client.query(
- summarySelect + where + ` ORDER BY ${order} LIMIT $5 OFFSET $6`,
- [...args, input.pageSize, (page - 1) * input.pageSize],
- );
+ // With no matches there is nothing to fetch. Skipping the query also
+ // avoids a worst case: for a word that matches nothing, the planner
+ // may scan the whole date index looking for a first page.
+ const rows =
+ totalCount === 0
+ ? { rows: [] }
+ : await client.query(
+ summarySelect +
+ where +
+ ` ORDER BY ${rankByWordStart}${order} LIMIT $5 OFFSET $6`,
+ [
+ ...args,
+ input.pageSize,
+ (page - 1) * input.pageSize,
+ ...(searchQuery ? [toSearchQuery(input.search, true)] : []),
+ ],
+ );
return {
items: rows.rows,
totalCount,
@@ -180,21 +327,42 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
};
});
},
+ /** Checks quota/image access and inserts the recipe and children atomically. */
async create(input: RecipeInput, userId: string) {
return transaction(async (client) => {
+ await checkCreateQuota(client, userId);
await validateImageReference(client, schema, input.imageUrl, userId);
const result = await client.query<{ id: string }>(
- `INSERT INTO ${t('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`,
- [...values(input), userId],
+ `INSERT INTO ${table('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`,
+ [...recipeColumnValues(input), userId],
);
const id = result.rows[0]!.id;
- await children(client, id, input);
+ await insertRecipeChildren(client, id, input);
return readRequired(client, id, userId);
});
},
- async update(id: string, input: RecipeInput, userId: string) {
+ /** Replaces an owned recipe and children, checking the supplied version if present. */
+ async update(
+ id: string,
+ input: RecipeInput,
+ userId: string,
+ expectedUpdatedAt?: string | null,
+ ) {
return transaction(async (client) => {
- await owned(client, id, userId);
+ await lockOwnedRecipe(client, id, userId);
+ // Optimistic concurrency: compare with updatedAt as the API serves
+ // it (milliseconds, UTC), under the row lock lockOwnedRecipe() just took.
+ if (expectedUpdatedAt) {
+ const current = await client.query<{ updatedAt: string }>(
+ `SELECT to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt" FROM ${table('recipes')} WHERE id=$1`,
+ [id],
+ );
+ if (current.rows[0]!.updatedAt !== expectedUpdatedAt)
+ throw new GraphQLError(
+ 'This recipe was changed after you opened it.',
+ { extensions: { code: 'CONFLICT' } },
+ );
+ }
await validateImageReference(
client,
schema,
@@ -203,31 +371,35 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
id,
);
await client.query(
- `UPDATE ${t('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`,
- [...values(input), id],
+ `UPDATE ${table('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`,
+ [...recipeColumnValues(input), id],
);
for (const name of [
'recipe_ingredients',
'recipe_instructions',
'recipe_tags',
])
- await client.query(`DELETE FROM ${t(name)} WHERE recipe_id=$1`, [id]);
- await children(client, id, input);
+ await client.query(`DELETE FROM ${table(name)} WHERE recipe_id=$1`, [
+ id,
+ ]);
+ await insertRecipeChildren(client, id, input);
return readRequired(client, id, userId);
});
},
+ /** Deletes an owned recipe; the image lock coordinates with attachment/cleanup. */
async delete(id: string, userId: string) {
return transaction(async (client) => {
- await owned(client, id, userId);
+ await lockOwnedRecipe(client, id, userId);
await lockImages(client, schema);
- await client.query(`DELETE FROM ${t('recipes')} WHERE id=$1`, [id]);
+ await client.query(`DELETE FROM ${table('recipes')} WHERE id=$1`, [id]);
return true;
});
},
+ /** Saves another user's public recipe idempotently, locking visibility until commit. */
async save(id: string, userId: string) {
return transaction(async (client) => {
const result = await client.query(
- `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`,
+ `SELECT id FROM ${table('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`,
[id, userId],
);
if (!result.rowCount)
@@ -236,23 +408,28 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
{ extensions: { code: 'FORBIDDEN' } },
);
await client.query(
- `INSERT INTO ${t('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`,
+ `INSERT INTO ${table('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`,
[userId, id],
);
return readRequired(client, id, userId);
});
},
+ /** Removes only this user's saved link, even if the recipe is no longer visible. */
async unsave(id: string, userId: string) {
await pool.query(
- `DELETE FROM ${t('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`,
+ `DELETE FROM ${table('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`,
[userId, id],
);
return true;
},
+ /** Inserts/replaces this user's rating on another user's public recipe. */
async rate(id: string, score: number, userId: string) {
return transaction(async (client) => {
const result = await client.query(
- `SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`,
+ // Exclusive, not FOR SHARE: the ratings trigger updates this row's
+ // cached rating. Two raters holding a shared lock would each wait
+ // for the other to release it before updating, a deadlock.
+ `SELECT id FROM ${table('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR NO KEY UPDATE`,
[id, userId],
);
if (!result.rowCount)
@@ -263,19 +440,28 @@ export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
},
);
await client.query(
- `INSERT INTO ${t('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,$3)
+ `INSERT INTO ${table('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,$3)
ON CONFLICT (user_id,recipe_id) DO UPDATE SET score=EXCLUDED.score, updated_at=now()`,
[id, userId, score],
);
return readRequired(client, id, userId);
});
},
+ /** Removes only this user's rating; an already absent rating is a successful no-op. */
async removeRating(id: string, userId: string) {
- await pool.query(
- `DELETE FROM ${t('ratings')} WHERE recipe_id=$1 AND user_id=$2`,
- [id, userId],
- );
- return true;
+ return transaction(async (client) => {
+ // Lock the recipe before the rating, in the same order as rate(), so
+ // a concurrent rate and remove by the same user cannot deadlock.
+ await client.query(
+ `SELECT id FROM ${table('recipes')} WHERE id=$1 FOR NO KEY UPDATE`,
+ [id],
+ );
+ await client.query(
+ `DELETE FROM ${table('ratings')} WHERE recipe_id=$1 AND user_id=$2`,
+ [id, userId],
+ );
+ return true;
+ });
},
};
}
diff --git a/apps/api/src/features/recipes/recipeResolvers.ts b/apps/api/src/features/recipes/recipeResolvers.ts
index 044fcc1..1522c8f 100644
--- a/apps/api/src/features/recipes/recipeResolvers.ts
+++ b/apps/api/src/features/recipes/recipeResolvers.ts
@@ -58,6 +58,7 @@ export function createRecipeResolvers(repository: RecipeRepository) {
recipeId(args.id),
validate(recipeInputSchema, args.input),
userId,
+ validate(z.string().max(40).nullish(), args.expectedUpdatedAt),
);
},
deleteRecipe: (_parent, args, context) =>
diff --git a/apps/api/src/features/recipes/recipeSearch.test.ts b/apps/api/src/features/recipes/recipeSearch.test.ts
new file mode 100644
index 0000000..bc63f45
--- /dev/null
+++ b/apps/api/src/features/recipes/recipeSearch.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+import { toSearchQuery } from './recipeRepository.js';
+
+describe('toSearchQuery', () => {
+ it('requires every word and matches word prefixes', () => {
+ expect(toSearchQuery('chicken rice')).toBe('chicken:* & rice:*');
+ expect(toSearchQuery(' Chick ')).toBe('chick:*');
+ });
+
+ it('can restrict every term to ordinary word starts for ranking', () => {
+ expect(toSearchQuery('cake in', true)).toBe('cake:*D & in:*D');
+ });
+
+ it('keeps non-English letters and digits', () => {
+ expect(toSearchQuery('Palačinke')).toBe('palačinke:*');
+ expect(toSearchQuery('bringebær muffins')).toBe('bringebær:* & muffins:*');
+ expect(toSearchQuery('15 min')).toBe('15:*D & min:*');
+ });
+
+ it('splits hyphenated words like the database does', () => {
+ expect(toSearchQuery('sunny-side-up')).toBe('sunny:* & side:* & up:*D');
+ });
+
+ it('drops tsquery syntax so user input can never break the query', () => {
+ expect(toSearchQuery('soup &')).toBe('soup:*');
+ expect(toSearchQuery("it's (soup) | !cake:*")).toBe(
+ 'it:*D & s:*D & soup:* & cake:*',
+ );
+ });
+
+ it('returns an empty query when there is nothing to search for', () => {
+ expect(toSearchQuery('')).toBe('');
+ expect(toSearchQuery('&|!():*')).toBe('');
+ });
+
+ it('uses every word of a long search, each only once', () => {
+ const words = 'one two three four five six seven eight nine ten';
+ expect(toSearchQuery(words).split(' & ')).toHaveLength(10);
+ expect(toSearchQuery(`${words} ten`)).toBe(toSearchQuery(words));
+ expect(toSearchQuery(words)).toMatch(/ten:\*$/);
+ });
+});
diff --git a/apps/api/src/features/recipes/recipeValidation.ts b/apps/api/src/features/recipes/recipeValidation.ts
index 116dc14..cbf9e55 100644
--- a/apps/api/src/features/recipes/recipeValidation.ts
+++ b/apps/api/src/features/recipes/recipeValidation.ts
@@ -1,5 +1,13 @@
import { GraphQLError } from 'graphql';
import { z } from 'zod';
+import {
+ MAX_INGREDIENTS,
+ MAX_INSTRUCTIONS,
+ MAX_SERVINGS,
+ MAX_TAG_LENGTH,
+ MAX_TAGS,
+ MIN_SERVINGS,
+} from '@t31/validation/recipe';
import { uploadedImagePattern } from './imagePaths.js';
export const categorySchema = z.enum([
@@ -31,7 +39,7 @@ export const recipeInputSchema = z.object({
visibility: z.enum(['public', 'private']),
prepMinutes: z.number().int().min(0).max(10080),
cookMinutes: z.number().int().min(0).max(10080),
- servings: z.number().int().min(1).max(1000),
+ servings: z.number().int().min(MIN_SERVINGS).max(MAX_SERVINGS),
ingredients: z
.array(
z.object({
@@ -49,11 +57,14 @@ export const recipeInputSchema = z.object({
}),
)
.min(1)
- .max(100),
- instructions: z.array(z.string().trim().min(1).max(5000)).min(1).max(100),
+ .max(MAX_INGREDIENTS),
+ instructions: z
+ .array(z.string().trim().min(1).max(5000))
+ .min(1)
+ .max(MAX_INSTRUCTIONS),
tags: z
- .array(z.string().trim().toLowerCase().min(1).max(50))
- .max(30)
+ .array(z.string().trim().toLowerCase().min(1).max(MAX_TAG_LENGTH))
+ .max(MAX_TAGS)
.transform((values) => [...new Set(values)]),
});
diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts
index 9d173b2..dfe2dc0 100644
--- a/apps/api/src/generated.ts
+++ b/apps/api/src/generated.ts
@@ -82,6 +82,7 @@ export type MutationCreateRecipeArgs = {
export type MutationUpdateRecipeArgs = {
id: Scalars['ID']['input'];
input: RecipeInput;
+ expectedUpdatedAt?: InputMaybe;
};
export type MutationDeleteRecipeArgs = {
diff --git a/apps/api/src/graphiql.test.ts b/apps/api/src/graphiql.test.ts
new file mode 100644
index 0000000..5d89092
--- /dev/null
+++ b/apps/api/src/graphiql.test.ts
@@ -0,0 +1,29 @@
+// @vitest-environment node
+import { tmpdir } from 'node:os';
+import { describe, expect, it } from 'vitest';
+import { createApp } from './app.js';
+
+// A browser opening /graphql asks for HTML; Yoga answers with GraphiQL only
+// when it is enabled. No database query runs for this request.
+async function openInBrowser(enableGraphiql?: boolean) {
+ const app = createApp(undefined, false, false, {}, tmpdir(), enableGraphiql);
+ return app.fetch('http://localhost/graphql', {
+ headers: { accept: 'text/html' },
+ });
+}
+
+describe('GraphiQL', () => {
+ it('is served by default (API_GRAPHIQL unset)', async () => {
+ delete process.env.API_GRAPHIQL;
+ const response = await openInBrowser();
+ expect(response.headers.get('content-type')).toContain('text/html');
+ expect(await response.text()).toContain('GraphiQL');
+ });
+
+ it('is not served when API_GRAPHIQL=false', async () => {
+ const response = await openInBrowser(false);
+ expect(response.headers.get('content-type') ?? '').not.toContain(
+ 'text/html',
+ );
+ });
+});
diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql
index 92bfd5c..6c7fc58 100644
--- a/apps/api/src/schema.graphql
+++ b/apps/api/src/schema.graphql
@@ -43,7 +43,10 @@ type Query {
type Mutation {
createRecipe(input: RecipeInput!): Recipe!
- updateRecipe(id: ID!, input: RecipeInput!): Recipe!
+ # expectedUpdatedAt: the recipe's updatedAt when the editor loaded it. If
+ # the recipe has changed since, the update fails with code CONFLICT
+ # instead of overwriting the newer version.
+ updateRecipe(id: ID!, input: RecipeInput!, expectedUpdatedAt: String): Recipe!
deleteRecipe(id: ID!): Boolean!
saveRecipe(id: ID!): Recipe!
unsaveRecipe(id: ID!): Boolean!
diff --git a/apps/validation/package.json b/apps/validation/package.json
index eadcd73..ddf1726 100644
--- a/apps/validation/package.json
+++ b/apps/validation/package.json
@@ -6,6 +6,10 @@
".": {
"types": "./dist/auth.d.ts",
"import": "./dist/auth.js"
+ },
+ "./recipe": {
+ "types": "./dist/recipe.d.ts",
+ "import": "./dist/recipe.js"
}
},
"scripts": {
diff --git a/apps/validation/src/recipe.test.ts b/apps/validation/src/recipe.test.ts
new file mode 100644
index 0000000..e8caaec
--- /dev/null
+++ b/apps/validation/src/recipe.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+import { parseTags } from './recipe';
+
+describe('parseTags', () => {
+ it('trims, lower-cases and drops empty and repeated tags, keeping order', () => {
+ expect(parseTags(' Quick , vegan,, QUICK, ,Italian ')).toEqual([
+ 'quick',
+ 'vegan',
+ 'italian',
+ ]);
+ expect(parseTags('')).toEqual([]);
+ });
+});
diff --git a/apps/validation/src/recipe.ts b/apps/validation/src/recipe.ts
new file mode 100644
index 0000000..71e5736
--- /dev/null
+++ b/apps/validation/src/recipe.ts
@@ -0,0 +1,33 @@
+/**
+ * Servings a recipe can be written for and scaled to. Shared by the API's
+ * input validation, the recipe form and the detail page's servings control,
+ * so the three can never disagree.
+ */
+export const MIN_SERVINGS = 1;
+export const MAX_SERVINGS = 1000;
+
+/*
+ * Size limits of a recipe, enforced by the API (recipeValidation.ts) and
+ * checked by the recipe form before it submits, so a form that looks valid
+ * is never rejected by the API.
+ */
+export const MAX_INGREDIENTS = 100;
+export const MAX_INSTRUCTIONS = 100;
+export const MAX_TAGS = 30;
+export const MAX_TAG_LENGTH = 50;
+
+/**
+ * Tags from the form's comma-separated text, as the API stores them:
+ * trimmed, lower-case, without empty entries or repeats. The form sends this
+ * list, so the API's MAX_TAGS counts the same tags the form counted.
+ */
+export function parseTags(text: string) {
+ return [
+ ...new Set(
+ text
+ .split(',')
+ .map((tag) => tag.trim().toLowerCase())
+ .filter(Boolean),
+ ),
+ ];
+}
diff --git a/apps/web/index.html b/apps/web/index.html
index ca7696e..f679f2c 100644
--- a/apps/web/index.html
+++ b/apps/web/index.html
@@ -3,6 +3,15 @@
+
+
Recipe Platform
diff --git a/apps/web/package.json b/apps/web/package.json
index d2cb06f..1c9618b 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -9,7 +9,6 @@
},
"dependencies": {
"@t31/validation": "*",
- "graphql": "16.12.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-easy-crop": "6.2.4",
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index cd06058..e8041a7 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -1,19 +1,32 @@
-import { useEffect } from 'react';
+import { lazy, useEffect } from 'react';
import { useAppStore } from './store';
import { Route, Routes } from 'react-router-dom';
import AppShell from './components/shell/AppShell/AppShell';
-import LoginPage from './features/auth/LoginPage';
-import RegisterPage from './features/auth/RegisterPage';
import RequireAuth from './features/auth/RequireAuth';
import ExplorePage from './features/explore/ExplorePage';
-import CookbookPage from './features/cookbook/CookbookPage';
-import RecipeCreatePage from './features/recipes/RecipeCreatePage';
-import RecipeDetailPage from './features/recipe-detail/RecipeDetailPage';
+
+/*
+ * Explore is the landing page and loads with the app. Other pages are split
+ * into their own chunks and fetched on first visit (AppShell shows a loading
+ * state meanwhile), so a visitor who only browses never downloads, for
+ * example, the image cropper used by Add Recipe.
+ */
+const LoginPage = lazy(() => import('./features/auth/LoginPage'));
+const RegisterPage = lazy(() => import('./features/auth/RegisterPage'));
+const CookbookPage = lazy(() => import('./features/cookbook/CookbookPage'));
+const RecipeCreatePage = lazy(
+ () => import('./features/recipes/RecipeCreatePage'),
+);
+const RecipeDetailPage = lazy(
+ () => import('./features/recipe-detail/RecipeDetailPage'),
+);
+
import NotFoundPage from './features/not-found/NotFoundPage';
+import { devPagesElement } from './dev/devPagesRoute';
export function App() {
const restoreSession = useAppStore((state) => state.restoreSession);
@@ -39,6 +52,8 @@ export function App() {
} />
+ {/* Design-system review pages; only exists in `npm run dev`. */}
+ {devPagesElement && }
);
}
diff --git a/apps/web/src/assets/recipe-fallback.webp b/apps/web/src/assets/recipe-fallback.webp
index 6948b1a..a72ff1a 100644
Binary files a/apps/web/src/assets/recipe-fallback.webp and b/apps/web/src/assets/recipe-fallback.webp differ
diff --git a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx
index 3c7b609..b3e60b7 100644
--- a/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx
+++ b/apps/web/src/components/recipe/RecipeCard/RecipeCard.tsx
@@ -24,13 +24,24 @@ export interface RecipeCardTag {
type RecipeCardImageProps =
| {
imageSrc: string;
+ /** Optional resized variants (see recipeImageSrcSet). */
+ imageSrcSet?: string;
imageAlt: string;
}
| {
imageSrc?: undefined;
+ imageSrcSet?: never;
imageAlt?: never;
};
+/*
+ * Rendered card width per layout (ExplorePage.css / CookbookPage.css):
+ * one column below 44rem, two up to 65rem, otherwise three columns in the
+ * 75rem container (about 400 px each). Lets the browser pick a variant.
+ */
+const CARD_IMAGE_SIZES =
+ '(max-width: 44rem) 100vw, (max-width: 65rem) 50vw, 400px';
+
type RecipeCardBaseProps = Omit<
ComponentPropsWithoutRef<'article'>,
'children' | 'title'
@@ -99,6 +110,7 @@ export default function RecipeCard({
title,
description,
imageSrc,
+ imageSrcSet,
imageAlt,
rating,
cookingTimeMinutes,
@@ -191,6 +203,8 @@ export default function RecipeCard({
.filter(Boolean)
.join(' ')}
src={imageSrc ?? fallbackRecipeImage}
+ srcSet={imageSrcSet}
+ sizes={imageSrcSet ? CARD_IMAGE_SIZES : undefined}
alt={imageSrc ? imageAlt : ''}
loading="lazy"
decoding="async"
diff --git a/apps/web/src/components/recipe/showcase/RecipeCardShowcase.tsx b/apps/web/src/components/recipe/showcase/RecipeCardShowcase.tsx
index 0686ef1..b88eb53 100644
--- a/apps/web/src/components/recipe/showcase/RecipeCardShowcase.tsx
+++ b/apps/web/src/components/recipe/showcase/RecipeCardShowcase.tsx
@@ -34,7 +34,7 @@ export default function RecipeCardShowcase() {
const [narrowCardSaved, setNarrowCardSaved] = useState(false);
return (
-
+
RecipeCard Showcase
@@ -249,6 +249,6 @@ export default function RecipeCardShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/recipe/toRecipeCardProps.ts b/apps/web/src/components/recipe/toRecipeCardProps.ts
index 1492d59..f302b0d 100644
--- a/apps/web/src/components/recipe/toRecipeCardProps.ts
+++ b/apps/web/src/components/recipe/toRecipeCardProps.ts
@@ -1,6 +1,6 @@
import type { RecipeSummary } from '../../types/recipe';
import type { RecipeCardProps } from './RecipeCard/RecipeCard';
-import { recipeImageUrl } from '../../lib/recipeImageUrl';
+import { recipeImageSrcSet, recipeImageUrl } from '../../lib/recipeImageUrl';
function formatTagLabel(tag: string) {
return tag
@@ -32,6 +32,7 @@ export function toRecipeCardProps(recipe: RecipeSummary): RecipeCardProps {
return {
...commonProps,
imageSrc: recipeImageUrl(recipe.imageUrl),
+ imageSrcSet: recipeImageSrcSet(recipe.imageUrl),
imageAlt: recipe.title,
};
}
diff --git a/apps/web/src/components/shell/AppShell/AppShell.css b/apps/web/src/components/shell/AppShell/AppShell.css
index e945a95..4c1b55a 100644
--- a/apps/web/src/components/shell/AppShell/AppShell.css
+++ b/apps/web/src/components/shell/AppShell/AppShell.css
@@ -9,4 +9,41 @@
),
var(--color-bg-page);
}
+
+ /* Off-screen until it receives keyboard focus, then shown top left. */
+ .app-shell__skip-link {
+ position: absolute;
+ z-index: var(--z-modal);
+ top: var(--space-2);
+ left: var(--space-2);
+
+ padding: var(--space-2) var(--space-4);
+
+ border-radius: var(--radius-md);
+
+ color: var(--color-text-inverse);
+ background-color: var(--color-text-primary);
+
+ font-weight: var(--font-weight-semibold);
+ text-decoration: none;
+
+ transform: translateY(calc(-100% - var(--space-4)));
+ }
+
+ .app-shell__skip-link:focus {
+ transform: none;
+ }
+
+ /*
+ * Focusing main scrolls it into view. On a scrolled-down page it would
+ * otherwise end up behind the sticky header, hiding its first control.
+ */
+ .app-shell main {
+ scroll-margin-top: calc(var(--site-header-height) + var(--space-2));
+ }
+
+ /* Main is only focused as a skip-link or navigation target, not typed in. */
+ .app-shell main:focus {
+ outline: none;
+ }
}
diff --git a/apps/web/src/components/shell/AppShell/AppShell.tsx b/apps/web/src/components/shell/AppShell/AppShell.tsx
index 195600a..cb2c7c0 100644
--- a/apps/web/src/components/shell/AppShell/AppShell.tsx
+++ b/apps/web/src/components/shell/AppShell/AppShell.tsx
@@ -1,14 +1,57 @@
-import { Outlet } from 'react-router-dom';
+import { Suspense, useEffect, useRef } from 'react';
+import { Outlet, useLocation, useNavigationType } from 'react-router-dom';
+import LoadingIndicator from '../../ui/LoadingIndicator/LoadingIndicator';
import SiteHeader from '../SiteHeader/SiteHeader';
import './AppShell.css';
function AppShell() {
+ const { pathname } = useLocation();
+ const navigationType = useNavigationType();
+ const previousPathname = useRef(pathname);
+
+ /*
+ * After client-side navigation to another page, move focus to the main
+ * content (and the view to the top), as a full page load would. Screen
+ * readers then start reading the new page instead of staying on the link
+ * that was activated. Skipped on the first load, for changes that only
+ * touch the query string (search, filters, paging keep their own focus),
+ * and while a dialog is open. Back/Forward (POP) keeps the scroll position
+ * the browser restores, so the user returns to where they were.
+ */
+ useEffect(() => {
+ if (previousPathname.current === pathname) return;
+ previousPathname.current = pathname;
+ if (document.querySelector('dialog[open], [role="dialog"]')) return;
+ if (navigationType !== 'POP')
+ window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
+ document.getElementById('main-content')?.focus({ preventScroll: true });
+ }, [pathname, navigationType]);
+
return (
);
diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.css b/apps/web/src/components/shell/SiteHeader/SiteHeader.css
index 9dabf39..cb557d2 100644
--- a/apps/web/src/components/shell/SiteHeader/SiteHeader.css
+++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.css
@@ -12,7 +12,7 @@
display: flex;
align-items: center;
gap: var(--space-8);
- min-height: 5rem;
+ min-height: var(--site-header-height);
}
.brand {
@@ -112,7 +112,7 @@
.site-header__inner {
flex-wrap: wrap;
gap: 0;
- min-height: 5rem;
+ min-height: var(--site-header-height);
padding-block: var(--space-3);
}
diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx
index accf529..755969f 100644
--- a/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx
+++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.test.tsx
@@ -1,10 +1,16 @@
import '@testing-library/jest-dom/vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import { signOutUser } from '../../../features/auth/authApi';
+import {
+ countUserDrafts,
+ saveDraft,
+ type RecipeDraftFields,
+} from '../../../lib/recipeDrafts';
+import { useUnsavedChanges } from '../../../lib/unsavedChanges';
import { useAppStore } from '../../../store';
import SiteHeader from './SiteHeader';
@@ -128,3 +134,83 @@ describe('SiteHeader authentication', () => {
expect(useAppStore.getState().currentUser).toEqual(authenticatedUser);
});
});
+
+describe('SiteHeader sign-out warning', () => {
+ const fields = { title: 'Draft' } as RecipeDraftFields;
+ beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ useUnsavedChanges.setState({ unsaved: false });
+ useAppStore.setState({
+ currentUser: authenticatedUser,
+ sessionStatus: 'authenticated',
+ });
+ vi.mocked(signOutUser).mockResolvedValue(true);
+ });
+
+ it('warns that drafts and unsaved editor changes will be lost', async () => {
+ saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields });
+ saveDraft(authenticatedUser.id, 'recipe-1', {
+ baseUpdatedAt: null,
+ fields,
+ });
+ saveDraft('someone-else', 'new', { baseUpdatedAt: null, fields });
+ useUnsavedChanges.setState({ unsaved: true });
+ const user = userEvent.setup();
+ renderHeader();
+
+ await user.click(screen.getByRole('button', { name: 'Sign out' }));
+ const dialog = screen.getByRole('dialog');
+ expect(dialog).toHaveTextContent(
+ 'Your unsaved changes in the recipe editor will be lost.',
+ );
+ expect(dialog).toHaveTextContent(
+ 'Your 2 saved drafts in this browser will be deleted.',
+ );
+ await user.click(
+ within(dialog).getByRole('button', { name: 'Stay signed in' }),
+ );
+ expect(signOutUser).not.toHaveBeenCalled();
+ expect(countUserDrafts(authenticatedUser.id)).toBe(2);
+
+ await user.click(screen.getByRole('button', { name: 'Sign out' }));
+ await user.click(
+ within(screen.getByRole('dialog')).getByRole('button', {
+ name: 'Sign out',
+ }),
+ );
+ await waitFor(() => expect(signOutUser).toHaveBeenCalledOnce());
+ await waitFor(() => expect(countUserDrafts(authenticatedUser.id)).toBe(0));
+ expect(countUserDrafts('someone-else')).toBe(1);
+ // The editor must not ask again about the changes just given up.
+ expect(useUnsavedChanges.getState().unsaved).toBe(false);
+ });
+
+ it('protects the unsaved changes again when signing out fails', async () => {
+ useUnsavedChanges.setState({ unsaved: true });
+ vi.mocked(signOutUser).mockRejectedValueOnce(new Error('Offline'));
+ const user = userEvent.setup();
+ renderHeader();
+ await user.click(screen.getByRole('button', { name: 'Sign out' }));
+ await user.click(
+ within(screen.getByRole('dialog')).getByRole('button', {
+ name: 'Sign out',
+ }),
+ );
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Unable to sign out',
+ );
+ expect(useUnsavedChanges.getState().unsaved).toBe(true);
+ });
+
+ it('names a single draft in the singular', async () => {
+ saveDraft(authenticatedUser.id, 'new', { baseUpdatedAt: null, fields });
+ const user = userEvent.setup();
+ renderHeader();
+ await user.click(screen.getByRole('button', { name: 'Sign out' }));
+ expect(screen.getByRole('dialog')).toHaveTextContent(
+ 'Your saved draft in this browser will be deleted.',
+ );
+ expect(screen.getByRole('dialog')).not.toHaveTextContent('unsaved');
+ });
+});
diff --git a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx
index 9fa2d73..82c6dfe 100644
--- a/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx
+++ b/apps/web/src/components/shell/SiteHeader/SiteHeader.tsx
@@ -16,6 +16,9 @@ import './SiteHeader.css';
import LogoMark from '../../brand/LogoMark/LogoMark';
import LinkButton from '../../ui/LinkButton/LinkButton';
import { Icon } from '../../ui/Icon/Icon';
+import ConfirmationDialog from '../../ui/ConfirmationDialog/ConfirmationDialog';
+import { countUserDrafts } from '../../../lib/recipeDrafts';
+import { useUnsavedChanges } from '../../../lib/unsavedChanges';
const pages = [
{ to: '/', label: 'Explore', icon: HomeIcon },
@@ -33,14 +36,40 @@ function SiteHeader() {
const closeMenu = () => setMenuOpen(false);
+ /*
+ * Signing out deletes this user's drafts (shared computers) and closes
+ * the recipe editor, so say what would be lost and ask first.
+ */
+ const [signOutLoss, setSignOutLoss] = useState<{
+ drafts: number;
+ unsaved: boolean;
+ } | null>(null);
+ const requestSignOut = () => {
+ const drafts = currentUser ? countUserDrafts(currentUser.id) : 0;
+ const { unsaved } = useUnsavedChanges.getState();
+ if (drafts || unsaved) setSignOutLoss({ drafts, unsaved });
+ else void handleSignOut();
+ };
+ const confirmSignOut = async () => {
+ const unsaved = Boolean(signOutLoss?.unsaved);
+ setSignOutLoss(null);
+ // The user gave up the editor's changes: the editor must not ask again
+ // as sign-out closes it. If signing out fails, the editor stays open
+ // and its changes are protected again.
+ useUnsavedChanges.setState({ unsaved: false });
+ if (!(await handleSignOut())) useUnsavedChanges.setState({ unsaved });
+ };
+
const handleSignOut = async () => {
setLogoutError('');
try {
await signOut();
closeMenu();
navigate('/');
+ return true;
} catch {
setLogoutError('Unable to sign out. Please try again.');
+ return false;
}
};
@@ -108,7 +137,7 @@ function SiteHeader() {
{currentUser.name}
-
+
Sign out
>
@@ -144,6 +173,30 @@ function SiteHeader() {
+ void confirmSignOut()}
+ onCancel={() => setSignOutLoss(null)}
+ >
+
+ {signOutLoss?.unsaved && (
+ Your unsaved changes in the recipe editor will be lost.
+ )}
+ {Boolean(signOutLoss?.drafts) && (
+
+ {signOutLoss?.drafts === 1
+ ? 'Your saved draft'
+ : `Your ${signOutLoss?.drafts} saved drafts`}{' '}
+ in this browser will be deleted.
+
+ )}
+
+
);
}
diff --git a/apps/web/src/components/ui/EmptyState/EmptyState.tsx b/apps/web/src/components/ui/EmptyState/EmptyState.tsx
index 61e7919..de165e4 100644
--- a/apps/web/src/components/ui/EmptyState/EmptyState.tsx
+++ b/apps/web/src/components/ui/EmptyState/EmptyState.tsx
@@ -15,6 +15,13 @@ export type EmptyStateProps = {
action?: ReactNode;
variant?: EmptyStateVariant;
size?: EmptyStateSize;
+ /**
+ * Heading level for the title. Defaults to 3 for empty states inside a
+ * page section. Use 1 when the empty state is the whole page (for example
+ * "Recipe not found") so the page still has a top-level heading.
+ * The visual size comes from the size prop, not from the level.
+ */
+ headingLevel?: 1 | 2 | 3 | 4;
};
function EmptyState({
@@ -25,7 +32,10 @@ function EmptyState({
action,
variant = 'surface',
size = 'md',
+ headingLevel = 3,
}: EmptyStateProps) {
+ const Heading = `h${headingLevel}` as const;
+
return (
-
{title}
+
{title}
{description && (
{description}
)}
diff --git a/apps/web/src/components/ui/README.md b/apps/web/src/components/ui/README.md
index 2ed7c71..2a45776 100644
--- a/apps/web/src/components/ui/README.md
+++ b/apps/web/src/components/ui/README.md
@@ -6,7 +6,7 @@ The component library is intentionally small and project-specific. Add a new gen
## Visual review
-The app currently renders `showcase/UiShowcaseCatalog.tsx`, which displays the component showcases as one long scrollable page. Use it as the primary visual and responsive review surface.
+`showcase/UiShowcaseCatalog.tsx` displays the component showcases as one long scrollable page. Use it as the primary visual and responsive review surface. It is mounted on development-only routes (`src/dev/`), so it is never part of the production build.
Run:
@@ -14,7 +14,16 @@ Run:
npm run dev
```
-Then scroll through the catalog and resize the browser. The showcase is intentionally kept as one page so it is quick to compare components, inspect states, and notice responsive regressions.
+Then open `http://localhost:5173/project2/dev/` and choose a page:
+
+| Route | Content |
+| ------------------ | ---------------------------------------------- |
+| `/dev/ui` | All UI component showcases |
+| `/dev/recipe-card` | `RecipeCard` variants (`../recipe/showcase/`) |
+| `/dev/styles` | Style guide (`src/styles/style_guide/`) |
+| `/dev/style-tests` | Style stress tests (`src/styles/style_tests/`) |
+
+Scroll through the catalog and resize the browser. The showcase is intentionally kept as one page so it is quick to compare components, inspect states, and notice responsive regressions.
Storybook is not currently necessary. The showcase already covers the project's main visual-review need with less setup and maintenance.
@@ -693,7 +702,7 @@ The component chooses the matching semantic icon and live-region role.
**Sizes:** `sm | md`.
-**Important props:** `icon`, `title`, `description`, `action`.
+**Important props:** `icon`, `title`, `description`, `action`, `headingLevel` (default `3`; use `1` when the empty state is the whole page).
```tsx
+
Button Showcase
@@ -414,6 +414,6 @@ export default function ButtonShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/CheckboxShowcase.tsx b/apps/web/src/components/ui/showcase/CheckboxShowcase.tsx
index d40075f..cafe4c8 100644
--- a/apps/web/src/components/ui/showcase/CheckboxShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/CheckboxShowcase.tsx
@@ -8,7 +8,7 @@ export default function CheckboxShowcase() {
const [quickRecipes, setQuickRecipes] = useState(true);
return (
-
+
Checkbox Showcase
@@ -259,6 +259,6 @@ export default function CheckboxShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/DropdownMenuShowcase.tsx b/apps/web/src/components/ui/showcase/DropdownMenuShowcase.tsx
index 0881182..2684587 100644
--- a/apps/web/src/components/ui/showcase/DropdownMenuShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/DropdownMenuShowcase.tsx
@@ -13,7 +13,7 @@ import { surfaceStyle } from './showcaseStyles';
export default function DropdownMenuShowcase() {
return (
-
+
DropdownMenu Showcase
@@ -208,6 +208,6 @@ export default function DropdownMenuShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/FieldShowcase.tsx b/apps/web/src/components/ui/showcase/FieldShowcase.tsx
index 301327f..bc4bf97 100644
--- a/apps/web/src/components/ui/showcase/FieldShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/FieldShowcase.tsx
@@ -3,7 +3,7 @@ import { surfaceStyle, raisedSurfaceStyle } from './showcaseStyles';
export default function FieldShowcase() {
return (
-
+
Field Showcase
@@ -348,6 +348,6 @@ export default function FieldShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/IconBadgeShowcase.tsx b/apps/web/src/components/ui/showcase/IconBadgeShowcase.tsx
index 00e444c..e24f3f8 100644
--- a/apps/web/src/components/ui/showcase/IconBadgeShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/IconBadgeShowcase.tsx
@@ -13,7 +13,7 @@ import { surfaceStyle, raisedSurfaceStyle } from './showcaseStyles';
export default function IconBadgeShowcase() {
return (
-
+
IconBadge Showcase
@@ -257,6 +257,6 @@ export default function IconBadgeShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/IconButtonShowcase.tsx b/apps/web/src/components/ui/showcase/IconButtonShowcase.tsx
index c43be8f..b3fdd11 100644
--- a/apps/web/src/components/ui/showcase/IconButtonShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/IconButtonShowcase.tsx
@@ -29,7 +29,7 @@ export default function IconButtonShowcase() {
const [favorite, setFavorite] = useState(false);
return (
-
+
IconButton Showcase
@@ -199,6 +199,6 @@ export default function IconButtonShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/IconShowcase.tsx b/apps/web/src/components/ui/showcase/IconShowcase.tsx
index 29c3151..cc1da2e 100644
--- a/apps/web/src/components/ui/showcase/IconShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/IconShowcase.tsx
@@ -319,7 +319,7 @@ const toneExamples: Array<{
export default function IconShowcase() {
return (
-
+
Icon Showcase
@@ -807,6 +807,6 @@ export default function IconShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/RadioShowcase.tsx b/apps/web/src/components/ui/showcase/RadioShowcase.tsx
index 459855d..0f4714a 100644
--- a/apps/web/src/components/ui/showcase/RadioShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/RadioShowcase.tsx
@@ -8,7 +8,7 @@ export default function RadioShowcase() {
const [difficulty, setDifficulty] = useState('medium');
return (
-
+
Radio Showcase
@@ -398,6 +398,6 @@ export default function RadioShowcase() {
-
+
);
}
diff --git a/apps/web/src/components/ui/showcase/SelectShowcase.tsx b/apps/web/src/components/ui/showcase/SelectShowcase.tsx
index 2bd3720..c4264f0 100644
--- a/apps/web/src/components/ui/showcase/SelectShowcase.tsx
+++ b/apps/web/src/components/ui/showcase/SelectShowcase.tsx
@@ -8,7 +8,7 @@ export default function SelectShowcase() {
const [sort, setSort] = useState('newest');
return (
-
+
Select Showcase
@@ -588,6 +588,6 @@ export default function SelectShowcase() {
-
+
);
}
diff --git a/apps/web/src/data/users.ts b/apps/web/src/data/users.ts
deleted file mode 100644
index c40bb6b..0000000
--- a/apps/web/src/data/users.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type { User } from '../types/user';
-
-export const mockUser = {
- id: 'mock-current-user',
- name: 'Recipe User',
- email: 'user@example.com',
-} satisfies User;
diff --git a/apps/web/src/dev/DevPages.tsx b/apps/web/src/dev/DevPages.tsx
new file mode 100644
index 0000000..d519cb7
--- /dev/null
+++ b/apps/web/src/dev/DevPages.tsx
@@ -0,0 +1,82 @@
+import { Link, Route, Routes } from 'react-router-dom';
+
+import NotFoundPage from '../features/not-found/NotFoundPage';
+
+import RecipeCardShowcase from '../components/recipe/showcase/RecipeCardShowcase';
+import UiShowcaseCatalog from '../components/ui/showcase/UiShowcaseCatalog';
+import StylesGuide from '../styles/style_guide/StylesGuide';
+import StyleTestSuite from '../styles/style_tests/StyleTestSuite';
+
+/**
+ * Design-system review pages for development.
+ *
+ * Mounted at /dev/* only when Vite runs in development mode (see App.tsx),
+ * so none of this code is part of the production build. Open
+ * http://localhost:5173/project2/dev/ while `npm run dev` is running.
+ */
+const pages = [
+ {
+ path: 'ui',
+ label: 'UI components',
+ description: 'Every shared component and its states.',
+ element: ,
+ },
+ {
+ path: 'recipe-card',
+ label: 'Recipe card',
+ description: 'RecipeCard variants and edge cases.',
+ element: ,
+ },
+ {
+ path: 'styles',
+ label: 'Style guide',
+ description: 'Tokens, typography, layout utilities.',
+ element: ,
+ },
+ {
+ path: 'style-tests',
+ label: 'Style stress tests',
+ description: 'Long content, states and responsive layouts.',
+ element: ,
+ },
+];
+
+function DevIndex() {
+ return (
+
+ Design-system review
+ Development-only pages. They are not included in production.
+
+ {pages.map((page) => (
+
+ {page.label} — {page.description}
+
+ ))}
+
+
+ );
+}
+
+export default function DevPages() {
+ return (
+
+ } />
+ {/* One main landmark per page; the showcases use sections inside it. */}
+ {pages.map((page) => (
+ {page.element}}
+ />
+ ))}
+
+
+
+ }
+ />
+
+ );
+}
diff --git a/apps/web/src/dev/devPagesRoute.tsx b/apps/web/src/dev/devPagesRoute.tsx
new file mode 100644
index 0000000..45fcb06
--- /dev/null
+++ b/apps/web/src/dev/devPagesRoute.tsx
@@ -0,0 +1,14 @@
+import { lazy, Suspense } from 'react';
+
+/*
+ * import.meta.env.DEV is replaced with `false` in production builds, so the
+ * minifier drops this branch and Vite never emits the DevPages chunk.
+ */
+const DevPages = import.meta.env.DEV ? lazy(() => import('./DevPages')) : null;
+
+/** Element for the /dev/* route, or null outside development. */
+export const devPagesElement = DevPages ? (
+
+
+
+) : null;
diff --git a/apps/web/src/features/auth/AuthPages.test.tsx b/apps/web/src/features/auth/AuthPages.test.tsx
index f8ca789..95e63f8 100644
--- a/apps/web/src/features/auth/AuthPages.test.tsx
+++ b/apps/web/src/features/auth/AuthPages.test.tsx
@@ -56,7 +56,6 @@ describe('authentication pages', () => {
localStorage.clear();
useAppStore.setState({
- search: '',
currentUser: null,
});
});
diff --git a/apps/web/src/features/auth/LoginPage.tsx b/apps/web/src/features/auth/LoginPage.tsx
index 34f07ca..d6f5414 100644
--- a/apps/web/src/features/auth/LoginPage.tsx
+++ b/apps/web/src/features/auth/LoginPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import { loginSchema, fieldErrors } from '@t31/validation';
import { useState, type FormEvent } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
@@ -15,6 +16,7 @@ interface LoginErrors {
}
function LoginPage() {
+ usePageTitle('Log in');
const navigate = useNavigate();
const location = useLocation();
const returnPath = getAuthReturnPath(location.state);
diff --git a/apps/web/src/features/auth/RegisterPage.tsx b/apps/web/src/features/auth/RegisterPage.tsx
index 928fe56..cda385e 100644
--- a/apps/web/src/features/auth/RegisterPage.tsx
+++ b/apps/web/src/features/auth/RegisterPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import { registerFormSchema, fieldErrors } from '@t31/validation';
import { useState, type FormEvent } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
@@ -17,6 +18,7 @@ interface RegisterErrors {
}
function RegisterPage() {
+ usePageTitle('Register');
const navigate = useNavigate();
const location = useLocation();
const returnPath = getAuthReturnPath(location.state);
diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx
index a1d760b..03771df 100644
--- a/apps/web/src/features/auth/RequireAuth.test.tsx
+++ b/apps/web/src/features/auth/RequireAuth.test.tsx
@@ -52,8 +52,14 @@ describe('protected routes with session restoration', () => {
'redirects a logged-out visitor from %s',
async (path) => {
renderApp(path);
+ // Log in is lazy-loaded; the first import in a test run can take
+ // over a second on the CI runner.
expect(
- await screen.findByRole('heading', { name: 'Log in' }),
+ await screen.findByRole(
+ 'heading',
+ { name: 'Log in' },
+ { timeout: 5000 },
+ ),
).toBeInTheDocument();
expect(screen.getByTestId('location')).toHaveTextContent('/login');
},
@@ -111,6 +117,30 @@ describe('protected routes with session restoration', () => {
await screen.findByRole('heading', { name: 'Add Recipe' }),
).toBeInTheDocument();
});
+ it('titles the session states of a protected page, then the page itself', async () => {
+ document.title = 'Creamy salmon pasta – Recipe Platform';
+ let failRestore!: (error: Error) => void;
+ vi.mocked(getCurrentUser).mockReturnValue(
+ new Promise((_resolve, reject) => {
+ failRestore = reject;
+ }),
+ );
+ renderApp('/cookbook');
+ // Not the title of whatever page was open before.
+ expect(document.title).toBe('Restoring session – Recipe Platform');
+ await act(async () => failRestore(new Error('Offline')));
+ await screen.findByRole('alert');
+ expect(document.title).toBe(
+ 'Session could not be restored – Recipe Platform',
+ );
+
+ vi.mocked(getCurrentUser).mockResolvedValue(user);
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Try again' }));
+ await screen.findByRole('heading', { name: 'My Cookbook' });
+ expect(document.title).toBe('My Cookbook – Recipe Platform');
+ });
it.each([false, true])(
'returns to the requested URL after authentication (register=%s)',
async (register) => {
@@ -126,6 +156,8 @@ describe('protected routes with session restoration', () => {
if (register) {
const links = screen.getAllByRole('link', { name: 'Register' });
await interaction.click(links[links.length - 1]!);
+ // Register is lazy-loaded (code splitting): wait for the page itself.
+ await screen.findByRole('heading', { name: 'Register' });
await interaction.type(screen.getByLabelText(/^Name/), 'Hasan');
await interaction.type(
screen.getByLabelText(/^Confirm password/),
diff --git a/apps/web/src/features/auth/RequireAuth.tsx b/apps/web/src/features/auth/RequireAuth.tsx
index b1c8dcb..4ec0e05 100644
--- a/apps/web/src/features/auth/RequireAuth.tsx
+++ b/apps/web/src/features/auth/RequireAuth.tsx
@@ -2,6 +2,7 @@ import { Navigate, Outlet, useLocation } from 'react-router-dom';
import Button from '../../components/ui/Button/Button';
import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage';
import { useAppStore } from '../../store';
+import { PageTitle } from '../../lib/usePageTitle';
export default function RequireAuth() {
const location = useLocation();
@@ -10,11 +11,17 @@ export default function RequireAuth() {
const restoreSession = useAppStore((state) => state.restoreSession);
if (sessionStatus === 'restoring') {
- return Restoring your session...
;
+ return (
+ <>
+
+ Restoring your session...
+ >
+ );
}
if (sessionStatus === 'error') {
return (
+
Unable to restore your session. Check your connection and try again.
diff --git a/apps/web/src/features/auth/authApi.ts b/apps/web/src/features/auth/authApi.ts
index 16f4e2e..a36f7d5 100644
--- a/apps/web/src/features/auth/authApi.ts
+++ b/apps/web/src/features/auth/authApi.ts
@@ -1,5 +1,8 @@
-import { ApiError, graphqlRequest as request } from '../../lib/graphqlClient';
-import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
+import {
+ ApiError,
+ graphqlRequest as request,
+ type GraphqlDocument,
+} from '../../lib/graphqlClient';
import {
RegisterDocument,
LoginDocument,
@@ -16,7 +19,7 @@ const errorMessages: Record
= {
RATE_LIMITED: 'Too many attempts. Please try again in a minute.',
};
async function graphqlRequest(
- document: TypedDocumentNode,
+ document: GraphqlDocument,
variables: V,
): Promise {
try {
diff --git a/apps/web/src/features/auth/authNavigation.test.ts b/apps/web/src/features/auth/authNavigation.test.ts
index ac187dc..61af532 100644
--- a/apps/web/src/features/auth/authNavigation.test.ts
+++ b/apps/web/src/features/auth/authNavigation.test.ts
@@ -8,13 +8,19 @@ describe('authentication return navigation', () => {
{ from: '//example.com' },
{ from: '/login' },
{ from: '/cookbook\\evil' },
+ { from: '/recipes/abc/edit' },
+ { from: '/recipes/11111111-1111-4111-8111-111111111111/editor' },
+ { from: '/recipes/11111111-1111-4111-8111-111111111111/edit/../../x' },
+ { from: '//example.com/recipes/11111111-1111-4111-8111-111111111111/edit' },
])('falls back for unsafe or unsupported state %j', (state) => {
expect(getAuthReturnPath(state)).toBe('/');
});
- it.each(['/cookbook?view=saved#recipes', '/recipes/new'])(
- 'preserves protected destination %s',
- (from) => {
- expect(getAuthReturnPath({ from })).toBe(from);
- },
- );
+ it.each([
+ '/cookbook?view=saved#recipes',
+ '/recipes/new',
+ '/recipes/11111111-1111-4111-8111-111111111111?view=full#ingredients',
+ '/recipes/11111111-1111-4111-8111-111111111111/edit',
+ ])('preserves protected destination %s', (from) => {
+ expect(getAuthReturnPath({ from })).toBe(from);
+ });
});
diff --git a/apps/web/src/features/auth/authNavigation.ts b/apps/web/src/features/auth/authNavigation.ts
index 2d4ef38..ea1ecfb 100644
--- a/apps/web/src/features/auth/authNavigation.ts
+++ b/apps/web/src/features/auth/authNavigation.ts
@@ -1,9 +1,17 @@
-// Only return to known protected routes. Never navigate to a supplied origin.
+// One recipe detail or editor route; nothing else under /recipes/.
+const RECIPE_ROUTE =
+ /^\/recipes\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?:\/edit)?$/;
+
+// Only return to known recipe and protected routes. Never navigate to a supplied origin.
export function getAuthReturnPath(state: unknown): string {
if (typeof state !== 'object' || state === null || !('from' in state))
return '/';
const from = state.from;
if (typeof from !== 'string' || from.includes('\\')) return '/';
- const pathname = from.split(/[?#]/)[0];
- return pathname === '/cookbook' || pathname === '/recipes/new' ? from : '/';
+ const pathname = from.split(/[?#]/)[0] ?? '';
+ return pathname === '/cookbook' ||
+ pathname === '/recipes/new' ||
+ RECIPE_ROUTE.test(pathname)
+ ? from
+ : '/';
}
diff --git a/apps/web/src/features/cookbook/CookbookControls.css b/apps/web/src/features/cookbook/CookbookControls.css
index e0de5fb..d526c79 100644
--- a/apps/web/src/features/cookbook/CookbookControls.css
+++ b/apps/web/src/features/cookbook/CookbookControls.css
@@ -15,7 +15,7 @@
.cookbook-controls__desktop {
display: flex;
flex-wrap: nowrap;
- align-items: center;
+ align-items: flex-start;
gap: var(--space-3);
min-width: 0;
@@ -61,8 +61,14 @@
width: 15.5rem;
}
- .cookbook-controls__custom-time-input {
+ .cookbook-controls__desktop-control--custom-time {
+ flex: 0 0 9rem;
width: 9rem;
+ overflow-wrap: anywhere;
+ }
+
+ .cookbook-controls__custom-time-input {
+ width: 100%;
background-color: var(--color-surface-raised);
border-color: var(--color-border-input);
diff --git a/apps/web/src/features/cookbook/CookbookControls.tsx b/apps/web/src/features/cookbook/CookbookControls.tsx
index 1f6d7bf..3992b18 100644
--- a/apps/web/src/features/cookbook/CookbookControls.tsx
+++ b/apps/web/src/features/cookbook/CookbookControls.tsx
@@ -1,7 +1,14 @@
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
+import {
+ clampCustomTime,
+ customTimeError,
+ customTimeText,
+} from '../../lib/recipeBrowse/browseValidation';
+import { useCustomTimeInput } from '../../lib/recipeBrowse/useCustomTimeInput';
import Button from '../../components/ui/Button/Button';
import Field from '../../components/ui/Field/Field';
+import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage';
import FilterChip from '../../components/ui/FilterChip/FilterChip';
import { Icon } from '../../components/ui/Icon/Icon';
import Radio from '../../components/ui/Radio/Radio';
@@ -32,6 +39,7 @@ import {
import './CookbookControls.css';
export type CookbookControlsProps = {
+ navigationKey?: string;
scope: CookbookScope;
browseState: CookbookBrowseState;
onScopeChange: (scope: CookbookScope) => void;
@@ -39,16 +47,6 @@ export type CookbookControlsProps = {
onFiltersChange: (scope: CookbookScope, value: CookbookBrowseState) => void;
};
-function parseCustomMaxMinutes(value: string) {
- if (value.trim() === '') {
- return null;
- }
-
- const parsed = Number(value);
-
- return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
-}
-
function getScopeSelectLabel(scope: CookbookScope) {
switch (scope) {
case 'saved':
@@ -65,12 +63,20 @@ function getScopeSelectLabel(scope: CookbookScope) {
function CookbookControls({
scope,
browseState,
+ navigationKey = '',
onScopeChange,
onBrowseStateChange,
onFiltersChange,
}: CookbookControlsProps) {
const [filterSheetOpen, setFilterSheetOpen] = useState(false);
const [sortSheetOpen, setSortSheetOpen] = useState(false);
+ const [focusMobileTime, setFocusMobileTime] = useState(false);
+ const desktopTimeRef = useRef(null);
+ const mobileTimeRef = useRef(null);
+
+ useEffect(() => {
+ if (filterSheetOpen && focusMobileTime) mobileTimeRef.current?.focus();
+ }, [filterSheetOpen, focusMobileTime]);
const [scopeDraft, setScopeDraft] = useState(scope);
@@ -81,7 +87,25 @@ function CookbookControls({
});
const [sortDraft, setSortDraft] = useState(browseState.sort);
- const [showCustomTimeError, setShowCustomTimeError] = useState(false);
+ const [mobileTime, setMobileTime] = useState('');
+ const resetKey = JSON.stringify([navigationKey, browseState, scope]);
+ const desktopTime = useCustomTimeInput(
+ browseState.customMaxMinutes,
+ resetKey,
+ (minutes, raw) => {
+ onBrowseStateChange({
+ ...browseState,
+ cookingTime: 'custom',
+ customMaxMinutes: minutes,
+ customMaxMinutesRaw: raw,
+ });
+ },
+ browseState.customMaxMinutesRaw,
+ );
+ const committedTimeError =
+ browseState.cookingTime === 'custom'
+ ? customTimeError(clampCustomTime(customTimeText(browseState)))
+ : undefined;
const activeFilterCount =
countActiveRecipeFilters(browseState) + (scope === 'all' ? 0 : 1);
@@ -100,17 +124,13 @@ function CookbookControls({
cookingTime,
customMaxMinutes:
cookingTime === 'custom' ? browseState.customMaxMinutes : null,
+ customMaxMinutesRaw:
+ cookingTime === 'custom' ? browseState.customMaxMinutesRaw : undefined,
});
}
- function handleDesktopCustomMaxChange(rawValue: string) {
- updateBrowseState({
- cookingTime: 'custom',
- customMaxMinutes: parseCustomMaxMinutes(rawValue),
- });
- }
-
- function openFilterSheet() {
+ function openFilterSheet(focusTime = false) {
+ setFocusMobileTime(focusTime);
setScopeDraft(scope);
setFilterDraft({
@@ -119,11 +139,13 @@ function CookbookControls({
customMaxMinutes: browseState.customMaxMinutes,
});
- setShowCustomTimeError(false);
+ setMobileTime(customTimeText(browseState));
setFilterSheetOpen(true);
}
function handleDraftCookingTimeChange(cookingTime: RecipeCookingTime) {
+ if (cookingTime === filterDraft.cookingTime) return;
+
setFilterDraft((current) => ({
...current,
cookingTime,
@@ -131,21 +153,26 @@ function CookbookControls({
cookingTime === 'custom' ? current.customMaxMinutes : null,
}));
- setShowCustomTimeError(false);
+ setMobileTime('');
}
function handleApplyFilters() {
- if (
- filterDraft.cookingTime === 'custom' &&
- filterDraft.customMaxMinutes === null
- ) {
- setShowCustomTimeError(true);
+ const clamped = clampCustomTime(mobileTime);
+ if (filterDraft.cookingTime === 'custom' && customTimeError(clamped)) {
return;
}
onFiltersChange(scopeDraft, {
...browseState,
...filterDraft,
+ customMaxMinutes:
+ filterDraft.cookingTime === 'custom' && clamped.trim()
+ ? Number(clamped)
+ : null,
+ customMaxMinutesRaw:
+ filterDraft.cookingTime === 'custom' && customTimeError(mobileTime)
+ ? mobileTime
+ : undefined,
});
setFilterSheetOpen(false);
@@ -158,7 +185,15 @@ function CookbookControls({
...DEFAULT_RECIPE_FILTER_STATE,
});
- setShowCustomTimeError(false);
+ setMobileTime('');
+ }
+
+ function editTimeFilter() {
+ if (desktopTimeRef.current?.getClientRects().length) {
+ desktopTimeRef.current.focus();
+ } else {
+ openFilterSheet(true);
+ }
}
function openSortSheet() {
@@ -245,19 +280,25 @@ function CookbookControls({
{browseState.cookingTime === 'custom' && (
-
+
No time limit applied.
+ ) : undefined
+ }
placeholder="Max minutes"
onChange={(event) =>
- handleDesktopCustomMaxChange(event.currentTarget.value)
+ desktopTime.change(event.currentTarget.value)
}
/>
@@ -290,7 +331,7 @@ function CookbookControls({
openFilterSheet()}
>
@@ -310,6 +351,18 @@ function CookbookControls({
+ {committedTimeError && (
+
+
+ Recipes cannot be loaded until the maximum cooking time is corrected
+ or cleared.
+
+
+ Edit time filter
+
+
+ )}
+
No time limit applied.
+ )
}
- onChange={(event) => {
- const customMaxMinutes = parseCustomMaxMinutes(
- event.currentTarget.value,
- );
-
- setFilterDraft((current) => ({
- ...current,
- cookingTime: 'custom',
- customMaxMinutes,
- }));
-
- setShowCustomTimeError(false);
- }}
+ error={customTimeError(mobileTime)}
+ onChange={(event) => setMobileTime(event.currentTarget.value)}
/>
)}
diff --git a/apps/web/src/features/cookbook/CookbookPage.css b/apps/web/src/features/cookbook/CookbookPage.css
index 4ee1844..3553e5d 100644
--- a/apps/web/src/features/cookbook/CookbookPage.css
+++ b/apps/web/src/features/cookbook/CookbookPage.css
@@ -29,7 +29,7 @@
.cookbook-page__search-form {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
- align-items: end;
+ align-items: start;
gap: var(--space-3);
width: min(100%, 52rem);
@@ -76,7 +76,21 @@
grid-template-columns: 1fr;
}
+ /* Keep the stacked button in place when field feedback appears. */
+ .cookbook-page__search-form > .field {
+ display: contents;
+ }
+
+ .cookbook-page__search-form .field__control {
+ grid-row: 1;
+ }
+
+ .cookbook-page__search-form .field__error {
+ grid-row: 3;
+ }
+
.cookbook-page__search-button {
+ grid-row: 2;
width: 100%;
}
diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx
index 0180bb9..5499a89 100644
--- a/apps/web/src/features/cookbook/CookbookPage.test.tsx
+++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, useLocation } from 'react-router-dom';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
@@ -30,6 +30,58 @@ beforeEach(() =>
);
afterEach(() => vi.unstubAllGlobals());
+it('keeps the pending search when sort and filters change during the debounce', async () => {
+ const requests: unknown[] = [];
+ mockRecipeFetch((_operation, variables) => {
+ requests.push(variables.input);
+ return { data: { cookbook: apiPage() } };
+ });
+ mount();
+ await screen.findByRole('heading', { name: 'API soup' });
+ const input = screen.getByRole('searchbox') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: 'cake' } });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Sort by' }), {
+ target: { value: 'quickest' },
+ });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), {
+ target: { value: 'dessert' },
+ });
+ expect(input.value).toBe('cake');
+ await waitFor(() =>
+ expect(requests.at(-1)).toMatchObject({
+ search: 'cake',
+ sort: 'quickest',
+ category: 'dessert',
+ page: 1,
+ }),
+ );
+ const params = new URLSearchParams(
+ screen.getByTestId('location').textContent ?? '',
+ );
+ expect(Object.fromEntries(params)).toMatchObject({
+ q: 'cake',
+ sort: 'quickest',
+ category: 'dessert',
+ });
+});
+
+it('searches once after typing pauses and keeps the filters', async () => {
+ const searches: string[] = [];
+ mockRecipeFetch((_operation, variables) => {
+ searches.push((variables.input as { search: string }).search);
+ return { data: { cookbook: apiPage() } };
+ });
+ mount('/cookbook?category=soup');
+ const user = userEvent.setup();
+ await user.type(screen.getByRole('searchbox'), 'cake');
+ await waitFor(() => expect(searches).toEqual(['', 'cake']));
+ const params = new URLSearchParams(
+ screen.getByTestId('location').textContent ?? '',
+ );
+ expect(params.get('category')).toBe('soup');
+ expect(params.get('q')).toBe('cake');
+});
+
it('requests cookbook scopes from the server', async () => {
const variables: unknown[] = [];
mockRecipeFetch((_operation, args) => {
@@ -94,3 +146,50 @@ it('shows session-expired failures with retry', async () => {
).toBeTruthy();
expect(screen.queryByText('Your cookbook is empty')).toBeNull();
});
+
+it('rejects oversized submitted searches beside the field without a request', async () => {
+ const fetch = mockRecipeFetch(() => ({ data: { cookbook: apiPage([]) } }));
+ mount();
+ await screen.findByText('0 recipes found');
+ const before = fetch.mock.calls.length;
+ const input = screen.getByRole('searchbox');
+ fireEvent.change(input, { target: { value: 'a'.repeat(201) } });
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Search' }));
+ expect(
+ screen.getByText('Use at most 200 characters for search.'),
+ ).toBeTruthy();
+ expect(fetch.mock.calls.length).toBe(before);
+ expect(screen.getByTestId('location').textContent).toBe('');
+ fireEvent.change(input, { target: { value: 'a'.repeat(200) } });
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Search' }));
+ await waitFor(() => expect(fetch.mock.calls.length).toBe(before + 1));
+});
+
+it.each([
+ ['?q=' + 'a'.repeat(201), 'Use at most 200 characters for search.'],
+ ['?time=custom&maxTime=1.5', 'Enter whole minutes from 1 to 20,160.'],
+])('blocks invalid bookmarked criteria %s', async (query, message) => {
+ const fetch = mockRecipeFetch(() => ({ data: { cookbook: apiPage([]) } }));
+ mount('/cookbook' + query);
+ await screen.findByText(message);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(screen.queryByText('0 recipes found')).toBeNull();
+});
+
+it('keeps malformed bookmarked input editable and loads results after clearing', async () => {
+ const fetch = mockRecipeFetch(() => ({ data: { cookbook: apiPage([]) } }));
+ mount('/cookbook?time=custom&maxTime=abc');
+ const input = screen.getByRole('textbox', { name: 'Maximum cooking time' });
+ expect((input as HTMLInputElement).value).toBe('abc');
+ expect(screen.getByText('Invalid time filter')).toBeTruthy();
+ expect(fetch).not.toHaveBeenCalled();
+ fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), {
+ target: { value: 'soup' },
+ });
+ expect(screen.getByTestId('location').textContent).toContain('maxTime=abc');
+ expect(fetch).not.toHaveBeenCalled();
+ fireEvent.change(input, { target: { value: '' } });
+ await screen.findByText('0 recipes found');
+ expect(screen.getByTestId('location').textContent).not.toContain('maxTime');
+ expect(screen.queryByText('Invalid time filter')).toBeNull();
+});
diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx
index bf753b4..648e4d3 100644
--- a/apps/web/src/features/cookbook/CookbookPage.tsx
+++ b/apps/web/src/features/cookbook/CookbookPage.tsx
@@ -1,3 +1,5 @@
+import { useDebouncedRecipeSearch } from '../../lib/recipeBrowse/useDebouncedRecipeSearch';
+import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
@@ -6,7 +8,13 @@ import {
useState,
type SubmitEvent,
} from 'react';
-import { useSearchParams } from 'react-router-dom';
+import { useLocation, useSearchParams } from 'react-router-dom';
+import {
+ clampCustomTime,
+ customTimeError,
+ customTimeText,
+ searchError,
+} from '../../lib/recipeBrowse/browseValidation';
import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard';
import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps';
@@ -44,9 +52,12 @@ import RecipeQueryStatus from '../recipes/RecipeQueryStatus';
import './CookbookPage.css';
function CookbookPage() {
+ usePageTitle('My Cookbook');
const searchInputRef = useRef(null);
+ const resultCountRef = useRef(null);
const [searchParams, setSearchParams] = useSearchParams();
+ const location = useLocation();
const pendingSaves = useRef(new Set());
const [savingIds, setSavingIds] = useState([]);
@@ -58,8 +69,16 @@ function CookbookPage() {
);
const [searchInput, setSearchInput] = useState(search);
+ const criteriaInvalid =
+ !!searchError(search) ||
+ (browseState.cookingTime === 'custom' &&
+ !!customTimeError(clampCustomTime(customTimeText(browseState))));
const queryFilters = getCookbookQueryFilters(browseState);
+ const { changeSearch, resetSearch } = useDebouncedRecipeSearch(
+ search,
+ setSearchInput,
+ );
const { category, maxCookingMinutes, sort } = queryFilters;
const load = useCallback(
@@ -89,6 +108,7 @@ function CookbookPage() {
scope,
]),
load,
+ { enabled: !criteriaInvalid },
);
const result = query.data ?? {
items: [],
@@ -104,10 +124,6 @@ function CookbookPage() {
const hasActiveFilters = activeFilterCount > 0;
const hasSearchOrFilters = hasSearch || hasActiveFilters;
- useEffect(() => {
- setSearchInput(search);
- }, [search]);
-
/**
* paginate() normalizes invalid/out-of-range pages.
* Keep the URL synchronized with that normalized result.
@@ -146,6 +162,10 @@ function CookbookPage() {
function handleSearchSubmit(event: SubmitEvent) {
event.preventDefault();
+ if (searchError(searchInput)) {
+ searchInputRef.current?.focus();
+ return;
+ }
updateUrlState({
scope,
@@ -205,13 +225,12 @@ function CookbookPage() {
}
function handleClearResultCriteria() {
+ resetSearch();
const nextBrowseState: CookbookBrowseState = {
...DEFAULT_RECIPE_FILTER_STATE,
sort: browseState.sort,
};
- setSearchInput('');
-
updateUrlState({
scope,
search: '',
@@ -237,6 +256,9 @@ function CookbookPage() {
left: 0,
behavior: 'auto',
});
+
+ // Move keyboard focus to the visible result count, as in ExplorePage.
+ resultCountRef.current?.focus({ preventScroll: true });
}
async function handleRecipeSaveChange(recipe: RecipeSummary, saved: boolean) {
@@ -327,26 +349,10 @@ function CookbookPage() {
type="search"
name="search"
value={searchInput}
- placeholder="Search recipe titles or descriptions..."
+ error={searchError(searchInput)}
+ placeholder="Search recipes, ingredients or tags..."
autoComplete="off"
- onChange={(event) => {
- const value = event.currentTarget.value;
-
- setSearchInput(value);
-
- /**
- * Match the current Explore behavior:
- * clearing a submitted search immediately clears it from the URL.
- */
- if (value === '' && search !== '') {
- updateUrlState({
- scope,
- search: '',
- browseState,
- page: 1,
- });
- }
- }}
+ onChange={(event) => changeSearch(event.currentTarget.value)}
/>
@@ -363,6 +369,7 @@ function CookbookPage() {
-
- {saveError && {saveError}
}
- {!query.loading && !query.error && (
- <>
-
+ {/*
+ * Always mounted, so screen readers announce the new count when a
+ * page change or filter finishes loading. Paging moves focus here:
+ * it is visible text, so keyboard users can see where they are.
+ */}
+
+ {query.loading ? (
+ 'Loading recipes…'
+ ) : query.error || criteriaInvalid ? null : (
+ <>
{result.totalItems}{' '}
{result.totalItems === 1 ? 'recipe' : 'recipes'} found
@@ -384,8 +401,14 @@ function CookbookPage() {
? `. Page ${result.page} of ${result.pageCount}.`
: '.'}
-
-
+ >
+ )}
+
+ {/* Errors and retry only; loading is shown in the line above. */}
+
+ {saveError && {saveError}
}
+ {!criteriaInvalid && !query.loading && !query.error && (
+ <>
{result.totalItems > 0 ? (
<>
diff --git a/apps/web/src/features/cookbook/cookbookBrowseState.ts b/apps/web/src/features/cookbook/cookbookBrowseState.ts
index b2cf465..1d7ab6d 100644
--- a/apps/web/src/features/cookbook/cookbookBrowseState.ts
+++ b/apps/web/src/features/cookbook/cookbookBrowseState.ts
@@ -15,7 +15,7 @@ export const COOKBOOK_SCOPE_OPTIONS = [
export type CookbookScope = (typeof COOKBOOK_SCOPE_OPTIONS)[number]['value'];
export const COOKBOOK_SORT_OPTIONS = [
- { value: 'newest', label: 'Newest first' },
+ { value: 'newest', label: 'Newest by creation date' },
{ value: 'quickest', label: 'Shortest cooking time' },
{ value: 'highest_rated', label: 'Highest rated' },
] as const;
@@ -58,6 +58,6 @@ export function countActiveCookbookFilters(state: CookbookBrowseState) {
export function getCookbookSortLabel(sort: CookbookSort) {
return (
COOKBOOK_SORT_OPTIONS.find((option) => option.value === sort)?.label ??
- 'Newest first'
+ 'Newest by creation date'
);
}
diff --git a/apps/web/src/features/cookbook/cookbookUrlState.test.ts b/apps/web/src/features/cookbook/cookbookUrlState.test.ts
index a1897f4..cafb56f 100644
--- a/apps/web/src/features/cookbook/cookbookUrlState.test.ts
+++ b/apps/web/src/features/cookbook/cookbookUrlState.test.ts
@@ -97,3 +97,27 @@ describe('Cookbook URL state', () => {
});
});
});
+
+it.each(['abc', '1.5', 'x'.repeat(300)])(
+ 'preserves invalid custom time %s without NaN',
+ (raw) => {
+ const state = readCookbookUrlState(
+ new URLSearchParams({ time: 'custom', maxTime: raw }),
+ );
+ expect(state.browseState.customMaxMinutes).toBeNull();
+ expect(state.browseState.customMaxMinutesRaw).toBe(raw);
+ expect(createCookbookSearchParams(state).get('maxTime')).toBe(raw);
+ },
+);
+
+it.each([
+ ['20161', 20160],
+ ['-1', 1],
+ ['0', 1],
+])('clamps bookmarked time %s to %s', (raw, expected) => {
+ const state = readCookbookUrlState(
+ new URLSearchParams({ time: 'custom', maxTime: raw }),
+ );
+ expect(state.browseState.customMaxMinutes).toBe(expected);
+ expect(state.browseState.customMaxMinutesRaw).toBe(raw);
+});
diff --git a/apps/web/src/features/cookbook/cookbookUrlState.ts b/apps/web/src/features/cookbook/cookbookUrlState.ts
index 59026a8..269dd9d 100644
--- a/apps/web/src/features/cookbook/cookbookUrlState.ts
+++ b/apps/web/src/features/cookbook/cookbookUrlState.ts
@@ -1,3 +1,4 @@
+import { readCustomTime } from '../../lib/recipeBrowse/browseValidation';
import {
isRecipeCategory,
isRecipeCookingTime,
@@ -50,10 +51,10 @@ export function readCookbookUrlState(
? sortParam
: DEFAULT_COOKBOOK_BROWSE_STATE.sort;
- const customMaxMinutes =
+ const customTime =
cookingTime === 'custom'
- ? parsePositiveInteger(searchParams.get('maxTime'))
- : null;
+ ? readCustomTime(searchParams.get('maxTime'))
+ : { customMaxMinutes: null };
return {
scope,
@@ -63,7 +64,7 @@ export function readCookbookUrlState(
browseState: {
category,
cookingTime,
- customMaxMinutes,
+ ...customTime,
sort,
},
@@ -98,9 +99,13 @@ export function createCookbookSearchParams({
if (
browseState.cookingTime === 'custom' &&
- browseState.customMaxMinutes !== null
+ (browseState.customMaxMinutesRaw !== undefined ||
+ browseState.customMaxMinutes !== null)
) {
- searchParams.set('maxTime', String(browseState.customMaxMinutes));
+ searchParams.set(
+ 'maxTime',
+ browseState.customMaxMinutesRaw ?? String(browseState.customMaxMinutes),
+ );
}
}
diff --git a/apps/web/src/features/explore/ExploreControls.css b/apps/web/src/features/explore/ExploreControls.css
index e7ab09d..a91a366 100644
--- a/apps/web/src/features/explore/ExploreControls.css
+++ b/apps/web/src/features/explore/ExploreControls.css
@@ -11,7 +11,7 @@
.explore-controls__desktop {
display: flex;
flex-wrap: nowrap;
- align-items: center;
+ align-items: flex-start;
gap: var(--space-3);
min-width: 0;
@@ -49,8 +49,14 @@
width: 18rem;
}
- .explore-controls__custom-time-input {
+ .explore-controls__desktop-control--custom-time {
+ flex: 0 0 9rem;
width: 9rem;
+ overflow-wrap: anywhere;
+ }
+
+ .explore-controls__custom-time-input {
+ width: 100%;
background-color: var(--color-surface-raised);
border-color: var(--color-border-input);
diff --git a/apps/web/src/features/explore/ExploreControls.test.tsx b/apps/web/src/features/explore/ExploreControls.test.tsx
index 7c6faff..bc04864 100644
--- a/apps/web/src/features/explore/ExploreControls.test.tsx
+++ b/apps/web/src/features/explore/ExploreControls.test.tsx
@@ -128,7 +128,7 @@ describe('ExploreControls', () => {
).toBe('lte60');
});
- it('requires a positive custom maximum before applying mobile filters', async () => {
+ it('requires a valid nonempty custom maximum before applying mobile filters', async () => {
const user = userEvent.setup();
render( );
@@ -146,20 +146,24 @@ describe('ExploreControls', () => {
}),
);
- await user.click(
- screen.getByRole('button', {
- name: 'Apply filters',
+ fireEvent.change(
+ screen.getByRole('textbox', {
+ name: 'Maximum cooking time in minutes',
}),
+ { target: { value: 'abc' } },
);
+ await user.click(screen.getByRole('button', { name: 'Apply filters' }));
+
expect(
- screen.getByText('Enter a maximum cooking time before applying filters.'),
+ screen.getByText('Enter whole minutes from 1 to 20,160.'),
).toBeTruthy();
- const customMaximum = screen.getByRole('spinbutton', {
+ const customMaximum = screen.getByRole('textbox', {
name: 'Maximum cooking time in minutes',
});
+ await user.clear(customMaximum);
await user.type(customMaximum, '45');
await user.click(
@@ -185,7 +189,7 @@ describe('ExploreControls', () => {
expect(
(
- screen.getByRole('spinbutton', {
+ screen.getByRole('textbox', {
name: 'Maximum cooking time',
}) as HTMLInputElement
).value,
diff --git a/apps/web/src/features/explore/ExploreControls.tsx b/apps/web/src/features/explore/ExploreControls.tsx
index 63bdb04..f2a8164 100644
--- a/apps/web/src/features/explore/ExploreControls.tsx
+++ b/apps/web/src/features/explore/ExploreControls.tsx
@@ -1,7 +1,14 @@
-import { useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
+import {
+ clampCustomTime,
+ customTimeError,
+ customTimeText,
+} from '../../lib/recipeBrowse/browseValidation';
+import { useCustomTimeInput } from '../../lib/recipeBrowse/useCustomTimeInput';
import Button from '../../components/ui/Button/Button';
import Field from '../../components/ui/Field/Field';
+import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage';
import FilterChip from '../../components/ui/FilterChip/FilterChip';
import { Icon } from '../../components/ui/Icon/Icon';
import Radio from '../../components/ui/Radio/Radio';
@@ -27,23 +34,25 @@ import {
import './ExploreControls.css';
export type ExploreControlsProps = {
+ navigationKey?: string;
value: ExploreBrowseState;
onChange: (value: ExploreBrowseState) => void;
};
-function parseCustomMaxMinutes(value: string) {
- if (value.trim() === '') {
- return null;
- }
-
- const parsed = Number(value);
-
- return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
-}
-
-function ExploreControls({ value, onChange }: ExploreControlsProps) {
+function ExploreControls({
+ value,
+ onChange,
+ navigationKey = '',
+}: ExploreControlsProps) {
const [filterSheetOpen, setFilterSheetOpen] = useState(false);
const [sortSheetOpen, setSortSheetOpen] = useState(false);
+ const [focusMobileTime, setFocusMobileTime] = useState(false);
+ const desktopTimeRef = useRef(null);
+ const mobileTimeRef = useRef(null);
+
+ useEffect(() => {
+ if (filterSheetOpen && focusMobileTime) mobileTimeRef.current?.focus();
+ }, [filterSheetOpen, focusMobileTime]);
const [filterDraft, setFilterDraft] = useState({
category: value.category,
@@ -52,7 +61,25 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
});
const [sortDraft, setSortDraft] = useState(value.sort);
- const [showCustomTimeError, setShowCustomTimeError] = useState(false);
+ const [mobileTime, setMobileTime] = useState('');
+ const resetKey = JSON.stringify([navigationKey, value]);
+ const desktopTime = useCustomTimeInput(
+ value.customMaxMinutes,
+ resetKey,
+ (minutes, raw) => {
+ onChange({
+ ...value,
+ cookingTime: 'custom',
+ customMaxMinutes: minutes,
+ customMaxMinutesRaw: raw,
+ });
+ },
+ value.customMaxMinutesRaw,
+ );
+ const committedTimeError =
+ value.cookingTime === 'custom'
+ ? customTimeError(clampCustomTime(customTimeText(value)))
+ : undefined;
const activeFilterCount = countActiveExploreFilters(value);
const currentSortLabel = getExploreSortLabel(value.sort);
@@ -69,28 +96,26 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
cookingTime,
customMaxMinutes:
cookingTime === 'custom' ? value.customMaxMinutes : null,
+ customMaxMinutesRaw:
+ cookingTime === 'custom' ? value.customMaxMinutesRaw : undefined,
});
}
- function handleDesktopCustomMaxChange(rawValue: string) {
- updateValue({
- cookingTime: 'custom',
- customMaxMinutes: parseCustomMaxMinutes(rawValue),
- });
- }
-
- function openFilterSheet() {
+ function openFilterSheet(focusTime = false) {
+ setFocusMobileTime(focusTime);
setFilterDraft({
category: value.category,
cookingTime: value.cookingTime,
customMaxMinutes: value.customMaxMinutes,
});
- setShowCustomTimeError(false);
+ setMobileTime(customTimeText(value));
setFilterSheetOpen(true);
}
function handleDraftCookingTimeChange(cookingTime: ExploreCookingTime) {
+ if (cookingTime === filterDraft.cookingTime) return;
+
setFilterDraft((current) => ({
...current,
cookingTime,
@@ -98,26 +123,39 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
cookingTime === 'custom' ? current.customMaxMinutes : null,
}));
- setShowCustomTimeError(false);
+ setMobileTime('');
}
function handleApplyFilters() {
- if (
- filterDraft.cookingTime === 'custom' &&
- filterDraft.customMaxMinutes === null
- ) {
- setShowCustomTimeError(true);
+ const clamped = clampCustomTime(mobileTime);
+ if (filterDraft.cookingTime === 'custom' && customTimeError(clamped)) {
return;
}
onChange({
...value,
...filterDraft,
+ customMaxMinutes:
+ filterDraft.cookingTime === 'custom' && clamped.trim()
+ ? Number(clamped)
+ : null,
+ customMaxMinutesRaw:
+ filterDraft.cookingTime === 'custom' && customTimeError(mobileTime)
+ ? mobileTime
+ : undefined,
});
setFilterSheetOpen(false);
}
+ function editTimeFilter() {
+ if (desktopTimeRef.current?.getClientRects().length) {
+ desktopTimeRef.current.focus();
+ } else {
+ openFilterSheet(true);
+ }
+ }
+
function openSortSheet() {
setSortDraft(value.sort);
setSortSheetOpen(true);
@@ -182,19 +220,25 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
{value.cookingTime === 'custom' && (
-
+
No time limit applied.
+ ) : undefined
+ }
placeholder="Max minutes"
onChange={(event) =>
- handleDesktopCustomMaxChange(event.currentTarget.value)
+ desktopTime.change(event.currentTarget.value)
}
/>
@@ -227,7 +271,7 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
openFilterSheet()}
>
@@ -247,6 +291,18 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
+ {committedTimeError && (
+
+
+ Recipes cannot be loaded until the maximum cooking time is corrected
+ or cleared.
+
+
+ Edit time filter
+
+
+ )}
+
{
setFilterDraft(DEFAULT_EXPLORE_FILTER_STATE);
- setShowCustomTimeError(false);
+ setMobileTime('');
}}
>
Clear filters
@@ -319,32 +375,21 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
{filterDraft.cookingTime === 'custom' && (
No time limit applied.
+ )
}
- onChange={(event) => {
- const customMaxMinutes = parseCustomMaxMinutes(
- event.currentTarget.value,
- );
-
- setFilterDraft((current) => ({
- ...current,
- cookingTime: 'custom',
- customMaxMinutes,
- }));
-
- setShowCustomTimeError(false);
- }}
+ error={customTimeError(mobileTime)}
+ onChange={(event) => setMobileTime(event.currentTarget.value)}
/>
)}
diff --git a/apps/web/src/features/explore/ExplorePage.css b/apps/web/src/features/explore/ExplorePage.css
index 048100b..e50df97 100644
--- a/apps/web/src/features/explore/ExplorePage.css
+++ b/apps/web/src/features/explore/ExplorePage.css
@@ -29,7 +29,7 @@
.explore-page__search-form {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
- align-items: end;
+ align-items: start;
gap: var(--space-3);
width: min(100%, 52rem);
@@ -85,7 +85,21 @@
grid-template-columns: 1fr;
}
+ /* Keep the stacked button in place when field feedback appears. */
+ .explore-page__search-form > .field {
+ display: contents;
+ }
+
+ .explore-page__search-form .field__control {
+ grid-row: 1;
+ }
+
+ .explore-page__search-form .field__error {
+ grid-row: 3;
+ }
+
.explore-page__search-button {
+ grid-row: 2;
width: 100%;
}
diff --git a/apps/web/src/features/explore/ExplorePage.test.tsx b/apps/web/src/features/explore/ExplorePage.test.tsx
index 9513503..0b01235 100644
--- a/apps/web/src/features/explore/ExplorePage.test.tsx
+++ b/apps/web/src/features/explore/ExplorePage.test.tsx
@@ -1,6 +1,17 @@
-import { act, render, screen, waitFor } from '@testing-library/react';
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { MemoryRouter, useLocation } from 'react-router-dom';
+import {
+ createMemoryRouter,
+ MemoryRouter,
+ RouterProvider,
+ useLocation,
+} from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
apiPage,
@@ -28,6 +39,89 @@ beforeEach(() => {
});
afterEach(() => vi.unstubAllGlobals());
+it('keeps the pending search when sort and filters change during the debounce', async () => {
+ const requests: unknown[] = [];
+ mockRecipeFetch((_operation, variables) => {
+ requests.push(variables.input);
+ return { data: { recipes: apiPage() } };
+ });
+ mount();
+ await screen.findByRole('heading', { name: 'API soup' });
+ const input = screen.getByRole('searchbox') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: 'cake' } });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Sort by' }), {
+ target: { value: 'quickest' },
+ });
+ fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), {
+ target: { value: 'dessert' },
+ });
+ expect(input.value).toBe('cake');
+ await waitFor(() =>
+ expect(requests.at(-1)).toMatchObject({
+ search: 'cake',
+ sort: 'quickest',
+ category: 'dessert',
+ page: 1,
+ }),
+ );
+ const params = new URLSearchParams(
+ screen.getByTestId('location').textContent ?? '',
+ );
+ expect(Object.fromEntries(params)).toMatchObject({
+ q: 'cake',
+ sort: 'quickest',
+ category: 'dessert',
+ });
+});
+
+it.each(['Back', 'Clear filters'])(
+ 'discards a pending search on %s',
+ async (action) => {
+ mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } }));
+ const router = createMemoryRouter(
+ [{ path: '/', element: }],
+ {
+ initialEntries: ['/?sort=quickest', '/?category=dessert'],
+ },
+ );
+ render( );
+ const clear = await screen.findByRole('button', { name: 'Clear filters' });
+ const input = screen.getByRole('searchbox') as HTMLInputElement;
+ vi.useFakeTimers();
+ try {
+ fireEvent.change(input, { target: { value: 'cake' } });
+ await act(async () => {
+ if (action === 'Back') await router.navigate(-1);
+ else fireEvent.click(clear);
+ });
+ await act(() => vi.advanceTimersByTimeAsync(350));
+ expect(input.value).toBe('');
+ expect(router.state.location.search).toBe(
+ action === 'Back' ? '?sort=quickest' : '',
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+);
+
+it('searches once after typing pauses and keeps the filters', async () => {
+ const searches: string[] = [];
+ mockRecipeFetch((_operation, variables) => {
+ searches.push((variables.input as { search: string }).search);
+ return { data: { recipes: apiPage() } };
+ });
+ mount('/?category=soup');
+ const user = userEvent.setup();
+ await user.type(screen.getByRole('searchbox'), 'cake');
+ await waitFor(() => expect(searches).toEqual(['', 'cake']));
+ const params = new URLSearchParams(
+ screen.getByTestId('location').textContent ?? '',
+ );
+ expect(params.get('category')).toBe('soup');
+ expect(params.get('q')).toBe('cake');
+});
+
describe('Explore API integration', () => {
it('sends sorting to the API and reuses only the matching cached sort', async () => {
const requests: string[] = [];
@@ -79,6 +173,30 @@ describe('Explore API integration', () => {
).toBeTruthy();
expect(screen.queryByRole('option', { name: 'Trending' })).toBeNull();
});
+ it('moves focus to the results after a page change', async () => {
+ mockRecipeFetch((_operation, variables) => {
+ const page = (variables.input as { page: number }).page;
+ return {
+ data: {
+ recipes: apiPage([{ ...apiRecipe, title: `Page ${page} recipe` }], {
+ page,
+ totalPages: 2,
+ totalCount: 7,
+ }),
+ },
+ };
+ });
+ mount('/');
+ await screen.findByRole('heading', { name: 'Page 1 recipe' });
+ const count = screen.getByText(/^7 recipes found/);
+ const user = userEvent.setup();
+ await user.click(screen.getAllByRole('button', { name: 'Next page' })[0]!);
+ await screen.findByRole('heading', { name: 'Page 2 recipe' });
+ // Focus is on the visible count, which stayed mounted while loading
+ // (same element) and now announces the new page.
+ expect(document.activeElement).toBe(count);
+ expect(count.textContent).toBe('7 recipes found. Page 2 of 2.');
+ });
it('commits search to the URL and resets the requested page', async () => {
const requests: unknown[] = [];
mockRecipeFetch((_operation, variables) => {
@@ -186,3 +304,50 @@ describe('Explore API integration', () => {
).toBeTruthy();
});
});
+
+it('rejects oversized submitted searches beside the field without a request', async () => {
+ const fetch = mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } }));
+ mount();
+ await screen.findByText('0 recipes found');
+ const before = fetch.mock.calls.length;
+ const input = screen.getByRole('searchbox');
+ fireEvent.change(input, { target: { value: 'a'.repeat(201) } });
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Search' }));
+ expect(
+ screen.getByText('Use at most 200 characters for search.'),
+ ).toBeTruthy();
+ expect(fetch.mock.calls.length).toBe(before);
+ expect(screen.getByTestId('location').textContent).toBe('');
+ fireEvent.change(input, { target: { value: 'a'.repeat(200) } });
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Search' }));
+ await waitFor(() => expect(fetch.mock.calls.length).toBe(before + 1));
+});
+
+it.each([
+ ['?q=' + 'a'.repeat(201), 'Use at most 200 characters for search.'],
+ ['?time=custom&maxTime=1.5', 'Enter whole minutes from 1 to 20,160.'],
+])('blocks invalid bookmarked criteria %s', async (query, message) => {
+ const fetch = mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } }));
+ mount('/' + query);
+ await screen.findByText(message);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(screen.queryByText('0 recipes found')).toBeNull();
+});
+
+it('keeps malformed bookmarked input editable and loads results after clearing', async () => {
+ const fetch = mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } }));
+ mount('/?time=custom&maxTime=abc');
+ const input = screen.getByRole('textbox', { name: 'Maximum cooking time' });
+ expect((input as HTMLInputElement).value).toBe('abc');
+ expect(screen.getByText('Invalid time filter')).toBeTruthy();
+ expect(fetch).not.toHaveBeenCalled();
+ fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), {
+ target: { value: 'soup' },
+ });
+ expect(screen.getByTestId('location').textContent).toContain('maxTime=abc');
+ expect(fetch).not.toHaveBeenCalled();
+ fireEvent.change(input, { target: { value: '' } });
+ await screen.findByText('0 recipes found');
+ expect(screen.getByTestId('location').textContent).not.toContain('maxTime');
+ expect(screen.queryByText('Invalid time filter')).toBeNull();
+});
diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx
index f5e486c..67f474d 100644
--- a/apps/web/src/features/explore/ExplorePage.tsx
+++ b/apps/web/src/features/explore/ExplorePage.tsx
@@ -1,3 +1,5 @@
+import { useDebouncedRecipeSearch } from '../../lib/recipeBrowse/useDebouncedRecipeSearch';
+import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
@@ -6,7 +8,13 @@ import {
useState,
type SubmitEvent,
} from 'react';
-import { useSearchParams } from 'react-router-dom';
+import { useLocation, useSearchParams } from 'react-router-dom';
+import {
+ clampCustomTime,
+ customTimeError,
+ customTimeText,
+ searchError,
+} from '../../lib/recipeBrowse/browseValidation';
import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard';
import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps';
@@ -48,9 +56,12 @@ type SaveFeedback = {
};
function ExplorePage() {
+ usePageTitle('Explore recipes');
const searchInputRef = useRef(null);
+ const resultCountRef = useRef(null);
const [searchParams, setSearchParams] = useSearchParams();
+ const location = useLocation();
const currentUser = useAppStore((state) => state.currentUser);
@@ -71,8 +82,16 @@ function ExplorePage() {
* sorting, and pagination.
*/
const [searchInput, setSearchInput] = useState(search);
+ const criteriaInvalid =
+ !!searchError(search) ||
+ (browseState.cookingTime === 'custom' &&
+ !!customTimeError(clampCustomTime(customTimeText(browseState))));
const queryFilters = getExploreQueryFilters(browseState);
+ const { changeSearch, resetSearch } = useDebouncedRecipeSearch(
+ search,
+ setSearchInput,
+ );
const { category, maxCookingMinutes, sort } = queryFilters;
const load = useCallback(
@@ -101,6 +120,7 @@ function ExplorePage() {
page,
]),
load,
+ { enabled: !criteriaInvalid },
);
const result = query.data ?? {
items: [],
@@ -116,14 +136,6 @@ function ExplorePage() {
const hasActiveFilters = activeFilterCount > 0;
const hasSearchOrFilters = hasSearch || hasActiveFilters;
- /*
- * Browser Back/Forward may change the committed search in the URL.
- * Keep the visible search input synchronized with that state.
- */
- useEffect(() => {
- setSearchInput(search);
- }, [search]);
-
/*
* paginate() clamps out-of-range pages.
*
@@ -155,6 +167,10 @@ function ExplorePage() {
function handleSearchSubmit(event: SubmitEvent) {
event.preventDefault();
+ if (searchError(searchInput)) {
+ searchInputRef.current?.focus();
+ return;
+ }
updateUrlState({
search: searchInput,
@@ -184,13 +200,12 @@ function ExplorePage() {
}
function handleClearResultCriteria() {
+ resetSearch();
const nextBrowseState: ExploreBrowseState = {
...DEFAULT_EXPLORE_FILTER_STATE,
sort: browseState.sort,
};
- setSearchInput('');
-
updateUrlState({
search: '',
browseState: nextBrowseState,
@@ -214,6 +229,14 @@ function ExplorePage() {
left: 0,
behavior: 'auto',
});
+
+ /*
+ * The pagination buttons sit below the results. Without this, keyboard
+ * and screen-reader users would stay at the bottom of a page they can no
+ * longer see. The result count is visible (so the focus ring shows) and
+ * stays mounted while loading, so its new text is announced.
+ */
+ resultCountRef.current?.focus({ preventScroll: true });
}
async function handleRecipeSaveChange(recipe: RecipeSummary, saved: boolean) {
@@ -294,25 +317,10 @@ function ExplorePage() {
type="search"
name="search"
value={searchInput}
- placeholder="Search recipe titles or descriptions..."
+ error={searchError(searchInput)}
+ placeholder="Search recipes, ingredients or tags..."
autoComplete="off"
- onChange={(event) => {
- const value = event.currentTarget.value;
-
- setSearchInput(value);
-
- /*
- * Preserve the existing Explore behavior where emptying a
- * previously submitted search immediately clears that search.
- */
- if (value === '' && search !== '') {
- updateUrlState({
- search: '',
- browseState,
- page: 1,
- });
- }
- }}
+ onChange={(event) => changeSearch(event.currentTarget.value)}
/>
@@ -329,14 +337,26 @@ function ExplorePage() {
-
- {!query.loading && !query.error && (
- <>
-
+ {/*
+ * Always mounted, so screen readers announce the new count when a
+ * page change or filter finishes loading. Paging moves focus here:
+ * it is visible text, so keyboard users can see where they are.
+ */}
+
+ {query.loading ? (
+ 'Loading recipes…'
+ ) : query.error || criteriaInvalid ? null : (
+ <>
{result.totalItems}{' '}
{result.totalItems === 1 ? 'recipe' : 'recipes'} found
@@ -346,8 +366,13 @@ function ExplorePage() {
? `. Page ${result.page} of ${result.pageCount}.`
: '.'}
-
-
+ >
+ )}
+
+ {/* Errors and retry only; loading is shown in the line above. */}
+
+ {!criteriaInvalid && !query.loading && !query.error && (
+ <>
{result.totalItems > 0 ? (
<>
diff --git a/apps/web/src/features/explore/SERVER_INTEGRATION.md b/apps/web/src/features/explore/SERVER_INTEGRATION.md
deleted file mode 100644
index 0a769f4..0000000
--- a/apps/web/src/features/explore/SERVER_INTEGRATION.md
+++ /dev/null
@@ -1,362 +0,0 @@
-> Historical design notes: Explore now uses the GraphQL API. See [the current integration checklist](../../../../../docs/frontend-integration.md) for implemented behavior and remaining work. The mock-query examples below describe the earlier prototype.
-
-# Explore server integration
-
-The current Explore implementation uses local mock data, but the feature is structured so the UI can later be connected to a GraphQL/API backend without redesigning the page.
-
-The main goal of the migration is to replace the mock data boundary while keeping the existing URL state, filter-state conversion, page structure, and presentation components.
-
-## Current flow
-
-```text
-URL query params
-→ exploreUrlState.ts
-→ ExploreBrowseState
-→ getExploreQueryFilters(...)
-→ mockExploreQuery.ts
-→ paginated recipe result
-→ ExplorePage.tsx
-→ RecipeCard
-```
-
-`ExplorePage.tsx` is intentionally not responsible for implementing search, filtering, sorting, or pagination rules itself.
-
-Instead, it:
-
-1. reads the current browse state from the URL
-2. converts UI-specific filter state into query-friendly values
-3. requests a result from the data layer
-4. renders the returned recipes and pagination metadata
-5. writes browse-state changes back to the URL
-
-That separation should remain when the backend is introduced.
-
-## Main files and responsibilities
-
-### `ExplorePage.tsx`
-
-This is the page and interaction layer.
-
-It currently:
-
-- reads URL state
-- owns the unsubmitted search input
-- calls the mock Explore query
-- renders the result count, recipe cards, empty state, and pagination
-- updates the URL when search, filters, sorting, or page changes
-- connects Save/Saved UI to shared application state
-
-When server data is introduced, the main change here should be replacing the synchronous mock query call with data from a GraphQL/API query.
-
-Today:
-
-```ts
-const result = getMockExploreResult({
- search,
- category,
- maxCookingMinutes,
- sort,
- page,
- pageSize,
-});
-```
-
-Later, this could become something conceptually like:
-
-```ts
-const { data, loading, error } = useExploreRecipesQuery({
- variables: {
- input: {
- search,
- category,
- maxCookingMinutes,
- sort,
- page,
- pageSize,
- },
- },
-});
-```
-
-The exact GraphQL client and hook names can be decided later.
-
-### `exploreUrlState.ts`
-
-This file should stay responsible for translating between browser query parameters and Explore state.
-
-For example:
-
-```text
-/project2/?q=pasta&category=dinner&time=lte30&sort=popular&page=2
-```
-
-can become frontend state such as:
-
-```ts
-{
- search: 'pasta',
- browseState: {
- category: 'dinner',
- cookingTime: 'lte30',
- customMaxMinutes: null,
- sort: 'popular',
- },
- page: 2,
-}
-```
-
-Keeping this logic in the frontend preserves:
-
-- refresh behavior
-- Back/Forward navigation
-- shareable browse URLs
-- returning from Recipe Detail to the same result context
-
-The server does not need to understand UI-specific URL values such as `time=lte30`.
-
-### `exploreBrowseState.ts`
-
-This file defines the Explore filter and sort options and converts UI values into query-friendly values.
-
-For example:
-
-```text
-lte30
-```
-
-is a frontend option, while the query layer receives:
-
-```ts
-maxCookingMinutes: 30;
-```
-
-That same conversion can be used when creating GraphQL variables.
-
-For example:
-
-```ts
-{
- category: 'dinner',
- maxCookingMinutes: 30,
- sort: 'popular',
-}
-```
-
-The backend should receive domain values, not frontend option IDs such as `lte15`, `lte30`, or `custom`.
-
-### `mockExploreQuery.ts`
-
-This is the main mock data boundary.
-
-Today it performs work that a backend would normally perform:
-
-- public/private visibility filtering
-- text search
-- category filtering
-- cooking-time filtering
-- Trending filtering
-- sorting
-- pagination
-- pagination metadata calculation
-
-Conceptually, it acts as a temporary local backend.
-
-When the real backend exists, this logic should move out of the browser and into the server/data layer.
-
-## What should move to the backend
-
-With GraphQL or another API, the server should normally handle:
-
-- returning only recipes the user is allowed to discover
-- searching title, description, tags, and ingredients
-- applying category filters
-- applying maximum cooking-time filters
-- implementing Trending / Most popular / Newest / Most saved ordering
-- paginating after filtering and sorting
-- returning pagination metadata
-
-The frontend should send query variables and render the result rather than loading the full recipe dataset and filtering it locally.
-
-For example:
-
-```ts
-{
- search: 'pasta',
- category: 'dinner',
- maxCookingMinutes: 30,
- sort: 'popular',
- page: 2,
- pageSize: 6,
-}
-```
-
-A useful server response shape would remain close to the current mock result:
-
-```ts
-{
- items,
- totalItems,
- page,
- pageCount,
-}
-```
-
-This allows the existing result count and pagination UI to stay mostly unchanged.
-
-## Possible GraphQL shape
-
-The exact schema does not need to match this, but a future query could look approximately like:
-
-```graphql
-query ExploreRecipes($input: ExploreRecipesInput!) {
- exploreRecipes(input: $input) {
- items {
- id
- title
- description
- category
- cuisine
- prepMinutes
- cookMinutes
- servings
- tags
- imageUrl
-
- author {
- id
- name
- }
-
- rating {
- average
- count
- }
-
- saveCount
- isSaved
- isCreatedByCurrentUser
- createdAt
- }
-
- totalItems
- page
- pageCount
- }
-}
-```
-
-Possible variables:
-
-```ts
-{
- input: {
- search: 'pasta',
- category: 'dinner',
- maxCookingMinutes: 30,
- sort: 'popular',
- page: 2,
- pageSize: 6,
- },
-}
-```
-
-## Saved recipes
-
-Keep aggregate save data and current-user saved state separate.
-
-```text
-saveCount
-```
-
-means how many users have saved a recipe and is used for **Most saved** sorting.
-
-```text
-isSaved / savedRecipeIds
-```
-
-represents whether the current user has saved that recipe.
-
-Today, `savedRecipeIds` is in-memory Zustand state seeded from mock recipe data.
-
-With a backend, the server should become the source of truth for this relationship.
-
-Saving could later become a mutation such as:
-
-```graphql
-mutation SaveRecipe($recipeId: ID!) {
- saveRecipe(recipeId: $recipeId) {
- recipeId
- isSaved
- }
-}
-```
-
-Unsaving could use a separate mutation or a single mutation that accepts the desired saved state.
-
-After a successful mutation, the frontend cache/shared state should update so that Explore, Recipe Detail, and My Cookbook all show the same state.
-
-## Recommended migration path
-
-A reasonable migration is:
-
-1. Keep `exploreUrlState.ts` and `exploreBrowseState.ts`.
-2. Introduce a GraphQL/API data-access layer for Explore.
-3. Replace `getMockExploreResult(...)` in `ExplorePage.tsx` with the server query result.
-4. Add loading and error states for asynchronous requests.
-5. Move filtering, sorting, visibility rules, and pagination to the server.
-6. Replace in-memory save updates with mutations and synchronized server-backed state.
-7. Remove or retain `mockExploreQuery.ts` only for tests/development once production uses real data.
-
-A future feature structure could look like:
-
-```text
-features/explore/
- ExplorePage.tsx
- ExploreControls.tsx
- exploreBrowseState.ts
- exploreUrlState.ts
- queries/
- exploreRecipes.graphql
- useExploreRecipes.ts
-```
-
-The exact structure can be adjusted to match the GraphQL tooling chosen by the project.
-
-## What should stay in the frontend
-
-The following should remain frontend responsibilities:
-
-- URL parsing and serialization
-- labels such as `15 min or less` and `Most popular`
-- temporary UI state such as open sheets/dialogs and unsubmitted search text
-- rendering recipe cards
-- rendering pagination controls
-- showing loading, empty, error, and success feedback
-
-Presentation components such as `RecipeCard`, `Pagination`, `Select`, and `Toast` should remain unaware of whether data came from mock arrays, GraphQL, REST, or another backend.
-
-## Target flow
-
-The final server-backed Explore flow should roughly be:
-
-```text
-User changes search/filter/sort/page
- ↓
-URL is updated
- ↓
-exploreUrlState.ts parses URL
- ↓
-exploreBrowseState.ts converts UI values
- ↓
-GraphQL/API variables are created
- ↓
-Server applies search/filter/sort/pagination
- ↓
-Server returns recipes + pagination metadata
- ↓
-ExplorePage.tsx renders the result
- ↓
-RecipeCard renders each recipe
-```
-
-The goal is therefore to replace the current mock data source, not rebuild the Explore UI.
diff --git a/apps/web/src/features/explore/exploreUrlState.test.ts b/apps/web/src/features/explore/exploreUrlState.test.ts
index 366e66d..dde606b 100644
--- a/apps/web/src/features/explore/exploreUrlState.test.ts
+++ b/apps/web/src/features/explore/exploreUrlState.test.ts
@@ -116,3 +116,27 @@ describe('Explore URL state', () => {
});
});
});
+
+it.each(['abc', '1.5', 'x'.repeat(300)])(
+ 'preserves invalid custom time %s without NaN',
+ (raw) => {
+ const state = readExploreUrlState(
+ new URLSearchParams({ time: 'custom', maxTime: raw }),
+ );
+ expect(state.browseState.customMaxMinutes).toBeNull();
+ expect(state.browseState.customMaxMinutesRaw).toBe(raw);
+ expect(createExploreSearchParams(state).get('maxTime')).toBe(raw);
+ },
+);
+
+it.each([
+ ['20161', 20160],
+ ['-1', 1],
+ ['0', 1],
+])('clamps bookmarked time %s to %s', (raw, expected) => {
+ const state = readExploreUrlState(
+ new URLSearchParams({ time: 'custom', maxTime: raw }),
+ );
+ expect(state.browseState.customMaxMinutes).toBe(expected);
+ expect(state.browseState.customMaxMinutesRaw).toBe(raw);
+});
diff --git a/apps/web/src/features/explore/exploreUrlState.ts b/apps/web/src/features/explore/exploreUrlState.ts
index c76d85a..432b27e 100644
--- a/apps/web/src/features/explore/exploreUrlState.ts
+++ b/apps/web/src/features/explore/exploreUrlState.ts
@@ -1,3 +1,4 @@
+import { readCustomTime } from '../../lib/recipeBrowse/browseValidation';
import {
DEFAULT_EXPLORE_BROWSE_STATE,
isExploreCategory,
@@ -41,10 +42,10 @@ export function readExploreUrlState(
? sortParam
: DEFAULT_EXPLORE_BROWSE_STATE.sort;
- const customMaxMinutes =
+ const customTime =
cookingTime === 'custom'
- ? parsePositiveInteger(searchParams.get('maxTime'))
- : null;
+ ? readCustomTime(searchParams.get('maxTime'))
+ : { customMaxMinutes: null };
return {
search: (searchParams.get('q') ?? '').trim(),
@@ -52,7 +53,7 @@ export function readExploreUrlState(
browseState: {
category,
cookingTime,
- customMaxMinutes,
+ ...customTime,
sort,
},
@@ -82,9 +83,13 @@ export function createExploreSearchParams({
if (
browseState.cookingTime === 'custom' &&
- browseState.customMaxMinutes !== null
+ (browseState.customMaxMinutesRaw !== undefined ||
+ browseState.customMaxMinutes !== null)
) {
- searchParams.set('maxTime', String(browseState.customMaxMinutes));
+ searchParams.set(
+ 'maxTime',
+ browseState.customMaxMinutesRaw ?? String(browseState.customMaxMinutes),
+ );
}
}
diff --git a/apps/web/src/features/not-found/NotFoundPage.tsx b/apps/web/src/features/not-found/NotFoundPage.tsx
index ce4c6d9..c0e0679 100644
--- a/apps/web/src/features/not-found/NotFoundPage.tsx
+++ b/apps/web/src/features/not-found/NotFoundPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import { useNavigate } from 'react-router-dom';
import Button from '../../components/ui/Button/Button';
@@ -7,6 +8,7 @@ import chefHatIllustration from '../../assets/illustrations/not-found-chef-hat.w
import './NotFoundPage.css';
function NotFoundPage() {
+ usePageTitle('Page not found');
const navigate = useNavigate();
function handleGoBack() {
diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.css b/apps/web/src/features/recipe-detail/RecipeDetailPage.css
index 059b14d..04b5ab5 100644
--- a/apps/web/src/features/recipe-detail/RecipeDetailPage.css
+++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.css
@@ -230,6 +230,9 @@
display: flex;
align-items: center;
justify-content: space-between;
+
+ /* "Jump to recipe" scrolls here; keep it clear of the sticky header. */
+ scroll-margin-top: var(--space-16);
gap: var(--space-4);
padding: var(--space-4);
@@ -259,7 +262,9 @@
.recipe-detail-page__servings-control p {
margin-block-start: var(--space-1);
- color: var(--color-text-muted);
+ /* Secondary, not muted: muted text is only 4.4:1 on the desktop panel's
+ --color-surface-muted background; secondary keeps it at 4.8:1. */
+ color: var(--color-text-secondary);
font-size: var(--font-size-xs);
}
@@ -284,11 +289,34 @@
line-height: var(--line-height-tight);
}
- .recipe-detail-page__servings-value strong {
+ .recipe-detail-page__servings-input {
+ width: 4.5ch;
+ padding: 0;
+
+ border: var(--border-width-thin) solid transparent;
+ border-radius: var(--radius-sm);
+
color: var(--color-text-primary);
+ background: transparent;
+ font: inherit;
font-size: var(--font-size-2xl);
+ font-weight: var(--font-weight-semibold);
line-height: var(--line-height-tight);
+ text-align: center;
+
+ /* Hide the browser's own spinner; the −/+ buttons do that job. */
+ appearance: textfield;
+ }
+
+ .recipe-detail-page__servings-input::-webkit-inner-spin-button,
+ .recipe-detail-page__servings-input::-webkit-outer-spin-button {
+ margin: 0;
+ appearance: none;
+ }
+
+ .recipe-detail-page__servings-input:hover {
+ border-color: var(--color-border-input);
}
.recipe-detail-page__content-card {
diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx
index f90b9fa..ea1bbd8 100644
--- a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx
+++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx
@@ -1,7 +1,8 @@
+import '@testing-library/jest-dom/vitest';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest';
import {
apiRecipe,
apiUser,
@@ -33,18 +34,18 @@ it('loads details and scales ingredient quantities without changing the server',
mount();
expect(await screen.findByRole('heading', { name: 'API soup' })).toBeTruthy();
expect(screen.getByText('Boil the water.')).toBeTruthy();
- expect(screen.getByText('1 l')).toBeTruthy();
+ expect(screen.getByText('1 L')).toBeTruthy();
await userEvent
.setup()
.click(screen.getAllByRole('button', { name: 'Increase servings' })[0]!);
- expect(screen.getByText('1.5 l')).toBeTruthy();
+ expect(screen.getByText('1.5 L')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Rate Recipe' })).toBeTruthy();
});
it('treats inaccessible private recipes as unavailable', async () => {
mockRecipeFetch(() => ({ data: { recipe: null } }));
mount();
expect(
- await screen.findByRole('heading', { name: 'Recipe not found' }),
+ await screen.findByRole('heading', { name: 'Recipe not found', level: 1 }),
).toBeTruthy();
});
it('offers owner editing and deletes only after confirmation', async () => {
@@ -139,3 +140,87 @@ it('keeps a failed rating editable and refreshes the persisted rating after retr
await screen.findByRole('button', { name: 'Rate Recipe' }),
).toBeTruthy();
});
+function mockJumpScrolling() {
+ // jsdom has no scrollIntoView; provide one for this test only.
+ const originalScroll = Element.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ onTestFinished(() => {
+ Element.prototype.scrollIntoView = originalScroll;
+ });
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ matches: query === '(prefers-reduced-motion: reduce)',
+ })),
+ );
+ return scrollIntoView;
+}
+it('jumps to the visible servings control, and Tab continues to its buttons', async () => {
+ const scrollIntoView = mockJumpScrolling();
+ mockRecipeFetch(() => ({ data: { recipe: apiRecipe } }));
+ mount();
+ await screen.findByRole('heading', { name: 'API soup' });
+ // jsdom applies no CSS; mark the desktop copy as the rendered one.
+ const [mobile, desktop] = screen.getAllByRole('region', {
+ name: 'Adjust Servings',
+ });
+ vi.spyOn(desktop!, 'getClientRects').mockReturnValue([
+ new DOMRect(0, 0, 100, 100),
+ ] as unknown as DOMRectList);
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Jump to recipe' }));
+ expect(scrollIntoView).toHaveBeenCalledWith({
+ behavior: 'auto',
+ block: 'start',
+ });
+ expect(scrollIntoView.mock.contexts[0]).toBe(desktop);
+ expect(document.activeElement).toBe(
+ within(desktop!).getByRole('heading', { name: 'Adjust Servings' }),
+ );
+ expect(mobile!.contains(document.activeElement)).toBe(false);
+ // Tab stays in the recipe: next come the servings buttons.
+ await user.tab();
+ expect(document.activeElement).toBe(
+ within(desktop!).getByRole('button', { name: 'Decrease servings' }),
+ );
+});
+it('falls back to the ingredients heading when no servings control is rendered', async () => {
+ mockJumpScrolling();
+ mockRecipeFetch(() => ({ data: { recipe: apiRecipe } }));
+ mount();
+ await screen.findByRole('heading', { name: 'API soup' });
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Jump to recipe' }));
+ expect(document.activeElement).toBe(
+ screen.getByRole('heading', { name: 'Ingredients' }),
+ );
+});
+it('scales beyond 20 servings and accepts a typed number within the API limits', async () => {
+ mockRecipeFetch(() => ({ data: { recipe: { ...apiRecipe, servings: 40 } } }));
+ mount();
+ await screen.findByRole('heading', { name: 'API soup' });
+ const user = userEvent.setup();
+ const [servings] = screen.getAllByLabelText('Servings (1–1000)');
+ expect(servings).toHaveValue(40);
+ await user.click(
+ screen.getAllByRole('button', { name: 'Increase servings' })[0]!,
+ );
+ expect(servings).toHaveValue(41);
+ await user.clear(servings!);
+ await user.type(servings!, '250');
+ expect(servings).toHaveValue(250);
+ // Out-of-range input is clamped when the field is left.
+ await user.clear(servings!);
+ await user.type(servings!, '5000');
+ await user.tab();
+ expect(servings).toHaveValue(1000);
+ expect(
+ screen.getAllByRole('button', { name: 'Increase servings' })[0],
+ ).toBeDisabled();
+ // Clearing the field and leaving restores the last valid value.
+ await user.clear(servings!);
+ await user.tab();
+ expect(servings).toHaveValue(1000);
+});
diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
index 384750d..18abb23 100644
--- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
+++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
@@ -7,22 +8,16 @@ import RecipeMeta from '../../components/recipe/RecipeMeta/RecipeMeta';
import RecipeRating from '../../components/recipe/RecipeRating/RecipeRating';
import RecipeRatingInput from '../../components/recipe/RecipeRatingInput/RecipeRatingInput';
import Dialog from '../../components/ui/Dialog/Dialog';
-import { recipeImageUrl } from '../../lib/recipeImageUrl';
+import { recipeImageSrcSet, recipeImageUrl } from '../../lib/recipeImageUrl';
import Avatar from '../../components/ui/Avatar/Avatar';
import Button from '../../components/ui/Button/Button';
import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog';
import EmptyState from '../../components/ui/EmptyState/EmptyState';
import { Icon } from '../../components/ui/Icon/Icon';
-import IconButton from '../../components/ui/IconButton/IconButton';
import LinkButton from '../../components/ui/LinkButton/LinkButton';
import Tag from '../../components/ui/Tag/Tag';
import Toast, { type ToastTone } from '../../components/ui/Toast/Toast';
-import {
- BookmarkIcon,
- EditIcon,
- MinusIcon,
- PlusIcon,
-} from '../../icons/actions';
+import { BookmarkIcon, EditIcon } from '../../icons/actions';
import { BackIcon } from '../../icons/navigation';
import { EmptyStateIcon, PrivateIcon } from '../../icons/recipe';
import { useAppStore } from '../../store';
@@ -37,16 +32,13 @@ import {
} from '../recipes/recipeApi';
import { useRecipeQuery } from '../recipes/useRecipeQuery';
import RecipeQueryStatus from '../recipes/RecipeQueryStatus';
+import { unitLabel } from '../../lib/ingredientUnits';
+import { formatAmount, scaleAmount } from '../../lib/recipeScaling';
+import ServingsStepper from './ServingsStepper';
import './RecipeDetailPage.css';
-const MIN_SERVINGS = 1;
-const MAX_SERVINGS = 20;
const MAX_VISIBLE_TAGS = 5;
-interface RecipeDetailLocationState {
- from?: string;
-}
-
interface RecipeDetailContentProps {
recipe: Recipe;
}
@@ -64,34 +56,27 @@ function formatTagLabel(tag: string) {
.join(' ');
}
+// Scaling and rounding rules live in lib/recipeScaling.ts (unit-tested).
function formatScaledAmount(
amount: number,
selectedServings: number,
originalServings: number,
) {
- const scaledAmount = amount * (selectedServings / originalServings);
-
- if (scaledAmount >= 200) {
- return String(Math.round(scaledAmount / 5) * 5);
- }
-
- if (scaledAmount >= 50) {
- return String(Math.round(scaledAmount));
- }
-
- if (scaledAmount >= 3) {
- return String(Math.round(scaledAmount * 10) / 10);
- }
-
- return String(Math.round(scaledAmount * 100) / 100);
+ return formatAmount(scaleAmount(amount, selectedServings, originalServings));
}
function getSourcePath(locationState: unknown) {
- const state = locationState as RecipeDetailLocationState | null;
-
- return typeof state?.from === 'string' && state.from.startsWith('/')
- ? state.from
- : undefined;
+ if (
+ !locationState ||
+ typeof locationState !== 'object' ||
+ !('from' in locationState)
+ )
+ return;
+ const { from } = locationState;
+ if (typeof from !== 'string') return;
+ const path = from.split(/[?#]/, 1)[0];
+ if (path === '/' || path === '/cookbook' || path === '/cookbook/')
+ return from;
}
function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
@@ -110,6 +95,8 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
const [busy, setBusy] = useState(false);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
const [selectedServings, setSelectedServings] = useState(recipe.servings);
+ const mobileServingsRef = useRef
(null);
+ const desktopServingsRef = useRef(null);
const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false);
const [feedback, setFeedback] = useState(null);
const [showAllTags, setShowAllTags] = useState(false);
@@ -143,36 +130,40 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
const hasOversizedSummary = Boolean(titleSizeClass) || hasHiddenTags;
- const sourcePath = getSourcePath(location.state);
- const fallbackPath = isOwner || isPrivate ? '/cookbook' : '/';
-
- const backLabel = sourcePath
- ? sourcePath.startsWith('/cookbook')
- ? 'Back to My Cookbook'
- : 'Back to Explore'
- : isOwner || isPrivate
- ? 'Back to My Cookbook'
- : 'Back to Explore';
-
- function handleBack() {
- if (sourcePath) {
- navigate(sourcePath, { replace: true });
- return;
- }
-
- if (location.key !== 'default' && window.history.length > 1) {
- navigate(-1);
- return;
- }
-
- navigate(fallbackPath);
- }
-
+ const backPath =
+ getSourcePath(location.state) ?? (isOwner || isPrivate ? '/cookbook' : '/');
+ const backLabel = backPath.startsWith('/cookbook')
+ ? 'Back to My Cookbook'
+ : 'Back to Explore';
+
+ /*
+ * The recipe starts at "Adjust Servings": it is directly above the
+ * ingredients and is the one control that acts on them. Jumping scrolls
+ * there and moves keyboard focus to its heading, so screen readers
+ * announce where the user landed and Tab continues to the servings
+ * buttons instead of leaving the recipe (the ingredient and step lists
+ * are text, read rather than tabbed through). The control exists twice,
+ * one copy per layout, and CSS hides the other; focusing a hidden element
+ * does nothing, so the rendered copy is picked. Smooth scrolling is
+ * skipped when the user prefers less motion.
+ */
function handleJumpToRecipe() {
- document.getElementById('recipe-detail-recipe')?.scrollIntoView({
- behavior: 'smooth',
+ const reduceMotion = window.matchMedia?.(
+ '(prefers-reduced-motion: reduce)',
+ ).matches;
+ const servings = [
+ mobileServingsRef.current,
+ desktopServingsRef.current,
+ ].find((section) => section && section.getClientRects().length > 0);
+ const target = servings ?? document.getElementById('recipe-detail-recipe');
+ target?.scrollIntoView({
+ behavior: reduceMotion ? 'auto' : 'smooth',
block: 'start',
});
+ (
+ servings?.querySelector('h2') ??
+ document.getElementById('recipe-detail-ingredients-title')
+ )?.focus({ preventScroll: true });
}
function openRating() {
@@ -240,15 +231,16 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
aria-labelledby="recipe-detail-title"
>
-
{backLabel}
-
+
@@ -390,6 +388,7 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
@@ -441,49 +440,23 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
-
Adjust Servings
+
+ Adjust Servings
+
Ingredient amounts update automatically.
-
-
- setSelectedServings((current) =>
- Math.max(MIN_SERVINGS, current - 1),
- )
- }
- />
-
-
- {selectedServings}
-
- {selectedServings === 1 ? 'serving' : 'servings'}
-
-
- = MAX_SERVINGS}
- onClick={() =>
- setSelectedServings((current) =>
- Math.min(MAX_SERVINGS, current + 1),
- )
- }
- />
-
+
@@ -498,49 +471,23 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
-
Adjust Servings
+
+ Adjust Servings
+
Ingredient amounts update automatically.
-
-
- setSelectedServings((current) =>
- Math.max(MIN_SERVINGS, current - 1),
- )
- }
- />
-
-
- {selectedServings}
-
- {selectedServings === 1 ? 'serving' : 'servings'}
-
-
- = MAX_SERVINGS}
- onClick={() =>
- setSelectedServings((current) =>
- Math.min(MAX_SERVINGS, current + 1),
- )
- }
- />
-
+
-
Ingredients
+
+ Ingredients
+
{selectedServings}{' '}
@@ -569,7 +518,7 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
);
const amountWithUnit =
- `${scaledAmount} ${ingredient.unit}`.trim();
+ `${scaledAmount} ${unitLabel(ingredient.unit)}`.trim();
return (
@@ -705,12 +654,18 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
function RecipeDetailPage() {
const { id } = useParams();
+ const location = useLocation();
+ const currentUser = useAppStore((state) => state.currentUser);
const load = useCallback(
(signal: AbortSignal) => getRecipe(id ?? '', signal),
[id],
);
const query = useRecipeQuery(id ?? '', load);
+ usePageTitle(
+ query.data?.title ??
+ (query.loading || query.error ? 'Recipe' : 'Recipe not found'),
+ );
if (query.loading || query.error)
return ;
const recipe = query.data;
@@ -720,9 +675,33 @@ function RecipeDetailPage() {
Back to Explore}
+ description={
+ currentUser
+ ? 'This recipe does not exist or is not available to you.'
+ : 'This recipe does not exist or is not available to you. If it is private, log in to the account that owns it.'
+ }
+ action={
+ <>
+ {!currentUser && (
+
+ Log in
+
+ )}
+
+ Back to Explore
+
+ >
+ }
/>
);
diff --git a/apps/web/src/features/recipe-detail/ServingsStepper.tsx b/apps/web/src/features/recipe-detail/ServingsStepper.tsx
new file mode 100644
index 0000000..cf8bb8f
--- /dev/null
+++ b/apps/web/src/features/recipe-detail/ServingsStepper.tsx
@@ -0,0 +1,95 @@
+import { useState } from 'react';
+import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe';
+
+import IconButton from '../../components/ui/IconButton/IconButton';
+import { MinusIcon, PlusIcon } from '../../icons/actions';
+
+type ServingsStepperProps = {
+ /** Unique per instance; the page renders one for mobile and one for desktop. */
+ id: string;
+ value: number;
+ onChange: (servings: number) => void;
+};
+
+const clamp = (servings: number) =>
+ Math.min(MAX_SERVINGS, Math.max(MIN_SERVINGS, servings));
+
+/**
+ * −/+ buttons around a number field. Typing a whole number within the limits
+ * updates the recipe right away; anything else is corrected when the field
+ * loses focus (clamped to the limits, or restored if not a number).
+ */
+export default function ServingsStepper({
+ id,
+ value,
+ onChange,
+}: ServingsStepperProps) {
+ // The text being typed may be briefly invalid (e.g. empty while retyping).
+ const [draft, setDraft] = useState(null);
+ const inputId = `${id}-servings-input`;
+
+ function commit(text: string) {
+ const typed = Number(text);
+ if (text.trim() === '' || !Number.isFinite(typed)) return;
+ onChange(clamp(Math.round(typed)));
+ }
+
+ return (
+
+ );
+}
diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css
index 416ee0e..bd90bca 100644
--- a/apps/web/src/features/recipes/RecipeCreatePage.css
+++ b/apps/web/src/features/recipes/RecipeCreatePage.css
@@ -1,4 +1,17 @@
@layer components {
+ .recipe-create-page__toast-region {
+ position: fixed;
+ right: var(--space-6);
+ bottom: var(--space-6);
+ z-index: var(--z-overlay);
+ width: min(24rem, calc(100% - (2 * var(--space-6))));
+ }
+
+ .recipe-create-page__form
+ :is(.field, .textarea, .select, .radio-group, [data-form-error]) {
+ scroll-margin-top: calc(var(--site-header-height) + var(--space-4));
+ }
+
.recipe-create-page {
padding-block: var(--space-10) var(--space-16);
}
@@ -336,11 +349,27 @@
background: var(--color-surface-selected);
}
+ .recipe-create-page__draft-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin-top: var(--space-2);
+ }
+
+ /* Shown next to a disabled Add button once a list is full. */
+ .recipe-create-page__limit {
+ margin: 0;
+ color: var(--color-text-secondary);
+ font-size: var(--font-size-sm);
+ }
+
+ /* Move up / move down / remove buttons at the end of each row. */
.recipe-create-page__delete-control {
display: flex;
align-items: center;
justify-content: center;
- width: var(--target-size-min);
+ gap: var(--space-1);
+ min-width: var(--target-size-min);
height: var(--target-size-min);
}
@@ -381,6 +410,17 @@
padding-block: var(--space-8) var(--space-12);
}
+ /* Move/remove buttons get their own line under the fields, so the
+ fields keep their full width on phones. */
+ .recipe-create-page__repeatable-row {
+ grid-template-columns: auto minmax(0, 1fr);
+ }
+
+ .recipe-create-page__repeatable-row > .recipe-create-page__delete-control {
+ grid-column: 2;
+ justify-self: end;
+ }
+
.recipe-create-page__content {
margin-top: var(--space-6);
}
diff --git a/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx
new file mode 100644
index 0000000..125df6d
--- /dev/null
+++ b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx
@@ -0,0 +1,185 @@
+import '@testing-library/jest-dom/vitest';
+import { act, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useAppStore } from '../../store';
+import {
+ apiRecipe,
+ apiUser,
+ mockRecipeFetch,
+} from '../../test/recipeApiFixtures';
+import RecipeCreatePage from './RecipeCreatePage';
+
+/*
+ * The real limits are 100 ingredients and 100 steps (shared with the API in
+ * @t31/validation/recipe). Rendering 100 rows takes seconds in jsdom, so
+ * this file lowers them to 3; the behaviour at the limit is the same.
+ */
+vi.mock('@t31/validation/recipe', async (importOriginal) => ({
+ ...(await importOriginal()),
+ MAX_INGREDIENTS: 3,
+ MAX_INSTRUCTIONS: 3,
+}));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ localStorage.clear();
+});
+beforeEach(() =>
+ useAppStore.setState({
+ currentUser: apiUser,
+ sessionStatus: 'authenticated',
+ }),
+);
+
+const rows = (count: number) => ({
+ ingredients: Array.from({ length: count }, (_, i) => ({
+ id: `ingredient-${i}`,
+ name: `Spice ${i + 1}`,
+ amount: 1,
+ unit: 'g',
+ note: null,
+ })),
+ instructions: Array.from({ length: count }, (_, i) => ({
+ step: i + 1,
+ text: `Step ${i + 1}`,
+ })),
+});
+function edit(recipe: object) {
+ const fetch = mockRecipeFetch(() => ({
+ data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true, ...recipe } },
+ }));
+ render(
+
+
+ } />
+ } />
+
+ ,
+ );
+ return fetch;
+}
+
+it('stops adding rows at the limit and says why', async () => {
+ edit(rows(3));
+ const addIngredient = await screen.findByRole('button', {
+ name: 'Add ingredient',
+ });
+ expect(addIngredient).toBeDisabled();
+ expect(addIngredient).toHaveAccessibleDescription(
+ 'A recipe can have at most 3 ingredients.',
+ );
+ const addStep = screen.getByRole('button', { name: 'Add step' });
+ expect(addStep).toBeDisabled();
+ expect(addStep).toHaveAccessibleDescription(
+ 'A recipe can have at most 3 steps.',
+ );
+ // Removing a row allows adding again.
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Remove ingredient 3' }),
+ );
+ expect(addIngredient).toBeEnabled();
+});
+
+it('flags a recipe with more rows than allowed and focuses the message', async () => {
+ const fetch = edit(rows(4));
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Save changes' }),
+ );
+ await act(() => new Promise((resolve) => setTimeout(resolve)));
+ const message = screen.getByText(
+ 'A recipe can have at most 3 ingredients. Remove 1 to save.',
+ );
+ expect(message.closest('[data-form-error]')).toHaveFocus();
+ expect(
+ screen.getByText('A recipe can have at most 3 steps. Remove 1 to save.'),
+ ).toBeInTheDocument();
+ expect(fetch).toHaveBeenCalledTimes(1); // only the initial load
+});
+
+it('keeps the row-limit error, with the remaining count, until the list fits', async () => {
+ edit(rows(5));
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Save changes' }),
+ );
+ await act(() => new Promise((resolve) => setTimeout(resolve)));
+ expect(
+ screen.getByText(
+ 'A recipe can have at most 3 ingredients. Remove 2 to save.',
+ ),
+ ).toBeInTheDocument();
+
+ // One removed, still over the limit: the message stays and recounts.
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Remove ingredient 5' }),
+ );
+ expect(
+ screen.getByText(
+ 'A recipe can have at most 3 ingredients. Remove 1 to save.',
+ ),
+ ).toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Remove ingredient 4' }),
+ );
+ expect(screen.queryByText(/at most 3 ingredients\. Remove/)).toBeNull();
+
+ // Steps behave the same, independently of the ingredients.
+ expect(
+ screen.getByText('A recipe can have at most 3 steps. Remove 2 to save.'),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: 'Remove step 5' }));
+ expect(
+ screen.getByText('A recipe can have at most 3 steps. Remove 1 to save.'),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: 'Remove step 4' }));
+ expect(screen.queryByText(/at most 3 steps\. Remove/)).toBeNull();
+});
+
+it('shows the row-limit errors as soon as an over-limit draft is restored', async () => {
+ localStorage.setItem(
+ `recipe-platform:draft:${apiUser.id}:new`,
+ JSON.stringify({
+ version: 1,
+ savedAt: '2026-10-01T10:00:00Z',
+ baseUpdatedAt: null,
+ fields: {
+ title: 'Big soup',
+ description: '',
+ category: 'soup',
+ difficulty: 'easy',
+ visibility: 'public',
+ prepTime: '1',
+ cookingTime: '1',
+ servings: '1',
+ tags: '',
+ imageUrl: null,
+ ingredients: rows(5).ingredients.map(({ name }) => ({
+ name,
+ amount: '1',
+ unit: 'g',
+ })),
+ instructions: rows(4).instructions.map(({ text }) => text),
+ },
+ }),
+ );
+ render(
+
+
+ } />
+
+ ,
+ );
+ await userEvent.click(
+ await screen.findByRole('button', { name: 'Restore draft' }),
+ );
+ // No submit needed.
+ expect(
+ screen.getByText(
+ 'A recipe can have at most 3 ingredients. Remove 2 to save.',
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText('A recipe can have at most 3 steps. Remove 1 to save.'),
+ ).toBeInTheDocument();
+});
diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx
index b05c11c..8786973 100644
--- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx
+++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx
@@ -1,5 +1,11 @@
import '@testing-library/jest-dom/vitest';
-import { fireEvent, render, screen } from '@testing-library/react';
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useAppStore } from '../../store';
@@ -8,7 +14,16 @@ import { useRecipeChanges } from './recipeApi';
import { act } from '@testing-library/react';
import RecipeCreatePage from './RecipeCreatePage';
-import { MemoryRouter, Routes, Route } from 'react-router-dom';
+import RecipeDetailPage from '../recipe-detail/RecipeDetailPage';
+import {
+ createMemoryRouter,
+ Link,
+ MemoryRouter,
+ Routes,
+ Route,
+ RouterProvider,
+} from 'react-router-dom';
+import { loadDraft, saveDraft } from '../../lib/recipeDrafts';
import { apiRecipe, mockRecipeFetch } from '../../test/recipeApiFixtures';
function mount(entry = '/recipes/new') {
@@ -43,7 +58,11 @@ describe('RecipeCreatePage', () => {
expect(screen.getByLabelText(/Recipe title/)).toBeInTheDocument();
expect(screen.getByLabelText(/Short description/)).toBeInTheDocument();
expect(screen.getByLabelText(/Cooking time/)).toBeInTheDocument();
- expect(screen.getByLabelText(/Servings/)).toBeInTheDocument();
+ expect(screen.getByLabelText(/Servings/)).toHaveAttribute(
+ 'placeholder',
+ 'e.g. 4',
+ );
+ expect(screen.getByLabelText(/Servings/)).toHaveValue(null);
expect(screen.getByLabelText(/Category/)).toBeInTheDocument();
expect(screen.getByLabelText(/Tags/)).toBeInTheDocument();
expect(
@@ -105,7 +124,8 @@ describe('RecipeCreatePage', () => {
expect(screen.queryByLabelText('Step 2')).not.toBeInTheDocument();
});
- it('supports structured ingredients and button-based reordering', async () => {
+ // Many real keystrokes and drags: close to the 5 s default on the CI runner.
+ it('supports structured ingredients and reordering by dragging the handle', async () => {
const user = userEvent.setup();
mount();
@@ -159,7 +179,7 @@ describe('RecipeCreatePage', () => {
expect(screen.getByLabelText('Step 1')).toHaveValue('Bake');
expect(screen.getByLabelText('Step 2')).toHaveValue('Mix');
- });
+ }, 15_000);
it('reorders ingredients and instructions by drag and drop', async () => {
const user = userEvent.setup();
@@ -230,18 +250,34 @@ async function fillRecipe() {
await user.type(screen.getByLabelText('Step 1'), 'Mix.');
return user;
}
+// Full form interactions can exceed 5 s on the shared CI runner.
it('creates a recipe with explicit times and difficulty, then opens its detail route', async () => {
let input: unknown;
- mockRecipeFetch((_operation, variables) => {
- input = variables.input;
- return { data: { createRecipe: apiRecipe } };
+ const recipe = { ...apiRecipe, isCreatedByCurrentUser: true };
+ mockRecipeFetch((operation, variables) => {
+ if (operation === 'CreateRecipe') {
+ input = variables.input;
+ return { data: { createRecipe: recipe } };
+ }
+ return { data: { recipe } };
});
- mount();
+ render(
+
+
+ } />
+ } />
+ Cookbook destination} />
+
+ ,
+ );
const user = await fillRecipe();
await user.click(screen.getByRole('button', { name: 'Publish recipe' }));
+ await user.click(
+ await screen.findByRole('link', { name: 'Back to My Cookbook' }),
+ );
expect(
- await screen.findByRole('heading', { name: 'Saved recipe destination' }),
- ).toBeInTheDocument();
+ await screen.findByRole('heading', { name: 'Cookbook destination' }),
+ ).toBeVisible();
expect(input).toMatchObject({
prepMinutes: 5,
cookMinutes: 0,
@@ -249,7 +285,35 @@ it('creates a recipe with explicit times and difficulty, then opens its detail r
imageUrl: null,
category: 'soup',
});
+}, 15_000);
+it.each([
+ ['/cookbook?view=created&category=soup&page=2', 'Back to My Cookbook'],
+ ['/?q=soup#results', 'Back to Explore'],
+])('returns to %s after editing a recipe', async (from, label) => {
+ const recipe = { ...apiRecipe, isCreatedByCurrentUser: true };
+ mockRecipeFetch((operation) => ({
+ data: operation === 'UpdateRecipe' ? { updateRecipe: recipe } : { recipe },
+ }));
+ const router = createMemoryRouter(
+ [
+ { path: '/recipes/:id', element: },
+ { path: '/recipes/:id/edit', element: },
+ { path: '*', element: Recipe list },
+ ],
+ {
+ initialEntries: [{ pathname: '/recipes/' + recipe.id, state: { from } }],
+ },
+ );
+ render( );
+ const user = userEvent.setup();
+ await user.click(await screen.findByRole('link', { name: 'Edit Recipe' }));
+ await user.click(await screen.findByRole('button', { name: 'Save changes' }));
+ await user.click(await screen.findByRole('link', { name: label }));
+ await screen.findByRole('heading', { name: 'Recipe list' });
+ const { pathname, search, hash } = router.state.location;
+ expect(pathname + search + hash).toBe(from);
});
+
it('preserves input after a failed save and allows retry', async () => {
let fail = true;
mockRecipeFetch(() =>
@@ -346,3 +410,743 @@ it('does not fetch or reset the new recipe form after list invalidation', () =>
expect(title).toHaveValue('New draft');
expect(fetch).not.toHaveBeenCalled();
});
+it('opens recipes with legacy Norwegian units as English and saves English', async () => {
+ let input: unknown;
+ mockRecipeFetch((operation, variables) => {
+ const recipe = {
+ ...apiRecipe,
+ isCreatedByCurrentUser: true,
+ ingredients: [{ ...apiRecipe.ingredients[0], unit: 'ss' }],
+ };
+ if (operation === 'UpdateRecipe') {
+ input = variables.input;
+ return { data: { updateRecipe: recipe } };
+ }
+ return { data: { recipe } };
+ });
+ mount('/recipes/' + apiRecipe.id + '/edit');
+ await screen.findByRole('heading', { name: 'Edit Recipe' });
+ expect(screen.getByLabelText('Ingredient 1 unit')).toHaveValue('tbsp');
+ expect(screen.queryByRole('option', { name: 'ss' })).toBeNull();
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Save changes' }));
+ await screen.findByRole('heading', { name: 'Saved recipe destination' });
+ expect(input).toMatchObject({
+ ingredients: [expect.objectContaining({ unit: 'tbsp' })],
+ });
+});
+// Keep the complete keyboard/focus scenario within one test, with CI headroom.
+it('reorders ingredients and steps with the keyboard, keeping focus and announcing the position', async () => {
+ const user = userEvent.setup();
+ mount();
+ // Fill fields directly so setup does not spend time on individual keystrokes;
+ // the keyboard interactions below exercise moving rows and retaining focus.
+ const fill = (label: string, value: string) =>
+ fireEvent.change(screen.getByLabelText(label), { target: { value } });
+ fill('Ingredient 1', 'Flour');
+ await user.click(screen.getByRole('button', { name: 'Add ingredient' }));
+ fill('Ingredient 2', 'Sugar');
+ await user.click(screen.getByRole('button', { name: 'Add ingredient' }));
+ fill('Ingredient 3', 'Salt');
+
+ // The first row cannot move up; the last cannot move down.
+ expect(
+ screen.getByRole('button', { name: 'Move ingredient 1 up' }),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole('button', { name: 'Move ingredient 3 down' }),
+ ).toBeDisabled();
+
+ screen.getByRole('button', { name: 'Move ingredient 1 down' }).focus();
+ await user.keyboard('{Enter}');
+ expect(screen.getByLabelText('Ingredient 1')).toHaveValue('Sugar');
+ expect(screen.getByLabelText('Ingredient 2')).toHaveValue('Flour');
+ // Focus follows the moved row, so pressing again keeps moving Flour.
+ expect(
+ screen.getByRole('button', { name: 'Move ingredient 2 down' }),
+ ).toHaveFocus();
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Ingredient moved to position 2 of 3.',
+ );
+ await user.keyboard('{Enter}');
+ expect(screen.getByLabelText('Ingredient 3')).toHaveValue('Flour');
+ // At the last place the down button is disabled, so focus moves to up.
+ expect(
+ screen.getByRole('button', { name: 'Move ingredient 3 up' }),
+ ).toHaveFocus();
+
+ fill('Step 1', 'Mix');
+ await user.click(screen.getByRole('button', { name: 'Add step' }));
+ fill('Step 2', 'Bake');
+ await user.click(screen.getByRole('button', { name: 'Move step 2 up' }));
+ expect(screen.getByLabelText('Step 1')).toHaveValue('Bake');
+ expect(screen.getByLabelText('Step 2')).toHaveValue('Mix');
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Step moved to position 1 of 2.',
+ );
+}, 15_000);
+describe('recipe drafts', () => {
+ beforeEach(() => localStorage.clear());
+
+ it('saves a draft that survives a reload and can be restored or discarded', async () => {
+ const user = userEvent.setup();
+ const first = mount();
+ fireEvent.change(screen.getByLabelText(/Recipe title/i), {
+ target: { value: 'Draft soup' },
+ });
+ fireEvent.change(screen.getByLabelText('Step 1'), {
+ target: { value: 'Simmer' },
+ });
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ expect(screen.getByText('Draft saved')).toBeInTheDocument();
+ first.unmount();
+
+ // A fresh form (as after navigation or reload) offers the draft.
+ const second = mount();
+ expect(screen.getByText('Saved draft found')).toBeInTheDocument();
+ expect(screen.getByLabelText(/Recipe title/i)).toHaveValue('');
+ await user.click(screen.getByRole('button', { name: 'Restore draft' }));
+ expect(screen.getByLabelText(/Recipe title/i)).toHaveValue('Draft soup');
+ expect(screen.getByLabelText('Step 1')).toHaveValue('Simmer');
+ second.unmount();
+
+ mount();
+ await user.click(screen.getByRole('button', { name: 'Discard draft' }));
+ await user.click(
+ within(
+ screen.getByRole('dialog', { name: 'Discard saved draft?' }),
+ ).getByRole('button', { name: 'Discard draft' }),
+ );
+ expect(screen.queryByText('Saved draft found')).not.toBeInTheDocument();
+ expect(localStorage.length).toBe(0);
+ });
+
+ it('marks a draft of an existing recipe as outdated after the recipe changed', async () => {
+ localStorage.setItem(
+ `recipe-platform:draft:${apiUser.id}:${apiRecipe.id}`,
+ JSON.stringify({
+ version: 1,
+ savedAt: '2026-10-01T10:00:00Z',
+ baseUpdatedAt: '2026-01-01T00:00:00Z',
+ fields: {
+ title: 'Old title',
+ description: '',
+ category: 'soup',
+ difficulty: 'easy',
+ visibility: 'public',
+ prepTime: '1',
+ cookingTime: '1',
+ servings: '1',
+ tags: '',
+ imageUrl: null,
+ ingredients: [{ name: 'Water', amount: '1', unit: 'l' }],
+ instructions: ['Boil'],
+ },
+ }),
+ );
+ mockRecipeFetch(() => ({
+ data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } },
+ }));
+ mount('/recipes/' + apiRecipe.id + '/edit');
+ expect(await screen.findByText('Outdated draft found')).toBeInTheDocument();
+ });
+
+ it('clears the draft after the recipe is saved', async () => {
+ mockRecipeFetch((operation) =>
+ operation === 'UpdateRecipe'
+ ? { data: { updateRecipe: apiRecipe } }
+ : { data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } } },
+ );
+ const user = userEvent.setup();
+ mount('/recipes/' + apiRecipe.id + '/edit');
+ await screen.findByRole('heading', { name: 'Edit Recipe' });
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ expect(localStorage.length).toBe(1);
+ await user.click(screen.getByRole('button', { name: 'Save changes' }));
+ await screen.findByRole('heading', { name: 'Saved recipe destination' });
+ expect(localStorage.length).toBe(0);
+ });
+});
+
+describe('recipe draft edge cases', () => {
+ beforeEach(() => localStorage.clear());
+
+ const draftKey = (recipeId: string) =>
+ `recipe-platform:draft:${apiUser.id}:${recipeId}`;
+ const storedDraft = (fields: Record, savedAt: string) =>
+ JSON.stringify({
+ version: 1,
+ savedAt,
+ baseUpdatedAt: null,
+ fields: {
+ title: 'Draft soup',
+ description: '',
+ category: 'soup',
+ difficulty: 'easy',
+ visibility: 'public',
+ prepTime: '1',
+ cookingTime: '1',
+ servings: '1',
+ tags: '',
+ imageUrl: null,
+ ingredients: [{ name: 'Water', amount: '1', unit: 'l' }],
+ instructions: ['Boil'],
+ ...fields,
+ },
+ });
+
+ /** Replaces Image so the test decides when an image check finishes. */
+ function controlImageChecks() {
+ const checks: { onload?: () => void; onerror?: () => void }[] = [];
+ vi.stubGlobal(
+ 'Image',
+ class {
+ onload?: () => void;
+ onerror?: () => void;
+ src = '';
+ constructor() {
+ checks.push(this);
+ }
+ },
+ );
+ return checks;
+ }
+
+ it('blocks saving until the draft image is checked, then uses it', async () => {
+ const checks = controlImageChecks();
+ localStorage.setItem(
+ draftKey('new'),
+ storedDraft({ imageUrl: '/uploads/draft.webp' }, '2026-10-01T10:00:00Z'),
+ );
+ const user = userEvent.setup();
+ mount();
+ await user.click(screen.getByRole('button', { name: 'Restore draft' }));
+ expect(
+ screen.getByRole('button', { name: 'Publish recipe' }),
+ ).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Save draft' })).toBeDisabled();
+ expect(screen.getByText(/Checking its image/)).toBeInTheDocument();
+
+ act(() => checks[0]!.onload!());
+ expect(screen.getByAltText('Recipe preview')).toHaveAttribute(
+ 'src',
+ '/uploads/draft.webp',
+ );
+ expect(
+ screen.getByRole('button', { name: 'Publish recipe' }),
+ ).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'Save draft' })).toBeEnabled();
+ });
+
+ it('ignores a late image check after the user changed the image', async () => {
+ const checks = controlImageChecks();
+ localStorage.setItem(
+ draftKey(apiRecipe.id),
+ JSON.stringify({
+ ...JSON.parse(
+ storedDraft(
+ { imageUrl: '/uploads/draft.webp' },
+ '2026-10-01T10:00:00Z',
+ ),
+ ),
+ baseUpdatedAt: apiRecipe.updatedAt,
+ }),
+ );
+ mockRecipeFetch(() => ({
+ data: {
+ recipe: {
+ ...apiRecipe,
+ imageUrl: '/uploads/current.webp',
+ isCreatedByCurrentUser: true,
+ },
+ },
+ }));
+ const user = userEvent.setup();
+ mount('/recipes/' + apiRecipe.id + '/edit');
+ await user.click(
+ await screen.findByRole('button', { name: 'Restore draft' }),
+ );
+ // The user removes the image while the draft's image is still checked.
+ await user.click(screen.getByRole('button', { name: 'Remove image' }));
+ expect(screen.getByRole('button', { name: 'Save changes' })).toBeEnabled();
+ act(() => checks[0]!.onload!());
+ expect(screen.queryByAltText('Recipe preview')).not.toBeInTheDocument();
+ });
+
+ it('hides "Draft saved" after any later change, including tags and steps', async () => {
+ const user = userEvent.setup();
+ mount();
+ const saveDraft = () =>
+ user.click(screen.getByRole('button', { name: 'Save draft' }));
+
+ await saveDraft();
+ expect(screen.getByText('Draft saved')).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText(/Tags/i), {
+ target: { value: 'quick' },
+ });
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+
+ await saveDraft();
+ await user.click(screen.getByRole('button', { name: 'Add step' }));
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+
+ await saveDraft();
+ await user.click(screen.getByRole('button', { name: 'Remove step 2' }));
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+
+ // Back to exactly what was saved: the message is true again.
+ await saveDraft();
+ expect(screen.getByText('Draft saved')).toBeInTheDocument();
+ });
+
+ it('does not discard a newer draft saved in another tab', async () => {
+ localStorage.setItem(
+ draftKey('new'),
+ storedDraft({}, '2026-10-01T10:00:00Z'),
+ );
+ const user = userEvent.setup();
+ mount();
+ expect(screen.getByText('Saved draft found')).toBeInTheDocument();
+ // Another tab saves a newer draft while this one shows the older one.
+ const newer = storedDraft({ title: 'Newer' }, '2026-10-01T11:00:00Z');
+ localStorage.setItem(draftKey('new'), newer);
+ await user.click(screen.getByRole('button', { name: 'Discard draft' }));
+ await user.click(
+ within(
+ screen.getByRole('dialog', { name: 'Discard saved draft?' }),
+ ).getByRole('button', { name: 'Discard draft' }),
+ );
+ expect(localStorage.getItem(draftKey('new'))).toBe(newer);
+ expect(
+ screen.getByText(/A newer draft was saved in another tab/),
+ ).toBeInTheDocument();
+ });
+});
+
+describe('edit page titles', () => {
+ it('names the state in the tab title: editing, not editable, or unavailable', async () => {
+ mockRecipeFetch(() => ({
+ data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } },
+ }));
+ const owned = mount('/recipes/' + apiRecipe.id + '/edit');
+ await screen.findByRole('heading', { name: 'Edit Recipe' });
+ // The heading can render before usePageTitle's effect updates the tab.
+ await waitFor(() =>
+ expect(document.title).toBe(`Edit ${apiRecipe.title} – Recipe Platform`),
+ );
+ owned.unmount();
+
+ mockRecipeFetch(() => ({
+ data: { recipe: { ...apiRecipe, id: crypto.randomUUID() } },
+ }));
+ const other = mount('/recipes/' + crypto.randomUUID() + '/edit');
+ await screen.findByRole('heading', { name: 'Cannot edit recipe' });
+ await waitFor(() =>
+ expect(document.title).toBe('Cannot edit recipe – Recipe Platform'),
+ );
+ other.unmount();
+
+ mount('/recipes/abc/edit');
+ await screen.findByRole('heading', { name: 'Recipe unavailable' });
+ await waitFor(() =>
+ expect(document.title).toBe('Recipe unavailable – Recipe Platform'),
+ );
+ });
+});
+
+describe('protecting edits', () => {
+ beforeEach(() => localStorage.clear());
+
+ it('sends the version it loaded and keeps the form when the recipe changed meanwhile', async () => {
+ let sent: Record = {};
+ mockRecipeFetch((operation, variables) => {
+ if (operation !== 'UpdateRecipe')
+ return {
+ data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } },
+ };
+ sent = variables;
+ return {
+ errors: [{ message: 'Changed.', extensions: { code: 'CONFLICT' } }],
+ };
+ });
+ const user = userEvent.setup();
+ mount('/recipes/' + apiRecipe.id + '/edit');
+ const title = await screen.findByLabelText(/Recipe title/);
+ fireEvent.change(title, { target: { value: 'My version' } });
+ await user.click(screen.getByRole('button', { name: 'Save changes' }));
+ expect(
+ await screen.findByText(/was changed in another tab or session/),
+ ).toBeInTheDocument();
+ expect(sent.expectedUpdatedAt).toBe(apiRecipe.updatedAt);
+ expect(title).toHaveValue('My version');
+ });
+
+ it('asks before replacing a draft that was offered but not restored', async () => {
+ saveDraft(apiUser.id, 'new', {
+ baseUpdatedAt: null,
+ fields: {
+ title: 'Older draft',
+ description: '',
+ category: '',
+ difficulty: '',
+ visibility: 'public',
+ prepTime: '',
+ cookingTime: '',
+ servings: '',
+ tags: '',
+ imageUrl: null,
+ ingredients: [{ name: '', amount: '', unit: 'g' }],
+ instructions: [''],
+ },
+ });
+ const user = userEvent.setup();
+ mount();
+ expect(screen.getByText('Saved draft found')).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Newer form' },
+ });
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ expect(
+ screen.getByRole('heading', { name: 'Replace saved draft?' }),
+ ).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Keep it' }));
+ expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Older draft');
+
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ await user.click(screen.getByRole('button', { name: 'Replace draft' }));
+ expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Newer form');
+ expect(screen.getByText('Draft saved')).toBeInTheDocument();
+ });
+
+ it('lets the browser warn on reload only while changes are unsaved', async () => {
+ const user = userEvent.setup();
+ mount();
+ const reload = () => {
+ const event = new Event('beforeunload', { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ expect(reload()).toBe(false);
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Unsaved soup' },
+ });
+ expect(reload()).toBe(true);
+ // Kept as a draft in this browser: nothing is lost by leaving.
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ expect(reload()).toBe(false);
+ });
+
+ it('counts a chosen image as unsaved before it is uploaded', () => {
+ mount();
+ const reload = () => {
+ const event = new Event('beforeunload', { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ expect(reload()).toBe(false);
+ URL.createObjectURL = vi.fn(() => 'blob:chosen');
+ URL.revokeObjectURL = vi.fn();
+ fireEvent.change(screen.getByLabelText('Upload a recipe image'), {
+ target: {
+ files: [new File(['x'], 'soup.png', { type: 'image/png' })],
+ },
+ });
+ // Nothing else changed, but the picked image is not saved anywhere yet.
+ expect(reload()).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(reload()).toBe(false);
+ });
+
+ it('warns when another tab replaces or deletes the saved draft', async () => {
+ const user = userEvent.setup();
+ mount();
+ const reload = () => {
+ const event = new Event('beforeunload', { cancelable: true });
+ window.dispatchEvent(event);
+ return event.defaultPrevented;
+ };
+ const draftKey = 'recipe-platform:draft:' + apiUser.id + ':new';
+ const otherTab = (change: () => void) => {
+ change();
+ act(() => {
+ window.dispatchEvent(new StorageEvent('storage', { key: draftKey }));
+ });
+ };
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'My soup' },
+ });
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ expect(reload()).toBe(false);
+
+ // Another tab saves its own draft over this one: ours is no longer kept.
+ otherTab(() =>
+ saveDraft(apiUser.id, 'new', {
+ baseUpdatedAt: null,
+ fields: { ...loadDraft(apiUser.id, 'new')!.fields, title: 'Theirs' },
+ }),
+ );
+ expect(reload()).toBe(true);
+
+ // Saving again over it asks first, then keeps this form as the draft.
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ await user.click(screen.getByRole('button', { name: 'Replace draft' }));
+ expect(reload()).toBe(false);
+
+ // Another tab deletes the draft.
+ otherTab(() => localStorage.removeItem(draftKey));
+ expect(reload()).toBe(true);
+ });
+
+ function mountWithDataRouter() {
+ const router = createMemoryRouter(
+ [
+ {
+ path: '/recipes/new',
+ element: (
+ <>
+ Go to My Cookbook
+
+ >
+ ),
+ },
+ { path: '/recipes/:id', element: Saved recipe destination },
+ { path: '/cookbook', element: Cookbook page },
+ ],
+ { initialEntries: ['/recipes/new'] },
+ );
+ render( );
+ }
+
+ it('asks before following a link away from unsaved changes', async () => {
+ const user = userEvent.setup();
+ mountWithDataRouter();
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Unsaved soup' },
+ });
+ await user.click(screen.getByRole('link', { name: 'Go to My Cookbook' }));
+ expect(
+ await screen.findByRole('heading', { name: 'Leave without saving?' }),
+ ).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Stay' }));
+ expect(screen.getByLabelText(/Recipe title/)).toHaveValue('Unsaved soup');
+
+ await user.click(screen.getByRole('link', { name: 'Go to My Cookbook' }));
+ await user.click(await screen.findByRole('button', { name: 'Leave' }));
+ expect(
+ await screen.findByRole('heading', { name: 'Cookbook page' }),
+ ).toBeInTheDocument();
+ });
+
+ it('does not ask after the recipe is published', async () => {
+ mockRecipeFetch(() => ({ data: { createRecipe: apiRecipe } }));
+ mountWithDataRouter();
+ const user = await fillRecipe();
+ await user.click(screen.getByRole('button', { name: 'Publish recipe' }));
+ expect(
+ await screen.findByRole('heading', { name: 'Saved recipe destination' }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole('heading', { name: 'Leave without saving?' }),
+ ).not.toBeInTheDocument();
+ });
+});
+
+describe('recipe size limits and error focus', () => {
+ /** A valid new recipe, filled without per-key typing (fast on CI). */
+ function fillValid() {
+ const change = (label: string | RegExp, value: string) =>
+ fireEvent.change(screen.getByLabelText(label), { target: { value } });
+ change(/Recipe title/, 'New soup');
+ change(/Preparation time/, '5');
+ change(/Cooking time/, '10');
+ change(/Difficulty/, 'easy');
+ change(/Servings/, '2');
+ change(/Category/, 'soup');
+ change('Ingredient 1', 'Water');
+ change('Ingredient 1 amount', '1');
+ change('Step 1', 'Boil.');
+ }
+ const publish = () =>
+ userEvent.click(screen.getByRole('button', { name: 'Publish recipe' }));
+ const tick = () => act(() => new Promise((resolve) => setTimeout(resolve)));
+
+ it('rejects more than 30 tags or a tag over 50 characters before submitting', async () => {
+ const fetch = mockRecipeFetch(() => ({
+ data: { createRecipe: apiRecipe },
+ }));
+ mount();
+ fillValid();
+ const tags = screen.getByLabelText(/Tags/);
+ fireEvent.change(tags, {
+ target: {
+ value: Array.from({ length: 31 }, (_, i) => `tag${i}`).join(', '),
+ },
+ });
+ await publish();
+ await tick();
+ expect(
+ screen.getByText('Use at most 30 tags (you have 31).'),
+ ).toBeInTheDocument();
+ expect(tags).toHaveFocus();
+
+ fireEvent.change(tags, { target: { value: `quick, ${'x'.repeat(51)}` } });
+ await publish();
+ await tick();
+ expect(
+ screen.getByText(/Keep each tag to 50 characters/),
+ ).toBeInTheDocument();
+ expect(tags).toHaveFocus();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it('counts and sends tags as the API stores them: lower-case, without repeats', async () => {
+ let input: { tags?: string[] } = {};
+ mockRecipeFetch((_operation, variables) => {
+ input = variables.input as typeof input;
+ return { data: { createRecipe: apiRecipe } };
+ });
+ mount();
+ fillValid();
+ // 30 distinct tags, written 60 times in different cases: allowed.
+ const distinct = Array.from({ length: 30 }, (_, i) => `tag${i}`);
+ fireEvent.change(screen.getByLabelText(/Tags/), {
+ target: {
+ value: [...distinct, ...distinct.map((tag) => tag.toUpperCase())].join(
+ ', ',
+ ),
+ },
+ });
+ await publish();
+ expect(
+ await screen.findByRole('heading', { name: 'Saved recipe destination' }),
+ ).toBeInTheDocument();
+ expect(input.tags).toEqual(distinct);
+ });
+
+ it('focuses the first invalid field in a later ingredient or step row', async () => {
+ mockRecipeFetch(() => ({ data: { createRecipe: apiRecipe } }));
+ const user = userEvent.setup();
+ mount();
+ fillValid();
+ await user.click(screen.getByRole('button', { name: 'Add ingredient' }));
+ fireEvent.change(screen.getByLabelText('Ingredient 2'), {
+ target: { value: 'Salt' },
+ });
+ const scroll = vi.fn();
+ const field = screen
+ .getByLabelText('Ingredient 2 amount')
+ .closest('.field')!;
+ Object.defineProperty(field, 'scrollIntoView', {
+ configurable: true,
+ value: scroll,
+ });
+ // Ingredient 2 has no amount: focus goes there, not to the title.
+ await publish();
+ await tick();
+ expect(screen.getByLabelText('Ingredient 2 amount')).toHaveFocus();
+ expect(scroll).toHaveBeenCalledWith({
+ block: 'start',
+ behavior: 'instant',
+ });
+
+ fireEvent.change(screen.getByLabelText('Ingredient 2 amount'), {
+ target: { value: '2' },
+ });
+ await user.click(screen.getByRole('button', { name: 'Add step' }));
+ await user.click(screen.getByRole('button', { name: 'Add step' }));
+ fireEvent.change(screen.getByLabelText('Step 2'), {
+ target: { value: 'Salt it.' },
+ });
+ // Step 3 is empty.
+ await publish();
+ await tick();
+ expect(screen.getByLabelText('Step 3')).toHaveFocus();
+ });
+});
+
+it('keeps a draft and the form when discarding is cancelled', async () => {
+ localStorage.clear();
+ const user = userEvent.setup();
+ const first = mount();
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Saved title' },
+ });
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ first.unmount();
+ mount();
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Current form' },
+ });
+ await user.click(screen.getByRole('button', { name: 'Discard draft' }));
+ expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Saved title');
+ await user.click(screen.getByRole('button', { name: 'Keep draft' }));
+ expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Saved title');
+ expect(screen.getByLabelText(/Recipe title/)).toHaveValue('Current form');
+ expect(screen.getByText('Saved draft found')).toBeInTheDocument();
+});
+
+it('restarts success notifications for each save and allows dismissal', async () => {
+ localStorage.clear();
+ const user = userEvent.setup();
+ mount();
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ const first = screen.getByText('Draft saved').closest('.toast');
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ expect(screen.getByText('Draft saved').closest('.toast')).not.toBe(first);
+ await user.click(
+ screen.getByRole('button', { name: 'Dismiss notification' }),
+ );
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Save draft' }));
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Changed' },
+ });
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+});
+
+it('expires success feedback but keeps a failed save visible until corrected', () => {
+ localStorage.clear();
+ vi.useFakeTimers();
+ let storage: ReturnType | undefined;
+ try {
+ mount();
+ fireEvent.click(screen.getByRole('button', { name: 'Save draft' }));
+ act(() => vi.advanceTimersByTime(4000));
+ fireEvent.click(screen.getByRole('button', { name: 'Save draft' }));
+ act(() => vi.advanceTimersByTime(1001));
+ expect(screen.getByText('Draft saved')).toBeInTheDocument();
+ act(() => vi.advanceTimersByTime(4000));
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+ storage = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('Storage full');
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save draft' }));
+ act(() => vi.advanceTimersByTime(10000));
+ expect(screen.getByText('Draft not saved')).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText(/Recipe title/), {
+ target: { value: 'Corrected' },
+ });
+ expect(screen.queryByText('Draft not saved')).not.toBeInTheDocument();
+ } finally {
+ storage?.mockRestore();
+ vi.useRealTimers();
+ }
+});
+
+it('does not restart draft feedback when publishing triggers validation', () => {
+ localStorage.clear();
+ vi.useFakeTimers();
+ try {
+ mount();
+ fireEvent.click(screen.getByRole('button', { name: 'Save draft' }));
+ act(() => vi.advanceTimersByTime(3500));
+ fireEvent.click(screen.getByRole('button', { name: 'Publish recipe' }));
+ expect(screen.getByText('Enter a recipe title.')).toBeInTheDocument();
+ act(() => vi.advanceTimersByTime(1499));
+ expect(screen.getByText('Draft saved')).toBeInTheDocument();
+ act(() => vi.advanceTimersByTime(1));
+ expect(screen.queryByText('Draft saved')).not.toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx
index 625399f..786ba65 100644
--- a/apps/web/src/features/recipes/RecipeCreatePage.tsx
+++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx
@@ -1,3 +1,4 @@
+import { PageTitle, usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
@@ -8,16 +9,18 @@ import {
} from 'react';
import { DeleteIcon, DragHandleIcon } from '../../icons/actions';
+import { ChevronDownIcon, ChevronUpIcon } from '../../icons/navigation';
import Button from '../../components/ui/Button/Button';
import Field from '../../components/ui/Field/Field';
import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage';
+import Toast from '../../components/ui/Toast/Toast';
import IconButton from '../../components/ui/IconButton/IconButton';
import { Icon } from '../../components/ui/Icon/Icon';
import Radio from '../../components/ui/Radio/Radio';
import RadioGroup from '../../components/ui/Radio/RadioGroup';
import Select from '../../components/ui/Select/Select';
import Textarea from '../../components/ui/Textarea/Textarea';
-import { useNavigate, useParams } from 'react-router-dom';
+import { useLocation, useNavigate, useParams } from 'react-router-dom';
import type { Recipe } from '../../types/recipe';
import {
getRecipe,
@@ -29,6 +32,27 @@ import { useRecipeQuery } from './useRecipeQuery';
import RecipeQueryStatus from './RecipeQueryStatus';
import LinkButton from '../../components/ui/LinkButton/LinkButton';
import RecipeImageField from './RecipeImageField';
+import { useAppStore } from '../../store';
+import { recipeImageUrl } from '../../lib/recipeImageUrl';
+import {
+ clearDraft,
+ loadDraft,
+ saveDraft,
+ type RecipeDraftFields,
+} from '../../lib/recipeDrafts';
+import { INGREDIENT_UNITS, normalizeUnit } from '../../lib/ingredientUnits';
+import {
+ MAX_INGREDIENTS,
+ MAX_INSTRUCTIONS,
+ MAX_SERVINGS,
+ MAX_TAG_LENGTH,
+ MAX_TAGS,
+ MIN_SERVINGS,
+ parseTags,
+} from '@t31/validation/recipe';
+import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog';
+import { useUnsavedChanges } from '../../lib/unsavedChanges';
+import UnsavedChangesGuard from './UnsavedChangesGuard';
import './RecipeCreatePage.css';
@@ -42,8 +66,12 @@ type RecipeErrors = {
category?: string;
visibility?: string;
image?: string;
+ tags?: string;
ingredients?: IngredientFieldErrors[];
instructions?: string[];
+ // Too many rows (possible from a restored draft); shown above the list.
+ ingredientCount?: string;
+ instructionCount?: string;
};
type IngredientFieldErrors = {
@@ -52,15 +80,46 @@ type IngredientFieldErrors = {
unit?: string;
};
-type FormStatus = 'idle' | 'draft';
+type FormStatus = 'idle' | 'draft' | 'draft-failed';
+/*
+ * Rows carry a stable key so React keeps each row's DOM (focus, typed text)
+ * with its data when rows are moved or removed; array indexes would not.
+ */
type IngredientDraft = {
+ key: string;
name: string;
amount: string;
unit: string;
note?: string;
};
+type InstructionDraft = { key: string; text: string };
+type RowType = 'ingredient' | 'instruction';
+
+let lastRowKey = 0;
+function newRowKey() {
+ lastRowKey += 1;
+ return `row-${lastRowKey}`;
+}
+
+function formatDraftTime(savedAt: string) {
+ return new Date(savedAt).toLocaleString('en-GB', {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ });
+}
+
+/** Row-count messages for lists over the API's limits; none when they fit. */
+function rowCountErrors(ingredientCount: number, instructionCount: number) {
+ const errors: Pick = {};
+ if (ingredientCount > MAX_INGREDIENTS)
+ errors.ingredientCount = `A recipe can have at most ${MAX_INGREDIENTS} ingredients. Remove ${ingredientCount - MAX_INGREDIENTS} to save.`;
+ if (instructionCount > MAX_INSTRUCTIONS)
+ errors.instructionCount = `A recipe can have at most ${MAX_INSTRUCTIONS} steps. Remove ${instructionCount - MAX_INSTRUCTIONS} to save.`;
+ return errors;
+}
+
function moveItem(items: T[], fromIndex: number, toIndex: number) {
const nextItems = [...items];
const [movedItem] = nextItems.splice(fromIndex, 1);
@@ -70,7 +129,10 @@ function moveItem(items: T[], fromIndex: number, toIndex: number) {
}
function RecipeEditor({ recipe }: { recipe?: Recipe }) {
+ usePageTitle(recipe ? `Edit ${recipe.title}` : 'Add recipe');
const navigate = useNavigate();
+ const location = useLocation();
+ const formRef = useRef(null);
const busyRef = useRef(false);
const [pending, setPending] = useState(false);
const [submitError, setSubmitError] = useState('');
@@ -92,19 +154,245 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
);
const [difficulty, setDifficulty] = useState(recipe?.difficulty ?? '');
const [ingredients, setIngredients] = useState(
- recipe?.ingredients.map((item) => ({
- ...item,
- amount: String(item.amount),
- })) ?? [{ name: '', amount: '', unit: 'g' }],
+ () =>
+ recipe?.ingredients.map((item) => ({
+ key: newRowKey(),
+ name: item.name,
+ amount: String(item.amount),
+ unit: normalizeUnit(item.unit),
+ note: item.note ?? undefined,
+ })) ?? [{ key: newRowKey(), name: '', amount: '', unit: 'g' }],
+ );
+ const [instructions, setInstructions] = useState(
+ () =>
+ recipe?.instructions.map((item) => ({
+ key: newRowKey(),
+ text: item.text,
+ })) ?? [{ key: newRowKey(), text: '' }],
+ );
+ // Announced after a row is moved with the keyboard buttons.
+ const [moveAnnouncement, setMoveAnnouncement] = useState('');
+ // Id of the control to focus after the next render (see moveRow).
+ const pendingFocusId = useRef(null);
+
+ /*
+ * Drafts are saved in this browser per user and recipe ("new" for a new
+ * recipe), see lib/recipeDrafts.ts. A saved draft is offered when the
+ * form opens; it is outdated if the recipe was changed after the draft.
+ */
+ const userId = useAppStore((state) => state.currentUser?.id);
+ const draftRecipeId = recipe?.id ?? 'new';
+ const [offeredDraft, setOfferedDraft] = useState(() =>
+ userId ? loadDraft(userId, draftRecipeId) : null,
);
- const [instructions, setInstructions] = useState(
- recipe?.instructions.map((item) => item.text) ?? [''],
+ const [draftNotice, setDraftNotice] = useState('');
+ const draftIsOutdated = Boolean(
+ recipe && offeredDraft && offeredDraft.baseUpdatedAt !== recipe.updatedAt,
);
+ /*
+ * savedAt of the drafts this tab has offered or saved. Discarding or
+ * submitting only removes one of these, never a newer draft that another
+ * tab saved in the meantime.
+ */
+ const knownDrafts = useRef(
+ offeredDraft ? [offeredDraft.savedAt] : [],
+ );
+ /*
+ * The form as it was when "Save draft" was last pressed. The draft
+ * message is only shown while the form still matches it, so any later
+ * change (text, tags, image, added, removed or moved rows) hides it.
+ */
+ const [savedSnapshot, setSavedSnapshot] = useState(null);
+ /*
+ * Restoring a draft checks that its image still exists before using it.
+ * Until then saving is blocked (it would save without the image), and a
+ * newer image choice cancels the check, so a late answer cannot replace
+ * the image the user picked.
+ */
+ const [imageRestoring, setImageRestoring] = useState(false);
+ const imageCheck = useRef(0);
+
+ function changeImage(url: string | null) {
+ imageCheck.current += 1;
+ setImageRestoring(false);
+ setImageUrl(url);
+ }
+
+ function draftFields(): RecipeDraftFields {
+ return {
+ title,
+ description,
+ category,
+ difficulty,
+ visibility,
+ prepTime,
+ cookingTime,
+ servings,
+ tags,
+ imageUrl,
+ ingredients: ingredients.map(({ name, amount, unit, note }) => ({
+ name,
+ amount,
+ unit,
+ note,
+ })),
+ instructions: instructions.map(({ text }) => text),
+ };
+ }
+ const formSnapshot = JSON.stringify(draftFields());
+ const draftMessageIsCurrent = savedSnapshot === formSnapshot;
+
+ /*
+ * Unsaved changes: the form differs from how it was opened and from the
+ * draft this browser holds for it right now, or an image is being chosen
+ * or uploaded. The stored draft is read again whenever it changes, also
+ * in another tab, so a draft replaced or deleted there is not counted as
+ * saving this form. Leaving, reloading or signing out then asks first
+ * (UnsavedChangesGuard, SiteHeader). The refs let the guard read the
+ * latest state when the user leaves, and let a successful save navigate
+ * away unasked.
+ */
+ const [openedSnapshot] = useState(formSnapshot);
+ const readStoredSnapshot = () => {
+ const stored = userId ? loadDraft(userId, draftRecipeId) : null;
+ return stored ? JSON.stringify(stored.fields) : null;
+ };
+ const [storedSnapshot, setStoredSnapshot] = useState(readStoredSnapshot);
+ const refreshStoredDraft = () => setStoredSnapshot(readStoredSnapshot());
+ useEffect(() => {
+ window.addEventListener('storage', refreshStoredDraft);
+ return () => window.removeEventListener('storage', refreshStoredDraft);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [userId, draftRecipeId]);
+ const unsaved =
+ imagePending ||
+ (formSnapshot !== openedSnapshot && formSnapshot !== storedSnapshot);
+ const unsavedRef = useRef(unsaved);
+ const leaving = useRef(false);
+ useEffect(() => {
+ unsavedRef.current = unsaved;
+ useUnsavedChanges.setState({ unsaved });
+ }, [unsaved]);
+ useEffect(() => () => useUnsavedChanges.setState({ unsaved: false }), []);
+ // The header clears the shared flag when the user confirms signing out
+ // with unsaved changes, so they are not asked a second time.
+ const isDirty = useCallback(
+ () =>
+ unsavedRef.current &&
+ !leaving.current &&
+ useUnsavedChanges.getState().unsaved,
+ [],
+ );
+
+ const [confirmReplaceDraft, setConfirmReplaceDraft] = useState(false);
+ const [confirmDiscardDraft, setConfirmDiscardDraft] = useState(false);
+ const [draftNotification, setDraftNotification] = useState(0);
+ function handleSaveDraft() {
+ if (!userId || imageRestoring) return;
+ // Do not silently replace a draft this tab has not restored or written:
+ // the one offered on opening, or one another tab saved in the meantime.
+ const stored = loadDraft(userId, draftRecipeId);
+ if (
+ offeredDraft ||
+ (stored && !knownDrafts.current.includes(stored.savedAt))
+ ) {
+ setConfirmReplaceDraft(true);
+ return;
+ }
+ writeDraft();
+ }
+
+ function writeDraft() {
+ setConfirmReplaceDraft(false);
+ if (!userId) return;
+ const saved = saveDraft(userId, draftRecipeId, {
+ baseUpdatedAt: recipe?.updatedAt ?? null,
+ fields: draftFields(),
+ });
+ if (saved) {
+ knownDrafts.current.push(saved.savedAt);
+ refreshStoredDraft();
+ }
+ setOfferedDraft(null);
+ setDraftNotice('');
+ setSavedSnapshot(formSnapshot);
+ setStatus(saved ? 'draft' : 'draft-failed');
+ setDraftNotification((current) => current + 1);
+ }
+
+ function restoreDraft() {
+ if (!offeredDraft) return;
+ const { fields } = offeredDraft;
+ setTitle(fields.title);
+ setDescription(fields.description);
+ setCategory(fields.category);
+ setDifficulty(fields.difficulty);
+ setVisibility(fields.visibility);
+ setPrepTime(fields.prepTime);
+ setCookingTime(fields.cookingTime);
+ setServings(fields.servings);
+ setTags(fields.tags);
+ setIngredients(
+ fields.ingredients.map((ingredient) => ({
+ ...ingredient,
+ key: newRowKey(),
+ })),
+ );
+ setInstructions(
+ fields.instructions.map((text) => ({ key: newRowKey(), text })),
+ );
+ // A draft can hold more rows than the API accepts: say so right away.
+ setErrors(
+ rowCountErrors(fields.ingredients.length, fields.instructions.length),
+ );
+ setOfferedDraft(null);
+ // Unused uploads are cleaned up after 24 hours, so the draft's image may
+ // be gone; keep the current image instead of a broken one.
+ const draftImage = fields.imageUrl;
+ if (!draftImage) {
+ changeImage(null);
+ setDraftNotice('Draft restored.');
+ return;
+ }
+ imageCheck.current += 1;
+ const check = imageCheck.current;
+ setImageRestoring(true);
+ setDraftNotice('Draft restored. Checking its image…');
+ const probe = new Image();
+ probe.onload = () => {
+ if (imageCheck.current !== check) return;
+ setImageRestoring(false);
+ setImageUrl(draftImage);
+ setDraftNotice('Draft restored.');
+ };
+ probe.onerror = () => {
+ if (imageCheck.current !== check) return;
+ setImageRestoring(false);
+ setDraftNotice(
+ 'Draft restored. Its image is no longer available and was left out.',
+ );
+ };
+ probe.src = recipeImageUrl(draftImage);
+ }
+
+ function discardDraft() {
+ setConfirmDiscardDraft(false);
+ const removed =
+ userId && clearDraft(userId, draftRecipeId, knownDrafts.current);
+ setOfferedDraft(null);
+ if (removed) refreshStoredDraft();
+ setDraftNotice(
+ removed || !userId || !loadDraft(userId, draftRecipeId)
+ ? 'Draft discarded.'
+ : 'A newer draft was saved in another tab, so it was kept.',
+ );
+ }
const [draggingRow, setDraggingRow] = useState<
{ type: 'ingredient' | 'instruction'; index: number } | undefined
>();
const [errors, setErrors] = useState({});
const [status, setStatus] = useState('idle');
+ const closeDraftNotification = useCallback(() => setStatus('idle'), []);
const pointerDragRef = useRef<
{ type: 'ingredient' | 'instruction'; index: number } | undefined
>(undefined);
@@ -121,11 +409,22 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
function addIngredient() {
setIngredients((currentIngredients) => [
...currentIngredients,
- { name: '', amount: '', unit: 'g' },
+ { key: newRowKey(), name: '', amount: '', unit: 'g' },
]);
}
function removeIngredient(index: number) {
+ // Keep the message, with the remaining count, until the list fits.
+ setErrors((currentErrors) => {
+ if (!currentErrors.ingredientCount) return currentErrors;
+ const nextErrors = { ...currentErrors };
+ delete nextErrors.ingredientCount;
+ return {
+ ...nextErrors,
+ ...rowCountErrors(ingredients.length - 1, 0),
+ };
+ });
+ setStatus('idle');
setIngredients((currentIngredients) =>
currentIngredients.filter(
(_, ingredientIndex) => ingredientIndex !== index,
@@ -173,10 +472,23 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
);
function addInstruction() {
- setInstructions((currentInstructions) => [...currentInstructions, '']);
+ setInstructions((currentInstructions) => [
+ ...currentInstructions,
+ { key: newRowKey(), text: '' },
+ ]);
}
function removeInstruction(index: number) {
+ setErrors((currentErrors) => {
+ if (!currentErrors.instructionCount) return currentErrors;
+ const nextErrors = { ...currentErrors };
+ delete nextErrors.instructionCount;
+ return {
+ ...nextErrors,
+ ...rowCountErrors(0, instructions.length - 1),
+ };
+ });
+ setStatus('idle');
setInstructions((currentInstructions) =>
currentInstructions.filter(
(_, instructionIndex) => instructionIndex !== index,
@@ -187,7 +499,9 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
function updateInstruction(index: number, value: string) {
setInstructions((currentInstructions) =>
currentInstructions.map((instruction, instructionIndex) =>
- instructionIndex === index ? value : instruction,
+ instructionIndex === index
+ ? { ...instruction, text: value }
+ : instruction,
),
);
setErrors((currentErrors) => ({
@@ -287,6 +601,37 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
setDraggingRow({ type, index });
}
+ /*
+ * Keyboard alternative to dragging (WCAG 2.5.7): moves a row one place,
+ * keeps focus on the moved row's button (or its other move button when it
+ * reaches the first/last place) and announces the new position.
+ */
+ function moveRow(type: RowType, index: number, direction: -1 | 1) {
+ const rows = type === 'ingredient' ? ingredients : instructions;
+ const target = index + direction;
+ if (target < 0 || target >= rows.length) return;
+ if (type === 'ingredient') reorderIngredients(index, target);
+ else reorderInstructions(index, target);
+ const atEdge = target === 0 || target === rows.length - 1;
+ const button = atEdge
+ ? target === 0
+ ? 'down'
+ : 'up'
+ : direction === -1
+ ? 'up'
+ : 'down';
+ pendingFocusId.current = `${type}-${rows[index]!.key}-move-${button}`;
+ setMoveAnnouncement(
+ `${type === 'ingredient' ? 'Ingredient' : 'Step'} moved to position ${target + 1} of ${rows.length}.`,
+ );
+ }
+
+ useEffect(() => {
+ if (!pendingFocusId.current) return;
+ document.getElementById(pendingFocusId.current)?.focus();
+ pendingFocusId.current = null;
+ });
+
function validateForm(): RecipeErrors {
const nextErrors: RecipeErrors = {};
@@ -309,15 +654,25 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
if (
!servings ||
!Number.isInteger(Number(servings)) ||
- Number(servings) < 1 ||
- Number(servings) > 1000
+ Number(servings) < MIN_SERVINGS ||
+ Number(servings) > MAX_SERVINGS
) {
- nextErrors.servings = 'Enter whole servings from 1 to 1000.';
+ nextErrors.servings = `Enter whole servings from ${MIN_SERVINGS} to ${MAX_SERVINGS}.`;
}
if (!category) nextErrors.category = 'Choose a recipe category.';
if (!visibility) {
nextErrors.visibility = 'Choose who can see this recipe.';
}
+ const tagList = parseTags(tags);
+ const longTag = tagList.find((tag) => tag.length > MAX_TAG_LENGTH);
+ if (tagList.length > MAX_TAGS)
+ nextErrors.tags = `Use at most ${MAX_TAGS} tags (you have ${tagList.length}).`;
+ else if (longTag)
+ nextErrors.tags = `Keep each tag to ${MAX_TAG_LENGTH} characters. "${longTag.slice(0, 20)}…" is ${longTag.length}.`;
+ Object.assign(
+ nextErrors,
+ rowCountErrors(ingredients.length, instructions.length),
+ );
const ingredientErrors = ingredients.map((ingredient) => ({
name: !ingredient.name.trim()
@@ -345,10 +700,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
)
nextErrors.ingredients = ingredientErrors;
- const instructionErrors = instructions.map((instruction) =>
- !instruction.trim()
+ const instructionErrors = instructions.map(({ text }) =>
+ !text.trim()
? 'Add an instruction.'
- : instruction.trim().length > 5000
+ : text.trim().length > 5000
? 'Keep instructions under 5000 characters.'
: '',
);
@@ -361,43 +716,25 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
async function handleSubmit(event: FormEvent) {
event.preventDefault();
- if (busyRef.current || imagePending) return;
+ if (busyRef.current || imagePending || imageRestoring) return;
const nextErrors = validateForm();
setErrors(nextErrors);
if (Object.keys(nextErrors).length > 0) {
- const firstIngredientError = nextErrors.ingredients?.[0];
- const firstInvalidId = [
- { id: 'recipe-title', invalid: Boolean(nextErrors.title) },
- { id: 'prep-time', invalid: Boolean(nextErrors.prepTime) },
- { id: 'difficulty', invalid: Boolean(nextErrors.difficulty) },
- { id: 'cooking-time', invalid: Boolean(nextErrors.cookingTime) },
- { id: 'servings', invalid: Boolean(nextErrors.servings) },
- { id: 'category', invalid: Boolean(nextErrors.category) },
- {
- id: 'ingredient-0',
- invalid: Boolean(firstIngredientError?.name),
- },
- {
- id: 'ingredient-0-amount',
- invalid: Boolean(firstIngredientError?.amount),
- },
- {
- id: 'ingredient-0-unit',
- invalid: Boolean(firstIngredientError?.unit),
- },
- {
- id: 'instruction-0',
- invalid: Boolean(nextErrors.instructions?.[0]),
- },
- ].find((field) => field.invalid)?.id;
-
- window.setTimeout(
- () =>
- document.getElementById(firstInvalidId ?? 'recipe-title')?.focus(),
- 0,
- );
+ // Once the errors are rendered, focus the first invalid control in
+ // page order, whichever field or row it is in. Row-count messages are
+ // marked with data-form-error.
+ window.setTimeout(() => {
+ const firstInvalid = formRef.current?.querySelector(
+ '[aria-invalid="true"], [data-form-error]',
+ );
+ const target = firstInvalid ?? document.getElementById('recipe-title');
+ target?.focus({ preventScroll: true });
+ const field =
+ target?.closest('.field, .textarea, .select, .radio-group') ?? target;
+ field?.scrollIntoView?.({ block: 'start', behavior: 'instant' });
+ }, 0);
return;
}
@@ -420,16 +757,22 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
unit: item.unit,
note: item.note,
})),
- instructions: instructions.map((text) => text.trim()),
- tags: tags
- .split(',')
- .map((tag) => tag.trim())
- .filter(Boolean),
+ instructions: instructions.map(({ text }) => text.trim()),
+ tags: parseTags(tags),
imageUrl,
cuisine: recipe?.cuisine || null,
};
- const saved = await writeRecipe(input, recipe?.id);
- navigate('/recipes/' + saved.id, { replace: Boolean(recipe) });
+ // Editing sends the version it loaded; if the recipe changed since
+ // (another tab or device), the API refuses instead of overwriting it.
+ const saved = await writeRecipe(input, recipe?.id, recipe?.updatedAt);
+ // The saved recipe replaces the draft (but not a newer one saved in
+ // another tab after this form read or saved its draft).
+ if (userId) clearDraft(userId, draftRecipeId, knownDrafts.current);
+ leaving.current = true;
+ navigate('/recipes/' + saved.id, {
+ replace: Boolean(recipe),
+ state: recipe ? location.state : { from: '/cookbook' },
+ });
} catch (error) {
setSubmitError(recipeErrorMessage(error));
} finally {
@@ -456,10 +799,14 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
-
+
);
}
diff --git a/apps/web/src/styles/tokens.css b/apps/web/src/styles/tokens.css
index ef84314..aa144d5 100644
--- a/apps/web/src/styles/tokens.css
+++ b/apps/web/src/styles/tokens.css
@@ -1,8 +1,18 @@
:root {
- /* Brand */
- --color-brand-primary: #e86a1c;
- --color-brand-primary-hover: #cc5b14;
- --color-brand-primary-active: #b84f0d;
+ /*
+ * Brand
+ *
+ * Brand colours are used both as button backgrounds (with white text) and
+ * as text/link colour on the light surfaces. They must keep at least 4.5:1
+ * contrast (WCAG 2.2 AA) in both roles:
+ * - primary on white text: 5.88:1, on --color-bg-page: 5.21:1,
+ * on --color-surface-selected: 4.67:1
+ * - hover: 6.80:1 and active: 7.57:1 with white text
+ * Check new values against these surfaces before changing them.
+ */
+ --color-brand-primary: #a8470b;
+ --color-brand-primary-hover: #9a3f08;
+ --color-brand-primary-active: #8f3a06;
--color-brand-accent-soft: #fff4e8;
/* Backgrounds and surfaces */
@@ -209,6 +219,8 @@
/* Layering */
--z-dropdown: 100;
--z-sticky: 200;
+ /* Height of the sticky site header; content scrolled to must clear it. */
+ --site-header-height: 5rem;
--z-overlay: 300;
--z-modal: 400;
diff --git a/contracts/generated.ts b/contracts/generated.ts
index c803e5c..6ce6fc2 100644
--- a/contracts/generated.ts
+++ b/contracts/generated.ts
@@ -7,7 +7,7 @@ export type Incremental
=
| {
[P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never;
};
-import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';
+import type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';
export type RecipeDifficulty = 'easy' | 'medium' | 'hard';
export type RecipeVisibility = 'public' | 'private';
@@ -269,6 +269,7 @@ export type CreateRecipeMutation = {
export type UpdateRecipeMutationVariables = Exact<{
id: string | number;
input: RecipeInput;
+ expectedUpdatedAt?: string | null | undefined;
}>;
export type UpdateRecipeMutation = {
@@ -400,1431 +401,464 @@ export type RemoveRecipeRatingMutationVariables = Exact<{
export type RemoveRecipeRatingMutation = { removeRecipeRating: boolean };
-export const RecipeFieldsFragmentDoc = {
- kind: 'Document',
- definitions: [
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'Recipe' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'category' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } },
- { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },
- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'author' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'ingredients' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'amount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'unit' } },
- { kind: 'Field', name: { kind: 'Name', value: 'note' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'instructions' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'step' } },
- { kind: 'Field', name: { kind: 'Name', value: 'text' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'userRating' } },
- { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const RecipeSummaryFieldsFragmentDoc = {
- kind: 'Document',
- definitions: [
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeSummaryFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeSummary' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const HealthDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'query',
- name: { kind: 'Name', value: 'Health' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'health' } },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const SignOutDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'SignOut' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'signOut' } },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const RegisterDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'Register' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'name' } },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'String' },
- },
- },
- },
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'email' },
- },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'String' },
- },
- },
- },
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'password' },
- },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'String' },
- },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'register' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'name' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'name' },
- },
- },
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'email' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'email' },
- },
- },
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'password' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'password' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'user' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'email' } },
- ],
- },
- },
- ],
- },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const LoginDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'Login' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'email' },
- },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'String' },
- },
- },
- },
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'password' },
- },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'String' },
- },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'login' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'email' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'email' },
- },
- },
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'password' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'password' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'user' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'email' } },
- ],
- },
- },
- ],
- },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const CurrentUserDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'query',
- name: { kind: 'Name', value: 'CurrentUser' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'currentUser' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'email' } },
- ],
- },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const RecipesDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'query',
- name: { kind: 'Name', value: 'Recipes' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeListInput' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'recipes' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'input' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'items' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeSummaryFields' },
- },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } },
- { kind: 'Field', name: { kind: 'Name', value: 'page' } },
- { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeSummaryFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeSummary' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const RecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'query',
- name: { kind: 'Name', value: 'Recipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'recipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeFields' },
- },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'Recipe' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'category' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } },
- { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },
- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'author' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'ingredients' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'amount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'unit' } },
- { kind: 'Field', name: { kind: 'Name', value: 'note' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'instructions' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'step' } },
- { kind: 'Field', name: { kind: 'Name', value: 'text' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'userRating' } },
- { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const CookbookDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'query',
- name: { kind: 'Name', value: 'Cookbook' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeListInput' },
- },
- },
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'scope' },
- },
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'CookbookScope' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'cookbook' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'input' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- },
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'scope' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'scope' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'items' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeSummaryFields' },
- },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } },
- { kind: 'Field', name: { kind: 'Name', value: 'page' } },
- { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeSummaryFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeSummary' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const CreateRecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'CreateRecipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeInput' },
- },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'createRecipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'input' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeFields' },
- },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'Recipe' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'category' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } },
- { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },
- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'author' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'ingredients' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'amount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'unit' } },
- { kind: 'Field', name: { kind: 'Name', value: 'note' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'instructions' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'step' } },
- { kind: 'Field', name: { kind: 'Name', value: 'text' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'userRating' } },
- { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode<
+export class TypedDocumentString
+ extends String
+ implements DocumentTypeDecoration
+{
+ __apiType?: NonNullable<
+ DocumentTypeDecoration['__apiType']
+ >;
+ private value: string;
+ public __meta__?: Record | undefined;
+
+ constructor(value: string, __meta__?: Record | undefined) {
+ super(value);
+ this.value = value;
+ this.__meta__ = __meta__;
+ }
+
+ override toString(): string & DocumentTypeDecoration {
+ return this.value;
+ }
+}
+export const RecipeFieldsFragmentDoc = new TypedDocumentString(
+ `
+ fragment RecipeFields on Recipe {
+ id
+ title
+ description
+ category
+ cuisine
+ difficulty
+ visibility
+ imageUrl
+ sourceRecipeId
+ prepMinutes
+ cookMinutes
+ servings
+ createdAt
+ updatedAt
+ author {
+ id
+ name
+ }
+ ingredients {
+ id
+ name
+ amount
+ unit
+ note
+ }
+ instructions {
+ step
+ text
+ }
+ tags
+ rating {
+ average
+ count
+ }
+ userRating
+ saveCount
+ isSaved
+ isCreatedByCurrentUser
+}
+ `,
+ { fragmentName: 'RecipeFields' },
+) as unknown as TypedDocumentString;
+export const RecipeSummaryFieldsFragmentDoc = new TypedDocumentString(
+ `
+ fragment RecipeSummaryFields on RecipeSummary {
+ id
+ title
+ description
+ visibility
+ imageUrl
+ prepMinutes
+ cookMinutes
+ servings
+ tags
+ rating {
+ average
+ count
+ }
+ isSaved
+ isCreatedByCurrentUser
+}
+ `,
+ { fragmentName: 'RecipeSummaryFields' },
+) as unknown as TypedDocumentString;
+export const HealthDocument = new TypedDocumentString(`
+ query Health {
+ health
+}
+ `) as unknown as TypedDocumentString;
+export const SignOutDocument = new TypedDocumentString(`
+ mutation SignOut {
+ signOut
+}
+ `) as unknown as TypedDocumentString<
+ SignOutMutation,
+ SignOutMutationVariables
+>;
+export const RegisterDocument = new TypedDocumentString(`
+ mutation Register($name: String!, $email: String!, $password: String!) {
+ register(name: $name, email: $email, password: $password) {
+ user {
+ id
+ name
+ email
+ }
+ }
+}
+ `) as unknown as TypedDocumentString<
+ RegisterMutation,
+ RegisterMutationVariables
+>;
+export const LoginDocument = new TypedDocumentString(`
+ mutation Login($email: String!, $password: String!) {
+ login(email: $email, password: $password) {
+ user {
+ id
+ name
+ email
+ }
+ }
+}
+ `) as unknown as TypedDocumentString;
+export const CurrentUserDocument = new TypedDocumentString(`
+ query CurrentUser {
+ currentUser {
+ id
+ name
+ email
+ }
+}
+ `) as unknown as TypedDocumentString<
+ CurrentUserQuery,
+ CurrentUserQueryVariables
+>;
+export const RecipesDocument = new TypedDocumentString(`
+ query Recipes($input: RecipeListInput) {
+ recipes(input: $input) {
+ items {
+ ...RecipeSummaryFields
+ }
+ totalCount
+ totalPages
+ page
+ pageSize
+ }
+}
+ fragment RecipeSummaryFields on RecipeSummary {
+ id
+ title
+ description
+ visibility
+ imageUrl
+ prepMinutes
+ cookMinutes
+ servings
+ tags
+ rating {
+ average
+ count
+ }
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString;
+export const RecipeDocument = new TypedDocumentString(`
+ query Recipe($id: ID!) {
+ recipe(id: $id) {
+ ...RecipeFields
+ }
+}
+ fragment RecipeFields on Recipe {
+ id
+ title
+ description
+ category
+ cuisine
+ difficulty
+ visibility
+ imageUrl
+ sourceRecipeId
+ prepMinutes
+ cookMinutes
+ servings
+ createdAt
+ updatedAt
+ author {
+ id
+ name
+ }
+ ingredients {
+ id
+ name
+ amount
+ unit
+ note
+ }
+ instructions {
+ step
+ text
+ }
+ tags
+ rating {
+ average
+ count
+ }
+ userRating
+ saveCount
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString;
+export const CookbookDocument = new TypedDocumentString(`
+ query Cookbook($input: RecipeListInput, $scope: CookbookScope) {
+ cookbook(input: $input, scope: $scope) {
+ items {
+ ...RecipeSummaryFields
+ }
+ totalCount
+ totalPages
+ page
+ pageSize
+ }
+}
+ fragment RecipeSummaryFields on RecipeSummary {
+ id
+ title
+ description
+ visibility
+ imageUrl
+ prepMinutes
+ cookMinutes
+ servings
+ tags
+ rating {
+ average
+ count
+ }
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString;
+export const CreateRecipeDocument = new TypedDocumentString(`
+ mutation CreateRecipe($input: RecipeInput!) {
+ createRecipe(input: $input) {
+ ...RecipeFields
+ }
+}
+ fragment RecipeFields on Recipe {
+ id
+ title
+ description
+ category
+ cuisine
+ difficulty
+ visibility
+ imageUrl
+ sourceRecipeId
+ prepMinutes
+ cookMinutes
+ servings
+ createdAt
+ updatedAt
+ author {
+ id
+ name
+ }
+ ingredients {
+ id
+ name
+ amount
+ unit
+ note
+ }
+ instructions {
+ step
+ text
+ }
+ tags
+ rating {
+ average
+ count
+ }
+ userRating
+ saveCount
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString<
CreateRecipeMutation,
CreateRecipeMutationVariables
>;
-export const UpdateRecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'UpdateRecipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- type: {
- kind: 'NonNullType',
- type: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'RecipeInput' },
- },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'updateRecipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'input' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'input' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeFields' },
- },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'Recipe' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'category' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } },
- { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },
- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'author' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'ingredients' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'amount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'unit' } },
- { kind: 'Field', name: { kind: 'Name', value: 'note' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'instructions' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'step' } },
- { kind: 'Field', name: { kind: 'Name', value: 'text' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'userRating' } },
- { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode<
+export const UpdateRecipeDocument = new TypedDocumentString(`
+ mutation UpdateRecipe($id: ID!, $input: RecipeInput!, $expectedUpdatedAt: String) {
+ updateRecipe(id: $id, input: $input, expectedUpdatedAt: $expectedUpdatedAt) {
+ ...RecipeFields
+ }
+}
+ fragment RecipeFields on Recipe {
+ id
+ title
+ description
+ category
+ cuisine
+ difficulty
+ visibility
+ imageUrl
+ sourceRecipeId
+ prepMinutes
+ cookMinutes
+ servings
+ createdAt
+ updatedAt
+ author {
+ id
+ name
+ }
+ ingredients {
+ id
+ name
+ amount
+ unit
+ note
+ }
+ instructions {
+ step
+ text
+ }
+ tags
+ rating {
+ average
+ count
+ }
+ userRating
+ saveCount
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString<
UpdateRecipeMutation,
UpdateRecipeMutationVariables
>;
-export const DeleteRecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'DeleteRecipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'deleteRecipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- ],
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode<
+export const DeleteRecipeDocument = new TypedDocumentString(`
+ mutation DeleteRecipe($id: ID!) {
+ deleteRecipe(id: $id)
+}
+ `) as unknown as TypedDocumentString<
DeleteRecipeMutation,
DeleteRecipeMutationVariables
>;
-export const SaveRecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'SaveRecipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'saveRecipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeFields' },
- },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'Recipe' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'category' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } },
- { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },
- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'author' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'ingredients' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'amount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'unit' } },
- { kind: 'Field', name: { kind: 'Name', value: 'note' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'instructions' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'step' } },
- { kind: 'Field', name: { kind: 'Name', value: 'text' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'userRating' } },
- { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const UnsaveRecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'UnsaveRecipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'unsaveRecipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- ],
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode<
+export const SaveRecipeDocument = new TypedDocumentString(`
+ mutation SaveRecipe($id: ID!) {
+ saveRecipe(id: $id) {
+ ...RecipeFields
+ }
+}
+ fragment RecipeFields on Recipe {
+ id
+ title
+ description
+ category
+ cuisine
+ difficulty
+ visibility
+ imageUrl
+ sourceRecipeId
+ prepMinutes
+ cookMinutes
+ servings
+ createdAt
+ updatedAt
+ author {
+ id
+ name
+ }
+ ingredients {
+ id
+ name
+ amount
+ unit
+ note
+ }
+ instructions {
+ step
+ text
+ }
+ tags
+ rating {
+ average
+ count
+ }
+ userRating
+ saveCount
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString<
+ SaveRecipeMutation,
+ SaveRecipeMutationVariables
+>;
+export const UnsaveRecipeDocument = new TypedDocumentString(`
+ mutation UnsaveRecipe($id: ID!) {
+ unsaveRecipe(id: $id)
+}
+ `) as unknown as TypedDocumentString<
UnsaveRecipeMutation,
UnsaveRecipeMutationVariables
>;
-export const RateRecipeDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'RateRecipe' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- {
- kind: 'VariableDefinition',
- variable: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'score' },
- },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'Int' } },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rateRecipe' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'score' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'score' },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'FragmentSpread',
- name: { kind: 'Name', value: 'RecipeFields' },
- },
- ],
- },
- },
- ],
- },
- },
- {
- kind: 'FragmentDefinition',
- name: { kind: 'Name', value: 'RecipeFields' },
- typeCondition: {
- kind: 'NamedType',
- name: { kind: 'Name', value: 'Recipe' },
- },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'title' } },
- { kind: 'Field', name: { kind: 'Name', value: 'description' } },
- { kind: 'Field', name: { kind: 'Name', value: 'category' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } },
- { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } },
- { kind: 'Field', name: { kind: 'Name', value: 'visibility' } },
- { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } },
- { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } },
- { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } },
- { kind: 'Field', name: { kind: 'Name', value: 'servings' } },
- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },
- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'author' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'ingredients' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'id' } },
- { kind: 'Field', name: { kind: 'Name', value: 'name' } },
- { kind: 'Field', name: { kind: 'Name', value: 'amount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'unit' } },
- { kind: 'Field', name: { kind: 'Name', value: 'note' } },
- ],
- },
- },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'instructions' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'step' } },
- { kind: 'Field', name: { kind: 'Name', value: 'text' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'tags' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'rating' },
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- { kind: 'Field', name: { kind: 'Name', value: 'average' } },
- { kind: 'Field', name: { kind: 'Name', value: 'count' } },
- ],
- },
- },
- { kind: 'Field', name: { kind: 'Name', value: 'userRating' } },
- { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } },
- { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } },
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'isCreatedByCurrentUser' },
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode;
-export const RemoveRecipeRatingDocument = {
- kind: 'Document',
- definitions: [
- {
- kind: 'OperationDefinition',
- operation: 'mutation',
- name: { kind: 'Name', value: 'RemoveRecipeRating' },
- variableDefinitions: [
- {
- kind: 'VariableDefinition',
- variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } },
- type: {
- kind: 'NonNullType',
- type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } },
- },
- },
- ],
- selectionSet: {
- kind: 'SelectionSet',
- selections: [
- {
- kind: 'Field',
- name: { kind: 'Name', value: 'removeRecipeRating' },
- arguments: [
- {
- kind: 'Argument',
- name: { kind: 'Name', value: 'id' },
- value: {
- kind: 'Variable',
- name: { kind: 'Name', value: 'id' },
- },
- },
- ],
- },
- ],
- },
- },
- ],
-} as unknown as DocumentNode<
+export const RateRecipeDocument = new TypedDocumentString(`
+ mutation RateRecipe($id: ID!, $score: Int!) {
+ rateRecipe(id: $id, score: $score) {
+ ...RecipeFields
+ }
+}
+ fragment RecipeFields on Recipe {
+ id
+ title
+ description
+ category
+ cuisine
+ difficulty
+ visibility
+ imageUrl
+ sourceRecipeId
+ prepMinutes
+ cookMinutes
+ servings
+ createdAt
+ updatedAt
+ author {
+ id
+ name
+ }
+ ingredients {
+ id
+ name
+ amount
+ unit
+ note
+ }
+ instructions {
+ step
+ text
+ }
+ tags
+ rating {
+ average
+ count
+ }
+ userRating
+ saveCount
+ isSaved
+ isCreatedByCurrentUser
+}`) as unknown as TypedDocumentString<
+ RateRecipeMutation,
+ RateRecipeMutationVariables
+>;
+export const RemoveRecipeRatingDocument = new TypedDocumentString(`
+ mutation RemoveRecipeRating($id: ID!) {
+ removeRecipeRating(id: $id)
+}
+ `) as unknown as TypedDocumentString<
RemoveRecipeRatingMutation,
RemoveRecipeRatingMutationVariables
>;
diff --git a/contracts/operations.graphql b/contracts/operations.graphql
index da1d6c8..5683a7b 100644
--- a/contracts/operations.graphql
+++ b/contracts/operations.graphql
@@ -124,8 +124,12 @@ mutation CreateRecipe($input: RecipeInput!) {
...RecipeFields
}
}
-mutation UpdateRecipe($id: ID!, $input: RecipeInput!) {
- updateRecipe(id: $id, input: $input) {
+mutation UpdateRecipe(
+ $id: ID!
+ $input: RecipeInput!
+ $expectedUpdatedAt: String
+) {
+ updateRecipe(id: $id, input: $input, expectedUpdatedAt: $expectedUpdatedAt) {
...RecipeFields
}
}
diff --git a/deploy/apache.conf b/deploy/apache.conf
index 4b27e19..ad72ad0 100644
--- a/deploy/apache.conf
+++ b/deploy/apache.conf
@@ -5,4 +5,18 @@ Alias /project2/ /srv/t31-project2/current/apps/web/dist/
Require all granted
FallbackResource /project2/index.html
+
+ # index.html and other unhashed files: always ask for the latest deploy.
+ Header set Cache-Control "no-cache"
+
+
+ # Vite puts a content hash in every file name under assets/, so changed
+ # files always get a new URL. Browsers can keep these for a year without
+ # asking again. Location is merged after Directory, so this wins for assets.
+
+ Header set Cache-Control "public, max-age=31536000, immutable"
+
+
+# The API (/project2/api/) sets its own Cache-Control; nothing here changes it.
+# Requires mod_headers: sudo a2enmod headers && sudo systemctl reload apache2
diff --git a/docs/CREDITS.md b/docs/CREDITS.md
new file mode 100644
index 0000000..25fabd5
--- /dev/null
+++ b/docs/CREDITS.md
@@ -0,0 +1,62 @@
+# Image credits
+
+## AI-generated
+
+The pictures "recipe-fallback.webp" and "not-found-chef-hat.webp" were AI-generated with ChatGPT.
+
+## Pexels
+
+Recipe photos were sourced from [Pexels](https://www.pexels.com/) and are free to use under the Pexels License.
+
+| Image key | Photo page / ID lookup | Photographer |
+| -------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
+| `lasagna` | [Pexels #31779545](https://www.pexels.com/photo/delicious-italian-lasagna-in-black-plate-31779545/) | Adriano Bragi |
+| `cake` | [Pexels #2147834](https://www.pexels.com/photo/2147834/) | [Quang Nguyen Vinh](https://www.pexels.com/@quang-nguyen-vinh-222549/) |
+| `fish-burger` | [Pexels #15076692](https://www.pexels.com/photo/15076692/) | [Nishess Shakya](https://www.pexels.com/@nshakya/) |
+| `beef-burger` | [Pexels #8162589](https://www.pexels.com/photo/close-up-shot-of-beef-burgers-8162589/) | Vinícius Caricatte |
+| `potato-boats` | [Pexels #8250190](https://www.pexels.com/photo/potato-wedges-on-a-metal-tray-8250190/) | Julia Filirovska |
+| `baked-potatoes` | [Pexels #34495400](https://www.pexels.com/photo/loaded-baked-potato-with-cheese-and-bacon-34495400/) | Nobleseed Nobleseed |
+| `shells` | [Pexels #6955638](https://www.pexels.com/photo/6955638/) | cottonbro |
+| `shrimp-salad` | [Pexels #10875192](https://www.pexels.com/photo/seafood-based-dish-served-on-white-plate-10875192/) | Valeria Boltneva |
+| `salmon` | [Pexels #12431192](https://www.pexels.com/photo/12431192/) | [Cristian Mihaila](https://www.pexels.com/@crysnet/) |
+| `cod` | [Pexels #5713767](https://www.pexels.com/photo/5713767/) | Farhad Ibrahimzade |
+| `peanut-soup` | [Pexels #8194817](https://www.pexels.com/photo/8194817/) | [Pelageia Zelenina](https://www.pexels.com/@pelageia-zelenina-58865108/) |
+| `tomato-soup` | [Pexels #13790510](https://www.pexels.com/photo/red-soup-in-red-bowl-13790510/) | Boryslav Shoot |
+| `sweet-potato-soup` | [Pexels #539451](https://www.pexels.com/photo/539451/) | Foodie Factor |
+| `broth-soup` | [Pexels #37043949](https://www.pexels.com/photo/37043949/) | [Ilo Frey](https://www.pexels.com/@couleur/) |
+| `homemade-fries` | [Pexels #31771051](https://www.pexels.com/photo/31771051/) | [Love Deep](https://www.pexels.com/@lpfstudio023/) |
+| `fried-chicken` | [Pexels #12261162](https://www.pexels.com/photo/fried-chicken-meal-in-white-plate-12261162/) | René Roa |
+| `carrot-cake` | [Pexels #18416956](https://www.pexels.com/photo/18416956/) | [Nadin Sh](https://www.pexels.com/@nadin-sh-78971847/) |
+| `orange-cake` | [Pexels #14996603](https://www.pexels.com/photo/14996603/) | [Sylwester Ficek](https://www.pexels.com/@sylwester-ficek-154797634/) |
+| `vanilla-cake` | [Pexels #17346228](https://www.pexels.com/photo/17346228/) | [Nadin Sh](https://www.pexels.com/@nadin-sh-78971847/) |
+| `oatmeal-muffin` | [Pexels #13054437](https://www.pexels.com/photo/close-up-shot-of-a-blueberry-muffin-13054437/) | Peter Stig Michaelsen |
+| `chocolate-muffin` | [Pexels #34657337](https://www.pexels.com/photo/34657337/) | [Paulina Kłys](https://www.pexels.com/@paulina-klys-2155606640/) |
+| `bringebær-muffins` | [Pexels #33468831](https://www.pexels.com/photo/33468831/) | [Gundula Vogel](https://www.pexels.com/@guvo59/) |
+| `colored-cupcakes` | [Pexels #15896658](https://www.pexels.com/photo/15896658/) | [Vikram Pataskar](https://www.pexels.com/@thepataskar/) |
+| `beef-dinner` | [Pexels #299347](https://www.pexels.com/photo/well-done-beef-steak-and-vegetables-on-plate-299347/) | Terje Sollie |
+| `sausage` | [Pexels #27976946](https://www.pexels.com/photo/27976946/) | [Andre](https://www.pexels.com/@andre-124356440/) |
+| `pancakes` | [Pexels #37648012](https://www.pexels.com/photo/37648012/) | [Tochukwu Ekeh](https://www.pexels.com/@tochukwu-ekeh-2149052634/) |
+| `american-pancakes` | [Pexels #37648013](https://www.pexels.com/photo/37648013/) | [Tochukwu Ekeh](https://www.pexels.com/@tochukwu-ekeh-2149052634/) |
+| `slovenian-pancakes` | [Pexels #33863387](https://www.pexels.com/photo/33863387/) | [Tochukwu Ekeh](https://www.pexels.com/@tochukwu-ekeh-2149052634/) |
+| `peppered-eggs` | [Pexels #40247255](https://www.pexels.com/photo/40247255/) | drmkhawarnazir |
+| `fried-egg` | [Pexels #6294382](https://www.pexels.com/photo/delicious-breakfast-with-fried-eggs-on-wooden-board-6294382/) | Klaus Nielsen |
+| `english-breakfast` | [Pexels #4869428](https://www.pexels.com/photo/4869428/) | [Roman Odintsov](https://www.pexels.com/@roman-odintsov/) |
+| `raw-egg` | [Pexels #24206876](https://www.pexels.com/photo/24206876/) | Dee Dave |
+| `car-cake` | [Pexels #20849550](https://www.pexels.com/photo/police-car-birthday-cake-20849550/) | tran duy anh |
+| `car-wheels-cake` | [Pexels #32370610](https://www.pexels.com/photo/playful-tire-shaped-donuts-on-display-32370610/) | Jonathan Borba |
+| `car-muffin` | [Pexels #32370608](https://www.pexels.com/photo/colorful-car-themed-cake-decorations-32370608/) | Jonathan Borba |
+| `fried-sausages` | [Pexels #31533630](https://www.pexels.com/photo/crispy-fries-with-savory-sausages-on-plate-31533630/) | jean Trinidad |
+| `fish-n-chips` | [Pexels #9725989](https://www.pexels.com/photo/9725989/) | Adrian Newell |
+| `masala` | [Pexels #30748996](https://www.pexels.com/photo/30748996/) | [Anil Sharma](https://www.pexels.com/@shootsaga/) |
+| `tiki-masala` | [Pexels #20408461](https://www.pexels.com/photo/20408461/) | [Jack Baghel](https://www.pexels.com/@jack-baghel-2199968/) |
+| `grilled-cheese` | [Pexels #11256671](https://www.pexels.com/photo/11256671/) | [Tolga Aslantürk](https://www.pexels.com/@tolgaaslanturk/) |
+| `roasted-chicken` | [Pexels #19335227](https://www.pexels.com/photo/19335227/) | [Jean-Merci Nam](https://www.pexels.com/@jeanmerciofficial/) |
+| `baguette` | [Pexels #30926131](https://www.pexels.com/photo/30926131/) | [Manish Jain](https://www.pexels.com/@manish-jain-1176829519/) |
+| `chips` | [Pexels #39900576](https://www.pexels.com/photo/39900576/) | [Jahra Tasfia Reza](https://www.pexels.com/@jahratreza/) |
+| `white-cookies` | [Pexels #31116125](https://www.pexels.com/photo/delicious-homemade-sugar-cookies-piled-together-31116125/) | Kate L |
+| `gingerbread-cookies` | [Pexels #29646620](https://www.pexels.com/photo/freshly-baked-gingerbread-cookies-on-tray-29646620/) | Nathan J Hilton |
+| `chocolate-cookies` | [Pexels #14580494](https://www.pexels.com/photo/close-up-of-cookies-with-chocolate-14580494/) | maria eugenia bedoya lopez |
+| `indian-dish-with-rice` | [Pexels #6544376](https://www.pexels.com/photo/6544376/) | [Alesia Kozik](https://www.pexels.com/@alesiakozik/) |
+| `plain-rice` | [Pexels #31555433](https://www.pexels.com/photo/bowl-of-raw-rice-on-a-white-background-31555433/) | Waskyria Miranda |
+| `yellow-rice-with-chikcen` | [Pexels #10541694](https://www.pexels.com/photo/10541694/) | [eugene k](https://www.pexels.com/@eugene-k-151118282/) |
+| `roasted-coffee-beans` | [Pexels #4815956](https://www.pexels.com/photo/4815956/) | [Maksim Goncharenok](https://www.pexels.com/@maksgelatin/) |
diff --git a/docs/architecture.md b/docs/architecture.md
index 38c61f4..ed68eb9 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -4,17 +4,17 @@ React-klienten bruker en felles, typet GraphQL-klient. GraphQL Yoga validerer
forespørsler og kaller tjenester og repositories. PostgreSQL lagrer dataene.
Eierskap og synlighet kontrolleres i API-et; skjulte knapper er ikke tilgangskontroll.
-| Mappe | Ansvar |
-| --------------------- | --------------------------------------------------------------- |
-| `apps/web` | React, sider, komponenter, URL-state og klientens API-kall |
-| `apps/api` | GraphQL-skjema, resolvere, autentisering og databaseoperasjoner |
-| `apps/api/src/db` | Drizzle-skjema, databasekobling, migreringskode og seed |
-| `apps/api/migrations` | Versjonerte SQL-migrasjoner og Drizzle-metadata |
-| `apps/validation` | Delt Zod-validering for autentisering |
-| `contracts` | Klientens GraphQL-operasjoner og genererte operasjonstyper |
-| `scripts` | Typegenerering, integrasjonstester, bildeopprydding og deploy |
-| `e2e` | Playwright-tester av brukerflyter |
-| `docs` | Detaljert dokumentasjon og historikk |
+| Mappe | Ansvar |
+| --------------------- | ----------------------------------------------------------------- |
+| `apps/web` | React, sider, komponenter, URL-state og klientens API-kall |
+| `apps/api` | GraphQL-skjema, resolvere, autentisering og databaseoperasjoner |
+| `apps/api/src/db` | Drizzle-skjema, databasekobling, migreringskode og seed |
+| `apps/api/migrations` | Versjonerte SQL-migrasjoner og Drizzle-metadata |
+| `apps/validation` | Delt Zod-validering for autentisering og felles oppskriftsgrenser |
+| `contracts` | Klientens GraphQL-operasjoner og genererte operasjonstyper |
+| `scripts` | Typegenerering, integrasjonstester, bildeopprydding og deploy |
+| `e2e` | Playwright-tester av brukerflyter |
+| `docs` | Detaljert dokumentasjon og historikk |
## Hvorfor to genererte filer?
@@ -42,16 +42,20 @@ dermed ikke Drizzle som spørringsbygger i repositories. SQL-valget gir direkte
kontroll over tilgangsvilkår, aggregater og transaksjoner, men krever at SQL og
resultattyper vedlikeholdes og testes.
-Søk og filtre utføres før `LIMIT`/`OFFSET`. Det finnes indekser for blant annet
-forfatter, offentlige oppskrifters opprettingstid og relasjoner. Et stort datasett
-og målinger av spørringsplaner trengs før vi kan hevde at løsningen skalerer godt.
+Søk og filtre utføres før `LIMIT`/`OFFSET`. Ordsøk i tittel, beskrivelse, ingredienser og tagger bruker PostgreSQL-fulltekstsøk
+med GIN-indeks, og hver sortering har en indeks som matcher `ORDER BY`. Løsningen
+er målt med 100 000 genererte oppskrifter; se
+[søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet).
## Klientens dataflyt
`apps/web/src/lib/graphqlClient.ts` håndterer GraphQL-transporten.
Oppskriftsfunksjonene bruker `recipeApi.ts` og `useRecipeQuery.ts` for lesing,
avbryting av utdaterte forespørsler og oppfrisking etter mutations. URL-en beholder
-søk, filtre og sidetall. En begrenset minnecache gjenbruker oppskriftslesinger i 30 sekunder og tømmes ved brukerbytte og mutations. En separat caching-avhengighet er ikke innført;
+søk, filtre og sidetall. En begrenset minnecache gjenbruker oppskriftslesinger i 30 sekunder og tømmes ved brukerbytte og mutations.
+Når vinduet får fokus eller fanen blir synlig igjen, hentes data eldre enn 30 sekunder på nytt.
+Redigeringsskjemaet er unntatt fra denne oppfriskingen for å bevare brukerens input.
+En separat caching-avhengighet er ikke innført;
dagens avgrensede flyt testes med kontrollerte API-svar og integrasjonstester.
Tidligere mockdata brukes ikke som applikasjonens datakilde. Historiske
diff --git a/docs/auth-improvements.md b/docs/auth-improvements.md
index 2534f9b..3f8d1cb 100644
--- a/docs/auth-improvements.md
+++ b/docs/auth-improvements.md
@@ -1,7 +1,9 @@
# Auth-forbedringer
-Dette er en avgrenset auth-endring. Cookie/context-migreringen er inkludert;
-CRUD-arbeid er et eget steg.
+Dette dokumentet beskriver autentisering med sesjonscookies, delt validering
+og begrensning av innloggings- og registreringsforsøk. Oppskrifts-CRUD er også
+implementert; se [Recipe API](recipe-api.md) for oppretting, lesing, redigering
+og sletting med tilgangskontroll.
## Delt validering
diff --git a/docs/database-model.md b/docs/database-model.md
index f90830d..3f1f291 100644
--- a/docs/database-model.md
+++ b/docs/database-model.md
@@ -1,11 +1,12 @@
# Databasemodell
-Modellen bruker PostgreSQL og Drizzle i skjemaet `project2`. Brukere og sesjoner
-fra autentiseringen er beholdt. API-operasjoner kommer i neste steg.
+Modellen bruker PostgreSQL og Drizzle i skjemaet `project2`. Den brukes av
+autentisering, oppskrifts-CRUD, kokebok, vurderinger og bildehåndtering.
```mermaid
erDiagram
users ||--o{ sessions : har
+ users |o--o{ uploaded_images : laster_opp
users ||--o{ recipes : eier
recipes |o--o{ recipes : kopiert_fra
recipes ||--o{ recipe_ingredients : inneholder
@@ -18,6 +19,8 @@ erDiagram
```
`||--o{` betyr at én rad kan ha null eller flere tilknyttede rader.
+`|o--o{` tillater null eller én eier per bilde, mens en bruker kan ha null eller
+flere bilder.
| Tabell | Innhold og regler |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
@@ -29,6 +32,7 @@ erDiagram
| `recipe_tags` | Enkle tagger per oppskrift, uten duplikater. |
| `saved_recipes` | Hvilke brukere som har lagret hvilke oppskrifter. |
| `ratings` | Én vurdering mellom 1 og 5 per bruker per oppskrift. |
+| `uploaded_images` | Filnavn, eier, størrelse og opprettingstid for opplastede bilder. |
## Viktige valg
@@ -41,38 +45,44 @@ erDiagram
- `source_recipe_id` er en valgfri henvisning til originaloppskriften. Kopier er
egne oppskrifter, uavhengige av bokmerker. Ved sletting av originalen settes
henvisningen til `NULL`, mens kopien beholdes. Varig kildeattribusjon med
- lagret forfatternavn/tittel kan legges til senere.
+ lagret forfatternavn/tittel kan legges til senere. Kopiering er støttet i
+ datamodellen, men er ikke en implementert brukerfunksjon i API-et.
- `image_url` er valgfri. Selve bildefilen lagres ikke i databasen.
+- `uploaded_images.owner_id` er valgfri (`NULL`). Ved sletting av brukeren
+ settes feltet til `NULL` med `ON DELETE SET NULL`; bilderaden slettes ikke
+ av denne fremmednøkkelen.
- Ingrediensmengder bruker `numeric(12,4)`, som gir nøyaktige desimaltall med
opptil åtte sifre før komma. Drizzle/pg returnerer verdiene som strenger.
- API-et må konvertere dem til frontendens tallformat ved behov.
+ Oppskriftslesingene konverterer mengdene til tall i JSON-resultatet.
- Mengder og porsjoner må være positive. Tider kan være null, men ikke negative.
- Ingredienser og steg har en unik, positiv `position` innenfor hver oppskrift.
Hent alltid med `ORDER BY position`; databasen krever ikke sammenhengende tall.
Tom ingrediensenhet er tillatt for for eksempel «2 egg».
- Tagger lagres med små bokstaver uten innledende/avsluttende mellomrom.
-- Gjennomsnittsvurdering, antall vurderinger og antall lagringer beregnes fra
- tabellene. De lagres ikke som ekstra tellere på oppskriften.
+- Gjennomsnittsvurdering og antall vurderinger lagres som `rating_avg` og
+ `rating_count` på oppskriften og vedlikeholdes av triggere. Antall lagringer
+ beregnes fra `saved_recipes` når detaljene hentes.
- `isSaved` og `isCreatedByCurrentUser` beregnes ut fra innlogget bruker.
-- Databasetriggere oppdaterer `updated_at` ved endring av oppskrifter og
- vurderinger, også gjennom vanlig SQL. Endring av bare ingredienser, steg eller
- tagger må også oppdatere foreldreraden i den senere API-transaksjonen.
+- API-et oppdaterer foreldreraden og erstatter ingredienser, steg og tagger
+ i samme transaksjon. Triggere vedlikeholder søkevektor og vurderingsfelter
+ også ved direkte SQL-endringer; se migrasjon `0005_recipe_search_and_ratings.sql`.
## Sletting og indekser
Sletting av en oppskrift sletter automatisk ingredienser, steg, tagger, lagringer
og vurderinger. Sletting av en bruker sletter brukerens oppskrifter, sesjoner,
lagringer og vurderinger. Dette er bevisst valgt med `ON DELETE CASCADE`.
-Brukersletting bør derfor behandles som en tydelig, destruktiv handling i et
-senere API.
+Brukersletting er ikke eksponert som en funksjon i dagens API.
Indekser støtter oppslag etter forfatter, offentlige oppskrifter sortert etter
opprettelsesdato og ID, og lagringer/vurderinger per oppskrift. De sammensatte
primærnøklene støtter brukerens egne lagringer og vurderinger. Unike indekser
-støtter ordnede ingredienser og steg. Flere søke- og filterindekser bør velges
-etter at API-spørringene finnes og kan måles.
+støtter ordnede ingredienser og steg. Migrasjon 0005 legger til fulltekstsøk
+(`search_vector` med GIN-indeks), lagret vurderingssnitt (`rating_avg`,
+`rating_count`, vedlikeholdt av en trigger) og delindekser for kategori, tid og
+vurdering. Se [søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet).
-## Klar for CRUD
+## CRUD i API-et
1. **Opprett:** Bruk innlogget bruker som forfatter. Sett inn oppskrift,
ingredienser, steg og tagger i én transaksjon.
@@ -83,11 +93,11 @@ etter at API-spørringene finnes og kan måles.
innenfor samme transaksjon for å unngå midlertidige posisjonskonflikter.
4. **Slett:** Kontroller eierskap før oppskriften slettes. Databasen rydder barna.
-Bruk `INSERT ... ON CONFLICT` for idempotent lagring eller endring av en
-vurdering. Bruk `DELETE` for å fjerne lagring/vurdering. API-et må validere tilgang
-til oppskriften, og håndheve at eiere ikke vurderer eller lagrer egne oppskrifter.
-Fremmednøkler kontrollerer koblinger, ikke hvem som er innlogget. API-et må også
-kreve minst én ingrediens og ett steg dersom dette er et produktkrav.
+API-et bruker `INSERT ... ON CONFLICT` for idempotent lagring eller endring av
+en vurdering, og `DELETE` for å fjerne lagring/vurdering. Det kontrollerer tilgang
+til oppskriften og håndhever at eiere ikke vurderer eller lagrer egne oppskrifter.
+Fremmednøkler kontrollerer koblinger, ikke hvem som er innlogget. Minst én
+ingrediens og ett steg kreves og valideres før lagring.
## Migrasjon og tester
@@ -118,6 +128,5 @@ constraints; behold de håndskrevne delene ved senere endringer.
Migrasjon `0003_recipe_review.sql` gjør kjøkken valgfritt, legger til kildehenvisning
og håndhever kategorinøklene. Eksisterende kategorier normaliseres til små
-bokstaver uten ytre mellomrom. Ukjente kategorier stopper migrasjonen og m?
-korrigeres eksplisitt. `0002` er beholdt uendret. API-et må kontrollere tilgang
-til originalen ved kopiering og kopiere ingredienser/steg i samme transaksjon.
+bokstaver uten ytre mellomrom. Ukjente kategorier stopper migrasjonen og må
+korrigeres eksplisitt. `0002` er beholdt uendret.
diff --git a/docs/delivery-history.md b/docs/delivery-history.md
index 7aa8eb0..0c18c85 100644
--- a/docs/delivery-history.md
+++ b/docs/delivery-history.md
@@ -4,7 +4,7 @@ Dette dokumentet beskriver tidligere milepæler, ikke dagens funksjonalitet. Se
## Første underveislevering
-Første leveranse skal gjøre konseptet forståelig gjennom en sammenhengende prototype. Følgende skal kunne demonstreres med lokale mockdata:
+Målet for første leveranse var å gjøre konseptet forståelig gjennom en sammenhengende prototype. Følgende funksjoner inngikk i planen for demonstrasjon med lokale mockdata:
- Explore med oppskriftskort
- søk, filtrering, sortering og paginering
@@ -20,13 +20,17 @@ Første leveranse skal gjøre konseptet forståelig gjennom en sammenhengende pr
I første leveranse:
-- kommer oppskriftene fra et delt, statisk TypeScript-datasett
-- behandles søk, filtrering, sortering og paginering lokalt
-- er innlogging og registrering mocket uten ekte passordkontroll
-- lagres ikke brukerdata eller nye oppskrifter permanent i databasen
-- utføres ingen tester mot en ekstern nettverkstjeneste
-
-Mockdata ligger adskilt fra komponentene og bruker delte TypeScript-modeller. Dette gjør det mulig å erstatte den lokale datakilden med GraphQL uten å redesigne hele frontendstrukturen.
+- kom oppskriftene fra et delt, statisk TypeScript-datasett
+- ble søk, filtrering, sortering og paginering behandlet lokalt
+- var innlogging og registrering mocket uten ekte passordkontroll
+- ble ikke brukerdata eller nye oppskrifter lagret permanent i databasen
+- ble ingen tester kjørt mot en ekstern nettverkstjeneste
+
+Mockdata lå adskilt fra komponentene og brukte delte TypeScript-modeller.
+Planen for serverintegrasjon var å beholde URL-state og visningskomponentene,
+mens søk, tilgang, sortering og paginering ble flyttet til API og database.
+Den gamle Explore-integrasjonsplanen i kildekodemappen er erstattet av denne
+historiske oppsummeringen og [gjeldende integrasjonsdokumentasjon](frontend-integration.md).
## Andre underveislevering
diff --git a/docs/frontend-integration.md b/docs/frontend-integration.md
index 5fca4bb..94d16b4 100644
--- a/docs/frontend-integration.md
+++ b/docs/frontend-integration.md
@@ -6,7 +6,7 @@
- [x] Load Explore, Cookbook and recipe details from the API.
- [x] Preserve URL search, filters, scope and server pagination.
- [x] Sort by newest, shortest total cooking time or highest average rating in the backend.
-- [x] Describe search accurately as title/description search.
+- [x] Search words in titles, descriptions, ingredient names and tags; all words must match. Words of three or more characters can also match inside title words. Word-start matches appear first.
- [x] Persist Save/Unsave and refetch recipe views after successful mutations.
- [x] Remove mock saved recipes and local ratings from application state.
- [x] Cancel obsolete reads and isolate results by authenticated user.
@@ -19,7 +19,9 @@
- [x] Upload/crop JPG, PNG and WebP images to persistent server storage.
- [x] Create, update and remove the current user's persisted rating.
- [x] Replace mock-page assertions with API integration tests.
-- [x] Add a real API/PostgreSQL browser test for recipe CRUD and Save/Unsave.
+- [x] Add independent real API/PostgreSQL browser scenarios for recipes, images, ratings, privacy and Save/Unsave.
+- [x] Save and restore drafts in localStorage, scoped to the user and recipe.
+- [x] Warn before leaving unsaved edits and detect version conflicts when saving.
Review follow-up and Docker checks: [Local review test guide](review-test-guide.md).
@@ -29,24 +31,28 @@ Run `npm run check`, `npm run test:api`, `npm run test:db` and
`npm run test:e2e`. Install the browser with `npx playwright install chromium`
if needed.
-The recipe browser test requires `DATABASE_URL` (loaded from `.env` when present)
+The recipe browser scenarios require `DATABASE_URL` (loaded from `.env` when present)
and CREATE SCHEMA permission. It applies migrations to a unique temporary schema
and removes that schema afterward. Use a development/test database. Without a
-database URL, that browser test is explicitly skipped; shell/auth browser tests
+database URL, those scenarios are explicitly skipped; shell/auth browser tests
remain available.
+## Sorting choices
+
+Sorting supports newest first, shortest total cooking time and highest average
+rating. Trending is outside the current feature scope. Ratings use an unweighted
+average: every vote counts equally, with no adjustment for the number of votes.
+The interface displays the rating count alongside the average.
+
## Follow-up work
-- [ ] Add ingredient/tag search and agree on normalization rules in D3.
-- [x] Implement shortest-time and highest-rated sorting before pagination.
-- [ ] Define trending behavior independently of the old fixed mock date.
-- [x] Separate SQL card-summary reads from detail reads.
- [ ] Consider domain-error translation.
- [ ] Verify the deployed VM flow after merge and deployment.
-The draft button keeps edits in the current form only. Drafts are not persisted
-across navigation or reload. Obsolete prototype query modules and their tests
-have been removed.
+**Save draft** writes form fields to localStorage per user and recipe. Drafts
+survive navigation and reload in the same browser and are removed on sign-out.
+They are not synchronized between devices. Restoring an outdated draft prompts
+the user; an image that has been cleaned up is omitted from the restored form.
## Local rating and image checks
@@ -64,7 +70,7 @@ configured PostgreSQL database and open `http://127.0.0.1:5173/project2/`.
5. Confirm that logged-out users cannot rate or upload, and that users cannot
rate their own or private recipes.
-Ratings use the existing table. Image metadata uses the new `uploaded_images` migration. Each user has
+Ratings are stored in `ratings`, and image metadata in `uploaded_images`. Each user has
at most one rating per recipe. Removing a rating affects only that user's row.
The API accepts authenticated binary uploads at `/uploads` and serves generated
diff --git a/docs/operations.md b/docs/operations.md
index dcc11fb..322bdc7 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -6,8 +6,8 @@ med Apache foran API-et og den bygde klienten.
## Versjoner og miljø
-Bruk Node 24.x og npm 11.x. `.nvmrc`, `.node-version` og `Dockerfile.dev` angir
-referanseversjonen 24.21.0. Bruk `nvm install` og `nvm use` der nvm er tilgjengelig.
+Bruk Node 24 eller nyere og npm 11 eller nyere; prosjektet er testet med Node 24 og 26.
+`.nvmrc`, `.node-version`, CI, `Dockerfile.dev` og VM-en bruker referanseversjonen 24.21.0. Bruk `nvm install` og `nvm use` der nvm er tilgjengelig.
Lokalt kopieres `.env.example` til `.env`. På VM-en leser deploy-migrasjonen
`/etc/t31-project2.env`. Hemmeligheter skal ikke lagres i Git.
@@ -19,12 +19,16 @@ Lokalt kopieres `.env.example` til `.env`. På VM-en leser deploy-migrasjonen
| `AUTH_TRUST_PROXY` | Aktiveres bare bak det dokumenterte lokale Apache-oppsettet |
| `AUTH_COOKIE_SECURE` | `true` ved HTTPS; `false` i dagens HTTP-oppsett |
| `UPLOAD_DIR` | Absolutt, vedvarende bildemappe som API-brukeren kan skrive til |
+| `API_GRAPHIQL` | `false` slår av GraphiQL; standard er på (se README) |
Sett `UPLOAD_DIR` utenfor release-mappene på VM-en, slik at opplastede bilder
beholdes ved deploy. Apache må videresende `/project2/api/graphql` til `/graphql`
og `/project2/api/uploads` til `/uploads` på API-et. Klienten publiseres under
-`/project2/`. Eksakt Apache- og systemd-konfigurasjon administreres på VM-en og
-ligger ikke i dette repositoryet.
+`/project2/`. Oppsettene ligger i [deploy/apache.conf](../deploy/apache.conf)
+og [deploy/api.service](../deploy/api.service). De installeres og tilpasses på
+VM-en separat; deploy-skriptet erstatter ikke tjeneste- eller Apache-oppsettet.
+Apache-reglene for caching krever `mod_headers`. Systemd-filen bruker
+`/srv/t31-project2/current` og leser `/etc/t31-project2.env`.
## Tester før PR
@@ -40,7 +44,7 @@ npm run test:e2e
Database- og API-testene krever `DATABASE_URL` til en utviklings-/testdatabase og
CREATE SCHEMA-rettighet. De bruker isolerte skjemaer; API- og nettlesertestene
bruker midlertidige bildefiler. Bruk ikke produksjonsdatabasen.
-Nettlesertesten for oppskrifter hoppes over lokalt dersom `DATABASE_URL` mangler.
+Nettleserscenariene mot ekte API hoppes over lokalt dersom `DATABASE_URL` mangler.
## CI uten Docker
@@ -61,13 +65,14 @@ mangler. Den kjører `check`, `test:db`, `test:api` og Playwright.
## Migrasjoner og utrulling på VM
-PR-er kjører kvalitetssjekkene. Push til `main` kjører i tillegg deploy etter
+PR-er kjører kvalitetssjekkene i [CI-workflowen](../.github/workflows/ci.yml).
+Push til `main` kjører i tillegg deploy etter
bestått `quality`. Workflowen:
1. Pakker de testede byggene og migrasjonene som et release-artifact.
2. Installerer produksjonsavhengigheter på deploy-runneren.
3. Kjører migrasjoner med `/etc/t31-project2.env`.
-4. Kaller `scripts/deploy.sh`, som oppretter en release under
+4. Kaller [scripts/deploy.sh](../scripts/deploy.sh), som oppretter en release under
`/srv/t31-project2/releases`, oppdaterer `current` og restarter
`t31-project2-api` med systemd.
5. Kontrollerer API-ets health-query på `127.0.0.1:3001`.
diff --git a/docs/performance-and-images.md b/docs/performance-and-images.md
index c2eda90..2c2f96b 100644
--- a/docs/performance-and-images.md
+++ b/docs/performance-and-images.md
@@ -13,6 +13,71 @@ bruker gjennomsnittet av avgitte vurderinger; oppskrifter uten vurderinger komme
sist. Like resultater sorteres stabilt etter opprettingstid og ID. Sortering
utføres i SQL før `LIMIT`/`OFFSET`, slik at den gjelder hele resultatsettet.
+## Søk og skalerbarhet
+
+Listevisningene har indekser for søk og vanlige sorteringer
+(migrasjon `0005_recipe_search_and_ratings.sql`). De reduserer arbeidet ved
+oppslag og sortering, men gir ikke konstant kostnad når katalogen vokser.
+Eksakt telling må fortsatt telle alle treff, og dyp paginering med `OFFSET`
+må passere radene før den ønskede siden:
+
+- **Ordsøk:** `recipes.search_vector` er en `tsvector` av tittel,
+ beskrivelse, ingrediensnavn og tagger med GIN-indeks (PostgreSQL-fulltekstsøk,
+ konfigurasjon `simple` uten språkspesifikk bøying). Triggere oppdaterer den
+ når oppskriften, ingrediensene eller taggene endres. Søket går mot én rad per
+ oppskrift, så treff i flere ingredienser gir ikke duplikater, og antallet er
+ eksakt. Synlighetsreglene er de samme som før. Søketeksten deles i ord i
+ API-et, og alle søkeord må finnes. «Chick rice» finner «Rice with chicken»,
+ og «golden saffron» finner en
+ oppskrift med «Golden» i tittelen og safran som ingrediens.
+ Spesialtegn fjernes, så brukerinput kan ikke gi syntaksfeil. Fra migrasjon `0006` kan
+ søkeord på minst tre tegn også gi treff inni ord i tittelen.
+ «Cake» finner dermed «cupcakes» etter treff på ord som starter med «cake».
+ Valgt sortering gjelder innenfor hver gruppe. Fulltekstsøk krever ingen
+ utvidelse som `pg_trgm`, og dermed ingen ekstra databaserettigheter.
+- **Høyest vurdert:** `rating_avg` og `rating_count` lagres på oppskriften og
+ holdes oppdatert av en trigger på `ratings`. Sorteringen bruker en indeks i
+ stedet for å regne gjennomsnitt for alle treff ved hver forespørsel.
+- **Samtidige skrivinger:** triggerne låser oppskriftsraden før de regner ut
+ vurderingssnitt eller søkedokument på nytt, slik at to samtidige vurderinger
+ eller ingrediensendringer ikke overskriver hverandre med utdaterte verdier.
+ `rateRecipe` og `removeRecipeRating` tar samme eksklusive lås først, så
+ samtidige vurderinger venter på hverandre i stedet for å gi vranglås. Flyttes
+ en vurdering, ingrediens eller tagg til en annen oppskrift, oppdateres begge.
+- **Kategori og kortest tid:** egne delindekser for offentlige oppskrifter,
+ med samme rekkefølge som `ORDER BY` i spørringen.
+- Når totalantallet er 0, hoppes radspørringen over.
+
+### Målinger med 100 000 oppskrifter
+
+`npm run db:seed:large -- 100000` legger til 100 000 genererte oppskrifter
+(635 000 ingredienser, 230 000 vurderinger) basert på demooppskriftene, og
+`npm run db:seed:large -- --remove` fjerner dem igjen. **Kjør det bare mot en
+egen testdatabase, aldri mot produksjonsdatabasen** – applikasjonen faglærer
+ser skal bare vise ekte demoinnhold. Skriptet kjøres aldri av CI eller deploy. Målingene under er gjort lokalt (PostgreSQL 16 i Docker på en
+utviklermaskin), median av tre kjøringer med `EXPLAIN ANALYZE`. «Før» er de
+gamle spørringene med de nye indeksene fjernet, på de samme dataene.
+
+| Spørring (offentlige oppskrifter) | Før | Etter | Plan etter |
+| ------------------------------------ | ------ | ------ | ------------------------------------- |
+| Høyest vurdert, første side | 719 ms | 0,2 ms | `recipes_public_rating_idx` |
+| Kortest tid, første side | 84 ms | 0,2 ms | `recipes_public_total_time_idx` |
+| Søk «chicken», antall treff | 91 ms | 11 ms | `recipes_search_idx` (GIN) |
+| Søk «gingerbread», antall treff | 80 ms | 7 ms | `recipes_search_idx` (GIN) |
+| Søk uten treff, antall + første side | 352 ms | 0,2 ms | GIN-indeks; radspørring hoppes over |
+| Kategori «soup», første side | 0,3 ms | 0,2 ms | `recipes_public_category_created_idx` |
+| Nyeste, side 1000 (`OFFSET` 5994) | 61 ms | 26 ms | `recipes_public_created_idx` |
+
+«Før» søkte bare i tittel og beskrivelse; «etter» søker også i ingredienser og
+tagger. Hele GraphQL-forespørsler (API + database) tok 4–25 ms for typiske
+søk, filtre og sorteringer. Svært vanlige ord som treffer halve katalogen
+(«butter»: 49 000 treff) tok 70–100 ms, fordi et eksakt antall må telle alle
+treffene. Etter masseinnlasting kjører skriptet `VACUUM ANALYZE`; uten det
+var spørringene flere ganger tregere til autovacuum hadde ryddet. Dyp paginering med `OFFSET` vokser fortsatt
+lineært med sidetallet; markørbasert paginering (keyset) er mulig videre arbeid.
+Kombinasjoner av filter og sortering uten egen indeks (for eksempel kategori og
+høyest vurdert) bruker en av indeksene og sorterer resten.
+
## Kortlivet minnecache
Oppskriftslesinger caches i nettleserens minne i 30 sekunder, med maksimalt 40
@@ -30,42 +95,95 @@ jsdom-miljøer gir ressursmangel og tidsavbrudd. Testenes ordinære tidsgrenser
og alle testtilfellene beholdes.
Endringer gjort av andre brukere kan være opptil 30 sekunder gamle når en
-cacheoppføring gjenbrukes. En allerede åpen side oppdateres ikke automatisk ved
-andre brukeres endringer. Tilgangskontroll på serveren gjelder fortsatt for alle
-nye forespørsler. Bildeendepunktet bruker `Cache-Control: no-store` av hensyn til
-privat/offentlig synlighet. Det caches ikke av denne resultatcachen.
+cacheoppføring gjenbrukes. Når vinduet får fokus eller fanen blir synlig igjen,
+hentes data eldre enn 30 sekunder på nytt i bakgrunnen. Skjemaet for redigering
+er unntatt, slik at skrevet input beholdes. Det er ingen løpende synkronisering
+mens brukeren blir på samme side. Tilgangskontroll på serveren gjelder for alle
+nye forespørsler. Bilder caches av nettleseren, uavhengig av resultatcachen.
+
+## HTTP-caching
+
+| Ressurs | `Cache-Control` | Effekt |
+| --------------------------------------- | ------------------------------------- | -------------------------------------------------------- |
+| `/project2/assets/*` (filnavn med hash) | `public, max-age=31536000, immutable` | Lastes ned én gang; ny deploy gir nye filnavn |
+| `index.html` og øvrige filer i klienten | `no-cache` | Nettleseren spør alltid etter siste deploy |
+| Offentlige bilder (`/uploads/…`) | `public, no-cache` + `ETag` | Uendret bilde besvares med tom `304`, ikke ny nedlasting |
+| Private bilder | `private, no-cache` + `ETag` | Som over, men lagres ikke i delte mellomlagre |
+| GraphQL-svar og feil | `no-store` | Persondata og tilgangsstyrte svar lagres aldri |
+
+`ETag`-en består av filnavnet og originalens størrelse og endringstid, så
+den endres hvis en fil erstattes, for eksempel når demo-seeden kjøres på nytt.
+Varianter lages da også på nytt, og de roteres etter EXIF-orientering. Tilgangskontrollen kjører ved hver forespørsel, også når
+nettleseren bare spør om bildet er endret. Når et bilde ikke lenger har noen
+offentlig oppskriftsreferanse, avvises nye forespørsler fra brukere uten tilgang,
+også ved revalidering av en bufret kopi. Et allerede innlastet bilde kan fortsatt
+være synlig i nettleseren; endringen fjerner ikke data som allerede er mottatt.
+For brukere med tilgang slipper gjentatte besøk å laste ned uendrede bilder
+på nytt.
+
+Asset-reglene står i `deploy/apache.conf` og krever `mod_headers`
+(`sudo a2enmod headers`). Filen må legges inn i Apache på VM-en manuelt.
+
+## JavaScript-pakker
+
+Explore er landingssiden og lastes sammen med appen. Øvrige sider (innlogging,
+registrering, kokebok, detaljside og oppskriftsskjema) deles i egne filer med
+`React.lazy` og hentes først når de besøkes. GraphQL-operasjonene genereres som
+ferdige spørrestrenger (`documentMode: 'string'`), slik at nettleseren ikke
+trenger graphql-js for å sende dem. Zod lastes bare på sidene som validerer
+skjemaer.
+
+| Måling (produksjonsbygg, gzip) | Før | Etter |
+| -------------------------------- | -------- | ------- |
+| JavaScript før Explore vises | 131,8 kB | 90,1 kB |
+| Oppskriftsskjema (egen fil) | – | 13,0 kB |
+| Innlogging/registrering (felles) | – | 23,1 kB |
+
+Tallene er fra `npm run build`. De måler overført filstørrelse, ikke lastetid
+eller energibruk.
## Bilder og bærekraft
-- Fallback-bildet og 404-illustrasjonen er WebP på henholdsvis 173 440 og
- 10 392 byte. Tidligere var de til sammen 4 290 949 byte; reduksjonen er omtrent
- 96 %. Dette måler filstørrelse, ikke utslipp eller faktisk lastetid.
+- **Serverside behandling:** API-et behandler alle opplastede bilder med
+ `sharp`, uansett hva klienten har gjort: bildet roteres riktig etter
+ EXIF-orientering, skaleres til maksimalt 1600 px på lengste side og lagres
+ som WebP (kvalitet 80). Metadata som GPS-posisjon kopieres ikke. Kvotene
+ regner med den lagrede størrelsen. Eksisterende bilder og URL-er endres ikke.
+- **Varianter:** API-et lager WebP-varianter på 480 og 800 px (`?w=480`,
+ kvalitet 75) under `UPLOAD_DIR/variants/`, ved opplasting og ellers første
+ gang de etterspørres (eldre bilder). Oppskriftskort og detaljsiden bruker
+ `srcset` og `sizes`, slik at nettleseren henter størrelsen som passer
+ visningen. Et seed-bilde på 133 568 byte blir 18 192 byte i 480 px (−86 %).
+- **Livssyklus for varianter:** hver variant går gjennom samme tilgangskontroll
+ som originalen ved hver forespørsel, også når et bilde blir privat. Varianter
+ slettes sammen med originalen ved opprydding (også varianter der originalen
+ allerede mangler), og den samlede lagringsgrensen regner med varianter.
+- Fallback-bildet er skalert ned til 800 px: 51 232 byte (tidligere 173 440).
+ 404-illustrasjonen er 10 392 byte. Opprinnelig var de to til sammen
+ 4 290 949 byte. Dette måler filstørrelse, ikke utslipp eller faktisk lastetid.
- Seed inneholder 51 lokale WebP-bilder. Disse leveres av appen fremfor å
hotlinkes fra eksterne nettsider.
- Oppskriftskort bruker `loading="lazy"`, slik at nettleseren kan utsette bilder
utenfor den synlige delen av siden. Den nøyaktige terskelen bestemmes av
nettleseren.
-- Opplastingsgrensesnittet beskjærer og skalerer bilder til maksimalt 1600 px på
- lengste side før opplasting. API-et kontrollerer også filtype og størrelse.
-- Separate mobilvarianter og `srcset` for opplastede bilder er videre arbeid;
- dagens mobilvisning kan laste samme bildefil som desktop.
+- Opplastingsgrensesnittet beskjærer og skalerer bilder til maksimalt 1600 px
+ før opplasting, slik at mindre data sendes. API-et kontrollerer filtype og
+ størrelse og normaliserer bildet uansett (se over).
## Kilder og rettigheter
-Oppskriftsbildene i seed-datasettet er hentet fra [Pexels](https://www.pexels.com/),
-som bekreftet av prosjektgruppen.
-De omfattes av [Pexels-lisensen](https://www.pexels.com/license/), som tillater
-gratis bruk uten obligatorisk kreditering. Originale bildelenker og fotografnavn
-er ikke registrert i repositoryet og bør legges til for sporbarhet. Kilden til
-de faste illustrasjonene må fortsatt avklares. WebP-konvertering endrer ikke
-opphav eller lisens.
-
-| Bildesett | Plassering | Opplysninger som må bekreftes |
-| ----------------------- | ------------------------------ | ----------------------------------------------------------------------------------------- |
-| 51 seed-bilder | `apps/api/src/db/seed-images/` | Pexels, bekreftet av prosjektgruppen. Original-URL-er og fotografnavn er ikke registrert. |
-| Fallback og 404 | `apps/web/src/assets/` | Skaper/kilde og vilkår for bruk |
-| Brukeropplastede bilder | Vedvarende `UPLOAD_DIR` | Opplasteren må ha rett til å bruke innholdet |
-
-Dette dokumentet bekrefter ikke at ukjente bildekilder er klarert. Se eksisterende
-redegjørelse for verktøybruk i README; konkrete verktøynavn må bekreftes av
-gruppen, ikke utledes fra bildenes utseende.
+Oppskriftsbildene i seed-datasettet er hentet fra [Pexels](https://www.pexels.com/), som bekreftet av prosjektgruppen. Bildene omfattes av [Pexels-lisensen](https://www.pexels.com/license/), som tillater gratis bruk uten obligatorisk kreditering.
+
+[Bildekrediteringen](CREDITS.md) samler lenker til fotosidene på Pexels og fotografnavn. Den dokumenterer også at illustrasjonene `recipe-fallback.webp` og `not-found-chef-hat.webp` er generert med ChatGPT.
+
+WebP-konvertering endrer ikke bildenes opprinnelse eller gjeldende bruksvilkår.
+
+| Bildesett | Plassering | Kilder og rettigheter |
+| ----------------------- | ------------------------------ | ----------------------------------------------------------------------------------- |
+| Seed-bilder | `apps/api/src/db/seed-images/` | Hentet fra Pexels. Se fotosider og fotografnavn i [bildekrediteringen](CREDITS.md). |
+| Fallback og 404 | `apps/web/src/assets/` | Generert med ChatGPT; opphavet er dokumentert i [bildekrediteringen](CREDITS.md). |
+| Brukeropplastede bilder | Vedvarende `UPLOAD_DIR` | Opplasteren må ha nødvendige rettigheter til å bruke og dele innholdet. |
+
+Dokumentasjonen i `CREDITS.md` gir sporbarhet for de registrerte bildekildene, men innebærer ikke en selvstendig juridisk vurdering av alle mulige tredjepartsrettigheter.
+
+Se [bruk av kunstig intelligens](../README.md#bruk-av-kunstig-intelligens) for konkrete eksempler på støtte i utviklingsarbeidet og hvordan forslag kontrolleres.
diff --git a/docs/recipe-api.md b/docs/recipe-api.md
index cb939bb..6b73f27 100644
--- a/docs/recipe-api.md
+++ b/docs/recipe-api.md
@@ -1,8 +1,9 @@
-# Recipe API – Delivery 2
+# Recipe API
API-et bruker eksisterende GraphQL Yoga og
PostgreSQL-oppsett, med SQL-parametre gjennom `pg`, som autentiseringen.
-Zod validerer input; databasekontrollene beholdes. Bildeopplastingen bruker nå en egen migrasjon for filmetadata.
+Zod validerer input, og databasen håndhever integritetsregler. Bildeopplastinger
+registreres i `uploaded_images`; selve filene ligger i `UPLOAD_DIR`.
## Hurtigstart for frontend
@@ -22,22 +23,22 @@ Bruk de ferdige operasjonene i [operations.graphql](../contracts/operations.grap
og importer tilhørende dokumenter og typer fra
[generated.ts](../contracts/generated.ts). Ikke rediger den genererte filen.
-| Komponent/funksjon | Generert dokument |
-| ------------------ | --------------------------------------------- |
-| Explore | `RecipesDocument` |
-| Recipe Detail | `RecipeDocument` |
-| Add Recipe | `CreateRecipeDocument` |
-| Edit Recipe | `UpdateRecipeDocument` |
-| Slett oppskrift | `DeleteRecipeDocument` |
-| Save / Unsave | `SaveRecipeDocument` / `UnsaveRecipeDocument` |
-| Cookbook | `CookbookDocument` |
+| Komponent/funksjon | Generert dokument |
+| ------------------ | --------------------------------------------------- |
+| Explore | `RecipesDocument` |
+| Recipe Detail | `RecipeDocument` |
+| Add Recipe | `CreateRecipeDocument` |
+| Edit Recipe | `UpdateRecipeDocument` |
+| Slett oppskrift | `DeleteRecipeDocument` |
+| Save / Unsave | `SaveRecipeDocument` / `UnsaveRecipeDocument` |
+| Cookbook | `CookbookDocument` |
+| Vurdering | `RateRecipeDocument` / `RemoveRecipeRatingDocument` |
Frontend bruker nå `apps/web/src/features/recipes/recipeApi.ts` og den delte
klienten `apps/web/src/lib/graphqlClient.ts`. Eksempelet under viser transporten. Det oppretter en oppskrift for innlogget bruker.
Samme URL, headere og cookie-innstilling brukes for de øvrige operasjonene.
```ts
-import { print } from 'graphql';
import {
CreateRecipeDocument,
type CreateRecipeMutation,
@@ -56,7 +57,11 @@ export async function createRecipe(
'Content-Type': 'application/json',
'X-Requested-With': 'recipe-platform',
},
- body: JSON.stringify({ query: print(CreateRecipeDocument), variables }),
+ // Dokumentene er strenger (TypedDocumentString), ikke AST-er.
+ body: JSON.stringify({
+ query: CreateRecipeDocument.toString(),
+ variables,
+ }),
});
if (!response.ok) throw new Error('Kunne ikke kontakte API-et.');
@@ -92,8 +97,9 @@ Et gyldig `input` for eksempelet:
}
```
-`updateRecipe` krever hele samme input, i tillegg til oppskriftens `id`;
-operasjonen er ikke en delvis oppdatering. Listeoperasjoner returnerer
+`updateRecipe` krever hele samme input, i tillegg til oppskriftens `id`.
+Klienten sender også `expectedUpdatedAt` fra den hentede oppskriften; et
+avvik gir `CONFLICT`, slik at nyere endringer ikke overskrives. Listeoperasjoner returnerer
`items`, `totalCount`, `totalPages`, `page` og `pageSize`. Cookbook bruker
`scope: "all"`, `"saved"` eller `"created"`.
@@ -104,7 +110,7 @@ Explore, Cookbook, Detail og oppskriftsskjemaet bruker nå API-et. Se
## Autentisering
-Branchen er oppdatert med `dev`, som inkluderer auth-cookie-forbedringene. Auth og CRUD bruker samme
+Auth og CRUD bruker samme
GraphQL-context og HttpOnly-cookie. Serveren finner brukeren fra en gyldig,
ikke-utløpt sesjon. Forfatter og cookbook-bruker kommer alltid fra context,
aldri fra klientens bruker-ID. `currentUser` returnerer bruker eller `null`.
@@ -120,23 +126,26 @@ Cookie har HttpOnly, SameSite=Lax og Path=/; Secure aktiveres ved HTTPS.
Alle operasjonene finnes i `contracts/operations.graphql`, med genererte typer og
dokumenter i `contracts/generated.ts`. Regenerer med `npm run types:api`.
-| Operasjon | Tilgang og oppførsel |
-| ------------------------- | ----------------------------------------------------------------------------- |
-| `recipes(input)` | Offentlige oppskrifter, også for innlogget eier. |
-| `recipe(id)` | Offentlig oppskrift eller eierens private. Utilgjengelig/ukjent gir `null`. |
-| `createRecipe(input)` | Krever innlogging; lagrer hele oppskriften i én transaksjon. |
-| `updateRecipe(id, input)` | Bare eier; erstatter alle redigerbare felt og barn i én transaksjon. |
-| `deleteRecipe(id)` | Bare eier; databasen sletter tilknyttede rader automatisk. |
-| `saveRecipe(id)` | Bare innlogget bruker; offentlig oppskrift av en annen bruker; idempotent. |
-| `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. |
-| `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. |
-
-Listeinput støtter `search` (tittel/beskrivelse), `category`, `maxCookingMinutes`,
+| Operasjon | Tilgang og oppførsel |
+| -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| `recipes(input)` | Offentlige oppskrifter, også for innlogget eier. |
+| `recipe(id)` | Offentlig oppskrift eller eierens private. Utilgjengelig/ukjent gir `null`. |
+| `createRecipe(input)` | Krever innlogging; lagrer hele oppskriften i én transaksjon. |
+| `updateRecipe(id, input, expectedUpdatedAt)` | Bare eier; erstatter felt og barn atomisk og kontrollerer versjonen når den er oppgitt. |
+| `deleteRecipe(id)` | Bare eier; databasen sletter tilknyttede rader automatisk. |
+| `saveRecipe(id)` | Bare innlogget bruker; offentlig oppskrift av en annen bruker; idempotent. |
+| `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. |
+| `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. |
+| `rateRecipe(id, score)` | Innlogget bruker kan gi en annens offentlige oppskrift 1–5 stjerner; ny score erstatter egen tidligere vurdering. |
+| `removeRecipeRating(id)` | Fjerner bare egen vurdering; idempotent. |
+
+Listeinput støtter `search` (ordsøk i tittel, beskrivelse, ingredienser og tagger; alle ord må finnes, som begynnelse av ord), `category`, `maxCookingMinutes`,
`sort`, `page` og `pageSize` (1–50, standard 6). Filtrering, sortering og paginering skjer i SQL.
Standard er nyeste først. Kortest tilberedningstid og høyest vurdering støttes også, med opprettingstid og ID som stabile tie-breakere. En side utenfor området
begrenses til siste side. Tom liste har `totalPages: 0` og `page: 1`.
-Oppskriften returnerer forfatterens offentlige ID/navn, ingredienser, ordnede steg,
+Listene returnerer `RecipeSummary` med kortfelter, uten ingredienser og steg.
+`recipe(id)` returnerer forfatterens offentlige ID/navn, ingredienser, ordnede steg,
tagger, datoer, vurderingsoppsummering og brukeravhengige lagrings-/eierskapsflagg.
E-post og passordhash eksponeres ikke som oppskriftsforfatterdata.
@@ -166,39 +175,60 @@ Frontend er koblet ved de eksisterende data-grensene. Integrasjonen følger diss
- `cuisine` er nullable; en frontend-mapper må håndtere manglende verdi.
- Bruk eksisterende pending/error/not-found-mønstre og behold formdata ved feil.
-Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND` og `FORBIDDEN`.
+Feilkoder inkluderer `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND`, `FORBIDDEN`,
+`CONFLICT`, `RATE_LIMITED`, `QUOTA_EXCEEDED`, `PAYLOAD_TOO_LARGE` og `QUERY_TOO_COMPLEX`.
Ugyldige enumverdier avvises av GraphQL før resolveren kjøres; klienten må også
håndtere GraphQL-valideringsfeil uten disse domenekodene.
-Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller
-ukjente oppskrifter gir samme feil og avslører ikke private data.
-### Avtale for frontendintegrasjon og videre arbeid
+### Ressursgrenser
+
+Grensene ligger i `apps/api/src/apiLimits.ts` og kan overstyres i `createApp`
+(tester som sender mange forespørsler fra én adresse, gjør det).
+
+- **Forespørsler:** 300 GraphQL-forespørsler per klient (IP-adresse, samme
+ nøkkel som auth-begrensningen bak Apache) per minutt. Deretter svarer API-et
+ `429` med `Retry-After` og koden `RATE_LIMITED`. Grensen holdes i minnet og
+ nullstilles ved omstart. Bare forespørsler som kjører en operasjon telles
+ (POST, og GET med `query`), og først etter at CSRF-headeren
+ `X-Requested-With` (og for POST `Content-Type`) er godkjent. GET med `query`
+ uten headeren får `403`. Avviste eller operasjonsløse forespørsler (`403`,
+ `413`, GraphiQL-siden) bruker ikke opp klientens kvote, så en side på et annet
+ nettsted kan ikke tømme kvoten til en besøkende.
+- **Spørringer:** høyst 10 alias, 3 toppnivåfelt, 300 felt etter at fragmenter
+ er utvidet og 8 nivåer. Større spørringer avvises med `QUERY_TOO_COMPLEX` før
+ noen resolver kjører. Introspeksjon (`__schema`, `__type`) teller som andre
+ felt for alias, toppnivåfelt og totalt antall felt, men ikke for dybde, slik
+ at GraphiQLs standardspørring (15 nivåer, ca. 230 felt) går gjennom.
+ `__typename` teller som felt og alias (så en fragmentkjede av `__typename`
+ stoppes), men ikke som toppnivåfelt eller dybde.
+- **Størrelse:** forespørsler over 1 MB avvises med `413`. `Content-Length`
+ avviser raskt; i tillegg telles bytene som faktisk leses, slik at chunked
+ forespørsler uten `Content-Length` også stoppes.
+- **Nye oppskrifter:** høyst 30 per bruker per time (`RATE_LIMITED` med
+ `retryAfterSeconds`) og 1000 totalt (`QUOTA_EXCEEDED`). En lås per bruker
+ gjør at parallelle forespørsler telles etter hverandre. Seed og direkte
+ databaseskriving begrenses ikke. Slettede oppskrifter teller ikke.
+- **Lagring:** ingredienser, steg og tagger skrives med én `INSERT` per tabell
+ (`unnest … WITH ORDINALITY`), uansett hvor stor oppskriften er.
+ Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller
+ ukjente oppskrifter gir samme feil og avslører ikke private data.
+
+### Enums og bilder
- GraphQL bruker RecipeDifficulty, RecipeVisibility, RecipeCategory og
CookbookScope som enums. Verdiene beholder databasens små bokstaver, for
eksempel `easy`, `public`, `soup` og `saved`. JSON-variabler sendes fortsatt
som strenger, men inline enumverdier skrives uten anførselstegn. Cookbook-
operasjoner må deklarere `$scope: CookbookScope`, ikke `$scope: String`.
- Bruk de regenererte kontraktene; ingen databasemigrasjon er nødvendig.
-- Søk gjelder foreløpig bare tittel/beskrivelse. Mock-søket inkluderer også
- ingredienser/tagger og normaliserer bindestrek, understrek og mellomrom mer
- omfattende. UI-et beskriver det faktiske søkeomfanget.
- Behold søkeinput ved datagrensen; ingrediens-/taggsøk og felles
- normaliseringsregler avklares i D3 og implementeres i backend.
-- UI-et tilbyr nyeste først, kortest tilberedningstid og høyest vurdering. Sorteringen utføres i backend før paginering. Ikke sorter eller filtrer én hentet side lokalt.
+ Regenerer kontraktene med `npm run types:api` etter skjemaendringer.
- Innloggede brukere kan velge og beskjære bilder før opplasting. API-et tar
imot JPG, PNG og WebP opptil 5 MB på `/uploads` og returnerer en generert sti.
Ikke send lokale blob-/data-URL-er som imageUrl. Se lagring og lokal testløype
i [frontend integration checklist](frontend-integration.md).
-- `rateRecipe(id, score)` krever innlogging og score 1–5. Bare offentlige
- oppskrifter av andre brukere kan vurderes. Ny score erstatter egen tidligere
- vurdering. `removeRecipeRating(id)` fjerner bare egen vurdering og er
- idempotent. `userRating` er brukerens egen score eller null; `rating` er
- oppsummert gjennomsnitt og antall. Rating bruker den eksisterende tabellen.
-- Frontendintegrasjonen ligger i en egen branch etter API-endringene.
- Separate liste-/detaljspørringer i SQL og domenefeil som oversettes til
- GraphQL-feil ved resolvergrensen vurderes i senere, avgrensede endringer.
- Listeoperasjonene henter foreløpig komplette oppskrifter også i databasen.
+
+`userRating` er brukerens egen score eller `null`; `rating` er oppsummert
+gjennomsnitt og antall. Kortlistene og detaljvisningen har separate SQL-lesinger.
+Se [søk og skalerbarhet](performance-and-images.md#søk-og-skalerbarhet) for indekser og sortering.
## Lokal kontroll og seed
@@ -222,32 +252,39 @@ PostgreSQL-testdatabase som den self-hosted runneren kan nå, med CREATE
SCHEMA-rettighet. CI feiler dersom hemmeligheten mangler. Testdatabasen må
opprettes separat; workflowen krever ikke Docker. Bruk aldri produksjonsdatabasen.
-Valgfri demoseed, etter migrasjon:
+### Demoseed
-```powershell
-$env:SEED_PASSWORD = ''
-npm.cmd run db:seed
-Remove-Item Env:SEED_PASSWORD
-```
+Seeden oppretter 51 oppskrifter med ingredienser, steg, tagger og lokale
+WebP-bilder, inkludert offentlige og private oppskrifter. `demo@example.invalid`
+(Demo Cook) eier oppskriftene. Fire demobrukere legger inn vurderinger på
+offentlige oppskrifter, slik at sortering etter høyest vurdering har data.
+
+Kjør migrasjonene først. Legg deretter `SEED_PASSWORD` med et selvvalgt
+testpassord på minst 12 tegn i den lokale `.env`-filen. Passordene lagres som
+Argon2-hasher. Se [README: lokal kjøring](../README.md#kom-i-gang) for kommandoer
+for Docker, Linux/macOS og PowerShell, og
+[lokal demoinnlogging](../README.md#demodata-og-lokal-innlogging) for bruk av kontoene.
+
+Seeden kopierer bildene fra `apps/api/src/db/seed-images/` til `UPLOAD_DIR`,
+som normalt er `uploads/` i prosjektroten. Seed og API må bruke samme mappe.
+Med Docker ligger bildene i det vedvarende `recipe_images`-volumet.
+
+Faste UUID-er gjør at gjentatt kjøring oppdaterer de samme demooppskriftene.
+Innhold, ingredienser, steg, tagger og bildefiler overskrives; eksisterende
+kontopassord og vurderinger beholdes. Kjør derfor ikke seeden for å bevare
+manuelle endringer i demooppskriftene. Databaseendringene samles i én transaksjon,
+mens filkopieringen skjer utenfor databasens rollback.
+
+Seeden kjøres eksplisitt, aldri automatisk ved oppstart eller deploy. Foreleser
+kan [registrere en testkonto på VM](../README.md#tilgang-for-foreleser-på-vm)
+for å prøve funksjonene som krever innlogging; ingen VM-passord publiseres i repoet.
+
+## Avgrensninger
-Seed oppretter `demo@example.invalid`, én offentlig og én privat suppe med faste
-UUID-er og strukturerte barn i én transaksjon. Gjentatte kjøringer overskriver
-ikke eksisterende seed-rader eller passord. Kjøres eksplisitt, aldri under deploy.
-Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:seed`.
-
-## Sjekk mot Delivery 2-planen
-
-- D2-01/03: relasjoner og migrasjoner finnes allerede; kontrakter er utvidet.
-- D2-04: eksplisitt demoseed er lagt til.
-- D2-05/06/08/10: API-testmønster, autentisert context, reads/visibility og create
- er implementert, sammen med eierstyrt update/delete.
-- D2-12: persistent Save/Unsave/Cookbook er implementert.
-- D2-07/09/11/13: frontend er koblet til oppskrifts-API-et, inkludert CRUD og Save/Unsave/Cookbook.
-- D2-02/15/16: VM-deploy og full nettleserdemonstrasjon må kontrolleres etter
- integrasjon. Bruk eksisterende Apache/systemd-oppsett og `/project2/api/graphql`.
-- D2-14: ratingmutasjoner er implementert; reviews gjenstår. Avansert sortering/søk er D3.
-- Bildeopplasting er implementert; editable copies gjenstår. Databasens sourceRecipeId
- returneres, men klienten kan ikke endre kildehenvisning via vanlig CRUD-input.
+`sourceRecipeId` finnes i datamodellen og returneres i detaljer, men klienten
+kan ikke opprette en avledet kopi gjennom dagens CRUD-input. Trending og
+tekstlige anmeldelser er heller ikke implementert. Tidligere leveransebeskrivelser
+er samlet i [leveransehistorikken](delivery-history.md).
AI er brukt til plananalyse, implementasjon og tester. Endringene skal gjennomgås
i PR og kontrolleres med prosjektets sjekker og API-/databasetestene.
diff --git a/docs/review-test-guide.md b/docs/review-test-guide.md
index 41c191f..b57bdcb 100644
--- a/docs/review-test-guide.md
+++ b/docs/review-test-guide.md
@@ -6,9 +6,9 @@
docker compose -f compose.dev.yaml up --build
```
-Open **http://localhost:5173/project2/**. Startup applies the new
-`uploaded_images` migration and preserves the database and image volumes.
-Existing recipe image references are imported into the metadata table.
+Open **http://localhost:5173/project2/**. Startup applies pending database
+migrations and preserves the database and image volumes. It does not seed
+recipes automatically; see [local setup](../README.md#kom-i-gang).
Use two accounts: an owner and a reader.
## Browser checks
@@ -36,7 +36,9 @@ Use two accounts: an owner and a reader.
An image is public only while at least one public recipe references it.
Unattached uploads are visible only to their uploader; attached private
-images are visible to the recipe owner. Responses use `Cache-Control: no-store`.
+images are visible to the recipe owner. Image responses use `no-cache` with an
+`ETag` (`public` or `private`), so the access check runs on every request and an
+unchanged image is answered with an empty 304.
## Cleanup and limits
@@ -70,8 +72,8 @@ docker compose -f compose.dev.yaml exec app npm run test:db
The API tests cover privacy changes, cross-user attachment, quota limits,
legacy image migration and cleanup without touching your own recipes.
-The recipe browser test needs a host-accessible `DATABASE_URL`; it explicitly
-skips when none is configured. The unit tests cover failed background refresh,
+The recipe browser scenarios need a host-accessible `DATABASE_URL`; they explicitly
+skip when none is configured. The unit tests cover failed background refresh,
session restoration, stale responses, malformed upload JSON and form retention.
Stop with `Ctrl+C`, then `docker compose -f compose.dev.yaml down`.
diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts
new file mode 100644
index 0000000..f25bce7
--- /dev/null
+++ b/e2e/accessibility.spec.ts
@@ -0,0 +1,173 @@
+import AxeBuilder from '@axe-core/playwright';
+import { expect, test, type Page } from '@playwright/test';
+import type {
+ RecipeFieldsFragment,
+ RecipeSummaryFieldsFragment,
+} from '../contracts/generated';
+
+/*
+ * Automated WCAG checks with axe-core.
+ *
+ * The pages run against the static preview build with the GraphQL API mocked,
+ * like the smoke tests, so the checks need no database. Only WCAG 2.x A/AA
+ * rules are enforced; axe "best-practice" rules are advisory and left out.
+ * axe finds roughly a third of accessibility problems, so keyboard tests and
+ * manual checks are still needed.
+ */
+
+const WCAG_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'];
+
+const recipe: RecipeFieldsFragment = {
+ id: '11111111-1111-4111-8111-111111111111',
+ title: 'Creamy salmon pasta',
+ description: 'Weeknight pasta with salmon, lemon and dill.',
+ category: 'dinner',
+ cuisine: 'Italian',
+ difficulty: 'easy',
+ visibility: 'public',
+ imageUrl: null,
+ sourceRecipeId: null,
+ prepMinutes: 5,
+ cookMinutes: 10,
+ servings: 2,
+ createdAt: '2026-10-22T12:00:00Z',
+ updatedAt: '2026-10-22T12:00:00Z',
+ author: { id: 'chef', name: 'Chef' },
+ ingredients: [
+ { id: 'i1', name: 'Pasta', amount: 200, unit: 'g', note: null },
+ { id: 'i2', name: 'Salmon', amount: 150, unit: 'g', note: 'skinless' },
+ ],
+ instructions: [
+ { step: 1, text: 'Boil the pasta.' },
+ { step: 2, text: 'Fry the salmon and mix.' },
+ ],
+ tags: ['pasta', 'fish', 'quick'],
+ rating: { average: 4.5, count: 2 },
+ userRating: null,
+ saveCount: 3,
+ isSaved: false,
+ isCreatedByCurrentUser: false,
+};
+
+const summary: RecipeSummaryFieldsFragment = {
+ id: recipe.id,
+ title: recipe.title,
+ description: recipe.description,
+ visibility: recipe.visibility,
+ imageUrl: recipe.imageUrl,
+ prepMinutes: recipe.prepMinutes,
+ cookMinutes: recipe.cookMinutes,
+ servings: recipe.servings,
+ tags: recipe.tags,
+ rating: recipe.rating,
+ isSaved: recipe.isSaved,
+ isCreatedByCurrentUser: recipe.isCreatedByCurrentUser,
+};
+
+const recipePage = {
+ items: [summary],
+ totalCount: 1,
+ totalPages: 1,
+ page: 1,
+ pageSize: 6,
+};
+
+const user = {
+ id: 'a11y-user',
+ name: 'Axe Tester',
+ email: 'axe@example.invalid',
+};
+
+/** Answers the client's GraphQL operations with fixed data. */
+async function mockApi(page: Page, signedIn: boolean) {
+ await page.route('**/project2/api/graphql', async (route) => {
+ const body = route.request().postDataJSON() as {
+ query?: string;
+ variables?: { id?: string };
+ };
+ const query = body.query ?? '';
+ let data: Record;
+ if (query.includes('query CurrentUser')) {
+ data = { currentUser: signedIn ? user : null };
+ } else if (query.includes('query Recipes')) {
+ data = { recipes: recipePage };
+ } else if (query.includes('query Cookbook')) {
+ // A realistic cookbook entry: a recipe the signed-in user has saved.
+ data = {
+ cookbook: { ...recipePage, items: [{ ...summary, isSaved: true }] },
+ };
+ } else {
+ data = { recipe: body.variables?.id === recipe.id ? recipe : null };
+ }
+ await route.fulfill({ json: { data } });
+ });
+}
+
+// `ready`: a recipe link that only exists once the page's data has loaded,
+// so the scan covers the rendered results, not the loading state.
+const pages: {
+ path: string;
+ heading: string;
+ signedIn: boolean;
+ ready?: string;
+}[] = [
+ {
+ path: '.',
+ heading: 'Explore Recipes',
+ signedIn: false,
+ ready: recipe.title,
+ },
+ { path: `recipes/${recipe.id}`, heading: recipe.title, signedIn: false },
+ {
+ path: 'recipes/00000000-0000-4000-8000-000000000000',
+ heading: 'Recipe not found',
+ signedIn: false,
+ },
+ { path: 'login', heading: 'Log in', signedIn: false },
+ { path: 'register', heading: 'Register', signedIn: false },
+ { path: 'does-not-exist', heading: 'Page not found', signedIn: false },
+ {
+ path: 'cookbook',
+ heading: 'My Cookbook',
+ signedIn: true,
+ ready: recipe.title,
+ },
+ { path: 'recipes/new', heading: 'Add Recipe', signedIn: true },
+];
+
+const viewports = [
+ { name: 'desktop', width: 1280, height: 800 },
+ { name: 'mobile', width: 375, height: 812 },
+];
+
+for (const viewport of viewports) {
+ for (const target of pages) {
+ test(`${target.path} has no WCAG A/AA violations on ${viewport.name}`, async ({
+ page,
+ }) => {
+ await mockApi(page, target.signedIn);
+ await page.setViewportSize(viewport);
+ await page.goto(target.path);
+ // Wait for data to render so the scan covers the real page content.
+ await expect(
+ page.getByRole('heading', { name: target.heading }).first(),
+ ).toBeVisible();
+ if (target.ready)
+ await expect(
+ page.getByRole('link', { name: target.ready }).first(),
+ ).toBeVisible();
+
+ const results = await new AxeBuilder({ page })
+ .withTags(WCAG_TAGS)
+ .analyze();
+
+ // Print a readable summary instead of the raw axe objects on failure.
+ const violations = results.violations.map(
+ (violation) =>
+ `${violation.id} (${violation.impact}): ${violation.help} -> ` +
+ violation.nodes.map((node) => node.target.join(' ')).join(', '),
+ );
+ expect(violations).toEqual([]);
+ });
+ }
+}
diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts
index be0f6ab..d9c166b 100644
--- a/e2e/recipe-api.spec.ts
+++ b/e2e/recipe-api.spec.ts
@@ -5,10 +5,19 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Pool } from 'pg';
-import { expect, test, type BrowserContext, type Page } from '@playwright/test';
+import sharp from 'sharp';
+import {
+ expect,
+ test,
+ type Browser,
+ type BrowserContext,
+ type Page,
+} from '@playwright/test';
import { createApp } from '../apps/api/src/app.js';
import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js';
import { createAuthService } from '../apps/api/src/features/auth/authService.js';
+import { createRecipeRepository } from '../apps/api/src/features/recipes/recipeRepository.js';
+import { createImageStore } from '../apps/api/src/features/recipes/imageStore.js';
if (existsSync('.env')) process.loadEnvFile('.env');
test.skip(
@@ -47,6 +56,10 @@ test.beforeAll(async () => {
false,
{ pool, schema },
imageDirectory,
+ false,
+ // Every scenario's browser requests come from 127.0.0.1, so the
+ // per-client request limit would count them all together.
+ { requestsPerMinute: 10_000 },
),
);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
@@ -95,16 +108,77 @@ async function register(page: Page, email: string) {
).toBeVisible();
}
-test('persists recipes, uploaded images and ratings through the real API', async ({
- page,
- context,
- browser,
-}) => {
- test.setTimeout(90000);
+/*
+ * Independent scenarios. Each creates its own users and recipes, so a
+ * failure points at one feature and does not hide the rest. Users are
+ * created through the auth service (registration through the UI is rate
+ * limited to 5 per minute per IP) and get a real session cookie; the
+ * end-to-end journey at the bottom still registers through the UI.
+ */
+async function signedIn(browser: Browser, name: string) {
+ const { user, sessionToken } = await createAuthService(
+ createAuthRepository(pool, pool, schema),
+ ).register(name, `${randomUUID()}@example.com`, 'browser-test-password');
+ const context = await browser.newContext({
+ baseURL: 'http://127.0.0.1:4173/project2/',
+ });
await connect(context);
- await register(page, 'owner@example.com');
+ await context.addCookies([
+ {
+ name: 't31_project2_session',
+ value: sessionToken,
+ domain: '127.0.0.1',
+ path: '/',
+ httpOnly: true,
+ sameSite: 'Lax',
+ },
+ ]);
+ return { user, context, page: await context.newPage() };
+}
+
+/** Stores a PNG as an upload of the user, as the upload API would. */
+async function uploadImage(userId: string) {
+ // Realistically sized: the page uses srcset width descriptors, and the
+ // browser scales naturalWidth by the chosen density, so a 1 px image
+ // would report 0 even when it loads.
+ const png = await sharp({
+ create: { width: 600, height: 400, channels: 3, background: '#f9a825' },
+ })
+ .png()
+ .toBuffer();
+ return createImageStore(pool, schema, imageDirectory).upload(userId, png);
+}
+
+/** Creates a public recipe directly in the database for a scenario. */
+async function createRecipe(
+ authorId: string,
+ title: string,
+ imageUrl: string | null = null,
+) {
+ const recipe = await createRecipeRepository(pool, schema).create(
+ {
+ title,
+ description: 'Created for a browser test.',
+ imageUrl,
+ category: 'soup',
+ cuisine: null,
+ difficulty: 'easy',
+ visibility: 'public',
+ prepMinutes: 5,
+ cookMinutes: 10,
+ servings: 2,
+ ingredients: [{ name: 'Water', amount: 1, unit: 'l', note: null }],
+ instructions: ['Boil water.'],
+ tags: [],
+ },
+ authorId,
+ );
+ return `recipes/${recipe.id}`;
+}
+
+async function fillRecipeForm(page: Page, title: string) {
await page.goto('recipes/new');
- await page.getByLabel(/Recipe title/).fill('Browser soup');
+ await page.getByLabel(/Recipe title/).fill(title);
await page.getByLabel(/Preparation time/).fill('5');
await page.getByLabel(/Cooking time/).fill('10');
await page.getByLabel(/Difficulty/).selectOption('medium');
@@ -114,127 +188,316 @@ test('persists recipes, uploaded images and ratings through the real API', async
await page.getByLabel('Ingredient 1 amount').fill('1');
await page.getByLabel('Ingredient 1 unit').selectOption('l');
await page.getByLabel('Step 1', { exact: true }).fill('Boil water.');
- const image = await page.evaluate(() => {
- const canvas = document.createElement('canvas');
- canvas.width = 300;
- canvas.height = 200;
- const context = canvas.getContext('2d')!;
- context.fillStyle = '#f9a825';
- context.fillRect(0, 0, 300, 200);
- return canvas.toDataURL('image/png').split(',')[1]!;
- });
- await page
- .getByLabel('Upload a recipe image', { exact: true })
- .setInputFiles({
- name: 'soup.png',
- mimeType: 'image/png',
- buffer: Buffer.from(image, 'base64'),
+}
+
+test('publishes a recipe with an uploaded image that persists, then removes the image', async ({
+ browser,
+}) => {
+ const owner = await signedIn(browser, 'Image Chef');
+ const { page } = owner;
+ try {
+ await fillRecipeForm(page, 'Browser soup');
+ const image = await page.evaluate(() => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 300;
+ canvas.height = 200;
+ const context = canvas.getContext('2d')!;
+ context.fillStyle = '#f9a825';
+ context.fillRect(0, 0, 300, 200);
+ return canvas.toDataURL('image/png').split(',')[1]!;
});
- await page.getByRole('button', { name: 'Use image' }).click();
- await expect(page.getByRole('img', { name: 'Recipe preview' })).toBeVisible();
- await page.getByRole('button', { name: 'Publish recipe' }).click();
- await expect(
- page.getByRole('heading', { name: 'Browser soup' }),
- ).toBeVisible();
- const recipeUrl = page.url();
- await page.reload();
- await expect(
- page.getByRole('heading', { name: 'Browser soup' }),
- ).toBeVisible();
- await expect(
- page.getByRole('img', { name: 'Browser soup', exact: true }),
- ).toBeVisible();
- expect(
await page
- .getByRole('img', { name: 'Browser soup', exact: true })
- .evaluate((image: HTMLImageElement) => image.naturalWidth),
- ).toBeGreaterThan(0);
- await page.getByRole('link', { name: 'Edit Recipe' }).click();
- await page.getByLabel(/Recipe title/).fill('Edited browser soup');
- await page.getByRole('button', { name: 'Save changes' }).click();
- await expect(
- page.getByRole('heading', { name: 'Edited browser soup' }),
- ).toBeVisible();
+ .getByLabel('Upload a recipe image', { exact: true })
+ .setInputFiles({
+ name: 'soup.png',
+ mimeType: 'image/png',
+ buffer: Buffer.from(image, 'base64'),
+ });
+ await page.getByRole('button', { name: 'Use image' }).click();
+ await expect(
+ page.getByRole('img', { name: 'Recipe preview' }),
+ ).toBeVisible();
+ await page.getByRole('button', { name: 'Publish recipe' }).click();
+ await expect(
+ page.getByRole('heading', { name: 'Browser soup' }),
+ ).toBeVisible();
+ await page.reload();
+ const shown = page.getByRole('img', { name: 'Browser soup', exact: true });
+ await expect(shown).toBeVisible();
+ // Poll: the element can be visible before the image has finished loading.
+ await expect
+ .poll(() =>
+ shown.evaluate((element: HTMLImageElement) => element.naturalWidth),
+ )
+ .toBeGreaterThan(0);
- const readerContext = await browser.newContext({
- baseURL: 'http://127.0.0.1:4173/project2/',
- });
+ await page.getByRole('link', { name: 'Edit Recipe' }).click();
+ await page.getByRole('button', { name: 'Remove image' }).click();
+ await page.getByRole('button', { name: 'Save changes' }).click();
+ await expect(
+ page.getByRole('heading', { name: 'Browser soup' }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole('img', { name: 'Browser soup', exact: true }),
+ ).toHaveCount(0);
+ } finally {
+ await owner.context.close();
+ }
+});
+
+test('edits a recipe, keeping its uploaded image, and another user saves the edited recipe', async ({
+ browser,
+}) => {
+ const owner = await signedIn(browser, 'Editing Chef');
+ const reader = await signedIn(browser, 'Edited Reader');
+ const page = owner.page;
+ /** The recipe's image, loaded from the server (not a broken image). */
+ async function expectImage(title: string) {
+ const image = page.getByRole('img', { name: title, exact: true });
+ await expect(image).toBeVisible();
+ await expect
+ .poll(() =>
+ image.evaluate((element: HTMLImageElement) => element.naturalWidth),
+ )
+ .toBeGreaterThan(0);
+ return image.getAttribute('src');
+ }
try {
- await connect(readerContext);
- const reader = await readerContext.newPage();
- await register(reader, 'reader@example.com');
- await reader.goto(recipeUrl);
- await reader.getByRole('button', { name: 'Increase servings' }).click();
- await reader
+ const imageUrl = await uploadImage(owner.user.id);
+ const recipeUrl = await createRecipe(
+ owner.user.id,
+ 'Soup to edit',
+ imageUrl,
+ );
+ await page.goto(recipeUrl);
+ const before = await expectImage('Soup to edit');
+ await page.getByRole('link', { name: 'Edit Recipe' }).click();
+ // The editor shows the existing image; editing only the title keeps it.
+ await expect(
+ page.getByRole('img', { name: 'Recipe preview' }),
+ ).toBeVisible();
+ await page.getByLabel(/Recipe title/).fill('Edited browser soup');
+ await page.getByRole('button', { name: 'Save changes' }).click();
+ // Wait for the save to finish before reloading.
+ await expect(
+ page.getByRole('heading', { name: 'Edited browser soup' }),
+ ).toBeVisible();
+ await page.reload();
+ await expect(
+ page.getByRole('heading', { name: 'Edited browser soup' }),
+ ).toBeVisible();
+ expect(await expectImage('Edited browser soup')).toBe(before);
+
+ await page.getByRole('link', { name: 'Back to My Cookbook' }).click();
+ await expect(page).toHaveURL(/\/cookbook$/);
+ await expect(
+ page.getByRole('link', { name: 'Edited browser soup' }),
+ ).toBeVisible();
+
+ // Another user saves the edited recipe and sees its new title in
+ // My Cookbook, not the old one.
+ await reader.page.goto(recipeUrl);
+ await reader.page.getByRole('button', { name: 'Save to Cookbook' }).click();
+ await expect(
+ reader.page.getByRole('button', { name: 'Saved', exact: true }),
+ ).toBeVisible();
+ await reader.page.goto('cookbook?view=saved');
+ await expect(
+ reader.page.getByRole('link', { name: 'Edited browser soup' }),
+ ).toBeVisible();
+ await expect(
+ reader.page.getByRole('link', { name: 'Soup to edit' }),
+ ).toHaveCount(0);
+ } finally {
+ await owner.context.close();
+ await reader.context.close();
+ }
+});
+
+test('another user rates a recipe, changes and removes the rating, saving right after each', async ({
+ browser,
+}) => {
+ const owner = await signedIn(browser, 'Rated Chef');
+ const reader = await signedIn(browser, 'Rating Reader');
+ try {
+ const recipeUrl = await createRecipe(owner.user.id, 'Soup to rate');
+ const page = reader.page;
+ await page.goto(recipeUrl);
+ await page
+ .getByRole('button', { name: 'Increase servings' })
+ .first()
+ .click();
+ await page
.getByRole('button', { name: 'Rate this recipe', exact: true })
.click();
- await reader.getByRole('radio', { name: '5 stars' }).check();
- await reader.getByRole('button', { name: 'Save rating' }).click();
+ await page.getByRole('radio', { name: '5 stars' }).check();
+ await page.getByRole('button', { name: 'Save rating' }).click();
await expect(
- reader.getByText('Rating saved.', { exact: true }),
+ page.getByText('Rating saved.', { exact: true }),
).toBeVisible();
+ // Rating does not reset the chosen servings.
await expect(
- reader
+ page
.getByRole('region', { name: 'Ingredients' })
.getByText('3 servings', { exact: true }),
).toBeVisible();
+ await page.reload();
+ await page.getByRole('button', { name: 'Your rating: 5/5' }).click();
+ await page.getByRole('radio', { name: '3 stars' }).check();
+ await page.getByRole('button', { name: 'Save rating' }).click();
+ // Saving straight after changing the rating keeps both.
+ await page.getByRole('button', { name: 'Save to Cookbook' }).click();
await expect(
- reader.getByRole('button', { name: 'Your rating: 5/5' }),
+ page.getByRole('button', { name: 'Saved', exact: true }),
).toBeVisible();
- await reader.reload();
- await reader.getByRole('button', { name: 'Your rating: 5/5' }).click();
- await reader.getByRole('radio', { name: '3 stars' }).check();
- await reader.getByRole('button', { name: 'Save rating' }).click();
- await reader.getByRole('button', { name: 'Your rating: 3/5' }).click();
- await reader.getByRole('button', { name: 'Remove rating' }).click();
await expect(
- reader.getByRole('button', { name: 'Rate Recipe' }),
+ page.getByRole('button', { name: 'Your rating: 3/5' }),
).toBeVisible();
- await reader.getByRole('button', { name: 'Save to Cookbook' }).click();
+
+ await page.getByRole('button', { name: 'Your rating: 3/5' }).click();
+ await page.getByRole('button', { name: 'Remove rating' }).click();
await expect(
- reader.getByRole('button', { name: 'Saved', exact: true }),
+ page.getByRole('button', { name: 'Rate Recipe' }),
).toBeVisible();
- await reader.goto('cookbook?view=saved');
+ // Unsaving and saving again straight after removing the rating.
+ await page.getByRole('button', { name: 'Saved', exact: true }).click();
+ await page.getByRole('button', { name: 'Unsave', exact: true }).click();
+ await page.getByRole('button', { name: 'Save to Cookbook' }).click();
await expect(
- reader.getByRole('link', { name: 'Edited browser soup' }),
+ page.getByRole('button', { name: 'Saved', exact: true }),
).toBeVisible();
- await reader
- .getByRole('button', {
- name: 'Remove Edited browser soup from My Cookbook',
- })
- .click();
- await reader.getByRole('button', { name: 'Unsave', exact: true }).click();
await expect(
- reader.getByRole('heading', { name: 'No saved recipes yet' }),
+ page.getByRole('button', { name: 'Rate Recipe' }),
).toBeVisible();
- await page.getByRole('link', { name: 'Edit Recipe' }).click();
- await page.getByRole('button', { name: 'Remove image' }).click();
- await page.getByLabel('Private', { exact: true }).check();
- await page.getByRole('button', { name: 'Save changes' }).click();
+ // Both are persisted: saved, and no rating.
+ await page.reload();
await expect(
- page.getByRole('heading', { name: 'Edited browser soup' }),
+ page.getByRole('button', { name: 'Saved', exact: true }),
).toBeVisible();
await expect(
- page.getByRole('img', { name: 'Edited browser soup', exact: true }),
- ).toHaveCount(0);
- await reader.goto(recipeUrl);
+ page.getByRole('button', { name: 'Rate Recipe' }),
+ ).toBeVisible();
+ } finally {
+ await owner.context.close();
+ await reader.context.close();
+ }
+});
+
+test('another user saves a recipe to My Cookbook and unsaves it there', async ({
+ browser,
+}) => {
+ const owner = await signedIn(browser, 'Saved Chef');
+ const reader = await signedIn(browser, 'Saving Reader');
+ try {
+ const recipeUrl = await createRecipe(owner.user.id, 'Soup to save');
+ const page = reader.page;
+ await page.goto(recipeUrl);
+ await page.getByRole('button', { name: 'Save to Cookbook' }).click();
await expect(
- reader.getByRole('heading', { name: 'Recipe not found' }),
+ page.getByRole('button', { name: 'Saved', exact: true }),
+ ).toBeVisible();
+ await page.goto('cookbook?view=saved');
+ await expect(
+ page.getByRole('link', { name: 'Soup to save' }),
).toBeVisible();
await page
+ .getByRole('button', { name: 'Remove Soup to save from My Cookbook' })
+ .click();
+ await page.getByRole('button', { name: 'Unsave', exact: true }).click();
+ await expect(
+ page.getByRole('heading', { name: 'No saved recipes yet' }),
+ ).toBeVisible();
+ } finally {
+ await owner.context.close();
+ await reader.context.close();
+ }
+});
+
+test('a private recipe is hidden from other users, and a deleted recipe is gone', async ({
+ browser,
+}) => {
+ const owner = await signedIn(browser, 'Private Chef');
+ const reader = await signedIn(browser, 'Curious Reader');
+ try {
+ const recipeUrl = await createRecipe(owner.user.id, 'Secret soup');
+ await owner.page.goto(recipeUrl);
+ await owner.page.getByRole('link', { name: 'Edit Recipe' }).click();
+ await owner.page.getByLabel('Private', { exact: true }).check();
+ await owner.page.getByRole('button', { name: 'Save changes' }).click();
+ await expect(
+ owner.page.getByRole('heading', { name: 'Secret soup' }),
+ ).toBeVisible();
+ await reader.page.goto(recipeUrl);
+ await expect(
+ reader.page.getByRole('heading', { name: 'Recipe not found' }),
+ ).toBeVisible();
+ await owner.page
.getByRole('button', { name: 'Delete Recipe', exact: true })
.click();
- await page
+ await owner.page
.getByRole('button', { name: 'Delete recipe', exact: true })
.click();
await expect(
- page.getByRole('heading', { name: 'My Cookbook' }),
+ owner.page.getByRole('heading', { name: 'My Cookbook' }),
).toBeVisible();
- await page.goto(recipeUrl);
+ await owner.page.goto(recipeUrl);
+ await expect(
+ owner.page.getByRole('heading', { name: 'Recipe not found' }),
+ ).toBeVisible();
+ } finally {
+ await owner.context.close();
+ await reader.context.close();
+ }
+});
+
+test('end-to-end journey: register, publish, find it in Explore, and another user saves it', async ({
+ page,
+ context,
+ browser,
+}) => {
+ test.setTimeout(60000);
+ const title = `Journey soup ${randomUUID().slice(0, 8)}`;
+ await connect(context);
+ await register(page, `${randomUUID()}@example.com`);
+ await fillRecipeForm(page, title);
+ await page.getByRole('button', { name: 'Publish recipe' }).click();
+ await expect(page.getByRole('heading', { name: title })).toBeVisible();
+
+ await page.getByRole('link', { name: 'Back to My Cookbook' }).click();
+ await expect(page).toHaveURL(/\/cookbook$/);
+ await expect(page.getByRole('link', { name: title })).toBeVisible();
+
+ const readerContext = await browser.newContext({
+ baseURL: 'http://127.0.0.1:4173/project2/',
+ });
+ try {
+ await connect(readerContext);
+ const reader = await readerContext.newPage();
+ await register(reader, `${randomUUID()}@example.com`);
+ // The new recipe is already on the first Explore page, so first check
+ // that searching filters it out; only then is finding it meaningful.
+ await expect(reader.getByRole('link', { name: title })).toBeVisible();
+ await reader.getByRole('searchbox').fill('unrelated porridge');
+ await reader.getByRole('searchbox').press('Enter');
+ // Wait for the search result itself: while results load, the old list
+ // is gone too, so a missing link alone would prove nothing.
await expect(
- page.getByRole('heading', { name: 'Recipe not found' }),
+ reader.getByRole('heading', {
+ name: 'No recipes found for “unrelated porridge”',
+ }),
).toBeVisible();
+ await expect(reader.getByRole('link', { name: title })).toHaveCount(0);
+ await reader.getByRole('searchbox').fill(title);
+ await reader.getByRole('searchbox').press('Enter');
+ await reader.getByRole('link', { name: title }).click();
+ await expect(reader.getByRole('heading', { name: title })).toBeVisible();
+ await reader.getByRole('button', { name: 'Save to Cookbook' }).click();
+ await expect(
+ reader.getByRole('button', { name: 'Saved', exact: true }),
+ ).toBeVisible();
+ await reader.goto('cookbook?view=saved');
+ await expect(reader.getByRole('link', { name: title })).toBeVisible();
} finally {
await readerContext.close();
}
diff --git a/e2e/recipe-usability.spec.ts b/e2e/recipe-usability.spec.ts
new file mode 100644
index 0000000..4d18b47
--- /dev/null
+++ b/e2e/recipe-usability.spec.ts
@@ -0,0 +1,432 @@
+import { expect, test, type Page, type Locator } from '@playwright/test';
+import type { RecipeFieldsFragment } from '../contracts/generated';
+
+const id = '11111111-1111-4111-8111-111111111111';
+const user = {
+ id: '22222222-2222-4222-8222-222222222222',
+ name: 'Chef',
+ email: 'chef@example.com',
+};
+const recipe: RecipeFieldsFragment = {
+ id,
+ title: 'Usability soup',
+ description: 'A simple soup',
+ category: 'soup',
+ cuisine: null,
+ difficulty: 'easy',
+ visibility: 'private',
+ imageUrl: null,
+ sourceRecipeId: null,
+ prepMinutes: 5,
+ cookMinutes: 10,
+ servings: 2,
+ createdAt: '2026-10-22T12:00:00Z',
+ updatedAt: '2026-10-22T12:00:00Z',
+ author: user,
+ ingredients: Array.from({ length: 8 }, (_, i) => ({
+ id: `ingredient-${i}`,
+ name: `Ingredient ${i + 1}`,
+ amount: 1,
+ unit: 'g',
+ note: null,
+ })),
+ instructions: Array.from({ length: 8 }, (_, i) => ({
+ step: i + 1,
+ text: `Prepare step ${i + 1}.`,
+ })),
+ tags: [],
+ rating: { average: 0, count: 0 },
+ userRating: null,
+ saveCount: 0,
+ isSaved: false,
+ isCreatedByCurrentUser: true,
+};
+
+async function mockApi(page: Page, signedIn = true) {
+ let authenticated = signedIn;
+ const limits: Array = [];
+ await page.route('**/project2/api/graphql', async (route) => {
+ const { query, variables } = route.request().postDataJSON() as {
+ query: string;
+ variables: { input?: { maxCookingMinutes?: number | null } };
+ };
+ let data;
+ if (query.includes('mutation Login')) {
+ authenticated = true;
+ data = { login: { user } };
+ } else if (query.includes('currentUser'))
+ data = { currentUser: authenticated ? user : null };
+ else if (
+ query.includes('query Recipes') ||
+ query.includes('query Cookbook')
+ ) {
+ limits.push(variables.input?.maxCookingMinutes ?? null);
+ const list = {
+ items: [
+ {
+ ...recipe,
+ title:
+ variables.input?.maxCookingMinutes == null
+ ? 'All time recipes'
+ : 'Time filtered recipes',
+ },
+ ],
+ totalCount: 1,
+ totalPages: 1,
+ page: 1,
+ pageSize: 6,
+ };
+ data = { recipes: list, cookbook: list };
+ } else data = { recipe: authenticated ? recipe : null };
+ await route.fulfill({ json: { data } });
+ });
+ return limits;
+}
+
+async function expectFieldVisibleBelowHeader(page: Page, input: Locator) {
+ await expect(input).toBeFocused();
+ const bounds = await input.locator('..').boundingBox();
+ const headerBottom = await page
+ .locator('.site-header')
+ .evaluate((el) => el.getBoundingClientRect().bottom);
+ expect(bounds).not.toBeNull();
+ expect(bounds!.y).toBeGreaterThanOrEqual(headerBottom);
+ expect(bounds!.y + bounds!.height).toBeLessThanOrEqual(
+ page.viewportSize()!.height,
+ );
+}
+
+for (const viewport of [
+ { width: 1280, height: 800 },
+ { width: 390, height: 844 },
+]) {
+ test(`editor feedback and later ingredient validation are visible at ${viewport.width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize(viewport);
+ await mockApi(page);
+ await page.goto(`recipes/${id}/edit`);
+ const amount = page.getByRole('spinbutton', {
+ name: 'Ingredient 7 amount',
+ exact: true,
+ });
+ await amount.fill('0');
+ await page.getByRole('button', { name: 'Save changes' }).click();
+ await expectFieldVisibleBelowHeader(page, amount);
+ await page.getByRole('button', { name: 'Save changes' }).click();
+ await expectFieldVisibleBelowHeader(page, amount);
+ await page.getByRole('button', { name: 'Save draft', exact: true }).click();
+ const toast = page.locator('.recipe-create-page__toast-region');
+ await expect(toast.getByText('Draft saved', { exact: true })).toBeVisible();
+ await expect(toast).toBeInViewport();
+ await page.reload();
+ await page
+ .getByRole('button', { name: 'Discard draft', exact: true })
+ .click();
+ const dialog = page.getByRole('dialog', { name: 'Discard saved draft?' });
+ await expect(dialog).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(dialog).not.toBeVisible();
+ await expect(page.getByText('Saved draft found')).toBeVisible();
+ await page
+ .getByRole('button', { name: 'Discard draft', exact: true })
+ .click();
+ await dialog.getByRole('button', { name: 'Discard draft' }).click();
+ await expect(page.getByText('Draft discarded.')).toBeVisible();
+ });
+}
+
+for (const path of ['.', 'cookbook']) {
+ test(`desktop custom time validates, debounces, and clears on ${path}`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 1600, height: 1000 });
+ const limits = await mockApi(page);
+ await page.goto(path);
+ await expect(
+ page.getByText('1 recipe found', { exact: false }),
+ ).toBeVisible();
+ await page
+ .getByRole('combobox', { name: 'Cooking time', exact: true })
+ .selectOption('custom');
+ const input = page.getByRole('textbox', {
+ name: 'Maximum cooking time',
+ exact: true,
+ });
+ await input.fill('abc');
+ await expect(
+ page.getByText('Enter whole minutes from 1 to 20,160.'),
+ ).toBeVisible();
+ expect(limits).not.toContain(20161);
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= window.innerWidth,
+ ),
+ ).toBe(true);
+ await input.fill('20161');
+ await expect(page).toHaveURL(/maxTime=20161/);
+ await expect.poll(() => limits).toContain(20160);
+ await expect(input).toHaveValue('20161');
+ await expect(input).toHaveAttribute('aria-invalid', 'true');
+ await input.fill('');
+ await expect(page.getByText('No time limit applied.')).toHaveClass(
+ 'sr-only',
+ );
+ await expect(page).not.toHaveURL(/maxTime=/);
+ // Clearing can reuse the cached unfiltered query without another request.
+ await expect(
+ page.getByRole('heading', { name: 'All time recipes', exact: true }),
+ ).toBeVisible();
+ const search = page.getByRole('searchbox');
+ await search.fill('a'.repeat(201));
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await expect(
+ page.getByText('Use at most 200 characters for search.'),
+ ).toBeVisible();
+ await expect(page).not.toHaveURL(/q=/);
+ });
+
+ test(`mobile empty custom maximum removes the limit on ${path}`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ const limits = await mockApi(page);
+ await page.goto(path);
+ await page.getByRole('button', { name: 'Filters', exact: true }).click();
+ await page
+ .getByRole('button', { name: 'Custom maximum', exact: true })
+ .click();
+ const input = page.getByRole('textbox', {
+ name: 'Maximum cooking time in minutes',
+ });
+ await input.fill('abc');
+ await page.getByRole('button', { name: 'Apply filters' }).click();
+ await expect(
+ page.getByRole('dialog', { name: 'Filter recipes' }),
+ ).toBeVisible();
+ await expect(
+ page.getByText('Enter whole minutes from 1 to 20,160.'),
+ ).toBeVisible();
+ await input.fill('');
+ await page.getByRole('button', { name: 'Apply filters' }).click();
+ await expect(
+ page.getByRole('dialog', { name: 'Filter recipes' }),
+ ).not.toBeVisible();
+ expect(limits).not.toContain(20161);
+ await expect(
+ page.getByRole('button', { name: 'Filters', exact: true }),
+ ).toBeVisible();
+ });
+}
+
+test('a logged-out private recipe bookmark returns to the recipe after login', async ({
+ page,
+}) => {
+ await mockApi(page, false);
+ await page.goto(`recipes/${id}?view=full#ingredients`);
+ await expect(
+ page.getByRole('heading', { name: 'Recipe not found' }),
+ ).toBeVisible();
+ await page
+ .getByRole('main')
+ .getByRole('link', { name: 'Log in', exact: true })
+ .click();
+ await page.getByRole('textbox', { name: 'Email' }).fill(user.email);
+ await page.getByLabel('Password', { exact: false }).fill('secret123');
+ await page.getByRole('button', { name: 'Log in', exact: true }).click();
+ await expect(page).toHaveURL(
+ new RegExp(`recipes/${id}\\?view=full#ingredients$`),
+ );
+ await expect(
+ page.getByRole('heading', { name: 'Usability soup', exact: true }),
+ ).toBeVisible();
+});
+
+for (const path of ['.', 'cookbook']) {
+ const breakpointWidths = path === '.' ? [961, 1000] : [1153, 1200];
+ for (const width of breakpointWidths) {
+ test(`invalid time feedback fits ${path} at ${width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await mockApi(page);
+ await page.goto(path);
+ await page
+ .getByRole('combobox', { name: 'Cooking time', exact: true })
+ .selectOption('custom');
+ const input = page.getByRole('textbox', {
+ name: 'Maximum cooking time',
+ exact: true,
+ });
+ await input.fill('abc');
+ await expect(
+ page.getByText('Enter whole minutes from 1 to 20,160.'),
+ ).toBeVisible();
+ expect(
+ await page.evaluate(() => document.documentElement.scrollWidth),
+ ).toBeLessThanOrEqual(width);
+ const fieldTop = (await input.boundingBox())!.y;
+ for (const name of ['Category', 'Cooking time', 'Sort by']) {
+ const bounds = await page
+ .getByRole('combobox', { name, exact: true })
+ .boundingBox();
+ expect(Math.abs(bounds!.y - fieldTop)).toBeLessThan(1);
+ }
+ await input.fill('x'.repeat(300));
+ expect(
+ await page.evaluate(() => document.documentElement.scrollWidth),
+ ).toBeLessThanOrEqual(width);
+ });
+ }
+
+ for (const width of [390, 1280]) {
+ test(`search validation keeps its button aligned on ${path} at ${width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await mockApi(page);
+ await page.goto(path);
+ const button = page.getByRole('button', { name: 'Search', exact: true });
+ const before = await button.evaluate(
+ (el) => el.getBoundingClientRect().top + window.scrollY,
+ );
+ await page.getByRole('searchbox').fill('a'.repeat(201));
+ await expect(
+ page.getByText('Use at most 200 characters for search.'),
+ ).toBeVisible();
+ const after = await button.evaluate(
+ (el) => el.getBoundingClientRect().top + window.scrollY,
+ );
+ expect(Math.abs(after - before)).toBeLessThan(1);
+ const input = await page.getByRole('searchbox').boundingBox();
+ if (width > 704) {
+ const bounds = await button.boundingBox();
+ expect(Math.abs(bounds!.y - input!.y)).toBeLessThan(1);
+ }
+ });
+
+ for (const raw of ['abc', '1.5']) {
+ test(`bookmarked ${raw} is visible and recoverable on ${path} at ${width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ const limits = await mockApi(page);
+ await page.goto(`${path}?time=custom&maxTime=${raw}`);
+ await expect(
+ page.getByText('Invalid time filter', { exact: true }),
+ ).toBeVisible();
+ expect(limits).toEqual([]);
+ // Changing another filter must not silently discard the invalid bookmark.
+ if (width > 1000 && path === '.') {
+ await page
+ .getByRole('combobox', { name: 'Category', exact: true })
+ .selectOption('soup');
+ await expect(page).toHaveURL(new RegExp(`maxTime=${raw}`));
+ }
+ await page
+ .getByRole('button', { name: 'Edit time filter', exact: true })
+ .click();
+ const input = page.getByRole('textbox', {
+ name:
+ width === 390
+ ? 'Maximum cooking time in minutes'
+ : 'Maximum cooking time',
+ exact: true,
+ });
+ await expect(input).toBeFocused();
+ await expect(input).toHaveValue(raw);
+ await input.fill('');
+ if (width === 390)
+ await page.getByRole('button', { name: 'Apply filters' }).click();
+ await expect(page).not.toHaveURL(/maxTime=/);
+ await expect(
+ page.getByText('Invalid time filter', { exact: true }),
+ ).not.toBeVisible();
+ await expect(
+ page.getByRole('heading', { name: 'All time recipes', exact: true }),
+ ).toBeVisible();
+ expect(limits).toEqual([null]);
+ if (width !== 390) {
+ const help = page
+ .getByRole('group', {
+ name:
+ path === '.'
+ ? 'Explore filters and sorting'
+ : 'Cookbook filters and sorting',
+ })
+ .getByText('No time limit applied.', { exact: true });
+ await expect(help).toHaveClass('sr-only');
+ const bounds = await help.boundingBox();
+ expect(bounds!.width).toBeLessThanOrEqual(1);
+ expect(bounds!.height).toBeLessThanOrEqual(1);
+ }
+ });
+ }
+ }
+
+ test(`malformed limit can be replaced with valid minutes on ${path}`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 1280, height: 900 });
+ const limits = await mockApi(page);
+ await page.goto(`${path}?time=custom&maxTime=abc`);
+ await page
+ .getByRole('textbox', { name: 'Maximum cooking time', exact: true })
+ .fill('30');
+ await expect(page).toHaveURL(/maxTime=30/);
+ await expect(
+ page.getByText('Invalid time filter', { exact: true }),
+ ).not.toBeVisible();
+ await expect.poll(() => limits).toEqual([30]);
+ });
+}
+
+for (const path of ['.', 'cookbook']) {
+ for (const width of [390, 1280]) {
+ test(`numeric limits clamp to bounds on ${path} at ${width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 900 });
+ const limits = await mockApi(page);
+ await page.goto(`${path}?time=custom&maxTime=99999`);
+ await expect(page).toHaveURL(/maxTime=99999/);
+ await expect.poll(() => limits).toEqual([20160]);
+ if (width === 390)
+ await page
+ .getByRole('button', { name: 'Filters (1)', exact: true })
+ .click();
+ const input = page.getByRole('textbox', {
+ name:
+ width === 390
+ ? 'Maximum cooking time in minutes'
+ : 'Maximum cooking time',
+ exact: true,
+ });
+ await expect(input).toHaveValue('99999');
+ await expect(input).toHaveAttribute('aria-invalid', 'true');
+ await input.fill('-5');
+ if (width === 390)
+ await page
+ .getByRole('button', { name: 'Apply filters', exact: true })
+ .click();
+ else await input.blur();
+ await expect(page).toHaveURL(/maxTime=-5(?:&|$)/);
+ await expect.poll(() => limits).toEqual([20160, 1]);
+ if (width === 390)
+ await page
+ .getByRole('button', { name: 'Filters (1)', exact: true })
+ .click();
+ await expect(input).toHaveValue('-5');
+ await expect(input).toHaveAttribute('aria-invalid', 'true');
+ await expect(
+ input
+ .locator('..')
+ .getByText('Enter whole minutes from 1 to 20,160.', { exact: true }),
+ ).toBeVisible();
+
+ await expect(
+ page.getByText('Invalid time filter', { exact: true }),
+ ).not.toBeVisible();
+ });
+ }
+}
diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts
index 6b2ba23..7d8e247 100644
--- a/e2e/smoke.spec.ts
+++ b/e2e/smoke.spec.ts
@@ -76,6 +76,19 @@ async function tabTo(page: Page, target: Locator) {
await expect(target).toBeFocused();
}
+/**
+ * Chooses an option in the focused native with the keyboard only.
+ *
+ * Arrow keys behave differently per platform: on Linux and Windows they
+ * change the value, but on macOS they open the option popup instead.
+ * Type-ahead (typing the start of an option's label) changes the value on
+ * every platform, so the test stays keyboard-only and portable.
+ */
+async function chooseByTyping(page: Page, select: Locator, label: string) {
+ await expect(select).toBeFocused();
+ await page.keyboard.type(label);
+}
+
test('desktop search, category, time and sorting work using only the keyboard', async ({
page,
}) => {
@@ -93,21 +106,18 @@ test('desktop search, category, time and sorting work using only the keyboard',
});
await tabTo(page, category);
await expect(category).toHaveCSS('outline-style', 'solid');
- await page.keyboard.press('ArrowDown');
- await page.keyboard.press('Enter');
+ await chooseByTyping(page, category, 'Breakfast');
await expect(page).toHaveURL(/category=breakfast/);
const time = page.getByRole('combobox', {
name: 'Cooking time',
exact: true,
});
await tabTo(page, time);
- await page.keyboard.press('ArrowDown');
- await page.keyboard.press('Enter');
+ await chooseByTyping(page, time, '15');
await expect(page).toHaveURL(/time=lte15/);
const sort = page.getByRole('combobox', { name: 'Sort by', exact: true });
await tabTo(page, sort);
- await page.keyboard.press('End');
- await page.keyboard.press('Enter');
+ await chooseByTyping(page, sort, 'Sort by: Highest');
await expect(page).toHaveURL(/sort=highest_rated/);
});
@@ -189,13 +199,11 @@ test('Cookbook filters and sorting can be used with a keyboard', async ({
exact: true,
});
await tabTo(page, category);
- await page.keyboard.press('ArrowDown');
- await page.keyboard.press('Enter');
+ await chooseByTyping(page, category, 'Breakfast');
await expect(page).toHaveURL(/category=breakfast/);
const sort = page.getByRole('combobox', { name: 'Sort by', exact: true });
await tabTo(page, sort);
- await page.keyboard.press('End');
- await page.keyboard.press('Enter');
+ await chooseByTyping(page, sort, 'Sort by: Highest');
await expect(page).toHaveURL(/sort=highest_rated/);
await page.setViewportSize({ width: 375, height: 812 });
const mobileSort = page.getByRole('button', { name: /^Sort:/ });
@@ -248,6 +256,36 @@ test('icons stay within their controls on desktop and mobile', async ({
}
});
+test('keeps component styles above the CSS reset on code-split pages', async ({
+ page,
+}) => {
+ // Login loads as its own chunk. If its CSS were linked before the main
+ // stylesheet without the layer order in index.html, the reset's
+ // `button { color: inherit }` would win and primary buttons lose their
+ // white text.
+ await page.goto('login');
+ await expect(page.getByRole('heading', { name: 'Log in' })).toBeVisible();
+ await expect(
+ page.locator('form').getByRole('button', { name: 'Log in' }),
+ ).toHaveCSS('color', 'rgb(255, 255, 255)');
+});
+
+test('clicking anywhere on a recipe card, including its image, opens the recipe', async ({
+ page,
+}) => {
+ // The title link's ::after overlay (RecipeCard.css) covers the whole card.
+ // jsdom cannot hit-test CSS, so this is checked in a real browser.
+ await page.goto('.');
+ const image = page.locator('.recipe-card__image').first();
+ await expect(image).toBeVisible();
+ const box = (await image.boundingBox())!;
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ await expect(page).toHaveURL(/recipes\/11111111-1111-4111-8111-111111111111/);
+ await expect(
+ page.getByRole('heading', { name: 'Creamy salmon pasta' }),
+ ).toBeVisible();
+});
+
test('renders each core route through the shared shell', async ({ page }) => {
for (const [path, title] of coreRoutes) {
await page.goto(path === '/' ? '.' : path.slice(1));
@@ -356,3 +394,241 @@ test('keeps recipe-specific not-found handling separate from the global 404', as
page.getByRole('heading', { name: 'Page not found' }),
).not.toBeVisible();
});
+
+for (const viewport of [
+ { name: 'desktop', width: 1280, height: 800 },
+ { name: 'mobile', width: 390, height: 844 },
+]) {
+ test(`Jump to recipe keeps keyboard focus in the recipe (${viewport.name})`, async ({
+ page,
+ }) => {
+ await page.setViewportSize(viewport);
+ // A recipe long enough that jumping has to scroll.
+ const longRecipe: RecipeFieldsFragment = {
+ ...recipe,
+ description: 'A long description. '.repeat(30),
+ ingredients: Array.from({ length: 12 }, (_, index) => ({
+ id: `ingredient-${index}`,
+ name: `Ingredient ${index + 1}`,
+ amount: index + 1,
+ unit: 'g',
+ note: null,
+ })),
+ instructions: Array.from({ length: 8 }, (_, index) => ({
+ step: index + 1,
+ text: 'Stir and simmer for a while. '.repeat(6),
+ })),
+ };
+ await page.route('**/project2/api/graphql', async (route) => {
+ const body = route.request().postDataJSON() as { query?: string };
+ await route.fulfill({
+ json: body.query?.includes('currentUser')
+ ? { data: { currentUser: null } }
+ : { data: { recipe: longRecipe } },
+ });
+ });
+ await page.goto(`recipes/${recipe.id}`);
+ const jump = page.getByRole('button', { name: 'Jump to recipe' });
+ await jump.focus();
+ await page.keyboard.press('Enter');
+
+ // Focus lands on the visible "Adjust Servings" heading, just above the
+ // ingredients, in view and not hidden behind the sticky header.
+ const heading = page
+ .getByRole('heading', { name: 'Adjust Servings' })
+ .locator('visible=true');
+ await expect(heading).toBeFocused();
+ await expect(heading).toBeInViewport();
+ const header = await page.locator('header').first().boundingBox();
+ await expect
+ .poll(async () => (await heading.boundingBox())!.y)
+ .toBeGreaterThanOrEqual(header!.y + header!.height);
+
+ // Tab continues inside the recipe, through the servings control.
+ await page.keyboard.press('Tab');
+ await expect(
+ page
+ .getByRole('button', { name: 'Decrease servings' })
+ .locator('visible=true'),
+ ).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(
+ page.getByLabel(/^Servings/).locator('visible=true'),
+ ).toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(
+ page
+ .getByRole('button', { name: 'Increase servings' })
+ .locator('visible=true'),
+ ).toBeFocused();
+ });
+}
+
+test('skip link is the first tab stop, visible on focus, and moves focus to main', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto('.');
+ await expect(
+ page.getByRole('heading', { name: 'Explore Recipes' }),
+ ).toBeVisible();
+ const skip = page.getByRole('link', { name: 'Skip to main content' });
+ await expect(skip).not.toBeInViewport();
+ await page.keyboard.press('Tab');
+ await expect(skip).toBeFocused();
+ await expect(skip).toBeInViewport();
+ // Light text on the dark text colour: well above the 4.5:1 AA minimum.
+ await expect(skip).toHaveCSS('color', 'rgb(255, 255, 255)');
+ await expect(skip).toHaveCSS('background-color', 'rgb(15, 23, 42)');
+ await page.keyboard.press('Enter');
+ await expect(page.locator('main#main-content')).toBeFocused();
+ await expect(page).not.toHaveURL(/#main-content/);
+ // The next Tab continues inside the page content, not in the header.
+ await page.keyboard.press('Tab');
+ expect(
+ await page.evaluate(() => Boolean(document.activeElement?.closest('main'))),
+ ).toBe(true);
+});
+
+test('sets page titles and moves focus to main only when the page changes', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto('.');
+ await expect(page).toHaveTitle('Explore recipes – Recipe Platform');
+ // Searching only changes the query string: focus stays in the search box.
+ const search = page.getByRole('searchbox');
+ await search.fill('pasta');
+ await search.press('Enter');
+ await expect(page).toHaveURL(/q=pasta/);
+ await expect(search).toBeFocused();
+ // Opening a recipe is a new page: title and focus follow.
+ await page.getByRole('link', { name: 'Creamy salmon pasta' }).click();
+ await expect(page).toHaveTitle('Creamy salmon pasta – Recipe Platform');
+ await expect(page.locator('main#main-content')).toBeFocused();
+ for (const [path, title] of [
+ ['login', 'Log in'],
+ ['register', 'Register'],
+ ['recipes/42', 'Recipe not found'],
+ ['no-such-page', 'Page not found'],
+ ]) {
+ await page.goto(path);
+ await expect(page).toHaveTitle(`${title} – Recipe Platform`);
+ }
+});
+
+test('Back returns to the earlier scroll position; opening a page starts at the top', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 600 });
+ const recipes = Array.from({ length: 6 }, (_, index) => ({
+ ...recipe,
+ id: `11111111-1111-4111-8111-11111111111${index}`,
+ title: `Scroll recipe ${index + 1}`,
+ }));
+ await page.route('**/project2/api/graphql', async (route) => {
+ const body = route.request().postDataJSON() as {
+ query?: string;
+ variables?: { id?: string };
+ };
+ await route.fulfill({
+ json: body.query?.includes('currentUser')
+ ? { data: { currentUser: null } }
+ : body.query?.includes('query Recipes')
+ ? {
+ data: {
+ recipes: {
+ items: recipes,
+ totalCount: 6,
+ totalPages: 1,
+ page: 1,
+ pageSize: 6,
+ },
+ },
+ }
+ : {
+ data: {
+ recipe:
+ recipes.find((item) => item.id === body.variables?.id) ??
+ null,
+ },
+ },
+ });
+ });
+ await page.goto('.');
+ const last = page.getByRole('link', { name: 'Scroll recipe 6' });
+ await last.scrollIntoViewIfNeeded();
+ const scrolled = await page.evaluate(() => window.scrollY);
+ expect(scrolled).toBeGreaterThan(200);
+
+ await last.click();
+ await expect(
+ page.getByRole('heading', { name: 'Scroll recipe 6', level: 1 }),
+ ).toBeVisible();
+ // A new page opens at the top, with focus on main.
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ await expect(page.locator('main#main-content')).toBeFocused();
+
+ await page.goBack();
+ await expect(last).toBeVisible();
+ await expect
+ .poll(() => page.evaluate(() => window.scrollY))
+ .toBeGreaterThan(scrolled - 5);
+ expect(await page.evaluate(() => window.scrollY)).toBeLessThan(scrolled + 5);
+ await expect(page.locator('main#main-content')).toBeFocused();
+});
+
+test('after the skip link on a scrolled page, the next control is not under the header', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 700 });
+ const longRecipe: RecipeFieldsFragment = {
+ ...recipe,
+ description: 'A long description. '.repeat(40),
+ ingredients: Array.from({ length: 15 }, (_, index) => ({
+ id: `ingredient-${index}`,
+ name: `Ingredient ${index + 1}`,
+ amount: index + 1,
+ unit: 'g',
+ note: null,
+ })),
+ instructions: Array.from({ length: 10 }, (_, index) => ({
+ step: index + 1,
+ text: 'Stir and simmer for a while. '.repeat(6),
+ })),
+ };
+ await page.route('**/project2/api/graphql', async (route) => {
+ const body = route.request().postDataJSON() as { query?: string };
+ await route.fulfill({
+ json: body.query?.includes('currentUser')
+ ? { data: { currentUser: null } }
+ : { data: { recipe: longRecipe } },
+ });
+ });
+ await page.goto(`recipes/${recipe.id}`);
+ await expect(
+ page.getByRole('heading', { name: recipe.title, level: 1 }),
+ ).toBeVisible();
+ // Read the recipe, scrolled well past the header area.
+ await page.mouse.wheel(0, 2000);
+ await expect
+ .poll(() => page.evaluate(() => window.scrollY))
+ .toBeGreaterThan(500);
+
+ await page.keyboard.press('Tab');
+ await expect(
+ page.getByRole('link', { name: 'Skip to main content' }),
+ ).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(page.locator('main#main-content')).toBeFocused();
+ await page.keyboard.press('Tab');
+ // The first control in main is the recipe's Back link: focused, in view
+ // and fully below the sticky header.
+ const back = page.getByRole('link', { name: 'Back to Explore' });
+ await expect(back).toBeFocused();
+ await expect(back).toBeInViewport({ ratio: 1 });
+ const header = (await page.locator('.site-header').boundingBox())!;
+ expect((await back.boundingBox())!.y).toBeGreaterThanOrEqual(
+ header.y + header.height,
+ );
+});
diff --git a/package-lock.json b/package-lock.json
index 60476a7..524be12 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,6 +9,7 @@
"apps/*"
],
"devDependencies": {
+ "@axe-core/playwright": "4.10.2",
"@eslint/js": "9.39.5",
"@graphql-codegen/core": "6.2.0",
"@graphql-codegen/typed-document-node": "7.1.0",
@@ -37,8 +38,8 @@
"vitest": "4.0.14"
},
"engines": {
- "node": "24.x",
- "npm": "11.x"
+ "node": ">=24",
+ "npm": ">=11"
}
},
"apps/api": {
@@ -50,6 +51,7 @@
"graphql": "16.12.0",
"graphql-yoga": "5.16.2",
"pg": "8.16.3",
+ "sharp": "0.34.4",
"zod": "4.6.7"
},
"devDependencies": {
@@ -67,7 +69,6 @@
"name": "@t31/web",
"dependencies": {
"@t31/validation": "*",
- "graphql": "16.12.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-easy-crop": "6.2.4",
@@ -164,6 +165,29 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@axe-core/playwright": {
+ "version": "4.10.2",
+ "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.10.2.tgz",
+ "integrity": "sha512-6/b5BJjG6hDaRNtgzLIfKr5DfwyiLHO4+ByTLB0cJgWSM8Ll7KqtdblIS6bEkwSF642/Ex91vNqIl3GLXGlceg==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "axe-core": "~4.10.3"
+ },
+ "peerDependencies": {
+ "playwright-core": ">= 1.0.0"
+ }
+ },
+ "node_modules/@axe-core/playwright/node_modules/axe-core": {
+ "version": "4.10.3",
+ "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.10.3.tgz",
+ "integrity": "sha512-Xm7bpRXnDSX2YE2YFfBk2FnF0ep6tmG7xPh8iHee8MIcrgq762Nkce856dYtJYLkuIoYZvGfTs/PbZhideTcEg==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -558,6 +582,16 @@
"dev": true,
"license": "Apache-2.0"
},
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/@envelop/core": {
"version": "5.6.1",
"resolved": "https://registry.npmjs.org/@envelop/core/-/core-5.6.1.tgz",
@@ -2196,6 +2230,475 @@
"url": "https://github.com/sponsors/nzakas"
}
},
+ "node_modules/@img/colour": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.4.tgz",
+ "integrity": "sha512-sitdlPzDVyvmINUdJle3TNHl+AG9QcwiAMsXmccqsCOMZNIdW2/7S26w0LyU8euiLVzFBL3dXPwVCq/ODnf2vA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.4.tgz",
+ "integrity": "sha512-rZheupWIoa3+SOdF/IcUe1ah4ZDpKBGWcsPX6MT0lYniH9micvIU7HQkYTfrx5Xi8u+YqwLtxC/3vl8TQN6rMg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.3.tgz",
+ "integrity": "sha512-QzWAKo7kpHxbuHqUC28DZ9pIKpSi2ts2OJnoIGI26+HMgq92ZZ4vk8iJd4XsxN+tYfNJxzH6W62X5eTcsBymHw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.3.tgz",
+ "integrity": "sha512-Ju+g2xn1E2AKO6YBhxjj+ACcsPQRHT0bhpglxcEf+3uyPY+/gL8veniKoo96335ZaPo03bdDXMv0t+BBFAbmRA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.3.tgz",
+ "integrity": "sha512-x1uE93lyP6wEwGvgAIV0gP6zmaL/a0tGzJs/BIDDG0zeBhMnuUPm7ptxGhUbcGs4okDJrk4nxgrmxpib9g6HpA==",
+ "cpu": [
+ "arm"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.3.tgz",
+ "integrity": "sha512-I4RxkXU90cpufazhGPyVujYwfIm9Nk1QDEmiIsaPwdnm013F7RIceaCc87kAH+oUB1ezqEvC6ga4m7MSlqsJvQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.3.tgz",
+ "integrity": "sha512-Y2T7IsQvJLMCBM+pmPbM3bKT/yYJvVtLJGfCs4Sp95SjvnFIjynbjzsa7dY1fRJX45FTSfDksbTp6AGWudiyCg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.3.tgz",
+ "integrity": "sha512-RgWrs/gVU7f+K7P+KeHFaBAJlNkD1nIZuVXdQv6S+fNA6syCcoboNjsV2Pou7zNlVdNQoQUpQTk8SWDHUA3y/w==",
+ "cpu": [
+ "s390x"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.3.tgz",
+ "integrity": "sha512-3JU7LmR85K6bBiRzSUc/Ff9JBVIFVvq6bomKE0e63UXGeRw2HPVEjoJke1Yx+iU4rL7/7kUjES4dZ/81Qjhyxg==",
+ "cpu": [
+ "x64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.3.tgz",
+ "integrity": "sha512-F9q83RZ8yaCwENw1GieztSfj5msz7GGykG/BA+MOUefvER69K/ubgFHNeSyUu64amHIYKGDs4sRCMzXVj8sEyw==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.3.tgz",
+ "integrity": "sha512-U5PUY5jbc45ANM6tSJpsgqmBF/VsL6LnxJmIf11kB7J5DctHgqm0SkuXzVWtIY90GnJxKnC/JT251TDnk1fu/g==",
+ "cpu": [
+ "x64"
+ ],
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.4.tgz",
+ "integrity": "sha512-Xyam4mlqM0KkTHYVSuc6wXRmM7LGN0P12li03jAnZ3EJWZqj83+hi8Y9UxZUbxsgsK1qOEwg7O0Bc0LjqQVtxA==",
+ "cpu": [
+ "arm"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.4.tgz",
+ "integrity": "sha512-YXU1F/mN/Wu786tl72CyJjP/Ngl8mGHN1hST4BGl+hiW5jhCnV2uRVTNOcaYPs73NeT/H8Upm3y9582JVuZHrQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.4.tgz",
+ "integrity": "sha512-F4PDtF4Cy8L8hXA2p3TO6s4aDt93v+LKmpcYFLAVdkkD3hSxZzee0rh6/+94FpAynsuMpLX5h+LRsSG3rIciUQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.4.tgz",
+ "integrity": "sha512-qVrZKE9Bsnzy+myf7lFKvng6bQzhNUAYcVORq2P7bDlvmF6u2sCmK2KyEQEBdYk+u3T01pVsPrkj943T1aJAsw==",
+ "cpu": [
+ "s390x"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.4.tgz",
+ "integrity": "sha512-ZfGtcp2xS51iG79c6Vhw9CWqQC8l2Ot8dygxoDoIQPTat/Ov3qAa8qpxSrtAEAJW+UjTXc4yxCjNfxm4h6Xm2A==",
+ "cpu": [
+ "x64"
+ ],
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.4.tgz",
+ "integrity": "sha512-8hDVvW9eu4yHWnjaOOR8kHVrew1iIX+MUgwxSuH2XyYeNRtLUe4VNioSqbNkB7ZYQJj9rUTT4PyRscyk2PXFKA==",
+ "cpu": [
+ "arm64"
+ ],
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.4.tgz",
+ "integrity": "sha512-lU0aA5L8QTlfKjpDCEFOZsTYGn3AEiO6db8W5aQDxj0nQkVrZWmN3ZP9sYKWJdtq3PWPhUNlqehWyXpYDcI9Sg==",
+ "cpu": [
+ "x64"
+ ],
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.2.3"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.4.tgz",
+ "integrity": "sha512-33QL6ZO/qpRyG7woB/HUALz28WnTMI2W1jgX3Nu2bypqLIKx/QKMILLJzJjI+SIbvXdG9fUnmrxR7vbi1sTBeA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.5.0"
+ },
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.4.tgz",
+ "integrity": "sha512-2Q250do/5WXTwxW3zjsEuMSv5sUU4Tq9VThWKlU2EYLm4MB7ZeMwF+SFJutldYODXF6jzc6YEOC+VfX0SZQPqA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.4.tgz",
+ "integrity": "sha512-3ZeLue5V82dT92CNL6rsal6I2weKw1cYu+rGKm8fOCCtJTR2gYeUfY3FqUnIJsMUPIH68oS5jmZ0NiJ508YpEw==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.4.tgz",
+ "integrity": "sha512-xIyj4wpYs8J18sVN3mSQjwrw7fKUqRw+Z5rnHNCy5fYTxigBz81u5mOMPmFumwjcn8+ld1ppptMBCLic1nz6ig==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -4565,9 +5068,7 @@
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
- "dev": true,
"license": "Apache-2.0",
- "peer": true,
"engines": {
"node": ">=8"
}
@@ -8969,6 +9470,60 @@
"node": ">= 0.4"
}
},
+ "node_modules/sharp": {
+ "version": "0.34.4",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.4.tgz",
+ "integrity": "sha512-FUH39xp3SBPnxWvd5iib1X8XY7J0K0X7d93sie9CJg2PO8/7gmg89Nve6OjItK53/MlAushNNxteBYfM6DEuoA==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.0.0",
+ "detect-libc": "^2.1.0",
+ "semver": "^7.7.2"
+ },
+ "engines": {
+ "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.34.4",
+ "@img/sharp-darwin-x64": "0.34.4",
+ "@img/sharp-libvips-darwin-arm64": "1.2.3",
+ "@img/sharp-libvips-darwin-x64": "1.2.3",
+ "@img/sharp-libvips-linux-arm": "1.2.3",
+ "@img/sharp-libvips-linux-arm64": "1.2.3",
+ "@img/sharp-libvips-linux-ppc64": "1.2.3",
+ "@img/sharp-libvips-linux-s390x": "1.2.3",
+ "@img/sharp-libvips-linux-x64": "1.2.3",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.2.3",
+ "@img/sharp-libvips-linuxmusl-x64": "1.2.3",
+ "@img/sharp-linux-arm": "0.34.4",
+ "@img/sharp-linux-arm64": "0.34.4",
+ "@img/sharp-linux-ppc64": "0.34.4",
+ "@img/sharp-linux-s390x": "0.34.4",
+ "@img/sharp-linux-x64": "0.34.4",
+ "@img/sharp-linuxmusl-arm64": "0.34.4",
+ "@img/sharp-linuxmusl-x64": "0.34.4",
+ "@img/sharp-wasm32": "0.34.4",
+ "@img/sharp-win32-arm64": "0.34.4",
+ "@img/sharp-win32-ia32": "0.34.4",
+ "@img/sharp-win32-x64": "0.34.4"
+ }
+ },
+ "node_modules/sharp/node_modules/semver": {
+ "version": "7.8.6",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
diff --git a/package.json b/package.json
index 09c0afc..077c187 100644
--- a/package.json
+++ b/package.json
@@ -6,8 +6,8 @@
"apps/*"
],
"engines": {
- "node": "24.x",
- "npm": "11.x"
+ "node": ">=24",
+ "npm": ">=11"
},
"scripts": {
"predev": "npm run build --workspace @t31/validation",
@@ -35,9 +35,11 @@
"test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts",
"test:api": "tsx --env-file-if-exists=.env scripts/test-recipe-api.ts",
"db:seed": "tsx --env-file-if-exists=.env apps/api/src/db/seed.ts",
+ "db:seed:large": "tsx --env-file-if-exists=.env scripts/seed-large.ts",
"images:cleanup": "tsx --env-file-if-exists=.env scripts/cleanup-images.ts"
},
"devDependencies": {
+ "@axe-core/playwright": "4.10.2",
"@eslint/js": "9.39.5",
"@graphql-codegen/core": "6.2.0",
"@graphql-codegen/typed-document-node": "7.1.0",
diff --git a/scripts/generate-api.ts b/scripts/generate-api.ts
index 0084dc0..3e2b4c7 100644
--- a/scripts/generate-api.ts
+++ b/scripts/generate-api.ts
@@ -21,7 +21,13 @@ const targets = [
filename: 'contracts/generated.ts',
// typescript-operations v6 also emits the used input types.
plugins: [{ operations: {} }, { typedDocument: {} }],
- config: { useTypeImports: true, enumsAsTypes: true },
+ // String documents carry the query text, so the browser can send them
+ // without graphql-js's print() and its ~40 KB of parser/printer code.
+ config: {
+ useTypeImports: true,
+ enumsAsTypes: true,
+ documentMode: 'string',
+ },
},
];
diff --git a/scripts/seed-large.ts b/scripts/seed-large.ts
new file mode 100644
index 0000000..d4dba7e
--- /dev/null
+++ b/scripts/seed-large.ts
@@ -0,0 +1,160 @@
+/*
+ * Loads a large generated recipe catalogue for scalability testing.
+ *
+ * npm run db:seed:large -- 100000 add 100 000 recipes
+ * npm run db:seed:large -- --remove delete everything this script added
+ *
+ * Never run this against the production database: the lecturer-facing app
+ * should only show real demo content. Point DATABASE_URL at a separate test
+ * database. Explicit opt-in, like db:seed; never run by CI or deploy.
+ * Run db:seed first:
+ * the 51 demo recipes are used as templates (title, text, image, ingredients,
+ * steps, tags), with varied names, times, dates and visibility. All rows
+ * belong to one "Load Test Cook" account that cannot log in, so --remove
+ * deletes them (and their ratings) through ON DELETE CASCADE.
+ */
+import { Pool } from 'pg';
+
+const SCHEMA = 'project2';
+const LOAD_AUTHOR_ID = '22222222-2222-4222-8222-222222222222';
+const RATER_COUNT = 200;
+const t = (name: string) => `"${SCHEMA}"."${name}"`;
+
+const argument = process.argv[2];
+if (!argument || (argument !== '--remove' && !/^\d+$/.test(argument))) {
+ console.error(
+ 'Usage: npm run db:seed:large -- | --remove\n' +
+ 'Use a separate test database (DATABASE_URL), never production.',
+ );
+ process.exit(1);
+}
+
+const pool = new Pool({ connectionString: process.env.DATABASE_URL });
+const client = await pool.connect();
+try {
+ await client.query('BEGIN');
+ if (argument === '--remove') {
+ // Raters are identified by their reserved e-mail domain.
+ const removed = await client.query(
+ `DELETE FROM ${t('recipes')} WHERE author_id = $1`,
+ [LOAD_AUTHOR_ID],
+ );
+ await client.query(
+ `DELETE FROM ${t('users')} WHERE id = $1 OR email LIKE '%@load-test.invalid'`,
+ [LOAD_AUTHOR_ID],
+ );
+ await client.query('COMMIT');
+ console.log(`Removed ${removed.rowCount} generated recipes.`);
+ } else {
+ const count = Number(argument);
+ const templates = await client.query(
+ `SELECT count(*)::int AS n FROM ${t('recipes')}
+ WHERE author_id = '11111111-1111-4111-8111-111111111111'`,
+ );
+ if (!templates.rows[0].n)
+ throw new Error('Run npm run db:seed first; its recipes are templates.');
+
+ // Password hash '!' matches no password, so these accounts cannot log in.
+ await client.query(
+ `INSERT INTO ${t('users')} (id, name, email, password_hash)
+ VALUES ($1, 'Load Test Cook', 'cook@load-test.invalid', '!')
+ ON CONFLICT DO NOTHING`,
+ [LOAD_AUTHOR_ID],
+ );
+ await client.query(
+ `INSERT INTO ${t('users')} (name, email, password_hash)
+ SELECT 'Load Test Rater ' || g, 'rater-' || g || '@load-test.invalid', '!'
+ FROM generate_series(1, $1::int) g
+ ON CONFLICT DO NOTHING`,
+ [RATER_COUNT],
+ );
+
+ // Each generated recipe copies template n = g mod 51 with a new name,
+ // cooking time, creation date (spread over two years) and visibility.
+ await client.query(
+ `CREATE TEMP TABLE generated ON COMMIT DROP AS
+ WITH template AS (
+ SELECT r.*, row_number() OVER (ORDER BY r.id) - 1 AS n,
+ count(*) OVER () AS total
+ FROM ${t('recipes')} r
+ WHERE r.author_id = '11111111-1111-4111-8111-111111111111'
+ )
+ SELECT gen_random_uuid() AS id, tp.id AS template_id, g
+ FROM generate_series(1, $1::int) g
+ JOIN template tp ON tp.n = g % tp.total`,
+ [count],
+ );
+ await client.query(
+ `INSERT INTO ${t('recipes')} (id, author_id, title, description,
+ image_url, category, cuisine, difficulty, visibility,
+ prep_minutes, cook_minutes, servings, created_at, updated_at)
+ SELECT x.id, $1, (ARRAY['Quick','Easy','Spicy','Family','Weekend',
+ 'Classic','Rustic','Light','Hearty','Simple','Festive','Budget'])
+ [1 + x.g % 12] || ' ' || r.title || ' ' || x.g,
+ r.description, r.image_url, r.category, r.cuisine, r.difficulty,
+ CASE WHEN x.g % 10 = 0 THEN 'private' ELSE 'public' END,
+ greatest(0, r.prep_minutes + (x.g % 21) - 10),
+ greatest(0, r.cook_minutes + (x.g % 31) - 15),
+ r.servings,
+ now() - (x.g * interval '10 minutes'),
+ now() - (x.g * interval '10 minutes')
+ FROM generated x JOIN ${t('recipes')} r ON r.id = x.template_id`,
+ [LOAD_AUTHOR_ID],
+ );
+ for (const [table, columns] of [
+ ['recipe_ingredients', 'name, amount, unit, note, position'],
+ ['recipe_instructions', 'text, position'],
+ ['recipe_tags', 'tag'],
+ ] as const)
+ await client.query(
+ `INSERT INTO ${t(table)} (recipe_id, ${columns})
+ SELECT x.id, ${columns
+ .split(', ')
+ .map((column) => 'c.' + column)
+ .join(', ')}
+ FROM generated x JOIN ${t(table)} c ON c.recipe_id = x.template_id`,
+ );
+
+ // About three ratings per public recipe. The per-row rating trigger is
+ // paused for the bulk insert and the cached columns refreshed once.
+ await client.query(
+ `ALTER TABLE ${t('ratings')} DISABLE TRIGGER ratings_refresh_recipe_rating`,
+ );
+ await client.query(
+ `INSERT INTO ${t('ratings')} (recipe_id, user_id, score)
+ SELECT x.id, u.id, 1 + (abs(hashtext(x.id::text || u.id::text)) % 5)
+ FROM generated x
+ JOIN ${t('recipes')} r ON r.id = x.id AND r.visibility = 'public'
+ CROSS JOIN LATERAL (
+ SELECT id FROM ${t('users')}
+ WHERE email LIKE 'rater-%@load-test.invalid'
+ ORDER BY md5(x.id::text || id::text) LIMIT (x.g % 6)
+ ) u
+ ON CONFLICT DO NOTHING`,
+ );
+ await client.query(
+ `ALTER TABLE ${t('ratings')} ENABLE TRIGGER ratings_refresh_recipe_rating`,
+ );
+ await client.query(
+ `UPDATE ${t('recipes')} r SET rating_avg = s.average, rating_count = s.total
+ FROM (SELECT recipe_id, avg(score) AS average, count(*)::int AS total
+ FROM ${t('ratings')} GROUP BY recipe_id) s
+ WHERE r.id = s.recipe_id AND r.author_id = $1`,
+ [LOAD_AUTHOR_ID],
+ );
+ await client.query('COMMIT');
+ // The search triggers rewrite every new recipe once after its ingredients
+ // and tags are inserted. Reclaim those dead rows and refresh statistics,
+ // otherwise counts stay several times slower until autovacuum runs.
+ // PARALLEL 0 avoids running out of shared memory in small containers.
+ await client.query(`VACUUM (ANALYZE, PARALLEL 0) ${t('recipes')}`);
+ await client.query(`VACUUM (ANALYZE, PARALLEL 0) ${t('ratings')}`);
+ console.log(`Added ${count} generated recipes.`);
+ }
+} catch (error) {
+ await client.query('ROLLBACK');
+ throw error;
+} finally {
+ client.release();
+ await pool.end();
+}
diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts
index 75befa0..04e9ecd 100644
--- a/scripts/test-recipe-api.ts
+++ b/scripts/test-recipe-api.ts
@@ -1,6 +1,13 @@
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
-import { mkdtemp, readFile, rm, utimes, access } from 'node:fs/promises';
+import {
+ mkdtemp,
+ readFile,
+ rm,
+ utimes,
+ access,
+ writeFile,
+} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -9,8 +16,8 @@ import {
} from '../apps/api/src/features/recipes/imageStore.js';
import { test } from 'node:test';
import { Pool } from 'pg';
-import { print } from 'graphql';
-import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
+import type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';
+import sharp from 'sharp';
import { createApp } from '../apps/api/src/app.js';
import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js';
import { createAuthService } from '../apps/api/src/features/auth/authService.js';
@@ -35,6 +42,11 @@ import {
import { seedRecipes } from '../apps/api/src/db/seedRecipes.js';
+// Generated operations are typed query strings (contracts/generated.ts).
+type TypedDocumentNode = DocumentTypeDecoration & {
+ toString(): string;
+};
+
await test('recipe GraphQL API against PostgreSQL', async (t) => {
assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL in .env.');
const pool = new Pool({
@@ -79,7 +91,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
'X-Requested-With': 'recipe-platform',
...(cookie ? { Cookie: cookie } : {}),
},
- body: JSON.stringify({ query: print(document), variables }),
+ body: JSON.stringify({ query: document.toString(), variables }),
});
const sessionCookie =
response.headers.get('set-cookie')?.split(';')[0] ?? '';
@@ -255,9 +267,63 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
const uploaded = await upload(owner.cookie);
assert.equal(uploaded.status, 201);
const { imageUrl } = (await uploaded.json()) as { imageUrl: string };
- const image = (cookie?: string) =>
- api.fetch(`http://localhost${imageUrl}`, {
- headers: cookie ? { Cookie: cookie } : {},
+ // Every upload is re-encoded as WebP on the server.
+ assert.match(imageUrl, /\.webp$/);
+ // A large camera-sized photo is scaled down to 1600 px on the server,
+ // whatever the client sent. (Row removed again so the per-hour quota
+ // checks below start from zero.)
+ const photo = await sharp({
+ create: {
+ width: 3000,
+ height: 2000,
+ channels: 3,
+ background: '#c0603a',
+ },
+ })
+ .jpeg()
+ .toBuffer();
+ const large = await createImageStore(
+ pool,
+ schema,
+ imageDirectory,
+ ).upload(owner.user.id, photo);
+ const largeFile = join(imageDirectory, large.slice('/uploads/'.length));
+ const stored = await sharp(largeFile).metadata();
+ assert.deepEqual(
+ [stored.format, stored.width, stored.height],
+ ['webp', 1600, 1067],
+ );
+ await access(
+ join(
+ imageDirectory,
+ 'variants',
+ '480',
+ large.slice('/uploads/'.length),
+ ),
+ );
+ await pool.query(
+ `DELETE FROM "${schema}".uploaded_images WHERE filename=$1`,
+ [large.slice('/uploads/'.length)],
+ );
+ for (const path of [
+ largeFile,
+ ...['480', '800'].map((width) =>
+ join(
+ imageDirectory,
+ 'variants',
+ width,
+ large.slice('/uploads/'.length),
+ ),
+ ),
+ ])
+ await rm(path, { force: true });
+ const image = (
+ cookie?: string,
+ query = '',
+ headers: Record = {},
+ ) =>
+ api.fetch(`http://localhost${imageUrl}${query}`, {
+ headers: { ...headers, ...(cookie ? { Cookie: cookie } : {}) },
});
assert.equal((await image()).status, 404);
assert.equal((await image(reader.cookie)).status, 404);
@@ -287,8 +353,27 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
},
owner.cookie,
);
- assert.equal((await image()).status, 200);
- assert.equal((await image()).headers.get('cache-control'), 'no-store');
+ const publicImage = await image();
+ assert.equal(publicImage.status, 200);
+ // Browsers may keep public images but must revalidate each time.
+ assert.equal(
+ publicImage.headers.get('cache-control'),
+ 'public, no-cache',
+ );
+ const etag = publicImage.headers.get('etag')!;
+ const revalidated = await image(undefined, '', {
+ 'If-None-Match': etag,
+ });
+ assert.equal(revalidated.status, 304);
+ assert.equal((await revalidated.arrayBuffer()).byteLength, 0);
+ // Resized WebP variants are generated with sharp and cached on disk.
+ const filename = imageUrl.slice('/uploads/'.length);
+ const thumbnail = await image(undefined, '?w=480');
+ assert.equal(thumbnail.status, 200);
+ assert.equal(thumbnail.headers.get('content-type'), 'image/webp');
+ const variantFile = join(imageDirectory, 'variants', '480', filename);
+ await access(variantFile);
+ assert.equal((await image(undefined, '?w=999')).status, 400);
await ok(
UpdateRecipeDocument,
{
@@ -298,8 +383,16 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
owner.cookie,
);
assert.equal((await image()).status, 404);
+ // A cached public copy is not confirmed once the recipe is private.
+ assert.equal(
+ (await image(undefined, '', { 'If-None-Match': etag })).status,
+ 404,
+ );
+ assert.equal(
+ (await image(owner.cookie)).headers.get('cache-control'),
+ 'private, no-cache',
+ );
const store = createImageStore(pool, schema, imageDirectory);
- const filename = imageUrl.slice('/uploads/'.length);
const old = new Date(Date.now() - 25 * 60 * 60 * 1000);
await utimes(join(imageDirectory, filename), old, old);
await pool.query(
@@ -318,15 +411,26 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
);
assert.equal(await store.cleanup(), 1);
await assert.rejects(access(join(imageDirectory, filename)));
+ await assert.rejects(access(variantFile)); // Variants go with it.
+ // A variant whose original is already gone is removed too.
+ const orphan = join(
+ imageDirectory,
+ 'variants',
+ '800',
+ `${randomUUID()}.webp`,
+ );
+ await writeFile(orphan, 'stale');
+ await store.cleanup();
+ await assert.rejects(access(orphan));
const restricted = createImageStore(pool, schema, imageDirectory, {
userBytes: 1000,
totalBytes: 2000,
totalFiles: 2,
perHour: 1,
});
- await restricted.upload(owner.user.id, png, 'png');
+ await restricted.upload(owner.user.id, png);
await assert.rejects(
- restricted.upload(owner.user.id, png, 'png'),
+ restricted.upload(owner.user.id, png),
(error: unknown) =>
error instanceof ImageError && error.status === 429,
);
@@ -337,7 +441,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
perHour: 20,
});
await assert.rejects(
- full.upload(reader.user.id, png, 'png'),
+ full.upload(reader.user.id, png),
(error: unknown) =>
error instanceof ImageError && error.status === 507,
);
@@ -348,13 +452,13 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
perHour: 20,
});
await assert.rejects(
- userFull.upload(owner.user.id, png, 'png'),
+ userFull.upload(owner.user.id, png),
(error: unknown) =>
error instanceof ImageError && error.status === 413,
);
const concurrent = await Promise.allSettled([
- restricted.upload(reader.user.id, png, 'png'),
- restricted.upload(reader.user.id, png, 'png'),
+ restricted.upload(reader.user.id, png),
+ restricted.upload(reader.user.id, png),
]);
assert.equal(
concurrent.filter((result) => result.status === 'fulfilled').length,
@@ -637,6 +741,591 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
}
},
);
+ await t.test(
+ 'stores ingredients, steps and tags in order with one insert each',
+ async () => {
+ const ingredients = [
+ { name: 'Flour', amount: 1234.5678, unit: 'g', note: 'sifted' },
+ { name: 'Salt', amount: 0.1, unit: 'tsp', note: null },
+ ...Array.from({ length: 98 }, (_, index) => ({
+ name: `Spice ${index + 3}`,
+ amount: index + 3,
+ unit: 'g',
+ note: null,
+ })),
+ ];
+ const { createRecipe } = await ok(
+ CreateRecipeDocument,
+ {
+ input: {
+ ...input,
+ title: 'Hundred ingredient bake',
+ ingredients,
+ instructions: ['Mix', 'Bake', 'Cool'],
+ tags: ['Baking', 'big'],
+ },
+ },
+ owner.cookie,
+ );
+ try {
+ assert.deepEqual(
+ createRecipe.ingredients.map(({ name, amount, note }) => ({
+ name,
+ amount,
+ note,
+ })),
+ ingredients.map(({ name, amount, note }) => ({
+ name,
+ amount,
+ note,
+ })),
+ );
+ assert.deepEqual(createRecipe.instructions, [
+ { step: 1, text: 'Mix' },
+ { step: 2, text: 'Bake' },
+ { step: 3, text: 'Cool' },
+ ]);
+ assert.deepEqual(createRecipe.tags, ['baking', 'big']);
+ // A recipe without tags writes no tag row.
+ const { updateRecipe } = await ok(
+ UpdateRecipeDocument,
+ { id: createRecipe.id, input: { ...input, tags: [] } },
+ owner.cookie,
+ );
+ assert.deepEqual(updateRecipe.tags, []);
+ assert.equal(updateRecipe.ingredients.length, 2);
+ } finally {
+ await ok(DeleteRecipeDocument, { id: createRecipe.id }, owner.cookie);
+ }
+ },
+ );
+ await t.test(
+ 'refuses an update based on an outdated version (CONFLICT)',
+ async () => {
+ const { createRecipe } = await ok(
+ CreateRecipeDocument,
+ { input: { ...input, title: 'Edited in two tabs' } },
+ owner.cookie,
+ );
+ try {
+ // updatedAt has millisecond precision; make sure the save below
+ // gets a later one than the create.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ // Tab A saves first, from the version both tabs loaded.
+ const { updateRecipe: first } = await ok(
+ UpdateRecipeDocument,
+ {
+ id: createRecipe.id,
+ input: { ...input, title: 'Saved by tab A' },
+ expectedUpdatedAt: createRecipe.updatedAt,
+ },
+ owner.cookie,
+ );
+ assert.notEqual(first.updatedAt, createRecipe.updatedAt);
+ // Tab B still has the old version: refused, nothing overwritten.
+ await fails(
+ UpdateRecipeDocument,
+ {
+ id: createRecipe.id,
+ input: { ...input, title: 'Saved by tab B' },
+ expectedUpdatedAt: createRecipe.updatedAt,
+ },
+ 'CONFLICT',
+ owner.cookie,
+ );
+ const { recipe } = await ok(
+ RecipeDocument,
+ { id: createRecipe.id },
+ owner.cookie,
+ );
+ assert.equal(recipe?.title, 'Saved by tab A');
+ // With the current version, or without one (older clients), it saves.
+ await ok(
+ UpdateRecipeDocument,
+ {
+ id: createRecipe.id,
+ input: { ...input, title: 'Saved by tab B' },
+ expectedUpdatedAt: first.updatedAt,
+ },
+ owner.cookie,
+ );
+ await ok(
+ UpdateRecipeDocument,
+ { id: createRecipe.id, input },
+ owner.cookie,
+ );
+ } finally {
+ await ok(DeleteRecipeDocument, { id: createRecipe.id }, owner.cookie);
+ }
+ },
+ );
+ await t.test(
+ 'word search and cached ratings are index-backed and stay correct',
+ async () => {
+ const created: string[] = [];
+ const search = async (text: string) =>
+ (
+ await ok(RecipesDocument, {
+ input: { search: text, pageSize: 50 },
+ })
+ ).recipes.items.map((item) => item.title);
+ try {
+ for (const title of ['Rice with chicken', 'Slovenian palačinke'])
+ created.push(
+ (
+ await ok(
+ CreateRecipeDocument,
+ { input: { ...input, title } },
+ owner.cookie,
+ )
+ ).createRecipe.id,
+ );
+ // Every word must match, in any order; words match as prefixes.
+ assert.deepEqual(await search('chicken rice'), ['Rice with chicken']);
+ assert.deepEqual(await search('CHICK'), ['Rice with chicken']);
+ assert.deepEqual(await search('chicken cake'), []);
+ assert.deepEqual(await search('Palačinke'), ['Slovenian palačinke']);
+ // Query syntax in user input is ignored, never a server error.
+ assert.deepEqual(await search('rice & (chicken'), [
+ 'Rice with chicken',
+ ]);
+ assert.ok((await search('&|!')).length >= created.length);
+
+ // The newer cupcake belongs on the second page even for newest-first.
+ for (const title of ['Lemon cake', 'Lemon cupcakes']) {
+ const { createRecipe } = await ok(
+ CreateRecipeDocument,
+ { input: { ...input, title } },
+ owner.cookie,
+ );
+ created.push(createRecipe.id);
+ }
+ const byCake = { search: 'cake', pageSize: 1 } as const;
+ const { recipes: first } = await ok(RecipesDocument, {
+ input: byCake,
+ });
+ assert.equal(first.totalCount, 2);
+ assert.deepEqual(
+ first.items.map((item) => item.title),
+ ['Lemon cake'],
+ );
+ const { recipes: second } = await ok(RecipesDocument, {
+ input: { ...byCake, page: 2 },
+ });
+ assert.deepEqual(
+ second.items.map((item) => item.title),
+ ['Lemon cupcakes'],
+ );
+ const { cookbook } = await ok(
+ CookbookDocument,
+ { scope: 'created', input: { search: 'cake salt' } },
+ owner.cookie,
+ );
+ assert.deepEqual(
+ cookbook.items.map((item) => item.title),
+ ['Lemon cake', 'Lemon cupcakes'],
+ );
+
+ // Ingredient names and tags are searchable too, across fields.
+ const saffron = {
+ ...input,
+ title: 'Golden festival bread',
+ ingredients: [
+ { name: 'Saffron threads', amount: 1, unit: 'g' },
+ { name: 'Saffron water', amount: 50, unit: 'ml' },
+ ],
+ tags: ['festive'],
+ };
+ const publicSaffron = (
+ await ok(CreateRecipeDocument, { input: saffron }, owner.cookie)
+ ).createRecipe.id;
+ const privateSaffron = (
+ await ok(
+ CreateRecipeDocument,
+ {
+ input: {
+ ...saffron,
+ title: 'Private saffron buns',
+ visibility: 'private',
+ },
+ },
+ owner.cookie,
+ )
+ ).createRecipe.id;
+ created.push(publicSaffron, privateSaffron);
+ // Two matching ingredients still give one result and count of 1.
+ const bySaffron = (
+ await ok(RecipesDocument, { input: { search: 'saffron' } })
+ ).recipes;
+ assert.deepEqual(
+ [bySaffron.totalCount, bySaffron.items.map((item) => item.title)],
+ [1, ['Golden festival bread']],
+ );
+ assert.deepEqual(await search('festive'), ['Golden festival bread']);
+ assert.deepEqual(await search('golden saffron festive'), [
+ 'Golden festival bread',
+ ]);
+ // No word is ignored, however long the search: a ninth word that
+ // matches nothing still means no results.
+ const eight = 'golden festival bread saffron festive gol fest bre';
+ assert.deepEqual(await search(eight), ['Golden festival bread']);
+ assert.deepEqual(await search(`${eight} cake`), []);
+ // Visibility rules still apply: the owner's cookbook finds both.
+ const cookbookSaffron = (
+ await ok(
+ CookbookDocument,
+ { scope: 'created', input: { search: 'saffron' } },
+ owner.cookie,
+ )
+ ).cookbook;
+ assert.equal(cookbookSaffron.totalCount, 2);
+ // Editing ingredients updates the search document.
+ await ok(
+ UpdateRecipeDocument,
+ {
+ id: publicSaffron,
+ input: {
+ ...saffron,
+ ingredients: [{ name: 'Turmeric', amount: 1, unit: 'tsp' }],
+ },
+ },
+ owner.cookie,
+ );
+ assert.deepEqual(await search('saffron'), []);
+ assert.deepEqual(await search('turmeric'), ['Golden festival bread']);
+
+ // A trigger keeps the cached rating summary in step with ratings.
+ const before = (await ok(RecipeDocument, { id: created[0]! }))
+ .recipe!;
+ await ok(
+ RateRecipeDocument,
+ { id: created[0]!, score: 4 },
+ reader.cookie,
+ );
+ const rated = (await ok(RecipeDocument, { id: created[0]! })).recipe!;
+ assert.deepEqual(rated.rating, { average: 4, count: 1 });
+ // Rating a recipe does not count as editing it.
+ assert.equal(rated.updatedAt, before.updatedAt);
+ await ok(
+ RemoveRecipeRatingDocument,
+ { id: created[0]! },
+ reader.cookie,
+ );
+ assert.deepEqual(
+ (await ok(RecipeDocument, { id: created[0]! })).recipe!.rating,
+ { average: 0, count: 0 },
+ );
+ } finally {
+ for (const id of created)
+ await ok(DeleteRecipeDocument, { id }, owner.cookie);
+ }
+ },
+ );
+ await t.test(
+ 'limits recipe creation per user, also for parallel requests',
+ async () => {
+ const limited = createApp(
+ createAuthService(createAuthRepository(pool, pool, schema)),
+ false,
+ false,
+ { pool, schema },
+ imageDirectory,
+ false,
+ { recipesPerHour: 2, recipesPerUser: 3 },
+ );
+ const { user, sessionToken } = await createAuthRepository(
+ pool,
+ pool,
+ schema,
+ ).createUserWithSession(
+ 'Busy cook',
+ 'busy-cook@example.com',
+ 'not-a-real-hash',
+ new Date(Date.now() + 3_600_000),
+ );
+ const cookie = `${owner.cookie.split('=')[0]}=${sessionToken}`;
+ const create = async (title: string) => {
+ const response = await limited.fetch('http://localhost/graphql', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Requested-With': 'recipe-platform',
+ Cookie: cookie,
+ },
+ body: JSON.stringify({
+ query: CreateRecipeDocument.toString(),
+ variables: { input: { ...input, title } },
+ }),
+ });
+ return (await response.json()) as {
+ errors?: {
+ extensions: { code: string; retryAfterSeconds?: number };
+ }[];
+ };
+ };
+ // Four at once with room for two: exactly two are created.
+ const results = await Promise.all(
+ ['One', 'Two', 'Three', 'Four'].map((title) => create(title)),
+ );
+ const codes = results.map(
+ (result) => result.errors?.[0]?.extensions.code ?? 'ok',
+ );
+ assert.deepEqual(codes.toSorted(), [
+ 'RATE_LIMITED',
+ 'RATE_LIMITED',
+ 'ok',
+ 'ok',
+ ]);
+ const retry = results.find((result) => result.errors)!.errors![0]!;
+ assert.ok(retry.extensions.retryAfterSeconds! > 3500);
+ // An hour later the hourly limit allows more, up to the total.
+ await pool.query(
+ `UPDATE "${schema}".recipes SET created_at=now()-interval '2 hours' WHERE author_id=$1`,
+ [user.id],
+ );
+ assert.equal((await create('Five')).errors, undefined);
+ assert.equal(
+ (await create('Six')).errors?.[0]?.extensions.code,
+ 'QUOTA_EXCEEDED',
+ );
+ await pool.query(`DELETE FROM "${schema}".recipes WHERE author_id=$1`, [
+ user.id,
+ ]);
+ },
+ );
+ await t.test(
+ 'cached ratings and search words stay correct under concurrent writes',
+ async () => {
+ const table = (name: string) => `"${schema}".${name}`;
+ const createRecipe = async (title: string, extra = {}) =>
+ (
+ await ok(
+ CreateRecipeDocument,
+ { input: { ...input, title, ...extra } },
+ owner.cookie,
+ )
+ ).createRecipe.id;
+ const cached = async (id: string) =>
+ (
+ await pool.query<{ count: number; average: number | null }>(
+ `SELECT rating_count AS count, rating_avg::float AS average FROM ${table('recipes')} WHERE id=$1`,
+ [id],
+ )
+ ).rows[0]!;
+ const search = async (text: string) =>
+ (
+ await ok(RecipesDocument, {
+ input: { search: text, pageSize: 50 },
+ })
+ ).recipes.items.map((item) => item.title);
+ // Resolves once `pid` is waiting for a lock held by another session.
+ async function blockedOnLock(pid: number) {
+ for (let attempt = 0; attempt < 200; attempt++) {
+ const waiting = await pool.query(
+ `SELECT 1 FROM pg_stat_activity WHERE pid=$1 AND wait_event_type='Lock'`,
+ [pid],
+ );
+ if (waiting.rowCount) return;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ assert.fail('The second writer never waited for the first.');
+ }
+ const created: string[] = [];
+ try {
+ // Many users rating the same recipe at once: no deadlock, and the
+ // cached summary counts every rating.
+ const target = await createRecipe('Popular stew');
+ created.push(target);
+ // Created directly: registration through the API is rate limited.
+ const cookieName = owner.cookie.split('=')[0]!;
+ const raters = await Promise.all(
+ Array.from({ length: 6 }, async (_, index) => {
+ const { user, sessionToken } = await createAuthRepository(
+ pool,
+ pool,
+ schema,
+ ).createUserWithSession(
+ `Rater ${index}`,
+ `rater-${index}@example.com`,
+ 'not-a-real-hash',
+ new Date(Date.now() + 3_600_000),
+ );
+ return { user, cookie: `${cookieName}=${sessionToken}` };
+ }),
+ );
+ for (let round = 0; round < 3; round++) {
+ const results = await Promise.all(
+ raters.map((rater, index) =>
+ request(
+ RateRecipeDocument,
+ { id: target, score: ((index + round) % 5) + 1 },
+ rater.cookie,
+ ),
+ ),
+ );
+ assert.deepEqual(
+ results.flatMap((result) => result.errors ?? []),
+ [],
+ );
+ }
+ const scores = raters.map((_, index) => ((index + 2) % 5) + 1);
+ const expected = scores.reduce((sum, s) => sum + s, 0) / 6;
+ assert.equal((await cached(target)).count, 6);
+ assert.equal((await cached(target)).average, expected);
+ // Removing ratings at the same time as others rate.
+ const mixed = await Promise.all(
+ raters.map((rater, index) =>
+ index % 2
+ ? request(
+ RemoveRecipeRatingDocument,
+ { id: target },
+ rater.cookie,
+ )
+ : request(
+ RateRecipeDocument,
+ { id: target, score: 5 },
+ rater.cookie,
+ ),
+ ),
+ );
+ assert.deepEqual(
+ mixed.flatMap((result) => result.errors ?? []),
+ [],
+ );
+ assert.deepEqual(await cached(target), { count: 3, average: 5 });
+
+ // Opposite lock order: a manual SQL session locks a rating, the API
+ // then locks the recipe and waits for that rating, and the SQL
+ // update's trigger waits for the recipe. PostgreSQL aborts the API
+ // transaction (it waited first) as a deadlock; the API retries it
+ // and succeeds after the SQL session commits.
+ const manual = await pool.connect();
+ try {
+ await manual.query('BEGIN');
+ await manual.query(
+ `SELECT 1 FROM ${table('ratings')} WHERE recipe_id=$1 AND user_id=$2 FOR UPDATE`,
+ [target, raters[0]!.user.id],
+ );
+ const manualPid = (
+ await manual.query<{ pid: number }>('SELECT pg_backend_pid() pid')
+ ).rows[0]!.pid;
+ const apiRating = request(
+ RateRecipeDocument,
+ { id: target, score: 1 },
+ raters[0]!.cookie,
+ );
+ // Wait until the API is blocked on the manual session's lock.
+ for (let waited = 0; ; waited++) {
+ const blocked = await pool.query(
+ `SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))`,
+ [manualPid],
+ );
+ if (blocked.rowCount) break;
+ assert.ok(waited < 200, 'The API never waited for the rating.');
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ await manual.query(
+ `UPDATE ${table('ratings')} SET score=3 WHERE recipe_id=$1 AND user_id=$2`,
+ [target, raters[0]!.user.id],
+ );
+ await manual.query('COMMIT');
+ assert.equal((await apiRating).errors, undefined);
+ } finally {
+ manual.release();
+ }
+ // The API's rating (1) was written after the manual one (3).
+ assert.deepEqual(await cached(target), {
+ count: 3,
+ average: 11 / 3,
+ });
+
+ // A write that commits while another is in progress, outside the
+ // API (seed, manual SQL): the second must count the first.
+ const second = await createRecipe('Second stew');
+ created.push(second);
+ const first = await pool.connect();
+ const later = await pool.connect();
+ try {
+ await first.query('BEGIN');
+ await later.query('BEGIN');
+ await first.query(
+ `INSERT INTO ${table('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,2)`,
+ [second, raters[0]!.user.id],
+ );
+ const laterPid = (
+ await later.query<{ pid: number }>('SELECT pg_backend_pid() pid')
+ ).rows[0]!.pid;
+ const pending = later.query(
+ `INSERT INTO ${table('ratings')} (recipe_id,user_id,score) VALUES ($1,$2,4)`,
+ [second, raters[1]!.user.id],
+ );
+ await blockedOnLock(laterPid);
+ await first.query('COMMIT');
+ await pending;
+ await later.query('COMMIT');
+ } finally {
+ first.release();
+ later.release();
+ }
+ assert.deepEqual(await cached(second), { count: 2, average: 3 });
+
+ // The same for ingredients: two concurrent ingredient writes on
+ // one recipe both end up searchable.
+ const a = await pool.connect();
+ const b = await pool.connect();
+ try {
+ await a.query('BEGIN');
+ await b.query('BEGIN');
+ await a.query(
+ `INSERT INTO ${table('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,'Cardamom',1,'tsp',NULL,10)`,
+ [second],
+ );
+ const bPid = (
+ await b.query<{ pid: number }>('SELECT pg_backend_pid() pid')
+ ).rows[0]!.pid;
+ const pending = b.query(
+ `INSERT INTO ${table('recipe_tags')} (recipe_id,tag) VALUES ($1,'wintery')`,
+ [second],
+ );
+ await blockedOnLock(bPid);
+ await a.query('COMMIT');
+ await pending;
+ await b.query('COMMIT');
+ } finally {
+ a.release();
+ b.release();
+ }
+ assert.deepEqual(await search('cardamom wintery'), ['Second stew']);
+
+ // Moving a rating, ingredient or tag to another recipe refreshes
+ // both the recipe it left and the one it joined.
+ const moved = await createRecipe('Moved-to stew', {
+ ingredients: [{ name: 'Water', amount: 1, unit: 'l' }],
+ tags: [],
+ });
+ created.push(moved);
+ await pool.query(
+ `UPDATE ${table('ratings')} SET recipe_id=$1 WHERE recipe_id=$2 AND user_id=$3`,
+ [moved, second, raters[1]!.user.id],
+ );
+ assert.deepEqual(await cached(second), { count: 1, average: 2 });
+ assert.deepEqual(await cached(moved), { count: 1, average: 4 });
+ await pool.query(
+ `UPDATE ${table('recipe_ingredients')} SET recipe_id=$1 WHERE recipe_id=$2 AND name='Cardamom'`,
+ [moved, second],
+ );
+ await pool.query(
+ `UPDATE ${table('recipe_tags')} SET recipe_id=$1 WHERE recipe_id=$2 AND tag='wintery'`,
+ [moved, second],
+ );
+ assert.deepEqual(await search('cardamom'), ['Moved-to stew']);
+ assert.deepEqual(await search('wintery'), ['Moved-to stew']);
+ } finally {
+ for (const id of created)
+ await ok(DeleteRecipeDocument, { id }, owner.cookie);
+ }
+ },
+ );
await t.test('only the owner can update or delete', async () => {
await fails(
UpdateRecipeDocument,
@@ -823,7 +1512,25 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
await t.test(
'demo seed is repeatable and preserves existing passwords',
async () => {
+ // Someone already holds one taster address (e.g. registered before it
+ // was reserved): the seed must still succeed, skipping that taster.
+ await pool.query(
+ `INSERT INTO "${schema}".users (name, email, password_hash) VALUES ('Squatter', 'demo-taster-2@example.invalid', 'x')`,
+ );
await seedDatabase(pool, 'demo-test-password', schema, imageDirectory);
+ assert.equal(
+ (
+ await pool.query(
+ `SELECT count(*)::int AS n FROM "${schema}".ratings x JOIN "${schema}".users u ON u.id = x.user_id WHERE u.email = 'demo-taster-2@example.invalid'`,
+ )
+ ).rows[0].n,
+ 0,
+ );
+ // Re-seeding must update descriptions already in the database.
+ await pool.query(
+ `UPDATE "${schema}".recipes SET description = 'Old generated text' WHERE author_id = $1`,
+ ['11111111-1111-4111-8111-111111111111'],
+ );
const originalHash = (
await pool.query(
@@ -856,6 +1563,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
const seeded = await pool.query<{
title: string;
+ description: string;
visibility: string;
image_url: string;
ingredient_count: number;
@@ -863,6 +1571,7 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
}>(
`SELECT
r.title,
+ r.description,
r.visibility,
r.image_url,
(
@@ -910,7 +1619,45 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
);
assert.match(seededRecipe.image_url, /^\/uploads\/[a-f0-9-]+\.webp$/);
+ // The stored description is the hand-written one, also after the
+ // stale value set above (checks the database, not the seed input).
+ assert.equal(seededRecipe.description, recipe.description);
+ assert.doesNotMatch(seededRecipe.description, /^A homemade /);
}
+
+ // Demo tasters rate most public recipes and never private ones.
+ const rated = await pool.query<{
+ visibility: string;
+ ratings: number;
+ min: number | null;
+ max: number | null;
+ }>(
+ `SELECT r.visibility, count(x.score)::int AS ratings,
+ min(x.score) AS min, max(x.score) AS max
+ FROM "${schema}".recipes r
+ LEFT JOIN "${schema}".ratings x ON x.recipe_id = r.id
+ WHERE r.author_id = $1
+ GROUP BY r.id, r.visibility`,
+ ['11111111-1111-4111-8111-111111111111'],
+ );
+ const publicRows = rated.rows.filter(
+ (row) => row.visibility === 'public',
+ );
+ assert.ok(
+ publicRows.filter((row) => row.ratings > 0).length >=
+ publicRows.length * 0.8,
+ 'Most public demo recipes should have ratings.',
+ );
+ assert.ok(
+ rated.rows
+ .filter((row) => row.visibility === 'private')
+ .every((row) => row.ratings === 0),
+ );
+ assert.ok(
+ publicRows.every(
+ (row) => row.ratings === 0 || (row.min! >= 3 && row.max! <= 5),
+ ),
+ );
},
);
} finally {
diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json
index c532c65..9874c65 100644
--- a/scripts/tsconfig.json
+++ b/scripts/tsconfig.json
@@ -6,5 +6,5 @@
"types": ["node"],
"noEmit": true
},
- "include": ["test-recipe-api.ts", "cleanup-images.ts"]
+ "include": ["test-recipe-api.ts", "cleanup-images.ts", "seed-large.ts"]
}
diff --git a/vitest.config.ts b/vitest.config.ts
index 339d587..d62ff4d 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -15,6 +15,10 @@ export default defineConfig({
environment: 'jsdom',
include: ['apps/web/**/*.test.{ts,tsx}'],
setupFiles: ['./apps/web/src/test/setup.ts'],
+ // Node 25+ defines a global localStorage that is undefined without
+ // --localstorage-file and hides jsdom's implementation. Turn it off
+ // so browser tests behave the same on Node 24 and newer releases.
+ execArgv: ['--no-experimental-webstorage'],
},
},
{