diff --git a/README.md b/README.md index a62a00f7..7d248fa5 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ http://it2810-03.idi.ntnu.no/project2/ - **Plant Match:** Shows random plants one at a time. 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, but the preferences do not change which plants are shown. - **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 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. 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 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. - **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. @@ -93,9 +93,9 @@ Browser ──> Apache (port 80, /project2) serves the built frontend The backend runs with pm2, which keeps it running in the background and restarts it if it crashes or the VM reboots. The backend reads `MONGODB_URI=mongodb://localhost:27017`, `DB_NAME=iloveplants` and `PORT=3001` from `backend/.env` on the VM (see `.env.example`). If the backend stops, see [How to start the backend if it stops](../T03-Project-2/docs/architecture.md) . - ### Frontend -The frontend runs on the VM by using Apache serves. It was copied to the folder Apache serves for `/project2`. The build reads `VITE_GRAPHQL_URL` from [frontend/.env.production](frontend/.env.production), so the deployed app sends its requests to the backend on port 3001 on the VM. + +The frontend runs on the VM by using Apache serves. It was copied to the folder Apache serves for `/project2`. The build reads `VITE_GRAPHQL_URL` from [frontend/.env.production](frontend/.env.production), so the deployed app sends its requests to the backend on port 3001 on the VM. ### Database diff --git a/backend/src/helpers.ts b/backend/src/helpers.ts index 71c41a81..cddb4f09 100644 --- a/backend/src/helpers.ts +++ b/backend/src/helpers.ts @@ -67,10 +67,10 @@ export const buildExploreFilter = ( ): Filter => { const filter: Filter = {}; if (args.search?.trim()) { - filter.commonName = { - $regex: escapeRegex(args.search.trim()), - $options: "i", - }; + const search = { $regex: escapeRegex(args.search.trim()), $options: "i" }; + // Match on the common name or any of the scientific names (a list, + // so a regex matches if any of the values contain the search) + filter.$or = [{ commonName: search }, { scientificName: search }]; } if (args.watering) { filter.watering = new RegExp(`^${normalize(args.watering)}$`, "i"); diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index 8c2b18bf..f29d928b 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -204,6 +204,7 @@ describe("plants", () => { }, { commonName: "Basil", + scientificName: ["Ocimum basilicum"], watering: "Frequent", careLevel: "Moderate", sunlight: ["Full sun", "part shade"], @@ -304,6 +305,12 @@ describe("plants", () => { expect((await explore({ search: ".*" })).totalCount).toBe(0); }); + it("searches by scientific name", async () => { + expect((await explore({ search: "ocimum basilicum" })).names).toEqual([ + "Basil", + ]); + }); + it("filters on watering and care level, with Medium and Moderate as the same", async () => { expect((await explore({ watering: "minimum" })).names).toEqual([ "Aloe", @@ -326,7 +333,9 @@ describe("plants", () => { "Basil", "Daisy", ]); - expect((await explore({ sunlight: "part_sun" })).names).toEqual(["Daisy"]); + expect((await explore({ sunlight: "filtered_shade" })).names).toEqual([ + "Fern (giant)", + ]); }); it("returns one page at a time with the total count", async () => { diff --git a/backend/tsconfig.json b/backend/tsconfig.json index dda18cce..03da5be9 100644 --- a/backend/tsconfig.json +++ b/backend/tsconfig.json @@ -11,5 +11,5 @@ "resolveJsonModule": true, "sourceMap": true }, - "include": ["src"] + "include": ["src", "test", "globalSetup.ts"] } diff --git a/docs/architecture.md b/docs/architecture.md index 4281db03..5bf8baa7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +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` or `sessionStorage`). +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. ## Overview @@ -20,7 +20,7 @@ Perenual API → seedDataFetch.js ─┐ │ GraphQL over HTTP (/graphql) │ Frontend: React + Apollo Client - (localStorage: userId, sessionStorage: explore filters) + (localStorage: userId, URL: Explore state) ``` The plant data is fetched from the Perenual API once and stored in our own database. The data was loaded using the seedDataFetch.js file. About 120 plants where loaded. The number is an estimate as we have not verified each plants response to the fetch operation. The frontend never talks to the database directly. All data goes through the GraphQL API in the backend: @@ -36,7 +36,7 @@ The sections below describe each part in more detail. 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`; `BrowserRouter` uses the same value through `import.meta.env.BASE_URL`. All pages except the start page are lazy-loaded. +- **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. | Route | Page | Purpose | | ----------------- | ---------------- | -------------------------------------------------------------- | @@ -47,7 +47,7 @@ The frontend is built with React and TypeScript (Vite). | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | - **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), and `useSessionState` stores state in `sessionStorage`. +- **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. - **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). - **Shared types:** `Plant` and `Preference` are defined in `types/`. @@ -73,11 +73,11 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f **Queries** -| Query | Description | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `getPlants(limit = 50, offset = 0): [Plant]` | Returns `limit` random plants (MongoDB `$sample`). Used by the match page. `offset` is accepted but has no effect, since the plants are random. | -| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on name (case-insensitive), filter on sunlight, watering and care level, sort and paginate. Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | -| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | +| Query | Description | +| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `getPlants(limit = 50, offset = 0): [Plant]` | Returns `limit` random plants (MongoDB `$sample`). Used by the match page. `offset` is accepted but has no effect, since the plants are random. | +| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate. Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | +| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | **Mutations** @@ -172,13 +172,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 | -| `sessionStorage` | Explore page search, filters and sort (`ExplorePlants.*` keys, via `useSessionState`) | The view is restored when the user navigates away and back, but starts fresh in a new tab or 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`) | 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. diff --git a/docs/tests.md b/docs/tests.md index a967dc07..b9703b7d 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -113,9 +113,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - Shows the right page for each route, and opens and closes the sidebar from the header. - `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, and the sort menu closes with Escape and with a click outside. + - 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. - Pagination: moving between pages, disabled buttons at the ends, and going back to page 1 when a filter or the search text changes. - - Reset and session: reset clears the search and all filters, and the filters are remembered when the page is opened again in the same session. + - 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. - `Header.test.tsx` @@ -167,7 +167,7 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in - Connecting to the database in `MONGODB_URI` and `DB_NAME`, using `iloveplants` when `DB_NAME` is not set, and the error messages when `MONGODB_URI` is missing or empty, is not a MongoDB address, or MongoDB cannot be reached (for example when the SSH tunnel is down). - `server.test.ts` - Starting the server: the default port 3001, the port in `PORT`, and stopping with the error when the port is in use. - - Plants: random plants from `getPlants`, stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search 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. + - Plants: random plants from `getPlants`, 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. diff --git a/e2e/uiExplorePlants.spec.ts b/e2e/uiExplorePlants.spec.ts index 4dc2cee2..a6b40825 100644 --- a/e2e/uiExplorePlants.spec.ts +++ b/e2e/uiExplorePlants.spec.ts @@ -55,7 +55,7 @@ test("user pages, filters, searches, opens a plant, sorts and resets", async ({ await jadeCard.locator(".plant-card-front .plant-card-info-button").click(); await expect(details).toHaveAttribute("aria-hidden", "false"); await expect(details).toContainText("Crassula ovata"); - await expect(details).toContainText("Minimum"); + await expect(details).toContainText("Low"); await expect(details).toContainText( "A succulent with round, glossy leaves.", ); diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 6d468c2e..20328f68 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -55,15 +55,15 @@ "noResults": "No results found", "watering": "Watering needs", "all": "All", - "minimum": "Minimum", + "minimum": "Low", "average": "Average", "frequent": "Frequent", "sunlight": "Sun requirements", "full_sun": "Full sun", - "part_sun": "Part sun", "part_shade": "Part shade", + "filtered_shade": "Filtered shade", "careLevel": "Care level", - "low": "Low", + "low": "Easy", "medium": "Medium", "high": "High", "pagination": "Page navigation", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index ab65d1a8..685717d0 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -60,10 +60,10 @@ "frequent": "Ofte", "sunlight": "Solforhold", "full_sun": "Full sol", - "part_sun": "Delvis sol", "part_shade": "Delvis skygge", + "filtered_shade": "Filtrert skygge", "careLevel": "Stell", - "low": "Lav", + "low": "Lettstelt", "medium": "Middels", "high": "Høy", "pagination": "Sidenavigasjon", diff --git a/frontend/src/pages/explorePlants/ExplorePlants.css b/frontend/src/pages/explorePlants/ExplorePlants.css index 36b86fe7..24cf0046 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.css +++ b/frontend/src/pages/explorePlants/ExplorePlants.css @@ -206,17 +206,38 @@ .sort-button { display: flex; align-items: center; - justify-content: center; - width: 40px; + gap: 0.5rem; height: 40px; + padding: 0 0.75rem; border: 1px solid var(--dark-pink); border-radius: 8px; background-color: var(--light-background); color: var(--text-dark); - font-size: 1.5rem; + 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); @@ -233,7 +254,7 @@ top: calc(100% + 6px); left: 0; z-index: 10; - min-width: 220px; + min-width: 100%; margin: 0; padding: 0.25rem; list-style: none; @@ -250,7 +271,6 @@ border-radius: 6px; background: none; color: var(--text-dark); - font: inherit; text-align: left; cursor: pointer; } diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index 9690cd79..830d76d7 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -1,10 +1,15 @@ -import { useEffect, useRef, useState } from "react"; +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 { useSessionState } from "../../hooks/useSessionState"; import { EXPLORE_PLANTS, type ExplorePlantsData, @@ -19,24 +24,51 @@ const SORT_OPTIONS = ["name_asc", "name_desc", "watering_asc", "careLevel_asc"]; 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, setSearch] = useSessionState("ExplorePlants.search"); + const search = searchParams.get("search") ?? ""; const debouncedSearch = useDebounce(search, 800); - const [watering, setWatering] = useSessionState("ExplorePlants.watering"); - const [sunlight, setSunlight] = useSessionState("ExplorePlants.sunlight"); - const [careLevel, setCareLevel] = useSessionState("ExplorePlants.careLevel"); - const [sort, setSort] = useSessionState("ExplorePlants.sort"); - const [page, setPage] = useState(1); + 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)) { @@ -44,7 +76,11 @@ export default function ExplorePlants() { } }; const handleKey = (e: KeyboardEvent) => { - if (e.key === "Escape") setSortOpen(false); + 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); @@ -55,13 +91,57 @@ export default function ExplorePlants() { }; }, [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(); + }; + const { data, loading, error } = useQuery(EXPLORE_PLANTS, { variables: { search: debouncedSearch || null, watering: watering || null, sunlight: sunlight || null, careLevel: careLevel || null, - sort: sort || "name_asc", + sort: currentSort, limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE, }, @@ -88,8 +168,7 @@ export default function ExplorePlants() { placeholder={t("ExplorePlants.search")} value={search} onChange={(e) => { - setSearch(e.target.value); - setPage(1); + updateExploreParams({ search: e.target.value, page: null }); }} /> @@ -104,8 +183,10 @@ export default function ExplorePlants() { { - setSunlight(e.target.value); - setPage(1); + updateExploreParams({ + sunlight: e.target.value, + page: null, + }); }} > - + @@ -138,8 +223,10 @@ export default function ExplorePlants() { @@ -138,13 +138,13 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with no re @@ -275,14 +302,14 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with resul ExplorePlants.full_sun @@ -319,13 +346,13 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with resul @@ -787,14 +841,14 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s ExplorePlants.full_sun @@ -831,13 +885,13 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s