diff --git a/README.md b/README.md
index 6a273e90..80e51dfe 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,7 @@ http://it2810-03.idi.ntnu.no/project2/
- **Plant Match:** Shows plants one at a time, best matches for your preferences first. Click ✿ to like a plant or ✖ to skip it.
- **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, and Plant Match shows the plants that match the most of your preferences first. Without preferences, the plants come in random order.
- **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants. You can also remove plants from the list.
-- **Explore Plants:** Search the plant collection by common or scientific name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the results are split into pages. The search, filters, sorting, and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. You can also add plants to My Matches from here.
+- **Explore Plants:** Search the plant collection by common or scientific name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the number of results is shown above the plants. The results are split into pages, and you can jump straight to any page. The search, filters, sorting and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. Add a plant to My Matches with the ✿ button, and click it again to remove it.
- **Plant details:** Each plant card shows an image, the scientific name, a description and care information (watering, sunlight and care level). Flip the card to read more about the plant.
- **Profile:** Your name, description, avatar and preferences are saved in the database, and your matched plants are shown here.
- **Plant Owner Test:** A short quiz that tells you what kind of plant owner you are. Each result has its own picture, which you can only get through the test, and you can save it as your profile picture.
diff --git a/backend/src/helpers.ts b/backend/src/helpers.ts
index 77c4733d..ee7cfc0e 100644
--- a/backend/src/helpers.ts
+++ b/backend/src/helpers.ts
@@ -29,7 +29,8 @@ export const rankOf = (order: string[], value: unknown): Document => ({
export const buildSortStages = (sort?: string): Document[] => {
switch (sort) {
case "name_desc":
- return [{ $sort: { commonName: -1, _id: 1 } }];
+ // _id is also reversed, so the sort can read the commonName index backwards
+ return [{ $sort: { commonName: -1, _id: -1 } }];
case "watering_asc":
return [
{
diff --git a/backend/src/indexes.ts b/backend/src/indexes.ts
new file mode 100644
index 00000000..a1a8076a
--- /dev/null
+++ b/backend/src/indexes.ts
@@ -0,0 +1,10 @@
+import type { Db } from "mongodb";
+
+// The indexes the app needs. createIndex does nothing if the index already
+// exists, so this is safe to run every time the server starts.
+export async function ensureIndexes(database: Db) {
+ // Sorting by name (A–Z, the default, and Z–A) reads the plants in order from
+ // this index instead of sorting the whole collection in memory. _id is part
+ // of the sort as a tie-breaker, so it is part of the index too.
+ await database.collection("plants").createIndex({ commonName: 1, _id: 1 });
+}
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 491f31c9..7992389d 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -2,6 +2,11 @@ import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { resolvers } from "./resolvers.js";
import { typeDefs } from "./schema.js";
+import { db } from "./db.js";
+import { ensureIndexes } from "./indexes.js";
+
+// Create the database indexes before the server starts taking requests
+await ensureIndexes(db);
const server = new ApolloServer({ typeDefs, resolvers });
diff --git a/backend/tests/indexes.test.ts b/backend/tests/indexes.test.ts
new file mode 100644
index 00000000..61ff0fce
--- /dev/null
+++ b/backend/tests/indexes.test.ts
@@ -0,0 +1,23 @@
+import { MongoClient } from "mongodb";
+import { afterAll, expect, inject, it } from "vitest";
+import { ensureIndexes } from "../src/indexes.js";
+
+// Uses the in-memory MongoDB from globalSetup.ts, with its own database for this file
+const client = await MongoClient.connect(inject("mongoUri"));
+const db = client.db("indexes-test");
+
+afterAll(async () => {
+ await client.close();
+});
+
+it("creates the index for sorting by name, and can run again on the next start", async () => {
+ await ensureIndexes(db);
+ // The server runs this on every start, so running it twice must not fail
+ await ensureIndexes(db);
+
+ const indexes = await db.collection("plants").indexes();
+ expect(indexes.map((index) => index.key)).toContainEqual({
+ commonName: 1,
+ _id: 1,
+ });
+});
diff --git a/backend/tests/tsconfig.json b/backend/tests/tsconfig.json
new file mode 100644
index 00000000..20c8bb75
--- /dev/null
+++ b/backend/tests/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "..",
+ "noEmit": true
+ },
+ "include": ["../src", "."]
+}
diff --git a/backend/tsconfig.json b/backend/tsconfig.json
index 03da5be9..dda18cce 100644
--- a/backend/tsconfig.json
+++ b/backend/tsconfig.json
@@ -11,5 +11,5 @@
"resolveJsonModule": true,
"sourceMap": true
},
- "include": ["src", "test", "globalSetup.ts"]
+ "include": ["src"]
}
diff --git a/docs/ai-usage.md b/docs/ai-usage.md
index a33d74c4..87fe8f34 100644
--- a/docs/ai-usage.md
+++ b/docs/ai-usage.md
@@ -5,11 +5,12 @@ AI was used as an assistant throughout the development of the web application. T
## What AI was used for
- **Setup and configuration:** setting up the project in VS Code, Vitest, and the project structure with backend and database.
-- **Explaining technical concepts:** how the database, backend and frontend are related, and how to implement debounce.
+- **Explaining technical concepts:** how the database, backend and frontend are related, how to implement debounce, the difference between offset- and cursor-based pagination, and when a database index helps.
- **Writing code:** suggestions for code, which were reviewed by the team before they were used.
- **Writing and reviewing tests:** drafting test files with mocked dependencies, and explaining the reasoning behind the test structure and snapshot testing. AI also suggested what should be tested to get better test coverage.
- **Writing documentation:** drafting and refining documentation and comments in the code.
- **Generating pictures:** the avatar pictures on the profile page were made with AI.
+- **Refactoring:** splitting large files containing a lot of logic into smaller components and hooks.
## Examples
@@ -31,6 +32,10 @@ The avatar pictures that the user can choose between on the profile page were ge
AI drafted many of the Vitest tests and the Playwright e2e and API tests, and suggested atypical cases to test, such as special characters in the search, too long names and invalid ids. The team reviewed the tests, adjusted them, and ran them to check that they pass and fail for the right reasons. The accessibility tests found a real problem with the language button (see [tests.md](tests.md)), which we then fixed.
+### 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.
+
## 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. Design and architectural decisions were made by the team.
diff --git a/docs/architecture.md b/docs/architecture.md
index 28befe65..2772d244 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -48,7 +48,8 @@ The frontend is built with React and TypeScript (Vite).
| `*` | `NotFound` | 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` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. All user queries and mutations live in `context/userQueries.ts`.
-- **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), `useSearchParams` keeps Explore search, filters, sorting and page in the URL, and `useSessionState` stores state in `sessionStorage` for features that still use it.
+- **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 Explore search, filters, sorting and page in the URL (with React Router's `useSearchParams`) and sends the user back to page 1 when the search, a filter or the sort order changes, and `useSessionState` stores state in `sessionStorage` for features that still use it.
+- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, and always shows the first and last page with "…" in between, so it works for any number of pages (`getPageItems`). `FilterSelect` is a labelled dropdown for one filter. `SortMenu` is a sort button that shows the selected option and opens a menu that can be used with the keyboard. All three take already translated texts, so they can be used on other pages.
- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next).
- **Shared types:** `Plant` and `Preference` are defined in `types/`.
@@ -56,7 +57,7 @@ The frontend is built with React and TypeScript (Vite).
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)).
-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.
+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. Adding and removing a match always returns the whole list of matches, so the cache replaces `matchedPlants` instead of merging it with the old list.
## Backend: GraphQL with Apollo Server
@@ -67,6 +68,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f
- `schema.ts` defines the GraphQL schema (`typeDefs`).
- `resolvers.ts` has the resolvers for plants and users, and validates user input.
- `helpers.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants.
+- `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#scalability)).
- `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments.
- `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below).
@@ -106,7 +108,7 @@ The database `iloveplants` has two collections: `plants` and `users`. Both the p
### The `plants` collection
-One document per plant species. The documents were written by `seedDataFetch.js` with data fetched from the Perenual API. The running app only reads them. There is a unique index on `perenualId`.
+One document per plant species. The documents were written by `seedDataFetch.js` with data fetched from the Perenual API. The running app only reads them. There is a unique index on `perenualId`, used by the seed script, and an index on `commonName` and `_id` for sorting by name (see [Scalability](#scalability)).
| Field | Type | Source / description | Exposed in GraphQL as |
| -------------------- | -------------- | ------------------------------------------------------------------------------------ | --------------------- |
@@ -173,14 +175,14 @@ 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` | Only the key `userId` | Lets the browser find its user again on the next visit, without a login |
-| URL parameters | Explore page search, filters, sort and page (`search`, `watering`, `sunlight`, `carelevel`, `sort`, `page`) | The view survives navigation and refresh and can be shared as a link |
-| `sessionStorage` | Features that still use `useSessionState`, such as the language switcher | The value is kept for the kurrent browser session |
-| 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` | Only the key `userId` | Lets the browser find its user again on the next visit, without a login |
+| URL parameters | Explore page 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` | Features that still use `useSessionState`, such as the language switcher | The value is kept for the kurrent browser session |
+| 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.
@@ -191,6 +193,12 @@ When the app starts, `UserProvider` reads `userId` from `localStorage` and runs
- **Use of MongoDB over local storage.** Local storage is only used for the `userId`, while the rest of the user information is stored in MongoDB. This makes it easy to add more user information later. Local 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, 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.
+ - **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.
- **Small responses.** GraphQL returns only the requested fields, and fields we do not use are kept out of the schema.
- **Small user documents.** Matches are stored as plant ids, and user updates only touch one document.
- **Less traffic from the client.** Search input is debounced, results are cached by Apollo, and pages other than the start page are lazy-loaded.
@@ -222,11 +230,12 @@ T03-Project-2/
│ ├── src/
│ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env)
│ │ ├── helpers.ts # Filters and sort stages for searching, filtering and sorting plants
+│ │ ├── indexes.ts # Database indexes, created when the server starts
│ │ ├── resolvers.ts # GraphQL resolvers for plants and users
│ │ ├── schema.ts # GraphQL schema
│ │ ├── server.ts # Starts Apollo Server
│ │ └── types.ts # TypeScript types for documents, GraphQL types and arguments
-│ ├── tests/ # Backend tests against an in-memory MongoDB (db, server)
+│ ├── tests/ # Backend tests against an in-memory MongoDB (db, server, indexes), with their own tsconfig.json
│ ├── seedDataFetch.js # Script that fetches plant data from the Perenual API and stores it in MongoDB
│ └── .env.example # Template for required environment variables
├── docs/ # Project documentation (architecture, tests, quality, AI usage), media/ has the coverage images
@@ -236,7 +245,7 @@ T03-Project-2/
│ │ ├── assets/ # Static images
│ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file
│ │ ├── context/ # UserProvider and the GraphQL queries and mutations for the user
-│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useSessionState, useProfile, useMatchedPlants, usePlantDeck)
+│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useExploreParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck)
│ │ ├── i18n/ # Translation setup and locale files (no, en)
│ │ ├── pages/ # One folder per page/route with a matching .css file
│ │ ├── tests/ # Unit and component tests, including test setup (see tests.md)
diff --git a/docs/quality.md b/docs/quality.md
index 5aa170c1..df075da1 100644
--- a/docs/quality.md
+++ b/docs/quality.md
@@ -41,11 +41,11 @@ The app includes the following accessibility features:
- **Page structure:** Semantic `header`, `nav`, `main` and `article` elements organise the content. Sidebar navigation has an accessible name, and the current page is marked with `aria-current="page"`.
-- **Keyboard controls:** Navigation uses links, and actions use native buttons. Sidebar links, pagination, sorting controls and avatar options have explicit focus styles. Plant Match instructions are also shown when their control receives focus.
+- **Keyboard controls:** Navigation uses links, and actions use native buttons. Sidebar links, pagination, sorting controls and avatar options have explicit focus styles. Plant Match instructions are also shown when their control receives focus. The sort menu can be used with the arrow keys, Home, End and Tab, focus moves into the menu when it opens, and back to the sort button when it is closed with Escape or an option is chosen.
- **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 exposes its expanded state, and sort and avatar choices expose their selected state with ARIA attributes. Pagination announces page changes through an `aria-live="polite"` region.
+- **Control states:** The sort menu exposes its expanded state, and sort and avatar choices expose their selected state with ARIA attributes. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants, the number of results is also announced when the search or filters change. The ✿ button's accessible name and tooltip say whether a click adds the plant to My Matches or removes it.
- **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.
@@ -76,7 +76,7 @@ and our approach to data handling.
- **Data fetching and storage:** Plant data is fetched from the Perenual API once and stored in our own MongoDB database. The application retrieves data through our GraphQL backend rather than repeatedly requesting data from the external API. This reduces unnecessary external requests and avoids repeatedly transferring the same data from Perenual.
-- **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset.
+- **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset. Sorting by name uses a database index, so the server does not have to sort the whole collection for every request.
- **Debouncing:** On the Explore Plants page, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost.
@@ -86,7 +86,7 @@ and our approach to data handling.
- **Colour palette and contrast:** We used a limited colour palette to maintain a consistent visual identity across the application. We also checked the contrast between our chosen colours to help ensure that text and other interface elements remain distinguishable.
-- **Reusable components:** We used reusable React components to maintain a consistent interface and avoid duplicating code. For example, the Header and Sidebar are shared across pages, while components such as plant cards are used to present plant information consistently. This makes the application easier to maintain and allows changes to be made in one place.
+- **Reusable components:** We used reusable React components to maintain a consistent interface and avoid duplicating code. For example, the Header and Sidebar are shared across pages, while components such as plant cards are used to present plant information consistently. The page navigation (`Pagination`), the filter dropdowns (`FilterSelect`) and the sort menu (`SortMenu`) are separate components that can be reused on other pages, and the filters on Explore Plants are defined in one list, so a new filter only needs one new line. This makes the application easier to maintain and allows changes to be made in one place.
- **Responsive design:** We designed the application for both desktop and mobile screens. The layout adapts to different screen sizes to ensure that the content and navigation remain usable across devices.
diff --git a/docs/tests.md b/docs/tests.md
index c324871e..f0aa11c6 100644
--- a/docs/tests.md
+++ b/docs/tests.md
@@ -114,10 +114,18 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p
- `ExplorePage.test.tsx`
- Loading, error and empty results: a loading message, an error message when the query fails, and a message without page navigation when nothing matches.
- Search, filters and sorting: the search text is only sent after the debounce delay, the chosen filters and sort order are sent in the query, the selected sort is visible and included in the sort button's accessible name, and the sort menu closes with Escape and with a click outside.
+ - 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, and it is hidden while loading and when nothing matches.
- 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 while staying clickable.
- 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 and labelled controls.
- Snapshots of the page with results, with no results and with the sort menu open.
+- `FilterSelect.test.tsx`
+ - A labelled dropdown with "All" as the first option, showing the selected value and reporting a new choice, including going back to "All".
+- `SortMenu.test.tsx`
+ - The selected option in the button's accessible name, opening the menu with focus on the selected option, moving between the options with the arrow keys, Home, End, Tab and Shift+Tab, choosing an option, and closing with Escape or a click outside, with focus going back to the button.
+- `getPageItems.test.ts`
+ - Which page numbers are shown: every page when there are few, the first pages near the start, the last pages near the end, the current page and its neighbours in the middle, "…" never hiding just one page, and never more than seven items however many pages there are.
- `Header.test.tsx`
- Shows the right title for each page, including the "Page not found" title for unknown paths, and opens the sidebar with the menu button.
- `LanguageSettings.test.tsx`
@@ -154,6 +162,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p
- No user without a provider, loading the user saved in the browser, creating and saving a new user on the first visit, creating a new user when the saved one no longer exists, keeping the saved user when the backend is down, working on when creating a user fails, and removing old user data left in the browser.
- `useDebounce.test.ts`
- The initial value is returned at once, updates only come after the delay, the delay restarts on quick changes, and the default delay is 300 ms.
+- `useExploreParams.test.tsx`
+ - Default values when the URL has no parameters, reading search, filters, sorting and page from the URL, page 1 for an invalid page number, going back to page 1 when the search, a filter or the sort order changes, keeping the other parameters when the page changes, removing a parameter that is set to an empty value, and clearing all Explore parameters on reset.
- `useSessionState.test.ts`
- Default and initial values, reading and saving in `sessionStorage`, keeping the value when the hook is mounted again, and working on when reading or saving fails.
@@ -170,6 +180,8 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in
- Plants: `getPlants` returns the plants that match the most of the user's preferences first, also when they are fetched in batches ("Low" counts as easy care), random plants when there are no preferences or only unknown ones, and leaves out the plants in `excludeIds` (returning none when all are excluded). Also stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search across common and scientific names with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, and all sort orders.
- Users: creating and fetching users, updating the profile (trimming text, storing empty text and `null` as `null`, and only changing the sent fields), the plant owner test results as profile pictures, preferences without duplicates, adding and removing matches in order, and skipping matched plants that were deleted.
- Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name or description, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and the server passes on a database error and keeps running.
+- `indexes.test.ts`
+ - The index for sorting by name is created, and creating it again on the next start does not fail.
### End-to-end and API tests
@@ -218,7 +230,7 @@ Each file covers one scenario, and API and UI tests for the same feature come in
**Matching plants (`uiMatchAndRemovePlant`):**
- Liking a plant on PlantMatch adds it to MyMatches, where it can be removed.
-- Adding a plant from ExplorePlants adds it to MyMatches and disables its ✿ button.
+- Adding a plant from ExplorePlants adds it to MyMatches and marks its ✿ button as matched. Clicking the button again on ExplorePlants removes the plant from MyMatches.
The test user has no preferences, so PlantMatch shows the plants in random order. The test therefore remembers the name of the liked plant and checks that it is the same plant that ends up in MyMatches.
@@ -274,6 +286,6 @@ Automatic testing only finds some accessibility problems, and the tests only che
The group has tested the application manually in Chrome on Mac and on a mobile phone throughout development, using all pages and features on both. This testing led to adjustments such as improvements to the mobile layout.
-**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, and the sort menu closes with Escape.
+**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, and in the sort menu, focus moves into the menu when it opens and back to the sort button when it closes.
**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).
diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts
index 7147b5bf..78165e65 100644
--- a/e2e/uiAccessibility.spec.ts
+++ b/e2e/uiAccessibility.spec.ts
@@ -101,7 +101,7 @@ test.describe("after interaction", () => {
.first()
.locator(".add-match-button");
await addButton.click();
- await expect(addButton).toBeDisabled();
+ await expect(addButton).toHaveClass(/add-match-button--matched/);
await page.goto("#/my-matches");
await expect(page.locator(".plant-card-match")).toHaveCount(1);
diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts
index 5b7854f4..b70d6435 100644
--- a/e2e/uiMatchAndRemovePlant.spec.ts
+++ b/e2e/uiMatchAndRemovePlant.spec.ts
@@ -2,7 +2,8 @@ import { test, expect } from "@playwright/test";
import { openSidebar } from "./helpers/navigation";
// User journeys for matching plants: from PlantMatch and from ExplorePlants,
-// and that matches show up in MyMatches and can be removed there.
+// and that matches show up in MyMatches and can be removed from both MyMatches
+// and ExplorePlants.
// Each test gets a new browser and therefore a new user with no matches.
test("user can like a plant in PlantMatch, find it in MyMatches and remove the match", async ({
@@ -35,7 +36,7 @@ test("user can like a plant in PlantMatch, find it in MyMatches and remove the m
);
});
-test("user can add a plant from ExplorePlants and find it in MyMatches", async ({
+test("user can add a plant from ExplorePlants, find it in MyMatches and remove it again from ExplorePlants", async ({
page,
}) => {
await page.goto("#/explorePlants");
@@ -44,17 +45,29 @@ test("user can add a plant from ExplorePlants and find it in MyMatches", async (
const firstCard = page.locator(".plant-grid > li").first();
await expect(firstCard).toContainText("Aloe Vera");
- const addButton = firstCard.locator(".add-match-button");
- await expect(addButton).toBeEnabled();
- await addButton.click();
+ const matchButton = firstCard.locator(".add-match-button");
+ const matchCards = page.locator(".plant-card-match");
+ await expect(matchButton).not.toHaveClass(/add-match-button--matched/);
+ await matchButton.click();
- // The button is disabled once the plant is in MyMatches
- await expect(addButton).toBeDisabled();
+ // The button shows that the plant is in MyMatches, and can still be clicked
+ await expect(matchButton).toHaveClass(/add-match-button--matched/);
+ await expect(matchButton).toBeEnabled();
await openSidebar(page);
await page.locator('a[href$="/my-matches"]').click();
-
- const matchCards = page.locator(".plant-card-match");
await expect(matchCards).toHaveCount(1);
await expect(matchCards.first()).toContainText("Aloe Vera");
+
+ // Clicking the button again on ExplorePlants removes the match
+ await openSidebar(page);
+ await page.locator('a[href$="/explorePlants"]').click();
+ await expect(firstCard).toContainText("Aloe Vera");
+ await expect(matchButton).toHaveClass(/add-match-button--matched/);
+ await matchButton.click();
+ await expect(matchButton).not.toHaveClass(/add-match-button--matched/);
+
+ await openSidebar(page);
+ await page.locator('a[href$="/my-matches"]').click();
+ await expect(matchCards).toHaveCount(0);
});
diff --git a/frontend/src/components/filterSelect/FilterSelect.css b/frontend/src/components/filterSelect/FilterSelect.css
new file mode 100644
index 00000000..53919975
--- /dev/null
+++ b/frontend/src/components/filterSelect/FilterSelect.css
@@ -0,0 +1,22 @@
+.filter {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ font-size: 1rem;
+}
+
+.filter select {
+ padding: 0.5rem;
+ border: 1px solid var(--dark-pink);
+ border-radius: 8px;
+ min-width: 160px;
+ font-size: 15px;
+ background-color: var(--light-background);
+ color: var(--text-dark);
+}
+
+.filter select:focus {
+ outline: none;
+ border-color: var(--dark-pink);
+ box-shadow: 0 0 0 2px var(--dark-pink);
+}
diff --git a/frontend/src/components/filterSelect/FilterSelect.tsx b/frontend/src/components/filterSelect/FilterSelect.tsx
new file mode 100644
index 00000000..2f7dee90
--- /dev/null
+++ b/frontend/src/components/filterSelect/FilterSelect.tsx
@@ -0,0 +1,35 @@
+import "./FilterSelect.css";
+
+type FilterOption = { value: string; label: string };
+
+type FilterSelectProps = {
+ label: string;
+ value: string;
+ allLabel: string;
+ options: FilterOption[];
+ onChange: (value: string) => void;
+};
+
+// A labelled dropdown for one filter, with an "All" option that clears it.
+// The texts come in already translated, so the component can be used for any filter.
+export default function FilterSelect({
+ label,
+ value,
+ allLabel,
+ options,
+ onChange,
+}: FilterSelectProps) {
+ return (
+
+ );
+}
diff --git a/frontend/src/components/header/Header.css b/frontend/src/components/header/Header.css
index 4109c1f2..fd88d289 100644
--- a/frontend/src/components/header/Header.css
+++ b/frontend/src/components/header/Header.css
@@ -19,7 +19,6 @@
.header h1 {
margin: 0;
font-size: 45px;
- font-family: Georgia, serif;
font-weight: 400;
letter-spacing: -0.3px;
}
diff --git a/frontend/src/components/pagination/Pagination.css b/frontend/src/components/pagination/Pagination.css
new file mode 100644
index 00000000..f324bb5f
--- /dev/null
+++ b/frontend/src/components/pagination/Pagination.css
@@ -0,0 +1,57 @@
+.pagination {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ gap: 0.5rem;
+ margin: 1.5rem 0;
+}
+
+.pagination-pages {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.25rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.pagination button {
+ min-width: 2.5rem;
+ padding: 0.5rem 0.75rem;
+ border: 1px solid var(--dark-green);
+ border-radius: 8px;
+ background-color: var(--light-green);
+ color: var(--text-dark);
+ font-family: var(--font-ui);
+ font-size: 1rem;
+ cursor: pointer;
+}
+
+.pagination button:hover:not(:disabled) {
+ background-color: var(--dark-green);
+ color: var(--text-on-green);
+}
+
+.pagination button:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px var(--dark-green);
+}
+
+.pagination button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+/* The current page is filled, so it stands out from the other numbers */
+.pagination-page[aria-current="page"] {
+ background-color: var(--dark-green);
+ color: var(--text-on-green);
+ font-weight: 700;
+}
+
+.pagination-ellipsis {
+ padding: 0 0.25rem;
+ color: var(--text-dark);
+}
diff --git a/frontend/src/components/pagination/Pagination.tsx b/frontend/src/components/pagination/Pagination.tsx
new file mode 100644
index 00000000..b8e8a8a4
--- /dev/null
+++ b/frontend/src/components/pagination/Pagination.tsx
@@ -0,0 +1,73 @@
+import { useTranslation } from "react-i18next";
+import { getPageItems } from "./getPageItems";
+import "./Pagination.css";
+
+type PaginationProps = {
+ page: number;
+ totalPages: number;
+ onPageChange: (page: number) => void;
+};
+
+// Page navigation with previous/next and numbered pages, so the user can jump
+// straight to any page. Works for any number of pages (see getPageItems), and
+// can be used on any page with paged results.
+export default function Pagination({
+ page,
+ totalPages,
+ onPageChange,
+}: PaginationProps) {
+ const { t } = useTranslation();
+
+ const goTo = (target: number) => {
+ if (target !== page) onPageChange(target);
+ };
+
+ return (
+
+ );
+}
diff --git a/frontend/src/components/pagination/getPageItems.ts b/frontend/src/components/pagination/getPageItems.ts
new file mode 100644
index 00000000..395de1ef
--- /dev/null
+++ b/frontend/src/components/pagination/getPageItems.ts
@@ -0,0 +1,42 @@
+// One item in the page list: a page number or an ellipsis ("…")
+export type PageItem = number | "ellipsis-start" | "ellipsis-end";
+
+const range = (from: number, to: number) =>
+ Array.from({ length: to - from + 1 }, (_, i) => from + i);
+
+// Returns the page numbers to show: always the first and last page, the current
+// page and `siblings` pages on each side, with "…" for the pages in between.
+// The list never gets longer than 2 * siblings + 5 items, however many pages there are.
+export function getPageItems(
+ page: number,
+ totalPages: number,
+ siblings = 1,
+): PageItem[] {
+ // First, last, current, the siblings and two ellipses
+ const maxItems = 2 * siblings + 5;
+ if (totalPages <= maxItems) return range(1, totalPages);
+
+ // How many numbers are shown in a row when the current page is near the start or end
+ const edgeCount = 2 * siblings + 3;
+
+ // Near the start: 1 2 3 4 5 … 10
+ if (page <= siblings + 3) {
+ return [...range(1, edgeCount), "ellipsis-end", totalPages];
+ }
+ // Near the end: 1 … 6 7 8 9 10
+ if (page >= totalPages - siblings - 2) {
+ return [
+ 1,
+ "ellipsis-start",
+ ...range(totalPages - edgeCount + 1, totalPages),
+ ];
+ }
+ // In the middle: 1 … 4 5 6 … 10
+ return [
+ 1,
+ "ellipsis-start",
+ ...range(page - siblings, page + siblings),
+ "ellipsis-end",
+ totalPages,
+ ];
+}
diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css
index 6308c0c8..9878818a 100644
--- a/frontend/src/components/plantCard/PlantCard.css
+++ b/frontend/src/components/plantCard/PlantCard.css
@@ -93,7 +93,7 @@
overflow: hidden;
- font-family: Palatino, "Palatino Linotype", "Book Antiqua", Georgia, serif;
+ font-family: var(--font-card);
}
.plant-card-face > .plant-card {
diff --git a/frontend/src/components/sidebarButtons/SideBarButton.css b/frontend/src/components/sidebarButtons/SideBarButton.css
index 839cf076..1bdccba9 100644
--- a/frontend/src/components/sidebarButtons/SideBarButton.css
+++ b/frontend/src/components/sidebarButtons/SideBarButton.css
@@ -10,7 +10,7 @@
}
.language-button {
- font-family: Arial, sans-serif;
+ font-family: var(--font-ui);
font-size: 19px;
font-weight: 600;
}
diff --git a/frontend/src/components/sortMenu/SortMenu.css b/frontend/src/components/sortMenu/SortMenu.css
new file mode 100644
index 00000000..4513cddd
--- /dev/null
+++ b/frontend/src/components/sortMenu/SortMenu.css
@@ -0,0 +1,85 @@
+.sort-menu {
+ position: relative;
+ align-self: flex-end;
+}
+
+.sort-button {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ height: 40px;
+ padding: 0 0.75rem;
+ border: 1px solid var(--dark-pink);
+ border-radius: 8px;
+ background-color: var(--light-pink);
+ color: var(--text-dark);
+ font-family: var(--font-ui);
+ font-size: 15px;
+ white-space: nowrap;
+ cursor: pointer;
+}
+
+.sort-button-icon {
+ font-size: 1.5rem;
+ flex-shrink: 0;
+}
+
+/* All labels share one grid cell, so the button always fits the longest one */
+.sort-button-label {
+ display: grid;
+ text-align: left;
+}
+
+.sort-button-label > span {
+ grid-area: 1 / 1;
+}
+
+.sort-button-label--hidden {
+ visibility: hidden;
+}
+
+.sort-button:hover {
+ background-color: var(--dark-pink);
+ color: var(--text-light);
+}
+
+.sort-button:focus-visible,
+.sort-option:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px var(--dark-pink);
+}
+
+.sort-options {
+ position: absolute;
+ top: calc(100% + 6px);
+ left: 0;
+ z-index: 10;
+ min-width: 100%;
+ margin: 0;
+ padding: 0.25rem;
+ list-style: none;
+ background-color: var(--light-background);
+ border: 1px solid var(--dark-pink);
+ border-radius: 8px;
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
+}
+
+.sort-option {
+ width: 100%;
+ padding: 0.5rem 0.75rem;
+ border: none;
+ border-radius: 6px;
+ background: none;
+ color: var(--text-dark);
+ text-align: left;
+ cursor: pointer;
+}
+
+.sort-option:hover {
+ background-color: var(--light-pink);
+}
+
+.sort-option--active {
+ background-color: var(--light-pink);
+ font-weight: 700;
+}
diff --git a/frontend/src/components/sortMenu/SortMenu.tsx b/frontend/src/components/sortMenu/SortMenu.tsx
new file mode 100644
index 00000000..7f6fe2ca
--- /dev/null
+++ b/frontend/src/components/sortMenu/SortMenu.tsx
@@ -0,0 +1,164 @@
+import {
+ useEffect,
+ useRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+} from "react";
+import { BiSortAlt2 } from "react-icons/bi";
+import "./SortMenu.css";
+
+type SortOption = { value: string; label: string };
+
+type SortMenuProps = {
+ label: string;
+ value: string;
+ options: SortOption[];
+ onChange: (value: string) => void;
+};
+
+// A sort button that opens a menu of sort options. The button shows the selected
+// option, and the menu can be used with the keyboard. The texts come in already
+// translated, so the component can be used on any page.
+export default function SortMenu({
+ label,
+ value,
+ options,
+ onChange,
+}: SortMenuProps) {
+ const [open, setOpen] = useState(false);
+ const menuRef = useRef(null);
+ const buttonRef = useRef(null);
+ const listRef = useRef(null);
+
+ const currentLabel = options.find((option) => option.value === value)?.label;
+
+ // Closes the menu and returns focus to the button, so keyboard users don't lose their place
+ const close = () => {
+ setOpen(false);
+ buttonRef.current?.focus();
+ };
+
+ // While the menu is open: focus the active option, and close on Escape or a click outside
+ useEffect(() => {
+ if (!open) return;
+ listRef.current
+ ?.querySelector(".sort-option--active")
+ ?.focus();
+
+ const handleClick = (e: MouseEvent) => {
+ if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
+ setOpen(false);
+ }
+ };
+ const handleKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") {
+ setOpen(false);
+ buttonRef.current?.focus();
+ }
+ };
+
+ document.addEventListener("mousedown", handleClick);
+ document.addEventListener("keydown", handleKey);
+ return () => {
+ document.removeEventListener("mousedown", handleClick);
+ document.removeEventListener("keydown", handleKey);
+ };
+ }, [open]);
+
+ // Keyboard navigation inside the open menu: arrows, Home/End,
+ // and Tab cycles through the options instead of leaving the menu
+ const handleListKeyDown = (e: ReactKeyboardEvent) => {
+ const buttons = Array.from(
+ listRef.current?.querySelectorAll(".sort-option") ??
+ [],
+ );
+ if (buttons.length === 0) return;
+
+ const current = buttons.indexOf(
+ document.activeElement as HTMLButtonElement,
+ );
+ const last = buttons.length - 1;
+ let next: number;
+
+ switch (e.key) {
+ case "ArrowDown":
+ next = current >= last ? 0 : current + 1;
+ break;
+ case "ArrowUp":
+ next = current <= 0 ? last : current - 1;
+ break;
+ case "Home":
+ next = 0;
+ break;
+ case "End":
+ next = last;
+ break;
+ case "Tab":
+ if (e.shiftKey) {
+ next = current <= 0 ? last : current - 1;
+ } else {
+ next = current >= last ? 0 : current + 1;
+ }
+ break;
+ default:
+ return; // Let Enter, Escape etc. behave as before
+ }
+
+ e.preventDefault();
+ buttons[next].focus();
+ };
+
+ return (
+
+
+
+ {open && (
+
+ {options.map((option) => (
+
+
+
+ ))}
+
+ )}
+
+ );
+}
diff --git a/frontend/src/hooks/useExploreParams.ts b/frontend/src/hooks/useExploreParams.ts
new file mode 100644
index 00000000..c2347bfc
--- /dev/null
+++ b/frontend/src/hooks/useExploreParams.ts
@@ -0,0 +1,66 @@
+import { useSearchParams } from "react-router-dom";
+
+// The filters on Explore Plants, as they are named in the URL
+export type FilterParam = "watering" | "sunlight" | "careLevel";
+
+const DEFAULT_SORT = "name_asc";
+
+// Keeps the Explore Plants state (search, filters, sorting and page) in the URL,
+// so it survives refresh and can be shared as a link. The page only gets the
+// values and functions to change them, and does not need to know about the URL.
+export function useExploreParams() {
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ const get = (key: string) => searchParams.get(key) ?? "";
+
+ // A missing or invalid page number (e.g. "abc" or "0") means page 1
+ const parsedPage = Number.parseInt(get("page"), 10);
+ const page = Number.isInteger(parsedPage) && parsedPage > 0 ? parsedPage : 1;
+
+ // Sets the given parameters, and removes the ones that are empty or null.
+ // replace: true, so changing a filter does not add a new step to the browser history.
+ const update = (updates: Record) => {
+ setSearchParams(
+ (currentParams) => {
+ const nextParams = new URLSearchParams(currentParams);
+ Object.entries(updates).forEach(([key, value]) => {
+ if (value) {
+ nextParams.set(key, value);
+ } else {
+ nextParams.delete(key);
+ }
+ });
+ return nextParams;
+ },
+ { replace: true },
+ );
+ };
+
+ return {
+ search: get("search"),
+ filters: {
+ watering: get("watering"),
+ sunlight: get("sunlight"),
+ careLevel: get("careLevel"),
+ },
+ sort: get("sort") || DEFAULT_SORT,
+ page,
+
+ // A new search, filter or sort order goes back to page 1,
+ // so the user never ends up on a page that no longer exists
+ setSearch: (value: string) => update({ search: value, page: null }),
+ setFilter: (param: FilterParam, value: string) =>
+ update({ [param]: value, page: null }),
+ setSort: (value: string) => update({ sort: value, page: null }),
+ setPage: (value: number) => update({ page: String(value) }),
+ reset: () =>
+ update({
+ search: null,
+ watering: null,
+ sunlight: null,
+ careLevel: null,
+ sort: null,
+ page: null,
+ }),
+ };
+}
diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json
index 288b0935..1b27ba93 100644
--- a/frontend/src/i18n/locales/en/translation.json
+++ b/frontend/src/i18n/locales/en/translation.json
@@ -53,6 +53,8 @@
"careLevel_asc": "Care (easy-hard)",
"reset": "Reset",
"noResults": "No results found",
+ "resultsCount_one": "{{count}} result found",
+ "resultsCount_other": "{{count}} results found",
"watering": "Watering needs",
"all": "All",
"minimum": "Low",
@@ -66,12 +68,15 @@
"low": "Easy",
"medium": "Medium",
"high": "High",
- "pagination": "Page navigation",
- "pageOf": "Page {{page}} of {{totalPages}}",
+ "addMatch": "Add to My Matches",
+ "removeMatch": "Remove from My Matches"
+ },
+ "pagination": {
+ "label": "Page navigation",
"previous": "Previous",
"next": "Next",
- "addMatch": "Add to My Matches",
- "alreadyMatched": "Already in My Matches"
+ "pageOf": "Page {{page}} of {{totalPages}}",
+ "goToPage": "Go to page {{page}}"
},
"myMatchesPage": {
"loading": "Loading your matches...",
diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json
index f7c8da11..6696bc25 100644
--- a/frontend/src/i18n/locales/no/translation.json
+++ b/frontend/src/i18n/locales/no/translation.json
@@ -53,6 +53,8 @@
"careLevel_asc": "Stell (lett-krevende)",
"reset": "Nullstill",
"noResults": "Ingen resultater funnet",
+ "resultsCount_one": "{{count}} treff funnet",
+ "resultsCount_other": "{{count}} treff funnet",
"watering": "Vanningsbehov",
"all": "Alle",
"minimum": "Sjeldent",
@@ -66,12 +68,15 @@
"low": "Lettstelt",
"medium": "Middels",
"high": "Høy",
- "pagination": "Sidenavigasjon",
- "pageOf": "Side {{page}} av {{totalPages}}",
+ "addMatch": "Legg til i Mine Matches",
+ "removeMatch": "Fjern fra Mine Matches"
+ },
+ "pagination": {
+ "label": "Sidenavigasjon",
"previous": "Forrige",
"next": "Neste",
- "addMatch": "Legg til i Mine Matches",
- "alreadyMatched": "Allerede i Mine Matches"
+ "pageOf": "Side {{page}} av {{totalPages}}",
+ "goToPage": "Gå til side {{page}}"
},
"myMatchesPage": {
"loading": "Laster matchene dine...",
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 68312d8c..c2e2e16b 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -10,11 +10,27 @@ body,
body {
min-height: 100vh;
background: var(--bg);
+ font-family: var(--font-text);
color: var(--text-dark);
}
+/* Form controls don't inherit the font from the page, so they get --font-ui here */
+button,
+input,
+select,
+textarea {
+ font-family: var(--font-ui);
+}
+
:root {
--sidebar-width: 16rem;
+ /* Fonts: serif for all pages, and a separate font for the plant cards */
+ --font-text: Georgia, serif;
+ --font-card: Palatino, "Palatino Linotype", "Book Antiqua", Georgia, serif;
+ /* --font-ui: system-ui, sans-serif; */
+ --font-ui: var(--font-text);
+ /* --font-ui: Arial, sans-serif; */
+ /* Colors: */
--text-dark: #44403c;
--text-light: #ffffff;
--light-background: #ffffff;
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 73994d24..6708c527 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -10,7 +10,17 @@ import { UserProvider } from "./context/UserContext.tsx";
const client = new ApolloClient({
link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL ?? "/graphql" }),
- cache: new InMemoryCache(),
+ cache: new InMemoryCache({
+ typePolicies: {
+ User: {
+ fields: {
+ // The backend always returns the whole list of matches, so the new
+ // list should replace the old one in the cache, not be merged with it
+ matchedPlants: { merge: false },
+ },
+ },
+ },
+ }),
});
createRoot(document.getElementById("root")!).render(
diff --git a/frontend/src/pages/explorePlants/ExplorePlants.css b/frontend/src/pages/explorePlants/ExplorePlants.css
index 3be91b98..0891d75f 100644
--- a/frontend/src/pages/explorePlants/ExplorePlants.css
+++ b/frontend/src/pages/explorePlants/ExplorePlants.css
@@ -9,8 +9,6 @@
flex-direction: column;
align-items: center;
gap: 30px;
-
- font-family: Georgia, serif;
}
.visually-hidden {
@@ -72,29 +70,6 @@
border: 0;
}
-.filter {
- display: flex;
- flex-direction: column;
- gap: 0.25rem;
- font-size: 1rem;
-}
-
-.filter select {
- padding: 0.5rem;
- border: 1px solid var(--dark-pink);
- border-radius: 8px;
- min-width: 160px;
- font-size: 15px;
- background-color: var(--light-pink);
- color: var(--text-dark);
-}
-
-.filter select:focus {
- outline: none;
- border-color: var(--dark-pink);
- box-shadow: 0 0 0 2px var(--dark-pink);
-}
-
.reset-button {
align-self: flex-start;
width: 74px;
@@ -129,7 +104,13 @@
.explore-results > p {
font-size: 20px;
text-align: center;
- font-family: Georgia, serif;
+}
+
+.explore-results .results-count {
+ margin: 0 0 1rem;
+ font-size: 1.25rem;
+ text-align: left;
+ color: var(--text-dark);
}
.plant-grid {
@@ -149,126 +130,6 @@
position: relative;
}
-.pagination {
- display: flex;
- flex-wrap: wrap;
- justify-content: center;
- align-items: center;
- gap: 1rem;
- margin: 1.5rem 0;
-}
-
-.pagination button {
- padding: 0.5rem 1rem;
- border: 1px solid var(--dark-green);
- border-radius: 8px;
- background-color: var(--light-green);
- color: var(--text-dark);
- font: inherit;
- cursor: pointer;
-}
-
-.pagination button:hover:not(:disabled) {
- background-color: var(--dark-green);
- color: var(--text-on-green);
-}
-
-.pagination button:focus-visible {
- outline: none;
- box-shadow: 0 0 0 2px var(--dark-green);
-}
-
-.pagination button:disabled {
- opacity: 0.5;
- cursor: not-allowed;
-}
-
-.sort-menu {
- position: relative;
- align-self: flex-end;
-}
-
-.sort-button {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- height: 40px;
- padding: 0 0.75rem;
- border: 1px solid var(--dark-pink);
- border-radius: 8px;
- background-color: var(--light-pink);
- color: var(--text-dark);
- font: inherit;
- font-size: 15px;
- white-space: nowrap;
- cursor: pointer;
-}
-
-.sort-button-icon {
- font-size: 1.5rem;
- flex-shrink: 0;
-}
-
-/* All labels share one grid cell, so the button always fits the longest one */
-.sort-button-label {
- display: grid;
- text-align: left;
-}
-
-.sort-button-label > span {
- grid-area: 1 / 1;
-}
-
-.sort-button-label--hidden {
- visibility: hidden;
-}
-
-.sort-button:hover {
- background-color: var(--dark-pink);
- color: var(--text-light);
-}
-
-.sort-button:focus-visible,
-.sort-option:focus-visible {
- outline: none;
- box-shadow: 0 0 0 2px var(--dark-pink);
-}
-
-.sort-options {
- position: absolute;
- top: calc(100% + 6px);
- left: 0;
- z-index: 10;
- min-width: 100%;
- margin: 0;
- padding: 0.25rem;
- list-style: none;
- background-color: var(--light-background);
- border: 1px solid var(--dark-pink);
- border-radius: 8px;
- box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
-}
-
-.sort-option {
- width: 100%;
- padding: 0.5rem 0.75rem;
- border: none;
- border-radius: 6px;
- background: none;
- color: var(--text-dark);
- text-align: left;
- cursor: pointer;
-}
-
-.sort-option:hover {
- background-color: var(--light-pink);
-}
-
-.sort-option--active {
- background-color: var(--light-pink);
- font-weight: 700;
-}
-
.add-match {
position: absolute;
top: -15px;
@@ -302,13 +163,14 @@
visibility: visible;
}
+/* Not matched: a filled dark pink button with a white flower */
.add-match-button {
width: 50px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
- border: none;
+ border: 2px solid var(--dark-pink);
border-radius: 50%;
background-color: var(--dark-pink);
color: var(--text-light);
@@ -318,14 +180,19 @@
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
-.add-match-button:not(:disabled):hover {
+/* Matched: white with a dark pink border and flower */
+.add-match-button--matched {
+ background-color: var(--light-background);
+ color: var(--dark-pink);
+}
+
+.add-match-button:hover {
transform: scale(1.1);
}
-.add-match-button:disabled {
- opacity: 0.5;
- cursor: default;
- pointer-events: none;
+.add-match-button:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 3px var(--dark-pink);
}
@media (max-width: 767px) {
diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx
index b5e2aa0f..eb6b1a4d 100644
--- a/frontend/src/pages/explorePlants/ExplorePlants.tsx
+++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx
@@ -1,20 +1,16 @@
-import {
- useEffect,
- useRef,
- useState,
- type KeyboardEvent as ReactKeyboardEvent,
-} from "react";
-import { BiSortAlt2 } from "react-icons/bi";
import { FaSearch } from "react-icons/fa";
import { useTranslation } from "react-i18next";
import { useQuery } from "@apollo/client/react";
-import { useSearchParams } from "react-router-dom";
import { useDebounce } from "../../hooks/useDebounce";
+import { useExploreParams } from "../../hooks/useExploreParams.ts";
import {
EXPLORE_PLANTS,
type ExplorePlantsData,
} from "./explorePlantsQuery.ts";
import PlantCard from "../../components/plantCard/PlantCard.tsx";
+import Pagination from "../../components/pagination/Pagination.tsx";
+import FilterSelect from "../../components/filterSelect/FilterSelect.tsx";
+import SortMenu from "../../components/sortMenu/SortMenu.tsx";
import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts";
import "./ExplorePlants.css";
@@ -22,126 +18,53 @@ const PAGE_SIZE = 12;
const SORT_OPTIONS = ["name_asc", "name_desc", "watering_asc", "careLevel_asc"];
+// The filters on the page: the URL parameter, the translation key for the label,
+// and the values to choose from. A new filter only needs a new line here.
+const FILTERS = [
+ {
+ param: "watering",
+ label: "ExplorePlants.watering",
+ options: ["minimum", "average", "frequent"],
+ },
+ {
+ param: "sunlight",
+ label: "ExplorePlants.sunlight",
+ options: ["full_sun", "part_shade", "filtered_shade"],
+ },
+ {
+ param: "careLevel",
+ label: "ExplorePlants.careLevel",
+ options: ["low", "medium", "high"],
+ },
+] as const;
+
export default function ExplorePlants() {
const { t } = useTranslation();
- const [searchParams, setSearchParams] = useSearchParams();
-
- // Matches come from the user in the database, so every page sees the same list
- const { matches, addMatch } = useMatchedPlants();
- const search = searchParams.get("search") ?? "";
+ // Search, filters, sorting and page are kept in the URL
+ const {
+ search,
+ filters,
+ sort,
+ page,
+ setSearch,
+ setFilter,
+ setSort,
+ setPage,
+ reset,
+ } = useExploreParams();
const debouncedSearch = useDebounce(search, 300);
- const watering = searchParams.get("watering") ?? "";
- const sunlight = searchParams.get("sunlight") ?? "";
- const careLevel = searchParams.get("careLevel") ?? "";
- const sort = searchParams.get("sort") ?? "";
- const parsedPage = Number.parseInt(searchParams.get("page") ?? "", 10);
- const page = Number.isInteger(parsedPage) && parsedPage > 0 ? parsedPage : 1;
- const [sortOpen, setSortOpen] = useState(false);
- const sortRef = useRef(null);
- const sortButtonRef = useRef(null);
- const sortListRef = useRef(null);
- const currentSort = sort || "name_asc";
-
- const updateExploreParams = (updates: Record) => {
- setSearchParams(
- (currentParams) => {
- const nextParams = new URLSearchParams(currentParams);
-
- Object.entries(updates).forEach(([key, value]) => {
- if (value) {
- nextParams.set(key, value);
- } else {
- nextParams.delete(key);
- }
- });
-
- return nextParams;
- },
- { replace: true },
- );
- };
-
- // Close the sort menu on outside click or Escape
- useEffect(() => {
- if (!sortOpen) return;
- // Move focus into the menu when it opens (to the active option)
- sortListRef.current
- ?.querySelector(".sort-option--active")
- ?.focus();
-
- const handleClick = (e: MouseEvent) => {
- if (sortRef.current && !sortRef.current.contains(e.target as Node)) {
- setSortOpen(false);
- }
- };
- const handleKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") {
- setSortOpen(false);
- // Return focus to the sort button so keyboard users don't lose their place
- sortButtonRef.current?.focus();
- }
- };
-
- document.addEventListener("mousedown", handleClick);
- document.addEventListener("keydown", handleKey);
- return () => {
- document.removeEventListener("mousedown", handleClick);
- document.removeEventListener("keydown", handleKey);
- };
- }, [sortOpen]);
-
- // Keyboard navigation inside the open sort menu: arrows, Home/End,
- // and Tab cycles through the options instead of leaving the menu
- const handleSortListKeyDown = (e: ReactKeyboardEvent) => {
- const options = Array.from(
- sortListRef.current?.querySelectorAll(
- ".sort-option",
- ) ?? [],
- );
- if (options.length === 0) return;
-
- const current = options.indexOf(
- document.activeElement as HTMLButtonElement,
- );
- const last = options.length - 1;
- let next: number;
-
- switch (e.key) {
- case "ArrowDown":
- next = current >= last ? 0 : current + 1;
- break;
- case "ArrowUp":
- next = current <= 0 ? last : current - 1;
- break;
- case "Home":
- next = 0;
- break;
- case "End":
- next = last;
- break;
- case "Tab":
- if (e.shiftKey) {
- next = current <= 0 ? last : current - 1;
- } else {
- next = current >= last ? 0 : current + 1;
- }
- break;
- default:
- return; // Let Enter, Escape etc. behave as before
- }
- e.preventDefault();
- options[next].focus();
- };
+ // Matches come from the user in the database, so every page sees the same list
+ const { matches, addMatch, removeMatch } = useMatchedPlants();
const { data, loading, error } = useQuery(EXPLORE_PLANTS, {
variables: {
search: debouncedSearch || null,
- watering: watering || null,
- sunlight: sunlight || null,
- careLevel: careLevel || null,
- sort: currentSort,
+ watering: filters.watering || null,
+ sunlight: filters.sunlight || null,
+ careLevel: filters.careLevel || null,
+ sort,
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
},
@@ -167,9 +90,7 @@ export default function ExplorePlants() {
type="search"
placeholder={t("ExplorePlants.search")}
value={search}
- onChange={(e) => {
- updateExploreParams({ search: e.target.value, page: null });
- }}
+ onChange={(e) => setSearch(e.target.value)}
/>
@@ -178,135 +99,33 @@ export default function ExplorePlants() {
{t("ExplorePlants.filters")}
-
-
-
-
-
-
-