From b64cfc86a427490dd62c56f298152d013a22a0b8 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 10:28:53 +0100 Subject: [PATCH 1/8] Resolved issues with adding plantcard to favorites caused by wrong merging --- .../src/graphql/fragments/userFragments.ts | 6 +---- frontend/src/graphql/user/mutations.ts | 20 ---------------- frontend/src/graphql/user/queries.ts | 24 +++++++++++++++++++ .../src/pages/myMatches/MyMatchesPage.tsx | 2 +- frontend/src/types/User.ts | 4 +--- 5 files changed, 27 insertions(+), 29 deletions(-) diff --git a/frontend/src/graphql/fragments/userFragments.ts b/frontend/src/graphql/fragments/userFragments.ts index 853c92d9..505ae544 100644 --- a/frontend/src/graphql/fragments/userFragments.ts +++ b/frontend/src/graphql/fragments/userFragments.ts @@ -1,5 +1,4 @@ import { gql } from "@apollo/client"; -import { PLANT_FIELDS } from "./plantFragments"; // The user fields every query and mutation asks for. Using the same fields // everywhere lets Apollo's cache update the user on all pages at once. @@ -10,9 +9,6 @@ export const USER_FIELDS = gql` description profilePicture preferences - matchedPlants { - ...PlantFields - } + matchedPlantIds } - ${PLANT_FIELDS} `; diff --git a/frontend/src/graphql/user/mutations.ts b/frontend/src/graphql/user/mutations.ts index 67e1fc31..1f8d1297 100644 --- a/frontend/src/graphql/user/mutations.ts +++ b/frontend/src/graphql/user/mutations.ts @@ -2,26 +2,6 @@ import { gql } from "@apollo/client"; import type { User } from "../../types/User"; import { USER_FIELDS } from "../fragments/userFragments"; -// One page of the user's matched plants, sorted. Only My Matches uses this, -// so the other pages don't have to fetch the whole plants with images. -export const MY_MATCHES = gql` - query MyMatches($userId: ID!, $sort: String, $limit: Int, $offset: Int) { - myMatches(userId: $userId, sort: $sort, limit: $limit, offset: $offset) { - totalCount - plants { - id - name - imageURL - scientificName - description - watering - sunlight - careLevel - } - } - } -`; - export const CREATE_USER = gql` mutation CreateUser { createUser { diff --git a/frontend/src/graphql/user/queries.ts b/frontend/src/graphql/user/queries.ts index 08f2caf1..20615bc8 100644 --- a/frontend/src/graphql/user/queries.ts +++ b/frontend/src/graphql/user/queries.ts @@ -1,4 +1,5 @@ import { gql } from "@apollo/client"; +import type { Plant } from "../../types/Plant"; import type { User } from "../../types/User"; import { USER_FIELDS } from "../fragments/userFragments"; @@ -11,4 +12,27 @@ export const GET_USER = gql` ${USER_FIELDS} `; +// One page of the user's matched plants, sorted. Only My Matches uses this, +// so the other pages don't have to fetch the whole plants with images. +export const MY_MATCHES = gql` + query MyMatches($userId: ID!, $sort: String, $limit: Int, $offset: Int) { + myMatches(userId: $userId, sort: $sort, limit: $limit, offset: $offset) { + totalCount + plants { + id + name + imageURL + scientificName + description + watering + sunlight + careLevel + } + } + } +`; + export type GetUserData = { getUser: User | null }; +export type MyMatchesData = { + myMatches: { totalCount: number; plants: Plant[] }; +}; diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index d73b34eb..e7f18dfe 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -8,7 +8,7 @@ import SortMenu from "../../components/sortMenu/SortMenu.tsx"; import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; import { useSessionState } from "../../hooks/useSessionState.ts"; import { useUser } from "../../context/UserContext"; -import { MY_MATCHES, type MyMatchesData } from "../../context/userQueries"; +import { MY_MATCHES, type MyMatchesData } from "../../graphql/user/queries"; const PAGE_SIZE = 12; diff --git a/frontend/src/types/User.ts b/frontend/src/types/User.ts index 7bf56666..d3a22d73 100644 --- a/frontend/src/types/User.ts +++ b/frontend/src/types/User.ts @@ -1,5 +1,3 @@ -import type { Plant } from "./Plant"; - // A user as returned by the user queries and mutations (the UserFields fragment). export type User = { id: string; @@ -7,5 +5,5 @@ export type User = { description: string | null; profilePicture: string; preferences: string[]; - matchedPlants: Plant[]; + matchedPlantIds: string[]; }; From 8e1257d416252678ea696e039e32d78c28cdfcfe Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 10:54:25 +0100 Subject: [PATCH 2/8] fixed colours in darkmode so they pass accseability --- frontend/src/App.css | 1 - .../src/components/pagination/Pagination.css | 1 - .../src/components/plantCard/PlantCard.css | 13 ++++- .../plantPreferences/PlantPreferences.css | 2 +- frontend/src/components/sidebar/Sidebar.css | 4 ++ .../sidebarButtons/SideBarButton.css | 7 ++- frontend/src/components/sortMenu/SortMenu.css | 1 - frontend/src/i18n/locales/en/translation.json | 4 +- frontend/src/i18n/locales/no/translation.json | 4 +- frontend/src/index.css | 52 +++++++++++++++---- .../src/pages/plantMatch/PlantMatchPage.css | 35 +++++-------- .../src/pages/plantMatch/PlantMatchPage.tsx | 2 +- .../pages/plantOwnerTest/PlantOwnerTest.css | 5 +- frontend/src/pages/profile/Profile.css | 50 +++++++++++++++++- frontend/src/pages/profile/Profile.tsx | 21 +++++++- .../tests/__snapshots__/Profile.test.tsx.snap | 29 +++++++++-- 16 files changed, 183 insertions(+), 48 deletions(-) diff --git a/frontend/src/App.css b/frontend/src/App.css index aed689d9..37436bcb 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -8,7 +8,6 @@ border-radius: 8px; background-color: var(--dark-green); color: var(--text-on-green); - font-family: var(--font-ui); text-decoration: none; transform: translateY(-200%); } diff --git a/frontend/src/components/pagination/Pagination.css b/frontend/src/components/pagination/Pagination.css index f324bb5f..90977b77 100644 --- a/frontend/src/components/pagination/Pagination.css +++ b/frontend/src/components/pagination/Pagination.css @@ -24,7 +24,6 @@ border-radius: 8px; background-color: var(--light-green); color: var(--text-dark); - font-family: var(--font-ui); font-size: 1rem; cursor: pointer; } diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index 9878818a..831883ad 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -92,8 +92,17 @@ border-radius: 32px; overflow: hidden; +} + +/* The back of the card and the empty card are too close to the page color in + dark mode, so they get a light green border to show where they end. The + front is light in both modes and does not need one. */ +[data-theme="dark"] .plant-card:not(.plant-card-front) { + border: 2px solid var(--dark-green); +} - font-family: var(--font-card); +.plant-card-front { + background: var(--card-front); } .plant-card-face > .plant-card { @@ -229,7 +238,7 @@ margin: auto 0 0; padding: 18px var(--card-hint-space) 32px 20px; - color: var(--dark-green); + color: var(--deep-green); font-size: 1rem; font-weight: 600; diff --git a/frontend/src/components/plantPreferences/PlantPreferences.css b/frontend/src/components/plantPreferences/PlantPreferences.css index d090acd3..a6bca110 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.css +++ b/frontend/src/components/plantPreferences/PlantPreferences.css @@ -6,7 +6,7 @@ .plant-preferences button { padding: 12px 20px; - border: 1px solid var(--border-pink); + border: 2px solid var(--dark-pink); border-radius: 10px 20px 20px 20px; background: var(--light-pink); color: var(--text-dark); diff --git a/frontend/src/components/sidebar/Sidebar.css b/frontend/src/components/sidebar/Sidebar.css index 29ec854a..799521de 100644 --- a/frontend/src/components/sidebar/Sidebar.css +++ b/frontend/src/components/sidebar/Sidebar.css @@ -2,6 +2,9 @@ width: var(--sidebar-width); max-width: 100%; height: 100vh; + /* 100vh is taller than the visible area on phones when the browser bar is + shown, which hid the language and theme buttons. dvh follows the bar. */ + height: 100dvh; position: fixed; overflow-y: auto; z-index: 100; @@ -58,6 +61,7 @@ .sidebar__footer { margin-top: auto; + padding-bottom: env(safe-area-inset-bottom); display: flex; flex-direction: row; align-items: center; diff --git a/frontend/src/components/sidebarButtons/SideBarButton.css b/frontend/src/components/sidebarButtons/SideBarButton.css index 1bdccba9..51ee7dec 100644 --- a/frontend/src/components/sidebarButtons/SideBarButton.css +++ b/frontend/src/components/sidebarButtons/SideBarButton.css @@ -9,8 +9,13 @@ cursor: pointer; } +[data-theme="dark"] .sidebar-button { + border-color: var(--dark-green); + background-color: var(--dark-green); + color: var(--text-on-green); +} + .language-button { - font-family: var(--font-ui); font-size: 19px; font-weight: 600; } diff --git a/frontend/src/components/sortMenu/SortMenu.css b/frontend/src/components/sortMenu/SortMenu.css index c5b6bf27..f9e841af 100644 --- a/frontend/src/components/sortMenu/SortMenu.css +++ b/frontend/src/components/sortMenu/SortMenu.css @@ -16,7 +16,6 @@ border-radius: 8px; background-color: var(--light-background); color: var(--text-dark); - font-family: var(--font-ui); font-size: 15px; white-space: nowrap; cursor: pointer; diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index e46c8e6c..087216ca 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -35,7 +35,9 @@ "noMorePlants": "No more plants to show. Reload to go again!" }, "preferences": { - "title": "Plant preferences ✿", + "infoLabel": "What are preferences?", + "info": "Preferences are the plant traits you like, such as how much water, sun and care a plant needs. Plants that match your preferences are marked on the plant cards.", + "title": "Plant preferences", "minimumWater": "low watering", "averageWater": "average watering", "frequentWater": "frequent watering", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index f2d58fc5..49d7d075 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -35,7 +35,9 @@ "noMorePlants": "Ingen flere planter å vise. Last inn siden på nytt for å gjøre det igjen!" }, "preferences": { - "title": "Plantepreferanser ✿", + "infoLabel": "Hva er preferanser?", + "info": "Preferanser er egenskaper du liker hos planter, som hvor mye vann, sol og stell de trenger. Planter som passer preferansene dine blir markert på plantekortene.", + "title": "Plantepreferanser", "minimumWater": "trenger lite vann", "averageWater": "middels vannbehov", "frequentWater": "trenger mye vann", diff --git a/frontend/src/index.css b/frontend/src/index.css index c2e2e16b..7744d3e8 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -14,22 +14,18 @@ body { color: var(--text-dark); } -/* Form controls don't inherit the font from the page, so they get --font-ui here */ +/* Form controls don't inherit the font from the page by default */ button, input, select, textarea { - font-family: var(--font-ui); + font-family: inherit; } :root { --sidebar-width: 16rem; - /* Fonts: serif for all pages, and a separate font for the plant cards */ + /* The one font used everywhere. It is set on body, and everything inherits it */ --font-text: Georgia, serif; - --font-card: Palatino, "Palatino Linotype", "Book Antiqua", Georgia, serif; - /* --font-ui: system-ui, sans-serif; */ - --font-ui: var(--font-text); - /* --font-ui: Arial, sans-serif; */ /* Colors: */ --text-dark: #44403c; --text-light: #ffffff; @@ -56,6 +52,41 @@ textarea { --card-shadow: drop-shadow(0 6px 14px rgba(30, 40, 30, 0.18)); --card-shadow-hover: drop-shadow(0 10px 22px rgba(30, 40, 30, 0.24)); --card-box-shadow: 0 6px 20px rgba(30, 40, 30, 0.15); + /* These keep the light mode colors in dark mode too, so they are not changed + in [data-theme="dark"]. Used for the front of the plant card and for icons + on white buttons. */ + --card-front: #f5f1e8; + --deep-green: #2e4a3b; +} + +/* The round "i" button that shows a help text, used on Plant Match and Profile */ +.info-button { + display: flex; + align-items: center; + justify-content: center; + padding: 0; + border: 2px solid var(--dark-pink); + border-radius: 50%; + background-color: var(--dark-pink); + color: var(--text-light); + font-weight: 700; + cursor: pointer; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12); + transition: + background-color 0.2s ease, + color 0.2s ease, + transform 0.2s ease; +} + +.info-button:hover { + background-color: var(--light-pink); + color: var(--pink-text); + transform: scale(1.05); +} + +.info-button:focus-visible { + outline: 2px solid var(--dark-green); + outline-offset: 2px; } [data-theme="dark"] { @@ -81,7 +112,8 @@ textarea { --sidebar-background: var(--light-sage); --sidebar-border: var(--border-soft); --sidebar-text: var(--text-dark); - --card-shadow: drop-shadow(0 8px 18px rgba(0, 0, 0, 0.45)); - --card-shadow-hover: drop-shadow(0 10px 22px rgba(0, 0, 0, 0.55)); - --card-box-shadow: 0 8px 18px rgba(0, 0, 0, 0.45); + /* No shadows in dark mode. The cards get a light border instead (PlantCard.css) */ + --card-shadow: none; + --card-shadow-hover: none; + --card-box-shadow: none; } diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.css b/frontend/src/pages/plantMatch/PlantMatchPage.css index b77cc0e6..92d8a012 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.css +++ b/frontend/src/pages/plantMatch/PlantMatchPage.css @@ -33,8 +33,8 @@ } [data-theme="dark"] .plant-card-container { - --card-shadow: drop-shadow(0 10px 22px rgba(0, 0, 0, 0.6)); - --card-shadow-hover: drop-shadow(0 12px 26px rgba(0, 0, 0, 0.7)); + --card-shadow: none; + --card-shadow-hover: none; } .match-info { @@ -47,27 +47,7 @@ .match-info-button { width: 50px; height: 50px; - display: flex; - align-items: center; - justify-content: center; - border: 2px solid var(--dark-pink); - border-radius: 50%; - background-color: var(--dark-pink); - color: var(--text-light); font-size: 22px; - font-weight: 700; - cursor: pointer; - box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12); - transition: - background-color 0.2s ease, - color 0.2s ease, - transform 0.2s ease; -} - -.match-info-button:hover { - background-color: var(--light-pink); - color: var(--pink-text); - transform: scale(1.05); } .match-info-box { @@ -189,6 +169,17 @@ color: var(--text-on-green); } +/* In dark mode the buttons are white and the icons get the button colors */ +[data-theme="dark"] .dislike-button { + background-color: var(--text-light); + color: var(--dark-pink); +} + +[data-theme="dark"] .like-button { + background-color: var(--text-light); + color: var(--deep-green); +} + @media (max-width: 767px) { .plant-match-page { margin-left: 0; diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index edba08bd..baff1dec 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -35,7 +35,7 @@ function PlantMatchPage() {
+ +
+
)} diff --git a/frontend/src/tests/__snapshots__/Profile.test.tsx.snap b/frontend/src/tests/__snapshots__/Profile.test.tsx.snap index 82583b5b..ea981cbe 100644 --- a/frontend/src/tests/__snapshots__/Profile.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/Profile.test.tsx.snap @@ -50,9 +50,32 @@ exports[`Profile page > matches snapshot 1`] = `
-

- preferences.title -

+
+

+ preferences.title +

+
+ + +
+
From f2f9d9c66c43c8c1b3f231659ba653c6060c40b8 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 11:01:02 +0100 Subject: [PATCH 3/8] Added more colour changes in lightmode to preserve accesability --- .../src/components/plantCard/PlantCard.css | 11 +++--- .../sidebarButtons/SideBarButton.css | 12 ++---- frontend/src/hooks/usePlantDeck.ts | 11 ++++++ frontend/src/i18n/locales/en/translation.json | 3 +- frontend/src/i18n/locales/no/translation.json | 3 +- frontend/src/index.css | 17 ++++++--- .../src/pages/plantMatch/PlantMatchPage.css | 38 ++++++++++++++++--- .../src/pages/plantMatch/PlantMatchPage.tsx | 15 ++++++++ .../pages/plantOwnerTest/PlantOwnerTest.css | 11 ++++-- frontend/src/tests/PlantMatchPage.test.tsx | 22 +++++++++++ 10 files changed, 112 insertions(+), 31 deletions(-) diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index 831883ad..25e9ad0c 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -94,10 +94,9 @@ overflow: hidden; } -/* The back of the card and the empty card are too close to the page color in - dark mode, so they get a light green border to show where they end. The - front is light in both modes and does not need one. */ -[data-theme="dark"] .plant-card:not(.plant-card-front) { +/* The back of the card is too close to the page color in dark mode, so it gets + a light green border to show where it ends */ +[data-theme="dark"] .plant-card-back { border: 2px solid var(--dark-green); } @@ -238,7 +237,7 @@ margin: auto 0 0; padding: 18px var(--card-hint-space) 32px 20px; - color: var(--deep-green); + color: var(--card-hint); font-size: 1rem; font-weight: 600; @@ -256,7 +255,7 @@ } .plant-card-face-back .plant-card-flap { - --flap-fill: var(--light-green); + --flap-fill: var(--cream); } .plant-card-back .plant-card-hint, diff --git a/frontend/src/components/sidebarButtons/SideBarButton.css b/frontend/src/components/sidebarButtons/SideBarButton.css index 51ee7dec..493c75df 100644 --- a/frontend/src/components/sidebarButtons/SideBarButton.css +++ b/frontend/src/components/sidebarButtons/SideBarButton.css @@ -1,18 +1,12 @@ .sidebar-button { width: 74px; height: 38px; - border: 1px solid var(--sidebar-border); + border: 1px solid var(--dark-green); border-radius: 8px; - background-color: var(--light-background); - color: var(--text-dark); - font-size: 18px; - cursor: pointer; -} - -[data-theme="dark"] .sidebar-button { - border-color: var(--dark-green); background-color: var(--dark-green); color: var(--text-on-green); + font-size: 18px; + cursor: pointer; } .language-button { diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 7d1688f0..047c1a0c 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -83,6 +83,16 @@ export function usePlantDeck() { const next = useCallback(() => setIndex((current) => current + 1), []); + // Start the deck over from the first plant. Also used to try again after an + // error. The fetch effect above loads the first batch again. + const restart = useCallback(() => { + seenIds.current = new Set(); + setPlants([]); + setIndex(0); + setError(undefined); + setHasMore(true); + }, []); + const plant = plants[index]; return { @@ -92,5 +102,6 @@ export function usePlantDeck() { loading: (loading || userLoading) && !plant, error: plant ? undefined : error, noMorePlants: !plant && !hasMore && !loading, + restart, } as const; } diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 087216ca..d8aa4c58 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -32,7 +32,8 @@ "loading": "Loading plants...", "error": "Could not load plants. Please try again later.", "noMorePlantsTitle": "Done!", - "noMorePlants": "No more plants to show. Reload to go again!" + "noMorePlants": "No more plants to show. Reload to see them again!", + "reload": "Reload" }, "preferences": { "infoLabel": "What are preferences?", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index 49d7d075..bb83fab6 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -32,7 +32,8 @@ "loading": "Laster planter...", "error": "Kunne ikke hente planter. Prøv igjen senere.", "noMorePlantsTitle": "Ferdig!", - "noMorePlants": "Ingen flere planter å vise. Last inn siden på nytt for å gjøre det igjen!" + "noMorePlants": "Ingen flere planter å vise. Last inn på nytt for å se dem igjen!", + "reload": "Last inn på nytt" }, "preferences": { "infoLabel": "Hva er preferanser?", diff --git a/frontend/src/index.css b/frontend/src/index.css index 7744d3e8..50e3bef7 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -34,7 +34,8 @@ textarea { --text-on-green: #f5f1e8; --light-green: #f5f1e8; --text-on-green-muted: #d9dcc8; - --card-flap: #7a8b5c; + /* The folded corner on the front of the plant card */ + --card-flap: var(--dark-pink); --card-back: #5c6b42; --dark-pink: #9e3050; --pink-text: #9e3050; @@ -52,11 +53,13 @@ textarea { --card-shadow: drop-shadow(0 6px 14px rgba(30, 40, 30, 0.18)); --card-shadow-hover: drop-shadow(0 10px 22px rgba(30, 40, 30, 0.24)); --card-box-shadow: 0 6px 20px rgba(30, 40, 30, 0.15); - /* These keep the light mode colors in dark mode too, so they are not changed - in [data-theme="dark"]. Used for the front of the plant card and for icons - on white buttons. */ - --card-front: #f5f1e8; + /* The dark green from light mode. Not changed in dark mode, so it can be + used on white or light backgrounds there too. */ --deep-green: #2e4a3b; + --cream: #f5f1e8; + /* Front of the plant card: dark green with light text in light mode */ + --card-front: var(--deep-green); + --card-hint: var(--cream); } /* The round "i" button that shows a help text, used on Plant Match and Profile */ @@ -97,7 +100,6 @@ textarea { --text-on-green: #1f2a22; --light-green: #2f3329; --text-on-green-muted: #2f3329; - --card-flap: #5e6b48; --card-back: #5e6b48; --dark-pink: #c2476b; --light-pink: #4a2a35; @@ -116,4 +118,7 @@ textarea { --card-shadow: none; --card-shadow-hover: none; --card-box-shadow: none; + /* Front of the plant card: light with dark green text in dark mode */ + --card-front: var(--cream); + --card-hint: var(--deep-green); } diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.css b/frontend/src/pages/plantMatch/PlantMatchPage.css index 92d8a012..34a6136b 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.css +++ b/frontend/src/pages/plantMatch/PlantMatchPage.css @@ -90,11 +90,14 @@ line-height: 1.6; } -.empty-plant-card { +/* .plant-card.empty-plant-card, because PlantCard.css is loaded after this file + and its .plant-card background would win otherwise */ +.plant-card.empty-plant-card { display: flex; align-items: center; justify-content: center; - background: var(--light-green); + background: var(--dark-pink); + color: var(--text-light); box-shadow: var(--card-box-shadow); } @@ -112,24 +115,49 @@ } .empty-plant-icon { - color: var(--dark-green); + color: var(--text-light); font-size: 3rem; } .empty-plant-card h2 { margin: 0; - color: var(--dark-green); + color: var(--text-light); font-size: 1.6rem; font-weight: 700; } .empty-plant-card p { margin: 0; - color: var(--text-dark); + color: var(--text-light); font-size: 1rem; line-height: 1.5; } +.reload-button { + margin-top: 8px; + padding: 12px 24px; + border: 2px solid var(--text-light); + border-radius: 999px; + background-color: var(--text-light); + color: var(--dark-pink); + font-size: 1rem; + font-weight: 600; + cursor: pointer; + transition: + background-color 0.2s ease, + color 0.2s ease; +} + +.reload-button:hover { + background-color: transparent; + color: var(--text-light); +} + +.reload-button:focus-visible { + outline: 2px solid var(--text-light); + outline-offset: 3px; +} + .swipe-button { width: 150px; height: 150px; diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index baff1dec..ef9dc70d 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -13,6 +13,7 @@ function PlantMatchPage() { loading, error, noMorePlants, + restart, } = usePlantDeck(); const matchPlant = () => { @@ -57,6 +58,13 @@ function PlantMatchPage() {

{t("plantMatchPage.error")}

+
)} @@ -73,6 +81,13 @@ function PlantMatchPage() {

{t("plantMatchPage.noMorePlantsTitle")}

{t("plantMatchPage.noMorePlants")}

+
)} diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css b/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css index 2f849f04..24b50a87 100644 --- a/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTest.css @@ -51,10 +51,10 @@ align-items: center; min-height: 145px; padding: 1.75rem; - border: 2px solid var(--border-soft); + border: 2px solid var(--dark-green); border-radius: 16px; - background: var(--light-sage); - color: var(--text-dark); + background: var(--dark-green); + color: var(--text-on-green); font-family: var(--font-text); font-size: 1.15rem; font-weight: 500; @@ -67,19 +67,24 @@ transform 0.2s ease; } +/* Dark mode keeps the dark background, with a white border to stand out */ [data-theme="dark"] .plant-owner-test-option { border-color: var(--text-light); + background: var(--light-sage); + color: var(--text-dark); } .plant-owner-test-option:hover { border-color: var(--dark-green); background: var(--light-pink); + color: var(--text-dark); transform: translateY(-2px); } .plant-owner-test-option.selected { border: 3px solid var(--dark-pink); background: var(--light-pink); + color: var(--text-dark); } .plant-owner-test-navigation { diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index b4c84aba..529c5e59 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -207,6 +207,28 @@ describe("PlantMatchPage", () => { ).not.toHaveLength(0); }); + it("starts the deck over from the first plant with the reload button", async () => { + render(); + await screen.findAllByText("Hydrangea"); + skip(); + skip(); + fireEvent.click( + await screen.findByRole("button", { name: "plantMatchPage.reload" }), + ); + expect((await screen.findAllByText("Hydrangea")).length).toBeGreaterThan(0); + // The new request does not exclude the plants from the first round + expect(query.mock.lastCall?.[0].variables.excludeIds).toEqual([]); + }); + + it("tries again with the reload button after an error", async () => { + query.mockRejectedValueOnce(new Error("Network error")); + render(); + fireEvent.click( + await screen.findByRole("button", { name: "plantMatchPage.reload" }), + ); + expect((await screen.findAllByText("Hydrangea")).length).toBeGreaterThan(0); + }); + it("shows the end card when there are no plants at all", async () => { mockBackend([]); render(); From f879c69c89940d6468231b3b2c56525def330aa2 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 11:25:17 +0100 Subject: [PATCH 4/8] Made match button its own component and made even more colour changes for accesability --- e2e/uiAccessibility.spec.ts | 448 +++++++++++++++--- .../components/matchButton/MatchButton.css | 83 ++++ .../components/matchButton/MatchButton.tsx | 43 ++ .../src/components/plantCard/PlantCard.css | 26 +- frontend/src/components/sortMenu/SortMenu.css | 6 + frontend/src/i18n/locales/en/translation.json | 2 +- frontend/src/i18n/locales/no/translation.json | 2 +- frontend/src/index.css | 1 + .../src/pages/explorePlants/ExplorePlants.css | 70 --- .../src/pages/explorePlants/ExplorePlants.tsx | 24 +- .../src/pages/myMatches/MyMatchesPage.css | 24 - .../src/pages/myMatches/MyMatchesPage.tsx | 13 +- 12 files changed, 565 insertions(+), 177 deletions(-) create mode 100644 frontend/src/components/matchButton/MatchButton.css create mode 100644 frontend/src/components/matchButton/MatchButton.tsx diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index 78165e65..9a221fe8 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -1,29 +1,282 @@ import { test, expect, type Page } from "@playwright/test"; import AxeBuilder from "@axe-core/playwright"; +import { openSidebar } from "./helpers/navigation"; // Automatic accessibility check with axe against WCAG 2.1 level A and AA, // the level required for the public sector in Norway. // axe only finds part of the problems, so this is combined with manual testing // (keyboard only, 200 % zoom and screen reader), see tests.md. +// +// axe has three gaps that are covered here: +// 1. It only checks text contrast (1.4.3). Contrast of borders, surfaces and +// icons (1.4.11) is checked by checkNonTextContrast below. +// 2. When it cannot find the background of a text, the result is "incomplete" +// instead of a violation. Those results now fail the test too. +// 3. It does not check placeholder text, so checkNonTextContrast does that. const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]; -/// Runs axe on the page and lists the violations in a readable form: the rule, -// which elements broke it, and axe's explanation (for contrast: the colours and ratio) -async function checkAccessibility(page: Page) { - const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze(); +// axe can't check text that is only symbols (✿, ✖). checkNonTextContrast +// checks those icons instead, so this incomplete result is expected. +const ICON_ONLY_MESSAGE = "contains only non-text characters"; + +// An open tooltip lies on top of the page, so axe can't find the background of +// the text under it, or of the tooltip itself. Tooltip tests therefore only run +// axe on the tooltip, and its text is checked by checkNonTextContrast. +const OVERLAP_MESSAGE = "overlap"; + +// Runs axe and the extra contrast checks on the page, and lists the problems +// in a readable form: the rule, which elements broke it, and why. +// `only` limits axe to one part of the page, used for tooltips. +async function checkAccessibility(page: Page, only?: string) { + // Both faces of a plant card are stacked on top of each other, so axe can't + // find the background of the text on the visible face. The hidden face is + // removed while axe runs. + await page.addStyleTag({ + content: + '.plant-card-face[aria-hidden="true"] { display: none !important; }', + }); + + const builder = new AxeBuilder({ page }).withTags(WCAG_TAGS); + if (only) builder.include(only); + const results = await builder.analyze(); const violations = results.violations.flatMap((v) => v.nodes.map( (node) => `${v.id}: ${node.target.join(" ")} – ${node.any[0]?.message ?? v.help}`, ), ); - expect(violations).toEqual([]); + const unchecked = results.incomplete + .filter((v) => v.id === "color-contrast") + .flatMap((v) => + v.nodes + .filter((node) => { + const message = node.any[0]?.message ?? ""; + if (message.includes(ICON_ONLY_MESSAGE)) return false; + return !(only && message.includes(OVERLAP_MESSAGE)); + }) + .map( + (node) => + `color-contrast not checked: ${node.target.join(" ")} – ${node.any[0]?.message}`, + ), + ); + + expect([ + ...violations, + ...unchecked, + ...(await checkNonTextContrast(page)), + ]).toEqual([]); +} + +// Components that must be visible against what is behind them (WCAG 1.4.11): +// the background or the border needs at least 3:1 against the background behind. +const BOUNDARY_SELECTORS = [ + '.plant-card-face[aria-hidden="false"] > .plant-card', + ".plant-card.empty-plant-card", + ".swipe-button:not(:disabled)", + ".info-button", + ".add-match-button", + ".reload-button", + ".sidebar-button", + ".plant-preferences button", + ".plant-owner-test-option", + ".sort-button", + ".pagination button:not(:disabled)", + "input", + "select", +]; + +// Buttons that only show a symbol: the symbol needs 3:1 against the button +const ICON_SELECTORS = [ + ".swipe-button:not(:disabled)", + ".info-button", + ".add-match-button", +]; + +// Tooltip text that axe can't check while the tooltip is open: 4.5:1 against +// the tooltip background +const TOOLTIP_TEXT_SELECTORS = [ + ".match-info-box h3", + ".match-info-box p", + ".preferences-info-box", + ".add-match-tooltip", +]; + +// Checks contrast that axe does not check, using the colors the browser has +// computed. Returns one line per problem, in the same form as the axe results. +async function checkNonTextContrast(page: Page): Promise { + return page.evaluate( + ({ boundarySelectors, iconSelectors, tooltipTextSelectors }) => { + type Rgba = [number, number, number, number]; + + const parse = (value: string): Rgba | null => { + const m = value.match(/rgba?\(([^)]+)\)/); + if (!m) return null; + const [r, g, b, a = 1] = m[1].split(/[\s,/]+/).map(Number); + return [r, g, b, a]; + }; + + // Puts a (possibly see-through) color on top of a solid color + const blend = (top: Rgba, bottom: Rgba): Rgba => { + const a = top[3]; + return [ + top[0] * a + bottom[0] * (1 - a), + top[1] * a + bottom[1] * (1 - a), + top[2] * a + bottom[2] * (1 - a), + 1, + ]; + }; + + const luminance = ([r, g, b]: Rgba) => { + const lin = (c: number) => { + const s = c / 255; + return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; + }; + return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b); + }; + + const ratio = (a: Rgba, b: Rgba) => { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); + }; + + // The solid color seen behind an element: its ancestors' backgrounds + // stacked on top of each other, starting from white + const backgroundBehind = (el: Element): Rgba => { + const ancestors: Element[] = []; + for (let p = el.parentElement; p; p = p.parentElement) { + ancestors.unshift(p); + } + return ancestors.reduce( + (color, ancestor) => { + const bg = parse(getComputedStyle(ancestor).backgroundColor); + return bg && bg[3] > 0 ? blend(bg, color) : color; + }, + [255, 255, 255, 1], + ); + }; + + const isShown = (el: Element) => { + const rect = el.getBoundingClientRect(); + return ( + rect.width > 0 && + rect.height > 0 && + el.checkVisibility({ + opacityProperty: true, + visibilityProperty: true, + }) + ); + }; + + const describe = (el: Element) => + el.tagName.toLowerCase() + + (el.id ? `#${el.id}` : "") + + [...el.classList].map((c) => `.${c}`).join("") + + (el.getAttribute("aria-label") + ? `[aria-label="${el.getAttribute("aria-label")}"]` + : ""); + + const problems: string[] = []; + const seen = new Set(); + const report = (line: string) => { + if (!seen.has(line)) problems.push(line); + seen.add(line); + }; + + for (const selector of boundarySelectors) { + for (const el of document.querySelectorAll(selector)) { + if (!isShown(el)) continue; + const style = getComputedStyle(el); + const behind = backgroundBehind(el); + const bg = parse(style.backgroundColor); + const own = bg && bg[3] > 0 ? blend(bg, behind) : behind; + const border = parse(style.borderTopColor); + const hasBorder = + parseFloat(style.borderTopWidth) > 0 && + style.borderTopStyle !== "none" && + border && + border[3] > 0; + + const surface = ratio(own, behind); + const edge = hasBorder ? ratio(blend(border, behind), behind) : 0; + if (Math.max(surface, edge) < 3) { + report( + `non-text-contrast: ${describe(el)} – background ${surface.toFixed(2)}:1 and ${hasBorder ? `border ${edge.toFixed(2)}:1` : "no border"} against what is behind, needs 3:1`, + ); + } + } + } + + for (const selector of iconSelectors) { + for (const el of document.querySelectorAll(selector)) { + if (!isShown(el)) continue; + const style = getComputedStyle(el); + const behind = backgroundBehind(el); + const bg = parse(style.backgroundColor); + const own = bg && bg[3] > 0 ? blend(bg, behind) : behind; + const icon = parse(style.color); + if (!icon) continue; + const value = ratio(blend(icon, own), own); + if (value < 3) { + report( + `icon-contrast: ${describe(el)} – icon ${value.toFixed(2)}:1 against the button, needs 3:1`, + ); + } + } + } + + for (const selector of tooltipTextSelectors) { + for (const el of document.querySelectorAll(selector)) { + if (!isShown(el)) continue; + const style = getComputedStyle(el); + const bg = parse(style.backgroundColor); + const behind = backgroundBehind(el); + const own = bg && bg[3] > 0 ? blend(bg, behind) : behind; + const text = parse(style.color); + if (!text) continue; + const value = ratio(blend(text, own), own); + if (value < 4.5) { + report( + `tooltip-contrast: ${describe(el)} – text ${value.toFixed(2)}:1 against the tooltip, needs 4.5:1`, + ); + } + } + } + + // Placeholder text is text, so it needs 4.5:1 against the input + for (const el of document.querySelectorAll( + "input[placeholder]", + )) { + if (!isShown(el) || el.value) continue; + const style = getComputedStyle(el); + const bg = parse(style.backgroundColor); + const own = + bg && bg[3] > 0 + ? blend(bg, backgroundBehind(el)) + : backgroundBehind(el); + const placeholder = parse(getComputedStyle(el, "::placeholder").color); + if (!placeholder) continue; + const value = ratio(blend(placeholder, own), own); + if (value < 4.5) { + report( + `placeholder-contrast: ${describe(el)} – ${value.toFixed(2)}:1 against the input, needs 4.5:1`, + ); + } + } + + return problems; + }, + { + boundarySelectors: BOUNDARY_SELECTORS, + iconSelectors: ICON_SELECTORS, + tooltipTextSelectors: TOOLTIP_TEXT_SELECTORS, + }, + ); } // Sets the theme the same way ThemeToggle does, after the page has loaded. // CSS transitions are turned off first, otherwise axe measures the colours -// halfway between the light and the dark theme. +// halfway between the light and the dark theme, or a tooltip that is fading in. async function setTheme(page: Page, theme: "light" | "dark") { await page.addStyleTag({ content: "*, *::before, *::after { transition: none !important; }", @@ -53,8 +306,7 @@ const PAGES = [ { name: "NotFound", path: "#/does-not-exist", loaded: ".not-found-page" }, ]; -// Colour contrast is the only check that differs between the themes, -// but both themes must meet the contrast requirements +// Both themes must meet the contrast requirements const THEMES = ["light", "dark"] as const; for (const theme of THEMES) { @@ -67,62 +319,142 @@ for (const theme of THEMES) { await checkAccessibility(page); }); } - }); -} -// Content that only appears after an interaction is not checked above + // Content that only appears after an interaction is not checked above -test.describe("after interaction", () => { - test("ExplorePlants with a plant card flipped", async ({ page }) => { - await page.goto("#/explorePlants"); - const firstCard = page.locator(".plant-grid > li").first(); - await firstCard.locator(".plant-card-front .plant-card-hint").click(); - await expect(firstCard.locator(".plant-card-face-back")).toHaveAttribute( - "aria-hidden", - "false", - ); - await checkAccessibility(page); - }); + test.describe("after interaction", () => { + test("ExplorePlants with a plant card flipped", async ({ page }) => { + await page.goto("#/explorePlants"); + const firstCard = page.locator(".plant-grid > li").first(); + await firstCard.locator(".plant-card-front .plant-card-hint").click(); + await expect( + firstCard.locator(".plant-card-face-back"), + ).toHaveAttribute("aria-hidden", "false"); + await setTheme(page, theme); + await checkAccessibility(page); + }); - test("Profile with the edit tab open", async ({ page }) => { - await page.goto("#/profile"); - await page - .getByRole("button", { name: /edit profile|endre profil/i }) - .click(); - await expect(page.locator("#profile-name")).toBeVisible(); - await checkAccessibility(page); - }); + test("ExplorePlants showing the add to matches tooltip", async ({ + page, + }) => { + await page.goto("#/explorePlants"); + await setTheme(page, theme); + const firstItem = page.locator(".plant-grid > li").first(); + await firstItem.locator(".add-match-button").hover(); + await expect(firstItem.locator(".add-match-tooltip")).toBeVisible(); + await checkAccessibility(page, ".add-match-tooltip"); + }); - test("MyMatches with a matched plant", async ({ page }) => { - // A new user has no matches, so add one from ExplorePlants first - await page.goto("#/explorePlants"); - const addButton = page - .locator(".plant-grid > li") - .first() - .locator(".add-match-button"); - await addButton.click(); - await expect(addButton).toHaveClass(/add-match-button--matched/); - - await page.goto("#/my-matches"); - await expect(page.locator(".plant-card-match")).toHaveCount(1); - await checkAccessibility(page); - }); + test("PlantMatch showing the how to match tooltip", async ({ page }) => { + await page.goto(""); + await expect(page.locator(".plant-card-front")).toBeVisible(); + await setTheme(page, theme); + await page.locator(".match-info-button").hover(); + await expect(page.locator(".match-info-box")).toBeVisible(); + await checkAccessibility(page, ".match-info-box"); + }); + + test("PlantMatch with no more plants", async ({ page }) => { + // The backend answers that there are no plants, so the done card shows + await page.route("**/graphql", async (route) => { + if (route.request().postDataJSON()?.operationName === "GetPlants") { + await route.fulfill({ json: { data: { getPlants: [] } } }); + } else { + await route.fallback(); + } + }); + await page.goto(""); + await expect(page.locator(".empty-plant-card")).toBeVisible(); + await expect(page.locator(".reload-button")).toBeVisible(); + await setTheme(page, theme); + await checkAccessibility(page); + }); - test("PlantOwnerTest showing a result", async ({ page }) => { - await page.goto("#/plantOwnerTest"); + test("PlantMatch when the plants can't be loaded", async ({ page }) => { + await page.route("**/graphql", async (route) => { + if (route.request().postDataJSON()?.operationName === "GetPlants") { + await route.abort(); + } else { + await route.fallback(); + } + }); + await page.goto(""); + await expect(page.locator(".empty-plant-card")).toBeVisible(); + await setTheme(page, theme); + await checkAccessibility(page); + }); - const options = page.locator(".plant-owner-test-option"); - const nextButton = page - .locator(".plant-owner-test-navigation button") - .last(); + test("Profile with the edit tab open", async ({ page }) => { + await page.goto("#/profile"); + await page + .getByRole("button", { name: /edit profile|endre profil/i }) + .click(); + await expect(page.locator("#profile-name")).toBeVisible(); + await setTheme(page, theme); + await checkAccessibility(page); + }); - // Picks the first option on all four questions, which gives "cityMinimalist" - for (let question = 0; question < 4; question++) { - await options.first().click(); - await nextButton.click(); - } + test("Profile showing the preferences tooltip", async ({ page }) => { + await page.goto("#/profile"); + await setTheme(page, theme); + await page.locator(".preferences-info-button").hover(); + await expect(page.locator(".preferences-info-box")).toBeVisible(); + await checkAccessibility(page, ".preferences-info-box"); + }); + + test("MyMatches with a matched plant", async ({ page }) => { + // A new user has no matches, so add one from ExplorePlants first + await page.goto("#/explorePlants"); + const addButton = page + .locator(".plant-grid > li") + .first() + .locator(".add-match-button"); + await addButton.click(); + await expect(addButton).toHaveClass(/add-match-button--matched/); + + await page.goto("#/my-matches"); + await expect(page.locator(".plant-card-match")).toHaveCount(1); + await setTheme(page, theme); + await checkAccessibility(page); + }); + + test("PlantOwnerTest showing a result", async ({ page }) => { + await page.goto("#/plantOwnerTest"); + + const options = page.locator(".plant-owner-test-option"); + const nextButton = page + .locator(".plant-owner-test-navigation button") + .last(); + + // Picks the first option on all four questions, which gives "cityMinimalist" + for (let question = 0; question < 4; question++) { + await options.first().click(); + await nextButton.click(); + } - await expect(page.locator(".plant-owner-test-result")).toBeVisible(); - await checkAccessibility(page); + await expect(page.locator(".plant-owner-test-result")).toBeVisible(); + await setTheme(page, theme); + await checkAccessibility(page); + }); + + test("Sidebar open, with the language and theme buttons reachable", async ({ + page, + }) => { + await page.goto(""); + await expect(page.locator(".plant-card-front")).toBeVisible(); + await setTheme(page, theme); + // Only does something on small screens, where the sidebar is a menu + await openSidebar(page); + + // The buttons at the bottom of the sidebar must be possible to scroll to + for (const button of await page + .locator(".sidebar__footer button") + .all()) { + await button.scrollIntoViewIfNeeded(); + await expect(button).toBeInViewport(); + } + await checkAccessibility(page); + }); + }); }); -}); +} diff --git a/frontend/src/components/matchButton/MatchButton.css b/frontend/src/components/matchButton/MatchButton.css new file mode 100644 index 00000000..95f733ac --- /dev/null +++ b/frontend/src/components/matchButton/MatchButton.css @@ -0,0 +1,83 @@ +/* The round flower button in the top right corner of a plant card, used on + Explore Plants and My Matches. The parent of the card must be position: relative. */ +.add-match { + position: absolute; + top: -15px; + right: -15px; + z-index: 2; +} + +.add-match-tooltip { + position: absolute; + top: calc(100% + 8px); + right: 0; + z-index: 20; + padding: 8px 12px; + background: var(--light-background); + color: var(--pink-text); + border-radius: 10px; + box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12); + font-size: 14px; + white-space: nowrap; + opacity: 0; + visibility: hidden; + pointer-events: none; + transition: + opacity 0.15s ease, + visibility 0.15s ease; +} + +.add-match:hover .add-match-tooltip, +.add-match:focus-within .add-match-tooltip { + opacity: 1; + visibility: visible; +} + +/* Not matched: a filled dark pink button with a white flower */ +.add-match-button { + width: 50px; + height: 50px; + display: flex; + align-items: center; + justify-content: center; + border: 2px solid var(--dark-pink); + border-radius: 50%; + background-color: var(--dark-pink); + color: var(--text-light); + font-size: 18px; + line-height: 1; + cursor: pointer; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); +} + +/* Matched: white with a dark pink border and flower */ +.add-match-button--matched { + background-color: var(--light-background); + color: var(--dark-pink); +} + +/* In dark mode the dark pink border is too close to the dark pink results box + behind the button (2.6:1), so the border and focus ring are white */ +[data-theme="dark"] .add-match-button { + 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); +} + +.add-match-button:focus-visible { + outline: none; + box-shadow: 0 0 0 3px var(--dark-pink); +} + +@media (max-width: 767px) { + .add-match-button { + width: 35px; + height: 35px; + } +} diff --git a/frontend/src/components/matchButton/MatchButton.tsx b/frontend/src/components/matchButton/MatchButton.tsx new file mode 100644 index 00000000..ccabc00a --- /dev/null +++ b/frontend/src/components/matchButton/MatchButton.tsx @@ -0,0 +1,43 @@ +import "./MatchButton.css"; + +type Props = { + isMatched: boolean; + // Says what the button does, shown as a tooltip and read by screen readers + label: string; + onClick: () => void; + className?: string; +}; + +// The flower button on a plant card that adds the plant to My Matches, or +// removes it if it is already there. Placed next to the card, not inside it, +// so there are no nested buttons. +export default function MatchButton({ + isMatched, + label, + onClick, + className, +}: Props) { + const classes = [ + "add-match-button", + isMatched && "add-match-button--matched", + className, + ] + .filter(Boolean) + .join(" "); + + return ( + + + + + ); +} diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index 25e9ad0c..5a0023ab 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -124,8 +124,13 @@ height: var(--card-fold); --flap-fill: var(--card-flap); + /* Same as the fill unless a face sets its own border color */ + --flap-border: var(--flap-fill); + --flap-border-width: 2px; - background: var(--flap-fill); + /* The triangle is drawn in the border color, and a smaller triangle in the + fill color on top. A normal border would not follow the diagonal edge. */ + background: var(--flap-border); clip-path: polygon(0 0, 100% 0, 0 100%); pointer-events: none; @@ -135,6 +140,25 @@ height 0.2s ease; } +.plant-card-flap::after { + /* The diagonal edge is moved in by the border width times sqrt(2) */ + --flap-inset: calc(var(--flap-border-width) * 2.414); + + content: ""; + position: absolute; + inset: 0; + background: var(--flap-fill); + clip-path: polygon( + var(--flap-border-width) var(--flap-border-width), + calc(100% - var(--flap-inset)) var(--flap-border-width), + var(--flap-border-width) calc(100% - var(--flap-inset)) + ); +} + +.plant-card-face-front .plant-card-flap { + --flap-border: var(--soft-green); +} + @media (prefers-reduced-motion: reduce) { .plant-card-flipper, .plant-card-face, diff --git a/frontend/src/components/sortMenu/SortMenu.css b/frontend/src/components/sortMenu/SortMenu.css index f9e841af..aa6a8aa1 100644 --- a/frontend/src/components/sortMenu/SortMenu.css +++ b/frontend/src/components/sortMenu/SortMenu.css @@ -21,6 +21,12 @@ cursor: pointer; } +/* On My Matches the button lies on the dark pink box, where a dark pink border + is too weak in dark mode (2.6:1), so it is white there */ +[data-theme="dark"] .sort-button { + border-color: var(--text-light); +} + .sort-button-icon { font-size: 1.5rem; flex-shrink: 0; diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index d8aa4c58..c07093d9 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -90,7 +90,7 @@ "myMatchesPage": { "loading": "Loading your matches...", "noMatches": "You have no matches yet. Press the flower on the match page to match with a plant.", - "removeMatch": "Remove the match", + "removeMatch": "Remove from My Matches", "matchCount_one": "You have {{count}} match", "matchCount_other": "You have {{count}} matches", "sort": "Sort", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index bb83fab6..ee9528ac 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -90,7 +90,7 @@ "myMatchesPage": { "loading": "Laster matchene dine...", "noMatches": "Du har ingen matcher ennå. Trykk på blomsten på match-siden for å matche med en plante.", - "removeMatch": "Fjern matchen", + "removeMatch": "Fjern fra Mine Matches", "matchCount_one": "Du har {{count}} match", "matchCount_other": "Du har {{count}} matches", "sort": "Sorter", diff --git a/frontend/src/index.css b/frontend/src/index.css index 50e3bef7..4aa9244e 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -57,6 +57,7 @@ textarea { used on white or light backgrounds there too. */ --deep-green: #2e4a3b; --cream: #f5f1e8; + --soft-green: #a9b48a; /* Front of the plant card: dark green with light text in light mode */ --card-front: var(--deep-green); --card-hint: var(--cream); diff --git a/frontend/src/pages/explorePlants/ExplorePlants.css b/frontend/src/pages/explorePlants/ExplorePlants.css index 0891d75f..3bcc0020 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.css +++ b/frontend/src/pages/explorePlants/ExplorePlants.css @@ -130,71 +130,6 @@ position: relative; } -.add-match { - position: absolute; - top: -15px; - right: -15px; - z-index: 2; -} - -.add-match-tooltip { - position: absolute; - top: calc(100% + 8px); - right: 0; - z-index: 20; - padding: 8px 12px; - background: var(--light-background); - color: var(--pink-text); - border-radius: 10px; - box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12); - font-size: 14px; - white-space: nowrap; - opacity: 0; - visibility: hidden; - pointer-events: none; - transition: - opacity 0.15s ease, - visibility 0.15s ease; -} - -.add-match:hover .add-match-tooltip, -.add-match:focus-within .add-match-tooltip { - opacity: 1; - visibility: visible; -} - -/* Not matched: a filled dark pink button with a white flower */ -.add-match-button { - width: 50px; - height: 50px; - display: flex; - align-items: center; - justify-content: center; - border: 2px solid var(--dark-pink); - border-radius: 50%; - background-color: var(--dark-pink); - color: var(--text-light); - font-size: 18px; - line-height: 1; - cursor: pointer; - box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15); -} - -/* Matched: white with a dark pink border and flower */ -.add-match-button--matched { - background-color: var(--light-background); - color: var(--dark-pink); -} - -.add-match-button:hover { - transform: scale(1.1); -} - -.add-match-button:focus-visible { - outline: none; - box-shadow: 0 0 0 3px var(--dark-pink); -} - @media (max-width: 767px) { .explore-page { margin-left: 0; @@ -212,9 +147,4 @@ grid-template-columns: 1fr; gap: 20px; } - - .add-match-button { - width: 35px; - height: 35px; - } } diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index 6af308fe..fa37c421 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -11,6 +11,7 @@ import PlantCard from "../../components/plantCard/PlantCard.tsx"; import Pagination from "../../components/pagination/Pagination.tsx"; import FilterSelect from "../../components/filterSelect/FilterSelect.tsx"; import SortMenu from "../../components/sortMenu/SortMenu.tsx"; +import MatchButton from "../../components/matchButton/MatchButton.tsx"; import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; import "./ExplorePlants.css"; @@ -153,22 +154,13 @@ export default function ExplorePlants() { return (
  • - {/* Sibling of the card (not inside it), so no nested buttons */} - - - - + + isMatched ? removeMatch(plant.id) : addMatch(plant) + } + />
  • ); })} diff --git a/frontend/src/pages/myMatches/MyMatchesPage.css b/frontend/src/pages/myMatches/MyMatchesPage.css index 2073326e..2aeefff1 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.css +++ b/frontend/src/pages/myMatches/MyMatchesPage.css @@ -59,25 +59,6 @@ justify-self: center; } -.remove-match-button { - position: absolute; - top: -15px; - right: -15px; - z-index: 2; - width: 50px; - height: 50px; - border: none; - border-radius: 50%; - background: var(--dark-pink); - color: var(--text-light); - font-size: 18px; - cursor: pointer; -} - -.remove-match-button:hover { - transform: scale(1.1); -} - @media (max-width: 767px) { .my-matches-page { margin-left: 0; @@ -92,9 +73,4 @@ padding: 20px 12px; border-radius: 12px; } - - .remove-match-button { - width: 35px; - height: 35px; - } } diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index e7f18dfe..c844c218 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useQuery } from "@apollo/client/react"; +import MatchButton from "../../components/matchButton/MatchButton.tsx"; import "./MyMatchesPage.css"; import PlantCard from "../../components/plantCard/PlantCard.tsx"; import Pagination from "../../components/pagination/Pagination.tsx"; @@ -86,13 +87,13 @@ function MyMatchesPage() { {plants.map((plant) => (
    - + className="remove-match-button" + />
    ))} From bc51e287870eda1a7db02f2c575570ad687d7f25 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 11:34:53 +0100 Subject: [PATCH 5/8] Added which card in plant match you are on to session storage and made titles wrap on the plantcards if they are long, and made the icons for dark and lightmode into svg icons --- e2e/uiAccessibility.spec.ts | 4 +- e2e/uiMatchAndRemovePlant.spec.ts | 32 ++++++++++++ .../src/components/plantCard/PlantCard.css | 11 +++-- .../sidebarButtons/SideBarButton.css | 14 ++++++ .../components/sidebarButtons/ThemeIcons.tsx | 47 ++++++++++++++++++ .../components/sidebarButtons/ThemeToggle.tsx | 3 +- frontend/src/hooks/usePlantDeck.ts | 49 +++++++++++++++++-- frontend/src/tests/PlantMatchPage.test.tsx | 38 +++++++++++++- frontend/src/tests/ThemeToggle.test.tsx | 13 +++++ 9 files changed, 201 insertions(+), 10 deletions(-) create mode 100644 frontend/src/components/sidebarButtons/ThemeIcons.tsx diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index 9a221fe8..ac2310e0 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -91,6 +91,8 @@ const ICON_SELECTORS = [ ".swipe-button:not(:disabled)", ".info-button", ".add-match-button", + // The SVG in the theme button, measured against the button behind it + ".theme-icon", ]; // Tooltip text that axe can't check while the tooltip is open: 4.5:1 against @@ -219,7 +221,7 @@ async function checkNonTextContrast(page: Page): Promise { const value = ratio(blend(icon, own), own); if (value < 3) { report( - `icon-contrast: ${describe(el)} – icon ${value.toFixed(2)}:1 against the button, needs 3:1`, + `icon-contrast: ${describe(el)} – icon ${value.toFixed(2)}:1 against what is behind it, needs 3:1`, ); } } diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index f7bf9bbf..bb8bbb6f 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -122,3 +122,35 @@ test("user can sort the matches in MyMatches and move between pages", async ({ await page.reload(); await expect(matchCards.first()).toContainText("Aloe Vera"); }); + +test("PlantMatch continues from the same card after visiting another page and after a reload", async ({ + page, +}) => { + await page.goto(""); + // Scoped to PlantMatch, so the cards on Explore Plants are not matched + const cardName = page.locator( + ".plant-match .plant-card-front .plant-card-name", + ); + await expect(cardName).toBeVisible(); + + // Skip the first plant, so the deck is on the second card + const firstName = (await cardName.textContent())?.trim(); + await page.locator("button.dislike-button").click(); + await expect(cardName).not.toHaveText(firstName ?? ""); + const currentName = (await cardName.textContent())?.trim(); + + // Visit another page and come back + await openSidebar(page); + await page.locator('a[href$="/explorePlants"]').click(); + await expect(page.locator(".plant-grid > li").first()).toBeVisible(); + await openSidebar(page); + await page + .locator("#sidebar") + .getByRole("link", { name: /plant match|plante-matching/i }) + .click(); + await expect(cardName).toHaveText(currentName ?? ""); + + // sessionStorage is kept when the page is reloaded in the same tab + await page.reload(); + await expect(cardName).toHaveText(currentName ?? ""); +}); diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index 5a0023ab..e07554cd 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -195,7 +195,9 @@ flex: none; height: var(--card-name-height); - padding: 5px 40px; + /* Room on both sides for the round button in the top right corner of the + card, so a long name is not hidden under it */ + padding: 5px 48px; display: flex; align-items: center; @@ -291,7 +293,8 @@ .plant-card-back-header { flex: none; - padding: 20px 28px 16px; + /* Room on both sides for the round button in the top right corner */ + padding: 20px 48px 16px; background: var(--dark-green); color: var(--text-on-green); @@ -409,7 +412,7 @@ .plant-card-front .plant-card-name { height: auto; min-height: var(--card-name-height); - padding: 10px 16px; + padding: 10px 24px; font-size: clamp(1.05rem, 6.5cqw, 1.25rem); overflow-wrap: anywhere; } @@ -425,7 +428,7 @@ } .plant-card-back-header { - padding: 16px 16px 12px; + padding: 16px 24px 12px; } .plant-card-back .plant-card-name { diff --git a/frontend/src/components/sidebarButtons/SideBarButton.css b/frontend/src/components/sidebarButtons/SideBarButton.css index 493c75df..63e62bd9 100644 --- a/frontend/src/components/sidebarButtons/SideBarButton.css +++ b/frontend/src/components/sidebarButtons/SideBarButton.css @@ -9,6 +9,20 @@ cursor: pointer; } +/* White on the dark green button in light mode, dark on the light green + button in dark mode */ +.theme-icon { + display: block; + width: 22px; + height: 22px; + margin: 0 auto; + color: var(--text-light); +} + +[data-theme="dark"] .theme-icon { + color: var(--text-on-green); +} + .language-button { font-size: 19px; font-weight: 600; diff --git a/frontend/src/components/sidebarButtons/ThemeIcons.tsx b/frontend/src/components/sidebarButtons/ThemeIcons.tsx new file mode 100644 index 00000000..6067b0e7 --- /dev/null +++ b/frontend/src/components/sidebarButtons/ThemeIcons.tsx @@ -0,0 +1,47 @@ +// Simple icons for the theme button. They use currentColor, so the color is +// set in CSS (.theme-icon in SideBarButton.css). aria-hidden, since the +// button already has a label for screen readers. + +export function MoonIcon() { + return ( + + ); +} + +export function SunIcon() { + // The eight rays, every 45 degrees around the center + const rays = [0, 45, 90, 135, 180, 225, 270, 315]; + + return ( + + ); +} diff --git a/frontend/src/components/sidebarButtons/ThemeToggle.tsx b/frontend/src/components/sidebarButtons/ThemeToggle.tsx index ee115d03..00f9f31e 100644 --- a/frontend/src/components/sidebarButtons/ThemeToggle.tsx +++ b/frontend/src/components/sidebarButtons/ThemeToggle.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import { MoonIcon, SunIcon } from "./ThemeIcons"; import "./SideBarButton.css"; export default function ThemeToggle() { @@ -35,7 +36,7 @@ export default function ThemeToggle() { darkMode ? "sidebar.switchToLightMode" : "sidebar.switchToDarkMode", )} > - {darkMode ? "🌞️" : "🌚"} + {darkMode ? : } ); } diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 047c1a0c..5271cf65 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -10,6 +10,38 @@ export const PLANT_BATCH_SIZE = 8; // The next batch is fetched when this many cards (or fewer) are left in the deck export const PREFETCH_THRESHOLD = 3; +// The deck is saved in sessionStorage, so the user comes back to the same card +// after visiting another page. Only the cards that are left are saved, since +// the images are large base64 strings. +export const DECK_STORAGE_KEY = "plantMatch.deck"; + +type SavedDeck = { plants: Plant[]; seenIds: string[]; hasMore: boolean }; + +function loadDeck(): SavedDeck | null { + try { + const saved = JSON.parse(sessionStorage.getItem(DECK_STORAGE_KEY) ?? ""); + if (Array.isArray(saved?.plants) && Array.isArray(saved?.seenIds)) { + return saved; + } + } catch { + // Nothing saved, or storage is not available + } + return null; +} + +function saveDeck(deck: SavedDeck) { + try { + sessionStorage.setItem(DECK_STORAGE_KEY, JSON.stringify(deck)); + } catch { + // Storage can be full or blocked. The deck then starts over next time. + try { + sessionStorage.removeItem(DECK_STORAGE_KEY); + } catch { + // Storage is not available at all + } + } +} + // A deck of plants that is loaded in small batches while the user swipes. // Plants already in the deck are excluded by the backend, so a plant is never // shown twice while the page is open. Plants matching the most of the user's @@ -17,15 +49,26 @@ export const PREFETCH_THRESHOLD = 3; export function usePlantDeck() { const client = useApolloClient(); const { user, loading: userLoading } = useUser(); - const [plants, setPlants] = useState([]); + // Continues from the saved deck if the user has been here before in this tab + const [saved] = useState(loadDeck); + const [plants, setPlants] = useState(saved?.plants ?? []); const [index, setIndex] = useState(0); const [loading, setLoading] = useState(false); const [error, setError] = useState(); - const [hasMore, setHasMore] = useState(true); + const [hasMore, setHasMore] = useState(saved?.hasMore ?? true); // Refs, so a second call in the same render can't start a duplicate request const inFlight = useRef(false); - const seenIds = useRef(new Set()); + const seenIds = useRef(new Set(saved?.seenIds ?? [])); + + // Save the cards that are left after every swipe and every new batch + useEffect(() => { + saveDeck({ + plants: plants.slice(index), + seenIds: [...seenIds.current], + hasMore, + }); + }, [plants, index, hasMore]); // Read when a batch is fetched, so new preferences don't restart the deck // Declared before the fetch effect, so it runs first diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 529c5e59..8f973641 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -1,7 +1,11 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, it, expect, vi } from "vitest"; import PlantMatchPage from "../pages/plantMatch/PlantMatchPage"; -import { PLANT_BATCH_SIZE, PREFETCH_THRESHOLD } from "../hooks/usePlantDeck"; +import { + DECK_STORAGE_KEY, + PLANT_BATCH_SIZE, + PREFETCH_THRESHOLD, +} from "../hooks/usePlantDeck"; import type { Plant } from "../types/Plant"; const { query, addUserMatch, useUser } = vi.hoisted(() => ({ @@ -70,6 +74,7 @@ function mockUser(preferences: string[] = []) { } beforeEach(() => { + sessionStorage.clear(); addUserMatch.mockClear(); query.mockReset(); mockUser(); @@ -207,6 +212,37 @@ describe("PlantMatchPage", () => { ).not.toHaveLength(0); }); + it("continues from the same card after leaving the page and coming back", async () => { + const { unmount } = render(); + await screen.findAllByText("Hydrangea"); + skip(); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + unmount(); + + query.mockClear(); + render(); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + expect(screen.queryByText("Hydrangea")).not.toBeInTheDocument(); + // The saved card is shown without asking the backend again + expect(query).not.toHaveBeenCalled(); + }); + + it("only saves the cards that are left, not the ones already swiped", async () => { + render(); + await screen.findAllByText("Hydrangea"); + skip(); + const saved = JSON.parse(sessionStorage.getItem(DECK_STORAGE_KEY) ?? ""); + expect(saved.plants.map((p: Plant) => p.name)).toEqual(["Orchid"]); + // Swiped plants are remembered, so the backend does not send them again + expect(saved.seenIds).toEqual(["0", "1"]); + }); + + it("starts a new deck when the saved deck can't be read", async () => { + sessionStorage.setItem(DECK_STORAGE_KEY, "not json"); + render(); + expect((await screen.findAllByText("Hydrangea")).length).toBeGreaterThan(0); + }); + it("starts the deck over from the first plant with the reload button", async () => { render(); await screen.findAllByText("Hydrangea"); diff --git a/frontend/src/tests/ThemeToggle.test.tsx b/frontend/src/tests/ThemeToggle.test.tsx index dacc91d0..c21d16e7 100644 --- a/frontend/src/tests/ThemeToggle.test.tsx +++ b/frontend/src/tests/ThemeToggle.test.tsx @@ -34,6 +34,19 @@ describe("ThemeToggle", () => { ).toBeInTheDocument(); }); + it("shows a moon in light mode and a sun in dark mode", async () => { + const user = userEvent.setup(); + const { container } = render(); + expect(container.querySelector(".theme-icon--moon")).toBeInTheDocument(); + expect(container.querySelector(".theme-icon--sun")).not.toBeInTheDocument(); + + await user.click(screen.getByRole("button")); + expect(container.querySelector(".theme-icon--sun")).toBeInTheDocument(); + expect( + container.querySelector(".theme-icon--moon"), + ).not.toBeInTheDocument(); + }); + it.each(["dark", "light"])("restores saved %s mode on mount", (theme) => { localStorage.setItem("theme", theme); render(); From 446452a35d3a561072da410fa5c0090c573a674e Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 11:39:35 +0100 Subject: [PATCH 6/8] plants you allready have matched with do not any longer appear in the matching page --- e2e/uiMatchAndRemovePlant.spec.ts | 36 ++++++++++++++++++++++ frontend/src/hooks/usePlantDeck.ts | 35 +++++++++++++++------ frontend/src/tests/PlantMatchPage.test.tsx | 31 +++++++++++++++++-- 3 files changed, 90 insertions(+), 12 deletions(-) diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index bb8bbb6f..c5012cca 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -154,3 +154,39 @@ test("PlantMatch continues from the same card after visiting another page and af await page.reload(); await expect(cardName).toHaveText(currentName ?? ""); }); + +test("a plant matched on ExplorePlants never shows up in PlantMatch", async ({ + page, +}) => { + await page.goto("#/explorePlants"); + const firstItem = page.locator(".plant-grid > li").first(); + const matchedName = ( + await firstItem.locator(".plant-card-front .plant-card-name").textContent() + )?.trim(); + const addButton = firstItem.locator(".add-match-button"); + await addButton.click(); + await expect(addButton).toHaveClass(/add-match-button--matched/); + + await openSidebar(page); + await page + .locator("#sidebar") + .getByRole("link", { name: /plant match|plante-matching/i }) + .click(); + + // Skip through the whole deck and check every card on the way + const cardName = page.locator( + ".plant-match .plant-card-front .plant-card-name", + ); + const doneCard = page.locator(".empty-plant-card"); + const shown: string[] = []; + while (!(await doneCard.isVisible())) { + await expect(cardName.or(doneCard)).toBeVisible(); + if (await doneCard.isVisible()) break; + const name = (await cardName.textContent())?.trim() ?? ""; + shown.push(name); + await page.locator("button.dislike-button").click(); + await expect(cardName.or(doneCard)).not.toHaveText(name); + } + expect(shown.length).toBeGreaterThan(0); + expect(shown).not.toContain(matchedName); +}); diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 5271cf65..811fa3a5 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useApolloClient } from "@apollo/client/react"; import { useUser } from "../context/UserContext"; import { GET_PLANTS, type GetPlantsData } from "../graphql/plants/queries"; @@ -73,8 +73,11 @@ export function usePlantDeck() { // Read when a batch is fetched, so new preferences don't restart the deck // Declared before the fetch effect, so it runs first const preferences = useRef([]); + // The user's matches are never shown, so they are excluded from every batch + const matchedIds = useRef([]); useEffect(() => { preferences.current = user?.preferences ?? []; + matchedIds.current = user?.matchedPlantIds ?? []; }, [user]); const loadMore = useCallback(async () => { @@ -86,7 +89,7 @@ export function usePlantDeck() { query: GET_PLANTS, variables: { limit: PLANT_BATCH_SIZE, - excludeIds: [...seenIds.current], + excludeIds: [...new Set([...seenIds.current, ...matchedIds.current])], preferences: preferences.current, }, fetchPolicy: "no-cache", @@ -111,20 +114,32 @@ export function usePlantDeck() { } }, [client]); + // Plants can be matched on other pages while they are in the deck (or in the + // saved deck), so matched plants are skipped here too + const matched = useMemo( + () => new Set(user?.matchedPlantIds ?? []), + [user?.matchedPlantIds], + ); + const firstUnmatched = plants.findIndex( + (p, i) => i >= index && !matched.has(p.id), + ); + const shownIndex = firstUnmatched === -1 ? plants.length : firstUnmatched; + const cardsLeft = plants + .slice(index) + .filter((p) => !matched.has(p.id)).length; + // Fetch the first batch, and the next one when the deck is nearly empty. // After a failed request it tries again on the next swipe. // Waits for the user, so the first batch is already sorted by preferences. useEffect(() => { - if ( - !userLoading && - hasMore && - plants.length - index <= PREFETCH_THRESHOLD - ) { + if (!userLoading && hasMore && cardsLeft <= PREFETCH_THRESHOLD) { void loadMore(); } - }, [index, plants.length, hasMore, loadMore, userLoading]); + }, [cardsLeft, hasMore, loadMore, userLoading]); - const next = useCallback(() => setIndex((current) => current + 1), []); + // Goes past the card that is shown, which can be after `index` if matched + // plants were skipped + const next = useCallback(() => setIndex(shownIndex + 1), [shownIndex]); // Start the deck over from the first plant. Also used to try again after an // error. The fetch effect above loads the first batch again. @@ -136,7 +151,7 @@ export function usePlantDeck() { setHasMore(true); }, []); - const plant = plants[index]; + const plant = plants[shownIndex]; return { plant, diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 8f973641..b209cc30 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -58,7 +58,7 @@ const skip = () => ); // A user with the given saved preferences and no matches yet -function mockUser(preferences: string[] = []) { +function mockUser(preferences: string[] = [], matchedPlantIds: string[] = []) { useUser.mockReturnValue({ userId: "user-1", user: { @@ -67,7 +67,7 @@ function mockUser(preferences: string[] = []) { description: null, profilePicture: "default", preferences, - matchedPlantIds: [], + matchedPlantIds, }, loading: false, }); @@ -212,6 +212,33 @@ describe("PlantMatchPage", () => { ).not.toHaveLength(0); }); + it("does not show plants the user has already matched", async () => { + mockUser([], ["0"]); + render(); + expect((await screen.findAllByText("Orchid")).length).toBeGreaterThan(0); + expect(screen.queryByText("Hydrangea")).not.toBeInTheDocument(); + expect(query.mock.calls[0][0].variables.excludeIds).toEqual(["0"]); + }); + + it("skips a card in the deck when the plant is matched on another page", async () => { + const { rerender } = render(); + await screen.findAllByText("Hydrangea"); + + // Hydrangea is matched somewhere else, for example on Explore Plants + mockUser([], ["0"]); + rerender(); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + expect(screen.queryByText("Hydrangea")).not.toBeInTheDocument(); + + // Skipping Orchid goes to the end, not back to Hydrangea + skip(); + expect( + await screen.findByRole("heading", { + name: "plantMatchPage.noMorePlantsTitle", + }), + ).toBeInTheDocument(); + }); + it("continues from the same card after leaving the page and coming back", async () => { const { unmount } = render(); await screen.findAllByText("Hydrangea"); From 6a1c1daf4e8a3497f13d978869ed8bc4b6875281 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Wed, 11 Nov 2026 11:54:10 +0100 Subject: [PATCH 7/8] Made the scaling on the plantcard between languages consistens --- frontend/src/components/plantCard/PlantCard.css | 13 ++++++++++++- frontend/src/components/plantCard/PlantCard.tsx | 8 ++++++-- frontend/src/i18n/locales/en/translation.json | 2 +- frontend/src/i18n/locales/no/translation.json | 2 +- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index e07554cd..0407c3f5 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -265,12 +265,23 @@ color: var(--card-hint); - font-size: 1rem; + /* The same size as on the compact cards on Explore Plants + (1.125rem at 80 % zoom) */ + font-size: 0.9rem; font-weight: 600; line-height: 1.3; text-align: center; } +/* Always room for two lines, so the card does not move when the text gets + shorter or longer, for example when the language is changed */ +.plant-card-hint-text { + display: flex; + align-items: center; + justify-content: center; + min-height: calc(2 * 1.3em); +} + .plant-card-hint:focus { outline: none; } diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index f4e1d926..1a506d71 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -98,7 +98,9 @@ export default function PlantCard({ plant, size = "large", onInfo }: Props) { className="plant-card-hint" aria-expanded={false} > - {t("plantCard.tapForDetails")} + + {t("plantCard.tapForDetails")} +