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å ` { + const text = event.currentTarget.value; + setDraft(text); + const typed = Number(text); + if ( + Number.isInteger(typed) && + typed >= MIN_SERVINGS && + typed <= MAX_SERVINGS + ) + onChange(typed); + }} + onBlur={(event) => { + commit(event.currentTarget.value); + setDraft(null); + }} + onKeyDown={(event) => { + if (event.key === 'Enter') event.currentTarget.blur(); + }} + /> + + {/* Announces changes made with the buttons. */} + + {value} {value === 1 ? 'serving' : 'servings'} + + + + = MAX_SERVINGS} + onClick={() => onChange(clamp(value + 1))} + /> + + ); +} 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 }) {
+

+ {moveAnnouncement} +

)} - {status === 'draft' && ( - - Your draft is available in this form until you leave the page. + {offeredDraft && ( + +

+ {draftIsOutdated + ? `You saved a draft on ${formatDraftTime(offeredDraft.savedAt)}, but the recipe has changed since. Restoring replaces the form with the older draft.` + : `You have a draft saved on ${formatDraftTime(offeredDraft.savedAt)}.`} +

+
+ + +
)} + {draftNotice && ( + {draftNotice} + )}
@@ -536,6 +908,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
{ @@ -631,10 +1004,15 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { setTags(event.target.value)} + error={errors.tags} + onChange={(event) => { + setTags(event.target.value); + clearError('tags'); + }} /> Ingredients

Add each ingredient with its name, amount, and unit.

+ {errors.ingredientCount && ( +
+ + {errors.ingredientCount} + +
+ )}
{ingredients.map((ingredient, index) => ( @@ -686,7 +1071,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ? ' recipe-create-page__repeatable-row--dragging' : '' }`} - key={`ingredient-${index}`} + key={ingredient.key} data-recipe-row-type="ingredient" data-recipe-row-index={index} > @@ -737,24 +1122,42 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { updateIngredient(index, 'unit', event.target.value) } > - {!['', 'g', 'kg', 'l', 'dl', 'ss', 'ts', 'stk'].includes( - ingredient.unit, + {/* Keep a custom stored unit (e.g. "cloves") selectable. */} + {!INGREDIENT_UNITS.some( + (unit) => unit.value === ingredient.unit, ) && ( )} - - - - - - - - + {INGREDIENT_UNITS.map((unit) => ( + + ))}
+ moveRow('ingredient', index, -1)} + disabled={index === 0} + /> + moveRow('ingredient', index, 1)} + disabled={index === ingredients.length - 1} + /> = MAX_INGREDIENTS} + aria-describedby={ + ingredients.length >= MAX_INGREDIENTS + ? 'ingredient-limit' + : undefined + } > Add ingredient + {ingredients.length >= MAX_INGREDIENTS && ( +

+ A recipe can have at most {MAX_INGREDIENTS} ingredients. +

+ )}
Instructions

Share the step-by-step process.

+ {errors.instructionCount && ( +
+ + {errors.instructionCount} + +
+ )}
{instructions.map((instruction, index) => ( @@ -797,7 +1218,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ? ' recipe-create-page__repeatable-row--dragging' : '' }`} - key={`instruction-${index}`} + key={instruction.key} data-recipe-row-type="instruction" data-recipe-row-index={index} > @@ -814,7 +1235,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { label={`Step ${index + 1}`} id={`instruction-${index}`} className="recipe-create-page__step-textarea" - value={instruction} + value={instruction.text} error={errors.instructions?.[index]} onChange={(event) => updateInstruction(index, event.target.value) @@ -823,6 +1244,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { rows={2} />
+ moveRow('instruction', index, -1)} + disabled={index === 0} + /> + moveRow('instruction', index, 1)} + disabled={index === instructions.length - 1} + /> = MAX_INSTRUCTIONS} + aria-describedby={ + instructions.length >= MAX_INSTRUCTIONS + ? 'instruction-limit' + : undefined + } > Add step + {instructions.length >= MAX_INSTRUCTIONS && ( +

+ A recipe can have at most {MAX_INSTRUCTIONS} steps. +

+ )}
-
+ {status !== 'idle' && draftMessageIsCurrent && ( +
+ + {status === 'draft' + ? 'Saved in this browser. It will be offered when you open this form again.' + : 'Saving the draft failed. Your changes are still in the form.'} + +
+ )} + setConfirmDiscardDraft(false)} + /> + + setConfirmReplaceDraft(false)} + > + Saving replaces that draft with this form. + ); } @@ -870,12 +1369,24 @@ function RecipeEditPage({ id }: { id: string }) { (signal: AbortSignal) => getRecipe(id, signal), [id], ); - const query = useRecipeQuery(id, load, { refreshOnMutation: false }); + const query = useRecipeQuery(id, load, { + refreshOnMutation: false, + refreshWhenStale: false, + }); + // Each state sets its own title; RecipeEditor sets "Edit ". if (query.loading || query.error) - return <RecipeQueryStatus {...query} label="Loading recipe for editing…" />; + return ( + <> + <PageTitle + title={query.error ? 'Recipe could not be loaded' : 'Edit recipe'} + /> + <RecipeQueryStatus {...query} label="Loading recipe for editing…" /> + </> + ); if (!query.data) return ( <section> + <PageTitle title="Recipe unavailable" /> <h1>Recipe unavailable</h1> <p>This recipe does not exist or is not available to you.</p> <LinkButton to="/cookbook">Back to My Cookbook</LinkButton> @@ -884,6 +1395,7 @@ function RecipeEditPage({ id }: { id: string }) { if (!query.data.isCreatedByCurrentUser) return ( <section> + <PageTitle title="Cannot edit recipe" /> <h1>Cannot edit recipe</h1> <p>You can only edit your own recipes.</p> <LinkButton to="/cookbook">Back to My Cookbook</LinkButton> diff --git a/apps/web/src/features/recipes/UnsavedChangesGuard.tsx b/apps/web/src/features/recipes/UnsavedChangesGuard.tsx new file mode 100644 index 0000000..fc8743b --- /dev/null +++ b/apps/web/src/features/recipes/UnsavedChangesGuard.tsx @@ -0,0 +1,51 @@ +import { useContext, useEffect } from 'react'; +import { UNSAFE_DataRouterContext, useBlocker } from 'react-router-dom'; +import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog'; + +type GuardProps = { + /** Read at the moment of leaving, so a just-finished save is not blocked. */ + isDirty: () => boolean; +}; + +/* + * Asks before leaving a page with unsaved changes. Reloading, closing the + * tab or typing another address gets the browser's own prompt + * (beforeunload); links and Back/Forward inside the app get a dialog. + * The dialog needs a data router (main.tsx); under a plain router, as in + * most unit tests, only the browser prompt is used. + */ +export default function UnsavedChangesGuard({ isDirty }: GuardProps) { + useEffect(() => { + function warn(event: BeforeUnloadEvent) { + if (!isDirty()) return; + event.preventDefault(); + // Older browsers need returnValue set to show the prompt. + event.returnValue = ''; + } + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [isDirty]); + const dataRouter = useContext(UNSAFE_DataRouterContext); + return dataRouter ? <LeavePrompt isDirty={isDirty} /> : null; +} + +function LeavePrompt({ isDirty }: GuardProps) { + const blocker = useBlocker( + ({ currentLocation, nextLocation }) => + currentLocation.pathname !== nextLocation.pathname && isDirty(), + ); + return ( + <ConfirmationDialog + open={blocker.state === 'blocked'} + title="Leave without saving?" + description="Your changes to this recipe are not saved." + confirmLabel="Leave" + cancelLabel="Stay" + tone="warning" + onConfirm={() => blocker.proceed?.()} + onCancel={() => blocker.reset?.()} + > + To keep them, stay and save the recipe or a draft first. + </ConfirmationDialog> + ); +} diff --git a/apps/web/src/features/recipes/recipeApi.test.ts b/apps/web/src/features/recipes/recipeApi.test.ts new file mode 100644 index 0000000..c61ba24 --- /dev/null +++ b/apps/web/src/features/recipes/recipeApi.test.ts @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { listRecipes, recipeErrorMessage } from './recipeApi'; + +afterEach(() => vi.unstubAllGlobals()); + +describe('recipe API limits', () => { + it('explains the per-client request limit (HTTP 429)', async () => { + vi.stubGlobal( + 'fetch', + vi + .fn() + .mockResolvedValue( + Response.json( + { errors: [{ extensions: { code: 'RATE_LIMITED' } }] }, + { status: 429, headers: { 'Retry-After': '30' } }, + ), + ), + ); + const error = await listRecipes({}).catch((caught: unknown) => caught); + expect(recipeErrorMessage(error)).toBe( + 'You are doing that too often. Please try again later.', + ); + }); + + it('explains the recipe creation quota', async () => { + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue( + Response.json({ + errors: [{ extensions: { code: 'QUOTA_EXCEEDED' } }], + }), + ), + ); + const error = await listRecipes({}).catch((caught: unknown) => caught); + expect(recipeErrorMessage(error)).toBe( + 'You have reached the maximum number of recipes. Delete one to add another.', + ); + }); +}); diff --git a/apps/web/src/features/recipes/recipeApi.ts b/apps/web/src/features/recipes/recipeApi.ts index 1e4c58b..ae6e0ca 100644 --- a/apps/web/src/features/recipes/recipeApi.ts +++ b/apps/web/src/features/recipes/recipeApi.ts @@ -1,5 +1,11 @@ import { create } from 'zustand'; -import { z } from 'zod'; +/* + * Same pattern as Zod's z.uuid(), which the API uses for recipe ids. + * Checked here with a plain regex so Explore does not load Zod (~40 KB + * gzipped) just to reject malformed ids before calling the API. + */ +const UUID_PATTERN = + /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; import { RecipesDocument, CookbookDocument, @@ -54,14 +60,24 @@ export async function listRecipes( } export async function getRecipe(id: string, signal?: AbortSignal) { - if (!z.uuid().safeParse(id).success) return null; + if (!UUID_PATTERN.test(id)) return null; const { recipe } = await graphqlRequest(RecipeDocument, { id }, signal); return recipe ? toRecipe(recipe) : null; } -export async function writeRecipe(input: RecipeInput, id?: string) { +export async function writeRecipe( + input: RecipeInput, + id?: string, + expectedUpdatedAt?: string, +) { const recipe = id - ? (await graphqlRequest(UpdateRecipeDocument, { id, input })).updateRecipe + ? ( + await graphqlRequest(UpdateRecipeDocument, { + id, + input, + expectedUpdatedAt, + }) + ).updateRecipe : (await graphqlRequest(CreateRecipeDocument, { input })).createRecipe; invalidateRecipes(); return toRecipe(recipe); @@ -91,6 +107,11 @@ export function recipeErrorMessage(error: unknown) { FORBIDDEN: 'You do not have permission to perform this action.', NOT_FOUND: 'This recipe is unavailable or you no longer have access.', BAD_USER_INPUT: 'Check the recipe fields and try again.', + RATE_LIMITED: 'You are doing that too often. Please try again later.', + QUOTA_EXCEEDED: + 'You have reached the maximum number of recipes. Delete one to add another.', + CONFLICT: + 'This recipe was changed in another tab or session after you opened it, so your version was not saved. Your changes are still in the form: save a draft, reload the page to see the latest version, then restore the draft if you want to keep your changes.', }; return messages[error.code] ?? error.message; } diff --git a/apps/web/src/features/recipes/recipeQueryCache.ts b/apps/web/src/features/recipes/recipeQueryCache.ts index c104012..19124ce 100644 --- a/apps/web/src/features/recipes/recipeQueryCache.ts +++ b/apps/web/src/features/recipes/recipeQueryCache.ts @@ -1,4 +1,6 @@ -const TTL_MS = 30_000; +/** How long fetched recipe data counts as fresh (cache and refresh-on-focus). */ +export const RECIPE_FRESHNESS_MS = 30_000; +const TTL_MS = RECIPE_FRESHNESS_MS; const MAX_ENTRIES = 40; const entries = new Map<string, { data: unknown; expires: number }>(); let generation = 0; @@ -8,18 +10,25 @@ export function clearRecipeQueryCache() { generation += 1; } +/** Drops one entry so the next read fetches from the API. */ +export function forgetRecipeCache(key: string) { + entries.delete(key); +} + export function recipeCacheGeneration() { return generation; } -export function readRecipeCache<T>(key: string): { data: T } | undefined { +export function readRecipeCache<T>( + key: string, +): { data: T; fetchedAt: number } | undefined { const entry = entries.get(key); if (!entry) return; if (entry.expires <= Date.now()) { entries.delete(key); return; } - return { data: entry.data as T }; + return { data: entry.data as T, fetchedAt: entry.expires - TTL_MS }; } export function writeRecipeCache(key: string, data: unknown, started: number) { diff --git a/apps/web/src/features/recipes/useRecipeQuery.test.tsx b/apps/web/src/features/recipes/useRecipeQuery.test.tsx index c84e700..64d9ac7 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.test.tsx +++ b/apps/web/src/features/recipes/useRecipeQuery.test.tsx @@ -136,3 +136,93 @@ it('invalidates cached pages after a mutation while they are unmounted', async ( await waitFor(() => expect(second.result.current.data).toBe('after')); expect(load).toHaveBeenCalledTimes(2); }); +it('refreshes stale data in the background when the page regains focus', async () => { + const now = vi.spyOn(Date, 'now'); + now.mockReturnValue(1_000_000); + const load = vi + .fn<(_: AbortSignal) => Promise<string>>() + .mockResolvedValueOnce('first') + .mockResolvedValueOnce('fresh'); + const { result } = renderHook(() => useRecipeQuery('freshness', load)); + await waitFor(() => expect(result.current.data).toBe('first')); + + // Returning after 10 s: still fresh, no request. + now.mockReturnValue(1_010_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(1); + + // After 31 s the data is stale: refetch, keeping the old data meanwhile. + now.mockReturnValue(1_031_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(result.current.data).toBe('first'); + await waitFor(() => expect(result.current.data).toBe('fresh')); + expect(load).toHaveBeenCalledTimes(2); + now.mockRestore(); +}); +it('never refreshes on focus when refreshWhenStale is off (forms)', async () => { + const now = vi.spyOn(Date, 'now'); + now.mockReturnValue(2_000_000); + const load = vi.fn(async () => 'form data'); + const { result } = renderHook(() => + useRecipeQuery('editor', load, { refreshWhenStale: false }), + ); + await waitFor(() => expect(result.current.data).toBe('form data')); + now.mockReturnValue(2_100_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(1); + now.mockRestore(); +}); +it('retries a failed background refresh the next time the page regains focus', async () => { + const now = vi.spyOn(Date, 'now'); + now.mockReturnValue(3_000_000); + let fail!: (error: Error) => void; + const load = vi + .fn<(_: AbortSignal) => Promise<string>>() + .mockResolvedValueOnce('first') + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + fail = reject; + }), + ) + .mockResolvedValueOnce('fresh'); + const { result } = renderHook(() => useRecipeQuery('retry-stale', load)); + await waitFor(() => expect(result.current.data).toBe('first')); + + // Stale: one refresh starts. focus and visibilitychange often fire + // together; the second event must not start another request. + now.mockReturnValue(3_031_000); + act(() => { + window.dispatchEvent(new Event('focus')); + document.dispatchEvent(new Event('visibilitychange')); + }); + expect(load).toHaveBeenCalledTimes(2); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(2); + + // The refresh fails: old data stays, the failure is reported. + await act(async () => fail(new Error('offline'))); + await waitFor(() => expect(result.current.refreshError).toBeTruthy()); + expect(result.current.data).toBe('first'); + + // Returning again shortly after still counts as stale and retries. + now.mockReturnValue(3_032_000); + act(() => window.dispatchEvent(new Event('focus'))); + expect(load).toHaveBeenCalledTimes(3); + await waitFor(() => expect(result.current.data).toBe('fresh')); + expect(result.current.refreshError).toBeUndefined(); + now.mockRestore(); +}); + +it('does not request disabled criteria and loads when enabled', async () => { + const load = vi.fn().mockResolvedValue('valid results'); + const { result, rerender } = renderHook( + ({ enabled }) => useRecipeQuery('guarded', load, { enabled }), + { initialProps: { enabled: false } }, + ); + expect(load).not.toHaveBeenCalled(); + expect(result.current.loading).toBe(false); + rerender({ enabled: true }); + await waitFor(() => expect(result.current.data).toBe('valid results')); + expect(load).toHaveBeenCalledTimes(1); +}); diff --git a/apps/web/src/features/recipes/useRecipeQuery.ts b/apps/web/src/features/recipes/useRecipeQuery.ts index 8ab3553..2dc87df 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.ts +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useAppStore } from '../../store'; import { recipeErrorMessage, useRecipeChanges } from './recipeApi'; import { @@ -6,6 +6,8 @@ import { writeRecipeCache, recipeCacheGeneration, clearRecipeQueryCache, + forgetRecipeCache, + RECIPE_FRESHNESS_MS, } from './recipeQueryCache'; useAppStore.subscribe((state, previous) => { @@ -23,7 +25,13 @@ useRecipeChanges.subscribe((state, previous) => { export function useRecipeQuery<T>( key: string, load: (signal: AbortSignal) => Promise<T>, - { refreshOnMutation = true } = {}, + { + enabled = true, + refreshOnMutation = true, + // Refetch stale data when the user comes back to a long-open page. + // Off for forms (the editor), which must never replace typed input. + refreshWhenStale = true, + } = {}, ) { const userId = useAppStore((state) => state.currentUser?.id); const sessionStatus = useAppStore((state) => state.sessionStatus); @@ -31,8 +39,21 @@ export function useRecipeQuery<T>( refreshOnMutation ? state.revision : 0, ); const [attempt, setAttempt] = useState(0); + // Bumped when the page regains focus with stale data (see below). + const [freshnessCheck, setFreshnessCheck] = useState(0); + // When the shown data was fetched. Only set when a request succeeds, so a + // failed refresh leaves the data stale and the next return retries it. + const fetchedAt = useRef(0); + // True from a freshness refresh until its request settles, so focus and + // visibilitychange (often fired together) do not start it twice. + const refreshInFlight = useRef(false); const identity = JSON.stringify([key, userId]); - const requestKey = JSON.stringify([identity, revision, attempt]); + const requestKey = JSON.stringify([ + identity, + revision, + attempt, + freshnessCheck, + ]); const waiting = sessionStatus === 'restoring'; const [state, setState] = useState<{ identity: string; @@ -42,7 +63,7 @@ export function useRecipeQuery<T>( error?: string; }>({ identity: '', key: '', hasData: false }); useEffect(() => { - if (waiting) return; + if (waiting || !enabled) return; const cached = attempt === 0 ? readRecipeCache<T>(identity) : undefined; const generation = recipeCacheGeneration(); const controller = new AbortController(); @@ -53,30 +74,58 @@ export function useRecipeQuery<T>( (data) => { if (!controller.signal.aborted) { if (!cached) writeRecipeCache(identity, data, generation); + fetchedAt.current = cached ? cached.fetchedAt : Date.now(); + refreshInFlight.current = false; setState({ identity, key: requestKey, hasData: true, data }); } }, (error: unknown) => { - if (!controller.signal.aborted) - setState((previous) => ({ - ...(previous.identity === identity ? previous : { hasData: false }), - identity, - key: requestKey, - error: recipeErrorMessage(error), - })); + if (controller.signal.aborted) return; + refreshInFlight.current = false; + setState((previous) => ({ + ...(previous.identity === identity ? previous : { hasData: false }), + identity, + key: requestKey, + error: recipeErrorMessage(error), + })); }, ); return () => controller.abort(); - }, [identity, requestKey, load, waiting, attempt]); - const current = !waiting && state.identity === identity ? state : undefined; + }, [identity, requestKey, load, waiting, attempt, enabled]); + const current = + enabled && !waiting && state.identity === identity ? state : undefined; const hasData = current?.hasData ?? false; + + /* + * A page left open (e.g. in a background tab) is refreshed when the user + * returns to it, if its data is older than RECIPE_FRESHNESS_MS. The + * refresh runs in the background: the shown data stays until new data + * arrives (`refreshing`), and failures appear as `refreshError`. + */ + useEffect(() => { + if (!refreshWhenStale || !hasData) return; + function refreshIfStale() { + if (document.visibilityState === 'hidden') return; + if (refreshInFlight.current) return; + if (Date.now() - fetchedAt.current < RECIPE_FRESHNESS_MS) return; + forgetRecipeCache(identity); + refreshInFlight.current = true; + setFreshnessCheck((value) => value + 1); + } + window.addEventListener('focus', refreshIfStale); + document.addEventListener('visibilitychange', refreshIfStale); + return () => { + window.removeEventListener('focus', refreshIfStale); + document.removeEventListener('visibilitychange', refreshIfStale); + }; + }, [refreshWhenStale, hasData, identity]); return { data: hasData ? current?.data : undefined, error: !hasData && current?.key === requestKey ? current.error : undefined, refreshError: hasData && current?.key === requestKey ? current.error : undefined, - loading: waiting || (!hasData && current?.key !== requestKey), - refreshing: hasData && current?.key !== requestKey, + loading: enabled && (waiting || (!hasData && current?.key !== requestKey)), + refreshing: enabled && hasData && current?.key !== requestKey, retry: () => setAttempt((value) => value + 1), }; } diff --git a/apps/web/src/icons/navigation.tsx b/apps/web/src/icons/navigation.tsx index 6098ed6..80739cc 100644 --- a/apps/web/src/icons/navigation.tsx +++ b/apps/web/src/icons/navigation.tsx @@ -38,6 +38,14 @@ export function SearchIcon(props: IconProps) { ); } +export function ChevronUpIcon(props: IconProps) { + return ( + <IconBase {...props}> + <path d="m6 15 6-6 6 6" /> + </IconBase> + ); +} + export function ChevronDownIcon(props: IconProps) { return ( <IconBase {...props}> diff --git a/apps/web/src/lib/graphqlClient.ts b/apps/web/src/lib/graphqlClient.ts index 4583a23..c53b541 100644 --- a/apps/web/src/lib/graphqlClient.ts +++ b/apps/web/src/lib/graphqlClient.ts @@ -1,5 +1,13 @@ -import { print } from 'graphql'; -import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; +import type { DocumentTypeDecoration } from '@graphql-typed-document-node/core'; + +/** + * A generated operation from contracts/generated.ts: the query text as a + * string, typed with its result (T) and variables (V). Sending the text + * directly keeps graphql-js out of the browser bundle. + */ +export type GraphqlDocument<T, V> = DocumentTypeDecoration<T, V> & { + toString(): string; +}; const GRAPHQL_URL = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; @@ -13,7 +21,7 @@ export class ApiError extends Error { } export async function graphqlRequest<T, V>( - document: TypedDocumentNode<T, V>, + document: GraphqlDocument<T, V>, variables: V, signal?: AbortSignal, ): Promise<T> { @@ -26,7 +34,7 @@ export async function graphqlRequest<T, V>( 'X-Requested-With': 'recipe-platform', }, credentials: 'same-origin', - body: JSON.stringify({ query: print(document), variables }), + body: JSON.stringify({ query: document.toString(), variables }), signal, }); } catch (error) { @@ -36,6 +44,12 @@ export async function graphqlRequest<T, V>( 'Unable to connect. Check your connection and try again.', ); } + // The API's per-client request limit (apps/api/src/apiLimits.ts). + if (response.status === 429) + throw new ApiError( + 'RATE_LIMITED', + 'Too many requests. Please wait a moment and try again.', + ); if (!response.ok) throw new ApiError( 'API_ERROR', diff --git a/apps/web/src/lib/ingredientUnits.test.ts b/apps/web/src/lib/ingredientUnits.test.ts new file mode 100644 index 0000000..5225266 --- /dev/null +++ b/apps/web/src/lib/ingredientUnits.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import { INGREDIENT_UNITS, normalizeUnit, unitLabel } from './ingredientUnits'; + +describe('ingredient units', () => { + it('translates legacy Norwegian units to English', () => { + expect(normalizeUnit('ss')).toBe('tbsp'); + expect(normalizeUnit('ts')).toBe('tsp'); + expect(normalizeUnit('STK')).toBe('pcs'); + expect(unitLabel('ss')).toBe('tbsp'); + }); + + it('keeps English and custom units as stored', () => { + expect(normalizeUnit('g')).toBe('g'); + expect(unitLabel('dl')).toBe('dL'); + expect(unitLabel('cloves')).toBe('cloves'); + expect(unitLabel('')).toBe(''); + }); + + it('offers no Norwegian units in the editor', () => { + const values: string[] = INGREDIENT_UNITS.map((unit) => unit.value); + for (const legacy of ['ss', 'ts', 'stk']) + expect(values).not.toContain(legacy); + }); + + it.each(['__proto__', 'constructor', 'toString', 'hasOwnProperty'])( + 'keeps the free-text unit "%s" as typed, not an inherited property', + (unit) => { + expect(normalizeUnit(unit)).toBe(unit); + expect(unitLabel(unit)).toBe(unit); + }, + ); +}); diff --git a/apps/web/src/lib/ingredientUnits.ts b/apps/web/src/lib/ingredientUnits.ts new file mode 100644 index 0000000..54caa28 --- /dev/null +++ b/apps/web/src/lib/ingredientUnits.ts @@ -0,0 +1,45 @@ +/** + * Ingredient units offered in the recipe editor, stored by `value` and shown + * by `label`. Units are free text in the API, so recipes may also contain + * other units (e.g. "cloves"); those are kept and shown as stored. + */ +export const INGREDIENT_UNITS = [ + { value: '', label: 'No unit' }, + { value: 'g', label: 'g' }, + { value: 'kg', label: 'kg' }, + { value: 'ml', label: 'ml' }, + { value: 'dl', label: 'dL' }, + { value: 'l', label: 'L' }, + { value: 'tsp', label: 'tsp' }, + { value: 'tbsp', label: 'tbsp' }, + { value: 'cup', label: 'cup' }, + { value: 'pcs', label: 'pcs' }, +] as const; + +/* + * Earlier versions of the editor stored Norwegian abbreviations. They are + * translated when a recipe is shown or opened for editing, so existing + * recipes keep working without a data migration; saving stores English. + */ +const LEGACY_UNITS: Record<string, string> = { + ss: 'tbsp', // spiseskje + ts: 'tsp', // teskje + stk: 'pcs', // stykk +}; + +/** The stored value to use for a unit, translating legacy Norwegian units. */ +export function normalizeUnit(unit: string) { + const key = unit.trim().toLowerCase(); + // Units are free text: only the mappings defined above count, never + // inherited object properties such as "__proto__" or "constructor". + return Object.hasOwn(LEGACY_UNITS, key) ? LEGACY_UNITS[key]! : unit; +} + +/** How a stored unit is displayed next to an amount ('' for no unit). */ +export function unitLabel(unit: string) { + const value = normalizeUnit(unit); + if (!value) return ''; + return ( + INGREDIENT_UNITS.find((option) => option.value === value)?.label ?? value + ); +} diff --git a/apps/web/src/lib/recipeBrowse/browseControls.test.tsx b/apps/web/src/lib/recipeBrowse/browseControls.test.tsx new file mode 100644 index 0000000..a69313c --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/browseControls.test.tsx @@ -0,0 +1,280 @@ +import '@testing-library/jest-dom/vitest'; +import { useState } from 'react'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import ExploreControls from '../../features/explore/ExploreControls'; +import CookbookControls from '../../features/cookbook/CookbookControls'; +import { + DEFAULT_EXPLORE_BROWSE_STATE, + type ExploreBrowseState, +} from '../../features/explore/exploreBrowseState'; +import { + DEFAULT_COOKBOOK_BROWSE_STATE, + type CookbookBrowseState, +} from '../../features/cookbook/cookbookBrowseState'; + +// Exercise both consumers so their desktop/mobile behavior cannot drift. +for (const kind of ['explore', 'cookbook'] as const) { + describe(`${kind} custom time controls`, () => { + afterEach(() => vi.useRealTimers()); + + function Harness({ navigationKey = 'first' }: { navigationKey?: string }) { + const [explore, setExplore] = useState<ExploreBrowseState>({ + ...DEFAULT_EXPLORE_BROWSE_STATE, + cookingTime: 'custom' as const, + customMaxMinutes: 30, + }); + const [cookbook, setCookbook] = useState<CookbookBrowseState>({ + ...DEFAULT_COOKBOOK_BROWSE_STATE, + cookingTime: 'custom' as const, + customMaxMinutes: 30, + }); + return ( + <> + {kind === 'explore' ? ( + <ExploreControls + navigationKey={navigationKey} + value={explore} + onChange={setExplore} + /> + ) : ( + <CookbookControls + navigationKey={navigationKey} + scope="all" + browseState={cookbook} + onScopeChange={() => {}} + onBrowseStateChange={setCookbook} + onFiltersChange={(_, next) => setCookbook(next)} + /> + )} + <output data-testid="applied"> + {(kind === 'explore' ? explore : cookbook).customMaxMinutes ?? + 'none'} + </output> + </> + ); + } + + it('debounces typing, preserves the prior limit, and clears immediately', () => { + vi.useFakeTimers(); + render(<Harness />); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: '4' } }); + act(() => vi.advanceTimersByTime(200)); + fireEvent.change(input, { target: { value: '45' } }); + act(() => vi.advanceTimersByTime(299)); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + act(() => vi.advanceTimersByTime(1)); + expect(screen.getByTestId('applied')).toHaveTextContent('45'); + fireEvent.change(input, { target: { value: '90' } }); + fireEvent.change(input, { target: { value: '' } }); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + expect( + screen.getAllByText('No time limit applied.')[0], + ).toBeInTheDocument(); + expect( + screen.getByRole('combobox', { name: 'Cooking time' }), + ).toHaveValue('custom'); + expect( + screen.getByRole('button', { name: 'Filters', hidden: true }), + ).toBeInTheDocument(); + }); + + it.each(['abc', '1.5'])( + 'keeps invalid input %s editable without applying it', + (text) => { + vi.useFakeTimers(); + render(<Harness />); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: text } }); + act(() => vi.advanceTimersByTime(500)); + expect(input).toHaveValue(text); + expect(input).toHaveAttribute('aria-invalid', 'true'); + expect( + screen.getByText('Enter whole minutes from 1 to 20,160.'), + ).toBeInTheDocument(); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + }, + ); + + it.each([ + ['0', '1'], + ['-5', '1'], + ['20161', '20160'], + ])( + 'uses %s as %s while keeping the typed value and error', + (text, expected) => { + vi.useFakeTimers(); + render(<Harness />); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: text } }); + expect(input).toHaveValue(text); + act(() => vi.advanceTimersByTime(300)); + expect(input).toHaveValue(text); + expect(input).toHaveAttribute('aria-invalid', 'true'); + expect(screen.getByTestId('applied')).toHaveTextContent(expected); + }, + ); + + it('clamps on blur even when the applied value is already the maximum', () => { + vi.useFakeTimers(); + render(<Harness />); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: '99999' } }); + fireEvent.blur(input); + expect(input).toHaveValue('99999'); + fireEvent.change(input, { target: { value: '999999' } }); + act(() => vi.advanceTimersByTime(300)); + expect(input).toHaveValue('999999'); + expect(screen.getByTestId('applied')).toHaveTextContent('20160'); + }); + + it('preserves the custom maximum when reselected and applied on mobile', () => { + render(<Harness />); + const openFilters = () => + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + openFilters(); + fireEvent.click(screen.getByRole('button', { name: 'Close filters' })); + openFilters(); + fireEvent.click(screen.getByRole('button', { name: 'Custom maximum' })); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + ).toHaveValue('30'); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + openFilters(); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + ).toHaveValue('30'); + }); + + it.each([ + ['0', '1'], + ['99999', '20160'], + ])('clamps mobile input %s on Apply', (text, expected) => { + render(<Harness />); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }); + fireEvent.change(input, { target: { value: text } }); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent(expected); + expect( + screen.getByRole('textbox', { name: 'Maximum cooking time' }), + ).toHaveValue(text); + }); + + it.each(['1', '20160'])('accepts boundary %s', (text) => { + vi.useFakeTimers(); + render(<Harness />); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + { target: { value: text } }, + ); + act(() => vi.advanceTimersByTime(300)); + expect(screen.getByTestId('applied')).toHaveTextContent(text); + }); + + it('cancels pending changes on navigation and preset changes', () => { + vi.useFakeTimers(); + const { rerender } = render(<Harness />); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + { target: { value: '45' } }, + ); + rerender(<Harness navigationKey="back" />); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + ).toHaveValue('30'); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + { target: { value: '45' } }, + ); + fireEvent.change(screen.getByRole('combobox', { name: 'Cooking time' }), { + target: { value: 'any' }, + }); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + expect( + screen.getByRole('combobox', { name: 'Cooking time' }), + ).toHaveValue('any'); + }); + + it('blocks invalid mobile values, then applies empty time as no limit', () => { + render(<Harness />); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }); + fireEvent.change(input, { target: { value: 'abc' } }); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect( + screen.getByRole('dialog', { name: 'Filter recipes' }), + ).toBeInTheDocument(); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + fireEvent.change(input, { target: { value: '' } }); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + expect( + screen.queryByRole('dialog', { name: 'Filter recipes' }), + ).not.toBeInTheDocument(); + expect( + screen.getAllByText('No time limit applied.')[0], + ).toBeInTheDocument(); + }); + + it('discards mobile edits when closed', () => { + render(<Harness />); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + { target: { value: '45' } }, + ); + fireEvent.click(screen.getByRole('button', { name: 'Close filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + ).toHaveValue('30'); + }); + }); +} diff --git a/apps/web/src/lib/recipeBrowse/browseValidation.ts b/apps/web/src/lib/recipeBrowse/browseValidation.ts new file mode 100644 index 0000000..9b67474 --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/browseValidation.ts @@ -0,0 +1,50 @@ +export const MAX_SEARCH_LENGTH = 200; +export const MAX_FILTER_MINUTES = 20160; + +export function searchError(value: string) { + return value.trim().length > MAX_SEARCH_LENGTH + ? 'Use at most 200 characters for search.' + : undefined; +} + +/** Clamp finite numeric input on commit; leave empty or malformed input editable. */ +export function clampCustomTime(value: string) { + if (!value.trim()) return value; + const minutes = Number(value); + if (!Number.isFinite(minutes)) return value; + if (minutes < 1) return '1'; + if (minutes > MAX_FILTER_MINUTES) return String(MAX_FILTER_MINUTES); + return value; +} + +export function customTimeError(value: string) { + if (!value.trim()) return undefined; + const minutes = Number(value); + return Number.isInteger(minutes) && + minutes >= 1 && + minutes <= MAX_FILTER_MINUTES + ? undefined + : 'Enter whole minutes from 1 to 20,160.'; +} + +// Preserve invalid URL input separately from the validated numeric query value. +export function readCustomTime(value: string | null): { + customMaxMinutes: number | null; + customMaxMinutesRaw?: string; +} { + if (value === null || value.trim() === '') return { customMaxMinutes: null }; + const clamped = clampCustomTime(value); + if (customTimeError(clamped)) + return { customMaxMinutes: null, customMaxMinutesRaw: value }; + return { + customMaxMinutes: Number(clamped), + ...(customTimeError(value) ? { customMaxMinutesRaw: value } : {}), + }; +} + +export function customTimeText(state: { + customMaxMinutes: number | null; + customMaxMinutesRaw?: string; +}) { + return state.customMaxMinutesRaw ?? String(state.customMaxMinutes ?? ''); +} diff --git a/apps/web/src/lib/recipeBrowse/recipeBrowse.ts b/apps/web/src/lib/recipeBrowse/recipeBrowse.ts index db14a47..384fd4f 100644 --- a/apps/web/src/lib/recipeBrowse/recipeBrowse.ts +++ b/apps/web/src/lib/recipeBrowse/recipeBrowse.ts @@ -33,6 +33,8 @@ export type RecipeFilterState = { category: RecipeCategory; cookingTime: RecipeCookingTime; customMaxMinutes: number | null; + // Invalid bookmarked input stays editable without putting NaN in query state. + customMaxMinutesRaw?: string; }; /** @@ -109,7 +111,9 @@ export function countActiveRecipeFilters(state: RecipeFilterState) { if ( state.cookingTime !== 'any' && - (state.cookingTime !== 'custom' || state.customMaxMinutes !== null) + (state.cookingTime !== 'custom' || + state.customMaxMinutes !== null || + state.customMaxMinutesRaw !== undefined) ) { count += 1; } diff --git a/apps/web/src/lib/recipeBrowse/useCustomTimeInput.ts b/apps/web/src/lib/recipeBrowse/useCustomTimeInput.ts new file mode 100644 index 0000000..a922569 --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/useCustomTimeInput.ts @@ -0,0 +1,66 @@ +import { useEffect, useEffectEvent, useState } from 'react'; +import { clampCustomTime, customTimeError } from './browseValidation'; + +/** Keep typed input separate from the URL until it is valid and typing pauses. */ +export function useCustomTimeInput( + committed: number | null, + resetKey: string, + onCommit: (minutes: number | null, raw?: string) => void, + raw?: string, +) { + const [draft, setDraft] = useState({ + key: resetKey, + text: raw ?? String(committed ?? ''), + }); + const text = + draft.key === resetKey ? draft.text : (raw ?? String(committed ?? '')); + const clamped = clampCustomTime(text); + const error = customTimeError(text); + const effectiveError = customTimeError(clamped); + const nextRaw = error ? text : undefined; + const commit = useEffectEvent(onCommit); + + useEffect(() => { + if ( + draft.key !== resetKey || + !text.trim() || + effectiveError || + (Number(clamped) === committed && nextRaw === raw) + ) + return; + const timer = window.setTimeout(() => { + commit(Number(clamped), nextRaw); + }, 300); + return () => window.clearTimeout(timer); + }, [ + draft.key, + resetKey, + text, + clamped, + effectiveError, + committed, + raw, + nextRaw, + ]); + + function change(text: string) { + setDraft({ key: resetKey, text }); + // Clearing is immediate, even if an earlier value was waiting to be committed. + if (!text.trim() && (committed !== null || raw !== undefined)) + onCommit(null); + } + + function apply() { + if (effectiveError || !clamped.trim()) return; + if (Number(clamped) !== committed || nextRaw !== raw) + onCommit(Number(clamped), nextRaw); + } + + return { + text, + error, + change, + apply, + noLimit: committed === null && raw === undefined, + }; +} diff --git a/apps/web/src/lib/recipeBrowse/useDebouncedRecipeSearch.ts b/apps/web/src/lib/recipeBrowse/useDebouncedRecipeSearch.ts new file mode 100644 index 0000000..b3ddb45 --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/useDebouncedRecipeSearch.ts @@ -0,0 +1,63 @@ +import { + useLayoutEffect, + useRef, + type Dispatch, + type SetStateAction, +} from 'react'; +import { + useLocation, + useNavigationType, + useSearchParams, +} from 'react-router-dom'; + +export function useDebouncedRecipeSearch( + search: string, + setInput: Dispatch<SetStateAction<string>>, +) { + const { key } = useLocation(); + const navigation = useNavigationType(); + const [, setSearchParams] = useSearchParams(); + const previousSearch = useRef(search); + const latestSetSearchParams = useRef(setSearchParams); + const timer = useRef<number | undefined>(undefined); + + useLayoutEffect(() => { + // The router's setter captures the parameters of its own render. + latestSetSearchParams.current = setSearchParams; + if (navigation === 'POP' || previousSearch.current !== search) { + window.clearTimeout(timer.current); + setInput((value) => (value.trim() === search ? value : search)); + } + previousSearch.current = search; + }, [key, navigation, search, setInput, setSearchParams]); + + useLayoutEffect(() => () => window.clearTimeout(timer.current), []); + + function resetSearch() { + window.clearTimeout(timer.current); + setInput(''); + } + + function changeSearch(value: string) { + setInput(value); + window.clearTimeout(timer.current); + const term = value.trim(); + if (term === search || term.length > 200) return; + function commit() { + latestSetSearchParams.current( + (current) => { + const params = new URLSearchParams(current); + if (term) params.set('q', term); + else params.delete('q'); + params.delete('page'); + return params; + }, + { replace: value !== '' }, + ); + } + if (value === '') commit(); + else timer.current = window.setTimeout(commit, 300); + } + + return { changeSearch, resetSearch }; +} diff --git a/apps/web/src/lib/recipeDrafts.test.ts b/apps/web/src/lib/recipeDrafts.test.ts new file mode 100644 index 0000000..084a146 --- /dev/null +++ b/apps/web/src/lib/recipeDrafts.test.ts @@ -0,0 +1,124 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { + clearDraft, + clearUserDrafts, + countUserDrafts, + loadDraft, + saveDraft, + type RecipeDraftFields, +} from './recipeDrafts'; + +const fields: RecipeDraftFields = { + title: 'Soup', + description: '', + category: 'soup', + difficulty: 'easy', + visibility: 'public', + prepTime: '5', + cookingTime: '10', + servings: '2', + tags: '', + imageUrl: null, + ingredients: [{ name: 'Water', amount: '1', unit: 'l' }], + instructions: ['Boil'], +}; + +beforeEach(() => localStorage.clear()); + +describe('recipe drafts', () => { + it('keeps drafts per user and per recipe', () => { + saveDraft('alice', 'new', { baseUpdatedAt: null, fields }); + saveDraft('alice', 'r1', { + baseUpdatedAt: '2026-01-01T00:00:00Z', + fields: { ...fields, title: 'Edited' }, + }); + expect(loadDraft('alice', 'new')?.fields.title).toBe('Soup'); + expect(loadDraft('alice', 'r1')?.fields.title).toBe('Edited'); + expect(loadDraft('bob', 'new')).toBeNull(); + }); + + it('clears one draft, or all drafts of a user on sign-out', () => { + saveDraft('alice', 'new', { baseUpdatedAt: null, fields }); + saveDraft('alice', 'r1', { baseUpdatedAt: null, fields }); + saveDraft('bob', 'new', { baseUpdatedAt: null, fields }); + expect(countUserDrafts('alice')).toBe(2); + expect(countUserDrafts('bob')).toBe(1); + clearDraft('alice', 'new'); + expect(loadDraft('alice', 'new')).toBeNull(); + expect(countUserDrafts('alice')).toBe(1); + clearUserDrafts('alice'); + expect(countUserDrafts('alice')).toBe(0); + expect(loadDraft('alice', 'r1')).toBeNull(); + expect(loadDraft('bob', 'new')).not.toBeNull(); + }); + + it('drops damaged or unknown drafts instead of failing', () => { + localStorage.setItem('recipe-platform:draft:alice:new', '{not json'); + expect(loadDraft('alice', 'new')).toBeNull(); + localStorage.setItem( + 'recipe-platform:draft:alice:new', + JSON.stringify({ version: 99, fields }), + ); + expect(loadDraft('alice', 'new')).toBeNull(); + expect(localStorage.getItem('recipe-platform:draft:alice:new')).toBeNull(); + }); +}); + +describe('damaged drafts and other tabs', () => { + const stored = (changes: Record<string, unknown>) => + JSON.stringify({ + version: 1, + savedAt: '2026-10-01T10:00:00Z', + baseUpdatedAt: null, + fields, + ...changes, + }); + + it.each([ + ['a non-string title', { fields: { ...fields, title: 5 } }], + ['an unknown visibility', { fields: { ...fields, visibility: 'team' } }], + ['a numeric image', { fields: { ...fields, imageUrl: 3 } }], + ['a null ingredient', { fields: { ...fields, ingredients: [null] } }], + [ + 'an ingredient without a unit', + { fields: { ...fields, ingredients: [{ name: 'Salt', amount: '1' }] } }, + ], + [ + 'a numeric note', + { + fields: { + ...fields, + ingredients: [{ name: 'Salt', amount: '1', unit: 'g', note: 2 }], + }, + }, + ], + ['a non-text step', { fields: { ...fields, instructions: [{}] } }], + ['a missing field', { fields: { ...fields, servings: undefined } }], + ['an invalid save time', { savedAt: 'yesterday' }], + ['an invalid base time', { baseUpdatedAt: 42 }], + ])('drops a draft with %s', (_, changes) => { + localStorage.setItem('recipe-platform:draft:alice:new', stored(changes)); + expect(loadDraft('alice', 'new')).toBeNull(); + expect(localStorage.getItem('recipe-platform:draft:alice:new')).toBeNull(); + }); + + it('keeps a valid draft with an ingredient note', () => { + const withNote = { + ...fields, + ingredients: [{ name: 'Salt', amount: '1', unit: 'g', note: 'flaky' }], + }; + localStorage.setItem( + 'recipe-platform:draft:alice:new', + stored({ fields: withNote }), + ); + expect(loadDraft('alice', 'new')?.fields).toEqual(withNote); + }); + + it('only clears the version of a draft this tab knows about', () => { + localStorage.setItem('recipe-platform:draft:alice:new', stored({})); + expect(clearDraft('alice', 'new', ['2026-09-01T00:00:00Z'])).toBe(false); + expect(loadDraft('alice', 'new')).not.toBeNull(); + expect(clearDraft('alice', 'new', ['2026-10-01T10:00:00Z'])).toBe(true); + expect(loadDraft('alice', 'new')).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/recipeDrafts.ts b/apps/web/src/lib/recipeDrafts.ts new file mode 100644 index 0000000..a36c446 --- /dev/null +++ b/apps/web/src/lib/recipeDrafts.ts @@ -0,0 +1,175 @@ +/* + * Recipe form drafts, kept in this browser's localStorage. + * + * A draft belongs to one user and one recipe ("new" for a recipe not yet + * created), so different accounts on the same browser never see each + * other's drafts, and drafts are removed when the user signs out. Storage + * may be unavailable (private mode, full quota); every function then + * quietly does nothing, and the form still works without drafts. + */ + +const PREFIX = 'recipe-platform:draft:'; + +/** The editable form fields, as entered (numbers are kept as typed text). */ +export type RecipeDraftFields = { + title: string; + description: string; + category: string; + difficulty: string; + visibility: 'public' | 'private'; + prepTime: string; + cookingTime: string; + servings: string; + tags: string; + imageUrl: string | null; + ingredients: { name: string; amount: string; unit: string; note?: string }[]; + instructions: string[]; +}; + +export type RecipeDraft = { + version: 1; + savedAt: string; + /** + * updatedAt of the recipe when the draft was saved (null for a new + * recipe). If the recipe has changed since, the draft is outdated. + */ + baseUpdatedAt: string | null; + fields: RecipeDraftFields; +}; + +const key = (userId: string, recipeId: string) => + `${PREFIX}${userId}:${recipeId}`; + +export function saveDraft( + userId: string, + recipeId: string, + draft: Omit<RecipeDraft, 'version' | 'savedAt'>, +): RecipeDraft | null { + const stored: RecipeDraft = { + version: 1, + savedAt: new Date().toISOString(), + ...draft, + }; + try { + localStorage.setItem(key(userId, recipeId), JSON.stringify(stored)); + return stored; + } catch { + return null; + } +} + +const isString = (value: unknown): value is string => typeof value === 'string'; +const isObject = (value: unknown): value is Record<string, unknown> => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/* + * localStorage can hold anything: an older format, a manual edit, another + * app's data. Check every field the form reads, so a damaged draft is + * dropped here instead of breaking the form when it is restored or saved. + */ +function isRecipeDraft(value: unknown): value is RecipeDraft { + if (!isObject(value) || !isObject(value.fields)) return false; + const fields = value.fields; + return ( + value.version === 1 && + isString(value.savedAt) && + !Number.isNaN(Date.parse(value.savedAt)) && + (value.baseUpdatedAt === null || isString(value.baseUpdatedAt)) && + ( + [ + 'title', + 'description', + 'category', + 'difficulty', + 'prepTime', + 'cookingTime', + 'servings', + 'tags', + ] as const + ).every((name) => isString(fields[name])) && + (fields.visibility === 'public' || fields.visibility === 'private') && + (fields.imageUrl === null || isString(fields.imageUrl)) && + Array.isArray(fields.ingredients) && + fields.ingredients.every( + (ingredient) => + isObject(ingredient) && + isString(ingredient.name) && + isString(ingredient.amount) && + isString(ingredient.unit) && + (ingredient.note === undefined || isString(ingredient.note)), + ) && + Array.isArray(fields.instructions) && + fields.instructions.every(isString) + ); +} + +export function loadDraft(userId: string, recipeId: string) { + try { + const raw = localStorage.getItem(key(userId, recipeId)); + if (!raw) return null; + let draft: unknown; + try { + draft = JSON.parse(raw); + } catch { + draft = null; + } + if (!isRecipeDraft(draft)) { + // Unknown or damaged format: drop it rather than break the form. + localStorage.removeItem(key(userId, recipeId)); + return null; + } + return draft; + } catch { + return null; + } +} + +/** + * Removes a draft. With `onlySavedAt`, only a draft saved at one of those + * times is removed: another tab may have saved a newer draft of the same + * recipe since this tab read it, and that one must be kept. Returns whether + * a draft was removed. + */ +export function clearDraft( + userId: string, + recipeId: string, + onlySavedAt?: readonly string[], +) { + try { + if (onlySavedAt) { + const stored = loadDraft(userId, recipeId); + if (!stored || !onlySavedAt.includes(stored.savedAt)) return false; + } + localStorage.removeItem(key(userId, recipeId)); + return true; + } catch { + // Storage unavailable: nothing to clear. + return false; + } +} + +/** Removes every draft of one user, e.g. when they sign out. */ +export function clearUserDrafts(userId: string) { + try { + const own = `${PREFIX}${userId}:`; + for (let index = localStorage.length - 1; index >= 0; index -= 1) { + const name = localStorage.key(index); + if (name?.startsWith(own)) localStorage.removeItem(name); + } + } catch { + // Storage unavailable: nothing to clear. + } +} + +/** How many drafts one user has in this browser (0 if storage is unavailable). */ +export function countUserDrafts(userId: string) { + try { + const own = `${PREFIX}${userId}:`; + let count = 0; + for (let index = 0; index < localStorage.length; index += 1) + if (localStorage.key(index)?.startsWith(own)) count += 1; + return count; + } catch { + return 0; + } +} diff --git a/apps/web/src/lib/recipeImageUrl.test.ts b/apps/web/src/lib/recipeImageUrl.test.ts new file mode 100644 index 0000000..8b66745 --- /dev/null +++ b/apps/web/src/lib/recipeImageUrl.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { recipeImageSrcSet } from './recipeImageUrl'; + +describe('recipeImageSrcSet', () => { + it('offers the API variants and the original for uploaded images', () => { + const srcSet = recipeImageSrcSet('/uploads/abc.webp'); + expect(srcSet).toContain('/uploads/abc.webp?w=480 480w'); + expect(srcSet).toContain('/uploads/abc.webp?w=800 800w'); + expect(srcSet).toMatch(/\/uploads\/abc\.webp 1600w$/); + }); + + it('returns undefined for external images, which have no variants', () => { + expect(recipeImageSrcSet('https://example.com/soup.jpg')).toBeUndefined(); + }); +}); diff --git a/apps/web/src/lib/recipeImageUrl.ts b/apps/web/src/lib/recipeImageUrl.ts index 64e6a01..fdf0ca3 100644 --- a/apps/web/src/lib/recipeImageUrl.ts +++ b/apps/web/src/lib/recipeImageUrl.ts @@ -1,5 +1,18 @@ +/** Absolute URL for a recipe image; uploads are served by the API. */ export function recipeImageUrl(url: string) { return url.startsWith('/uploads/') && !import.meta.env.DEV ? `/project2/api${url}` : url; } + +/** + * srcset for uploaded images: the API serves resized WebP copies at 480 and + * 800 px (?w=…), so the browser downloads only the size the layout needs. + * Uploads are at most 1600 px wide, hence the descriptor for the original. + * External image URLs have no variants and return undefined. + */ +export function recipeImageSrcSet(url: string) { + if (!url.startsWith('/uploads/')) return undefined; + const source = recipeImageUrl(url); + return `${source}?w=480 480w, ${source}?w=800 800w, ${source} 1600w`; +} diff --git a/apps/web/src/lib/recipeScaling.test.ts b/apps/web/src/lib/recipeScaling.test.ts new file mode 100644 index 0000000..9b66d82 --- /dev/null +++ b/apps/web/src/lib/recipeScaling.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import { formatAmount, scaleAmount } from './recipeScaling'; + +const scaled = (amount: number, to: number, from: number) => + formatAmount(scaleAmount(amount, to, from)); + +describe('recipe scaling', () => { + it('never turns a small positive amount into 0', () => { + expect(scaled(0.125, 1, 4)).toBe('0.031'); // 1/8 tsp for one instead of four + expect(scaled(0.01, 1, 10)).toBe('0.001'); + expect(scaled(0.0001, 1, 1000)).toBe('0.0000001'); + }); + + it('keeps common fractions readable', () => { + expect(scaled(0.5, 3, 2)).toBe('0.75'); + expect(scaled(1, 1, 3)).toBe('0.33'); + expect(scaled(2.5, 3, 2)).toBe('3.8'); + expect(scaled(0.1, 3, 1)).toBe('0.3'); // not 0.30000000000000004 + }); + + it('rounds large quantities sensibly', () => { + expect(scaled(500, 3, 4)).toBe('375'); + expect(scaled(60, 3, 2)).toBe('90'); + expect(scaled(1234, 3, 1)).toBe('3700'); + expect(scaled(99999999.9999, 1000, 1)).toBe('100000000000'); + }); + + it('scales from the original amount, so repeated changes do not drift', () => { + // 4 -> 3 -> 7 -> 4 servings always starts from the stored 0.3. + for (const servings of [3, 7, 4]) scaled(0.3, servings, 4); + expect(scaled(0.3, 4, 4)).toBe('0.3'); + expect(scaled(1 / 3, 3, 1)).toBe('1'); + }); + + it('shows 0 only for zero or invalid amounts', () => { + expect(formatAmount(0)).toBe('0'); + expect(formatAmount(Number.NaN)).toBe('0'); + }); +}); diff --git a/apps/web/src/lib/recipeScaling.ts b/apps/web/src/lib/recipeScaling.ts new file mode 100644 index 0000000..880f45d --- /dev/null +++ b/apps/web/src/lib/recipeScaling.ts @@ -0,0 +1,35 @@ +/** + * Scales an ingredient amount from the recipe's own servings to the + * servings the reader chose. Always scales from the stored original amount, + * so changing servings back and forth never accumulates rounding errors. + */ +export function scaleAmount( + amount: number, + selectedServings: number, + originalServings: number, +) { + return amount * (selectedServings / originalServings); +} + +/** + * Rounds a scaled amount to something readable in a kitchen: + * - 200 and above: nearest 5 (e.g. 245 g) + * - 50–199: whole numbers + * - 3–49: one decimal + * - 0.1–3: two decimals (e.g. 1.25 tsp) + * - below 0.1: two significant figures (e.g. 0.042) + * A positive amount is never shown as 0. + */ +export function formatAmount(value: number) { + if (!Number.isFinite(value) || value <= 0) return '0'; + let rounded: number; + if (value >= 200) rounded = Math.round(value / 5) * 5; + else if (value >= 50) rounded = Math.round(value); + else if (value >= 3) rounded = Math.round(value * 10) / 10; + else if (value >= 0.1) rounded = Math.round(value * 100) / 100; + else rounded = Number(value.toPrecision(2)); + // Number(...toPrecision()) also removes float noise like 0.30000000000000004. + const text = String(Number(rounded.toPrecision(12))); + // Very small values would print as "1e-7"; show them as plain decimals. + return text.includes('e') ? rounded.toFixed(20).replace(/\.?0+$/, '') : text; +} diff --git a/apps/web/src/lib/unsavedChanges.ts b/apps/web/src/lib/unsavedChanges.ts new file mode 100644 index 0000000..4a2f934 --- /dev/null +++ b/apps/web/src/lib/unsavedChanges.ts @@ -0,0 +1,8 @@ +import { create } from 'zustand'; + +/* + * Whether the recipe editor currently has changes that are neither saved + * nor kept as a draft. The editor sets it; the header reads it to warn + * before signing out, which would close the editor. + */ +export const useUnsavedChanges = create(() => ({ unsaved: false })); diff --git a/apps/web/src/lib/usePageTitle.ts b/apps/web/src/lib/usePageTitle.ts new file mode 100644 index 0000000..a35864b --- /dev/null +++ b/apps/web/src/lib/usePageTitle.ts @@ -0,0 +1,25 @@ +import { useEffect } from 'react'; + +const APP_NAME = 'Recipe Platform'; + +/** + * Sets the browser tab title for the current page, e.g. + * "My Cookbook – Recipe Platform". Screen readers announce the title after + * navigation, so every route should call this (WCAG 2.4.2 Page Titled). + */ +export function usePageTitle(title: string | null) { + useEffect(() => { + document.title = title ? `${title} – ${APP_NAME}` : APP_NAME; + }, [title]); +} + +/** + * Sets the title for a state that renders instead of a page, such as a + * loading, error or access message. Render it only in that state: a parent + * calling usePageTitle unconditionally would run its effect after the + * child page's and overwrite the page's own title. + */ +export function PageTitle({ title }: { title: string }) { + usePageTitle(title); + return null; +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 8ead562..5676925 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,6 +1,6 @@ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; -import { BrowserRouter } from 'react-router-dom'; +import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import './styles/layers.css'; import './styles/resets.css'; @@ -10,10 +10,14 @@ import './styles/utilities.css'; import { App } from './App'; +// A data router (rather than <BrowserRouter>) so the recipe editor can ask +// before leaving with unsaved changes (useBlocker). App keeps its <Routes>. +const router = createBrowserRouter([{ path: '*', element: <App /> }], { + basename: '/project2/', +}); + createRoot(document.getElementById('root')!).render( <StrictMode> - <BrowserRouter basename="/project2/"> - <App /> - </BrowserRouter> + <RouterProvider router={router} /> </StrictMode>, ); diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 5b5a12f..a4b00a7 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -85,3 +85,44 @@ describe('cookie authentication store', () => { }, ); }); +describe('drafts on sign-out', () => { + it('removes the signed-out user’s recipe drafts only', async () => { + localStorage.clear(); + localStorage.setItem(`recipe-platform:draft:${user.id}:new`, '{}'); + localStorage.setItem('recipe-platform:draft:someone-else:new', '{}'); + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); + vi.mocked(signOutUser).mockResolvedValue(true); + await useAppStore.getState().signOut(); + expect( + localStorage.getItem(`recipe-platform:draft:${user.id}:new`), + ).toBeNull(); + expect(localStorage.getItem('recipe-platform:draft:someone-else:new')).toBe( + '{}', + ); + }); + + it('clears the drafts of the user who signed out, even if the user changes meanwhile', async () => { + localStorage.clear(); + localStorage.setItem(`recipe-platform:draft:${user.id}:new`, '{}'); + localStorage.setItem('recipe-platform:draft:next-user:new', '{}'); + useAppStore.setState({ currentUser: user, sessionStatus: 'authenticated' }); + let finishSignOut!: (value: boolean) => void; + vi.mocked(signOutUser).mockReturnValue( + new Promise((resolve) => (finishSignOut = resolve)), + ); + const signingOut = useAppStore.getState().signOut(); + // Another auth change lands while the sign-out request is in flight. + useAppStore.setState({ + currentUser: { ...user, id: 'next-user' }, + sessionStatus: 'authenticated', + }); + finishSignOut(true); + await signingOut; + expect( + localStorage.getItem(`recipe-platform:draft:${user.id}:new`), + ).toBeNull(); + expect(localStorage.getItem('recipe-platform:draft:next-user:new')).toBe( + '{}', + ); + }); +}); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 9386b69..e7e69d6 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -7,6 +7,7 @@ import { signOutUser, } from './features/auth/authApi'; import type { User } from './types/user'; +import { clearUserDrafts } from './lib/recipeDrafts'; // Ignore restoration responses that finish after a newer auth action. let authVersion = 0; @@ -20,11 +21,14 @@ export type SessionStatus = // Remove credentials left by the old token-based client during migration. const LEGACY_TOKEN_KEY = 'recipe-platform-session-token'; +/* + * Global client state: only the signed-in user and session status. + * Search, filters, sorting and paging live in the URL (see the + * *UrlState.ts modules), and server data in useRecipeQuery's cache. + */ interface AppState { - search: string; currentUser: User | null; sessionStatus: SessionStatus; - setSearch: (search: string) => void; login: (email: string, password: string) => Promise<void>; @@ -34,13 +38,10 @@ interface AppState { signOut: () => Promise<void>; } -export const useAppStore = create<AppState>((set) => ({ - search: '', +export const useAppStore = create<AppState>((set, get) => ({ currentUser: null, sessionStatus: 'restoring', - setSearch: (search) => set({ search }), - login: async (email, password) => { const result = await loginUser(email, password); @@ -86,10 +87,15 @@ export const useAppStore = create<AppState>((set) => ({ }, signOut: async () => { + // Read the user before awaiting: by the time sign-out finishes, the + // current user may already be someone else (or nobody). + const userId = get().currentUser?.id; // Do not claim logout succeeded while the server session is still active. await signOutUser(); authVersion += 1; localStorage.removeItem(LEGACY_TOKEN_KEY); + // Recipe drafts are personal; do not leave them on a shared computer. + if (userId) clearUserDrafts(userId); set({ currentUser: null, sessionStatus: 'anonymous' }); }, })); diff --git a/apps/web/src/styles/style_guide/StylesGuide.tsx b/apps/web/src/styles/style_guide/StylesGuide.tsx index 561a10c..12b5ae9 100644 --- a/apps/web/src/styles/style_guide/StylesGuide.tsx +++ b/apps/web/src/styles/style_guide/StylesGuide.tsx @@ -38,7 +38,7 @@ const tokenRows = [ function StylesGuide() { return ( - <main className="container"> + <section className="container"> <div className="flex flex-col gap-8"> <header className="flex flex-col gap-2"> <h1>Styles Guide</h1> @@ -182,7 +182,7 @@ function StylesGuide() { > <Example title="Centered page content" - code={`<main className="container">...</main>`} + code={`<section className="container">...</section>`} /> <Example @@ -297,7 +297,7 @@ function StylesGuide() { </div> </section> </div> - </main> + </section> ); } diff --git a/apps/web/src/styles/style_tests/ColorAndStateTest.tsx b/apps/web/src/styles/style_tests/ColorAndStateTest.tsx index 890695b..d546a31 100644 --- a/apps/web/src/styles/style_tests/ColorAndStateTest.tsx +++ b/apps/web/src/styles/style_tests/ColorAndStateTest.tsx @@ -108,7 +108,7 @@ const borders = [ function ColorAndStateTest() { return ( - <main className="container"> + <section className="container"> <div className="flex flex-col gap-8"> <header className="flex flex-col gap-2"> <h1>Color & State Test</h1> @@ -465,7 +465,7 @@ function ColorAndStateTest() { </div> </section> </div> - </main> + </section> ); } diff --git a/apps/web/src/styles/style_tests/FoundationStressTest.tsx b/apps/web/src/styles/style_tests/FoundationStressTest.tsx index 8bf36c0..0e9919e 100644 --- a/apps/web/src/styles/style_tests/FoundationStressTest.tsx +++ b/apps/web/src/styles/style_tests/FoundationStressTest.tsx @@ -11,7 +11,7 @@ function FoundationStressTest() { const [moved, setMoved] = useState(false); return ( - <main className="container"> + <section className="container"> <div className="flex flex-col gap-8"> <header className="flex flex-col gap-2"> <h1>Foundation Stress Test</h1> @@ -528,7 +528,7 @@ function FoundationStressTest() { </div> </section> </div> - </main> + </section> ); } diff --git a/apps/web/src/styles/style_tests/LayoutUtilitiesTest.tsx b/apps/web/src/styles/style_tests/LayoutUtilitiesTest.tsx index c1b7826..9b70f3c 100644 --- a/apps/web/src/styles/style_tests/LayoutUtilitiesTest.tsx +++ b/apps/web/src/styles/style_tests/LayoutUtilitiesTest.tsx @@ -14,7 +14,7 @@ const testAreaStyle = { function LayoutUtilitiesTest() { return ( - <main className="container"> + <section className="container"> <div className="flex flex-col gap-8"> <header className="flex flex-col gap-2"> <h1>Layout Utilities Test</h1> @@ -340,7 +340,7 @@ function LayoutUtilitiesTest() { </p> </section> </div> - </main> + </section> ); } diff --git a/apps/web/src/styles/style_tests/TypographyTest.tsx b/apps/web/src/styles/style_tests/TypographyTest.tsx index c4bcc09..49325dd 100644 --- a/apps/web/src/styles/style_tests/TypographyTest.tsx +++ b/apps/web/src/styles/style_tests/TypographyTest.tsx @@ -1,6 +1,6 @@ function TypographyTest() { return ( - <main className="container"> + <section className="container"> <div className="flex flex-col gap-8"> <header className="flex flex-col gap-2"> <h1>Typography Test</h1> @@ -241,7 +241,7 @@ function TypographyTest() { </div> </section> </div> - </main> + </section> ); } 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<T> = | { [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<RecipeFieldsFragment, unknown>; -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<RecipeSummaryFieldsFragment, unknown>; -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<HealthQuery, HealthQueryVariables>; -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<SignOutMutation, SignOutMutationVariables>; -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<RegisterMutation, RegisterMutationVariables>; -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<LoginMutation, LoginMutationVariables>; -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<CurrentUserQuery, CurrentUserQueryVariables>; -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<RecipesQuery, RecipesQueryVariables>; -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<RecipeQuery, RecipeQueryVariables>; -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<CookbookQuery, CookbookQueryVariables>; -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<TResult, TVariables> + extends String + implements DocumentTypeDecoration<TResult, TVariables> +{ + __apiType?: NonNullable< + DocumentTypeDecoration<TResult, TVariables>['__apiType'] + >; + private value: string; + public __meta__?: Record<string, any> | undefined; + + constructor(value: string, __meta__?: Record<string, any> | undefined) { + super(value); + this.value = value; + this.__meta__ = __meta__; + } + + override toString(): string & DocumentTypeDecoration<TResult, TVariables> { + 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<RecipeFieldsFragment, unknown>; +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<RecipeSummaryFieldsFragment, unknown>; +export const HealthDocument = new TypedDocumentString(` + query Health { + health +} + `) as unknown as TypedDocumentString<HealthQuery, HealthQueryVariables>; +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<LoginMutation, LoginMutationVariables>; +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<RecipesQuery, RecipesQueryVariables>; +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<RecipeQuery, RecipeQueryVariables>; +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<CookbookQuery, CookbookQueryVariables>; +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<SaveRecipeMutation, SaveRecipeMutationVariables>; -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<RateRecipeMutation, RateRecipeMutationVariables>; -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/ <Directory /srv/t31-project2/current/apps/web/dist/> Require all granted FallbackResource /project2/index.html + <IfModule mod_headers.c> + # index.html and other unhashed files: always ask for the latest deploy. + Header set Cache-Control "no-cache" + </IfModule> </Directory> +<IfModule mod_headers.c> + # 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. + <LocationMatch "^/project2/assets/"> + Header set Cache-Control "public, max-age=31536000, immutable" + </LocationMatch> +</IfModule> +# 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 = '<velg et demopassord med minst 12 tegn>' -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<string, unknown>; + 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<void>((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<number | null> = []; + 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 <select> 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 -- <count> | --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<T, V> = DocumentTypeDecoration<T, V> & { + 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<string, string> = {}, + ) => + 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'], }, }, {