diff --git a/.gitignore b/.gitignore index 0e00e5c3..551884ba 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,9 @@ dist-ssr # Test coverage coverage +# Raw Perenual API responses cached by backend/seedDataFetch.js +backend/data/ + # Environment variables (.env.example and frontend/.env.production are committed on purpose) .env *.local diff --git a/README.md b/README.md index 0a6432c7..5b48323e 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,8 @@ I <3 Plants is a web app for finding plants that suit you and reading about them ## Concept - **The problem:** A long plant catalogue is hard to get started with if you do not know what you are looking for. -- **The idea:** Instead of scrolling through a long list, you first choose your preferences for water, sun and care. The app then shows you one plant at a time, starting with the plants that match your preferences best. You like or skip each plant, and the ones you like are saved in My Matches so you can come back to them later. -- **Low threshold:** There is no login. A user is created the first time the app is opened, so anyone can start finding plants right away, without creating an account. -- **For those who know what they want:** Users who already know what they are looking for can search and filter the whole collection instead. +- **The idea:** Instead of scrolling through a long list, you can easily match with plants by either swiping right or left on them. You can also set your preferences for water, sun and care if you know them, or take the plant owner test and get suggestions for preferences. Your preferences will be highlighted on the plants, and the plants that match your preferences best will be shown first. The ones you like are saved in My Matches so you can come back to them later. Alternatively, if you know what plant you want to read about, you can search for it directly on the Explore Plants page. +- **Low threshold:** There is no login. A user is created the first time the app is opened and is connected to your browser, so anyone can start finding plants right away, without creating an account. ## Link to VM @@ -15,20 +14,24 @@ http://it2810-03.idi.ntnu.no/project2/ ## Documentation -| Document | Contents | -| --------------------------------------- | ------------------------------------------------------------------------------------------------- | -| [architecture.md](docs/architecture.md) | How the frontend, backend and database fit together, the plant data, data flow and code structure | -| [tests.md](docs/tests.md) | Test strategy, how to run the tests, coverage and what the tests found | -| [quality.md](docs/quality.md) | Work practices, accessibility, sustainable web development and design choices | -| [ai-usage.md](docs/ai-usage.md) | How AI tools were used during development | +| Document | Contents | +| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| [architecture.md](docs/architecture.md) | How the frontend, backend and database fit together, the plant data, data flow, code structure and the architecture choices | +| [tests.md](docs/tests.md) | Test strategy, how to run the tests, coverage and what the tests found | +| [quality.md](docs/quality.md) | Work practices, accessibility, sustainable web development and design choices | +| [ai-usage.md](docs/ai-usage.md) | How AI tools were used during development | ## Core features -- **Plant Match:** The user swipes the card right to match with a plant and left to skip it, or uses the ♥ and ✖ buttons. Plants matching the most preferences come first, otherwise the order is random. The deck is kept while the user visits other pages, so they can continue where they left off. -- **My Matches:** Collects liked plants from both Plant Match and Explore Plants, with the same search, filters and match counts as Explore Plants. Both pages can also sort the plants by how well they match the user's preferences. The user only stores plant ids, and the list is fetched one page at a time, so responses do not grow with the number of matches. -- **Explore Plants:** Search, filtering, sorting and pagination run in the backend, so the frontend only receives one page at a time, whatever the size of the collection. The state is kept in the URL, so a view survives a refresh and can be shared as a link. Each filter value shows how many plants it would give, and values that would give none can't be chosen, so filtering never ends in an empty list. -- **Plant Owner Test:** Four questions give one of six plant owner types, whose picture can be used as profile picture. The result also suggests one preference each for watering, light and care level, based on the answers and the description of the type. The user chooses which of them to add, and they are added to the preferences they already have, so PlantMatch puts plants that suit them first right away. -- **Walkthrough:** A short guide opens on the first visit and explains what the user can do on each page. It can be reopened at any time with the ? button, starts at the current page (or at the welcome step on the home page), links to each page and lets the user change language without closing it. +- **Plant Match:** The user swipes the card right to match with a plant and left to skip it, or uses the ♥ and ✖ buttons. Plants matching the most preferences come first, otherwise the order is random. This is to make it easier for the user to find plants they are compatible with. When plants are matched on Plant Match or Explore Plants, a badge on My Matches in the sidebar shows how many plants have been matched since the page was last opened, to make it easier to understand where the matches end up. + +- **My Matches:** Collects the plants the user has liked (♥) on Plant Match and Explore Plants, and lets them search, filter and sort among them, with a count of how many matches they have. + +- **Explore Plants:** The page where the user can find specific plants they are searching for without having matched with them. Search, filtering and sorting are possible. The state is kept in the URL, so a view survives a refresh and the user can share the page as a link. + +- **Plant Owner Test:** A short test (four questions) to give the user insight into what kind of plant owner they are. It is meant to help them set one preference each for watering, light and care level, based on the answers and the description of the type. It also gives an avatar that can be used as a profile picture that can only be achieved through the test to communicate the type of plant owner the user is. + +- **Walkthrough:** A short guide opens on the first visit and explains what the user can do on each page. It can be reopened at any time with the ? button. It is meant to help with any confusion connected to how the application works, and help the user to get started. ## Tech stack @@ -40,10 +43,6 @@ http://it2810-03.idi.ntnu.no/project2/ | Testing | Vitest, React Testing Library, jsdom, mongodb-memory-server, Playwright, axe-core | | Tooling | ESLint, Prettier, GitHub Actions | -## Architecture - -See [architecture.md](docs/architecture.md) for how the frontend, backend and database fit together, and how the code is organised. It also describes the plant data and the Perenual API, why we chose GraphQL and MongoDB, and how the data flows from the API to the frontend. - ## Run the project locally ### Requirements @@ -53,8 +52,6 @@ See [architecture.md](docs/architecture.md) for how the frontend, backend and da - Access to the NTNU network (use the NTNU VPN if you are not on campus) - An NTNU user with access to the VM `it2810-03.idi.ntnu.no` -The local backend uses the database on the VM, which is why you need the NTNU network and a user on the VM. - ### 1. Install dependencies ```bash @@ -71,7 +68,7 @@ This installs the dependencies for the repo root, `backend` and `frontend`, whic cp backend/.env.example backend/.env ``` -The backend reads the database address, the database name and its port from this file. The default values work as they are. `.env` is ignored by git and must never be committed. +The backend reads the database address, the database name and its port from this file. The default values work as they are. `PERENUAL_API_KEY` can be left empty, since it is only used by the seed script (`npm run seed`), which the running app does not need. `.env` is ignored by git and must never be committed. ### 3. Open an SSH tunnel to the database (in a separate PC-terminal) @@ -117,10 +114,31 @@ Apache serves the built frontend on the VM. The build was copied to the folder A MongoDB is installed directly on the VM and only listens on `127.0.0.1`, so it cannot be reached from outside the VM. The plant data was loaded once with `npm run seed` in the backend, so the running app never calls the Perenual API and is not limited by its daily request quota (see [architecture.md](docs/architecture.md#data-source-the-perenual-api)). +### How to start the backend if it stops + +On the VM, the backend runs in pm2 under the name `plants-backend`, as the user `alexajah`, from `/home/alexajah/T03-Project-2/backend`. pm2 restarts it if it crashes or the VM reboots. + +Log in with: + +```bash +ssh @it2810-03.idi.ntnu.no +``` + +If you are not `alexajah`, put `sudo -u alexajah` in front of the pm2 commands, since pm2 only shows the processes of the user who started them. + +```bash +pm2 list # is plants-backend online? +pm2 restart plants-backend # start it again if it is not +``` + +If the logs show that the backend cannot connect to MongoDB, the database has stopped and must be started before the backend is restarted. + ## Testing The application is tested on three levels: component tests for the frontend (Vitest and React Testing Library), backend tests against an in-memory MongoDB (Vitest and mongodb-memory-server), and end-to-end and API tests with Playwright, which also check all pages against WCAG 2.1 AA with axe. Each level has its own purpose: the component and backend tests are fast and test one part at a time, also cases that are hard to reach through the UI, while the end-to-end tests check that the parts work together the way a user experiences them. None of the tests use the database on the VM. The backend and e2e tests use an in-memory MongoDB filled with known test data, so every run starts from the same data, the tests never change real user data, and they need neither the VPN nor the SSH tunnel. The tests run in GitHub Actions on every pull request, so a change that breaks a test is caught before it is merged. +The first time you run the e2e tests, install the browser with `npx playwright install chromium`. If the tests do not start, see [If the tests do not start](docs/tests.md#if-the-tests-do-not-start). + Run the tests from the repo root: ```bash @@ -131,21 +149,15 @@ npm run test:e2e `npm run test:all` runs all three after each other, and `npm run ci:all` first does a clean install (`npm ci`) in the root, backend and frontend, and then runs all the tests. Only run one e2e test run at a time, since all the e2e tests share the same test database and servers. -The first time you run the e2e tests, install the browser with `npx playwright install chromium`. - ### Test coverage | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 97.38 % | 93.86 % | 96.76 % | 98.39 % | +| Frontend | 97.44 % | 93.78 % | 96.83 % | 98.43 % | | Backend | 100 % | 100 % | 100 % | 100 % | See [tests.md](docs/tests.md) for the test strategy, more ways to run the tests, how to run the tests with coverage and screenshots of the coverage reports, what the test files cover and what the tests found. -## Quality and design - -See [quality.md](docs/quality.md) for work practices, accessibility, sustainable web development and design choices. - ## Known issues - The plant images are stored as base64 in the database, which takes about 33 % more space than image files. See [Limitations of the architecture](docs/architecture.md#limitations-of-the-architecture) for why we chose it and how it could be improved. diff --git a/backend/package-lock.json b/backend/package-lock.json index 96af9e68..2d38dfea 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -32,7 +32,7 @@ "vitest": "^5.0.5" }, "engines": { - "node": ">=20" + "node": ">=24.6" } }, "node_modules/@apollo/cache-control-types": { @@ -74,7 +74,6 @@ "resolved": "https://registry.npmjs.org/@apollo/server/-/server-5.5.2.tgz", "integrity": "sha512-VTEEQdI2T6L5h9DFe/Bh75EBnGabqdFvYYbLjGwJ2G2kKik5gWINBpkK6vLfEwBaSgL2mBjd1o9GDBn+xde/AQ==", "license": "MIT", - "peer": true, "dependencies": { "@apollo/cache-control-types": "^1.0.3", "@apollo/server-gateway-interface": "^2.0.0", @@ -404,6 +403,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -1179,6 +1179,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@tybys/wasm-util": "^0.10.3" }, @@ -1200,6 +1201,7 @@ "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/oxc-project" } @@ -1280,6 +1282,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1297,6 +1300,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1314,6 +1318,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1331,6 +1336,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1348,6 +1354,7 @@ "os": [ "freebsd" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1365,6 +1372,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1382,6 +1390,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1399,6 +1408,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1416,6 +1426,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1433,6 +1444,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1450,6 +1462,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1467,6 +1480,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1484,6 +1498,7 @@ "os": [ "openharmony" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1498,6 +1513,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@emnapi/core": "2.0.0-beta.2", "@emnapi/runtime": "2.0.0-beta.2", @@ -1520,6 +1536,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1537,6 +1554,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1546,7 +1564,8 @@ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@tybys/wasm-util": { "version": "0.10.5", @@ -1555,6 +1574,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -1772,7 +1792,6 @@ "integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.73.0", "@typescript-eslint/types": "8.73.0", @@ -1970,7 +1989,6 @@ "integrity": "sha512-xL4NkbVx/UqqDHaXSOyvB8qsSoLQ+dVNGR9H2Bh/4ggQtmaPFNPUC9gZQwKZePLOQ6WDcgwXVnPulFW9eCHt0w==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/istanbul-lib-coverage": "^2.1.0", @@ -2086,7 +2104,6 @@ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -2228,7 +2245,6 @@ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", "dev": true, "license": "Apache-2.0", - "peer": true, "peerDependencies": { "bare-abort-controller": "*" }, @@ -2608,6 +2624,7 @@ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "dev": true, "license": "Apache-2.0", + "peer": true, "engines": { "node": ">=8" } @@ -2764,7 +2781,6 @@ "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", "dev": true, "license": "MIT", - "peer": true, "workspaces": [ "packages/*" ], @@ -2974,7 +2990,6 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", "license": "MIT", - "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", @@ -3315,7 +3330,6 @@ "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.15.0.tgz", "integrity": "sha512-32kz9FecohDiC/tgcViwnRXM7HFBVTPiW7pHO+DikKOI5KjhU/jNULOReXsrFqt2WAYbE9xFXsTffJw6iTO8qw==", "license": "MIT", - "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -3572,7 +3586,6 @@ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -3597,6 +3610,7 @@ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", + "peer": true, "dependencies": { "detect-libc": "^2.0.3" }, @@ -3634,6 +3648,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3655,6 +3670,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3676,6 +3692,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3697,6 +3714,7 @@ "os": [ "freebsd" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3718,6 +3736,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3739,6 +3758,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3760,6 +3780,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3781,6 +3802,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3802,6 +3824,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3823,6 +3846,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3844,6 +3868,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -4195,6 +4220,7 @@ } ], "license": "MIT", + "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -4422,7 +4448,8 @@ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "dev": true, - "license": "ISC" + "license": "ISC", + "peer": true }, "node_modules/picomatch": { "version": "4.0.7", @@ -4430,7 +4457,6 @@ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -4536,6 +4562,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", @@ -4660,6 +4687,7 @@ "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" @@ -5118,7 +5146,6 @@ "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "~0.28.0" }, @@ -5196,7 +5223,6 @@ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -5349,7 +5375,6 @@ "integrity": "sha512-trVmzUFOSraCZcI3uZIMD5FqBh4atFkC/XuJP/IU7qtyQay0FCs3Ia+0QiQ2JJwGyWG/xrcBoJNel2+O7kEZ0g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.1.1", diff --git a/backend/package.json b/backend/package.json index 0b370516..fbc1cad4 100644 --- a/backend/package.json +++ b/backend/package.json @@ -6,7 +6,7 @@ "type": "module", "private": true, "engines": { - "node": ">=20" + "node": ">=24.6" }, "scripts": { "dev": "tsx watch src/server.ts", diff --git a/backend/seedDataFetch.js b/backend/seedDataFetch.js index 4d0fd565..a0674479 100644 --- a/backend/seedDataFetch.js +++ b/backend/seedDataFetch.js @@ -1,13 +1,13 @@ // Fetches plant data and images from the Perenual API and stores them in MongoDB. // Run from backend/ with the SSH tunnel open: npm run seed -// Delete the whole database and load everything again: npm run seed:reset +// Delete the plants collection and load everything again: npm run seed:reset // // Phase 1: species-list -> clean -> upsert into "plants" (one row per plant, key: perenualId) // + download the image, base64-encode it and store it as a data URI in imageData // Phase 2: species/details/{id} for the plants from phase 1 -> clean -> update the same document // // The image URLs from Perenual are signed links that expire after 24 hours. That is why the -// plant list is always fetched fresh from the API (3 calls), and the image is downloaded right away. +// plant list is always fetched fresh from the API (4 calls), and the image is downloaded right away. // // Raw responses from species/details are stored in data/raw/. If the file already exists, it is // used instead of a new API call. The script can therefore be run several times (e.g. over several @@ -27,8 +27,8 @@ const MAX_FREE_DETAILS_ID = 3000; const DELAY_MS = 1000; // pause between calls so we don't spam the API const RESET = process.argv.includes("--reset"); -// Which image size we store, in order of priority. Smaller images give smaller -// GraphQL responses, since the image is included in getPlants. +// Which image size we store, in order of priority. Smaller images are faster +// for the browser to load from /images/:id and take less space in the database. const IMAGE_SIZES = ["small_url", "medium_url", "regular_url"]; const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "image/webp"]; @@ -258,7 +258,9 @@ try { // Check the key before anything is deleted, otherwise we are left with an empty database if (!API_KEY) throw new Error("PERENUAL_API_KEY is missing in .env"); if (RESET) { - console.log(`Deleting the whole database "${db.databaseName}"...`); + console.log( + `Deleting the plants collection in the database "${db.databaseName}"...`, + ); await plants.drop(); } await plants.createIndex({ perenualId: 1 }, { unique: true }); diff --git a/backend/src/app.ts b/backend/src/app.ts index e485f637..adbfaa65 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -1,18 +1,46 @@ import express from "express"; import cors from "cors"; import { ApolloServer } from "@apollo/server"; +import { + ApolloServerErrorCode, + unwrapResolverError, +} from "@apollo/server/errors"; import { expressMiddleware } from "@as-integrations/express5"; import { resolvers } from "./resolvers/index.js"; import { typeDefs } from "./schema.js"; import { sendPlantImage } from "./images.js"; +// The message the client gets for an unexpected error on the server +export const INTERNAL_ERROR_MESSAGE = "Internal server error"; + // The backend app: the GraphQL API on /graphql and the plant images on // /images/:id. Express is used instead of Apollo's standalone server, since // that one can only serve GraphQL and not the images next to it. // Returns the Apollo server too, so the tests can send it GraphQL requests // without opening a port. export async function createApp() { - const apollo = new ApolloServer({ typeDefs, resolvers }); + const apollo = new ApolloServer({ + typeDefs, + resolvers, + // Apollo adds stack traces to errors unless NODE_ENV is "production" or + // "test". They are turned off here, so they are never sent to the client, + // however the backend is started. + includeStacktraceInErrorResponses: false, + // Errors the client caused (invalid input, invalid GraphQL) are sent as + // they are, since their messages explain what to fix. An unexpected error, + // e.g. from the database, can contain internal details such as addresses, + // so it is logged on the server and the client only gets a general message. + formatError: (formattedError, error) => { + if ( + formattedError.extensions?.code !== + ApolloServerErrorCode.INTERNAL_SERVER_ERROR + ) { + return formattedError; + } + console.error(unwrapResolverError(error)); + return { ...formattedError, message: INTERNAL_ERROR_MESSAGE }; + }, + }); await apollo.start(); const app = express(); diff --git a/backend/src/queryBuilders.ts b/backend/src/queryBuilders.ts index e0e23a90..f28751ca 100644 --- a/backend/src/queryBuilders.ts +++ b/backend/src/queryBuilders.ts @@ -1,4 +1,4 @@ -import type { Document, Filter, ObjectId } from "mongodb"; +import { ObjectId, type Document, type Filter } from "mongodb"; import type { FilterCounts, FilterParam, @@ -6,7 +6,7 @@ import type { PlantFilterArgs, } from "./types.js"; -// Helpers for searching, filtering and sorting plants +// Helpers for searching, filtering, sorting and paginating plants // Escape user input so it can't be interpreted as regex const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -22,9 +22,28 @@ export const FILTER_OPTIONS: Record = { careLevel: ["low", "medium", "high"], }; -// Sorted by name A–Z, with _id as a tie-breaker so the order is stable. -// Uses the index from indexes.ts. -const BY_NAME = { commonName: 1, _id: 1 } as const; +// 1 is A–Z, -1 is Z–A +export type NameSortDirection = 1 | -1; + +// Sorted by name, with _id as a tie-breaker so the order is stable. Uses the +// index from indexes.ts. Z–A also reverses _id, so the index is read backwards. +export const byName = (direction: NameSortDirection) => + ({ commonName: direction, _id: direction }) as const; +const BY_NAME = byName(1); + +// How the plants are sorted: the aggregation stages, and whether the order is +// a plain name sort. Only a name sort can be paged with a cursor (see +// cursorFilter below), since its order is read straight from an index. +// The other sort orders are calculated, so they are paged with an offset. +export type SortPlan = { + stages: Document[]; + nameDirection: NameSortDirection | null; +}; + +const nameSortPlan = (direction: NameSortDirection): SortPlan => ({ + stages: [{ $sort: byName(direction) }], + nameDirection: direction, +}); // Position in the order list, unknown or missing values go last const rankOf = (order: string[], value: unknown): Document => ({ @@ -43,85 +62,96 @@ export const knownPreferences = (preferences?: string[] | null): string[] => // The plants matching the most of the given preferences first, with the same // score as Plant Match uses. Plants that match equally well are sorted by // name. Without preferences, the plants are sorted by name. -const byPreferenceStages = (preferences: string[]): Document[] => +const byPreference = (preferences: string[]): SortPlan => preferences.length === 0 - ? [{ $sort: BY_NAME }] - : [ - { $addFields: { matchScore: matchScore(preferences) } }, - { $sort: { matchScore: -1, ...BY_NAME } }, - ]; + ? nameSortPlan(1) + : { + stages: [ + { $addFields: { matchScore: matchScore(preferences) } }, + { $sort: { matchScore: -1, ...BY_NAME } }, + ], + nameDirection: null, + }; -// Builds the aggregation stages that handle sorting. preferences is only -// used by the "preferences" sort order. -export const buildSortStages = ( - sort?: string, +// Decides how Explore Plants is sorted. preferences is only used by the +// "preferences" sort order. +export const buildSortPlan = ( + sort?: string | null, preferences: string[] = [], -): Document[] => { +): SortPlan => { switch (sort) { case "preferences": - return byPreferenceStages(preferences); + return byPreference(preferences); case "name_desc": - // _id is also reversed, so the sort can read the commonName index backwards - return [{ $sort: { commonName: -1, _id: -1 } }]; + return nameSortPlan(-1); case "watering_asc": - return [ - { - $addFields: { - sortRank: rankOf(FILTER_OPTIONS.watering, { - $toLower: "$watering", - }), + return { + stages: [ + { + $addFields: { + sortRank: rankOf(FILTER_OPTIONS.watering, { + $toLower: "$watering", + }), + }, }, - }, - { $sort: { sortRank: 1, ...BY_NAME } }, - ]; + { $sort: { sortRank: 1, ...BY_NAME } }, + ], + nameDirection: null, + }; case "careLevel_asc": // "Moderate" and "Medium" both exist in the data, treat them as equal - return [ - { - $addFields: { - sortRank: rankOf(FILTER_OPTIONS.careLevel, { - $let: { - vars: { c: { $toLower: { $ifNull: ["$careLevel", ""] } } }, - in: { - $cond: [{ $eq: ["$$c", "moderate"] }, "medium", "$$c"], + return { + stages: [ + { + $addFields: { + sortRank: rankOf(FILTER_OPTIONS.careLevel, { + $let: { + vars: { c: { $toLower: { $ifNull: ["$careLevel", ""] } } }, + in: { + $cond: [{ $eq: ["$$c", "moderate"] }, "medium", "$$c"], + }, }, - }, - }), + }), + }, }, - }, - { $sort: { sortRank: 1, ...BY_NAME } }, - ]; + { $sort: { sortRank: 1, ...BY_NAME } }, + ], + nameDirection: null, + }; default: - return [{ $sort: BY_NAME }]; + return nameSortPlan(1); } }; -// Builds the aggregation stages that sort the user's matched plants on My Matches. +// Decides how the user's matched plants on My Matches are sorted. // matchedPlantIds is in the order the plants were matched, so a plant's // position in it tells how new the match is. -export const buildMatchSortStages = ( - sort: string | undefined, +export const buildMatchSortPlan = ( + sort: string | null | undefined, matchedPlantIds: ObjectId[], preferences: string[] = [], -): Document[] => { - const byMatchOrder = (direction: 1 | -1): Document[] => [ - { - $addFields: { - matchOrder: { $indexOfArray: [matchedPlantIds, "$_id"] }, +): SortPlan => { + const byMatchOrder = (direction: 1 | -1): SortPlan => ({ + stages: [ + { + $addFields: { + matchOrder: { $indexOfArray: [matchedPlantIds, "$_id"] }, + }, }, - }, - { $sort: { matchOrder: direction } }, - ]; + { $sort: { matchOrder: direction } }, + ], + nameDirection: null, + }); switch (sort) { case "preferences": - return byPreferenceStages(preferences); + return byPreference(preferences); case "oldest": return byMatchOrder(1); case "name_asc": - return [{ $sort: BY_NAME }]; + return nameSortPlan(1); case "name_desc": - return [{ $sort: { commonName: -1, _id: -1 } }]; + return nameSortPlan(-1); default: // Newest first is the default, since those are usually // the ones the user wants to see @@ -129,6 +159,57 @@ export const buildMatchSortStages = ( } }; +// A cursor points at one plant in a name sort: its commonName and _id, which +// together are unique and are exactly the fields of the sort. It is sent to +// the client as base64url-encoded JSON, so the client treats it as an opaque +// string and never needs to know what is in it. +export type PlantCursor = { commonName: string; _id: ObjectId }; + +export const encodeCursor = (plant: PlantCursor): string => + Buffer.from( + JSON.stringify([plant.commonName, plant._id.toHexString()]), + ).toString("base64url"); + +// The plant in a cursor, or null if the cursor is not one we made (it comes +// from the client, so it is checked instead of trusted) +export const decodeCursor = (cursor: string): PlantCursor | null => { + try { + const value: unknown = JSON.parse( + Buffer.from(cursor, "base64url").toString("utf8"), + ); + if ( + Array.isArray(value) && + value.length === 2 && + typeof value[0] === "string" && + typeof value[1] === "string" && + /^[0-9a-f]{24}$/i.test(value[1]) + ) { + return { commonName: value[0], _id: new ObjectId(value[1]) }; + } + } catch { + // Not base64-encoded JSON + } + return null; +}; + +// The plants that come after the cursor in a name sort in the given +// direction: a later name, or the same name and a later _id (the tie-breaker). +// MongoDB reads these straight from the commonName index, so a page deep in +// the list is as fast as the first one, unlike $skip, which has to read past +// every plant before the page. +export const cursorFilter = ( + cursor: PlantCursor, + direction: NameSortDirection, +): Document => { + const after = direction === 1 ? "$gt" : "$lt"; + return { + $or: [ + { commonName: { [after]: cursor.commonName } }, + { commonName: cursor.commonName, _id: { [after]: cursor._id } }, + ], + }; +}; + // Builds the MongoDB filter for the search and filters on Explore Plants and My Matches export const buildPlantFilter = (args: PlantFilterArgs): Filter => { const filter: Filter = {}; diff --git a/backend/src/resolvers/plants.ts b/backend/src/resolvers/plants.ts index b6f27467..8bd67438 100644 --- a/backend/src/resolvers/plants.ts +++ b/backend/src/resolvers/plants.ts @@ -2,10 +2,16 @@ import type { Document, Filter, WithId } from "mongodb"; import { buildPlantFilter, buildFilterCountStages, - buildSortStages, + buildSortPlan, + byName, + cursorFilter, + decodeCursor, + encodeCursor, knownPreferences, matchScore, toFilterCounts, + type NameSortDirection, + type SortPlan, } from "../queryBuilders.js"; import type { ExplorePlantsArgs, @@ -18,7 +24,13 @@ import type { } from "../types.js"; import { DEFAULT_PAGE_SIZE, MAX_LIMIT } from "../schema.js"; import { imagePath } from "../images.js"; -import { plants, toObjectId } from "./helpers.js"; +import { badInput, plants, toObjectId } from "./helpers.js"; + +// The longest search allowed. No plant name is anywhere near this long, so a +// longer search can't find anything, and it would only make the database run +// a needlessly large regular expression. Must match SEARCH_MAX_LENGTH in +// frontend/src/components/plantSearchForm/plantFilters.ts. +export const MAX_SEARCH_LENGTH = 100; // Keeps limit between 1 and MAX_LIMIT, and offset at 0 or more, so a bad value // from the client gives a valid page instead of an error from MongoDB. @@ -53,6 +65,53 @@ const withoutImageData: Document[] = [ { $project: { imageData: 0 } }, ]; +// The stages that pick out one page of the sorted plants. +// - With a cursor (after or before), the page starts right after or ends +// right before the plant in the cursor. This only works for the name sort +// orders, where MongoDB reads the page straight from the commonName index, +// so it is as fast deep in the list as on the first page. The frontend uses +// it for the next and previous page. +// - Otherwise the page is found with an offset ($skip), which works for every +// sort order and lets the user jump to any page number, but has to read +// past every plant before the page. +const pageStages = ( + filter: Filter, + args: PaginationArgs, + sort: SortPlan, +): Document[] => { + const limit = clampLimit(args.limit, DEFAULT_PAGE_SIZE); + if (args.after && args.before) { + throw badInput("Send either after or before, not both"); + } + const sentCursor = args.after || args.before; + if (!sentCursor) { + return [ + { $match: filter }, + ...sort.stages, + { $skip: clampOffset(args.offset) }, + { $limit: limit }, + ]; + } + + if (!sort.nameDirection) { + throw badInput("after and before can only be used when sorting by name"); + } + const cursor = decodeCursor(sentCursor); + if (!cursor) throw badInput("Invalid cursor"); + + // The page before the cursor is read backwards from the cursor, so the + // closest plants come first, and is then put back in the normal order + const direction = args.after + ? sort.nameDirection + : (-sort.nameDirection as NameSortDirection); + return [ + { $match: { $and: [filter, cursorFilter(cursor, direction)] } }, + { $sort: byName(direction) }, + { $limit: limit }, + ...(args.before ? [{ $sort: byName(sort.nameDirection) }] : []), + ]; +}; + // One page of plants for Explore Plants and My Matches: the plants matching the // base filter (on My Matches the user's matches) and the user's search and // filters, the total count, and the match counts for the filter values, so the @@ -61,17 +120,17 @@ const withoutImageData: Document[] = [ export const findPlantPage = async ( baseFilter: Filter, args: PlantFilterArgs & PaginationArgs, - sortStages: Document[], + sort: SortPlan, ): Promise => { + if ((args.search?.length ?? 0) > MAX_SEARCH_LENGTH) { + throw badInput(`Search can be at most ${MAX_SEARCH_LENGTH} characters`); + } const filter = { ...baseFilter, ...buildPlantFilter(args) }; const [docs, totalCount, [facets]] = await Promise.all([ plants .aggregate>([ - { $match: filter }, - ...sortStages, - { $skip: clampOffset(args.offset) }, - { $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) }, + ...pageStages(filter, args, sort), ...withoutImageData, ]) .toArray(), @@ -83,10 +142,17 @@ export const findPlantPage = async ( .toArray(), ]); + // Cursors only make sense for a name sort, and need a plant to point at + const first = docs.at(0); + const last = docs.at(-1); + const hasCursors = sort.nameDirection !== null && first && last; + return { plants: docs.map(toPlant), totalCount, filterCounts: toFilterCounts(facets), + startCursor: hasCursors ? encodeCursor(first) : null, + endCursor: hasCursors ? encodeCursor(last) : null, }; }; @@ -126,19 +192,7 @@ export const plantQueries = { .aggregate>([ { $match: { _id: { $nin: excluded } } }, ...orderStages, - { - $project: { - commonName: 1, - // Only whether there is an image, see withoutImageData - hasImage: { $gt: ["$imageData", null] }, - imageURL: 1, - scientificName: 1, - description: 1, - watering: 1, - sunlight: 1, - careLevel: 1, - }, - }, + ...withoutImageData, ]) .toArray(); return docs.map(toPlant); @@ -151,6 +205,6 @@ export const plantQueries = { findPlantPage( {}, args, - buildSortStages(args.sort, knownPreferences(args.preferences)), + buildSortPlan(args.sort, knownPreferences(args.preferences)), ), }; diff --git a/backend/src/resolvers/users.ts b/backend/src/resolvers/users.ts index c43a561f..cfb44b37 100644 --- a/backend/src/resolvers/users.ts +++ b/backend/src/resolvers/users.ts @@ -1,6 +1,6 @@ import type { Document, WithId } from "mongodb"; import { - buildMatchSortStages, + buildMatchSortPlan, knownPreferences, PREFERENCE_MATCHERS, toFilterCounts, @@ -107,7 +107,13 @@ export const userQueries = { : null; const matchedPlantIds = user?.matchedPlantIds ?? []; if (matchedPlantIds.length === 0) { - return { plants: [], totalCount: 0, filterCounts: toFilterCounts() }; + return { + plants: [], + totalCount: 0, + filterCounts: toFilterCounts(), + startCursor: null, + endCursor: null, + }; } // Only plants that still exist are shown and counted (e.g. after a reseed) @@ -115,7 +121,7 @@ export const userQueries = { { _id: { $in: matchedPlantIds } }, args, // The user's saved preferences, for the "preferences" sort order - buildMatchSortStages( + buildMatchSortPlan( args.sort, matchedPlantIds, knownPreferences(user?.preferences), diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 458580c9..81466120 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,10 +1,13 @@ -// The most plants one request can ask for. The plants include their images, -// so without a limit one request could fetch the whole collection. +// The most plants one request can ask for, so one request can't fetch the +// whole collection. export const MAX_LIMIT = 50; // The page size on Explore Plants and My Matches when the client sends no limit export const DEFAULT_PAGE_SIZE = 12; // The GraphQL schema. The resolvers are in the resolvers folder. +// explorePlants and myMatches are paged with offset, or, for the name sort +// orders, with after/before and the cursors in PlantPage (see findPlantPage +// in resolvers/plants.ts). export const typeDefs = ` type Query { getPlants(limit: Int = ${MAX_LIMIT}, excludeIds: [ID!], preferences: [String!]): [Plant] @@ -17,6 +20,8 @@ export const typeDefs = ` preferences: [String!] limit: Int = ${DEFAULT_PAGE_SIZE} offset: Int = 0 + after: String + before: String ): PlantPage! getUser(userId: ID!): User myMatches( @@ -28,6 +33,8 @@ export const typeDefs = ` sort: String limit: Int = ${DEFAULT_PAGE_SIZE} offset: Int = 0 + after: String + before: String ): PlantPage! } @@ -59,6 +66,8 @@ export const typeDefs = ` plants: [Plant!]! totalCount: Int! filterCounts: FilterCounts! + startCursor: String + endCursor: String } type Plant { diff --git a/backend/src/types.ts b/backend/src/types.ts index a3924a94..dbf75782 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -48,9 +48,14 @@ export interface PlantFilterArgs { // The sort order and page, on Explore Plants and My Matches. // Null if the client sends null explicitly, see clampLimit in resolvers/plants.ts export interface PaginationArgs { - sort?: string; + sort?: string | null; limit?: number | null; offset?: number | null; + // A cursor from the page the user is on (its endCursor or startCursor), to + // get the page right after or right before it. Only for the name sort + // orders. offset is ignored when one of them is sent. + after?: string | null; + before?: string | null; } export interface ExplorePlantsArgs extends PlantFilterArgs, PaginationArgs { @@ -76,6 +81,11 @@ export interface PlantPage { plants: Plant[]; totalCount: number; filterCounts: FilterCounts; + // Cursors for the first and the last plant on the page, to send as before + // and after for the previous and the next page. Null when the sort order + // can't be paged with a cursor, or the page is empty. + startCursor: string | null; + endCursor: string | null; } // The shape of a user document in MongoDB. _id is added by MongoDB. diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index 7b146978..8d2efaff 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -455,6 +455,16 @@ describe("plants", () => { expect((await explore({ search: ".*" })).totalCount).toBe(0); }); + it("accepts a search of 100 characters and rejects a longer one", async () => { + expect((await explore({ search: "a".repeat(100) })).totalCount).toBe(0); + + const result = await execute(EXPLORE, { search: "a".repeat(101) }); + expect(firstError(result)).toEqual({ + message: "Search can be at most 100 characters", + code: "BAD_USER_INPUT", + }); + }); + it("searches by scientific name", async () => { expect((await explore({ search: "ocimum basilicum" })).names).toEqual([ "Basil", @@ -624,6 +634,187 @@ describe("plants", () => { }); }); +// The next and previous page with a cursor (after/before), for the name sort +// orders. The pages must be exactly the same as with offset. +describe("cursor pagination", () => { + const CURSOR_PAGE = ` + query ($search: String, $sort: String, $limit: Int, $offset: Int, $after: String, $before: String) { + explorePlants(search: $search, sort: $sort, limit: $limit, offset: $offset, after: $after, before: $before) { + plants { name } + startCursor + endCursor + } + } + `; + + type CursorPage = { + names: string[]; + startCursor: string | null; + endCursor: string | null; + }; + + async function page(variables: Record): Promise { + const result = await execute<{ + explorePlants: { + plants: { name: string }[]; + startCursor: string | null; + endCursor: string | null; + }; + }>(CURSOR_PAGE, variables); + expect(result.errors).toBeUndefined(); + const { plants, startCursor, endCursor } = result.data!.explorePlants; + return { names: plants.map((p) => p.name), startCursor, endCursor }; + } + + // Three plants share a name, so the _id tie-breaker decides their order, + // and a page boundary falls between them + beforeEach(async () => { + await insertPlants( + { commonName: "Aloe" }, + { commonName: "Basil" }, + { commonName: "Basil" }, + { commonName: "Basil" }, + { commonName: "Cactus" }, + { commonName: "Daisy" }, + { commonName: "Fern" }, + ); + }); + + it.each(["name_asc", "name_desc"])( + "with %s, gives the same pages as offset, forwards with after and backwards with before", + async (sort) => { + const limit = 2; + const offsetPages: string[][] = []; + for (let offset = 0; offset < 7; offset += limit) { + offsetPages.push((await page({ sort, limit, offset })).names); + } + + // Forwards: each page starts after the last plant on the one before + const forwardPages: CursorPage[] = [await page({ sort, limit })]; + while (forwardPages.length < offsetPages.length) { + const after = forwardPages.at(-1)!.endCursor; + forwardPages.push(await page({ sort, limit, after })); + } + expect(forwardPages.map((p) => p.names)).toEqual(offsetPages); + + // Backwards from the last page: each page ends before the first plant + // on the one after it + const backwardPages: CursorPage[] = [forwardPages.at(-1)!]; + while (backwardPages.length < offsetPages.length) { + const before = backwardPages.at(-1)!.startCursor; + backwardPages.push(await page({ sort, limit, before })); + } + expect(backwardPages.map((p) => p.names).reverse()).toEqual(offsetPages); + }, + ); + + it("keeps the search when paging with a cursor, and ignores offset", async () => { + const first = await page({ search: "basil", limit: 2 }); + expect(first.names).toEqual(["Basil", "Basil"]); + + // offset would skip past every plant, but the cursor decides the page + const next = await page({ + search: "basil", + limit: 2, + offset: 100, + after: first.endCursor, + }); + expect(next.names).toEqual(["Basil"]); + }); + + it("gives an empty page and no cursors after the last plant", async () => { + const last = await page({ limit: 7 }); + + expect(await page({ limit: 7, after: last.endCursor })).toEqual({ + names: [], + startCursor: null, + endCursor: null, + }); + }); + + it("gives no cursors for the calculated sort orders", async () => { + for (const sort of ["watering_asc", "careLevel_asc"]) { + const result = await page({ sort, limit: 2 }); + expect(result.names).toHaveLength(2); + expect(result).toMatchObject({ startCursor: null, endCursor: null }); + } + }); + + it.each([ + [ + "a cursor with a calculated sort order", + async () => ({ + sort: "watering_asc", + after: (await page({ limit: 2 })).endCursor, + }), + "after and before can only be used when sorting by name", + ], + [ + "both after and before", + async () => { + const { startCursor, endCursor } = await page({ limit: 2 }); + return { after: endCursor, before: startCursor }; + }, + "Send either after or before, not both", + ], + [ + "a cursor that is not base64 JSON", + async () => ({ after: "%%%" }), + "Invalid cursor", + ], + [ + "a cursor with a malformed id", + async () => ({ + after: Buffer.from(JSON.stringify(["Aloe", "not-an-id"])).toString( + "base64url", + ), + }), + "Invalid cursor", + ], + ])("rejects %s", async (_, makeVariables, message) => { + const result = await execute(CURSOR_PAGE, await makeVariables()); + + expect(firstError(result)).toEqual({ message, code: "BAD_USER_INPUT" }); + }); + + it("pages My Matches with a cursor when sorted by name, but not newest first", async () => { + const { id } = await createUser(); + const plantIds = (await db.collection("plants").find().toArray()).map((p) => + p._id.toString(), + ); + for (const plantId of plantIds) await addMatch(id, plantId); + + const MATCHES = ` + query ($userId: ID!, $sort: String, $after: String) { + myMatches(userId: $userId, sort: $sort, limit: 5, after: $after) { + plants { name } + endCursor + } + } + `; + type Result = { + myMatches: { plants: { name: string }[]; endCursor: string | null }; + }; + + const first = await execute(MATCHES, { + userId: id, + sort: "name_asc", + }); + const next = await execute(MATCHES, { + userId: id, + sort: "name_asc", + after: first.data!.myMatches.endCursor, + }); + expect(next.data!.myMatches.plants.map((p) => p.name)).toEqual([ + "Daisy", + "Fern", + ]); + + const newest = await execute(MATCHES, { userId: id }); + expect(newest.data!.myMatches.endCursor).toBeNull(); + }); +}); + describe("users", () => { it("createUser makes an empty user and getUser finds it again", async () => { const user = await createUser(); @@ -1064,20 +1255,26 @@ describe("error messages", () => { }); }); - it("passes on the error when the database fails, and keeps running", async () => { + it("hides the details of a database error from the client, logs it, and keeps running", async () => { const { id } = await createUser(); - vi.spyOn(Collection.prototype, "findOne").mockRejectedValueOnce( - new Error("connection to MongoDB lost"), - ); + const dbError = new Error("connection to mongodb://10.0.0.5:27017 lost"); + vi.spyOn(Collection.prototype, "findOne").mockRejectedValueOnce(dbError); + const logError = vi.spyOn(console, "error").mockImplementation(() => {}); const failed = await getUser(id); expect(firstError(failed)).toEqual({ - message: "connection to MongoDB lost", + message: "Internal server error", code: "INTERNAL_SERVER_ERROR", }); + // Neither the message nor a stack trace reaches the client + expect(JSON.stringify(failed)).not.toContain("10.0.0.5"); + expect(JSON.stringify(failed)).not.toContain("stacktrace"); + // The real error is logged on the server, so it can be found + expect(logError).toHaveBeenCalledWith(dbError); expect(failed.data?.getUser).toBeNull(); // The next request works again expect((await getUser(id)).data?.getUser?.id).toBe(id); + logError.mockRestore(); }); }); diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 3bb3b356..4ecc4ea8 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -40,9 +40,9 @@ In retrospect, we should have added a shared context file, such as an `AGENTS.md AI helped us write [backend/seedDataFetch.js](../backend/seedDataFetch.js), which fetches the plant data from the Perenual API and stores it in MongoDB. This included: -- downloading each image and storing it as a base64 data URI, because the image URLs from Perenual expire after 24 hours -- caching the raw responses locally, so the same plant is never requested twice -- stopping before the daily quota of about 100 requests is used up, so the script can be run again the next day and continue where it left off +- Downloading each image and storing it as a base64 data URI, because the image URLs from Perenual expire after 24 hours +- Caching the raw responses locally, so the same plant is never requested twice +- Stopping before the daily quota of about 100 requests is used up, so the script can be run again the next day and continue where it left off We decided which fields to keep and how they are mapped to the GraphQL schema, and we checked the data in the database after each run. @@ -52,12 +52,14 @@ AI drafted many of the Vitest tests and the Playwright e2e and API tests, and su ### Refactoring after peer review -After the peer reviews, we used AI to help us split up `ExplorePlants.tsx`, which contained a lot of logic in one file. The team decided which parts should become reusable components and hooks, and AI helped us move the right code out of the file without changing how the page works. +After the peer reviews, we used AI to help us split up `ExplorePlants.tsx` (now `ExplorePlantsPage.tsx`), which contained a lot of logic in one file. The team decided which parts should become reusable components and hooks, and AI helped us move the right code out of the file without changing how the page works. ## How we kept control All AI-generated suggestions were reviewed, tested and adapted by the team before they were committed. Every change went through a pull request that had to be approved by another group member (see [quality.md](quality.md#work-practices)), so no AI-generated code was merged without a review. The tests and lint in GitHub Actions also had to pass. Design and architectural decisions were made by the team. +In retrospect, we could have added a shared context file for the AI tools we used, but none of us thought of this until the end of the project. This would have helped make sure all of them followed the same rules based on the project description, and we would do this in future projects. + ### Being critical of a suggestion from AI We did not always follow the suggestions from AI. For example, when My Matches was changed to fetch one page of plants at a time, the old `matchedPlants` field on the user was no longer used by the app. AI first suggested keeping the field because the tests used it, but we decided to remove it, since keeping unused code only for the tests made no sense. Before removing it, we searched the code for every place it was used, to make sure it was safe. Then we updated the tests to use the new field, and wrote new tests for the `myMatches` query. diff --git a/docs/architecture.md b/docs/architecture.md index 492ebbc7..65649e89 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,7 +1,6 @@ # Architecture -This document describes how the frontend, backend and database fit together, how data flows between them, and what is stored in each MongoDB collection. It also describes the plant data from the Perenual API, why we chose GraphQL and MongoDB, and where the app keeps state (database, `localStorage`, URL parameters or `sessionStorage`). -The folder structure is shown at the end of this document. +This document describes how the frontend, backend and database fit together, how data flows between them, and what is stored in each MongoDB collection. It follows the data: first where the plant data comes from (the Perenual API), then the database and why we chose MongoDB, the GraphQL backend and the design choices made for scalability, and the frontend and where it keeps state (database, `localStorage`, URL parameters or `sessionStorage`). It ends with the limitations of the architecture, and the folder structure and naming conventions for reference. ## Overview @@ -32,127 +31,43 @@ The plant data was fetched from the Perenual API once with the script `seedDataF 2. Apollo Server runs the matching resolver, which reads from or writes to the `plants` or `users` collection in MongoDB. 3. The resolver maps the database documents to the GraphQL types (for example `commonName` becomes `name`, and `_id` becomes `id`) and returns only the fields the frontend asked for. 4. The frontend receives the data as JSON, stores it in the Apollo cache and renders it. +5. The plant images are not part of the GraphQL response. A plant's `imageURL` is a link to `/images/` on the backend, and the browser loads each image from there as a file when the plant card is shown. The sections below describe each part in more detail. -## Frontend: React, TypeScript and Apollo Client - -The frontend is built with React and TypeScript (Vite). - -- **Routing:** Routes are defined in `AppRoutes.tsx` with React Router, and the app is served under the base path `/project2/`. Vite defines this base in `frontend/vite.config.ts`; `HashRouter` provides the client-side routes, including Explore query parameters after the hash. All pages except the start page are lazy-loaded. Any path that does not match a route shows the 404 page, and the header shows the "Page not found" title for it. - - | Route | Page | Purpose | - | ----------------- | -------------------- | ------------------------------------------------------------------------------------ | - | `/` | `PlantMatchPage` | Swipe through preference-ranked plants (`getPlants`) and match with them | - | `/explorePlants` | `ExplorePlantsPage` | Search, filter, sort and paginate all plants (`explorePlants`) | - | `/myMatches` | `MyMatchesPage` | Search, filter, sort, paginate and remove the user's matches (`myMatches`) | - | `/profile` | `ProfilePage` | Edit name, description, profile picture and preferences | - | `/plantOwnerTest` | `PlantOwnerTestPage` | A quiz whose result can be set as the profile picture, and that suggests preferences | - | `*` | `NotFoundPage` | 404 page for unknown paths, with a link back to Plant Match | - -- **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile`, `usePreferences` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). -- **Error messages:** `ErrorMessageProvider` (`context/ErrorMessageContext.tsx`) wraps the app and makes `showError()` available through `useErrorMessage()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails. -- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays search and profile saves while the user types. `useExploreParams` keeps the Explore search, filters, sort and page in the URL, and `useMyMatchesParams` keeps them in `sessionStorage` for My Matches, since a link to the user's matches could not be shared. `usePreferences` saves the preferences, both on the profile page and after the plant owner test. -- `usePlantDeck` keeps the remaining Plant Match cards in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored. -- **Swiping on Plant Match:** `PlantMatchPage` wraps the card in an element that follows the pointer (mouse, finger or pen) with Pointer Events. Dragging the card more than 100 px to the right matches the plant, and to the left skips it. A shorter drag springs back, a movement of less than 8 px counts as a tap and flips the card as before, and a movement that is mostly up or down is left to the browser, so the page can still be scrolled. The ♥ and ✖ buttons do the same as a swipe. The card then flies off to that side for 300 ms before the next card is shown. The match is saved at once, before the animation, so it is not lost if the user leaves the page while the card is moving. When the user prefers reduced motion, the next card is shown at once. -- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `PlantSearchForm` is the search field, filters, sort menu and reset button used on both Explore Plants and My Matches (the filters are listed once in `plantFilters.ts`), `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (♥) or removes it (✖), `HeartIcon` is the SVG heart used on the match buttons and on Plant Match, `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages. -- **Plant Owner Test:** The questions, results and suggestions are data in `pages/plantOwnerTest/plantOwnerTest.ts`, so the page only shows them. `getPlantOwnerResult()` gives the result from the location and watering answers. `getSuggestedPreferences()` gives three preference ids from the answers and the result: - - **Watering** from the result: the minimalists get `minimumWater`, the average gardeners `averageWater`, and the dreaming city gardener and the garden expert `frequentWater`. - - **Light** from the light answer. There is no preference for partial sun, so it suggests `partShade`, since those plants are listed as "part sun/part shade" in the data and match the part shade preference. - - **Care level** from the result where its description says something about care: `easyCare` for the minimalists ("hardy plants") and `hardCare` for the dreaming city gardener and the garden expert ("a lot of attention"). The average gardeners get it from the time answer (10 minutes: `easyCare`, 30 minutes or 1 hour: `mediumCare`, 1 day: `hardCare`). - - `SuggestedPreferences.tsx` shows the suggestions that the user does not already have as toggle buttons, all chosen from the start. Nothing is saved until the user clicks "Add to my preferences", which saves the saved preferences plus the chosen suggestions with `usePreferences`, so no preference is removed. It uses an optimistic response like the buttons on the profile page, so the profile and Plant Match are updated at once. The suggestions are shown above "Use as profile picture", since that button takes the user to the profile page. - -- **Walkthrough:** The guide for new users is in `components/walkthrough/`, and is made up of three parts: - - **The steps are data:** `walkthroughSteps.ts` lists the steps in the same order as the pages in the sidebar. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page. - - **`App.tsx` decides when it is open:** The walkthrough opens by itself when `walkthroughSeen` is not in `localStorage`, and the key is set when it is closed, so it is only shown once. The ? button in the `Header` opens it again at the step for the current page (`stepForPath`). When it closes, focus goes back to the ? button, except when the "Go to" link has moved the user to another page, where focus moves to the start of the new page like for any other navigation. - - **`Walkthrough.tsx` shows one step at a time:** It uses the native `` element with `showModal()`, so the browser grays out the page behind, keeps keyboard focus inside the dialog and closes it with Escape. It can also be closed with ×, Finish or a click outside the box. The user moves between steps with Back and Next or the arrow keys, and steps about a page have a "Go to" link that opens the page and closes the walkthrough. The `LanguageSwitcher` from the sidebar is reused at the bottom of the dialog, so the language can be changed without leaving the walkthrough. This matters on mobile, where the sidebar is hidden behind the menu button. The text of all steps is placed in the same CSS grid cell, and only the current step is visible (the others have `visibility: hidden`, `aria-hidden` and `inert`), so the box always has the height of the longest step and does not change size between steps. -- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. `getPlantPreferences()` in the same file uses the same keys to find which preferences a plant matches, which the preference chips on the plant cards use. -- **Shared types:** `Plant` and `User` are defined in `types/`, together with the ids that are also checked in the backend: the preferences (`Preference.ts`) and the profile pictures (`ProfilePicture.ts`). - -### Communication with the backend - -The frontend uses Apollo Client, which is set up in `main.tsx` with an in-memory cache. The GraphQL URL is read from `VITE_GRAPHQL_URL` (set in `frontend/.env.production` for the deployed app) and falls back to `/graphql`. During development, requests to `/graphql` are proxied by Vite to the backend on port 3001 (see [vite.config.ts](../frontend/vite.config.ts)). - -### GraphQL operations in the frontend - -All GraphQL queries, mutations and fragments in the frontend are collected in `frontend/src/graphql/`, grouped by domain the same way as the backend schema: - -```text -graphql/ -├── fragments/ -│ ├── plantFragments.ts # PlantFields: the plant fields every plant list asks for -│ └── userFragments.ts # UserFields: the user fields every user operation returns -├── plants/ -│ └── queries.ts # GET_PLANTS (Plant Match deck), EXPLORE_PLANTS (Explore Plants) -└── user/ - ├── queries.ts # GET_USER, MY_MATCHES (My Matches) - └── mutations.ts # CREATE_USER, ADD_USER_MATCH, REMOVE_USER_MATCH, UPDATE_USER_PROFILE, UPDATE_USER_PREFERENCES -``` - -Each file also exports the TypeScript type for the result of its operations (for example `GetPlantsData` and `ExplorePlantsData`). The shared `Plant` and `User` types are in `types/`. Pages, hooks and the context only import the operations they use, for example `usePlantDeck` imports `GET_PLANTS` and `useMatchedPlants` imports `ADD_USER_MATCH` and `REMOVE_USER_MATCH`. - -The operations used to be spread across the context, a page and a hook, and we moved them into one folder after feedback, and because one of our main goals is that the app should scale: - -- **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. -- **The user operations are shared.** They are used by `UserProvider`, three hooks and My Matches, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. -- **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. -- **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and `myMatches`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. -- **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. - -We considered keeping each query next to the component that uses it (colocation), which is common in large apps organised by feature. Our frontend is organised by technical role (`pages/`, `components/`, `hooks/`, `context/`), and most of our operations are used in more than one place, so a shared folder fits better. If the app is later reorganised into feature folders, each domain folder in `graphql/` can be moved into its feature. - -### Apollo cache - -All user queries and mutations ask for the same `UserFields` fragment, so when one page changes the user (for example adds a match), Apollo's cache updates the user on every page at once. Changing the profile picture uses an optimistic response, so the new picture is shown before the server has answered. The fragment only has the ids of the matched plants (`matchedPlantIds`), so the user stays small however many matches there are. Adding and removing a match returns the whole list of ids, so the cache replaces it instead of merging it with the old list. My Matches fetches its plants with its own `myMatches` query. When a match is added or removed, the saved My Matches pages are removed from the cache, so My Matches is fetched again at once if it is open, or the next time it is opened, and never shows an old list. +## Data source: the Perenual API -## Backend: GraphQL with Apollo Server +The plant data comes from the [Perenual API](https://perenual.com/docs/api), which has information about thousands of plant species, including images, care information and plant traits. -The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks for exactly the fields each view needs. A plant card needs more fields than a list item, and both are served by the same `Plant` type without extra endpoints. The schema also gives us one typed contract between frontend and backend. +The app does **not** call Perenual while it is running. Instead, the script [backend/seedDataFetch.js](../backend/seedDataFetch.js) fetched the data once, cleaned it and stored it in our own MongoDB database on the VM. We have kept the script so you can see how this has been done. It runs in two phases: -- `db.ts` connects to MongoDB using `MONGODB_URI` and `DB_NAME` from `.env` (see `.env.example`). The database name defaults to `iloveplants`. -- `server.ts` starts the backend on `PORT` (default 3001). `app.ts` sets up Express with the GraphQL API (Apollo Server, with the schema and resolvers below) on `/graphql`, and the plant images on `/images/:id` (`images.ts`). Express is used instead of Apollo's standalone server, since that one can only serve GraphQL. -- `schema.ts` defines the GraphQL schema (`typeDefs`). -- `resolvers/` has the resolvers, split like the GraphQL operations in the frontend: `plants.ts` has the plant queries, `users.ts` has the user queries and mutations and validates user input, `helpers.ts` has the collections and helpers both use, and `index.ts` puts them together. -- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches, and the counts of how many plants each filter value would give. -- `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#design-choices-made-for-scalability)). -- `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments. -- `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below). +1. **Species list:** fetches the plant list, upserts one document per plant (keyed on `perenualId`), and downloads each image and stores it as a base64 data URI in `imageData`. The image URLs from Perenual expire after 24 hours, which is why the image itself is stored. +2. **Details:** fetches `species/details/{id}` for every plant that is missing details and adds the detail fields to the same document. -### Schema +The raw detail responses are cached in `backend/data/raw/` (ignored by git, so they are not in the repo), and the script stops before it uses up the daily quota, so it can be run again (for example over several days) and continue where it left off. `npm run seed:reset` drops the collection and starts over. -**Queries** - -| Query | Description | -| ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants (at most 50) for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. | -| `explorePlants(search, sunlight, watering, careLevel, sort, preferences, limit = 12, offset = 0): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate (`limit` is kept between 1 and 50, and a negative `offset` counts as 0). Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc`, `careLevel_asc` or `preferences`; the default is name A–Z. `preferences` puts the plants matching the most of the sent preferences first, with the same score as Plant Match, and sorts plants that match equally well by name. Also returns `filterCounts`: for every filter value, and for "All" (an empty value), the number of plants it would give instead of the current choice in the same filter, together with the search and the other filters. The counts use the same filter as the results, so they always agree, and are done in one `$facet` aggregation. | -| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | -| `myMatches(userId, search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Returns one page of the user's matched plants and `totalCount`, searched and filtered like in `explorePlants`, with `filterCounts` counted only among the user's matches (`limit` and `offset` are kept within the same bounds as in `explorePlants`). Sort can be `oldest`, `name_asc`, `name_desc` or `preferences`; the default is newest first. `preferences` uses the preferences saved on the user, like in `explorePlants`. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. | +We chose this approach for these reasons: -**Mutations** +- **Rate limits:** The free tier on the Perenual API allows about 100 requests per day, and only returns details for plants with an ID up to 3000. If the app called Perenual directly, a handful of users would use up the daily limit in minutes. By fetching the data once and serving it from our own database, the number of users no longer affects the number of requests to Perenual. +- **Fewer requests:** Because the data is fetched only once, and the raw responses are cached locally so the script never requests the same data twice, we avoid unnecessary network traffic and resource use. +- **Control over the data:** We only keep the fields we use, in the format we want. That keeps responses small, and makes searching, filtering, sorting and pagination something we decide on ourselves, instead of being limited by what Perenual supports. +- **Reliability:** The app keeps working even if Perenual is down or changes its API, since the data is stored in our own database. -| Mutation | Description | -| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `createUser: User!` | Creates an empty user with default values. | -| `updateUserProfile(userId, name, description, profilePicture)` | Updates only the fields that are sent. Text is trimmed and length-checked; empty text is stored as `null`. | -| `updateUserPreferences(userId, preferences)` | Replaces the preference list. Unknown preferences are rejected and duplicates removed. | -| `addUserMatch(userId, plantId)` | Adds a plant to the user's matches (`$addToSet`, so never twice). Unknown plants are rejected. | -| `removeUserMatch(userId, plantId)` | Removes a plant from the user's matches (`$pull`). | +## Database: MongoDB -**Types** +The database `iloveplants` has two collections: `plants` and `users`. We chose to store both the plants and the users in MongoDB to make the app scalable. More plants and users can be added, and each of them can have more fields than if browser storage, such as `localStorage` or `sessionStorage`, had been used. -- `Plant`: `id`, `name`, `imageURL`, `scientificName`, `description`, `watering`, `sunlight`, `careLevel` -- `PlantPage`: `plants`, `totalCount`, `filterCounts`. `FilterCounts` has `watering`, `sunlight` and `careLevel`, each a list of `OptionCount` (`value`, `count`). Both `explorePlants` and `myMatches` return it, and share the code that builds it (`findPlantPage` in `resolvers/plants.ts`). -- `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlantIds`, `createdAt` +### Why MongoDB was used -`User.matchedPlantIds` only returns the ids, so the pages that just need to know whether a plant is matched do not fetch the whole plants with images. The plants themselves are fetched one page at a time with `myMatches`, which only shows and counts plants that still exist (for example after a reseed). +We store the data in MongoDB, a document database. It is a good fit for this data: -Invalid input from the client gives a GraphQL error with the code `BAD_USER_INPUT` instead of crashing the server. +- **The data from Perenual is already documents.** Perenual returns JSON with nested objects and lists (such as sunlight requirements and scientific names). Each plant becomes one document with almost the same shape, so there is no need to split it into several tables and join them back together. This limits the cleaning needed. +- **Plants have different fields.** Some plants have information that others lack. A document database handles optional fields naturally, without many empty columns, which would be inefficient. +- **It is simple to update.** The seed script first inserts a basic entry for each plant, and later adds details to the same document (an upsert keyed on `perenualId`). User updates are single atomic operations such as `$set`, `$addToSet` and `$pull`. -## Database: MongoDB +The trade-off in using a NoSQL database such as MongoDB compared to a relational database such as MySQL is that it does not enforce relationships between collections. That matters little here: the plant collection is read-only for the app, and the only reference between the collections is `users.matchedPlantIds`. `addUserMatch` checks that the plant exists before storing the id, and `myMatches` skips ids that no longer point to a plant. -The database `iloveplants` has two collections: `plants` and `users`. We chose to store both the plants and the users in MongoDB to make the app scalable. More plants and users can be added, and each of them can have more fields than if browser storage, such as `localStorage` or `sessionStorage`, had been used. MongoDB was also chosen because of its flexible schema. +MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be reached directly from the internet. During development, it is reached through an SSH tunnel (see [Run the project locally](../README.md#run-the-project-locally) in the README). The backend tests use an in-memory MongoDB (`mongodb-memory-server`), so they never touch the database on the VM. ### The `plants` collection @@ -167,7 +82,7 @@ One document per plant species. The documents were written by `seedDataFetch.js` | `otherNames` | string[] | Species list | – | | `family` | string | Species list | – | | `genus` | string | Species list | – | -| `imageData` | string | The plant image downloaded and stored as a base64 data URI | `imageURL` | +| `imageData` | string | The plant image downloaded and stored as a base64 data URI, sent from `/images/` | `imageURL` (the link) | | `imageLicense` | string | Licence name of the image | – | | `createdAt` | Date | When the plant was first inserted | – | | `description` | string | Species details | `description` | @@ -209,76 +124,182 @@ A new user starts with `name: null`, `description: null`, `profilePicture: "defa Matches only store the plant id, not a copy of the plant. That keeps user documents small and means the user always sees the current plant data. -### Why MongoDB was used +**Security of the user id:** Without login, the user id works as the key to a user. The backend checks that the id exists, but not who sends it, so anyone who knows an id can read and change that user. We consider the risk low for this app: -We store the data in MongoDB, a document database. It is a good fit for this data: +- The backend runs on the VM, which can only be reached from the NTNU network or through the NTNU VPN. +- An attacker would also need to know the id of a specific user, which is only stored in that user's browser. +- The database holds no sensitive data. No password, e-mail address or other personal information is asked for, only an optional display name, a short description, preferences and matched plants. -- **The data from Perenual is already documents.** Perenual returns JSON with nested objects and lists (such as sunlight requirements and scientific names). Each plant becomes one document with almost the same shape, so there is no need to split it into several tables and join them back together. This limits the cleaning needed. -- **Plants have different fields.** Some plants have information that others lack. A document database handles optional fields naturally, without many empty columns, which would be inefficient. -- **It is simple to update.** The seed script first inserts a basic entry for each plant, and later adds details to the same document (an upsert keyed on `perenualId`). User updates are single atomic operations such as `$set`, `$addToSet` and `$pull`. +The ids are MongoDB ObjectIds, which are unique but not secret, random tokens. If the app later stores sensitive data or is opened to the internet, the id alone should no longer be enough to change a user, and login (or a secret token per user) would be needed (see [No login](quality.md#design-choices)). -The trade-off in using a NoSQL database such as MongoDB compared to a relational database such as MySQL is that it does not enforce relationships between collections. That matters little here: the plant collection is read-only for the app, and the only reference between the collections is `users.matchedPlantIds`. `addUserMatch` checks that the plant exists before storing the id, and `myMatches` skips ids that no longer point to a plant. +## Backend: GraphQL with Apollo Server -MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be reached directly from the internet. During development, it is reached through an SSH tunnel (see [Run the project locally](../README.md#run-the-project-locally) in the README). The backend tests use an in-memory MongoDB (`mongodb-memory-server`), so they never touch the database on the VM. +The backend exposes a single GraphQL endpoint, and a route for the plant images (`/images/:id`). With GraphQL, the frontend asks for exactly the fields each view needs. A plant card needs more fields than a list item, and both are served by the same `Plant` type without extra endpoints. The schema also gives us one typed contract between frontend and backend. -## Where state is kept +- `db.ts` connects to MongoDB using `MONGODB_URI` and `DB_NAME` from `.env` (see `.env.example`). The database name defaults to `iloveplants`. +- `server.ts` starts the backend on `PORT` (default 3001). `app.ts` sets up Express with the GraphQL API (Apollo Server, with the schema and resolvers below) on `/graphql`, and the plant images on `/images/:id` (`images.ts`). Express is used instead of Apollo's standalone server, since that one can only serve GraphQL. +- `schema.ts` defines the GraphQL schema (`typeDefs`). +- `resolvers/` has the resolvers, split like the GraphQL operations in the frontend: `plants.ts` has the plant queries, `users.ts` has the user queries and mutations and validates user input, `helpers.ts` has the collections and helpers both use, and `index.ts` puts them together. +- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches, and the counts of how many plants each filter value would give. It also has the preference score used by Plant Match and the best match sort order (`PREFERENCE_MATCHERS` and `matchScore`), and the cursors used for paging by name (`encodeCursor`, `decodeCursor` and `cursorFilter`). +- `listen.ts` starts listening on the port, and is kept in its own file so the tests can replace it without opening a port. +- `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#design-choices-made-for-scalability)). +- `migrations.ts` updates data stored by older versions of the app when the server starts (see [The `users` collection](#the-users-collection)). +- `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments. +- `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api)). -| Where | What | Why | -| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | -| `localStorage` | The user id (`userId`), the theme (`theme`), the language (`language`) and whether the walkthrough has been seen (`walkthroughSeen`) | Lets the browser find its user again on the next visit without a login, keeps the chosen theme and language between visits, and only opens the walkthrough by itself on the first visit | -| URL parameters | Explore search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`) via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | -| `sessionStorage` | The search, filters and sort order on My Matches (`myMatches.search`, `myMatches.watering`, `myMatches.sunlight`, `myMatches.careLevel`, `myMatches.sort`) via `useMyMatchesParams`, and the cards left on Plant Match (`plantMatch.deck`) | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | -| Apollo in-memory cache | Query results (plants and the current user) | Avoids asking the backend again for data the app already has, and keeps all pages in sync | -| React state | Short-lived UI state, such as the current plant on the match page and unsaved profile text | Only matters while the component is shown | +### Schema -User data used to be stored in `localStorage`. `UserProvider` now removes the old keys (`plantPreferences`, `matchedPlants`, `profileName`, `description`, `profileAvatar`) on start-up, so old data does not lie around in the browser. +**Queries** + +| Query | Description | +| ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants (at most 50) for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" and "Easy" count as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. | +| `explorePlants(search, sunlight, watering, careLevel, sort, preferences, limit = 12, offset = 0, after, before): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate (`limit` is kept between 1 and 50, and a negative `offset` counts as 0). Returns the plants on the page and `totalCount` for the whole result. With a name sort, `after` or `before` (the `endCursor` or `startCursor` of the page on screen) gives the page right after or before it, read from the index instead of with `offset`, and every page sorted by name comes with these cursors (see [Scalability](#design-choices-made-for-scalability)). Sort can be `name_asc`, `name_desc`, `watering_asc`, `careLevel_asc` or `preferences`; the default (and any unknown value) is name A–Z. `preferences` puts the plants matching the most of the sent preferences first, with the same score as Plant Match, and sorts plants that match equally well by name. Also returns `filterCounts`: for every filter value, and for "All" (an empty value), the number of plants it would give instead of the current choice in the same filter, together with the search and the other filters. The counts use the same filter as the results, so they always agree, and are done in one `$facet` aggregation. | +| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | +| `myMatches(userId, search, sunlight, watering, careLevel, sort, limit = 12, offset = 0, after, before): PlantPage!` | Returns one page of the user's matched plants and `totalCount`, searched and filtered like in `explorePlants`, with `filterCounts` counted only among the user's matches (`limit` and `offset` are kept within the same bounds as in `explorePlants`). `after` and `before` work like in `explorePlants` for `name_asc` and `name_desc`. Sort can be `oldest`, `name_asc`, `name_desc` or `preferences`; the default is newest first. `preferences` uses the preferences saved on the user, like in `explorePlants`. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. | -When the app starts, `UserProvider` reads `userId` from `localStorage` and runs `getUser`. If there is no id, or the id no longer exists in the database, it runs `createUser` and saves the new id. If the backend cannot be reached, it does not create a new user, and the app still works without saved data. +**Mutations** -## Design choices made for scalability +| Mutation | Description | +| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `createUser: User!` | Creates an empty user with default values. | +| `updateUserProfile(userId, name, description, profilePicture)` | Updates only the fields that are sent. Text is trimmed and length-checked; empty text is stored as `null`. | +| `updateUserPreferences(userId, preferences)` | Replaces the preference list. Unknown preferences are rejected and duplicates removed. | +| `addUserMatch(userId, plantId)` | Adds a plant to the user's matches (`$addToSet`, so never twice). Unknown plants are rejected. | +| `removeUserMatch(userId, plantId)` | Removes a plant from the user's matches (`$pull`). Malformed plant ids are rejected. | + +**Types** + +- `Plant`: `id`, `name`, `imageURL`, `scientificName`, `description`, `watering`, `sunlight`, `careLevel` +- `PlantPage`: `plants`, `totalCount`, `filterCounts`, `startCursor` and `endCursor`. The cursors point at the first and last plant on the page, and are `null` unless the list is sorted by name (see [Scalability](#design-choices-made-for-scalability)). `FilterCounts` has `watering`, `sunlight` and `careLevel`, each a list of `OptionCount` (`value`, `count`). Both `explorePlants` and `myMatches` return it, and share the code that builds it (`findPlantPage` in `resolvers/plants.ts`). +- `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlantIds`, `createdAt` + +`User.matchedPlantIds` only returns the ids, so the user stays small however many matches there are, and the pages that just need to know whether a plant is matched do not fetch the plants themselves. The plants themselves are fetched one page at a time with `myMatches`, which only shows and counts plants that still exist (for example after a reseed). + +Invalid input from the client gives a GraphQL error with the code `BAD_USER_INPUT` instead of crashing the server. This includes a search longer than 100 characters, which no plant name comes close to and which would only make the database run a needlessly large regular expression (the search field in the frontend has the same limit). An unexpected error, for example from the database, is logged on the server, and the client only gets the message "Internal server error" with the code `INTERNAL_SERVER_ERROR`, since the original message can contain internal details such as the database address. Stack traces are never sent to the client (`formatError` and `includeStacktraceInErrorResponses` in `app.ts`). + +### Design choices made for scalability - **Use of MongoDB over browser storage.** All user data (profile, preferences and matches) is stored in MongoDB. The browser only keeps small values that do not need the server: `localStorage` holds the `userId`, the chosen theme and language and whether the walkthrough has been seen, and `sessionStorage` holds the search, filters and sort order on My Matches and the cards left on Plant Match (see [Where state is kept](#where-state-is-kept)). Browser storage is limited to about 5 MB per site and only exists in that one browser, where the server cannot use it. By storing user data in MongoDB, there is no practical limit to how many plants a user can save, more user information can easily be added later, and the data can be used by the backend. - **Plant data does not depend on Perenual.** The number of users does not affect the number of requests to Perenual, since the app only reads from our own database. It also makes it possible to fetch more plants later if one wants to. - **The server does the heavy work.** Searching, filtering, sorting and pagination run as MongoDB queries, so the frontend only receives one page of plants at a time (12 by default) together with the total count. This works the same whether the collection has a hundred or many thousand plants, and keeps responses small so pages load faster. - **Index for sorting by name.** Sorting by name (A–Z, the default, and Z–A) uses an index on `commonName` and `_id`, created by `indexes.ts` when the server starts. The plants are then read in order from the index instead of being sorted in memory, which matters more the larger the collection gets. Lookups by id (users, matches and plants) already use the `_id` index that MongoDB creates on every collection. - **Why the other fields have no index:** - - **Search:** The search uses a case-insensitive regular expression, which cannot use a normal index efficiently. A text index would make the search faster, but it only matches whole words, so "monst" would no longer find Monstera. We chose to keep the search on parts of names, since that matters to the user. The search still works on any amount of data, since it runs in the database and only one page of results is returned. For very large collections, a dedicated search index that supports parts of words would make it faster. + - **Search:** The search uses a case-insensitive regular expression, which cannot use a normal index efficiently. A text index would make the search faster, but it only matches whole words, so "alp" would no longer find Alpine Fir. We chose to keep the search on parts of names, since that matters to the user. The search still works on any amount of data, since it runs in the database and only one page of results is returned. For very large collections, a dedicated search index that supports parts of words would make it faster. - **Filters:** The filters also use regular expressions, because the data is not consistent: the same value can have different casing, "Medium" and "Moderate" mean the same care level, and sunlight can be combined (e.g. "part sun/part shade"). - **Sorting by watering and care level:** These use a calculated rank, since the values cannot be sorted alphabetically (Minimum, Average, Frequent), and plants without a value are put last. A calculated rank cannot use an index. If the collection grows much larger, the rank could be calculated once when the data is loaded, stored on each plant and indexed. -- **Offset-based pagination.** We use offset-based pagination (`$skip` and `$limit`) instead of cursor-based pagination, because it lets the user jump to any page and works with all our sort orders, including the ones on calculated values. Offset pagination gets slower for very deep pages, but that only matters for collections far larger than ours. +- **Numbered pages, with cursors for next and previous.** Explore Plants and My Matches combine two kinds of pagination, so the user keeps the page numbers, and stepping through the pages stays fast however deep in the list the user is: + - **Cursor for next and previous (name sort orders):** Every page sorted by name comes with a `startCursor` and an `endCursor`, which point at its first and last plant (its `commonName` and `_id`, base64url-encoded so the client treats the cursor as an opaque string). When the user clicks Next, the frontend sends `after: endCursor`, and the backend asks for the plants after that plant (Previous sends `before: startCursor`). MongoDB reads these straight from the `commonName` index, so page 57 is as fast as page 1. With `$skip`, MongoDB has to read past every plant before the page, so a deep page gets slower the larger the collection is. The cursor logic in the frontend is in `usePageCursor`, and in the backend in `findPlantPage` (`resolvers/plants.ts`) and `cursorFilter` (`queryBuilders.ts`). + - **Offset for everything else:** Jumping to a page number, page 1, a reload of a page and the calculated sort orders (watering, care level, best match first and newest or oldest match) use `offset` (`$skip` and `$limit`). A jump has no plant on screen to continue from, and the calculated orders have no stored value a cursor could point at. + - **Why not only cursors:** With only cursors, the user could no longer jump to a page number or reload a page from the URL, only go to the next or previous page (or scroll), and the calculated sort orders would not work. Keeping both gives the user numbered pages, and the common case, stepping through a list sorted by name (the default order), the speed of cursors. + - **Safety:** A cursor comes from the client, so the backend checks that it is one it made, and only accepts it with a name sort and never together with both `after` and `before`. Otherwise it answers with `BAD_USER_INPUT`. The frontend only uses a cursor for the exact search, filters and sort order it came from. + + If the catalogue grew dramatically (for example to hundreds of thousands of plants), this would also have to change: + - **Stored sort values:** Cursors need a value to continue from, so the calculated ranks for watering, care level and best match first would have to be stored on each plant and indexed (see above) before those orders could use cursors too. Best match first depends on each user's preferences, so it would probably be limited to the first pages. + - **Cheaper counts:** `totalCount` and the filter counts are counted on every request, also with a cursor. On a very large collection they would be estimated, or calculated in advance and cached, instead. + - **Deep jumps:** Jumping straight to a far page still uses `offset`. A search or a filter usually narrows the list first, but a very large collection could limit how far one jump goes. + - **Small responses.** GraphQL returns only the requested fields, and fields we do not use are kept out of the schema. - **GraphQL operations in one folder.** All queries, mutations and fragments are in `frontend/src/graphql/`, grouped by domain, with shared fragments for the plant and user fields. New features get their own folder, and a schema change only has to be followed up in one place (see [GraphQL operations](#graphql-operations-in-the-frontend)). - **Small user documents and responses.** Matches are stored as plant ids, and user updates only touch one document. Only the ids are sent with the user, and My Matches fetches one page of plants at a time, so the responses do not grow with the number of matches. - **Less traffic from the client.** Search input is debounced, results are cached by Apollo, and pages other than the start page are lazy-loaded. -## Limitations of the architecture +## Frontend: React, TypeScript and Apollo Client -- **Plant images are stored as base64 in the database.** Each plant image is stored as a base64 data URI in `imageData` (see [Data source: the Perenual API](#data-source-the-perenual-api)), instead of as an image file on the VM. +The frontend is built with React and TypeScript (Vite). - **Why:** The image URLs from Perenual stop working after 24 hours, so we had to store the images ourselves. We chose the database over image files on the VM, since the seed script then writes everything in one step, the image is stored and deleted together with its plant, and the VM needs no extra setup. +- **Routing:** Routes are defined in `AppRoutes.tsx` with React Router, and the app is served under the base path `/project2/`. Vite defines this base in `frontend/vite.config.ts`; `HashRouter` provides the client-side routes, including Explore query parameters after the hash. All pages except the start page are lazy-loaded. Any path that does not match a route shows the 404 page, and the header shows the "Page not found" title for it. - **How they are sent:** The GraphQL responses only contain a link, `/images/`, and `images.ts` sends the image as a file from that route. The browser keeps it for a week (`Cache-Control`) and the plant cards load it lazily (`loading="lazy"`). The plant queries no longer read `imageData`, only whether there is one. Before, the images were sent as base64 inside the GraphQL responses (see the measurement in [Sustainable web development](quality.md#sustainable-web-development)). + | Route | Page | Purpose | + | ----------------- | -------------------- | ------------------------------------------------------------------------------------ | + | `/` | `PlantMatchPage` | Swipe through preference-ranked plants (`getPlants`) and match with them | + | `/explorePlants` | `ExplorePlantsPage` | Search, filter, sort and paginate all plants (`explorePlants`) | + | `/myMatches` | `MyMatchesPage` | Search, filter, sort, paginate and remove the user's matches (`myMatches`) | + | `/profile` | `ProfilePage` | Edit name, description, profile picture and preferences | + | `/plantOwnerTest` | `PlantOwnerTestPage` | A quiz whose result can be set as the profile picture, and that suggests preferences | + | `*` | `NotFoundPage` | 404 page for unknown paths, with a link back to Plant Match | - **What is left:** The images still take about 33 % more space in the database than as files, and the backend decodes them on every request the browser has not cached. With many more plants, they should be stored as files with only the path in MongoDB. The `/images/:id` route could then be changed without changing the frontend. +- **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile`, `usePreferences` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). +- **Error messages:** `ErrorMessageProvider` (`context/ErrorMessageContext.tsx`) wraps the app and makes `showError()` available through `useErrorMessage()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails. +- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text). `useExploreParams` keeps the Explore search, filters, sort order and page in the URL, and sends the user back to page 1 when the search, a filter or the sort order changes. It uses `useUrlParams`, which reads the page number and updates the URL (with React Router's `useSearchParams`). `useMyMatchesParams` does the same for My Matches, but keeps the search, filters and sort order in `sessionStorage` with `useSessionState`, since the matches belong to the user in this browser and a link to them could not be shared. `usePageCursor` remembers the cursor that leads to the next or previous page on both pages, and only uses it for the exact search, filters and sort order it came from (see [Scalability](#design-choices-made-for-scalability)). `usePreferences` saves the preferences, both on the profile page and after the plant owner test. `useNewMatches` counts the plants matched since My Matches was last opened, which the sidebar shows as a badge on the My Matches link (with a text for screen readers). The matches the user already has when the app opens count as seen, so only the user id has to be kept in the browser. A plant that is removed from the matches is no longer seen, so it counts as new if it is matched again. `useDismissibleTooltip` lets the "i" help texts be hidden with Escape. +- `usePlantDeck` fetches the Plant Match cards in batches of 8 (`getPlants`), and fetches the next batch when 3 or fewer cards are left. Each request sends the ids of the plants already fetched into the deck and the plants the user has already matched as `excludeIds`, so no plant is shown twice and plants in My Matches are never shown. A plant that is matched on another page while it is in the deck is skipped. The remaining cards are kept in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored. When the deck is empty, the user can start it over with the Reload button, and if every plant is matched, the end card says so and links to My Matches instead. +- **Swiping on Plant Match:** `PlantMatchPage` follows the card with Pointer Events, so the same code handles mouse, finger and pen. The match is saved before the card flies off, so it is not lost if the user leaves the page during the animation. The ♥ and ✖ buttons do the same as a swipe. +- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `PlantSearchForm` is the search field, filters, sort menu and reset button used on both Explore Plants and My Matches (the filters are listed once in `plantFilters.ts`), `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (♥) or removes it (✖), `HeartIcon` is the SVG heart used on the match buttons and on Plant Match, `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages. +- **Plant Owner Test:** The questions, results and suggestions are data in `pages/plantOwnerTest/plantOwnerTest.ts`, so the page only shows them. `getPlantOwnerResult()` gives the result from the location and watering answers. `getSuggestedPreferences()` gives three preference ids from the answers and the result: + - **Watering** from the result: the minimalists get `minimumWater`, the average gardeners `averageWater`, and the dreaming city gardener and the garden expert `frequentWater`. + - **Light** from the light answer. There is no preference for partial sun, so it suggests `partShade`, since those plants are listed as "part sun/part shade" in the data and match the part shade preference. + - **Care level** from the result where its description says something about care: `easyCare` for the minimalists ("hardy plants") and `hardCare` for the dreaming city gardener and the garden expert ("a lot of attention"). The average gardeners get it from the time answer (10 minutes: `easyCare`, 30 minutes or 1 hour: `mediumCare`, 1 day: `hardCare`). -## Data source: the Perenual API + `SuggestedPreferences.tsx` shows the suggestions that the user does not already have as toggle buttons, all chosen from the start. Nothing is saved until the user clicks "Add to my preferences", which saves the saved preferences plus the chosen suggestions with `usePreferences`, so no preference is removed. It uses an optimistic response like the buttons on the profile page, so the profile and Plant Match are updated at once. The suggestions are shown above "Use as profile picture", since that button takes the user to the profile page. -The plant data comes from the [Perenual API](https://perenual.com/docs/api), which has information about thousands of plant species, including images, care information and plant traits. +- **Walkthrough:** The guide for new users is in `components/walkthrough/`, and is made up of three parts: + - **The steps are data:** `walkthroughSteps.ts` lists the steps in the same order as the sidebar, each with an `id`, a picture and, for steps about a page, its `route`. The texts are in the translation files, so a new step only needs one line in the list and a title and text in each language. + - **`App.tsx` decides when it is open:** on the first visit (until `walkthroughSeen` is set in `localStorage`), and from the ? button in the header, where `stepForPath()` starts it at the step for the current page. + - **`Walkthrough.tsx` shows one step at a time** in a native `` opened with `showModal()`, so the browser handles focus, Escape and the grayed-out page behind (see [Accessibility](quality.md#accessibility)). It reuses `LanguageSwitcher`, so the language can be changed without leaving the walkthrough. +- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. `getPlantPreferences()` in the same file uses the same keys to find which preferences a plant matches, which the preference chips on the plant cards use. +- **Shared types:** `Plant` and `User` are defined once in `types/`, together with the ids that are also checked in the backend: the preferences (`Preference.ts`) and the profile pictures (`ProfilePicture.ts`). The types are used by the GraphQL result types, hooks, pages and components. TypeScript then checks that every part of the frontend uses the same field names and types. If a field changes, the compiler points out every place that has to be updated, instead of the error first showing up in the browser. -The app does **not** call Perenual while it is running. Instead, the script [backend/seedDataFetch.js](../backend/seedDataFetch.js) fetched the data once, cleaned it and stored it in our own MongoDB database on the VM. We have kept the script so you can see how this has been done. It runs in two phases: +### Communication with the backend -1. **Species list:** fetches the plant list, upserts one document per plant (keyed on `perenualId`), and downloads each image and stores it as a base64 data URI in `imageData`. The image URLs from Perenual expire after 24 hours, which is why the image itself is stored. -2. **Details:** fetches `species/details/{id}` for every plant that is missing details and adds the detail fields to the same document. +The frontend uses Apollo Client, which is set up in `main.tsx` with an in-memory cache. The GraphQL URL is read from `VITE_GRAPHQL_URL` (set in `frontend/.env.production` for the deployed app) and falls back to `/graphql`. This is done in `graphql/apiUrl.ts`, which also has `toImageUrl()`: the plant images are on the same server as the API, so `PlantCard` resolves the `/images/` path against the API's address and not the page's. During development, requests to `/graphql` and `/images` are proxied by Vite to the backend on port 3001 (see [vite.config.ts](../frontend/vite.config.ts)). -The raw detail responses are cached in `backend/data/raw/`, and the script stops before it uses up the daily quota, so it can be run again (for example over several days) and continue where it left off. `npm run seed:reset` drops the collection and starts over. +### GraphQL operations in the frontend -We chose this approach for these reasons: +All GraphQL queries, mutations and fragments in the frontend are collected in `frontend/src/graphql/`, grouped by domain the same way as the backend schema: -- **Rate limits:** The free tier on the Perenual API allows about 100 requests per day, and only returns details for plants with an ID up to 3000. If the app called Perenual directly, a handful of users would use up the daily limit in minutes. By fetching the data once and serving it from our own database, the number of users no longer affects the number of requests to Perenual. -- **Fewer requests:** Because the data is fetched only once, and the raw responses are cached locally so the script never requests the same data twice, we avoid unnecessary network traffic and resource use. -- **Control over the data:** We only keep the fields we use, in the format we want. That keeps responses small, and makes searching, filtering, sorting and pagination something we decide on ourselves, instead of being limited by what Perenual supports. -- **Reliability:** The app keeps working even if Perenual is down or changes its API, since the data is stored in our own database. +```text +graphql/ +├── apiUrl.ts # GRAPHQL_URL and toImageUrl(): where the API and the plant images are +├── fragments/ +│ ├── plantFragments.ts # PlantFields: the plant fields every plant list asks for, FilterCountFields: the filter counts +│ └── userFragments.ts # UserFields: the user fields every user operation returns +├── plants/ +│ └── queries.ts # GET_PLANTS (Plant Match deck), EXPLORE_PLANTS (Explore Plants) +└── user/ + ├── queries.ts # GET_USER, MY_MATCHES (My Matches) + └── mutations.ts # CREATE_USER, ADD_USER_MATCH, REMOVE_USER_MATCH, UPDATE_USER_PROFILE, UPDATE_USER_PREFERENCES +``` + +Each file also exports the TypeScript type for the result of its operations (for example `GetPlantsData` and `ExplorePlantsData`). The shared `Plant` and `User` types are in `types/`. Pages, hooks and the context only import the operations they use, for example `usePlantDeck` imports `GET_PLANTS` and `useMatchedPlants` imports `ADD_USER_MATCH` and `REMOVE_USER_MATCH`. + +The operations used to be spread across the context, a page and a hook, and we moved them into one folder after feedback, and because one of our main goals is that the app should scale: + +- **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. +- **The user operations are shared.** They are used by `UserProvider`, three hooks and My Matches, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. +- **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. +- **Shared fragments.** The plant fields are defined once in `PlantFields` instead of in each of the three plant queries, so a new field is added in one place. +- **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. + +We considered keeping each query next to the component that uses it (colocation), which is common in large apps organised by feature. Our frontend is organised by technical role (`pages/`, `components/`, `hooks/`, `context/`), and most of our operations are used in more than one place, so a shared folder fits better. If the app is later reorganised into feature folders, each domain folder in `graphql/` can be moved into its feature. + +### Apollo cache + +`GET_USER`, `CREATE_USER` and the two match mutations ask for the same `UserFields` fragment, and the profile and preference mutations return the user's `id` and the fields they change. Apollo's cache stores the user by its `id`, so when one page changes the user (for example adds a match), the user is updated on every page at once. Changing the profile picture and saving preferences use an optimistic response, so the change is shown before the server has answered, and Apollo rolls it back if the server fails. The fragment only has the ids of the matched plants (`matchedPlantIds`), so the user stays small however many matches there are. Adding and removing a match returns the whole list of ids, so the cache replaces it instead of merging it with the old list. My Matches fetches its plants with its own `myMatches` query. When a match is added or removed, the saved My Matches pages are removed from the cache, so My Matches is fetched again at once if it is open, or the next time it is opened, and never shows an old list. + +### Where state is kept + +| Where | What | Why | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | +| `localStorage` | The user id (`userId`), the theme (`theme`), the language (`language`) and whether the walkthrough has been seen (`walkthroughSeen`) | Lets the browser find its user again on the next visit without a login, keeps the chosen theme and language between visits, and only opens the walkthrough by itself on the first visit | +| URL parameters | Explore search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`) via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | +| `sessionStorage` | The search, filters and sort order on My Matches (`myMatches.search`, `myMatches.watering`, `myMatches.sunlight`, `myMatches.careLevel`, `myMatches.sort`) via `useMyMatchesParams`, and the cards left on Plant Match (`plantMatch.deck`) | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | +| Apollo in-memory cache | The current user and the pages of Explore Plants and My Matches. The Plant Match batches are fetched past the cache (`no-cache`), since the deck itself is kept in `sessionStorage` | Avoids asking the backend again for data the app already has, and keeps all pages in sync | +| React state | Short-lived UI state, such as the current card and drag on Plant Match, unsaved profile text, whether the sidebar or walkthrough is open, and which matches have been seen for the new-matches badge | Only matters while the app or component is open | + +User data used to be stored in `localStorage`. `UserProvider` now removes the old keys (`plantPreferences`, `matchedPlants`, `profileName`, `description`, `profileAvatar`) on start-up, so old data does not lie around in the browser. + +When the app starts, `UserProvider` reads `userId` from `localStorage` and runs `getUser`. If there is no id, or the id no longer exists in the database, it runs `createUser` and saves the new id. If the backend cannot be reached, it does not create a new user, and the app still works without saved data. It then tries to load the user again every 5 seconds, so the user's data shows up once the backend is back. + +## Limitations of the architecture + +- **Plant images are stored as base64 in the database.** Each plant image is stored as a base64 data URI in `imageData` (see [Data source: the Perenual API](#data-source-the-perenual-api)), instead of as an image file on the VM. + + **Why:** Pictures are central to the app. Plant Match is built around deciding on a plant from its card, and Explore Plants and My Matches show the plants as picture cards. Perenual was the only free source we found with pictures for a sufficient number of plants, together with the care data we needed. Its image URLs stop working after 24 hours, so we had to store the images ourselves. We chose the database over image files on the VM, since the seed script then writes everything in one step, the image is stored and deleted together with its plant, and the VM needs no extra setup. + + **How they are sent:** The GraphQL responses only contain a link, `/images/`, and `images.ts` sends the image as a file from that route. The browser keeps it for a week (`Cache-Control`) and the plant cards load it lazily (`loading="lazy"`). The plant queries no longer read `imageData`, only whether there is one. Before, the images were sent as base64 inside the GraphQL responses (see the measurement in [Sustainable web development](quality.md#sustainable-web-development)). + + **What is left:** The images still take about 33 % more space in the database than as files, and the backend decodes them on every request the browser has not cached. With many more plants, they should be stored as files with only the path in MongoDB. The `/images/:id` route could then be changed without changing the frontend. ## Folder structure @@ -287,13 +308,16 @@ T03-Project-2/ ├── .github/ # CI workflow (format, lint, tests, build, e2e) and CODEOWNERS (required PR review) ├── backend/ │ ├── src/ +│ │ ├── app.ts # Express app with GraphQL on /graphql and the plant images on /images/:id │ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env) +│ │ ├── images.ts # Sends a stored plant image as a file (/images/:id) │ │ ├── queryBuilders.ts # Filters and sort stages for searching, filtering and sorting plants │ │ ├── indexes.ts # Database indexes, created when the server starts -│ │ ├── migrations.ts # Updates old data when the server starts +│ │ ├── listen.ts # Starts listening on the port (replaced in the tests) +│ │ ├── migrations.ts # Updates old data (the snake plant avatar id) when the server starts │ │ ├── resolvers/ # GraphQL resolvers: plants.ts, users.ts, shared helpers.ts and index.ts │ │ ├── schema.ts # GraphQL schema -│ │ ├── server.ts # Starts the backend (app.ts: Express with /graphql and /images) +│ │ ├── server.ts # Starts the backend: indexes, migrations, then the app from app.ts │ │ └── types.ts # TypeScript types for documents, GraphQL types and arguments │ ├── tests/ # Backend tests against an in-memory MongoDB (db, server, indexes, migrations, listen), with their own tsconfig.json │ ├── seedDataFetch.js # Script that fetches plant data from the Perenual API and stores it in MongoDB @@ -301,7 +325,7 @@ T03-Project-2/ ├── docs/ # Project documentation (architecture, tests, quality, AI usage), media/ has the coverage images ├── e2e/ # Playwright e2e and API tests │ ├── fixtures/ # The 20 test plants -│ ├── helpers/ # Shared helpers for GraphQL requests, navigation and the accessible names used by the UI tests +│ ├── helpers/ # Shared helpers for GraphQL requests, navigation, locators and the accessible names used by the UI tests │ ├── api*.spec.ts # API tests, GraphQL requests straight to the backend │ ├── ui*.spec.ts # UI tests in the browser, including accessibility (uiAccessibility.spec.ts) │ ├── globalSetup.ts # Empties the test database and adds the test plants before the tests @@ -312,8 +336,8 @@ T03-Project-2/ │ │ ├── assets/ # Static images (WebP) │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file (walkthrough/ has the guide and its steps) │ │ ├── context/ # UserProvider and useUser() for the current user, ErrorMessageProvider and useErrorMessage() for error messages -│ │ ├── graphql/ # All GraphQL queries, mutations and fragments, grouped by domain (fragments/, plants/, user/) -│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useMyMatchesParams, useSessionState, useProfile, usePreferences, useMatchedPlants, useNewMatches, usePlantDeck, useDismissibleTooltip) +│ │ ├── graphql/ # All GraphQL queries, mutations and fragments, grouped by domain (fragments/, plants/, user/), and apiUrl.ts with the API and image addresses +│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useMyMatchesParams, useSessionState, useProfile, usePreferences, useMatchedPlants, usePlantDeck, useNewMatches, useDismissibleTooltip) │ │ ├── i18n/ # Translation setup and locale files (no, en) │ │ ├── pages/ # One folder per page/route, each with a Page.tsx and a matching .css file │ │ │ ├── explorePlants/ # ExplorePlantsPage @@ -324,7 +348,9 @@ T03-Project-2/ │ │ │ └── profile/ # ProfilePage │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) │ │ ├── types/ # Shared TypeScript types and ids (Plant, User, Preference, ProfilePicture) +│ │ ├── App.tsx # Layout (sidebar, header, skip link), walkthrough and ErrorMessageProvider │ │ ├── AppRoutes.tsx # Route definitions +│ │ ├── index.css # Colors as CSS variables for the light and dark theme │ │ └── main.tsx # Application entry point (Apollo Client, UserProvider, router) │ ├── .env.production # GraphQL URL for the deployed app │ └── vite.config.ts # Vite and Vitest configuration, including proxy to the backend @@ -338,28 +364,3 @@ T03-Project-2/ - **PascalCase** for React components and their files (`PlantCard.tsx`, `SortMenu.css`), and for TypeScript types (`Plant`, `PlantCardProps`). Every page component ends in `Page` (`ExplorePlantsPage`), and test files are named after what they test (`ExplorePlantsPage.test.tsx`). - **camelCase** for variables, functions, hooks (`useMatchedPlants`), folders, routes (`/myMatches`), translation sections and keys (`explorePlantsPage.search`), and all other files, including images and e2e helpers (`snakePlant.webp`, `globalSetup.ts`). - **UPPER_SNAKE_CASE** for module-level constants that never change (`ROUTES`, `PAGE_SIZE`, `GET_PLANTS`, `LANGUAGE_STORAGE_KEY`). - -## How to start the backend if it stops - -On the VM, the backend runs in pm2 under the name `plants-backend`, as the user `alexajah`, from `/home/alexajah/T03-Project-2/backend`. pm2 restarts it if it crashes or the VM reboots. - -The backend reads the following variables from `backend/.env` on the VM (see `.env.example`): - -- `MONGODB_URI=mongodb://localhost:27017` -- `DB_NAME=iloveplants` -- `PORT=3001` - -Log in with: - -```bash -ssh @it2810-03.idi.ntnu.no -``` - -If you are not `alexajah`, put `sudo -u alexajah` in front of the pm2 commands, since pm2 only shows the processes of the user who started them. - -```bash -pm2 list # is plants-backend online? -pm2 restart plants-backend # start it again if it is not -``` - -If the logs show that the backend cannot connect to MongoDB, the database has stopped and must be started before the backend is restarted. diff --git a/docs/media/coverageBackend.png b/docs/media/coverageBackend.png index a7834344..84c11c7a 100644 Binary files a/docs/media/coverageBackend.png and b/docs/media/coverageBackend.png differ diff --git a/docs/media/coverageFrontend.png b/docs/media/coverageFrontend.png index a9e1c5ee..184b7fbe 100644 Binary files a/docs/media/coverageFrontend.png and b/docs/media/coverageFrontend.png differ diff --git a/docs/quality.md b/docs/quality.md index 9e9f58c0..baa20cdf 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -1,14 +1,14 @@ # Quality -This document describes how we have worked to ensure the quality of the application through work practices, accessibility, sustainable web development and design choices. Testing is described in its own document, [tests.md](tests.md), which covers the test strategy, how to run the tests, the coverage and what the tests found. +This document describes how we have worked to ensure the quality of the application through work practices, accessibility, sustainable web development and design choices. Testing is also part of our quality work and is described in [tests.md](tests.md). ## Quality aspects - Work practices: [Work practices](#work-practices) -- Testing: [tests.md](tests.md) - Accessibility: [Accessibility](#accessibility) - Sustainable web development: [Sustainable web development](#sustainable-web-development) - Design choices: [Design choices](#design-choices) +- Testing: [tests.md](tests.md) ### Continuous integration @@ -61,13 +61,15 @@ The app includes the following accessibility features: - **Forms and images:** Search, filters and profile inputs have associated labels. Plant images use the plant name as alternative text, and profile and avatar images also include alternative text. -- **Control states:** The sort menu and the mobile menu button expose their expanded state and which element they control. Sort, avatar and preference choices and the profile tabs expose their selected state with `aria-pressed`. The preference chips on the plant cards are a list, and a chip that matches the user's preferences also says so in text that only screen readers read, so the information is not given by color alone. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes, including "No results found" when a search gives no plants and "no matches" when the last match is removed. Filter values that would give no plants are disabled options, so screen readers say they are unavailable, and the number of plants is part of the option text. Every page has one `h1` (the page title in the header) and a `main` landmark. The match button on the plant cards shows a heart to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. If adding or removing a match fails, an error message is shown at the top of the screen in a `role="alert"` region, so screen readers read it at once without moving focus. +- **Control states:** The sort menu and the mobile menu button expose their expanded state and which element they control. Sort, avatar and preference choices and the profile tabs expose their selected state with `aria-pressed`. The preference chips on the plant cards are a list, and a chip that matches the user's preferences also says so in text that only screen readers read, so the information is not given by color alone. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes, including "No results found" when a search gives no plants and "no matches" when the last match is removed. Filter values that would give no plants are disabled options, so screen readers say they are unavailable, and the number of plants is part of the option text. Every page has one `h1` (the page title in the header) and a `main` landmark. The match button on the plant cards shows a heart to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. The badge with the number of new matches on the My Matches link in the sidebar is hidden from screen readers, which instead read a text such as "2 new matches" as part of the link. If adding or removing a match fails, an error message is shown at the top of the screen in a `role="alert"` region, so screen readers read it at once without moving focus. - **Plant cards:** The inactive side of a flipped card is hidden from assistive technology with `aria-hidden`, and its information button is removed from the keyboard tab order. - **Swiping is never the only way:** On Plant Match the card can be swiped, but the ♥ and ✖ buttons next to it do the same, so users who use the keyboard, a screen reader or cannot drag can still match and skip plants (WCAG 2.5.1 Pointer Gestures). The "How to match" help text mentions both. -- **Reduced motion:** When the user has asked for reduced motion in their system settings, the animation of the card flying off after a swipe, the plant card flip and hover effects, the animation of the error message and the hover effects in the Plant Owner Test are turned off. +- **Reduced motion:** When the user has asked for reduced motion in their system settings, the animation of the card flying off after a swipe, the plant card flip and hover effects, the animation of the error message and the hover effects in the Plant Owner Test are turned off. A rule in `index.css` also turns off every other transition and animation in the app (such as the hover movements on buttons and preference chips), and the best match button on My Matches jumps straight to the plant instead of scrolling smoothly. + +- **Focus in high contrast mode:** Many focus styles draw the focus ring with `box-shadow`, which forced-colors modes such as Windows High Contrast remove. Those styles therefore use a transparent outline instead of `outline: none`: it is invisible normally, but forced-colors mode gives it a visible color, so keyboard users can still see where focus is. - **Testing:** The end-to-end tests check all pages against WCAG 2.1 AA with axe, in both light and dark mode, and the component tests check accessible names, navigation state and sorting states. The axe DevTools extension found no issues, and the deployed app scored 100 for accessibility in Lighthouse. The app has also been tested manually with the keyboard only and at 200 % zoom. See [tests.md](tests.md#accessibility) for the results, including two problems the tests found. @@ -87,13 +89,13 @@ We considered sustainability through both our design choices and our approach to - **Data fetching and storage:** Plant data is fetched from the Perenual API once and stored in our own MongoDB database. The application retrieves data through our GraphQL backend rather than repeatedly requesting data from the external API. This reduces unnecessary external requests and avoids repeatedly transferring the same data from Perenual. -- **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset. Sorting by name uses a database index, so the server does not have to sort the whole collection for every request. Only the ids of the user's matches are sent with the user, and My Matches fetches one page of plants at a time, so the plant images are only sent when they are shown. +- **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset. Sorting by name uses a database index, so the server does not have to sort the whole collection for every request. Only the ids of the user's matches are sent with the user, and My Matches fetches one page of plants at a time, so the responses do not grow with the number of matches. The plant images are sent as separate files that the browser loads lazily and caches for a week, so an image is only downloaded when its card is shown, and only once. - **Inline SVG icons without an icon library:** The application only needs a few icons (search, sort, the heart on the match buttons, and the sun and moon on the theme button), so we draw them ourselves as small inline SVG components instead of installing an icon library such as `react-icons`. This keeps the project to one fewer dependency that has to be downloaded, installed and kept up to date, and the icons are part of the JavaScript the page already loads, so they need no extra requests or icon font. SVGs are also vector graphics, so they stay sharp at any size and zoom level without image files in several resolutions. - **Debouncing:** On Explore Plants and My Matches, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost. -- **Filter counts in one query:** The number of plants for every filter value on Explore Plants is counted in the same request as the results, in one database query, instead of one request per value. Values that would give no plants can't be chosen, so the user does not send requests that only return an empty list. +- **Filter counts in one query:** The number of plants for every filter value on Explore Plants and My Matches (where only the user's matches are counted) is counted in the same request as the results, in one database query, instead of one request per value. Values that would give no plants can't be chosen, so the user does not send requests that only return an empty list. - **Images in WebP:** The avatars, plant owner test images and plant placeholder were converted from PNG to WebP. Measured on the build and on the Profile page with the avatar chooser open: @@ -121,7 +123,7 @@ We considered sustainability through both our design choices and our approach to - **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `PlantSearchForm` (search, filters, sort menu and reset), `Pagination` and `MatchButton` are shared by Explore Plants and My Matches, so the two pages look and work the same, and `ErrorMessage` shows error messages on every page. The filters are defined in one list (`plantFilters.ts`), which the search form, the URL, `sessionStorage` and the query variables all use. A new filter also needs a variable in the GraphQL queries, its texts in the translation files, and support in the backend. -- **Keeping the previous results while loading:** On Explore Plants, the previous results and the number of results stay on screen, slightly dimmed, while new ones load (with Apollo's `previousData`). The page does not flicker or jump when the search, a filter or the page changes, and the loading text is only shown the first time. +- **Keeping the previous results while loading:** On Explore Plants and My Matches, the previous results stay on screen while new ones load (with Apollo's `previousData`), slightly dimmed. The page does not flicker or jump when the search, a filter or the page changes, and the loading text is only shown the first time. - **Consistent icons:** All icons are inline SVG components in [Icons.tsx](../frontend/src/components/icons/Icons.tsx), [ThemeIcons.tsx](../frontend/src/components/sidebarButtons/ThemeIcons.tsx) and [HeartIcon.tsx](../frontend/src/components/heartIcon/HeartIcon.tsx), drawn on the same 24 × 24 grid. They use `currentColor`, so they follow the text color in both light and dark mode, and they are sized with `font-size`, so they scale with the text around them. They are marked with `aria-hidden` and `focusable="false"`, since the search field and the buttons they are in already have accessible names, so screen readers do not read the icons twice. Because we drew the icons ourselves, there are no third-party licences to credit. diff --git a/docs/tests.md b/docs/tests.md index a8786c72..7f6360cb 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -35,7 +35,7 @@ All levels test both **typical use** (searching, filtering, matching plants, edi None of the tests use the database on the VM, so they need neither the VPN nor the SSH tunnel. -All tests run in GitHub Actions on every pull request (see [Continuous integration](quality.md#continuous-integration)), so a pull request that breaks a test cannot be merged unnoticed. The end-to-end tests also check all pages against WCAG 2.1 AA, which helped us find and fix accessibility problems that the other tests did not catch (see [Accessibility](#accessibility)). +All tests run in GitHub Actions on every pull request (see [Continuous integration](quality.md#continuous-integration)), so a pull request that breaks a test cannot be merged unnoticed. The end-to-end tests also check all pages against WCAG 2.1 AA, which helped us find and fix accessibility problems that the other tests did not catch (see [Accessibility](#accessibility)). All tests were also run before each merge with `npm run ci:all`. ## Run the tests @@ -83,6 +83,7 @@ npm install --prefix backend ```bash npm run test:frontend -- --coverage npm run test:backend -- --coverage +npm run test:coverage # both, backend first ``` If some tests fail, a report can still be made with `npx vitest run --coverage --coverage.reportOnFailure=true`. @@ -93,7 +94,7 @@ To watch an e2e test, open UI mode, run a test, and expand it to choose the desk | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 97.38 % | 93.86 % | 96.76 % | 98.39 % | +| Frontend | 97.44 % | 93.78 % | 96.83 % | 98.43 % | | Backend | 100 % | 100 % | 100 % | 100 % | - Frontend test coverage: @@ -116,7 +117,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `App.test.tsx` - Shows the right page for each route, and opens and closes the sidebar from the header. - - The skip link is the first thing a keyboard user reaches and moves focus to the main content without changing the route, and when the user goes to another page, focus moves to the start of the page so the next Tab goes to the skip link. + - The skip link is the first thing a keyboard user reaches and moves focus to the main content without changing the route, and when the user goes to another page, the page scrolls to the top and focus moves to the start of the page so the next Tab goes to the skip link. - The walkthrough opens on the first visit and is not shown again after it is closed, focus goes back to the ? button, and the ? button opens it at the step for the current page. - `ErrorMessageContext.test.tsx` - The message is shown in an `alert` region, hidden after six seconds, replaced by a new message with the time started again, and nothing happens without a provider. @@ -124,8 +125,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - Loading, error and empty results: a loading message, an error message when the query fails, and a message without page navigation when nothing matches. - Search, filters and sorting: the search text is only sent after the debounce delay, the chosen filters and sort order are sent in the query, the selected sort is visible and included in the sort button's accessible name, and the sort menu closes with Escape and with a click outside, and "Best match first" is only offered when the user has preferences, sends them with the query, and falls back to A–Z when the URL asks for it without preferences. - Number of results: the total number for the whole result is shown, not only the plants on the page, it updates when a filter changes, it is in an `aria-live` region together with "No results found", and it is hidden while loading. Each filter value shows its number of matches, values with no matches are disabled except the chosen one, and the previous results stay on screen while new ones load. - - Pagination: moving between pages, disabled buttons at the ends, and going back to page 1 when a filter or the search text changes. - - Matches: the button adds a plant that is not matched (✿), and removes a plant that is already matched (✖). + - Pagination: moving between pages, disabled buttons at the ends, and going back to page 1 when a filter or the search text changes. Sorted by name, Next and Previous send the cursor of the page on screen (`after` and `before`), while page 1 and a jump to a page number use the offset, and each page is fetched once with no extra requests. + - Matches: the button adds a plant that is not matched (heart), and removes a plant that is already matched (✖). - URL state: search, filters, sorting and page are restored from the URL, changes are written to the URL, and reset clears the Explore parameters. - Accessibility: a search landmark, a heading, labelled controls, a search field with an example in the placeholder, and the filters grouped under a name. - `FilterSelect.test.tsx` @@ -136,6 +137,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - Which page numbers are shown: every page when there are few, the first pages near the start, the last pages near the end, the current page and its neighbours in the middle, "…" never hiding just one page, and never more than seven items however many pages there are. - `Pagination.test.tsx` - Clicking a page number goes straight to that page, the current page is marked with `aria-current` and clicking it does nothing, and the previous and next buttons are disabled at the ends. +- `usePageCursor.test.ts` + - No cursor at first, the last plant for the next page and the first for the previous one, the offset for a jump, page 1, a sort order without cursors and a page that has not loaded yet, and that a cursor is forgotten when the search, filters or sort order change. - `Header.test.tsx` - Shows the right title for each page, including the "Page not found" title for unknown paths, opens the sidebar with the menu button, and that the menu button tells screen readers whether the sidebar is open (`aria-expanded`, `aria-controls`). - `i18n.test.tsx` @@ -160,7 +163,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `PlantMatchPage.test.tsx` - The instructions and the first plant, going to the next plant with like and dislike and the empty card at the end, that a liked plant is saved as a match and a skipped one is not, the loading and error states, that preferences saved on the profile are highlighted on the card and also said in text for screen readers, and that the info button is described by the instructions, which Escape hides. - Loading in batches: the first batch is fetched with the batch size and no excluded plants, the next batch is only fetched when few cards are left and leaves out the plants already shown, every plant is shown exactly once, no more requests are made after a short batch, and a second request is not started while one is in progress. - - Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, changing preferences starts a new deck with the updated ordering, also when they were changed on the profile page while PlantMatch was closed (the saved deck remembers which preferences it was sorted by), nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all. + - Matched plants and the saved deck: plants the user has already matched are not shown, a card is skipped when its plant is matched on another page, the user continues from the same card after leaving the page and coming back, only the cards that are left are saved, and a new deck is started when the saved deck can't be read. + - Reload and end cards: the Reload button starts the deck over from the first plant and tries again after an error, the end card with disabled buttons is shown when there are no plants at all, and when every plant is matched the end card says so and links to My Matches, while the normal end card is shown when some plants are not matched. + - Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, changing preferences starts a new deck with the updated ordering, also when they were changed on the profile page while PlantMatch was closed (the saved deck remembers which preferences it was sorted by), and nothing is fetched before the user has loaded. - Swiping: dragging the card far enough right saves a match and left skips the plant, a short drag moves the card back without flipping it, a tap that hardly moves flips the card, a mostly vertical movement lets the page scroll, other mouse buttons are ignored, and with animations on, the card flies off before the next plant is shown and swipes are ignored meanwhile. A liked card stays on screen while it flies off, even though it is already saved as a match, and the end card is only shown after the last card has flown off. - `PlantOwnerTestPage.test.tsx` - The result for all six combinations of answers, and that the time and light answers do not change it. @@ -173,9 +178,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - The name, the image alt text and a screen reader prefix for the description, the preferences tab open by default (`aria-pressed`), the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, and that a picture from the plant owner test is shown but not offered in the chooser. - Saving the profile text at once when a field loses focus, when the user leaves the page and when the tab is reloaded or closed, without saving the same text twice. - `Sidebar.test.tsx` - - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, that only the current page is marked as active, that focus moves to the close button when it opens, that Escape closes it while other keys do not, and that the heart in the title is in its own element so it can be green. + - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, that only the current page is marked as active, that focus moves to the close button when it opens, that Escape closes it while other keys do not (and does nothing while it is closed), and that the heart in the title is in its own element so it can be green. - `SidebarNewMatches.test.tsx` - - The badge on My Matches counts only matches made while the app is open, not a match that is removed again, and counts a match the user already had as new if it is removed and added again. It is cleared when My Matches is opened. + - The badge on My Matches in the sidebar: the matches the user already had are not counted, new matches are counted, a match that is removed again is not counted, a match the user already had counts as new if it is removed and added again, and the badge is cleared when My Matches is opened. - `ThemeToggle.test.tsx` - Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked. - `translationKeys.test.tsx` @@ -212,7 +217,8 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in - Plants: `getPlants` returns the plants that match the most of the user's preferences first, also when they are fetched in batches ("Low" counts as easy care), random plants when there are no preferences or only unknown ones, and leaves out the plants in `excludeIds` (returning none when all are excluded). Also that the plant queries link to the stored image (`/images/`) before the image URL and never send the base64 image, and in `explorePlants` the default sorting, case-insensitive search across common and scientific names with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, that `limit` and `offset` are kept within valid bounds (at most 50 plants per request), and all sort orders including best match first (by the preferences sent, by name when plants match equally well, and by name without preferences), and the match counts for every filter value (with the search and the other filters, but not the filter's own choice). - Users: creating and fetching users, updating the profile (trimming text, storing empty text and `null` as `null`, and only changing the sent fields), the plant owner test results as profile pictures, preferences without duplicates, and adding and removing matches in order. - My matches: `myMatches` sorts by newest (the default), oldest, A–Z, Z–A and best match first (by the user's saved preferences), returns one page at a time with the total count, leaves out and does not count matched plants that were deleted, and returns an empty page for a user without matches and for an unknown or malformed user id. Filtering and searching only among the user's matches, with the filter counts also counted only among them, and zero counts for a user without matches. - - Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name or description, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and the server passes on a database error and keeps running. + - Cursor pagination: with `name_asc` and `name_desc`, paging forwards with `after` and backwards with `before` gives exactly the same pages as `offset`, also where plants share a name and the `_id` decides the order. A cursor keeps the search and overrides `offset`, the page after the last plant is empty and has no cursors, the calculated sort orders give no cursors, and My Matches is paged with a cursor when sorted by name but not newest first. A cursor with a calculated sort order, both `after` and `before`, and a cursor that is not one the backend made are rejected with `BAD_USER_INPUT`. + - Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name, description or search, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and a database error is logged on the server while the client only gets a general message without internal details or a stack trace, and the server keeps running. - `indexes.test.ts` - The index for sorting by name is created, and creating it again on the next start does not fail. - `migrations.test.ts` @@ -274,7 +280,9 @@ The UI tests find elements the way a user or a screen reader would: by role, lab - Liking a plant on PlantMatch adds it to MyMatches, where it can be removed. - Swiping a plant left on PlantMatch skips it and swiping right matches it, with the mouse on desktop and a finger on mobile. Playwright can only tap with a finger, so the drag is sent through the Chrome DevTools Protocol, and the browser handles it like a real finger, including `touch-action` on the card. The component tests send pointer events in jsdom, so only this test checks that the gesture works in a real browser. -- Adding a plant from ExplorePlants adds it to MyMatches and turns its ✿ button into ✖. Clicking the button again on ExplorePlants removes the plant from MyMatches. +- Adding a plant from ExplorePlants adds it to MyMatches and turns its heart button into ✖. Clicking the button again on ExplorePlants removes the plant from MyMatches. +- A plant matched on ExplorePlants never shows up in PlantMatch. +- PlantMatch continues from the same card after the user visits another page, and after a reload. - Searching and filtering MyMatches: the search only looks among the user's matches, a filter disables the values that would give no matches, the choices are remembered when going to another page and back, a search that finds nothing says so under the filters, and reset shows all the matches again. - Matching 13 plants from ExplorePlants gives two pages in MyMatches: the count, the newest first on page 1 and the oldest on page 2, sorting A–Z going back to page 1, and the sort order remembered when going to another page and back, and after a reload. @@ -314,16 +322,21 @@ Saving the profile is debounced by 500 ms, and the text is also saved at once wh **API tests:** -- **explorePlants**: default sorting and page size, `offset`, case-insensitive search, regex characters treated as plain text, the watering, care level and sunlight filters, the sort orders, and that plants without a care level are sorted last. -- **User profile**: a new user's default values, updating and reading back the profile and preferences, that only the sent fields change, that duplicate preferences are removed, and that too long names and descriptions, unknown profile pictures, unknown preferences and invalid user ids are rejected or return `null` without crashing. -- **Matches**: adding, reading back and removing a match, that matches keep the order they were added in, that the same plant is only matched once, and that unknown or malformed plant ids are rejected. Also that `myMatches` returns the whole plant, sorts by newest, oldest and name, returns one page at a time with the total count, and returns an empty page for a user without matches or an unknown user. +- **explorePlants**: default sorting and page size, `offset`, that a cursor (`after` and `before`) gives the same next and previous pages as `offset` in both name orders, case-insensitive search, regex characters treated as plain text, the watering, care level and sunlight filters, the sort orders, and that plants without a care level are sorted last. +- **User profile**: a new user's default values, updating and reading back the profile and preferences, that only the sent fields change, that every preference and profile picture id in `frontend/src/types/` is accepted, that duplicate preferences are removed, that an empty name is stored as `null`, and that too long names and descriptions, unknown profile pictures, unknown preferences and invalid user ids are rejected or return `null` without crashing. +- **Matches**: adding, reading back and removing a match, that matches keep the order they were added in, that the same plant is only matched once, that unknown or malformed plant ids are rejected, and that removing a plant that is not matched changes nothing. Also that `myMatches` returns the whole plant, sorts by newest, oldest and name, returns one page at a time with the total count, and returns an empty page for a user without matches or an unknown user. #### Accessibility `uiAccessibility.spec.ts` runs **axe** through `@axe-core/playwright` against WCAG 2.1 level A and AA, the level required for the public sector in Norway. It checks: - all six pages (PlantMatch, ExplorePlants, MyMatches, Profile, PlantOwnerTest and the 404 page), in both light and dark mode, since colour contrast has to meet the WCAG 2.1 requirements in both themes -- content that only appears after an interaction: a flipped plant card, the edit tab on the profile page, MyMatches with a matched plant, the result of the plant owner test with the suggested preferences (whose buttons are also checked for non-text contrast), and the open walkthrough +- content that only appears after an interaction: a flipped plant card, the "i" and match button tooltips on ExplorePlants, PlantMatch and Profile, PlantMatch with no more plants and when the plants can't be loaded, the edit tab on the profile page, MyMatches with a matched plant, the result of the plant owner test with the suggested preferences, the open walkthrough, and the open sidebar with the language and theme buttons + +axe leaves some gaps, which the test file covers itself: + +- axe only checks the contrast of text (WCAG 1.4.3). The contrast of borders, surfaces and icons (WCAG 1.4.11), and of placeholder text, is checked by a separate function in the test file. +- When axe cannot find the background of a text, the result is "incomplete" instead of a violation. Those results fail the test too, except the expected ones (icon-only text such as ✖, and text under an open tooltip). The tests run on both desktop and mobile, since the layout, and the elements that are visible, differ between them. A failing test lists each element that breaks a rule, with axe's explanation (for contrast: the colours and the ratio). @@ -358,16 +371,18 @@ Automatic testing only finds some accessibility problems, and the tests only che ## Manual testing -The group has tested the application manually in Chrome on Mac and on a mobile phone (iphone) throughout development, using all pages and features on both. The testing was also done on mac using the "inspect" and choosing mobile view. This testing led to adjustments such as improvements to the mobile layout. Here are some examples: +The group has tested the application manually in Chrome and Safari on Mac and on an iPhone 16 throughout development, using all pages and features on each device. The testing was also done on Mac using Chrome DevTools ("Inspect") in mobile view. This testing led to adjustments such as improvements to the mobile layout. Here are some examples: + +**Keyboard only:** All pages have been tested with Tab, Shift+Tab, Enter and Escape only. All links and buttons can be reached and used, the focus is visible at all times, in the sort menu, focus moves into the menu when it opens and back to the sort button when it closes, and on mobile, focus moves into the sidebar when it opens and back to the menu button when it closes. The "i" help texts can be closed with Escape. The first Tab on every page shows the "Skip to content" link, which jumps past the sidebar, and the same happens after going to another page. -**Keyboard only:** all pages have been tested with Tab, Shift+Tab, Enter and Escape only. All links and buttons can be reached and used, the focus is visible at all times, in the sort menu, focus moves into the menu when it opens and back to the sort button when it closes, and on mobile, focus moves into the sidebar when it opens and back to the menu button when it closes. The "i" help texts can be closed with Escape. The first Tab on every page shows the "Skip to content" link, which jumps past the sidebar, and the same happens after going to another page. +**Screen reader:** To ensure aria-live was performing according to our intention, the application was tested using Voiceover on macOS. We checked that changes to the number of matches, loading messages and empty search results were announced. **Finding: the skip link hid the search field.** The first version scrolled the content up behind the sticky header, which the component tests did not catch, since jsdom does not scroll. The link now moves focus without scrolling. -**Zoom to 200 %:** on a laptop screen, the app switches to the mobile layout at 200 % zoom. The sidebar is hidden and can be opened with the menu button in the header, so the layout adapts to the larger text instead of needing horizontal scrolling (WCAG 1.4.4 and 1.4.10). +**Zoom to 200 %:** On a laptop screen, the app switches to the mobile layout at 200 % zoom. The sidebar is hidden and can be opened with the menu button in the header, so the layout adapts to the larger text instead of needing horizontal scrolling (WCAG 1.4.4 and 1.4.10). ## Lighthouse -We ran Lighthouse in Chrome DevTools on the deployed app on the VM. Lighthouse audits a page for performance, accessibility, best practices and SEO. The app passed the accessibility audit with a score of **100**, so Lighthouse found no problems with, for example, colour contrast, labels or alternative text. Lighthouse was also one of the tools we used to check the colour contrast (see [Accessibility](quality.md#accessibility) in quality.md). +We ran Lighthouse in Chrome DevTools on the deployed app on the VM. Lighthouse audits a page for performance, accessibility, best practices and SEO. In order to securely confirm accessibility, we tested all pages of the app in both dark and lightmode. All pages of the app passed the accessibility audit with a score of **100**, so Lighthouse found no problems with, for example, colour contrast, labels or alternative text. Lighthouse was also one of the tools we used to check the colour contrast (see [Accessibility](quality.md#accessibility) in quality.md). Like axe, Lighthouse only finds problems that can be detected automatically, so it does not replace the manual testing above. diff --git a/e2e/apiExplorePlants.spec.ts b/e2e/apiExplorePlants.spec.ts index 19efe555..b117e3c2 100644 --- a/e2e/apiExplorePlants.spec.ts +++ b/e2e/apiExplorePlants.spec.ts @@ -65,6 +65,48 @@ test.describe("explorePlants", () => { expect(result.plants[0].name).toBe("Monstera"); }); + test("a cursor gives the same next and previous pages as offset", async ({ + request, + }) => { + const CURSOR_PAGE = ` + query ($sort: String, $limit: Int, $offset: Int, $after: String, $before: String) { + explorePlants(sort: $sort, limit: $limit, offset: $offset, after: $after, before: $before) { + plants { name } + startCursor + endCursor + } + } + `; + type Page = { + plants: { name: string }[]; + startCursor: string | null; + endCursor: string | null; + }; + const page = async (variables: Record): Promise => { + const body = await graphql(request, CURSOR_PAGE, variables); + expect(body.errors).toBeUndefined(); + return body.data.explorePlants; + }; + const pageNames = (p: Page) => p.plants.map((plant) => plant.name); + + for (const sort of ["name_asc", "name_desc"]) { + const first = await page({ sort, limit: 8 }); + const second = await page({ sort, limit: 8, after: first.endCursor }); + const third = await page({ sort, limit: 8, after: second.endCursor }); + + expect(pageNames(second)).toEqual( + pageNames(await page({ sort, limit: 8, offset: 8 })), + ); + expect(pageNames(third)).toEqual( + pageNames(await page({ sort, limit: 8, offset: 16 })), + ); + // Back from the third page gives the second page again + expect( + pageNames(await page({ sort, limit: 8, before: third.startCursor })), + ).toEqual(pageNames(second)); + } + }); + test("search is case insensitive", async ({ request }) => { const result = await explorePlants(request, { search: "PLANT" }); expect(result.totalCount).toBe(2); diff --git a/e2e/helpers/graphql.ts b/e2e/helpers/graphql.ts index ebd6095e..5141c5ec 100644 --- a/e2e/helpers/graphql.ts +++ b/e2e/helpers/graphql.ts @@ -1,6 +1,6 @@ import { expect, type APIRequestContext } from "@playwright/test"; -// Shared helpers for the API tests (api-*.spec.ts). +// Shared helpers for the API tests (api*.spec.ts). // Queries used by more than one test file are kept here; queries only used // in one file stay in that file. diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index 40ee4d9f..1afa4655 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -16,7 +16,7 @@ import { openSidebar } from "./helpers/navigation"; const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]; -// axe can't check text that is only symbols (✿, ✖). checkNonTextContrast +// axe can't check text that is only symbols (such as ✖). checkNonTextContrast // checks those icons instead, so this incomplete result is expected. const ICON_ONLY_MESSAGE = "contains only non-text characters"; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 6cf14bd2..fb867c76 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -35,6 +35,9 @@ "typescript-eslint": "^8.69.0", "vite": "^8.3.0", "vitest": "^5.0.3" + }, + "engines": { + "node": ">=24.6" } }, "node_modules/@adobe/css-tools": { diff --git a/frontend/package.json b/frontend/package.json index 99f851fe..968eecac 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,9 @@ { "name": "frontend", "private": true, + "engines": { + "node": ">=24.6" + }, "version": "0.0.0", "type": "module", "scripts": { diff --git a/frontend/src/components/filterSelect/FilterSelect.css b/frontend/src/components/filterSelect/FilterSelect.css index c75004fc..c42d2b8a 100644 --- a/frontend/src/components/filterSelect/FilterSelect.css +++ b/frontend/src/components/filterSelect/FilterSelect.css @@ -16,6 +16,6 @@ } .filter select:focus { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-pink); } diff --git a/frontend/src/components/matchButton/MatchButton.css b/frontend/src/components/matchButton/MatchButton.css index 64722382..780c1fe4 100644 --- a/frontend/src/components/matchButton/MatchButton.css +++ b/frontend/src/components/matchButton/MatchButton.css @@ -67,7 +67,7 @@ } .add-match-button:focus-visible { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 3px var(--dark-pink); } diff --git a/frontend/src/components/pagination/Pagination.css b/frontend/src/components/pagination/Pagination.css index 90977b77..cc89c96f 100644 --- a/frontend/src/components/pagination/Pagination.css +++ b/frontend/src/components/pagination/Pagination.css @@ -34,7 +34,7 @@ } .pagination button:focus-visible { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-green); } diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index bbc7c45e..f338a24b 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -18,14 +18,12 @@ export type PlantCardHandle = { type PlantCardProps = { plant: PlantCardData; size?: "large" | "compact"; - onInfo?: () => void; ref?: Ref; }; export default function PlantCard({ plant, size = "large", - onInfo, ref, }: PlantCardProps) { const { @@ -58,7 +56,6 @@ export default function PlantCard({ moveFocusRef.current = cardRef.current?.contains(document.activeElement) ?? false; setIsFlipped((flipped) => !flipped); - onInfo?.(); } function handleKeyDown(event: KeyboardEvent) { diff --git a/frontend/src/components/plantSearchForm/PlantSearchForm.css b/frontend/src/components/plantSearchForm/PlantSearchForm.css index 0ee605da..fd657c56 100644 --- a/frontend/src/components/plantSearchForm/PlantSearchForm.css +++ b/frontend/src/components/plantSearchForm/PlantSearchForm.css @@ -31,7 +31,7 @@ } .plant-search input:focus { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-pink); } @@ -67,6 +67,6 @@ } .reset-button.reset-button:focus-visible { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-pink); } diff --git a/frontend/src/components/plantSearchForm/PlantSearchForm.tsx b/frontend/src/components/plantSearchForm/PlantSearchForm.tsx index 7772bcd9..fd64fede 100644 --- a/frontend/src/components/plantSearchForm/PlantSearchForm.tsx +++ b/frontend/src/components/plantSearchForm/PlantSearchForm.tsx @@ -5,6 +5,7 @@ import SortMenu from "../sortMenu/SortMenu"; import type { FilterCounts } from "../../graphql/plants/queries"; import { PLANT_FILTERS, + SEARCH_MAX_LENGTH, type FilterParam, type PlantFilters, } from "./plantFilters"; @@ -61,6 +62,7 @@ export default function PlantSearchForm({ type="search" placeholder={t("explorePlantsPage.searchPlaceholder")} value={search} + maxLength={SEARCH_MAX_LENGTH} onChange={(e) => onSearchChange(e.target.value)} /> diff --git a/frontend/src/components/plantSearchForm/plantFilters.ts b/frontend/src/components/plantSearchForm/plantFilters.ts index 23ca9de5..6522d004 100644 --- a/frontend/src/components/plantSearchForm/plantFilters.ts +++ b/frontend/src/components/plantSearchForm/plantFilters.ts @@ -46,3 +46,7 @@ export const PREFERENCES_SORT = "preferences"; // How long to wait after the user stops typing before searching, in ms export const SEARCH_DEBOUNCE_MS = 300; + +// The longest search the field accepts. Must match MAX_SEARCH_LENGTH in +// backend/src/resolvers/plants.ts, which rejects longer searches. +export const SEARCH_MAX_LENGTH = 100; diff --git a/frontend/src/components/sortMenu/SortMenu.css b/frontend/src/components/sortMenu/SortMenu.css index fb12c25c..03b43c6b 100644 --- a/frontend/src/components/sortMenu/SortMenu.css +++ b/frontend/src/components/sortMenu/SortMenu.css @@ -45,7 +45,7 @@ .sort-button:focus-visible, .sort-option:focus-visible { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-pink); } diff --git a/frontend/src/graphql/plants/queries.ts b/frontend/src/graphql/plants/queries.ts index 05480a2a..b923726e 100644 --- a/frontend/src/graphql/plants/queries.ts +++ b/frontend/src/graphql/plants/queries.ts @@ -32,6 +32,8 @@ export const EXPLORE_PLANTS = gql` $preferences: [String!] $limit: Int $offset: Int + $after: String + $before: String ) { explorePlants( search: $search @@ -42,8 +44,12 @@ export const EXPLORE_PLANTS = gql` preferences: $preferences limit: $limit offset: $offset + after: $after + before: $before ) { totalCount + startCursor + endCursor plants { ...PlantFields } @@ -63,10 +69,15 @@ export type FilterCounts = Record< "watering" | "sunlight" | "careLevel", OptionCount[] >; -export type ExplorePlantsData = { - explorePlants: { - totalCount: number; - plants: Plant[]; - filterCounts: FilterCounts; - }; +// One page of plants, as Explore Plants and My Matches get it. The cursors +// point at the first and last plant on the page, and are sent as before and +// after to get the previous and next page (see usePageCursor). They are null +// when the sort order can't be paged with a cursor. +export type PlantPage = { + totalCount: number; + plants: Plant[]; + filterCounts: FilterCounts; + startCursor: string | null; + endCursor: string | null; }; +export type ExplorePlantsData = { explorePlants: PlantPage }; diff --git a/frontend/src/graphql/user/queries.ts b/frontend/src/graphql/user/queries.ts index 0b1d6089..bb147e7a 100644 --- a/frontend/src/graphql/user/queries.ts +++ b/frontend/src/graphql/user/queries.ts @@ -1,8 +1,7 @@ import { gql } from "@apollo/client"; -import type { Plant } from "../../types/Plant"; import type { User } from "../../types/User"; import { FILTER_COUNT_FIELDS, PLANT_FIELDS } from "../fragments/plantFragments"; -import type { FilterCounts } from "../plants/queries"; +import type { PlantPage } from "../plants/queries"; import { USER_FIELDS } from "../fragments/userFragments"; export const GET_USER = gql` @@ -27,6 +26,8 @@ export const MY_MATCHES = gql` $sort: String $limit: Int $offset: Int + $after: String + $before: String ) { myMatches( userId: $userId @@ -37,8 +38,12 @@ export const MY_MATCHES = gql` sort: $sort limit: $limit offset: $offset + after: $after + before: $before ) { totalCount + startCursor + endCursor plants { ...PlantFields } @@ -52,10 +57,4 @@ export const MY_MATCHES = gql` `; export type GetUserData = { getUser: User | null }; -export type MyMatchesData = { - myMatches: { - totalCount: number; - plants: Plant[]; - filterCounts: FilterCounts; - }; -}; +export type MyMatchesData = { myMatches: PlantPage }; diff --git a/frontend/src/hooks/usePageCursor.ts b/frontend/src/hooks/usePageCursor.ts new file mode 100644 index 00000000..80ec451c --- /dev/null +++ b/frontend/src/hooks/usePageCursor.ts @@ -0,0 +1,69 @@ +import { useState } from "react"; + +// The cursors the backend sends with a page of plants: the first and the last +// plant on the page. Null when the sort order can't be paged with a cursor. +export type PageCursors = { + startCursor: string | null; + endCursor: string | null; +}; + +// How one page is fetched: right after or right before a plant +type PageCursor = { after: string } | { before: string }; + +// Numbered pages that are fast to step through. When the user goes to the +// next or previous page, the backend gets the cursor of the last or first +// plant on the page that is shown, and reads the new page straight from an +// index, however deep in the list it is (see findPlantPage in the backend). +// Jumping to another page number, page 1, a reload and the sort orders +// without cursors use the offset as before, so every page can still be +// reached by its number. +// +// queryKey describes everything except the page that decides the result +// (search, filters, sort), so a cursor is only used for the exact list it +// came from. +export function usePageCursor( + queryKey: string, + page: number, + setPage: (page: number) => void, +) { + // The cursor for each page the user has stepped to, by page and query. + // Every page keeps its own cursor, so the page on screen keeps its variables + // until the new page is shown. The URL (with the page number) can update a + // render later than this state, and a page whose variables changed for a + // moment would be fetched again for nothing. + const [cursors, setCursors] = useState>({}); + const keyFor = (target: number) => `${target}:${queryKey}`; + const active = cursors[keyFor(page)]; + + // shown is the page on screen. It must be the result for the current + // variables (not the previous result shown while loading), or undefined, + // since a cursor from another page would lead to the wrong page. + const goToPage = (target: number, shown: PageCursors | undefined) => { + let cursor: PageCursor | null = null; + if (target === page + 1 && shown?.endCursor) { + cursor = { after: shown.endCursor }; + } else if (target === page - 1 && target > 1 && shown?.startCursor) { + cursor = { before: shown.startCursor }; + } + // Page 1 needs no cursor, and a jump has no plant to start from, so any + // cursor saved for the page from an earlier visit is removed + const key = keyFor(target); + setCursors((previous) => { + const next = { ...previous }; + if (cursor) next[key] = cursor; + else delete next[key]; + return next; + }); + setPage(target); + }; + + return { + // Sent with the query. offset is still sent, and the backend ignores it + // when there is a cursor. + cursorVariables: { + after: active && "after" in active ? active.after : null, + before: active && "before" in active ? active.before : null, + }, + goToPage, + }; +} diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 70e49b77..9a80717e 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -11,8 +11,8 @@ export const PLANT_BATCH_SIZE = 8; export const PREFETCH_THRESHOLD = 3; // The deck is saved in sessionStorage, so the user comes back to the same card -// after visiting another page. Only the cards that are left are saved, since -// the images are large base64 strings. +// after visiting another page. Only the cards that are left are saved, so the +// saved deck stays small. export const DECK_STORAGE_KEY = "plantMatch.deck"; // The preferences the deck was sorted by are saved too, so a deck that is out diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index 46d1567b..16d56973 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -100,7 +100,7 @@ "oldest": "Eldste først", "name_asc": "Navn (A-Z)", "name_desc": "Navn (Z-A)", - "preferences": "Best match først", + "preferences": "Beste match først", "compatible-plant": "Din mest kompatible plante akkurat nå er:" }, "matches": { diff --git a/frontend/src/index.css b/frontend/src/index.css index 01d0641b..5c9b0df1 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -105,6 +105,26 @@ textarea { outline-offset: 2px; } +/* Several focus styles draw the focus ring with box-shadow instead of + outline. Box shadows are removed in forced-colors mode (e.g. Windows High + Contrast), so those rules use a transparent outline instead of + "outline: none". It is invisible normally, but forced-colors mode gives it + a visible color, so the focus is still shown there. */ + +/* For users who ask for less motion: no hover movements, transitions or + animations anywhere. Components with larger movements (the card flip and + the swipe) also turn them off themselves. */ +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} + [data-theme="dark"] { --text-dark: #f5f1ec; --text-light: #ffffff; diff --git a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx index d6efcc11..6964650b 100644 --- a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx @@ -18,6 +18,7 @@ import { import MatchButton from "../../components/matchButton/MatchButton"; import { useMatchedPlants } from "../../hooks/useMatchedPlants"; import { useUser } from "../../context/UserContext"; +import { usePageCursor } from "../../hooks/usePageCursor"; import "./ExplorePlantsPage.css"; const SORT_OPTIONS = ["name_asc", "name_desc", "watering_asc", "careLevel_asc"]; @@ -52,6 +53,13 @@ export default function ExplorePlantsPage() { // Matches come from the user in the database, so every page sees the same list const { matchedPlantIds, addMatch, removeMatch } = useMatchedPlants(); + // Next and previous page use a cursor when sorted by name + const { cursorVariables, goToPage } = usePageCursor( + JSON.stringify([debouncedSearch, filters, activeSort]), + page, + setPage, + ); + const { data: currentData, previousData, @@ -65,6 +73,7 @@ export default function ExplorePlantsPage() { preferences: activeSort === PREFERENCES_SORT ? preferences : null, limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE, + ...cursorVariables, }, }); @@ -151,7 +160,10 @@ export default function ExplorePlantsPage() { + goToPage(target, currentData?.explorePlants) + } /> )} diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index a5974b4a..615e7494 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -15,6 +15,7 @@ import { import { useMatchedPlants } from "../../hooks/useMatchedPlants"; import { useMyMatchesParams } from "../../hooks/useMyMatchesParams"; import { useDebounce } from "../../hooks/useDebounce"; +import { usePageCursor } from "../../hooks/usePageCursor"; import { useUser } from "../../context/UserContext"; import { MY_MATCHES, type MyMatchesData } from "../../graphql/user/queries"; import { PAGE_SIZE } from "../../graphql/plants/queries"; @@ -48,6 +49,13 @@ export default function MyMatchesPage() { const activeSort = sort === PREFERENCES_SORT && !hasPreferences ? "newest" : sort; + // Next and previous page use a cursor when sorted by name, like on Explore + const { cursorVariables, goToPage } = usePageCursor( + JSON.stringify([userId, debouncedSearch, filters, activeSort]), + page, + setPage, + ); + const { data: currentData, previousData, @@ -63,6 +71,7 @@ export default function MyMatchesPage() { sort: activeSort, limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE, + ...cursorVariables, }, skip: !userId, // Fetch again every time the page is opened, since matches can be @@ -88,16 +97,15 @@ export default function MyMatchesPage() { const bestMatch = bestMatchData?.myMatches.plants[0]; // Clicking the best match shows all matches sorted by best match, and // scrolls to the plant and turns its card to the details once that list is - // shown. scrollRequest changes on - // every click, so it also scrolls when the list is already sorted that way - // and nothing else changes. + // shown. scrollRequest changes on every click, so it also scrolls when the + // list is already sorted that way and nothing else changes. const scrollToBestMatch = useRef(false); const bestMatchCardRef = useRef(null); const [scrollRequest, setScrollRequest] = useState(0); const showBestMatch = () => { + // reset and setSort both go back to page 1 reset(); setSort(PREFERENCES_SORT); - setPage(1); scrollToBestMatch.current = true; setScrollRequest((request) => request + 1); }; @@ -124,8 +132,12 @@ export default function MyMatchesPage() { const element = document.getElementById(`plant-${bestMatch.id}`); if (element) { + // Jumps straight there for users who prefer reduced motion + const reduceMotion = + typeof window.matchMedia === "function" && + window.matchMedia("(prefers-reduced-motion: reduce)").matches; element.scrollIntoView({ - behavior: "smooth", + behavior: reduceMotion ? "auto" : "smooth", block: "center", }); @@ -185,9 +197,10 @@ export default function MyMatchesPage() { removed or the search or a filter changes, "no matches" when the last one is removed, and that none fit when the search finds nothing. While loading it says so, so "no matches" does not flash before the - matches are fetched. */} + matches are fetched. An error is always shown here, since the + search, the filters and the list are hidden when the fetch fails. */} - {(loading || (totalCount === 0 && !shownFiltered)) && ( + {(loading || error || (totalCount === 0 && !shownFiltered)) && (

)} - {/* Hidden when user has no preferences set in their profile.*/} {/* Hidden only when the user has no matches at all, so the search and filters stay on screen when they give no results and can be changed */} @@ -294,7 +306,8 @@ export default function MyMatchesPage() { goToPage(target, currentData?.myMatches)} /> )} diff --git a/frontend/src/pages/notFound/NotFoundPage.css b/frontend/src/pages/notFound/NotFoundPage.css index 63848144..aeb7bc88 100644 --- a/frontend/src/pages/notFound/NotFoundPage.css +++ b/frontend/src/pages/notFound/NotFoundPage.css @@ -40,7 +40,7 @@ } .not-found-link:focus-visible { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-pink); } diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index f00ecfd3..4c952ea0 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from "react"; import type { MouseEvent, PointerEvent } from "react"; import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; import HeartIcon from "../../components/heartIcon/HeartIcon"; import PlantCard from "../../components/plantCard/PlantCard"; import { useMatchedPlants } from "../../hooks/useMatchedPlants"; @@ -221,9 +222,9 @@ export default function PlantMatchPage() { <>

{t("plantMatchPage.allMatchedTitle")}

{t("plantMatchPage.allMatched")}

- + {t("plantMatchPage.goToMyMatches")} - + ) : ( <> diff --git a/frontend/src/pages/profile/ProfilePage.css b/frontend/src/pages/profile/ProfilePage.css index 829497b8..077cc127 100644 --- a/frontend/src/pages/profile/ProfilePage.css +++ b/frontend/src/pages/profile/ProfilePage.css @@ -171,7 +171,7 @@ } .edit-profile-form input:focus { - outline: none; + outline: 2px solid transparent; /* Shown in forced-colors mode, see index.css */ box-shadow: 0 0 0 2px var(--dark-green); } diff --git a/frontend/src/pages/profile/ProfilePage.tsx b/frontend/src/pages/profile/ProfilePage.tsx index 2b029bb4..9f1071f1 100644 --- a/frontend/src/pages/profile/ProfilePage.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -143,7 +143,7 @@ export default function ProfilePage() { {t("profile.editProfile")}
- + - + -

{t("profile.avatarChooser")}

+

{t("profile.avatarChooser")}

{AVATAR_IDS.map((id) => (