From f5e3f488217288a93e9c87272f11c97eb4725214 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 13:20:07 +0100 Subject: [PATCH 01/15] updated readMe and minor fixes --- README.md | 26 +++++++++------- backend/seedDataFetch.js | 4 +-- docs/ai-usage.md | 4 ++- docs/architecture.md | 31 ++++++++++--------- docs/quality.md | 4 +-- docs/tests.md | 30 ++++++++++++------ e2e/helpers/graphql.ts | 2 +- e2e/uiAccessibility.spec.ts | 2 +- frontend/src/i18n/locales/no/translation.json | 2 +- 9 files changed, 61 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 0a6432c7..4eb39512 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 plantwoner test and get sugestions for prefernaces. Your preferances will be highligted 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. Or alternativly if you know what plant you want to read about you can search it directly in the explore 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 @@ -24,11 +23,16 @@ http://it2810-03.idi.ntnu.no/project2/ ## 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 it is compatible with. A badge on My Matches in the sidebar shows how many plants have been matched since the page was last opened when matches happens on Plant Match to make it easier to understand where the matches end up. + +- **My Matches:** Gives the user an easy way to find ♥ plants from both Plant Match and Explore Plant, and lets the user search, filters and match count. + +- **Explore Plants:** The page where the user can find spesific plants they are searching for without having matched with them. +Search, filtering and sorting is possivle. 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 preference each for watering, light and care level, based on the answers and the description of the type. It also gives an avtar that can only be achived trough 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 get started. ## Tech stack @@ -42,7 +46,7 @@ http://it2810-03.idi.ntnu.no/project2/ ## 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. +See [architecture.md](docs/architecture.md) for how the frontend, backend and database fit together, and how the code is organised, as well as architecture choices. ## Run the project locally @@ -53,8 +57,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 +73,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) diff --git a/backend/seedDataFetch.js b/backend/seedDataFetch.js index 4d0fd565..f352321b 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 diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 3bb3b356..38453945 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -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. This would have helped make sure all of them followed the same rules, 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..64013535 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -52,8 +52,8 @@ The frontend is built with React and TypeScript (Vite). - **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. +- **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. `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 shown 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` 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: @@ -64,7 +64,7 @@ The frontend is built with React and TypeScript (Vite). `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. + - **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 set `hasMobileHint`, which adds a sentence (`walkthrough.steps..mobileHint` in the translation files) 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. @@ -116,6 +116,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f - `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)). +- `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) below). @@ -123,12 +124,12 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f **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. | +| 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_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): 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. | **Mutations** @@ -138,7 +139,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f | `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`). | +| `removeUserMatch(userId, plantId)` | Removes a plant from the user's matches (`$pull`). Malformed plant ids are rejected. | **Types** @@ -234,7 +235,7 @@ MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be r 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. +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. ## Design choices made for scalability @@ -290,7 +291,7 @@ T03-Project-2/ │ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env) │ │ ├── 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 +│ │ ├── 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) @@ -301,7 +302,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 @@ -313,7 +314,7 @@ T03-Project-2/ │ │ ├── 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) +│ │ ├── 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 +325,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 diff --git a/docs/quality.md b/docs/quality.md index 9e9f58c0..bcd6ed40 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -61,7 +61,7 @@ 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. @@ -121,7 +121,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`), and on Explore Plants they are 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..ccdd1c34 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -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`. @@ -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. @@ -125,7 +126,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - 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 (✖). + - 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` @@ -160,7 +161,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 +176,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` @@ -274,7 +277,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. @@ -315,15 +320,20 @@ 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. +- **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, 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,7 +368,7 @@ 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 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 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. 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/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": { From e826ea1c8cb098ae32e5770b258637f0c1bfe257 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 13:24:28 +0100 Subject: [PATCH 02/15] more updates to ReadMe --- docs/ai-usage.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 38453945..30f08f6f 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. @@ -58,7 +58,7 @@ After the peer reviews, we used AI to help us split up `ExplorePlants.tsx` (now 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. This would have helped make sure all of them followed the same rules, and we would do this in future projects. +In retrospect, we could have added a shared context file for the AI tools we used, but non of us though of this till the end of the porject. 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 From 459f87061e08635adf3e205eb27f7f554af939d8 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 13:27:23 +0100 Subject: [PATCH 03/15] Fix typos in ai-usage.md Co-Authored-By: Claude Opus 5.5 --- docs/ai-usage.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 30f08f6f..4ecc4ea8 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -58,7 +58,7 @@ After the peer reviews, we used AI to help us split up `ExplorePlants.tsx` (now 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 non of us though of this till the end of the porject. 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. +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 From 41a68eea4030cd4a3c97f4399531fd34ba31fb62 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 13:32:49 +0100 Subject: [PATCH 04/15] Fix typos in README Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4eb39512..bcc260bd 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ 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 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 plantwoner test and get sugestions for prefernaces. Your preferances will be highligted 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. Or alternativly if you know what plant you want to read about you can search it directly in the explore page. +- **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 @@ -23,14 +23,13 @@ http://it2810-03.idi.ntnu.no/project2/ ## 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. This is to make it easier for the user to find plants it is compatible with. A badge on My Matches in the sidebar shows how many plants have been matched since the page was last opened when matches happens on Plant Match to make it easier to understand where the matches end up. +- **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, 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:** Gives the user an easy way to find ♥ plants from both Plant Match and Explore Plant, and lets the user search, filters and match count. +- **My Matches:** Gives the user an easy way to find the ♥ plants from both Plant Match and Explore Plants, and lets the user search, filter and see the number of matches. -- **Explore Plants:** The page where the user can find spesific plants they are searching for without having matched with them. -Search, filtering and sorting is possivle. The state is kept in the URL, so a view survives a refresh and the user can share the page as a link. +- **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 preference each for watering, light and care level, based on the answers and the description of the type. It also gives an avtar that can only be achived trough the test to communicate the type of plant owner the user is. +- **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 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 get started. From 18d3c67523a2b0cf29c79a90bd1b4b8474eb65c3 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Mon, 23 Nov 2026 13:46:38 +0100 Subject: [PATCH 05/15] small fixes in README --- README.md | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index bcc260bd..43482611 100644 --- a/README.md +++ b/README.md @@ -14,24 +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. This is to make it easier for the user to find plants they are compatible with. When plants are matched on Plant Match, 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. +- **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:** Gives the user an easy way to find the ♥ plants from both Plant Match and Explore Plants, and lets the user search, filter and see the number of matches. +- **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 only be achieved through the test, to communicate the type of plant owner the user is. +- **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 get started. +- **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 @@ -43,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, as well as architecture choices. - ## Run the project locally ### Requirements @@ -122,6 +118,8 @@ MongoDB is installed directly on the VM and only listens on `127.0.0.1`, so it c 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 @@ -132,8 +130,6 @@ 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 | @@ -143,10 +139,6 @@ The first time you run the e2e tests, install the browser with `npx playwright i 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. From 91acb7cabeef6668c9b5d7d271d489ea3d8f84a7 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 14:00:23 +0100 Subject: [PATCH 06/15] Updates to architecture ReadMe and what to do if the backend stops --- README.md | 19 +++ docs/architecture.md | 328 +++++++++++++++++++++---------------------- 2 files changed, 177 insertions(+), 170 deletions(-) diff --git a/README.md b/README.md index 43482611..54233a30 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,25 @@ 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. diff --git a/docs/architecture.md b/docs/architecture.md index 64013535..d9ac8170 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 @@ -35,125 +34,39 @@ The plant data was fetched from the Perenual API once with the script `seedDataF 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 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. `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 shown 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` 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 set `hasMobileHint`, which adds a sentence (`walkthrough.steps..mobileHint` in the translation files) 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. - -## Backend: GraphQL with Apollo Server +## Data source: the Perenual API -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 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. -- `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)). -- `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) below). +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: -### Schema +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. -**Queries** +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. -| 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_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): 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`). Malformed plant ids are rejected. | +## 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 @@ -210,76 +123,176 @@ 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. 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. +- `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** -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. +| 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_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): 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. | + +**Mutations** + +| 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`. `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 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). + +Invalid input from the client gives a GraphQL error with the code `BAD_USER_INPUT` instead of crashing the server. -## Design choices made for scalability +### 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. +- **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, since MongoDB still has to read past every skipped plant, but that only matters for collections far larger than ours. + + If the catalogue grew dramatically (for example to hundreds of thousands of plants), this would have to change: + - **Cursor-based pagination:** Instead of `offset`, the frontend would send the last plant it got (for example its `commonName` and `_id`), and the backend would ask for the plants after it. This reads straight from the index, so every page is as fast as the first. The cost is that the user can no longer jump to page 57, only go to the next or previous page (or scroll), so the page numbers in `Pagination` would be replaced. + - **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). 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. On a very large collection they would be estimated, or calculated in advance and cached, instead. + - **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. `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 shown 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`. During development, requests to `/graphql` 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/ +├── 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 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 + +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. + +### 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 @@ -341,28 +354,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. From c99659eabd8d6bb08c7a52df00881a914b1a9ad5 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 14:07:11 +0100 Subject: [PATCH 07/15] minor updates to test.md --- docs/tests.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/tests.md b/docs/tests.md index ccdd1c34..78abf782 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 @@ -368,7 +368,7 @@ 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 Chrome DevTools ("Inspect") in 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. From 8dab17e4cdaeb699c16dcc4946b2865f0581512d Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Mon, 23 Nov 2026 14:12:37 +0100 Subject: [PATCH 08/15] small adjustment in quality.md --- docs/quality.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/quality.md b/docs/quality.md index bcd6ed40..cb625c7f 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 From ef722ca4789f9e985c171623465c15e75f71bed3 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 14:42:51 +0100 Subject: [PATCH 09/15] Updated documentation after rebase --- docs/architecture.md | 15 ++++++++++----- docs/tests.md | 2 +- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index d9ac8170..ad76603c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -31,6 +31,7 @@ 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. @@ -81,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` | @@ -133,7 +134,7 @@ The ids are MongoDB ObjectIds, which are unique but not secret, random tokens. I ## Backend: GraphQL with Apollo Server -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 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. - `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. @@ -235,7 +236,7 @@ The frontend is built with React and TypeScript (Vite). ### 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)). +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)). ### GraphQL operations in the frontend @@ -243,6 +244,7 @@ All GraphQL queries, mutations and fragments in the frontend are collected in `f ```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 │ └── userFragments.ts # UserFields: the user fields every user operation returns @@ -301,13 +303,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 +│ │ ├── 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 @@ -326,7 +331,7 @@ 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/) +│ │ ├── 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 diff --git a/docs/tests.md b/docs/tests.md index 78abf782..5e232211 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -320,7 +320,7 @@ 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, 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. +- **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 From c35ec28ecf75a6ec0ea5694ca74f40e87a00380d Mon Sep 17 00:00:00 2001 From: Mia Gamlem Date: Mon, 23 Nov 2026 20:14:18 +0100 Subject: [PATCH 10/15] added updated lighthouse test --- docs/tests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tests.md b/docs/tests.md index 5e232211..1b864b88 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -378,6 +378,6 @@ The group has tested the application manually in Chrome and Safari on Mac and on ## 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. From 0fc3cf0da694d1bf85d1537814427fc0059e258d Mon Sep 17 00:00:00 2001 From: Mia Gamlem Date: Mon, 23 Nov 2026 20:34:22 +0100 Subject: [PATCH 11/15] added aria test doc --- docs/tests.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/tests.md b/docs/tests.md index 1b864b88..b917b0c0 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -370,11 +370,13 @@ Automatic testing only finds some accessibility problems, and the tests only che 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 From b384f3714fe081ed400a5a6cae10d0694f500f0d Mon Sep 17 00:00:00 2001 From: Alexandra Date: Tue, 24 Nov 2026 11:35:39 +0100 Subject: [PATCH 12/15] small code tidy ups and updated the test to reflect this --- .gitignore | 3 + backend/seedDataFetch.js | 8 ++- backend/src/resolvers/plants.ts | 14 +--- backend/src/schema.ts | 4 +- .../src/components/plantCard/PlantCard.tsx | 3 - frontend/src/hooks/usePlantDeck.ts | 4 +- .../src/pages/myMatches/MyMatchesPage.tsx | 13 ++-- .../src/pages/plantMatch/PlantMatchPage.tsx | 5 +- frontend/src/pages/profile/ProfilePage.tsx | 9 +-- frontend/src/tests/MyMatchesPage.test.tsx | 17 +++++ frontend/src/tests/PlantCard.test.tsx | 3 - frontend/src/tests/PlantMatchPage.test.tsx | 65 ++++++++++--------- 12 files changed, 77 insertions(+), 71 deletions(-) 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/backend/seedDataFetch.js b/backend/seedDataFetch.js index f352321b..a0674479 100644 --- a/backend/seedDataFetch.js +++ b/backend/seedDataFetch.js @@ -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/resolvers/plants.ts b/backend/src/resolvers/plants.ts index b6f27467..58b7891c 100644 --- a/backend/src/resolvers/plants.ts +++ b/backend/src/resolvers/plants.ts @@ -126,19 +126,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); diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 458580c9..3a9ccb7f 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,5 +1,5 @@ -// 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; 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/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/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index a5974b4a..b29b9312 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -88,16 +88,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); }; @@ -185,9 +184,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 */} 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.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) => (