Skip to content
Merged
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ http://it2810-03.idi.ntnu.no/project2/
- **Plant Match:** 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. 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.
- **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.

## Tech stack

Expand Down Expand Up @@ -61,7 +62,7 @@ cd T03-Project-2
npm run install:all
```

This installs the dependencies for the repo root, `backend` and `frontend`, which each have their own `package.json`.
This installs the dependencies for the repo root, `backend` and `frontend`, which each have their own `package.json`. To install exactly the versions in the lock files instead, as GitHub Actions does, run `npm ci && npm ci --prefix backend && npm ci --prefix frontend`. `npm ci` only installs the dependencies and does not run any tests (see [Testing](#testing)).

### 2. Create the backend `.env` file (in the VS Code terminal)

Expand Down Expand Up @@ -127,6 +128,8 @@ npm run test:backend
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
Expand Down
28 changes: 16 additions & 12 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Perenual API → seedDataFetch.js ─┐
│ GraphQL over HTTP (/graphql)
│
Frontend: React + Apollo Client
(localStorage: userId, theme, language,
(localStorage: userId, theme, language, walkthroughSeen,
URL: Explore state,
sessionStorage: My Matches sort, Plant Match deck)
```
Expand Down Expand Up @@ -53,7 +53,11 @@ The frontend is built with React and TypeScript (Vite).
- **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`). `useSessionState` stores state in `sessionStorage`, for example the sort order on My Matches.
- `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 components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `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 (✖), and `ErrorMessage` shows a short error message. The components take already translated texts, so they can be used on other pages.
- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `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 (✖), `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.
- **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 order. 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.<id>`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page.
- **`App.tsx` decides when it is open:** The walkthrough opens by itself when `walkthroughSeen` is not in `localStorage`, and the key is set when it is closed, so it is only shown once. The ? button in the `Header` opens it again at the step for the current page (`stepForPath`). When it closes, focus goes back to the ? button, except when the "Go to" link has moved the user to another page, where focus moves to the start of the new page like for any other navigation.
- **`Walkthrough.tsx` shows one step at a time:** It uses the native `<dialog>` 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.
- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next).
- **Shared types:** `Plant`, `User` and `Preference` are defined in `types/`.

Expand Down Expand Up @@ -211,22 +215,22 @@ MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be r

## 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`) and the language (`language`) | Lets the browser find its user again on the next visit without a login, and keeps the chosen theme and language between visits |
| 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 sort order on My Matches (`myMatches.sort`) 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 |
| 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 sort order on My Matches (`myMatches.sort`) 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 |

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.

## 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` and the chosen theme and language, and `sessionStorage` holds the 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.
- **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 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.
Expand Down Expand Up @@ -298,7 +302,7 @@ T03-Project-2/
├── frontend/
│ ├── src/
│ │ ├── assets/ # Static images
│ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file
│ │ ├── 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, useSessionState, useProfile, useMatchedPlants, usePlantDeck, useDismissibleTooltip)
Expand Down
Loading
Loading