diff --git a/README.md b/README.md index f7b825a4..f3fbda33 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ http://it2810-03.idi.ntnu.no/project2/ - **Plant Match:** Plants matching the most preferences come first, otherwise the order is random. The deck is kept while the user visits other pages, so they can continue where they left off. - **My Matches:** Collects liked plants from both Plant Match and Explore Plants. The user only stores plant ids, and the list is fetched one page at a time, so responses do not grow with the number of matches. - **Explore Plants:** Search, filtering, sorting and pagination run in the backend, so the frontend only receives one page at a time, whatever the size of the collection. The state is kept in the URL, so a view survives a refresh and can be shared as a link. Each filter value shows how many plants it would give, and values that would give none can't be chosen, so filtering never ends in an empty list. +- **Walkthrough:** A short guide opens on the first visit and explains what the user can do on each page. It can be reopened at any time with the ? button, starts at the current page (or at the welcome step on the home page), links to each page and lets the user change language without closing it. ## Tech stack @@ -61,7 +62,7 @@ cd T03-Project-2 npm run install:all ``` -This installs the dependencies for the repo root, `backend` and `frontend`, which each have their own `package.json`. +This installs the dependencies for the repo root, `backend` and `frontend`, which each have their own `package.json`. To install exactly the versions in the lock files instead, as GitHub Actions does, run `npm ci && npm ci --prefix backend && npm ci --prefix frontend`. `npm ci` only installs the dependencies and does not run any tests (see [Testing](#testing)). ### 2. Create the backend `.env` file (in the VS Code terminal) @@ -127,6 +128,8 @@ npm run test:backend npm run test:e2e ``` +`npm run test:all` runs all three after each other, and `npm run ci:all` first does a clean install (`npm ci`) in the root, backend and frontend, and then runs all the tests. Only run one e2e test run at a time, since all the e2e tests share the same test database and servers. + The first time you run the e2e tests, install the browser with `npx playwright install chromium`. ### Test coverage diff --git a/docs/architecture.md b/docs/architecture.md index 60be1300..636749c5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ Perenual API → seedDataFetch.js ─┐ │ GraphQL over HTTP (/graphql) │ Frontend: React + Apollo Client - (localStorage: userId, theme, language, + (localStorage: userId, theme, language, walkthroughSeen, URL: Explore state, sessionStorage: My Matches sort, Plant Match deck) ``` @@ -53,7 +53,11 @@ The frontend is built with React and TypeScript (Vite). - **Error messages:** `ErrorMessageProvider` (`context/ErrorMessageContext.tsx`) wraps the app and makes `showError()` available through `useErrorMessage()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails. - **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text). `useExploreParams` keeps the Explore search, filters, sort order and page in the URL, and sends the user back to page 1 when the search, a filter or the sort order changes. It uses `useUrlParams`, which reads the page number and updates the URL (with React Router's `useSearchParams`). `useSessionState` stores state in `sessionStorage`, for example the sort order on My Matches. - `usePlantDeck` keeps the remaining Plant Match cards in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored. -- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (✿) or removes it (✖), and `ErrorMessage` shows a short error message. The components take already translated texts, so they can be used on other pages. +- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (✿) or removes it (✖), `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages. +- **Walkthrough:** The guide for new users is in `components/walkthrough/`, and is made up of three parts: + - **The steps are data:** `walkthroughSteps.ts` lists the steps in order. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. 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). - **Shared types:** `Plant`, `User` and `Preference` are defined in `types/`. @@ -211,14 +215,14 @@ MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be r ## Where state is kept -| Where | What | Why | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | -| `localStorage` | The user id (`userId`), the theme (`theme`) and the language (`language`) | Lets the browser find its user again on the next visit without a login, and keeps the chosen theme and language between visits | -| URL parameters | Explore search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`) via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | -| `sessionStorage` | The sort order on My Matches (`myMatches.sort`) and the cards left on Plant Match (`plantMatch.deck`) | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | -| Apollo in-memory cache | Query results (plants and the current user) | Avoids asking the backend again for data the app already has, and keeps all pages in sync | -| React state | Short-lived UI state, such as the current plant on the match page and unsaved profile text | Only matters while the component is shown | +| Where | What | Why | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | +| `localStorage` | The user id (`userId`), the theme (`theme`), the language (`language`) and whether the walkthrough has been seen (`walkthroughSeen`) | Lets the browser find its user again on the next visit without a login, keeps the chosen theme and language between visits, and only opens the walkthrough by itself on the first visit | +| URL parameters | Explore search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`) via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | +| `sessionStorage` | The sort order on My Matches (`myMatches.sort`) and the cards left on Plant Match (`plantMatch.deck`) | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | +| Apollo in-memory cache | Query results (plants and the current user) | Avoids asking the backend again for data the app already has, and keeps all pages in sync | +| React state | Short-lived UI state, such as the current plant on the match page and unsaved profile text | Only matters while the component is shown | User data used to be stored in `localStorage`. `UserProvider` now removes the old keys (`plantPreferences`, `matchedPlants`, `profileName`, `description`, `profileAvatar`) on start-up, so old data does not lie around in the browser. @@ -226,7 +230,7 @@ When the app starts, `UserProvider` reads `userId` from `localStorage` and runs ## Design choices made for scalability -- **Use of MongoDB over browser storage.** All user data (profile, preferences and matches) is stored in MongoDB. The browser only keeps small values that do not need the server: `localStorage` holds the `userId` and the chosen theme and language, and `sessionStorage` holds the sort order on My Matches and the cards left on Plant Match (see [Where state is kept](#where-state-is-kept)). Browser storage is limited to about 5 MB per site and only exists in that one browser, where the server cannot use it. By storing user data in MongoDB, there is no practical limit to how many plants a user can save, more user information can easily be added later, and the data can be used by the backend. +- **Use of MongoDB over browser storage.** All user data (profile, preferences and matches) is stored in MongoDB. The browser only keeps small values that do not need the server: `localStorage` holds the `userId`, the chosen theme and language and whether the walkthrough has been seen, and `sessionStorage` holds the sort order on My Matches and the cards left on Plant Match (see [Where state is kept](#where-state-is-kept)). Browser storage is limited to about 5 MB per site and only exists in that one browser, where the server cannot use it. By storing user data in MongoDB, there is no practical limit to how many plants a user can save, more user information can easily be added later, and the data can be used by the backend. - **Plant data does not depend on Perenual.** The number of users does not affect the number of requests to Perenual, since the app only reads from our own database. It also makes it possible to fetch more plants later if one wants to. - **The server does the heavy work.** Searching, filtering, sorting and pagination run as MongoDB queries, so the frontend only receives one page of plants at a time (12 by default) together with the total count. This works the same whether the collection has a hundred or many thousand plants, and keeps responses small so pages load faster. - **Index for sorting by name.** Sorting by name (A–Z, the default, and Z–A) uses an index on `commonName` and `_id`, created by `indexes.ts` when the server starts. The plants are then read in order from the index instead of being sorted in memory, which matters more the larger the collection gets. Lookups by id (users, matches and plants) already use the `_id` index that MongoDB creates on every collection. @@ -298,7 +302,7 @@ T03-Project-2/ ├── frontend/ │ ├── src/ │ │ ├── assets/ # Static images -│ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file +│ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file (walkthrough/ has the guide and its steps) │ │ ├── context/ # UserProvider and useUser() for the current user, ErrorMessageProvider and useErrorMessage() for error messages │ │ ├── graphql/ # All GraphQL queries, mutations and fragments, grouped by domain (fragments/, plants/, user/) │ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck, useDismissibleTooltip) diff --git a/docs/quality.md b/docs/quality.md index 45b6e20a..0e9cc443 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -12,7 +12,7 @@ This document describes how we have worked to ensure the quality of the applicat ### Continuous integration -GitHub Actions ([.github/workflows/ci.yml](../.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, runs lint, tests and a build for both the backend and the frontend, and runs the end-to-end tests. This means a pull request that breaks the formatting, lint, a test or the build is caught before it is merged, instead of being found later on `main`. +GitHub Actions ([.github/workflows/ci.yml](../.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, runs lint, tests and a build for both the backend and the frontend, and runs the end-to-end tests. This means a pull request that breaks the formatting, lint, a test or the build is caught before it is merged, instead of being found later on `main`. Each job first installs the dependencies with `npm ci`, which installs exactly the versions in `package-lock.json`, and then runs the checks as separate steps, so it is clear which step failed. `npm run ci:all` does the same install and runs all the tests locally (see [Run the tests](tests.md#run-the-tests)), but not the formatting check, lint and build, which are run with `npm run format:check`, `npm run lint` and `npm run build`. ## Work practices @@ -43,6 +43,12 @@ GitHub Actions ([.github/workflows/ci.yml](../.github/workflows/ci.yml)) runs on - As part of our code review process, team members checked out pull requests locally and tested the new functionality before approving changes. This helped us verify that changes worked as expected in practice, rather than relying solely on code review. +### User testing and the walkthrough + +User testing showed that new users did not get a clear overview of what the app is for and what they can do on each page. + +Based on this, we added a walkthrough that gives a clear overview of the app and its purpose. It opens by itself on the first visit and explains each page in a short step with a "Go to" link to the page. It only opens by itself once, so it does not get in the way of users who come back. It can be opened again at any time with the ? button in the header, and then starts at the page the user is on, so it also works as help for the current page. The language can be changed inside the walkthrough, so users who do not read Norwegian can switch to English before reading on. + ## Accessibility The app includes the following accessibility features: @@ -51,6 +57,8 @@ The app includes the following accessibility features: - **Keyboard controls:** Navigation uses links, and actions use native buttons. Sidebar links, pagination, sorting controls and avatar options have explicit focus styles. Plant Match instructions are also shown when their control receives focus. The sort menu can be used with the arrow keys, Home and End, focus moves into the menu when it opens, and back to the sort button when it is closed with Escape or an option is chosen. Tab leaves the menu and closes it. On mobile, the sidebar is hidden from the keyboard and screen readers while it is closed. Focus moves into it when it opens, Escape closes it, and focus then goes back to the menu button. The "i" help texts on Plant Match and Profile are linked to their button with `aria-describedby`, and can be hidden with Escape without moving the mouse or focus. A "Skip to content" link is the first thing keyboard users reach on every page, so they can jump past the sidebar. When the user goes to another page, focus moves to the start of the page, like when a normal web page loads, so the next Tab shows the skip link again. The app uses HashRouter, so the link moves focus with JavaScript instead of a normal `#` link, which would have changed the route. +- **Walkthrough:** The walkthrough is a native `` opened with `showModal()`, so the browser grays out the page behind, keeps focus inside the dialog and closes it with Escape. The dialog is named by the step title and described by the step text (`aria-labelledby`, `aria-describedby`), and "Step 2 of 7" is in an `aria-live` region, so screen readers announce the new step. The arrow keys move between steps, focus starts on the Next button, and when the walkthrough closes, focus goes back to the ? button that opened it. The pictures are decorative and have an empty `alt`, since the title says what the step is about. + - **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. @@ -97,6 +105,8 @@ We considered sustainability through both our design choices and our approach to - **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. +- **Walkthrough:** The walkthrough was added after user testing showed that new users did not get a clear overview of the app (see [User testing and the walkthrough](#user-testing-and-the-walkthrough)). Each step uses one of the avatars from the profile page, and the Next and Back buttons are pink, so the guide looks like the rest of the app. The steps are kept short, with one page per step, so users can read through them quickly or close the guide and come back to it later. + - **Page not found:** Unknown addresses show a 404 page instead of a blank page. It links back to Plant Match, and tells the user they can choose another page in the sidebar on desktop or the menu on mobile, so the hint matches the navigation they actually see. - **No login:** The user id is stored in the browser, so the profile and matches belong to that browser and cannot be reached from other devices, and anyone who knows a user id can change that user, since the id is sent with every request. Login would solve both and is a possible next step. We actively chose not to implement login, because we felt it was more important that the app is quick to start using than that the data can be reached from several devices. diff --git a/docs/tests.md b/docs/tests.md index 0b4ca493..4f340b14 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -47,12 +47,18 @@ Run from the root folder: npm run test:frontend # component tests npm run test:backend # backend tests npm run test:e2e # end-to-end and API tests +npm run test:all # backend, frontend and e2e tests, one after the other +npm run ci:all # clean install (npm ci) in root, backend and frontend, then test:all npm run test:e2e:ui # e2e tests in Playwright's UI mode, step by step npm run test:e2e:headed # desktop e2e tests in a visible browser npx playwright test --project=mobile --headed # the same on mobile (Pixel 7) npx playwright show-report # HTML report with traces of failed e2e tests ``` +`npm ci` on its own only installs the dependencies from `package-lock.json` and does not run any tests. Each folder has its own lock file, so `npm ci` in the root does not install `backend` or `frontend`. `npm run ci:all` does the install and the tests in one command. Stop `npm run dev` first, since `npm ci` deletes `node_modules`. + +Only run one e2e test run at a time. All e2e tests share one test database and the servers on ports 4173 and 3002, and Playwright reuses servers that are already running locally. Two runs at the same time therefore empty each other's database, and when one run ends it stops the servers the other run uses, so the tests fail with `ERR_CONNECTION_REFUSED`. + ### If the tests do not start If the tests stop with `Cannot find native binding` or `Cannot find module '@rolldown/binding-...'`, @@ -111,6 +117,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `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. + - The walkthrough opens on the first visit and is not shown again after it is closed, focus goes back to the ? button, and the ? button opens it at the step for the current page. - `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. - `ExplorePlantsPage.test.tsx` @@ -169,6 +176,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - The ids of the matched plants, that My Matches is removed from the cache when a match is added or removed, 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. +- `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. + - `stepForPath` starts on the step for the current page, and at the beginning on pages without a step. ### Backend tests @@ -232,6 +242,7 @@ The UI tests find elements the way a user or a screen reader would: by role, lab | Accessibility on all pages | – | `uiAccessibility` | | Pictures load | – | `uiImages` | | Preferences decide the order in PlantMatch | – | `uiPreferences` | +| Walkthrough | – | `uiWalkthrough` | **ExplorePlants (`uiExplorePlants`):** one continuous user journey that tests pagination, filtering, search, the detail view, sorting and reset, and that changing a filter on page 2 takes the user back to page 1. @@ -254,6 +265,14 @@ Saving the profile is debounced by 500 ms, and the text is also saved at once wh - The pictures from the plant owner test are only shown after the test is finished, so the test sets each result as profile picture through the API, reloads the profile page and checks the picture shown there. - The placeholder is a CSS background, so the test reads the URL the browser uses from the card's `::before` element and loads it as an image. +**Walkthrough (`uiWalkthrough`):** these tests start as new users with empty storage. The other UI tests start as users who have already seen the walkthrough (`storageState` in `playwright.config.ts`), since it would otherwise cover the page they test. + +- The walkthrough opens on the first visit, closes with Escape and is not shown again after a reload. +- 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 hint about the ☰ menu button is only shown on mobile. + **API tests:** - **explorePlants**: default sorting and page size, `offset`, case-insensitive search, regex characters treated as plain text, the watering, care level and sunlight filters, the sort orders, and that plants without a care level are sorted last. @@ -265,7 +284,7 @@ Saving the profile is debounced by 500 ms, and the text is also saved at once wh `uiAccessibility.spec.ts` runs **axe** through `@axe-core/playwright` against WCAG 2.1 level A and AA, the level required for the public sector in Norway. It checks: - all six pages (PlantMatch, ExplorePlants, MyMatches, Profile, PlantOwnerTest and the 404 page), in both light and dark mode, since colour contrast has to meet the WCAG 2.1 requirements in both themes -- content that only appears after an interaction: a flipped plant card, the edit tab on the profile page, MyMatches with a matched plant, and the result of the plant owner test +- content that only appears after an interaction: a flipped plant card, the edit tab on the profile page, MyMatches with a matched plant, the result of the plant owner test, and the open walkthrough The tests run on both desktop and mobile, since the layout, and the elements that are visible, differ between them. A failing test lists each element that breaks a rule, with axe's explanation (for contrast: the colours and the ratio). diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index f17dbac6..c13460d6 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -78,6 +78,8 @@ const BOUNDARY_SELECTORS = [ ".add-match-button", ".reload-button", ".sidebar-button", + ".help-button", + ".walkthrough__button", ".plant-preferences button", ".plant-owner-test-option", ".sort-button", @@ -91,6 +93,7 @@ const ICON_SELECTORS = [ ".swipe-button:not(:disabled)", ".info-button", ".add-match-button", + ".walkthrough__close", // The SVG in the theme button, measured against the button behind it ".theme-icon", ]; @@ -444,6 +447,16 @@ for (const theme of THEMES) { await checkAccessibility(page); }); + test("Walkthrough open", async ({ page }) => { + await page.goto(""); + await expect(page.locator(".plant-card-front")).toBeVisible(); + await setTheme(page, theme); + await page.locator(".help-button").click(); + await expect(page.getByRole("dialog")).toBeVisible(); + // The grayed out page behind is not checked, only the walkthrough + await checkAccessibility(page, ".walkthrough"); + }); + test("Sidebar open, with the language and theme buttons reachable", async ({ page, }) => { diff --git a/e2e/uiWalkthrough.spec.ts b/e2e/uiWalkthrough.spec.ts new file mode 100644 index 00000000..984a257e --- /dev/null +++ b/e2e/uiWalkthrough.spec.ts @@ -0,0 +1,97 @@ +import { test, expect } from "@playwright/test"; + +// The other UI tests start as users who have seen the walkthrough +// (playwright.config.ts). These start as new users, with empty storage. +test.use({ storageState: { cookies: [], origins: [] } }); + +test("the walkthrough opens for new users and not after it is closed", async ({ + page, +}) => { + await page.goto(""); + const dialog = page.getByRole("dialog"); + await expect(dialog).toBeVisible(); + await expect(page.locator(".walkthrough__progress")).toHaveText( + /1 (of|av) 7/, + ); + + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + + await page.reload(); + await expect(page.locator(".plant-card-front")).toBeVisible(); + await expect(dialog).toBeHidden(); +}); + +test("the page behind is grayed out and can't be used while the walkthrough is open", async ({ + page, +}) => { + await page.goto(""); + await expect(page.getByRole("dialog")).toBeVisible(); + + const backdrop = await page + .locator(".walkthrough") + .evaluate((el) => getComputedStyle(el, "::backdrop").backgroundColor); + expect(backdrop).not.toBe("rgba(0, 0, 0, 0)"); + + // Tab never reaches the page behind. The browser may move focus to its own + // address bar after the last button, then the page reports body as focused. + for (let i = 0; i < 8; i++) { + await page.keyboard.press("Tab"); + const focusOnPageBehind = await page.evaluate(() => { + const el = document.activeElement; + return !!el && el !== document.body && !el.closest(".walkthrough"); + }); + expect(focusOnPageBehind).toBe(false); + } +}); + +test("the help button opens the walkthrough at the current page, and Go to changes page", async ({ + page, +}) => { + await page.goto(""); + await page.keyboard.press("Escape"); + + await page.goto("#/explorePlants"); + await page.locator(".help-button").click(); + await expect(page.locator(".walkthrough__progress")).toHaveText( + /3 (of|av) 7/, + ); + + await page.keyboard.press("ArrowRight"); + await page.locator(".walkthrough__go-to").click(); + + await expect(page.getByRole("dialog")).toBeHidden(); + await expect(page).toHaveURL(/#\/myMatches$/); +}); + +test("the language button in the walkthrough changes the language and keeps the walkthrough open", async ({ + page, +}) => { + await page.goto(""); + const dialog = page.getByRole("dialog"); + await page.keyboard.press("ArrowRight"); + await expect(page.locator(".walkthrough__progress")).toHaveText(/2 av 7/); + + await dialog.getByRole("button", { name: "EN - Switch to English" }).click(); + + await expect(dialog).toBeVisible(); + await expect(page.locator(".walkthrough__progress")).toHaveText(/2 of 7/); + await expect(page.locator("html")).toHaveAttribute("lang", "en"); + + await dialog.getByRole("button", { name: "NO - Bytt til norsk" }).click(); + await expect(page.locator(".walkthrough__progress")).toHaveText(/2 av 7/); +}); + +test("the hint about the menu button is only shown on small screens", async ({ + page, + isMobile, +}) => { + await page.goto(""); + // The last step is about language and theme, in the menu + for (let i = 0; i < 6; i++) await page.keyboard.press("ArrowRight"); + await expect(page.locator(".walkthrough__progress")).toHaveText(/7 av 7/); + + const hint = page.getByText("På små skjermer åpner du menyen med ☰."); + if (isMobile) await expect(hint).toBeVisible(); + else await expect(hint).toBeHidden(); +}); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 37257b16..38cad29d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -6,6 +6,29 @@ import Sidebar from "./components/sidebar/Sidebar"; import Header from "./components/header/Header"; import AppRoutes from "./AppRoutes.tsx"; import { ErrorMessageProvider } from "./context/ErrorMessageContext.tsx"; +import Walkthrough from "./components/walkthrough/Walkthrough.tsx"; +import { stepForPath } from "./components/walkthrough/walkthroughSteps.ts"; + +// Remembers that the user has seen the walkthrough, so it only opens by +// itself on the first visit +const WALKTHROUGH_SEEN_KEY = "walkthroughSeen"; + +function hasSeenWalkthrough() { + try { + return localStorage.getItem(WALKTHROUGH_SEEN_KEY) === "true"; + } catch { + // Without storage the walkthrough would open on every page load + return true; + } +} + +function markWalkthroughSeen() { + try { + localStorage.setItem(WALKTHROUGH_SEEN_KEY, "true"); + } catch { + // The walkthrough still closes, it just isn't remembered + } +} function App() { const { t } = useTranslation(); @@ -26,6 +49,33 @@ function App() { pageStartRef.current?.focus({ preventScroll: true }); }, [pathname]); + // The walkthrough opens by itself on the first visit, starting at the + // welcome step. The help button opens it at the step for the current page. + const [walkthrough, setWalkthrough] = useState(() => ({ + isOpen: !hasSeenWalkthrough(), + startStep: 0, + })); + const helpButtonRef = useRef(null); + const returnFocusToHelp = useRef(false); + + const openWalkthrough = () => { + setWalkthrough({ isOpen: true, startStep: stepForPath(pathname) }); + }; + + const closeWalkthrough = (returnFocus: boolean) => { + markWalkthroughSeen(); + returnFocusToHelp.current = returnFocus; + setWalkthrough((current) => ({ ...current, isOpen: false })); + }; + + // Focus goes back to the help button when the walkthrough closes. Done in + // an effect, since the page can't get focus while the dialog is still open. + useEffect(() => { + if (walkthrough.isOpen || !returnFocusToHelp.current) return; + returnFocusToHelp.current = false; + helpButtonRef.current?.focus(); + }, [walkthrough.isOpen]); + const sidebarRef = useRef(null); const menuButtonRef = useRef(null); @@ -82,8 +132,17 @@ function App() { menuButtonRef={menuButtonRef} isSidebarOpen={isSidebarOpen} onOpenSidebar={openSidebar} + onOpenWalkthrough={openWalkthrough} + helpButtonRef={helpButtonRef} /> + {walkthrough.isOpen && ( + + )} + {/* tabIndex -1 lets the skip link focus it, without adding it to the tab order */}
void; menuButtonRef?: Ref; + onOpenWalkthrough?: () => void; + helpButtonRef?: Ref; }; // Maps each route path to the translation key used for its title @@ -23,6 +25,8 @@ export default function Header({ isSidebarOpen, onOpenSidebar, menuButtonRef, + onOpenWalkthrough, + helpButtonRef, }: HeaderProps) { const { t } = useTranslation(); const { pathname } = useLocation(); @@ -45,6 +49,19 @@ export default function Header({

{t(titleKey)}

+ + {onOpenWalkthrough && ( + + )} ); } diff --git a/frontend/src/components/matchButton/MatchButton.css b/frontend/src/components/matchButton/MatchButton.css index 694786af..3a679fb0 100644 --- a/frontend/src/components/matchButton/MatchButton.css +++ b/frontend/src/components/matchButton/MatchButton.css @@ -56,10 +56,6 @@ border-color: var(--text-light); } -[data-theme="dark"] .add-match-button:focus-visible { - box-shadow: 0 0 0 3px var(--text-light); -} - .add-match-button:hover { transform: scale(1.1); } @@ -69,6 +65,10 @@ box-shadow: 0 0 0 3px var(--dark-pink); } +[data-theme="dark"] .add-match-button:focus-visible { + box-shadow: 0 0 0 3px var(--text-light); +} + @media (max-width: 767px) { .add-match-button { width: 35px; diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index e4c74e84..58e4fa91 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -104,6 +104,10 @@ overflow: hidden; } +[data-theme="dark"] .plant-card-back { + border: 2px solid var(--dark-green); +} + .plant-card-front { background: var(--card-front); } @@ -245,13 +249,8 @@ margin: 0; padding: 20px 18px 4px; - display: flex; - flex-wrap: wrap; - justify-content: flex-start; align-items: center; align-content: flex-start; - - gap: 8px; } .plant-card-hint { @@ -261,7 +260,6 @@ width: 100%; border: none; background: none; - font-family: inherit; cursor: pointer; margin: auto 0 0; @@ -440,11 +438,33 @@ overflow-wrap: anywhere; } + /* The chips are shown two by two, with the same width */ .plant-card-front .plant-card-preferences { + display: grid; + grid-template-columns: 1fr 1fr; padding: 18px 12px 4px; gap: 6px; } + /* The columns are too narrow for the longest texts on one line (for example + "middels vannbehov"), so the text goes over two lines instead of being + cut off. The grid gives both chips in a row the same height. */ + .plant-card-flipper .plant-preference-chip { + width: 100%; + padding: 0.45em 0.6em; + text-align: center; + + display: flex; + align-items: center; + justify-content: center; + + white-space: normal; + text-overflow: clip; + overflow-wrap: anywhere; + text-wrap: balance; + line-height: 1.2; + } + .plant-card-hint { padding: 16px var(--card-hint-space) 26px 14px; font-size: clamp(0.8rem, 4.8cqw, 0.9rem); diff --git a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css index 5751786a..9395914b 100644 --- a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css +++ b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css @@ -13,15 +13,6 @@ display: flex; } -.plant-card-preferences .visually-hidden { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip: rect(0 0 0 0); - white-space: nowrap; -} - .plant-preference-chip { flex-shrink: 0; @@ -42,6 +33,5 @@ .plant-preference-chip.is-match { background: var(--dark-pink); color: var(--text-light); - font-weight: 700; transform: scale(1.05); } diff --git a/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx b/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx index 0615a112..a7ca27c7 100644 --- a/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx +++ b/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx @@ -1,4 +1,5 @@ import { useTranslation } from "react-i18next"; +import "./SidebarButton.css"; // The chosen language is saved in localStorage by i18n/index.ts when it // changes, so the switcher only reads and changes the language in i18next. diff --git a/frontend/src/components/walkthrough/Walkthrough.css b/frontend/src/components/walkthrough/Walkthrough.css new file mode 100644 index 00000000..f12909dd --- /dev/null +++ b/frontend/src/components/walkthrough/Walkthrough.css @@ -0,0 +1,178 @@ +/* The pop-up box. padding is on the content, so a click on the dialog + element itself always means a click on the gray area outside the box. */ +.walkthrough { + width: min(460px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + padding: 0; + border: 1px solid var(--border-soft); + border-radius: 24px; + background-color: var(--light-background); + color: var(--text-dark); + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.25); +} + +/* Grays out the page behind the walkthrough */ +.walkthrough::backdrop { + background-color: rgba(30, 30, 30, 0.6); +} + +.walkthrough__content { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + padding: 36px 32px 24px; + text-align: center; +} + +.walkthrough__close { + position: absolute; + top: 12px; + right: 14px; + width: 44px; + height: 44px; + border: none; + border-radius: 50%; + background: none; + color: var(--text-dark); + font-size: 32px; + line-height: 1; + cursor: pointer; +} + +.walkthrough__close:hover { + background-color: var(--light-green); +} + +/* The avatar pictures are a green circle that is cut off at the edges of the + square image, so they are cropped to a circle, like on the profile page */ +.walkthrough__image { + width: 120px; + height: 120px; + object-fit: cover; + border-radius: 50%; +} + +.walkthrough__progress { + margin: 16px 0 4px; + color: var(--pink-text); + font-size: 16px; + letter-spacing: 0.5px; +} + +.walkthrough__title { + margin: 0 0 12px; + font-size: 30px; + font-weight: 400; +} + +.walkthrough__text { + margin: 0 0 12px; + font-size: 18px; + line-height: 1.5; +} + +/* Only shown on small screens, see the media query at the bottom */ +.walkthrough__mobile-hint { + display: none; +} + +.walkthrough__reminder { + font-style: italic; +} + +.walkthrough__go-to { + margin: 4px 0 8px; + padding: 8px 4px; + color: var(--dark-green); + font-size: 18px; + text-underline-offset: 4px; +} + +.walkthrough__dots { + display: flex; + gap: 8px; + margin: 16px 0 20px; + padding: 0; + list-style: none; +} + +.walkthrough__dot { + width: 10px; + height: 10px; + border-radius: 50%; + background-color: var(--border-soft); +} + +.walkthrough__dot--active { + background-color: var(--dark-pink); +} + +.walkthrough__navigation { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + width: 100%; +} + +.walkthrough__step-buttons { + display: flex; + gap: 10px; +} + +.walkthrough__button { + min-width: 90px; + padding: 10px 18px; + border: 2px solid var(--dark-pink); + border-radius: 999px; + background-color: var(--dark-pink); + /* White has enough contrast on the pink in both light and dark mode */ + color: var(--text-light); + font-size: 16px; + cursor: pointer; +} + +.walkthrough__button--secondary { + background-color: transparent; + /* --pink-text instead of --dark-pink, which is too light on the dark background */ + color: var(--pink-text); +} + +.walkthrough__button:hover { + opacity: 0.85; +} + +.walkthrough button:focus-visible, +.walkthrough__go-to:focus-visible { + outline: 2px solid var(--dark-pink); + outline-offset: 2px; +} + +@media (max-width: 767px) { + .walkthrough__mobile-hint { + display: block; + } + + .walkthrough__content { + padding: 28px 20px 20px; + } + + .walkthrough__image { + width: 90px; + height: 90px; + } + + .walkthrough__title { + font-size: 26px; + } + + .walkthrough__text { + font-size: 16px; + } + + .walkthrough__button { + min-width: 0; + padding: 10px 14px; + } +} diff --git a/frontend/src/components/walkthrough/Walkthrough.tsx b/frontend/src/components/walkthrough/Walkthrough.tsx new file mode 100644 index 00000000..4b12a53d --- /dev/null +++ b/frontend/src/components/walkthrough/Walkthrough.tsx @@ -0,0 +1,160 @@ +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { useTranslation } from "react-i18next"; +import { Link, useLocation } from "react-router-dom"; +import LanguageSwitcher from "../sidebarButtons/LanguageSwitcher"; +import { walkthroughSteps } from "./walkthroughSteps"; +import "./Walkthrough.css"; + +type WalkthroughProps = { + startStep?: number; + onClose: (returnFocus: boolean) => void; +}; + +export default function Walkthrough({ + startStep = 0, + onClose, +}: WalkthroughProps) { + const { t } = useTranslation(); + const { pathname } = useLocation(); + const dialogRef = useRef(null); + const nextButtonRef = useRef(null); + const [stepIndex, setStepIndex] = useState(startStep); + + const step = walkthroughSteps[stepIndex]; + const isFirst = stepIndex === 0; + const isLast = stepIndex === walkthroughSteps.length - 1; + + useEffect(() => { + const dialog = dialogRef.current; + if (!dialog) return; + if (!dialog.open) dialog.showModal(); + nextButtonRef.current?.focus(); + return () => { + if (dialog.open) dialog.close(); + }; + }, []); + + const goBack = () => { + if (isFirst) return; + setStepIndex(stepIndex - 1); + if (stepIndex - 1 === 0) nextButtonRef.current?.focus(); + }; + + const goNext = () => { + if (isLast) onClose(true); + else setStepIndex(stepIndex + 1); + }; + + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === "ArrowRight" && !isLast) setStepIndex(stepIndex + 1); + if (e.key === "ArrowLeft") goBack(); + }; + + return ( + { + e.preventDefault(); + onClose(true); + }} + // A click on the gray area outside the box hits the dialog itself + onClick={(e) => { + if (e.target === e.currentTarget) onClose(true); + }} + > +
+ + + + +

+ {t("walkthrough.stepOf", { + step: stepIndex + 1, + total: walkthroughSteps.length, + })} +

+

+ {t(`walkthrough.steps.${step.id}.title`)} +

+

+ {t(`walkthrough.steps.${step.id}.text`)} +

+ {/* Hidden with CSS on large screens, where the sidebar is always shown */} + {step.hasMobileHint && ( +

+ {t(`walkthrough.steps.${step.id}.mobileHint`)} +

+ )} + {isLast && ( +

+ {t("walkthrough.reminder")} +

+ )} + + {step.route && ( + onClose(step.route === pathname)} + > + {t("walkthrough.goTo", { + page: t(`walkthrough.steps.${step.id}.title`), + })}{" "} + + + )} + + + +
+ +
+ {!isFirst && ( + + )} + +
+
+
+
+ ); +} diff --git a/frontend/src/components/walkthrough/walkthroughSteps.ts b/frontend/src/components/walkthrough/walkthroughSteps.ts new file mode 100644 index 00000000..dc724358 --- /dev/null +++ b/frontend/src/components/walkthrough/walkthroughSteps.ts @@ -0,0 +1,40 @@ +// The steps of the walkthrough that shows new users around the app. +// The text for each step is in translation.json under walkthrough.steps.. + +import { ROUTES } from "../../AppRoutes"; +import monstera from "../../assets/avatars/monstera.png"; +import pothos from "../../assets/avatars/pothos.png"; +import fern from "../../assets/avatars/fern.png"; +import anthurium from "../../assets/avatars/anthurium.png"; +import orchid from "../../assets/avatars/orchid.png"; +import succulent from "../../assets/avatars/succulent.png"; +import snakePlant from "../../assets/avatars/snakePlant.png"; + +export type WalkthroughStep = { + id: string; + image: string; + // The page the step is about. Steps without a route have no "Go to" link. + route?: string; + // Steps with a hint that is only shown on small screens, where the sidebar + // is hidden behind the ☰ button. The text is in walkthrough.steps..mobileHint + hasMobileHint?: boolean; +}; + +export const walkthroughSteps: WalkthroughStep[] = [ + { id: "welcome", image: monstera }, + { id: "plantMatch", image: pothos, route: ROUTES.plantMatch }, + { id: "explore", image: fern, route: ROUTES.explore }, + { id: "myMatches", image: anthurium, route: ROUTES.myMatches }, + { id: "profile", image: orchid, route: ROUTES.profile }, + { id: "plantOwnerTest", image: succulent, route: ROUTES.plantOwnerTest }, + { id: "settings", image: snakePlant, hasMobileHint: true }, +]; + +// The step to start on when the walkthrough is opened from a page, so the +// help button explains the page the user is on. Other pages start at the beginning. +// Plant Match is the home page, so it starts at the welcome step instead. +export function stepForPath(pathname: string) { + if (pathname === ROUTES.plantMatch) return 0; + const index = walkthroughSteps.findIndex((step) => step.route === pathname); + return Math.max(index, 0); +} diff --git a/frontend/src/context/UserContext.tsx b/frontend/src/context/UserContext.tsx index 72152d25..3204f713 100644 --- a/frontend/src/context/UserContext.tsx +++ b/frontend/src/context/UserContext.tsx @@ -14,6 +14,9 @@ import type { User } from "../types/User"; // The only user data kept in the browser. Everything else is in the database. const STORAGE_KEY = "userId"; +// How often to try loading the user again after an error +const RETRY_MS = 5000; + function readUserId(): string | null { try { return localStorage.getItem(STORAGE_KEY); @@ -67,13 +70,25 @@ export function UserProvider({ children }: { children: ReactNode }) { useEffect(removeLegacyKeys, []); - const { data, loading, error } = useQuery(GET_USER, { + const { data, loading, error, refetch } = useQuery(GET_USER, { variables: { userId: userId ?? "" }, // No id yet, so there is nothing to ask for skip: !userId, }); const [createUser] = useMutation(CREATE_USER); + // If the backend or database was down when the page loaded, keep trying, + // so the user shows up (and changes are shown) once it is back + useEffect(() => { + if (!error || !userId) return; + const retry = setInterval(() => { + refetch().catch(() => { + // Still down. Try again on the next tick. + }); + }, RETRY_MS); + return () => clearInterval(retry); + }, [error, userId, refetch]); + // Stops StrictMode (which runs effects twice) from creating two users const creating = useRef(false); diff --git a/frontend/src/hooks/useProfile.ts b/frontend/src/hooks/useProfile.ts index 9771fde9..fb1c80a3 100644 --- a/frontend/src/hooks/useProfile.ts +++ b/frontend/src/hooks/useProfile.ts @@ -71,7 +71,7 @@ export function useProfile() { const setProfilePicture = async (profilePicture: string) => { if (!userId) return false; try { - await updateProfile({ + const result = await updateProfile({ variables: { userId, profilePicture }, // Shows the new picture right away instead of waiting for the server optimisticResponse: { @@ -84,7 +84,8 @@ export function useProfile() { }, }, }); - return true; + // null means the user was not found in the database + return Boolean(result.data?.updateUserProfile); } catch { // Apollo rolls the picture back if the server fails return false; diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 171fcadd..83f5aced 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -115,7 +115,7 @@ "fern": "Fern", "orchid": "Orchid", "placeholderName": "Enter your name", - "placeholderAbout": "Something about you..." + "placeholderAbout": "Something about you" }, "plantCard": { "preferences": "Plant preferences", @@ -199,5 +199,46 @@ "backToPlantMatch": "Go to Plant Match", "orChooseInSidebar": "Or choose another page in the sidebar.", "orChooseInMenu": "Or choose another page in the menu." + }, + "walkthrough": { + "open": "Open guide", + "close": "Close guide", + "next": "Next", + "back": "Back", + "finish": "Finish", + "stepOf": "Step {{step}} of {{total}}", + "goTo": "Go to {{page}}", + "reminder": "You can open this guide again at any time with the ? button in the top right corner.", + "steps": { + "welcome": { + "title": "Welcome!", + "text": "I <3 Plants helps you find plants that suit you by letting you set preferences on your profile page, and through a fun matching page. Here is a brief tour of what you can do on each page." + }, + "plantMatch": { + "title": "Plant Match", + "text": "You are shown one plant at a time. Press ✿ if you like the plant and ✖ if you don't. Press the corner of the card to see how much water, sun and care the plant needs." + }, + "explore": { + "title": "Explore Plants", + "text": "Search for plants by name, filter on watering, sun and care level, and sort the results. Press ✿ next to a plant to add it to My Matches." + }, + "myMatches": { + "title": "My Matches", + "text": "All the plants you have liked are saved here. Sort them by date or name, and remove the ones you no longer want." + }, + "profile": { + "title": "Profile", + "text": "Add your name, a short description and an avatar. Choose your plant preferences, and the plants that match them are marked on the plant cards." + }, + "plantOwnerTest": { + "title": "Plant Owner Test", + "text": "Answer four questions to find out what kind of plant owner you are. You can use the result as your profile picture." + }, + "settings": { + "title": "Language and theme", + "text": "At the bottom of the menu you can switch between Norwegian and English, and between light and dark mode.", + "mobileHint": "On small screens, open the menu with ☰." + } + } } } diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index d63b81d3..9135b43e 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -115,7 +115,7 @@ "fern": "Bregne", "orchid": "Orkidé", "placeholderName": "Skriv inn navnet ditt", - "placeholderAbout": "Noe om deg..." + "placeholderAbout": "Noe om deg" }, "plantCard": { "preferences": "Plantepreferanser", @@ -199,5 +199,46 @@ "backToPlantMatch": "Gå til Plante-Matching", "orChooseInSidebar": "Eller velg en annen side i sidemenyen.", "orChooseInMenu": "Eller velg en annen side i menyen." + }, + "walkthrough": { + "open": "Åpne guide", + "close": "Lukk guiden", + "next": "Neste", + "back": "Tilbake", + "finish": "Ferdig", + "stepOf": "Steg {{step}} av {{total}}", + "goTo": "Gå til {{page}}", + "reminder": "Du kan åpne guiden igjen når som helst med ?-knappen øverst til høyre.", + "steps": { + "welcome": { + "title": "Velkommen!", + "text": "I <3 Plants hjelper deg å finne planter som passer deg gjennom å sette preferanser på profil siden og en gøy match side. Her er en kort omvisning i hva du kan gjøre på hver side." + }, + "plantMatch": { + "title": "Plante-Matching", + "text": "Du får se én plante om gangen. Trykk ✿ hvis du liker planten og ✖ hvis ikke. Trykk på hjørnet av kortet for å se hvor mye vann, sol og stell planten trenger." + }, + "explore": { + "title": "Utforsk Planter", + "text": "Søk etter planter på navn, filtrer på vanning, sol og stellbehov, og sorter resultatene. Trykk ✿ ved en plante for å legge den til i Mine Matches." + }, + "myMatches": { + "title": "Mine Matches", + "text": "Alle plantene du har likt blir lagret her. Sorter dem etter dato eller navn, og fjern de du ikke vil ha lenger." + }, + "profile": { + "title": "Profil", + "text": "Legg inn navnet ditt, en kort beskrivelse og en avatar. Velg plantepreferansene dine, så blir plantene som passer markert på plantekortene." + }, + "plantOwnerTest": { + "title": "Planteeiertest", + "text": "Svar på fire spørsmål og finn ut hva slags planteeier du er. Du kan bruke resultatet som profilbilde." + }, + "settings": { + "title": "Språk og tema", + "text": "Nederst i menyen kan du bytte mellom norsk og engelsk, og mellom lys og mørk modus.", + "mobileHint": "På små skjermer åpner du menyen med ☰." + } + } } } diff --git a/frontend/src/index.css b/frontend/src/index.css index 4ce02caa..a752b4eb 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -61,6 +61,19 @@ textarea { --card-hint: var(--cream); } +/* Hidden on screen, but still read by screen readers. Used on several pages */ +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + border: 0; +} + .info-button { display: flex; align-items: center; @@ -116,6 +129,8 @@ textarea { --card-shadow: drop-shadow(0 8px 18px rgba(0, 0, 0, 0.55)); --card-shadow-hover: drop-shadow(0 12px 26px rgba(0, 0, 0, 0.65)); --card-box-shadow: 0 8px 22px rgba(0, 0, 0, 0.5); - --card-front: var(--cream); - --card-hint: var(--deep-green); + /* Front of the plant card: light green with dark green text in dark mode, + the same color as the name at the top */ + --card-front: var(--soft-green); + --card-hint: var(--text-on-green); } diff --git a/frontend/src/pages/explorePlants/ExplorePlantsPage.css b/frontend/src/pages/explorePlants/ExplorePlantsPage.css index de7f75c8..e3a7e09a 100644 --- a/frontend/src/pages/explorePlants/ExplorePlantsPage.css +++ b/frontend/src/pages/explorePlants/ExplorePlantsPage.css @@ -11,15 +11,6 @@ gap: 30px; } -.visually-hidden { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip: rect(0 0 0 0); - white-space: nowrap; -} - .explore-form, .plant-grid { width: 100%; @@ -53,7 +44,6 @@ .explore-search input:focus { outline: none; - border-color: var(--dark-pink); box-shadow: 0 0 0 2px var(--dark-pink); } @@ -90,7 +80,6 @@ .reset-button.reset-button:focus-visible { outline: none; - border-color: var(--dark-pink); box-shadow: 0 0 0 2px var(--dark-pink); } diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.css b/frontend/src/pages/plantMatch/PlantMatchPage.css index 46da52e9..78081990 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.css +++ b/frontend/src/pages/plantMatch/PlantMatchPage.css @@ -26,9 +26,7 @@ display: flex; justify-content: center; align-items: center; -} - -.plant-card-container { + /* A stronger shadow than the cards on the other pages */ --card-shadow: drop-shadow(0 8px 18px rgba(30, 40, 30, 0.3)); --card-shadow-hover: drop-shadow(0 12px 26px rgba(30, 40, 30, 0.36)); } @@ -225,7 +223,6 @@ margin-left: 0; width: 100%; padding: 16px 8px 24px; - gap: 14px; overflow-x: hidden; } @@ -272,7 +269,6 @@ } .match-info-box p { - margin: 0; font-size: 14px; line-height: 1.45; } @@ -283,18 +279,4 @@ flex: 0 0 80px; font-size: 36px; } - - .plant-card-front .plant-card-preferences { - padding: 18px 14px 20px; - display: grid; - grid-template-columns: 1fr 1fr; - gap: 8px; - } - - .plant-preference-chip { - width: 100%; - box-sizing: border-box; - text-align: center; - justify-content: center; - } } diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css index db59f5e1..b6efdb98 100644 --- a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css @@ -55,7 +55,6 @@ border-radius: 16px; background: var(--dark-green); color: var(--text-on-green); - font-family: var(--font-text); font-size: 1.45rem; font-weight: 500; line-height: 1.5; @@ -152,13 +151,14 @@ .plant-owner-test-eyebrow { margin: 0 0 1rem; - color: var(--dark-pink); + color: var(--text-dark); font-size: 2rem; font-weight: 600; } .plant-owner-test-result h2 { margin: 0 0 1.25rem; + color: var(--dark-pink); font-size: 2.25rem; line-height: 1.3; } diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx index d1171d05..a477bea6 100644 --- a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx @@ -1,5 +1,7 @@ import { useState } from "react"; import { useTranslation } from "react-i18next"; +import { useNavigate } from "react-router-dom"; +import { ROUTES } from "../../AppRoutes"; import { useProfile } from "../../hooks/useProfile.ts"; import { plantOwnerTest, @@ -12,6 +14,7 @@ import "./PlantOwnerTestPage.css"; export default function PlantOwnerTestPage() { const { t } = useTranslation(); const { profilePicture, setProfilePicture } = useProfile(); + const navigate = useNavigate(); const [currentQuestion, setCurrentQuestion] = useState(0); // Question id -> chosen option id. Only kept while the test is open, so the @@ -53,7 +56,10 @@ export default function PlantOwnerTestPage() { } async function saveAsProfilePicture(type: PlantOwnerType) { - setSaveFailed(!(await setProfilePicture(type))); + const saved = await setProfilePicture(type); + setSaveFailed(!saved); + // Show the new picture on the profile page + if (saved) navigate(ROUTES.profile); } if (result) { diff --git a/frontend/src/pages/profile/ProfilePage.css b/frontend/src/pages/profile/ProfilePage.css index c819bb1b..829497b8 100644 --- a/frontend/src/pages/profile/ProfilePage.css +++ b/frontend/src/pages/profile/ProfilePage.css @@ -26,18 +26,6 @@ padding-top: 20px; } -.profile-description-label { - position: absolute; - width: 1px; - height: 1px; - padding: 0; - margin: -1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; - border: 0; -} - .profile-preferences { margin-top: 50px; } diff --git a/frontend/src/pages/profile/ProfilePage.tsx b/frontend/src/pages/profile/ProfilePage.tsx index 2e4e1466..a4911e84 100644 --- a/frontend/src/pages/profile/ProfilePage.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -83,7 +83,7 @@ export default function ProfilePage() {

{shownName}

- + {t("profile.descriptionLabel")}:{" "} {shownDescription} diff --git a/frontend/src/tests/App.test.tsx b/frontend/src/tests/App.test.tsx index 6294d3c2..ac630fe4 100644 --- a/frontend/src/tests/App.test.tsx +++ b/frontend/src/tests/App.test.tsx @@ -1,7 +1,7 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { MemoryRouter } from "react-router-dom"; -import { describe, it, expect, vi } from "vitest"; +import { beforeEach, describe, it, expect, vi } from "vitest"; import App from "../App"; import { ROUTES } from "../AppRoutes"; @@ -36,6 +36,13 @@ function renderApp(route: string) { } describe("App", () => { + // The walkthrough opens on the first visit. These tests are about the + // rest of the app, so it is marked as seen. It is tested below. + beforeEach(() => { + localStorage.clear(); + localStorage.setItem("walkthroughSeen", "true"); + }); + it.each([ [ROUTES.plantMatch, "plant match page"], [ROUTES.explore, "explore page"], @@ -93,4 +100,44 @@ describe("App", () => { screen.getByRole("link", { name: "app.skipToContent" }), ).toHaveFocus(); }); + + describe("walkthrough", () => { + beforeEach(() => { + localStorage.clear(); + }); + + it("opens on the first visit and is not shown again after closing", async () => { + const user = userEvent.setup(); + renderApp(ROUTES.plantMatch); + + expect(screen.getByRole("dialog")).toHaveAccessibleName( + "walkthrough.steps.welcome.title", + ); + await user.click( + screen.getByRole("button", { name: "walkthrough.close" }), + ); + + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(localStorage.getItem("walkthroughSeen")).toBe("true"); + // Focus goes back to the help button + expect( + screen.getByRole("button", { name: "walkthrough.open" }), + ).toHaveFocus(); + }); + + it("opens from the help button at the step for the current page", async () => { + localStorage.setItem("walkthroughSeen", "true"); + const user = userEvent.setup(); + renderApp(ROUTES.explore); + + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + await user.click( + screen.getByRole("button", { name: "walkthrough.open" }), + ); + + expect(screen.getByRole("dialog")).toHaveAccessibleName( + "walkthrough.steps.explore.title", + ); + }); + }); }); diff --git a/frontend/src/tests/PlantOwnerTestPage.test.tsx b/frontend/src/tests/PlantOwnerTestPage.test.tsx index 2dac5d84..9adaabe4 100644 --- a/frontend/src/tests/PlantOwnerTestPage.test.tsx +++ b/frontend/src/tests/PlantOwnerTestPage.test.tsx @@ -4,10 +4,12 @@ import { beforeEach, describe, it, expect, vi } from "vitest"; import PlantOwnerTestPage from "../pages/plantOwnerTest/PlantOwnerTestPage.tsx"; import { getPlantOwnerResult } from "../pages/plantOwnerTest/plantOwnerTest.ts"; -const { updateProfile, useUser } = vi.hoisted(() => ({ +const { updateProfile, useUser, navigate } = vi.hoisted(() => ({ updateProfile: vi.fn(), useUser: vi.fn(), + navigate: vi.fn(), })); +vi.mock("react-router-dom", () => ({ useNavigate: () => navigate })); vi.mock("@apollo/client/react", () => ({ useMutation: () => [updateProfile], })); @@ -81,7 +83,10 @@ describe("getPlantOwnerResult", () => { describe("PlantOwnerTestPage", () => { beforeEach(() => { updateProfile.mockReset(); - updateProfile.mockResolvedValue({}); + navigate.mockReset(); + updateProfile.mockResolvedValue({ + data: { updateUserProfile: { id: "user-1" } }, + }); mockUser(); }); @@ -150,6 +155,7 @@ describe("PlantOwnerTestPage", () => { }), ); expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(navigate).toHaveBeenCalledWith("/profile"); }); it("shows an error when the profile picture could not be saved", async () => { @@ -161,6 +167,19 @@ describe("PlantOwnerTestPage", () => { expect(await screen.findByRole("alert")).toHaveTextContent( "plantQuiz.profilePicture.failed", ); + expect(navigate).not.toHaveBeenCalled(); + }); + + it("shows an error when the user was not found in the database", async () => { + updateProfile.mockResolvedValue({ data: { updateUserProfile: null } }); + const { pick } = await takeTest("city", "minimum"); + + await pick("plantQuiz.profilePicture.use"); + + expect(await screen.findByRole("alert")).toHaveTextContent( + "plantQuiz.profilePicture.failed", + ); + expect(navigate).not.toHaveBeenCalled(); }); it("says so when the result already is the profile picture", async () => { diff --git a/frontend/src/tests/ProfilePage.test.tsx b/frontend/src/tests/ProfilePage.test.tsx index 11c58e3f..ac9f06e6 100644 --- a/frontend/src/tests/ProfilePage.test.tsx +++ b/frontend/src/tests/ProfilePage.test.tsx @@ -62,7 +62,7 @@ describe("Profile page", () => { render(); const label = screen.getByText("profile.descriptionLabel:"); - expect(label).toHaveClass("profile-description-label"); + expect(label).toHaveClass("visually-hidden"); expect(label.closest("p")).toHaveTextContent( "profile.descriptionLabel: profile.description", ); diff --git a/frontend/src/tests/Walkthrough.test.tsx b/frontend/src/tests/Walkthrough.test.tsx new file mode 100644 index 00000000..a08e710a --- /dev/null +++ b/frontend/src/tests/Walkthrough.test.tsx @@ -0,0 +1,155 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import { describe, it, expect, vi } from "vitest"; +import Walkthrough from "../components/walkthrough/Walkthrough"; +import { + stepForPath, + walkthroughSteps, +} from "../components/walkthrough/walkthroughSteps"; +import { ROUTES } from "../AppRoutes"; + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ + t: (key: string) => key, + i18n: { language: "no", changeLanguage: vi.fn() }, + }), +})); + +function renderWalkthrough(startStep = 0, route = ROUTES.plantMatch) { + const onClose = vi.fn(); + render( + + + + explore page

} /> + + + , + ); + return onClose; +} + +const LAST_STEP = walkthroughSteps.length - 1; + +describe("Walkthrough", () => { + it("opens as a modal dialog on the given step", () => { + renderWalkthrough(2); + + const dialog = screen.getByRole("dialog"); + expect(dialog).toHaveAttribute("open"); + expect(dialog).toHaveAccessibleName("walkthrough.steps.explore.title"); + }); + + it("goes forward and back through the steps", async () => { + const user = userEvent.setup(); + renderWalkthrough(); + + expect( + screen.queryByRole("button", { name: "walkthrough.back" }), + ).not.toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "walkthrough.next" })); + expect( + screen.getByRole("heading", { + name: "walkthrough.steps.plantMatch.title", + }), + ).toBeInTheDocument(); + + await user.click(screen.getByRole("button", { name: "walkthrough.back" })); + expect( + screen.getByRole("heading", { name: "walkthrough.steps.welcome.title" }), + ).toBeInTheDocument(); + }); + + it("moves between steps with the arrow keys", async () => { + const user = userEvent.setup(); + renderWalkthrough(); + + await user.keyboard("{ArrowRight}{ArrowRight}"); + expect( + screen.getByRole("heading", { name: "walkthrough.steps.explore.title" }), + ).toBeInTheDocument(); + + await user.keyboard("{ArrowLeft}"); + expect( + screen.getByRole("heading", { + name: "walkthrough.steps.plantMatch.title", + }), + ).toBeInTheDocument(); + }); + + it("closes with Finish on the last step", async () => { + const user = userEvent.setup(); + const onClose = renderWalkthrough(LAST_STEP); + + expect(screen.getByText("walkthrough.reminder")).toBeInTheDocument(); + await user.click( + screen.getByRole("button", { name: "walkthrough.finish" }), + ); + + expect(onClose).toHaveBeenCalledWith(true); + }); + + it("closes with the close button", async () => { + const user = userEvent.setup(); + const onClose = renderWalkthrough(); + + await user.click(screen.getByRole("button", { name: "walkthrough.close" })); + + expect(onClose).toHaveBeenCalledWith(true); + }); + + it("has the small screen hint only on the steps that have one", () => { + renderWalkthrough(LAST_STEP); + expect( + screen.getByText("walkthrough.steps.settings.mobileHint"), + ).toBeInTheDocument(); + }); + + it("has no small screen hint on other steps", () => { + renderWalkthrough(0); + expect(screen.queryByText(/mobileHint/)).not.toBeInTheDocument(); + }); + + it("shows the language switcher on every step", () => { + renderWalkthrough(LAST_STEP); + + expect( + screen.getByRole("button", { name: /switch to english|bytt til norsk/i }), + ).toBeInTheDocument(); + }); + + it("goes to the page of the step and closes", async () => { + const user = userEvent.setup(); + const onClose = renderWalkthrough(2); + + await user.click(screen.getByRole("link", { name: /walkthrough.goTo/ })); + + expect(screen.getByText("explore page")).toBeInTheDocument(); + // The app moves focus to the new page, so it should not go back to the help button + expect(onClose).toHaveBeenCalledWith(false); + }); + + it("has no link on steps that are not about a page", () => { + renderWalkthrough(0); + + expect(screen.queryByRole("link")).not.toBeInTheDocument(); + }); +}); + +describe("stepForPath", () => { + it("starts on the step for the current page", () => { + expect(walkthroughSteps[stepForPath(ROUTES.myMatches)].id).toBe( + "myMatches", + ); + }); + + it("starts at the beginning on pages without a step", () => { + expect(stepForPath("/unknown-page")).toBe(0); + }); + + it("starts at the welcome step on the home page", () => { + expect(stepForPath(ROUTES.plantMatch)).toBe(0); + }); +}); diff --git a/frontend/src/tests/setup.ts b/frontend/src/tests/setup.ts index 2ba240b8..505180fa 100644 --- a/frontend/src/tests/setup.ts +++ b/frontend/src/tests/setup.ts @@ -5,3 +5,15 @@ import { cleanup } from "@testing-library/react"; afterEach(() => { cleanup(); }); + +// jsdom has but not showModal() and close(), so they are added here +if (!HTMLDialogElement.prototype.showModal) { + HTMLDialogElement.prototype.showModal = function () { + this.open = true; + }; +} +if (!HTMLDialogElement.prototype.close) { + HTMLDialogElement.prototype.close = function () { + this.open = false; + }; +} diff --git a/package.json b/package.json index b52494de..65400b33 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,8 @@ "test:e2e:headed": "playwright test --project=desktop --headed", "test:backend": "npm test --prefix backend -- --run", "test:frontend": "npm test --prefix frontend -- --run", + "test:all": "npm run test:backend && npm run test:frontend && npm run test:e2e", + "ci:all": "npm ci && npm ci --prefix backend && npm ci --prefix frontend && npm run test:all", "test:coverage": "npm run test:backend -- --coverage && npm run test:frontend -- --coverage", "format": "prettier --write .", "format:check": "prettier --check ." diff --git a/playwright.config.ts b/playwright.config.ts index 93a712cf..1fc103b0 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -4,6 +4,17 @@ import { E2E_DB_NAME, E2E_DB_PORT, E2E_MONGODB_URI } from "./e2e/testDb"; // The test backend runs on 3002, so it does not collide with the dev backend on 3001 const E2E_BACKEND_PORT = 3002; +// The walkthrough opens on the first visit and covers the page. +const WALKTHROUGH_SEEN = { + cookies: [], + origins: [ + { + origin: "http://localhost:4173", + localStorage: [{ name: "walkthroughSeen", value: "true" }], + }, + ], +}; + export default defineConfig({ testDir: "./e2e", // Runs after the web servers are up: empties the test database and fills it with fixtures @@ -34,12 +45,12 @@ export default defineConfig({ { name: "desktop", testMatch: "**/ui*.spec.ts", - use: { ...devices["Desktop Chrome"] }, + use: { ...devices["Desktop Chrome"], storageState: WALKTHROUGH_SEEN }, }, { name: "mobile", testMatch: "**/ui*.spec.ts", - use: { ...devices["Pixel 7"] }, + use: { ...devices["Pixel 7"], storageState: WALKTHROUGH_SEEN }, }, ], // Started in order: the database must be up before the backend, which connects on startup