diff --git a/README.md b/README.md index ed0b0ea9..402b720d 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ http://it2810-03.idi.ntnu.no/project2/ ## Core features -- **Plant Match:** Plants matching the most preferences come first, otherwise the order is random. The deck is kept while the user visits other pages, so they can continue where they left off. +- **Plant Match:** The user swipes the card right to match with a plant and left to skip it, or uses the ♥ and ✖ buttons. Plants matching the most preferences come first, otherwise the order is random. The deck is kept while the user visits other pages, so they can continue where they left off. - **My Matches:** Collects liked plants from both Plant Match and Explore Plants, with the same search, filters and match counts as Explore Plants. Both pages can also sort the plants by how well they match the user's preferences. The user only stores plant ids, and the list is fetched one page at a time, so responses do not grow with the number of matches. - **Explore Plants:** Search, filtering, sorting and pagination run in the backend, so the frontend only receives one page at a time, whatever the size of the collection. The state is kept in the URL, so a view survives a refresh and can be shared as a link. Each filter value shows how many plants it would give, and values that would give none can't be chosen, so filtering never ends in an empty list. - **Plant Owner Test:** Four questions give one of six plant owner types, whose picture can be used as profile picture. The result also suggests one preference each for watering, light and care level, based on the answers and the description of the type. The user chooses which of them to add, and they are added to the preferences they already have, so PlantMatch puts plants that suit them first right away. diff --git a/backend/src/migrations.ts b/backend/src/migrations.ts new file mode 100644 index 00000000..ae571d62 --- /dev/null +++ b/backend/src/migrations.ts @@ -0,0 +1,15 @@ +import type { Db } from "mongodb"; + +// Updates data stored by older versions of the app. Each step only changes +// documents that still have the old value, so this is safe to run every time +// the server starts. +export async function migrateData(database: Db) { + // The snake plant avatar id was "snake-plant". It is now "snakePlant", in + // the same camelCase as the other picture ids. + await database + .collection("users") + .updateMany( + { profilePicture: "snake-plant" }, + { $set: { profilePicture: "snakePlant" } }, + ); +} diff --git a/backend/src/queryBuilders.ts b/backend/src/queryBuilders.ts index 270e9b97..ced5792b 100644 --- a/backend/src/queryBuilders.ts +++ b/backend/src/queryBuilders.ts @@ -14,11 +14,9 @@ const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Filter values come in as "full_sun", the database has "full sun" const normalize = (s: string) => escapeRegex(s.replace(/_/g, " ").trim()); -// Order from low to high. -const SORT_ORDERS = { - watering: ["minimum", "average", "frequent"], - careLevel: ["low", "medium", "high"], -}; +// Sorted by name A–Z, with _id as a tie-breaker so the order is stable. +// Uses the index from indexes.ts. +const BY_NAME = { commonName: 1, _id: 1 } as const; // Position in the order list, unknown or missing values go last const rankOf = (order: string[], value: unknown): Document => ({ @@ -39,10 +37,10 @@ export const knownPreferences = (preferences?: string[] | null): string[] => // name. Without preferences, the plants are sorted by name. const byPreferenceStages = (preferences: string[]): Document[] => preferences.length === 0 - ? [{ $sort: { commonName: 1, _id: 1 } }] + ? [{ $sort: BY_NAME }] : [ { $addFields: { matchScore: matchScore(preferences) } }, - { $sort: { matchScore: -1, commonName: 1, _id: 1 } }, + { $sort: { matchScore: -1, ...BY_NAME } }, ]; // Builds the aggregation stages that handle sorting. preferences is only @@ -61,17 +59,19 @@ export const buildSortStages = ( return [ { $addFields: { - sortRank: rankOf(SORT_ORDERS.watering, { $toLower: "$watering" }), + sortRank: rankOf(FILTER_OPTIONS.watering, { + $toLower: "$watering", + }), }, }, - { $sort: { sortRank: 1, commonName: 1, _id: 1 } }, + { $sort: { sortRank: 1, ...BY_NAME } }, ]; case "careLevel_asc": // "Moderate" and "Medium" both exist in the data, treat them as equal return [ { $addFields: { - sortRank: rankOf(SORT_ORDERS.careLevel, { + sortRank: rankOf(FILTER_OPTIONS.careLevel, { $let: { vars: { c: { $toLower: { $ifNull: ["$careLevel", ""] } } }, in: { @@ -81,10 +81,10 @@ export const buildSortStages = ( }), }, }, - { $sort: { sortRank: 1, commonName: 1, _id: 1 } }, + { $sort: { sortRank: 1, ...BY_NAME } }, ]; default: - return [{ $sort: { commonName: 1, _id: 1 } }]; + return [{ $sort: BY_NAME }]; } }; @@ -111,7 +111,7 @@ export const buildMatchSortStages = ( case "oldest": return byMatchOrder(1); case "name_asc": - return [{ $sort: { commonName: 1, _id: 1 } }]; + return [{ $sort: BY_NAME }]; case "name_desc": return [{ $sort: { commonName: -1, _id: -1 } }]; default: @@ -149,7 +149,8 @@ export const buildPlantFilter = (args: PlantFilterArgs): Filter => { return filter; }; -// The values each filter can have. Must match PLANT_FILTERS in +// The values each filter can have, from low to high, so the watering and +// care level sort orders use them too. Must match PLANT_FILTERS in // frontend/src/components/plantSearchForm/plantFilters.ts export const FILTER_OPTIONS: Record = { watering: ["minimum", "average", "frequent"], diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index bbd00cd9..7b57f65c 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -16,6 +16,7 @@ import type { ExplorePlantsArgs, GetPlantsArgs, MyMatchesArgs, + PaginationArgs, Plant, PlantDoc, PlantFilterArgs, @@ -38,7 +39,7 @@ const PROFILE_PICTURES = [ "default", "monstera", "pothos", - "snake-plant", + "snakePlant", "anthurium", "succulent", "fern", @@ -121,7 +122,7 @@ const cleanText = ( // The three queries run at the same time. const findPlantPage = async ( baseFilter: Filter, - args: PlantFilterArgs & { limit?: number | null; offset?: number | null }, + args: PlantFilterArgs & PaginationArgs, sortStages: Document[], ): Promise => { const filter = { ...baseFilter, ...buildPlantFilter(args) }; diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 046f3a3c..c2f0f33e 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,6 +1,6 @@ // The GraphQL schema. The resolvers are in resolvers.ts. export const typeDefs = ` - type Query{ + type Query { getPlants(limit: Int = 50, excludeIds: [ID!], preferences: [String!]): [Plant] explorePlants( search: String @@ -55,7 +55,7 @@ export const typeDefs = ` filterCounts: FilterCounts! } - type Plant{ + type Plant { id: ID! name: String! imageURL: String diff --git a/backend/src/server.ts b/backend/src/server.ts index c26a8983..fe5bca79 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -4,9 +4,12 @@ import { resolvers } from "./resolvers.js"; import { typeDefs } from "./schema.js"; import { db } from "./db.js"; import { ensureIndexes } from "./indexes.js"; +import { migrateData } from "./migrations.js"; -// Create the database indexes before the server starts taking requests +// Create the database indexes and update old data before the server starts +// taking requests await ensureIndexes(db); +await migrateData(db); const server = new ApolloServer({ typeDefs, resolvers }); diff --git a/backend/src/types.ts b/backend/src/types.ts index 82126a3e..6a5c8bee 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -43,13 +43,18 @@ export interface PlantFilterArgs { careLevel?: string | null; } -export interface ExplorePlantsArgs extends PlantFilterArgs { +// The sort order and page, on Explore Plants and My Matches. +// Null if the client sends null explicitly, see clampLimit in resolvers.ts +export interface PaginationArgs { sort?: string; + limit?: number | null; + offset?: number | null; +} + +export interface ExplorePlantsArgs extends PlantFilterArgs, PaginationArgs { // The user's preferences, for the "preferences" sort order. Explore Plants // has no user id, so the frontend sends them, like for getPlants. preferences?: string[] | null; - limit?: number | null; - offset?: number | null; } // The filters on Explore Plants and My Matches @@ -114,8 +119,5 @@ export interface UserMatchArgs extends UserIdArgs { plantId: string; } -export interface MyMatchesArgs extends UserIdArgs, PlantFilterArgs { - sort?: string; - limit?: number | null; - offset?: number | null; -} +export interface MyMatchesArgs + extends UserIdArgs, PlantFilterArgs, PaginationArgs {} diff --git a/backend/tests/migrations.test.ts b/backend/tests/migrations.test.ts new file mode 100644 index 00000000..c17b2fde --- /dev/null +++ b/backend/tests/migrations.test.ts @@ -0,0 +1,28 @@ +import { MongoClient } from "mongodb"; +import { afterAll, expect, inject, it } from "vitest"; +import { migrateData } from "../src/migrations.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("migrations-test"); + +afterAll(async () => { + await client.close(); +}); + +it("renames the old snake-plant avatar id, and can run again on the next start", async () => { + const users = db.collection("users"); + await users.insertMany([ + { name: "old", profilePicture: "snake-plant" }, + { name: "other", profilePicture: "fern" }, + ]); + + await migrateData(db); + // The server runs this on every start, so running it twice must not fail + await migrateData(db); + + const pictures = (await users.find().sort({ name: 1 }).toArray()).map( + (user) => user.profilePicture, + ); + expect(pictures).toEqual(["snakePlant", "fern"]); +}); diff --git a/docs/architecture.md b/docs/architecture.md index 1f33d298..dac4e104 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -53,20 +53,21 @@ The frontend is built with React and TypeScript (Vite). - **Error messages:** `ErrorMessageProvider` (`context/ErrorMessageContext.tsx`) wraps the app and makes `showError()` available through `useErrorMessage()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails. - **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text). `useExploreParams` keeps the Explore search, filters, sort order and page in the URL, and sends the user back to page 1 when the search, a filter or the sort order changes. It uses `useUrlParams`, which reads the page number and updates the URL (with React Router's `useSearchParams`). `useMyMatchesParams` does the same for My Matches, but keeps the search, filters and sort order in `sessionStorage` with `useSessionState`, since the matches belong to the user in this browser and a link to them could not be shared. - `usePlantDeck` keeps the remaining Plant Match cards in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored. -- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `PlantSearchForm` is the search field, filters, sort menu and reset button used on both Explore Plants and My Matches (the filters are listed once in `plantFilters.ts`), `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (✿) or removes it (✖), `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages. +- **Swiping on Plant Match:** `PlantMatchPage` wraps the card in an element that follows the pointer (mouse, finger or pen) with Pointer Events. Dragging the card more than 100 px to the right matches the plant, and to the left skips it. A shorter drag springs back, a movement of less than 8 px counts as a tap and flips the card as before, and a movement that is mostly up or down is left to the browser, so the page can still be scrolled. The ♥ and ✖ buttons do the same as a swipe. The card then flies off to that side for 300 ms before the next card is shown. The match is saved at once, before the animation, so it is not lost if the user leaves the page while the card is moving. When the user prefers reduced motion, the next card is shown at once. +- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `PlantSearchForm` is the search field, filters, sort menu and reset button used on both Explore Plants and My Matches (the filters are listed once in `plantFilters.ts`), `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (♥) or removes it (✖), `HeartIcon` is the SVG heart used on the match buttons and on Plant Match, `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages. - **Plant Owner Test:** The questions, results and suggestions are data in `pages/plantOwnerTest/plantOwnerTest.ts`, so the page only shows them. `getPlantOwnerResult()` gives the result from the location and watering answers. `getSuggestedPreferences()` gives three preference ids from the answers and the result: - **Watering** from the result: the minimalists get `minimumWater`, the average gardeners `averageWater`, and the dreaming city gardener and the garden expert `frequentWater`. - **Light** from the light answer. There is no preference for partial sun, so it suggests `partShade`, since those plants are listed as "part sun/part shade" in the data and match the part shade preference. - **Care level** from the result where its description says something about care: `easyCare` for the minimalists ("hardy plants") and `hardCare` for the dreaming city gardener and the garden expert ("a lot of attention"). The average gardeners get it from the time answer (10 minutes: `easyCare`, 30 minutes or 1 hour: `mediumCare`, 1 day: `hardCare`). `SuggestedPreferences.tsx` shows the suggestions that the user does not already have as toggle buttons, all chosen from the start. Nothing is saved until the user clicks "Add to my preferences", which runs `updateUserPreferences` with the saved preferences plus the chosen suggestions, so no preference is removed. It uses an optimistic response like the buttons on the profile page, so the profile and Plant Match are updated at once. The suggestions are shown above "Use as profile picture", since that button takes the user to the profile page. - + - **Walkthrough:** The guide for new users is in `components/walkthrough/`, and is made up of three parts: - - **The steps are data:** `walkthroughSteps.ts` lists the steps in order. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page. + - **The steps are data:** `walkthroughSteps.ts` lists the steps in the same order as the pages in the sidebar. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page. - **`App.tsx` decides when it is open:** The walkthrough opens by itself when `walkthroughSeen` is not in `localStorage`, and the key is set when it is closed, so it is only shown once. The ? button in the `Header` opens it again at the step for the current page (`stepForPath`). When it closes, focus goes back to the ? button, except when the "Go to" link has moved the user to another page, where focus moves to the start of the new page like for any other navigation. - - **`Walkthrough.tsx` shows one step at a time:** It uses the native `` element with `showModal()`, so the browser grays out the page behind, keeps keyboard focus inside the dialog and closes it with Escape. It can also be closed with ×, Finish or a click outside the box. The user moves between steps with Back and Next or the arrow keys, and steps about a page have a "Go to" link that opens the page and closes the walkthrough. The `LanguageSwitcher` from the sidebar is reused at the bottom of the dialog, so the language can be changed without leaving the walkthrough. This matters on mobile, where the sidebar is hidden behind the menu button. -- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. -- **Shared types:** `Plant`, `User` and `Preference` are defined in `types/`. + - **`Walkthrough.tsx` shows one step at a time:** It uses the native `` element with `showModal()`, so the browser grays out the page behind, keeps keyboard focus inside the dialog and closes it with Escape. It can also be closed with ×, Finish or a click outside the box. The user moves between steps with Back and Next or the arrow keys, and steps about a page have a "Go to" link that opens the page and closes the walkthrough. The `LanguageSwitcher` from the sidebar is reused at the bottom of the dialog, so the language can be changed without leaving the walkthrough. This matters on mobile, where the sidebar is hidden behind the menu button. The text of all steps is placed in the same CSS grid cell, and only the current step is visible (the others have `visibility: hidden`, `aria-hidden` and `inert`), so the box always has the height of the longest step and does not change size between steps. +- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. `plantPreferenceIds()` in the same file uses the same keys to find which preference ids a plant matches, which the preference chips on the plant cards use. The preference ids on the profile page are a plain list, and their texts are found in the translation files under `preferences.`. +- **Shared types:** `Plant` and `User` are defined in `types/`. ### Communication with the backend @@ -193,17 +194,17 @@ Note: the image URLs from the Perenual API expire after 24 hours. That is why ea One document per user. There is no login: a user is created the first time someone opens the app, and the browser keeps the user id (see [Where state is kept](#where-state-is-kept)). The id is generated by MongoDB. -| Field | Type | Description | Exposed in GraphQL as | -| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | -| `_id` | ObjectId | Set by MongoDB, and the id the browser stores | `id` | -| `name` | string/null | Display name, at most 40 characters. `null` means not chosen, and the frontend shows a translated default | `name` | -| `description` | string/null | Short profile text, at most 100 characters | `description` | -| `profilePicture` | string | Id of the chosen picture. One of the avatars (`default`, `monstera`, `pothos`, `snake-plant`, `anthurium`, `succulent`, `fern`, `orchid`) or a plant owner test result (`cityMinimalist`, `averageCityGardener`, `cityGardenerDreaming`, `countryMinimalist`, `averageCountryGardener`, `gardenExpert`) | `profilePicture` | -| `preferences` | string[] | Chosen plant preferences: `minimumWater`, `averageWater`, `frequentWater`, `fullSun`, `partShade`, `filteredShade`, `easyCare`, `mediumCare`, `hardCare` | `preferences` | -| `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlantIds`, and the plants through `myMatches` | -| `createdAt` | Date | When the user was created | `createdAt` (ISO string) | +| Field | Type | Description | Exposed in GraphQL as | +| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- | +| `_id` | ObjectId | Set by MongoDB, and the id the browser stores | `id` | +| `name` | string/null | Display name, at most 40 characters. `null` means not chosen, and the frontend shows a translated default | `name` | +| `description` | string/null | Short profile text, at most 100 characters | `description` | +| `profilePicture` | string | Id of the chosen picture. One of the avatars (`default`, `monstera`, `pothos`, `snakePlant`, `anthurium`, `succulent`, `fern`, `orchid`) or a plant owner test result (`cityMinimalist`, `averageCityGardener`, `cityGardenerDreaming`, `countryMinimalist`, `averageCountryGardener`, `gardenExpert`) | `profilePicture` | +| `preferences` | string[] | Chosen plant preferences: `minimumWater`, `averageWater`, `frequentWater`, `fullSun`, `partShade`, `filteredShade`, `easyCare`, `mediumCare`, `hardCare` | `preferences` | +| `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlantIds`, and the plants through `myMatches` | +| `createdAt` | Date | When the user was created | `createdAt` (ISO string) | -A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers.ts` and must match the ids used in the frontend (`ProfilePage.tsx` and `plantOwnerTest.ts`). The preference ids are the keys of `PREFERENCE_MATCHERS` in `queryBuilders.ts`, so the list used for validation and the list used for scoring cannot get out of sync. The avatar id `snake-plant` is kept as it is, since it is already stored on existing users. +A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers.ts` and must match the ids used in the frontend (`ProfilePage.tsx` and `plantOwnerTest.ts`). The preference ids are the keys of `PREFERENCE_MATCHERS` in `queryBuilders.ts`, so the list used for validation and the list used for scoring cannot get out of sync. The avatar id was `snake-plant` before, and `migrations.ts` renames it to `snakePlant` on existing users when the server starts. Matches only store the plant id, not a copy of the plant. That keeps user documents small and means the user always sees the current plant data. @@ -321,7 +322,7 @@ T03-Project-2/ │ │ │ ├── plantOwnerTest/ # PlantOwnerTestPage, SuggestedPreferences, and plantOwnerTest.ts with the questions, results and suggestions │ │ │ └── profile/ # ProfilePage │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) -│ │ ├── types/ # Shared TypeScript types (Plant, User, Preference) +│ │ ├── types/ # Shared TypeScript types (Plant, User) │ │ ├── AppRoutes.tsx # Route definitions │ │ └── main.tsx # Application entry point (Apollo Client, UserProvider, router) │ ├── .env.production # GraphQL URL for the deployed app diff --git a/docs/quality.md b/docs/quality.md index 6b08bd55..123e1cf6 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -61,11 +61,13 @@ The app includes the following accessibility features: - **Forms and images:** Search, filters and profile inputs have associated labels. Plant images use the plant name as alternative text, and profile and avatar images also include alternative text. -- **Control states:** The sort menu and the mobile menu button expose their expanded state and which element they control. Sort, avatar and preference choices and the profile tabs expose their selected state with `aria-pressed`. The preference chips on the plant cards are a list, and a chip that matches the user's preferences also says so in text that only screen readers read, so the information is not given by color alone. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes, including "No results found" when a search gives no plants and "no matches" when the last match is removed. Filter values that would give no plants are disabled options, so screen readers say they are unavailable, and the number of plants is part of the option text. Every page has one `h1` (the page title in the header) and a `main` landmark. The match button on the plant cards shows ✿ to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. If adding or removing a match fails, an error message is shown at the top of the screen in a `role="alert"` region, so screen readers read it at once without moving focus. +- **Control states:** The sort menu and the mobile menu button expose their expanded state and which element they control. Sort, avatar and preference choices and the profile tabs expose their selected state with `aria-pressed`. The preference chips on the plant cards are a list, and a chip that matches the user's preferences also says so in text that only screen readers read, so the information is not given by color alone. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes, including "No results found" when a search gives no plants and "no matches" when the last match is removed. Filter values that would give no plants are disabled options, so screen readers say they are unavailable, and the number of plants is part of the option text. Every page has one `h1` (the page title in the header) and a `main` landmark. The match button on the plant cards shows a heart to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. 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. -- **Reduced motion:** When the user has asked for reduced motion in their system settings, the plant card flip and hover effects, the animation of the error message and the hover effects in the Plant Owner Test are turned off. +- **Swiping is never the only way:** On Plant Match the card can be swiped, but the ♥ and ✖ buttons next to it do the same, so users who use the keyboard, a screen reader or cannot drag can still match and skip plants (WCAG 2.5.1 Pointer Gestures). The "How to match" help text mentions both. + +- **Reduced motion:** When the user has asked for reduced motion in their system settings, the animation of the card flying off after a swipe, the plant card flip and hover effects, the animation of the error message and the hover effects in the Plant Owner Test are turned off. - **Testing:** The end-to-end tests check all pages against WCAG 2.1 AA with axe, in both light and dark mode, and the component tests check accessible names, navigation state and sorting states. The axe DevTools extension found no issues, and the deployed app scored 100 for accessibility in Lighthouse. The app has also been tested manually with the keyboard only and at 200 % zoom. See [tests.md](tests.md#accessibility) for the results, including two problems the tests found. @@ -87,7 +89,7 @@ We considered sustainability through both our design choices and our approach to - **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. Only the ids of the user's matches are sent with the user, and My Matches fetches one page of plants at a time, so the plant images are only sent when they are shown. -- **Inline SVG icons without an icon library:** The application only needs a few icons (search, sort, and the sun and moon on the theme button), so we draw them ourselves as small inline SVG components instead of installing an icon library such as `react-icons`. This keeps the project to one fewer dependency that has to be downloaded, installed and kept up to date, and the icons are part of the JavaScript the page already loads, so they need no extra requests or icon font. SVGs are also vector graphics, so they stay sharp at any size and zoom level without image files in several resolutions. +- **Inline SVG icons without an icon library:** The application only needs a few icons (search, sort, the heart on the match buttons, and the sun and moon on the theme button), so we draw them ourselves as small inline SVG components instead of installing an icon library such as `react-icons`. This keeps the project to one fewer dependency that has to be downloaded, installed and kept up to date, and the icons are part of the JavaScript the page already loads, so they need no extra requests or icon font. SVGs are also vector graphics, so they stay sharp at any size and zoom level without image files in several resolutions. - **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. @@ -111,7 +113,7 @@ We considered sustainability through both our design choices and our approach to - **Keeping the previous results while loading:** On Explore Plants, the previous results and the number of results stay on screen, slightly dimmed, while new ones load (with Apollo's `previousData`). The page does not flicker or jump when the search, a filter or the page changes, and the loading text is only shown the first time. -- **Consistent icons:** All icons are inline SVG components in [Icons.tsx](../frontend/src/components/icons/Icons.tsx) and [ThemeIcons.tsx](../frontend/src/components/sidebarButtons/ThemeIcons.tsx), drawn on the same 24 × 24 grid. They use `currentColor`, so they follow the text color in both light and dark mode, and they are sized with `font-size`, so they scale with the text around them. They are marked with `aria-hidden` and `focusable="false"`, since the search field and the buttons they are in already have accessible names, so screen readers do not read the icons twice. Because we drew the icons ourselves, there are no third-party licences to credit. +- **Consistent icons:** All icons are inline SVG components in [Icons.tsx](../frontend/src/components/icons/Icons.tsx), [ThemeIcons.tsx](../frontend/src/components/sidebarButtons/ThemeIcons.tsx) and [HeartIcon.tsx](../frontend/src/components/heartIcon/HeartIcon.tsx), drawn on the same 24 × 24 grid. They use `currentColor`, so they follow the text color in both light and dark mode, and they are sized with `font-size`, so they scale with the text around them. They are marked with `aria-hidden` and `focusable="false"`, since the search field and the buttons they are in already have accessible names, so screen readers do not read the icons twice. Because we drew the icons ourselves, there are no third-party licences to credit. - **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 62bb19f5..aa357c91 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -181,7 +181,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `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. - `Walkthrough.test.tsx` - - Opens as a modal dialog on the given step, going forward and back with the buttons and the arrow keys, closing with Finish on the last step and with the close button, the small screen hint only on the steps that have one, the language switcher on every step, the "Go to" link opening the page of the step and closing the walkthrough, and no link on steps that are not about a page. + - Opens as a modal dialog on the given step, going forward and back with the buttons and the arrow keys, closing with Finish on the last step and with the close button, the small screen hint only on the steps that have one, the language switcher on every step, the "Go to" link opening the page of the step and closing the walkthrough, no link on steps that are not about a page, the steps being in the same order as the sidebar, and the text of the other steps being hidden. - `stepForPath` starts on the step for the current page, and at the beginning on pages without a step. ### Backend tests @@ -286,6 +286,7 @@ Saving the profile is debounced by 500 ms, and the text is also saved at once wh - The page behind is grayed out, and Tab never reaches it while the walkthrough is open. - The ? button opens the walkthrough at the step for the current page, and the "Go to" link opens that page and closes the walkthrough. - The language button in the walkthrough changes the language, while the walkthrough stays open on the same step. +- The walkthrough box keeps the same width and height on every step. - The hint about the ☰ menu button is only shown on mobile. **API tests:** diff --git a/e2e/helpers/names.ts b/e2e/helpers/names.ts index 8422e081..c4e1113a 100644 --- a/e2e/helpers/names.ts +++ b/e2e/helpers/names.ts @@ -63,7 +63,7 @@ export const names = { // Hidden text on a chip on a plant card that matches a saved preference matchesPreferences: /matches your saved preferences|matcher dine lagrede preferanser/i, - editProfile: /^(edit profile|endre profil)$/i, + editProfile: /^(edit profile|rediger profil)$/i, nameField: /write your name|skriv ditt navn/i, descriptionField: /write something about you|skriv noe om deg selv/i, // "Profile picture: " diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index 56224e61..40ee4d9f 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -79,7 +79,7 @@ const BOUNDARY_SELECTORS = [ ".reload-button", ".sidebar-button", ".help-button", - ".walkthrough__button", + ".walkthrough-button", ".plant-preferences button", ".plant-owner-test-option", ".plant-owner-test-suggestion-list button", @@ -94,7 +94,7 @@ const ICON_SELECTORS = [ ".swipe-button:not(:disabled)", ".info-button", ".add-match-button", - ".walkthrough__close", + ".walkthrough-close", // The SVG in the theme button, measured against the button behind it ".theme-icon", ]; @@ -398,7 +398,7 @@ for (const theme of THEMES) { test("Profile with the edit tab open", async ({ page }) => { await page.goto("#/profile"); await page - .getByRole("button", { name: /edit profile|endre profil/i }) + .getByRole("button", { name: /edit profile|rediger profil/i }) .click(); await expect(page.locator("#profile-name")).toBeVisible(); await setTheme(page, theme); @@ -469,7 +469,7 @@ for (const theme of THEMES) { // The buttons at the bottom of the sidebar must be possible to scroll to for (const button of await page - .locator(".sidebar__footer button") + .locator(".sidebar-footer button") .all()) { await button.scrollIntoViewIfNeeded(); await expect(button).toBeInViewport(); diff --git a/e2e/uiWalkthrough.spec.ts b/e2e/uiWalkthrough.spec.ts index 69ce39cd..d36e1b01 100644 --- a/e2e/uiWalkthrough.spec.ts +++ b/e2e/uiWalkthrough.spec.ts @@ -59,7 +59,7 @@ test("the help button opens the walkthrough at the current page, and Go to chang await page.goto("#/explorePlants"); await page.getByRole("button", { name: names.openGuide }).click(); - await expect(stepCounter(page)).toHaveText(/3 (of|av) 7/); + await expect(stepCounter(page)).toHaveText(/4 (of|av) 7/); await page.keyboard.press("ArrowRight"); await page @@ -68,7 +68,7 @@ test("the help button opens the walkthrough at the current page, and Go to chang .click(); await expect(page.getByRole("dialog")).toBeHidden(); - await expect(page).toHaveURL(/#\/myMatches$/); + await expect(page).toHaveURL(/#\/plantOwnerTest$/); }); test("the language button in the walkthrough changes the language and keeps the walkthrough open", async ({ @@ -102,3 +102,20 @@ test("the hint about the menu button is only shown on small screens", async ({ if (isMobile) await expect(hint).toBeVisible(); else await expect(hint).toBeHidden(); }); + +test("the walkthrough box keeps the same size on every step", async ({ + page, +}) => { + await page.goto(""); + const dialog = page.getByRole("dialog"); + await expect(stepCounter(page)).toHaveText(/1 av 7/); + const first = await dialog.boundingBox(); + + for (let step = 2; step <= 7; step++) { + await page.keyboard.press("ArrowRight"); + await expect(stepCounter(page)).toHaveText(new RegExp(`${step} av 7`)); + const box = await dialog.boundingBox(); + expect(box?.width).toBe(first?.width); + expect(box?.height).toBe(first?.height); + } +}); diff --git a/frontend/index.html b/frontend/index.html index 0440c963..387cdd7a 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,7 +2,6 @@ - I <3 plants import("./pages/explorePlants/ExplorePlantsPage.tsx"), + () => import("./pages/explorePlants/ExplorePlantsPage"), ); -const MyMatchesPage = lazy(() => import("./pages/myMatches/MyMatchesPage.tsx")); -const ProfilePage = lazy(() => import("./pages/profile/ProfilePage.tsx")); +const MyMatchesPage = lazy(() => import("./pages/myMatches/MyMatchesPage")); +const ProfilePage = lazy(() => import("./pages/profile/ProfilePage")); const PlantOwnerTestPage = lazy( - () => import("./pages/plantOwnerTest/PlantOwnerTestPage.tsx"), + () => import("./pages/plantOwnerTest/PlantOwnerTestPage"), ); -const NotFoundPage = lazy(() => import("./pages/notFound/NotFoundPage.tsx")); +const NotFoundPage = lazy(() => import("./pages/notFound/NotFoundPage")); // eslint-disable-next-line react-refresh/only-export-components export const ROUTES = { diff --git a/frontend/src/components/heartIcon/HeartIcon.tsx b/frontend/src/components/heartIcon/HeartIcon.tsx new file mode 100644 index 00000000..e5a38bab --- /dev/null +++ b/frontend/src/components/heartIcon/HeartIcon.tsx @@ -0,0 +1,23 @@ +type HeartIconProps = { + className?: string; +}; + +// A filled heart drawn in SVG. It takes the text color (currentColor) and the +// font size (1em), so it fits in with the text around it. +// Hidden from screen readers, since the button around it has its own label. +export default function HeartIcon({ className }: HeartIconProps) { + return ( + + ); +} diff --git a/frontend/src/components/matchButton/MatchButton.css b/frontend/src/components/matchButton/MatchButton.css index bd2e06a7..64722382 100644 --- a/frontend/src/components/matchButton/MatchButton.css +++ b/frontend/src/components/matchButton/MatchButton.css @@ -31,7 +31,7 @@ visibility: visible; } -/* A filled dark pink button with a white flower (add) or X (remove) */ +/* A filled dark pink button with a white heart (add) or X (remove) */ .add-match-button { width: 56px; height: 56px; diff --git a/frontend/src/components/matchButton/MatchButton.tsx b/frontend/src/components/matchButton/MatchButton.tsx index 26b52695..bed291ae 100644 --- a/frontend/src/components/matchButton/MatchButton.tsx +++ b/frontend/src/components/matchButton/MatchButton.tsx @@ -1,4 +1,5 @@ import "./MatchButton.css"; +import HeartIcon from "../heartIcon/HeartIcon"; type MatchButtonProps = { isMatched: boolean; @@ -8,7 +9,7 @@ type MatchButtonProps = { className?: string; }; -// The round button on a plant card that adds the plant to My Matches (✿), or +// The round button on a plant card that adds the plant to My Matches (heart), or // removes it if it is already there (✖). It looks the same on every page. // Placed next to the card, not inside it, so there are no nested buttons. export default function MatchButton({ @@ -33,7 +34,7 @@ export default function MatchButton({ onClick={onClick} aria-label={label} > - {isMatched ? "✖" : "✿"} + {isMatched ? "✖" : }