From 806c07be989e8833c17a3bfef84ef1ef115e88a6 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Wed, 11 Nov 2026 13:44:15 +0100 Subject: [PATCH 1/6] show an error message when adding or removing a match fails --- frontend/src/App.tsx | 5 +- frontend/src/components/toast/Toast.css | 45 ++++++++++++++++ frontend/src/components/toast/Toast.tsx | 16 ++++++ frontend/src/context/ToastContext.tsx | 54 +++++++++++++++++++ frontend/src/hooks/useMatchedPlants.ts | 30 +++++++++-- frontend/src/i18n/locales/en/translation.json | 4 ++ frontend/src/i18n/locales/no/translation.json | 4 ++ 7 files changed, 152 insertions(+), 6 deletions(-) create mode 100644 frontend/src/components/toast/Toast.css create mode 100644 frontend/src/components/toast/Toast.tsx create mode 100644 frontend/src/context/ToastContext.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index b930ab61..f71d9b4c 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -5,6 +5,7 @@ import "./App.css"; import Sidebar from "./components/sidebar/Sidebar"; import Header from "./components/header/Header"; import AppRoutes from "./AppRoutes.tsx"; +import { ToastProvider } from "./context/ToastContext.tsx"; function App() { const { t } = useTranslation(); @@ -34,7 +35,7 @@ function App() { }; return ( - <> + {/* The start of the page. Focus is moved here when the page changes, so the next Tab goes to the skip link */}
@@ -66,7 +67,7 @@ function App() { >
- +
); } diff --git a/frontend/src/components/toast/Toast.css b/frontend/src/components/toast/Toast.css new file mode 100644 index 00000000..e599df80 --- /dev/null +++ b/frontend/src/components/toast/Toast.css @@ -0,0 +1,45 @@ +/* In the top right corner, over the empty part of the header, where the + background is always the plain page colour */ +.toast-region { + position: fixed; + top: 1rem; + right: 1.5rem; + z-index: 1000; + pointer-events: none; +} + +.toast { + margin: 0; + max-width: 90vw; + padding: 0.75rem 1.25rem; + border: 2px solid var(--dark-pink); + border-radius: 8px; + background-color: var(--dark-pink); + color: var(--text-light); + font-family: var(--font-ui); + font-size: 1rem; + animation: toast-in 0.2s ease-out; +} + +@keyframes toast-in { + from { + opacity: 0; + transform: translateY(-0.5rem); + } +} + +@media (prefers-reduced-motion: reduce) { + .toast { + animation: none; + } +} + +/* On mobile the header is narrow, so the toast is centred at the top */ +@media (max-width: 767px) { + .toast-region { + top: 0.5rem; + right: auto; + left: 50%; + transform: translateX(-50%); + } +} diff --git a/frontend/src/components/toast/Toast.tsx b/frontend/src/components/toast/Toast.tsx new file mode 100644 index 00000000..d75df80c --- /dev/null +++ b/frontend/src/components/toast/Toast.tsx @@ -0,0 +1,16 @@ +import "./Toast.css"; + +type ToastProps = { + message: string | null; +}; + +// A short error message at the top of the screen. The region is always there, +// so screen readers notice when a message appears and read it at once, without +// moving focus. +export default function Toast({ message }: ToastProps) { + return ( +
+ {message &&

{message}

} +
+ ); +} diff --git a/frontend/src/context/ToastContext.tsx b/frontend/src/context/ToastContext.tsx new file mode 100644 index 00000000..966bdcc0 --- /dev/null +++ b/frontend/src/context/ToastContext.tsx @@ -0,0 +1,54 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from "react"; +import Toast from "../components/toast/Toast"; + +// How long an error message is shown +const DURATION = 6000; + +type ToastContextValue = { + showToast: (message: string) => void; +}; + +// Without a provider showToast does nothing, so components that use it can +// still be rendered alone, for example in tests +const ToastContext = createContext({ showToast: () => {} }); + +export function ToastProvider({ children }: { children: ReactNode }) { + const [toast, setToast] = useState<{ id: number; message: string } | null>( + null, + ); + const nextId = useRef(0); + + // A new message replaces the one that is shown. The id makes the timer start + // again even when the same message is shown twice in a row. + const showToast = useCallback((message: string) => { + nextId.current += 1; + setToast({ id: nextId.current, message }); + }, []); + + useEffect(() => { + if (!toast) return; + const timer = setTimeout(() => setToast(null), DURATION); + return () => clearTimeout(timer); + }, [toast]); + + const value = useMemo(() => ({ showToast }), [showToast]); + + return ( + + {children} + + + ); +} + +// eslint-disable-next-line react-refresh/only-export-components +export const useToast = () => useContext(ToastContext); diff --git a/frontend/src/hooks/useMatchedPlants.ts b/frontend/src/hooks/useMatchedPlants.ts index 3e650525..e3efecae 100644 --- a/frontend/src/hooks/useMatchedPlants.ts +++ b/frontend/src/hooks/useMatchedPlants.ts @@ -1,5 +1,7 @@ import { useMutation } from "@apollo/client/react"; +import { useTranslation } from "react-i18next"; import { useUser } from "../context/UserContext"; +import { useToast } from "../context/ToastContext"; import { ADD_USER_MATCH, REMOVE_USER_MATCH, @@ -13,7 +15,9 @@ import type { Plant } from "../types/Plant"; const refetchMyMatches = { refetchQueries: ["MyMatches"] }; export function useMatchedPlants() { + const { t } = useTranslation(); const { userId, user, loading } = useUser(); + const { showToast } = useToast(); const [addUserMatch] = useMutation( ADD_USER_MATCH, refetchMyMatches, @@ -26,14 +30,32 @@ export function useMatchedPlants() { // Only the ids, which is all a page needs to show whether a plant is matched const matchedPlantIds = user?.matchedPlantIds ?? []; - const addMatch = (plant: Plant) => { + // If saving fails, the user is told, so a failed save is not mistaken for a + // saved one. The page already shows when it works (the button changes or the + // card disappears). The mutation returns null if the user was not found, + // which also counts as a failure. + const addMatch = async (plant: Plant) => { if (!userId || matchedPlantIds.includes(plant.id)) return; - addUserMatch({ variables: { userId, plantId: plant.id } }); + try { + const result = await addUserMatch({ + variables: { userId, plantId: plant.id }, + }); + if (!result?.data?.addUserMatch) throw new Error("No user returned"); + } catch { + showToast(t("matches.addFailed")); + } }; - const removeMatch = (id: string) => { + const removeMatch = async (id: string) => { if (!userId) return; - removeUserMatch({ variables: { userId, plantId: id } }); + try { + const result = await removeUserMatch({ + variables: { userId, plantId: id }, + }); + if (!result?.data?.removeUserMatch) throw new Error("No user returned"); + } catch { + showToast(t("matches.removeFailed")); + } }; return { matchedPlantIds, loading, addMatch, removeMatch } as const; diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index f3bb92d7..8d862e9d 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -99,6 +99,10 @@ "name_asc": "Name (A-Z)", "name_desc": "Name (Z-A)" }, + "matches": { + "addFailed": "Could not add the plant to My Matches. Please try again.", + "removeFailed": "Could not remove the plant from My Matches. Please try again." + }, "profile": { "name": "Name Surname", "description": "Description", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index 76230f9d..72d11f35 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -99,6 +99,10 @@ "name_asc": "Navn (A-Z)", "name_desc": "Navn (Z-A)" }, + "matches": { + "addFailed": "Kunne ikke legge planten til i Mine Matches. Prøv igjen.", + "removeFailed": "Kunne ikke fjerne planten fra Mine Matches. Prøv igjen." + }, "profile": { "name": "Navn Etternavn", "description": "Beskrivelse", From 278d700327fb0a3807c7e43d3db434e65a0644d7 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Wed, 11 Nov 2026 13:53:12 +0100 Subject: [PATCH 2/6] add tests for error message --- frontend/src/tests/ToastContext.test.tsx | 70 +++++++++ frontend/src/tests/useMatchedPlants.test.tsx | 148 +++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 frontend/src/tests/ToastContext.test.tsx create mode 100644 frontend/src/tests/useMatchedPlants.test.tsx diff --git a/frontend/src/tests/ToastContext.test.tsx b/frontend/src/tests/ToastContext.test.tsx new file mode 100644 index 00000000..dd2440c3 --- /dev/null +++ b/frontend/src/tests/ToastContext.test.tsx @@ -0,0 +1,70 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"; +import { ToastProvider, useToast } from "../context/ToastContext"; + +// A button that shows the given message, so the tests can trigger a toast +function ShowButton({ message }: { message: string }) { + const { showToast } = useToast(); + return ; +} + +function renderWithProvider() { + render( + + + + , + ); +} + +describe("ToastContext", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("shows the message in an alert region, so screen readers read it at once", () => { + renderWithProvider(); + + fireEvent.click(screen.getByText("show First error")); + + expect(screen.getByRole("alert")).toHaveTextContent("First error"); + }); + + it("hides the message after six seconds", () => { + renderWithProvider(); + fireEvent.click(screen.getByText("show First error")); + + act(() => vi.advanceTimersByTime(5999)); + expect(screen.getByRole("alert")).toHaveTextContent("First error"); + + act(() => vi.advanceTimersByTime(1)); + expect(screen.getByRole("alert")).toBeEmptyDOMElement(); + }); + + it("replaces the shown message with a new one, and starts the time again", () => { + renderWithProvider(); + fireEvent.click(screen.getByText("show First error")); + act(() => vi.advanceTimersByTime(4000)); + + fireEvent.click(screen.getByText("show Second error")); + + expect(screen.getByRole("alert")).toHaveTextContent("Second error"); + expect(screen.queryByText("First error")).not.toBeInTheDocument(); + // Still shown 4 seconds later, since the time started again + act(() => vi.advanceTimersByTime(4000)); + expect(screen.getByRole("alert")).toHaveTextContent("Second error"); + }); + + it("does nothing without a provider, instead of crashing", () => { + render(); + + expect(() => + fireEvent.click(screen.getByText("show First error")), + ).not.toThrow(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + }); +}); diff --git a/frontend/src/tests/useMatchedPlants.test.tsx b/frontend/src/tests/useMatchedPlants.test.tsx new file mode 100644 index 00000000..bfb86aa7 --- /dev/null +++ b/frontend/src/tests/useMatchedPlants.test.tsx @@ -0,0 +1,148 @@ +import { act, renderHook, screen } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { beforeEach, describe, it, expect, vi } from "vitest"; +import { useMatchedPlants } from "../hooks/useMatchedPlants"; +import { ToastProvider } from "../context/ToastContext"; +import { ADD_USER_MATCH } from "../graphql/user/mutations"; +import type { Plant } from "../types/Plant"; + +const { addUserMatch, removeUserMatch, useUser } = vi.hoisted(() => ({ + addUserMatch: vi.fn(), + removeUserMatch: vi.fn(), + useUser: vi.fn(), +})); + +// Returns the right mutation function for each mutation +vi.mock("@apollo/client/react", () => ({ + useMutation: (mutation: unknown) => + mutation === ADD_USER_MATCH ? [addUserMatch] : [removeUserMatch], +})); +vi.mock("../context/UserContext", () => ({ useUser })); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ t: (key: string) => key }), +})); + +const orchid = { id: "plant-1", name: "Orchid" } as Plant; + +function mockUser(userId: string | null, matchedPlantIds: string[] = []) { + useUser.mockReturnValue({ + userId, + user: userId ? { id: userId, matchedPlantIds } : null, + loading: false, + }); +} + +// Renders the hook inside a ToastProvider, so the error messages are shown +function renderMatchedPlants() { + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const hook = renderHook(() => useMatchedPlants(), { wrapper }); + return hook.result; +} + +// The toast region is rendered by the provider inside the hook's container +const alert = () => screen.getByRole("alert"); + +beforeEach(() => { + addUserMatch.mockReset(); + removeUserMatch.mockReset(); + mockUser("user-1"); +}); + +describe("useMatchedPlants", () => { + it("returns the ids of the matched plants", () => { + mockUser("user-1", ["plant-1", "plant-2"]); + + const result = renderMatchedPlants(); + + expect(result.current.matchedPlantIds).toEqual(["plant-1", "plant-2"]); + }); + + describe("adding a match", () => { + it("saves the plant and shows no message when it works", async () => { + addUserMatch.mockResolvedValue({ data: { addUserMatch: { id: "user-1" } } }); + const result = renderMatchedPlants(); + + await act(() => result.current.addMatch(orchid)); + + expect(addUserMatch).toHaveBeenCalledWith({ + variables: { userId: "user-1", plantId: "plant-1" }, + }); + expect(alert()).toBeEmptyDOMElement(); + }); + + it("shows an error message when the request fails", async () => { + addUserMatch.mockRejectedValue(new Error("Network error")); + const result = renderMatchedPlants(); + + await act(() => result.current.addMatch(orchid)); + + expect(alert()).toHaveTextContent("matches.addFailed"); + }); + + it("shows an error message when the user was not found", async () => { + addUserMatch.mockResolvedValue({ data: { addUserMatch: null } }); + const result = renderMatchedPlants(); + + await act(() => result.current.addMatch(orchid)); + + expect(alert()).toHaveTextContent("matches.addFailed"); + }); + + it("does nothing when the plant is already matched or there is no user", async () => { + mockUser("user-1", ["plant-1"]); + const matched = renderMatchedPlants(); + await act(() => matched.current.addMatch(orchid)); + + mockUser(null); + const noUser = renderMatchedPlants(); + await act(() => noUser.current.addMatch(orchid)); + + expect(addUserMatch).not.toHaveBeenCalled(); + }); + }); + + describe("removing a match", () => { + it("removes the plant and shows no message when it works", async () => { + removeUserMatch.mockResolvedValue({ + data: { removeUserMatch: { id: "user-1" } }, + }); + const result = renderMatchedPlants(); + + await act(() => result.current.removeMatch("plant-1")); + + expect(removeUserMatch).toHaveBeenCalledWith({ + variables: { userId: "user-1", plantId: "plant-1" }, + }); + expect(alert()).toBeEmptyDOMElement(); + }); + + it("shows an error message when the request fails", async () => { + removeUserMatch.mockRejectedValue(new Error("Network error")); + const result = renderMatchedPlants(); + + await act(() => result.current.removeMatch("plant-1")); + + expect(alert()).toHaveTextContent("matches.removeFailed"); + }); + + it("shows an error message when the user was not found", async () => { + removeUserMatch.mockResolvedValue({ data: { removeUserMatch: null } }); + const result = renderMatchedPlants(); + + await act(() => result.current.removeMatch("plant-1")); + + expect(alert()).toHaveTextContent("matches.removeFailed"); + }); + + it("does nothing when there is no user", async () => { + mockUser(null); + const result = renderMatchedPlants(); + + await act(() => result.current.removeMatch("plant-1")); + + expect(removeUserMatch).not.toHaveBeenCalled(); + }); + }); +}); From d1f687d1c0e51c118bae75a43a26e389a854f7e5 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Wed, 11 Nov 2026 13:56:48 +0100 Subject: [PATCH 3/6] run lint and Prettier and fix what failed --- docs/ai-usage.md | 1 - frontend/src/pages/myMatches/MyMatchesPage.tsx | 13 +++++++------ frontend/src/tests/useMatchedPlants.test.tsx | 4 +++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/ai-usage.md b/docs/ai-usage.md index a7534479..24c146de 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -24,7 +24,6 @@ AI helped us write [backend/seedDataFetch.js](../backend/seedDataFetch.js), whic We decided which fields to keep and how they are mapped to the GraphQL schema, and we checked the data in the database after each run. - ### Tests and end-to-end tests 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. diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index c844c218..3068890e 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useState } from "react"; import { useTranslation } from "react-i18next"; import { useQuery } from "@apollo/client/react"; import MatchButton from "../../components/matchButton/MatchButton.tsx"; @@ -54,11 +54,12 @@ function MyMatchesPage() { // Only show the loading text when there is nothing to show yet const loading = userLoading || (matchesLoading && !data); - // If the last plant on the last page is removed, or the URL points to a page - // that does not exist, go to the last page that has plants - useEffect(() => { - if (totalCount > 0 && page > totalPages) setPage(totalPages); - }, [totalCount, page, totalPages, setPage]); + // If the last plant on the last page is removed, go to the last page that + // has plants. This is done while rendering instead of in an effect, so React + // corrects the page before anything is shown, without an extra render. + if (totalCount > 0 && page > totalPages) { + setPage(totalPages); + } return (
diff --git a/frontend/src/tests/useMatchedPlants.test.tsx b/frontend/src/tests/useMatchedPlants.test.tsx index bfb86aa7..952617f4 100644 --- a/frontend/src/tests/useMatchedPlants.test.tsx +++ b/frontend/src/tests/useMatchedPlants.test.tsx @@ -61,7 +61,9 @@ describe("useMatchedPlants", () => { describe("adding a match", () => { it("saves the plant and shows no message when it works", async () => { - addUserMatch.mockResolvedValue({ data: { addUserMatch: { id: "user-1" } } }); + addUserMatch.mockResolvedValue({ + data: { addUserMatch: { id: "user-1" } }, + }); const result = renderMatchedPlants(); await act(() => result.current.addMatch(orchid)); From 4ad53e180087154110d7fd5375a564ba893e1956 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Wed, 11 Nov 2026 14:21:59 +0100 Subject: [PATCH 4/6] document error messages for matches Describe the Toast and ToastProvider in architecture.md and quality.md, and add the new ToastContext and useMatchedPlants tests to tests.md. Also remove a duplicated section in architecture.md, update the GraphQL folder tree, and remove duplicated test files in tests.md. --- docs/architecture.md | 41 ++++++----------------------------------- docs/quality.md | 4 ++-- docs/tests.md | 12 ++++++------ 3 files changed, 14 insertions(+), 43 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 31cc59d7..257a360c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -49,8 +49,9 @@ 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. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). +- **Error messages:** `ToastProvider` (`context/ToastContext.tsx`) wraps the app and makes `showToast()` available through `useToast()`. `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. -- **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. +- **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 `Toast` shows a short error message. The components 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`, `User` and `Preference` are defined in `types/`. @@ -66,11 +67,11 @@ All GraphQL queries, mutations and fragments in the frontend are collected in `f graphql/ ├── fragments/ │ ├── plantFragments.ts # PlantFields: the plant fields every plant list asks for -│ └── userFragments.ts # UserFields: the user fields every user operation returns (uses PlantFields for matchedPlants) +│ └── userFragments.ts # UserFields: the user fields every user operation returns ├── plants/ │ └── queries.ts # GET_PLANTS (Plant Match deck), EXPLORE_PLANTS (Explore Plants) └── user/ - ├── queries.ts # GET_USER + ├── queries.ts # GET_USER, MY_MATCHES (My Matches) └── mutations.ts # CREATE_USER, ADD_USER_MATCH, REMOVE_USER_MATCH, UPDATE_USER_PROFILE, UPDATE_USER_PREFERENCES ``` @@ -81,37 +82,7 @@ Earlier the operations were spread across three places: the user operations in ` - **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. - **The user operations are shared.** They are used by `UserProvider`, two hooks and a component, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. - **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. -- **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and the user's `matchedPlants`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. -- **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. - -We considered keeping each query next to the component that uses it (colocation), which is common in large apps organised by feature. Our frontend is organised by technical role (`pages/`, `components/`, `hooks/`, `context/`), and most of our operations are used in more than one place, so a shared folder fits better. If the app is later reorganised into feature folders, each domain folder in `graphql/` can be moved into its feature. - -### Apollo cache - -### GraphQL operations in the frontend - -All GraphQL queries, mutations and fragments in the frontend are collected in `frontend/src/graphql/`, grouped by domain the same way as the backend schema: - -```text -graphql/ -├── fragments/ -│ ├── plantFragments.ts # PlantFields: the plant fields every plant list asks for -│ └── userFragments.ts # UserFields: the user fields every user operation returns (uses PlantFields for matchedPlants) -├── plants/ -│ └── queries.ts # GET_PLANTS (Plant Match deck), EXPLORE_PLANTS (Explore Plants) -└── user/ - ├── queries.ts # GET_USER - └── mutations.ts # CREATE_USER, ADD_USER_MATCH, REMOVE_USER_MATCH, UPDATE_USER_PROFILE, UPDATE_USER_PREFERENCES -``` - -Each file also exports the TypeScript type for the result of its operations (for example `GetPlantsData` and `ExplorePlantsData`). The shared `Plant` and `User` types are in `types/`. Pages, hooks and the context only import the operations they use, for example `usePlantDeck` imports `GET_PLANTS` and `useMatchedPlants` imports `ADD_USER_MATCH` and `REMOVE_USER_MATCH`. - -Earlier the operations were spread across three places: the user operations in `context/userQueries.ts`, `EXPLORE_PLANTS` next to the Explore Plants page and `GET_PLANTS` inside the `usePlantDeck` hook. We moved them into one folder after feedback, and because one of our main goals is that the app should scale: - -- **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. -- **The user operations are shared.** They are used by `UserProvider`, two hooks and a component, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. -- **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. -- **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and the user's `matchedPlants`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. +- **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and `myMatches`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. - **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. We considered keeping each query next to the component that uses it (colocation), which is common in large apps organised by feature. Our frontend is organised by technical role (`pages/`, `components/`, `hooks/`, `context/`), and most of our operations are used in more than one place, so a shared folder fits better. If the app is later reorganised into feature folders, each domain folder in `graphql/` can be moved into its feature. @@ -315,7 +286,7 @@ T03-Project-2/ │ ├── src/ │ │ ├── assets/ # Static images │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file -│ │ ├── context/ # UserProvider and useUser() for the current user +│ │ ├── context/ # UserProvider and useUser() for the current user, ToastProvider and useToast() 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) │ │ ├── i18n/ # Translation setup and locale files (no, en) diff --git a/docs/quality.md b/docs/quality.md index e0731111..c0234454 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -45,7 +45,7 @@ The app includes the following accessibility features: - **Forms and images:** Search, filters and profile inputs have associated labels. Plant images use the plant name as alternative text, and profile and avatar images also include alternative text. -- **Control states:** The sort menu 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 and My Matches, the number of results or matches is also announced when it changes. The ✿ button's accessible name and tooltip say whether a click adds the plant to My Matches or removes it. +- **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 and My Matches, the number of results or matches is also announced when it changes. The match button on the plant cards shows ✿ to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. If adding or removing a match fails, an error message is shown at the top of the screen in a `role="alert"` region, so screen readers read it at once without moving focus. - **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. @@ -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. The page navigation (`Pagination`) and the sort menu (`SortMenu`) are separate components used on both Explore Plants and My Matches, so the two pages look and work the same way. The filter dropdowns (`FilterSelect`) are also a separate component, 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. +- **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `Pagination`, `SortMenu` and `MatchButton` are shared by Explore Plants and My Matches, and `Toast` shows error messages on every page. The filters on Explore Plants are defined in one list of `FilterSelect` components, so a new filter only needs one new line. - **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 4d79491f..fcaadb17 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -107,8 +107,6 @@ The coverage only counts the Vitest tests. Code that is only run by the end-to-e The tests are in `frontend/src/tests`. Snapshot tests are used for the explore page, the language switcher and the profile page. -- `Sidebar.test.tsx` - - Tests the sidebar, including the title, navigation links to all pages, and that the language switcher and theme toggle are displayed. Also verifies that the sidebar closes when a link or the close button is clicked, that the open state is reflected in the `data-open` attribute, and that the navigation landmark is accessible and only the current page is marked as active. - `App.test.tsx` - Shows the right page for each route, and opens and closes the sidebar from the header. - The skip link is the first thing a keyboard user reaches and moves focus to the main content without changing the route, and when the user goes to another page, focus moves to the start of the page so the next Tab goes to the skip link. @@ -117,7 +115,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - 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. + - Matches: the button adds a plant that is not matched (✿), and removes a plant that is already matched (✖). - URL state: search, filters, sorting and page are restored from the URL, changes are written to the URL, and reset clears the Explore parameters. - Accessibility: a search landmark, a heading and labelled controls. - Snapshots of the page with results, with no results and with the sort menu open. @@ -153,12 +151,12 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `Profile.test.tsx` - The name, the image alt text and a screen reader prefix for the description, the preferences tab by default, the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, that a picture from the plant owner test is shown but not offered in the chooser, and a snapshot. - Saving the profile text at once when a field loses focus, when the user leaves the page and when the tab is reloaded or closed, without saving the same text twice. -- `LanguageSwitcher.test.tsx` - - Tests the language switcher button in both Norwegian and English, and verifies that it shows the correct label and accessible name, and that clicking it switches to the other language. - `Sidebar.test.tsx` - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, and that only the current page is marked as active. - `ThemeToggle.test.tsx` - Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked. +- `ToastContext.test.tsx` + - The message is shown in an `alert` region, hidden after six seconds, replaced by a new message with the time started again, and nothing happens without a provider. - `Translation.test.tsx` - The Norwegian and English translation files have exactly the same keys, so no text is missing in either language. - `UserContext.test.tsx` @@ -167,6 +165,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - 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. +- `useMatchedPlants.test.tsx` + - The ids of the matched plants, adding and removing a match with no message when it works, an error message when the request fails or the user is not found, and nothing sent when there is no user or the plant is already matched. - `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. @@ -235,7 +235,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 marks its ✿ button as matched. Clicking the button again on ExplorePlants removes the plant from MyMatches. +- Adding a plant from ExplorePlants adds it to MyMatches and turns its ✿ button into ✖. Clicking the button again on ExplorePlants removes the plant from MyMatches. - Matching 13 plants from ExplorePlants gives two pages in MyMatches: the count, the newest first on page 1 and the oldest on page 2, sorting A–Z going back to page 1, and the sort order remembered when going to another page and back, and after a reload. 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. From f9a5e44a708c006db7438206be8107b17ab86068 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Wed, 11 Nov 2026 15:33:23 +0100 Subject: [PATCH 5/6] rename Toast to ErrorMessage --- frontend/src/App.tsx | 6 +- .../ErrorMessage.css} | 16 +++--- .../components/errorMessage/ErrorMessage.tsx | 16 ++++++ frontend/src/components/toast/Toast.tsx | 16 ------ frontend/src/context/ErrorMessageContext.tsx | 56 +++++++++++++++++++ frontend/src/context/ToastContext.tsx | 54 ------------------ frontend/src/hooks/useMatchedPlants.ts | 8 +-- ....test.tsx => ErrorMessageContext.test.tsx} | 17 +++--- frontend/src/tests/useMatchedPlants.test.tsx | 22 ++++---- 9 files changed, 108 insertions(+), 103 deletions(-) rename frontend/src/components/{toast/Toast.css => errorMessage/ErrorMessage.css} (74%) create mode 100644 frontend/src/components/errorMessage/ErrorMessage.tsx delete mode 100644 frontend/src/components/toast/Toast.tsx create mode 100644 frontend/src/context/ErrorMessageContext.tsx delete mode 100644 frontend/src/context/ToastContext.tsx rename frontend/src/tests/{ToastContext.test.tsx => ErrorMessageContext.test.tsx} (86%) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f71d9b4c..0a9ba12b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -5,7 +5,7 @@ import "./App.css"; import Sidebar from "./components/sidebar/Sidebar"; import Header from "./components/header/Header"; import AppRoutes from "./AppRoutes.tsx"; -import { ToastProvider } from "./context/ToastContext.tsx"; +import { ErrorMessageProvider } from "./context/ErrorMessageContext.tsx"; function App() { const { t } = useTranslation(); @@ -35,7 +35,7 @@ function App() { }; return ( - + {/* The start of the page. Focus is moved here when the page changes, so the next Tab goes to the skip link */}
@@ -67,7 +67,7 @@ function App() { >
-
+ ); } diff --git a/frontend/src/components/toast/Toast.css b/frontend/src/components/errorMessage/ErrorMessage.css similarity index 74% rename from frontend/src/components/toast/Toast.css rename to frontend/src/components/errorMessage/ErrorMessage.css index e599df80..05f078af 100644 --- a/frontend/src/components/toast/Toast.css +++ b/frontend/src/components/errorMessage/ErrorMessage.css @@ -1,6 +1,6 @@ /* In the top right corner, over the empty part of the header, where the background is always the plain page colour */ -.toast-region { +.error-message-region { position: fixed; top: 1rem; right: 1.5rem; @@ -8,7 +8,7 @@ pointer-events: none; } -.toast { +.error-message { margin: 0; max-width: 90vw; padding: 0.75rem 1.25rem; @@ -18,10 +18,10 @@ color: var(--text-light); font-family: var(--font-ui); font-size: 1rem; - animation: toast-in 0.2s ease-out; + animation: error-message-in 0.2s ease-out; } -@keyframes toast-in { +@keyframes error-message-in { from { opacity: 0; transform: translateY(-0.5rem); @@ -29,17 +29,17 @@ } @media (prefers-reduced-motion: reduce) { - .toast { + .error-message { animation: none; } } -/* On mobile the header is narrow, so the toast is centred at the top */ +/* On mobile the header is narrow, so the message is centred at the top */ @media (max-width: 767px) { - .toast-region { + .error-message-region { top: 0.5rem; right: auto; left: 50%; transform: translateX(-50%); } -} +} \ No newline at end of file diff --git a/frontend/src/components/errorMessage/ErrorMessage.tsx b/frontend/src/components/errorMessage/ErrorMessage.tsx new file mode 100644 index 00000000..35f017f8 --- /dev/null +++ b/frontend/src/components/errorMessage/ErrorMessage.tsx @@ -0,0 +1,16 @@ +import "./ErrorMessage.css"; + +type ErrorMessageProps = { + message: string | null; +}; + +// A short error message at the top of the screen. The region is always there, +// so screen readers notice when a message appears and read it at once, without +// moving focus. +export default function ErrorMessage({ message }: ErrorMessageProps) { + return ( +
+ {message &&

{message}

} +
+ ); +} diff --git a/frontend/src/components/toast/Toast.tsx b/frontend/src/components/toast/Toast.tsx deleted file mode 100644 index d75df80c..00000000 --- a/frontend/src/components/toast/Toast.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import "./Toast.css"; - -type ToastProps = { - message: string | null; -}; - -// A short error message at the top of the screen. The region is always there, -// so screen readers notice when a message appears and read it at once, without -// moving focus. -export default function Toast({ message }: ToastProps) { - return ( -
- {message &&

{message}

} -
- ); -} diff --git a/frontend/src/context/ErrorMessageContext.tsx b/frontend/src/context/ErrorMessageContext.tsx new file mode 100644 index 00000000..d21d6beb --- /dev/null +++ b/frontend/src/context/ErrorMessageContext.tsx @@ -0,0 +1,56 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from "react"; +import ErrorMessage from "../components/errorMessage/ErrorMessage"; + +// How long an error message is shown +const DURATION = 6000; + +type ErrorMessageContextValue = { + showError: (message: string) => void; +}; + +// Without a provider showError does nothing, so components that use it can +// still be rendered alone, for example in tests +const ErrorMessageContext = createContext({ + showError: () => {}, +}); + +export function ErrorMessageProvider({ children }: { children: ReactNode }) { + const [error, setError] = useState<{ id: number; message: string } | null>( + null, + ); + const nextId = useRef(0); + + // A new message replaces the one that is shown. The id makes the timer start + // again even when the same message is shown twice in a row. + const showError = useCallback((message: string) => { + nextId.current += 1; + setError({ id: nextId.current, message }); + }, []); + + useEffect(() => { + if (!error) return; + const timer = setTimeout(() => setError(null), DURATION); + return () => clearTimeout(timer); + }, [error]); + + const value = useMemo(() => ({ showError }), [showError]); + + return ( + + {children} + + + ); +} + +// eslint-disable-next-line react-refresh/only-export-components +export const useErrorMessage = () => useContext(ErrorMessageContext); diff --git a/frontend/src/context/ToastContext.tsx b/frontend/src/context/ToastContext.tsx deleted file mode 100644 index 966bdcc0..00000000 --- a/frontend/src/context/ToastContext.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { - createContext, - useCallback, - useContext, - useEffect, - useMemo, - useRef, - useState, - type ReactNode, -} from "react"; -import Toast from "../components/toast/Toast"; - -// How long an error message is shown -const DURATION = 6000; - -type ToastContextValue = { - showToast: (message: string) => void; -}; - -// Without a provider showToast does nothing, so components that use it can -// still be rendered alone, for example in tests -const ToastContext = createContext({ showToast: () => {} }); - -export function ToastProvider({ children }: { children: ReactNode }) { - const [toast, setToast] = useState<{ id: number; message: string } | null>( - null, - ); - const nextId = useRef(0); - - // A new message replaces the one that is shown. The id makes the timer start - // again even when the same message is shown twice in a row. - const showToast = useCallback((message: string) => { - nextId.current += 1; - setToast({ id: nextId.current, message }); - }, []); - - useEffect(() => { - if (!toast) return; - const timer = setTimeout(() => setToast(null), DURATION); - return () => clearTimeout(timer); - }, [toast]); - - const value = useMemo(() => ({ showToast }), [showToast]); - - return ( - - {children} - - - ); -} - -// eslint-disable-next-line react-refresh/only-export-components -export const useToast = () => useContext(ToastContext); diff --git a/frontend/src/hooks/useMatchedPlants.ts b/frontend/src/hooks/useMatchedPlants.ts index e3efecae..9c378080 100644 --- a/frontend/src/hooks/useMatchedPlants.ts +++ b/frontend/src/hooks/useMatchedPlants.ts @@ -1,7 +1,7 @@ import { useMutation } from "@apollo/client/react"; import { useTranslation } from "react-i18next"; import { useUser } from "../context/UserContext"; -import { useToast } from "../context/ToastContext"; +import { useErrorMessage } from "../context/ErrorMessageContext"; import { ADD_USER_MATCH, REMOVE_USER_MATCH, @@ -17,7 +17,7 @@ const refetchMyMatches = { refetchQueries: ["MyMatches"] }; export function useMatchedPlants() { const { t } = useTranslation(); const { userId, user, loading } = useUser(); - const { showToast } = useToast(); + const { showError } = useErrorMessage(); const [addUserMatch] = useMutation( ADD_USER_MATCH, refetchMyMatches, @@ -42,7 +42,7 @@ export function useMatchedPlants() { }); if (!result?.data?.addUserMatch) throw new Error("No user returned"); } catch { - showToast(t("matches.addFailed")); + showError(t("matches.addFailed")); } }; @@ -54,7 +54,7 @@ export function useMatchedPlants() { }); if (!result?.data?.removeUserMatch) throw new Error("No user returned"); } catch { - showToast(t("matches.removeFailed")); + showError(t("matches.removeFailed")); } }; diff --git a/frontend/src/tests/ToastContext.test.tsx b/frontend/src/tests/ErrorMessageContext.test.tsx similarity index 86% rename from frontend/src/tests/ToastContext.test.tsx rename to frontend/src/tests/ErrorMessageContext.test.tsx index dd2440c3..6abd732a 100644 --- a/frontend/src/tests/ToastContext.test.tsx +++ b/frontend/src/tests/ErrorMessageContext.test.tsx @@ -1,23 +1,26 @@ import { act, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"; -import { ToastProvider, useToast } from "../context/ToastContext"; +import { + ErrorMessageProvider, + useErrorMessage, +} from "../context/ErrorMessageContext"; -// A button that shows the given message, so the tests can trigger a toast +// A button that shows the given message, so the tests can trigger an error message function ShowButton({ message }: { message: string }) { - const { showToast } = useToast(); - return ; + const { showError } = useErrorMessage(); + return ; } function renderWithProvider() { render( - + - , + , ); } -describe("ToastContext", () => { +describe("ErrorMessageContext", () => { beforeEach(() => { vi.useFakeTimers(); }); diff --git a/frontend/src/tests/useMatchedPlants.test.tsx b/frontend/src/tests/useMatchedPlants.test.tsx index 952617f4..ce55080d 100644 --- a/frontend/src/tests/useMatchedPlants.test.tsx +++ b/frontend/src/tests/useMatchedPlants.test.tsx @@ -2,7 +2,7 @@ import { act, renderHook, screen } from "@testing-library/react"; import type { ReactNode } from "react"; import { beforeEach, describe, it, expect, vi } from "vitest"; import { useMatchedPlants } from "../hooks/useMatchedPlants"; -import { ToastProvider } from "../context/ToastContext"; +import { ErrorMessageProvider } from "../context/ErrorMessageContext"; import { ADD_USER_MATCH } from "../graphql/user/mutations"; import type { Plant } from "../types/Plant"; @@ -32,17 +32,17 @@ function mockUser(userId: string | null, matchedPlantIds: string[] = []) { }); } -// Renders the hook inside a ToastProvider, so the error messages are shown +// Renders the hook inside an ErrorMessageProvider, so the error messages are shown function renderMatchedPlants() { const wrapper = ({ children }: { children: ReactNode }) => ( - {children} + {children} ); const hook = renderHook(() => useMatchedPlants(), { wrapper }); return hook.result; } -// The toast region is rendered by the provider inside the hook's container -const alert = () => screen.getByRole("alert"); +// The region where the provider shows the error messages +const errorRegion = () => screen.getByRole("alert"); beforeEach(() => { addUserMatch.mockReset(); @@ -71,7 +71,7 @@ describe("useMatchedPlants", () => { expect(addUserMatch).toHaveBeenCalledWith({ variables: { userId: "user-1", plantId: "plant-1" }, }); - expect(alert()).toBeEmptyDOMElement(); + expect(errorRegion()).toBeEmptyDOMElement(); }); it("shows an error message when the request fails", async () => { @@ -80,7 +80,7 @@ describe("useMatchedPlants", () => { await act(() => result.current.addMatch(orchid)); - expect(alert()).toHaveTextContent("matches.addFailed"); + expect(errorRegion()).toHaveTextContent("matches.addFailed"); }); it("shows an error message when the user was not found", async () => { @@ -89,7 +89,7 @@ describe("useMatchedPlants", () => { await act(() => result.current.addMatch(orchid)); - expect(alert()).toHaveTextContent("matches.addFailed"); + expect(errorRegion()).toHaveTextContent("matches.addFailed"); }); it("does nothing when the plant is already matched or there is no user", async () => { @@ -117,7 +117,7 @@ describe("useMatchedPlants", () => { expect(removeUserMatch).toHaveBeenCalledWith({ variables: { userId: "user-1", plantId: "plant-1" }, }); - expect(alert()).toBeEmptyDOMElement(); + expect(errorRegion()).toBeEmptyDOMElement(); }); it("shows an error message when the request fails", async () => { @@ -126,7 +126,7 @@ describe("useMatchedPlants", () => { await act(() => result.current.removeMatch("plant-1")); - expect(alert()).toHaveTextContent("matches.removeFailed"); + expect(errorRegion()).toHaveTextContent("matches.removeFailed"); }); it("shows an error message when the user was not found", async () => { @@ -135,7 +135,7 @@ describe("useMatchedPlants", () => { await act(() => result.current.removeMatch("plant-1")); - expect(alert()).toHaveTextContent("matches.removeFailed"); + expect(errorRegion()).toHaveTextContent("matches.removeFailed"); }); it("does nothing when there is no user", async () => { From d0b1ebf82a1b1e913fb760a6fd6a6aab15e341a8 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Wed, 11 Nov 2026 15:40:30 +0100 Subject: [PATCH 6/6] update comments and documentation related to renaming Toast to ErrorMessage and run prettier --- docs/architecture.md | 6 +++--- docs/quality.md | 2 +- docs/tests.md | 4 ++-- frontend/src/components/errorMessage/ErrorMessage.css | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 257a360c..153b1993 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -49,9 +49,9 @@ 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. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). -- **Error messages:** `ToastProvider` (`context/ToastContext.tsx`) wraps the app and makes `showToast()` available through `useToast()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails. +- **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. -- **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 `Toast` 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 (✖), and `ErrorMessage` shows a short error message. The components 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`, `User` and `Preference` are defined in `types/`. @@ -286,7 +286,7 @@ T03-Project-2/ │ ├── src/ │ │ ├── assets/ # Static images │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file -│ │ ├── context/ # UserProvider and useUser() for the current user, ToastProvider and useToast() for error messages +│ │ ├── 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) │ │ ├── i18n/ # Translation setup and locale files (no, en) diff --git a/docs/quality.md b/docs/quality.md index c0234454..6a675d49 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -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:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `Pagination`, `SortMenu` and `MatchButton` are shared by Explore Plants and My Matches, and `Toast` shows error messages on every page. The filters on Explore Plants are defined in one list of `FilterSelect` components, so a new filter only needs one new line. +- **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `Pagination`, `SortMenu` and `MatchButton` are shared by Explore Plants and My Matches, and `ErrorMessage` shows error messages on every page. The filters on Explore Plants are defined in one list of `FilterSelect` components, so a new filter only needs one new line. - **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 fcaadb17..0003c9f7 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -110,6 +110,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `App.test.tsx` - Shows the right page for each route, and opens and closes the sidebar from the header. - The skip link is the first thing a keyboard user reaches and moves focus to the main content without changing the route, and when the user goes to another page, focus moves to the start of the page so the next Tab goes to the skip link. +- `ErrorMessageContext.test.tsx` + - The message is shown in an `alert` region, hidden after six seconds, replaced by a new message with the time started again, and nothing happens without a provider. - `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. @@ -155,8 +157,6 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, and that only the current page is marked as active. - `ThemeToggle.test.tsx` - Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked. -- `ToastContext.test.tsx` - - The message is shown in an `alert` region, hidden after six seconds, replaced by a new message with the time started again, and nothing happens without a provider. - `Translation.test.tsx` - The Norwegian and English translation files have exactly the same keys, so no text is missing in either language. - `UserContext.test.tsx` diff --git a/frontend/src/components/errorMessage/ErrorMessage.css b/frontend/src/components/errorMessage/ErrorMessage.css index 05f078af..aa8d1197 100644 --- a/frontend/src/components/errorMessage/ErrorMessage.css +++ b/frontend/src/components/errorMessage/ErrorMessage.css @@ -42,4 +42,4 @@ left: 50%; transform: translateX(-50%); } -} \ No newline at end of file +}