From 3404b2041c745d8ebb5ed321d3d7db9eaf9ed946 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Mon, 23 Nov 2026 11:13:05 +0100 Subject: [PATCH 1/6] Remove duplicated preference logic --- backend/src/queryBuilders.ts | 4 +- e2e/apiUserProfile.spec.ts | 17 +++++- .../src/components/plantCard/plantTraits.ts | 60 +++++++++++++++++-- .../PlantPreferenceChips.tsx | 60 +------------------ .../plantPreferences/PlantPreferences.tsx | 22 +++---- .../plantOwnerTest/SuggestedPreferences.tsx | 7 ++- .../pages/plantOwnerTest/plantOwnerTest.ts | 12 ++-- frontend/src/pages/profile/ProfilePage.tsx | 19 +----- frontend/src/tests/PlantPreferences.test.tsx | 28 +++++---- frontend/src/types/Preference.ts | 20 +++++-- 10 files changed, 127 insertions(+), 122 deletions(-) diff --git a/backend/src/queryBuilders.ts b/backend/src/queryBuilders.ts index 270e9b97..10fd207f 100644 --- a/backend/src/queryBuilders.ts +++ b/backend/src/queryBuilders.ts @@ -222,8 +222,8 @@ const sunlightIncludes = (text: string): Document => ({ }); // How each preference id maps to the plant attributes. Must match -// frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx -// and the preference ids in frontend/src/pages/profile/ProfilePage.tsx. +// PREFERENCE_IDS in frontend/src/types/Preference.ts and getPlantPreferences +// in frontend/src/components/plantCard/plantTraits.ts. // The data uses "Low" for easy care and both "Medium" and "Moderate". export const PREFERENCE_MATCHERS: Record = { minimumWater: { $eq: [lower("$watering"), "minimum"] }, diff --git a/e2e/apiUserProfile.spec.ts b/e2e/apiUserProfile.spec.ts index 9fc67922..bb26b315 100644 --- a/e2e/apiUserProfile.spec.ts +++ b/e2e/apiUserProfile.spec.ts @@ -1,9 +1,9 @@ import { test, expect } from "@playwright/test"; import { graphql, createUser, CREATE_USER, GET_USER } from "./helpers/graphql"; +import { PREFERENCE_IDS } from "../frontend/src/types/Preference"; // Tests the user profile in the API: a new user's defaults, name, description, // avatar and preferences, and that invalid values are rejected. - const UPDATE_PROFILE = ` mutation UpdateProfile( $userId: ID! @@ -86,6 +86,21 @@ test.describe("typical use", () => { }); }); + // The frontend and backend have their own lists of preferences, so this + // fails if one is added in the frontend but not in the backend + test("accepts every preference the frontend has", async ({ request }) => { + const userId = await createUser(request); + + const result = await graphql(request, UPDATE_PREFERENCES, { + userId, + preferences: PREFERENCE_IDS, + }); + expect(result.errors).toBeUndefined(); + expect(result.data.updateUserPreferences.preferences).toEqual( + PREFERENCE_IDS, + ); + }); + test("only the fields that are sent are changed", async ({ request }) => { const userId = await createUser(request); diff --git a/frontend/src/components/plantCard/plantTraits.ts b/frontend/src/components/plantCard/plantTraits.ts index 0358a6a4..1cc3ff14 100644 --- a/frontend/src/components/plantCard/plantTraits.ts +++ b/frontend/src/components/plantCard/plantTraits.ts @@ -1,9 +1,10 @@ +import type { PreferenceId } from "../../types/Preference.ts"; + // The watering, sunlight and care values come from Perenual in English, and // are not consistent: the casing varies, and "Medium" and "Moderate" (and "Low" // and "Easy") mean the same. Each known value is mapped to a fixed key, which // is used to find its translation (plantCard.values.* in translation.json). -// The same rules are used for the preferences in PREFERENCE_MATCHERS in -// backend/src/queryBuilders.ts. +// The same rules are used for the preferences, see getPlantPreferences below. const TRAIT_KEYS = { watering: { minimum: "minimum", @@ -27,6 +28,12 @@ const TRAIT_KEYS = { export type Trait = keyof typeof TRAIT_KEYS; +// The fixed key for a value, or undefined if the value is not known +function traitKey(trait: Trait, value: string): string | undefined { + const keys: Record = TRAIT_KEYS[trait]; + return keys[value.trim().toLowerCase()]; +} + // The translated text for a value, e.g. "Minimum" becomes "Sjeldent" in // Norwegian. A value that is not known is shown as it is, in English, so // nothing is lost if the data has a value we have not seen. @@ -35,7 +42,52 @@ export function traitLabel( trait: Trait, value: string, ): string { - const keys: Record = TRAIT_KEYS[trait]; - const key = keys[value.trim().toLowerCase()]; + const key = traitKey(trait, value); return key ? t(`plantCard.values.${trait}.${key}`) : value; } + +// The preference for each watering and care key in TRAIT_KEYS +const WATERING_PREFERENCES: Record = { + minimum: "minimumWater", + average: "averageWater", + frequent: "frequentWater", +}; + +const CARE_PREFERENCES: Record = { + low: "easyCare", + medium: "mediumCare", + high: "hardCare", +}; + +// A sunlight value matches a preference if it contains the text, so +// "part sun/part shade" also gives part shade, like in the backend +const SUNLIGHT_PREFERENCES: [string, PreferenceId][] = [ + ["full sun", "fullSun"], + ["part shade", "partShade"], + ["filtered shade", "filteredShade"], +]; + +// The preferences a plant matches, in the order watering, sunlight, care. +// Must match PREFERENCE_MATCHERS in backend/src/queryBuilders.ts. +export function getPlantPreferences( + watering?: string | null, + sunlight?: string[] | null, + careLevel?: string | null, +): PreferenceId[] { + const sunlightValues = sunlight?.map((value) => value.toLowerCase()) ?? []; + + const wateringPreference = + WATERING_PREFERENCES[traitKey("watering", watering ?? "") ?? ""]; + const sunlightPreferences = SUNLIGHT_PREFERENCES.filter(([text]) => + sunlightValues.some((value) => value.includes(text)), + ).map(([, preference]) => preference); + const carePreference = + CARE_PREFERENCES[traitKey("careLevel", careLevel ?? "") ?? ""]; + + return [ + ...(wateringPreference ? [wateringPreference] : []), + // At most two, so the card does not get too many chips + ...sunlightPreferences.slice(0, 2), + ...(carePreference ? [carePreference] : []), + ]; +} diff --git a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx index c71f9a2b..f769e2e7 100644 --- a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx +++ b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx @@ -1,5 +1,6 @@ import { useTranslation } from "react-i18next"; import { useUser } from "../../context/UserContext.tsx"; +import { getPlantPreferences } from "../plantCard/plantTraits.ts"; import "./PlantPreferenceChips.css"; type PlantPreferenceChipsProps = { @@ -18,64 +19,7 @@ export default function PlantPreferenceChips({ // Re-renders on its own when the preferences change, since they come from the Apollo cache const selectedPreferences = useUser().user?.preferences ?? []; - const wateringPreferences: string[] = []; - const sunlightPreferences: string[] = []; - const carePreferences: string[] = []; - - // Watering - if (watering?.toLowerCase() === "minimum") { - wateringPreferences.push("minimumWater"); - } - - if (watering?.toLowerCase() === "average") { - wateringPreferences.push("averageWater"); - } - - if (watering?.toLowerCase() === "frequent") { - wateringPreferences.push("frequentWater"); - } - - // Sunlight - const sunlightValues = sunlight?.map((value) => value.toLowerCase()) ?? []; - - if (sunlightValues.some((value) => value.includes("full sun"))) { - sunlightPreferences.push("fullSun"); - } - - if ( - sunlightValues.some( - (value) => - value.includes("part shade") || value.includes("part sun/part shade"), - ) - ) { - sunlightPreferences.push("partShade"); - } - - if (sunlightValues.some((value) => value.includes("filtered shade"))) { - sunlightPreferences.push("filteredShade"); - } - - // Care level - const care = careLevel?.toLowerCase(); - - // The data uses "Low" for easy care. Must match PREFERENCE_MATCHERS in backend/src/queryBuilders.ts - if (care === "easy" || care === "low") { - carePreferences.push("easyCare"); - } - - if (care === "medium" || care === "moderate") { - carePreferences.push("mediumCare"); - } - - if (care === "high") { - carePreferences.push("hardCare"); - } - - const plantPreferences = [ - ...wateringPreferences.slice(0, 2), - ...sunlightPreferences.slice(0, 2), - ...carePreferences.slice(0, 2), - ]; + const plantPreferences = getPlantPreferences(watering, sunlight, careLevel); if (plantPreferences.length === 0) { return null; diff --git a/frontend/src/components/plantPreferences/PlantPreferences.tsx b/frontend/src/components/plantPreferences/PlantPreferences.tsx index f6c18f7a..966caaa1 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.tsx +++ b/frontend/src/components/plantPreferences/PlantPreferences.tsx @@ -5,17 +5,11 @@ import { UPDATE_USER_PREFERENCES, type UpdateUserPreferencesData, } from "../../graphql/user/mutations.ts"; -import type { Preference } from "../../types/Preference.ts"; +import { PREFERENCE_IDS } from "../../types/Preference.ts"; import "./PlantPreferences.css"; -type PlantPreferencesProps = { - preferences: Preference[]; -}; - // Display plant preferences -export default function PlantPreferences({ - preferences, -}: PlantPreferencesProps) { +export default function PlantPreferences() { const { t } = useTranslation(); // Saved preferences come from the database through UserContext @@ -56,15 +50,15 @@ export default function PlantPreferences({ // Button for each preference return (
- {preferences.map((preference) => ( + {PREFERENCE_IDS.map((id) => ( ))}
diff --git a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx index 3058b111..bf6286ac 100644 --- a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx +++ b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx @@ -6,10 +6,11 @@ import { UPDATE_USER_PREFERENCES, type UpdateUserPreferencesData, } from "../../graphql/user/mutations.ts"; +import type { PreferenceId } from "../../types/Preference.ts"; type SuggestedPreferencesProps = { // Preference ids suggested by the test - suggestions: string[]; + suggestions: PreferenceId[]; }; // Shows the preferences suggested by the plant owner test. The user chooses @@ -26,14 +27,14 @@ export default function SuggestedPreferences({ ); // The suggestions the user wants to add. All are chosen to begin with. - const [chosen, setChosen] = useState(suggestions); + const [chosen, setChosen] = useState(suggestions); const [status, setStatus] = useState<"idle" | "added" | "failed">("idle"); // Suggestions that are not in the user's preferences yet const newSuggestions = suggestions.filter((id) => !saved.includes(id)); const toAdd = chosen.filter((id) => newSuggestions.includes(id)); - function toggle(id: string) { + function toggle(id: PreferenceId) { setChosen((previous) => previous.includes(id) ? previous.filter((item) => item !== id) diff --git a/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts index ccfaed4f..9b155b40 100644 --- a/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts +++ b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts @@ -6,6 +6,7 @@ import cityGardenerDreaming from "../../assets/plantQuiz/cityGardenerDreaming.we import countryMinimalist from "../../assets/plantQuiz/countryMinimalist.webp"; import averageCountryGardener from "../../assets/plantQuiz/averageCountryGardener.webp"; import gardenExpert from "../../assets/plantQuiz/gardenExpert.webp"; +import type { PreferenceId } from "../../types/Preference.ts"; export type PlantOwnerType = | "cityMinimalist" @@ -59,20 +60,19 @@ export function getPlantOwnerResult( return results[answers.location][answers.watering]; } -// Preferences suggested after the test. The ids must match the preferences on -// the profile page (PREFERENCES in ProfilePage.tsx). +// Preferences suggested after the test // How much light the plants get. "Partial sun" has no preference of its own, // but the plants that like it are listed as "part sun/part shade" in the data, // so they match the part shade preference. -const lightPreferences: Record = { +const lightPreferences: Record = { partShade: "partShade", partSun: "partShade", fullSun: "fullSun", }; // The time spent on plants each week decides how much care they can need -const timePreferences: Record = { +const timePreferences: Record = { tenMinutes: "easyCare", thirtyMinutes: "mediumCare", oneHour: "mediumCare", @@ -84,7 +84,7 @@ const timePreferences: Record = { // care level too. The average gardeners get the care level from their time. const resultPreferences: Record< PlantOwnerType, - { watering: string; care?: string } + { watering: PreferenceId; care?: PreferenceId } > = { cityMinimalist: { watering: "minimumWater", care: "easyCare" }, averageCityGardener: { watering: "averageWater" }, @@ -99,7 +99,7 @@ const resultPreferences: Record< export function getSuggestedPreferences( answers: Record, result: PlantOwnerType, -): string[] { +): PreferenceId[] { const { watering, care } = resultPreferences[result]; return [ watering, diff --git a/frontend/src/pages/profile/ProfilePage.tsx b/frontend/src/pages/profile/ProfilePage.tsx index 7e4f062e..d0792b7b 100644 --- a/frontend/src/pages/profile/ProfilePage.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -1,6 +1,5 @@ import "./ProfilePage.css"; import profileImg from "../../assets/avatars/profile.webp"; -import type { Preference } from "../../types/Preference.ts"; import { useTranslation } from "react-i18next"; import { useState } from "react"; import PlantPreferences from "../../components/plantPreferences/PlantPreferences.tsx"; @@ -18,22 +17,6 @@ import { type PlantOwnerType, } from "../plantOwnerTest/plantOwnerTest.ts"; -// The preferences the user can choose. Must match PREFERENCE_MATCHERS in -// backend/src/queryBuilders.ts -const PREFERENCES: Preference[] = [ - { id: "minimumWater", translationKey: "preferences.minimumWater" }, - { id: "averageWater", translationKey: "preferences.averageWater" }, - { id: "frequentWater", translationKey: "preferences.frequentWater" }, - - { id: "fullSun", translationKey: "preferences.fullSun" }, - { id: "partShade", translationKey: "preferences.partShade" }, - { id: "filteredShade", translationKey: "preferences.filteredShade" }, - - { id: "easyCare", translationKey: "preferences.easyCare" }, - { id: "mediumCare", translationKey: "preferences.mediumCare" }, - { id: "hardCare", translationKey: "preferences.hardCare" }, -]; - export default function ProfilePage() { const { t } = useTranslation(); @@ -140,7 +123,7 @@ export default function ProfilePage() {

- + )} diff --git a/frontend/src/tests/PlantPreferences.test.tsx b/frontend/src/tests/PlantPreferences.test.tsx index a32fd412..621bc295 100644 --- a/frontend/src/tests/PlantPreferences.test.tsx +++ b/frontend/src/tests/PlantPreferences.test.tsx @@ -2,7 +2,7 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; import PlantPreferences from "../components/plantPreferences/PlantPreferences"; -import type { Preference } from "../types/Preference"; +import { PREFERENCE_IDS } from "../types/Preference"; const { updatePreferences, useUser } = vi.hoisted(() => ({ updatePreferences: vi.fn(), @@ -16,11 +16,6 @@ vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); -const preferences: Preference[] = [ - { id: "averageWater", translationKey: "preferences.averageWater" }, - { id: "fullSun", translationKey: "preferences.fullSun" }, -]; - function mockUser(selected: string[], userId: string | null = "user-1") { useUser.mockReturnValue({ userId, @@ -39,9 +34,18 @@ describe("PlantPreferences", () => { updatePreferences.mockResolvedValue({}); }); + it("shows a button for every preference", () => { + mockUser([]); + render(); + + expect( + screen.getAllByRole("button").map((button) => button.textContent), + ).toEqual(PREFERENCE_IDS.map((id) => `preferences.${id}`)); + }); + it("tells screen readers which preferences are selected", () => { mockUser(["fullSun"]); - render(); + render(); expect( screen.getByRole("button", { name: "preferences.fullSun" }), @@ -53,7 +57,7 @@ describe("PlantPreferences", () => { it("marks the preferences saved on the user", () => { mockUser(["fullSun"]); - render(); + render(); expect( screen.getByRole("button", { name: "preferences.fullSun" }), @@ -65,7 +69,7 @@ describe("PlantPreferences", () => { it("adds a preference that is not selected", async () => { mockUser(["fullSun"]); - render(); + render(); await userEvent.click( screen.getByRole("button", { name: "preferences.averageWater" }), @@ -84,7 +88,7 @@ describe("PlantPreferences", () => { it("removes a preference that is already selected", async () => { mockUser(["fullSun", "averageWater"]); - render(); + render(); await userEvent.click( screen.getByRole("button", { name: "preferences.fullSun" }), @@ -96,7 +100,7 @@ describe("PlantPreferences", () => { it("does not crash when saving fails", async () => { mockUser([]); updatePreferences.mockRejectedValue(new Error("Offline")); - render(); + render(); await userEvent.click( screen.getByRole("button", { name: "preferences.fullSun" }), @@ -107,7 +111,7 @@ describe("PlantPreferences", () => { it("saves nothing before the user exists", async () => { mockUser([], null); - render(); + render(); await userEvent.click( screen.getByRole("button", { name: "preferences.fullSun" }), diff --git a/frontend/src/types/Preference.ts b/frontend/src/types/Preference.ts index bd7c8aaf..40900b0e 100644 --- a/frontend/src/types/Preference.ts +++ b/frontend/src/types/Preference.ts @@ -1,4 +1,16 @@ -export type Preference = { - id: string; - translationKey: string; -}; +// The preferences the user can choose. +// Must match PREFERENCE_MATCHERS in backend/src/queryBuilders.ts. +// The text for each one is preferences. in translation.json. +export const PREFERENCE_IDS = [ + "minimumWater", + "averageWater", + "frequentWater", + "fullSun", + "partShade", + "filteredShade", + "easyCare", + "mediumCare", + "hardCare", +] as const; + +export type PreferenceId = (typeof PREFERENCE_IDS)[number]; From c20ec63286f9ccdcb79b2d7cb5fcdfa7ba8b07c9 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Mon, 23 Nov 2026 11:34:38 +0100 Subject: [PATCH 2/6] Also count re-matched plants --- frontend/src/hooks/useNewMatches.ts | 7 +++++++ frontend/src/tests/SidebarNewMatches.test.tsx | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/frontend/src/hooks/useNewMatches.ts b/frontend/src/hooks/useNewMatches.ts index 2f181b7e..cf27321d 100644 --- a/frontend/src/hooks/useNewMatches.ts +++ b/frontend/src/hooks/useNewMatches.ts @@ -26,6 +26,13 @@ export function useNewMatches() { (seenIds === null || onMyMatches) ) { setSeenIds(matchedPlantIds); + } else if ( + matchedPlantIds && + seenIds?.some((id) => !matchedPlantIds.includes(id)) + ) { + // A plant that is removed from the matches is no longer seen, so it counts + // as new if it is matched again + setSeenIds(seenIds.filter((id) => matchedPlantIds.includes(id))); } if (!matchedPlantIds || !seenIds || onMyMatches) return 0; diff --git a/frontend/src/tests/SidebarNewMatches.test.tsx b/frontend/src/tests/SidebarNewMatches.test.tsx index 965c8853..261f132c 100644 --- a/frontend/src/tests/SidebarNewMatches.test.tsx +++ b/frontend/src/tests/SidebarNewMatches.test.tsx @@ -87,6 +87,18 @@ describe("Sidebar new matches badge", () => { expect(badge()).toBeNull(); }); + it("counts a match the user already had as new if it is removed and added again", () => { + const { rerender } = renderSidebar(); + + matchedPlantIds = matchedPlantIds.filter((id) => id !== "a"); + rerender(); + expect(badge()).toBeNull(); + + matchedPlantIds = [...matchedPlantIds, "a"]; + rerender(); + expect(badge()).toHaveTextContent("1"); + }); + it("is cleared when My Matches is opened", async () => { const { user, rerender } = renderSidebar(); From 9f26d851c784cbbb2a05395b62e2a51015e9ce28 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Mon, 23 Nov 2026 11:34:38 +0100 Subject: [PATCH 3/6] Split resolvers file --- backend/src/resolvers.ts | 360 ------------------------------- backend/src/resolvers/helpers.ts | 16 ++ backend/src/resolvers/index.ts | 10 + backend/src/resolvers/plants.ts | 143 ++++++++++++ backend/src/resolvers/users.ts | 212 ++++++++++++++++++ backend/src/schema.ts | 2 +- backend/src/server.ts | 2 +- backend/src/types.ts | 2 +- docs/architecture.md | 10 +- 9 files changed, 389 insertions(+), 368 deletions(-) delete mode 100644 backend/src/resolvers.ts create mode 100644 backend/src/resolvers/helpers.ts create mode 100644 backend/src/resolvers/index.ts create mode 100644 backend/src/resolvers/plants.ts create mode 100644 backend/src/resolvers/users.ts diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts deleted file mode 100644 index bbd00cd9..00000000 --- a/backend/src/resolvers.ts +++ /dev/null @@ -1,360 +0,0 @@ -import { GraphQLError } from "graphql"; -import { ObjectId } from "mongodb"; -import type { Document, Filter, WithId } from "mongodb"; -import { db } from "./db.js"; -import { - buildPlantFilter, - buildFilterCountStages, - buildMatchSortStages, - buildSortStages, - knownPreferences, - matchScore, - PREFERENCE_MATCHERS, - toFilterCounts, -} from "./queryBuilders.js"; -import type { - ExplorePlantsArgs, - GetPlantsArgs, - MyMatchesArgs, - Plant, - PlantDoc, - PlantFilterArgs, - PlantPage, - UpdateUserPreferencesArgs, - UpdateUserProfileArgs, - User, - UserDoc, - UserIdArgs, - UserMatchArgs, -} from "./types.js"; - -// Same limits as the inputs on the profile page -const NAME_MAX_LENGTH = 40; -const DESCRIPTION_MAX_LENGTH = 100; - -// Must match the avatar ids in frontend/src/pages/profile/ProfilePage.tsx and the -// result ids in frontend/src/pages/plantOwnerTest/plantOwnerTest.ts -const PROFILE_PICTURES = [ - "default", - "monstera", - "pothos", - "snake-plant", - "anthurium", - "succulent", - "fern", - "orchid", - // Results from the plant owner test - "cityMinimalist", - "averageCityGardener", - "cityGardenerDreaming", - "countryMinimalist", - "averageCountryGardener", - "gardenExpert", -]; - -// The preference ids are the keys of PREFERENCE_MATCHERS, so the two lists -// can't get out of sync. Must match the ids in frontend/src/pages/profile/ProfilePage.tsx -const PREFERENCES = Object.keys(PREFERENCE_MATCHERS); - -// The most plants one request can ask for. The plants include their images, -// so without a limit one request could fetch the whole collection. -const MAX_LIMIT = 50; -// The page size on Explore Plants and My Matches, the same as the schema default -const DEFAULT_PAGE_SIZE = 12; - -// Keeps limit between 1 and MAX_LIMIT, and offset at 0 or more, so a bad value -// from the client gives a valid page instead of an error from MongoDB. -// null is possible when the client sends it explicitly. -const clampLimit = (limit: number | null | undefined, fallback: number) => - Math.min(Math.max(limit ?? fallback, 1), MAX_LIMIT); -const clampOffset = (offset: number | null | undefined) => - Math.max(offset ?? 0, 0); - -const plants = db.collection("plants"); -const users = db.collection("users"); - -const toPlant = (doc: WithId): Plant => ({ - id: doc._id.toString(), - name: doc.commonName.replace(/\*/g, "").replace(/\s+/g, " ").trim(), - imageURL: doc.imageData ?? doc.imageURL ?? null, - scientificName: doc.scientificName, - description: doc.description, - watering: doc.watering, - sunlight: doc.sunlight, - careLevel: doc.careLevel, -}); - -const toUser = (doc: WithId): User => ({ - id: doc._id.toString(), - name: doc.name, - description: doc.description, - profilePicture: doc.profilePicture, - preferences: doc.preferences, - matchedPlantIds: doc.matchedPlantIds, - createdAt: doc.createdAt.toISOString(), -}); - -const badInput = (message: string) => - new GraphQLError(message, { extensions: { code: "BAD_USER_INPUT" } }); - -// Ids come from the client, so a malformed id gives null instead of a crash -const toObjectId = (id: string): ObjectId | null => - ObjectId.isValid(id) ? new ObjectId(id) : null; - -// Trims text and checks the length. Empty text is stored as null. -const cleanText = ( - value: string | null | undefined, - maxLength: number, - field: string, -): string | null => { - const trimmed = value?.trim() ?? ""; - if (trimmed.length > maxLength) { - throw badInput(`${field} can be at most ${maxLength} characters`); - } - return trimmed || null; -}; - -// One page of plants for Explore Plants and My Matches: the plants matching the -// base filter (on My Matches the user's matches) and the user's search and -// filters, the total count, and the match counts for the filter values, so the -// frontend can show them and disable the values that would give no plants. -// The three queries run at the same time. -const findPlantPage = async ( - baseFilter: Filter, - args: PlantFilterArgs & { limit?: number | null; offset?: number | null }, - sortStages: Document[], -): Promise => { - const filter = { ...baseFilter, ...buildPlantFilter(args) }; - - const [docs, totalCount, [facets]] = await Promise.all([ - plants - .aggregate>([ - { $match: filter }, - ...sortStages, - { $skip: clampOffset(args.offset) }, - { $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) }, - ]) - .toArray(), - plants.countDocuments(filter), - plants - .aggregate>( - buildFilterCountStages(args, baseFilter), - ) - .toArray(), - ]); - - return { - plants: docs.map(toPlant), - totalCount, - filterCounts: toFilterCounts(facets), - }; -}; - -// Applies an update to one user and returns the updated user, or null if not found -const updateUser = async ( - userId: string, - update: Document, -): Promise => { - const _id = toObjectId(userId); - if (!_id) return null; - const doc = await users.findOneAndUpdate({ _id }, update, { - returnDocument: "after", - }); - return doc ? toUser(doc) : null; -}; - -export const resolvers = { - Query: { - getPlants: async ( - _parent: unknown, - args: GetPlantsArgs, - ): Promise => { - // $sample gives a random order, so offset paging would repeat plants. - // Instead the client sends the ids it has, and they are excluded. - const limit = clampLimit(args.limit, MAX_LIMIT); - const excluded = (args.excludeIds ?? []).flatMap((id) => { - const objectId = toObjectId(id); - return objectId ? [objectId] : []; - }); - const preferences = knownPreferences(args.preferences); - - // Without preferences the plants come in random order. With preferences - // the best matches come first, and plants with the same score are shuffled. - // Since the plants already sent are excluded, each batch continues where - // the last one stopped, so the whole stack is in score order. - const orderStages: Document[] = - preferences.length === 0 - ? [{ $sample: { size: limit } }] - : [ - { - $addFields: { - matchScore: matchScore(preferences), - shuffle: { $rand: {} }, - }, - }, - { $sort: { matchScore: -1, shuffle: 1 } }, - { $limit: limit }, - ]; - - const docs = await plants - .aggregate>([ - { $match: { _id: { $nin: excluded } } }, - ...orderStages, - { - $project: { - commonName: 1, - imageData: 1, - imageURL: 1, - scientificName: 1, - description: 1, - watering: 1, - sunlight: 1, - careLevel: 1, - }, - }, - ]) - .toArray(); - return docs.map(toPlant); - }, - - explorePlants: async ( - _parent: unknown, - args: ExplorePlantsArgs, - ): Promise => - findPlantPage( - {}, - args, - buildSortStages(args.sort, knownPreferences(args.preferences)), - ), - - getUser: async ( - _parent: unknown, - args: UserIdArgs, - ): Promise => { - const _id = toObjectId(args.userId); - if (!_id) return null; - const doc = await users.findOne({ _id }); - return doc ? toUser(doc) : null; - }, - - // One page of the user's matched plants, searched, filtered and sorted. - // Only the ids are stored on the user, so the plants are looked up and - // sorted in the plants collection. An unknown or malformed user id gives an - // empty page. - myMatches: async ( - _parent: unknown, - args: MyMatchesArgs, - ): Promise => { - const _id = toObjectId(args.userId); - const user = _id - ? await users.findOne( - { _id }, - { projection: { matchedPlantIds: 1, preferences: 1 } }, - ) - : null; - const matchedPlantIds = user?.matchedPlantIds ?? []; - if (matchedPlantIds.length === 0) { - return { plants: [], totalCount: 0, filterCounts: toFilterCounts() }; - } - - // Only plants that still exist are shown and counted (e.g. after a reseed) - return findPlantPage( - { _id: { $in: matchedPlantIds } }, - args, - // The user's saved preferences, for the "preferences" sort order - buildMatchSortStages( - args.sort, - matchedPlantIds, - knownPreferences(user?.preferences), - ), - ); - }, - }, - - Mutation: { - createUser: async (): Promise => { - const doc: UserDoc = { - name: null, - description: null, - profilePicture: "default", - preferences: [], - matchedPlantIds: [], - createdAt: new Date(), - }; - const { insertedId } = await users.insertOne(doc); - return toUser({ _id: insertedId, ...doc }); - }, - - updateUserProfile: async ( - _parent: unknown, - args: UpdateUserProfileArgs, - ): Promise => { - // Only fields that were sent are changed - const changes: Partial = {}; - if (args.name !== undefined) { - changes.name = cleanText(args.name, NAME_MAX_LENGTH, "Name"); - } - if (args.description !== undefined) { - changes.description = cleanText( - args.description, - DESCRIPTION_MAX_LENGTH, - "Description", - ); - } - if (args.profilePicture !== undefined) { - const picture = args.profilePicture ?? "default"; - if (!PROFILE_PICTURES.includes(picture)) { - throw badInput(`Unknown profile picture: ${picture}`); - } - changes.profilePicture = picture; - } - return updateUser(args.userId, { $set: changes }); - }, - - updateUserPreferences: async ( - _parent: unknown, - args: UpdateUserPreferencesArgs, - ): Promise => { - const unknown = args.preferences.filter((p) => !PREFERENCES.includes(p)); - if (unknown.length > 0) { - throw badInput(`Unknown preferences: ${unknown.join(", ")}`); - } - // Set removes duplicates - const preferences = [...new Set(args.preferences)]; - return updateUser(args.userId, { $set: { preferences } }); - }, - - addUserMatch: async ( - _parent: unknown, - args: UserMatchArgs, - ): Promise => { - const plantId = toObjectId(args.plantId); - if (!plantId || !(await plants.countDocuments({ _id: plantId }))) { - throw badInput(`Unknown plant: ${args.plantId}`); - } - // $addToSet never adds the same plant twice - return updateUser(args.userId, { - $addToSet: { matchedPlantIds: plantId }, - }); - }, - - removeUserMatch: async ( - _parent: unknown, - args: UserMatchArgs, - ): Promise => { - const plantId = toObjectId(args.plantId); - if (!plantId) throw badInput(`Unknown plant: ${args.plantId}`); - return updateUser(args.userId, { - $pull: { matchedPlantIds: plantId }, - }); - }, - }, - - User: { - // Only the ids of the matched plants, so pages that just need to know - // whether a plant is matched don't fetch the whole plants with images. - // My Matches gets the plants themselves from the myMatches query. - matchedPlantIds: (user: User): string[] => - user.matchedPlantIds.map((id) => id.toString()), - }, -}; diff --git a/backend/src/resolvers/helpers.ts b/backend/src/resolvers/helpers.ts new file mode 100644 index 00000000..398612e7 --- /dev/null +++ b/backend/src/resolvers/helpers.ts @@ -0,0 +1,16 @@ +import { GraphQLError } from "graphql"; +import { ObjectId } from "mongodb"; +import { db } from "../db.js"; +import type { PlantDoc, UserDoc } from "../types.js"; + +// Used by both the plant and the user resolvers + +export const plants = db.collection("plants"); +export const users = db.collection("users"); + +export const badInput = (message: string) => + new GraphQLError(message, { extensions: { code: "BAD_USER_INPUT" } }); + +// Ids come from the client, so a malformed id gives null instead of a crash +export const toObjectId = (id: string): ObjectId | null => + ObjectId.isValid(id) ? new ObjectId(id) : null; diff --git a/backend/src/resolvers/index.ts b/backend/src/resolvers/index.ts new file mode 100644 index 00000000..5c240a87 --- /dev/null +++ b/backend/src/resolvers/index.ts @@ -0,0 +1,10 @@ +import { plantQueries } from "./plants.js"; +import { userMutations, userQueries, userResolvers } from "./users.js"; + +// All the resolvers, split by plants and users like the GraphQL operations in +// the frontend (frontend/src/graphql/plants and frontend/src/graphql/user) +export const resolvers = { + Query: { ...plantQueries, ...userQueries }, + Mutation: userMutations, + User: userResolvers, +}; diff --git a/backend/src/resolvers/plants.ts b/backend/src/resolvers/plants.ts new file mode 100644 index 00000000..1163064c --- /dev/null +++ b/backend/src/resolvers/plants.ts @@ -0,0 +1,143 @@ +import type { Document, Filter, WithId } from "mongodb"; +import { + buildPlantFilter, + buildFilterCountStages, + buildSortStages, + knownPreferences, + matchScore, + toFilterCounts, +} from "../queryBuilders.js"; +import type { + ExplorePlantsArgs, + GetPlantsArgs, + Plant, + PlantDoc, + PlantFilterArgs, + PlantPage, +} from "../types.js"; +import { plants, toObjectId } from "./helpers.js"; + +// The most plants one request can ask for. The plants include their images, +// so without a limit one request could fetch the whole collection. +const MAX_LIMIT = 50; +// The page size on Explore Plants and My Matches, the same as the schema default +const DEFAULT_PAGE_SIZE = 12; + +// Keeps limit between 1 and MAX_LIMIT, and offset at 0 or more, so a bad value +// from the client gives a valid page instead of an error from MongoDB. +// null is possible when the client sends it explicitly. +const clampLimit = (limit: number | null | undefined, fallback: number) => + Math.min(Math.max(limit ?? fallback, 1), MAX_LIMIT); +const clampOffset = (offset: number | null | undefined) => + Math.max(offset ?? 0, 0); + +const toPlant = (doc: WithId): Plant => ({ + id: doc._id.toString(), + name: doc.commonName.replace(/\*/g, "").replace(/\s+/g, " ").trim(), + imageURL: doc.imageData ?? doc.imageURL ?? null, + scientificName: doc.scientificName, + description: doc.description, + watering: doc.watering, + sunlight: doc.sunlight, + careLevel: doc.careLevel, +}); + +// One page of plants for Explore Plants and My Matches: the plants matching the +// base filter (on My Matches the user's matches) and the user's search and +// filters, the total count, and the match counts for the filter values, so the +// frontend can show them and disable the values that would give no plants. +// The three queries run at the same time. +export const findPlantPage = async ( + baseFilter: Filter, + args: PlantFilterArgs & { limit?: number | null; offset?: number | null }, + sortStages: Document[], +): Promise => { + const filter = { ...baseFilter, ...buildPlantFilter(args) }; + + const [docs, totalCount, [facets]] = await Promise.all([ + plants + .aggregate>([ + { $match: filter }, + ...sortStages, + { $skip: clampOffset(args.offset) }, + { $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) }, + ]) + .toArray(), + plants.countDocuments(filter), + plants + .aggregate>( + buildFilterCountStages(args, baseFilter), + ) + .toArray(), + ]); + + return { + plants: docs.map(toPlant), + totalCount, + filterCounts: toFilterCounts(facets), + }; +}; + +export const plantQueries = { + getPlants: async ( + _parent: unknown, + args: GetPlantsArgs, + ): Promise => { + // $sample gives a random order, so offset paging would repeat plants. + // Instead the client sends the ids it has, and they are excluded. + const limit = clampLimit(args.limit, MAX_LIMIT); + const excluded = (args.excludeIds ?? []).flatMap((id) => { + const objectId = toObjectId(id); + return objectId ? [objectId] : []; + }); + const preferences = knownPreferences(args.preferences); + + // Without preferences the plants come in random order. With preferences + // the best matches come first, and plants with the same score are shuffled. + // Since the plants already sent are excluded, each batch continues where + // the last one stopped, so the whole stack is in score order. + const orderStages: Document[] = + preferences.length === 0 + ? [{ $sample: { size: limit } }] + : [ + { + $addFields: { + matchScore: matchScore(preferences), + shuffle: { $rand: {} }, + }, + }, + { $sort: { matchScore: -1, shuffle: 1 } }, + { $limit: limit }, + ]; + + const docs = await plants + .aggregate>([ + { $match: { _id: { $nin: excluded } } }, + ...orderStages, + { + $project: { + commonName: 1, + imageData: 1, + imageURL: 1, + scientificName: 1, + description: 1, + watering: 1, + sunlight: 1, + careLevel: 1, + }, + }, + ]) + .toArray(); + return docs.map(toPlant); + }, + + explorePlants: async ( + _parent: unknown, + args: ExplorePlantsArgs, + ): Promise => + findPlantPage( + {}, + args, + buildSortStages(args.sort, knownPreferences(args.preferences)), + ), +}; diff --git a/backend/src/resolvers/users.ts b/backend/src/resolvers/users.ts new file mode 100644 index 00000000..9faedf78 --- /dev/null +++ b/backend/src/resolvers/users.ts @@ -0,0 +1,212 @@ +import type { Document, WithId } from "mongodb"; +import { + buildMatchSortStages, + knownPreferences, + PREFERENCE_MATCHERS, + toFilterCounts, +} from "../queryBuilders.js"; +import type { + MyMatchesArgs, + PlantPage, + UpdateUserPreferencesArgs, + UpdateUserProfileArgs, + User, + UserDoc, + UserIdArgs, + UserMatchArgs, +} from "../types.js"; +import { badInput, plants, toObjectId, users } from "./helpers.js"; +import { findPlantPage } from "./plants.js"; + +// Same limits as the inputs on the profile page +const NAME_MAX_LENGTH = 40; +const DESCRIPTION_MAX_LENGTH = 100; + +// Must match the avatar ids in frontend/src/pages/profile/ProfilePage.tsx and the +// result ids in frontend/src/pages/plantOwnerTest/plantOwnerTest.ts +const PROFILE_PICTURES = [ + "default", + "monstera", + "pothos", + "snake-plant", + "anthurium", + "succulent", + "fern", + "orchid", + // Results from the plant owner test + "cityMinimalist", + "averageCityGardener", + "cityGardenerDreaming", + "countryMinimalist", + "averageCountryGardener", + "gardenExpert", +]; + +// The preference ids are the keys of PREFERENCE_MATCHERS, so the two lists +// can't get out of sync. Must match PREFERENCE_IDS in frontend/src/types/Preference.ts +const PREFERENCES = Object.keys(PREFERENCE_MATCHERS); + +const toUser = (doc: WithId): User => ({ + id: doc._id.toString(), + name: doc.name, + description: doc.description, + profilePicture: doc.profilePicture, + preferences: doc.preferences, + matchedPlantIds: doc.matchedPlantIds, + createdAt: doc.createdAt.toISOString(), +}); + +// Trims text and checks the length. Empty text is stored as null. +const cleanText = ( + value: string | null | undefined, + maxLength: number, + field: string, +): string | null => { + const trimmed = value?.trim() ?? ""; + if (trimmed.length > maxLength) { + throw badInput(`${field} can be at most ${maxLength} characters`); + } + return trimmed || null; +}; + +// Applies an update to one user and returns the updated user, or null if not found +const updateUser = async ( + userId: string, + update: Document, +): Promise => { + const _id = toObjectId(userId); + if (!_id) return null; + const doc = await users.findOneAndUpdate({ _id }, update, { + returnDocument: "after", + }); + return doc ? toUser(doc) : null; +}; + +export const userQueries = { + getUser: async (_parent: unknown, args: UserIdArgs): Promise => { + const _id = toObjectId(args.userId); + if (!_id) return null; + const doc = await users.findOne({ _id }); + return doc ? toUser(doc) : null; + }, + + // One page of the user's matched plants, searched, filtered and sorted. + // Only the ids are stored on the user, so the plants are looked up and + // sorted in the plants collection. An unknown or malformed user id gives an + // empty page. + myMatches: async ( + _parent: unknown, + args: MyMatchesArgs, + ): Promise => { + const _id = toObjectId(args.userId); + const user = _id + ? await users.findOne( + { _id }, + { projection: { matchedPlantIds: 1, preferences: 1 } }, + ) + : null; + const matchedPlantIds = user?.matchedPlantIds ?? []; + if (matchedPlantIds.length === 0) { + return { plants: [], totalCount: 0, filterCounts: toFilterCounts() }; + } + + // Only plants that still exist are shown and counted (e.g. after a reseed) + return findPlantPage( + { _id: { $in: matchedPlantIds } }, + args, + // The user's saved preferences, for the "preferences" sort order + buildMatchSortStages( + args.sort, + matchedPlantIds, + knownPreferences(user?.preferences), + ), + ); + }, +}; + +export const userMutations = { + createUser: async (): Promise => { + const doc: UserDoc = { + name: null, + description: null, + profilePicture: "default", + preferences: [], + matchedPlantIds: [], + createdAt: new Date(), + }; + const { insertedId } = await users.insertOne(doc); + return toUser({ _id: insertedId, ...doc }); + }, + + updateUserProfile: async ( + _parent: unknown, + args: UpdateUserProfileArgs, + ): Promise => { + // Only fields that were sent are changed + const changes: Partial = {}; + if (args.name !== undefined) { + changes.name = cleanText(args.name, NAME_MAX_LENGTH, "Name"); + } + if (args.description !== undefined) { + changes.description = cleanText( + args.description, + DESCRIPTION_MAX_LENGTH, + "Description", + ); + } + if (args.profilePicture !== undefined) { + const picture = args.profilePicture ?? "default"; + if (!PROFILE_PICTURES.includes(picture)) { + throw badInput(`Unknown profile picture: ${picture}`); + } + changes.profilePicture = picture; + } + return updateUser(args.userId, { $set: changes }); + }, + + updateUserPreferences: async ( + _parent: unknown, + args: UpdateUserPreferencesArgs, + ): Promise => { + const unknown = args.preferences.filter((p) => !PREFERENCES.includes(p)); + if (unknown.length > 0) { + throw badInput(`Unknown preferences: ${unknown.join(", ")}`); + } + // Set removes duplicates + const preferences = [...new Set(args.preferences)]; + return updateUser(args.userId, { $set: { preferences } }); + }, + + addUserMatch: async ( + _parent: unknown, + args: UserMatchArgs, + ): Promise => { + const plantId = toObjectId(args.plantId); + if (!plantId || !(await plants.countDocuments({ _id: plantId }))) { + throw badInput(`Unknown plant: ${args.plantId}`); + } + // $addToSet never adds the same plant twice + return updateUser(args.userId, { + $addToSet: { matchedPlantIds: plantId }, + }); + }, + + removeUserMatch: async ( + _parent: unknown, + args: UserMatchArgs, + ): Promise => { + const plantId = toObjectId(args.plantId); + if (!plantId) throw badInput(`Unknown plant: ${args.plantId}`); + return updateUser(args.userId, { + $pull: { matchedPlantIds: plantId }, + }); + }, +}; + +export const userResolvers = { + // Only the ids of the matched plants, so pages that just need to know + // whether a plant is matched don't fetch the whole plants with images. + // My Matches gets the plants themselves from the myMatches query. + matchedPlantIds: (user: User): string[] => + user.matchedPlantIds.map((id) => id.toString()), +}; diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 046f3a3c..920d2c89 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,4 +1,4 @@ -// The GraphQL schema. The resolvers are in resolvers.ts. +// The GraphQL schema. The resolvers are in the resolvers folder. export const typeDefs = ` type Query{ getPlants(limit: Int = 50, excludeIds: [ID!], preferences: [String!]): [Plant] diff --git a/backend/src/server.ts b/backend/src/server.ts index c26a8983..3a698ee8 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,6 +1,6 @@ import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; -import { resolvers } from "./resolvers.js"; +import { resolvers } from "./resolvers/index.js"; import { typeDefs } from "./schema.js"; import { db } from "./db.js"; import { ensureIndexes } from "./indexes.js"; diff --git a/backend/src/types.ts b/backend/src/types.ts index 82126a3e..92cccee2 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -26,7 +26,7 @@ export interface Plant { } export interface GetPlantsArgs { - // Null if the client sends null explicitly, see clampLimit in resolvers.ts + // Null if the client sends null explicitly, see clampLimit in resolvers/plants.ts limit?: number | null; // Plants the client already has. They are left out, so the next random batch // only has new plants. An empty result means there are no more plants. diff --git a/docs/architecture.md b/docs/architecture.md index 1f33d298..36cd747a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -60,7 +60,7 @@ The frontend is built with React and TypeScript (Vite). - **Care level** from the result where its description says something about care: `easyCare` for the minimalists ("hardy plants") and `hardCare` for the dreaming city gardener and the garden expert ("a lot of attention"). The average gardeners get it from the time answer (10 minutes: `easyCare`, 30 minutes or 1 hour: `mediumCare`, 1 day: `hardCare`). `SuggestedPreferences.tsx` shows the suggestions that the user does not already have as toggle buttons, all chosen from the start. Nothing is saved until the user clicks "Add to my preferences", which runs `updateUserPreferences` with the saved preferences plus the chosen suggestions, so no preference is removed. It uses an optimistic response like the buttons on the profile page, so the profile and Plant Match are updated at once. The suggestions are shown above "Use as profile picture", since that button takes the user to the profile page. - + - **Walkthrough:** The guide for new users is in `components/walkthrough/`, and is made up of three parts: - **The steps are data:** `walkthroughSteps.ts` lists the steps in order. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page. - **`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. @@ -111,7 +111,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f - `db.ts` connects to MongoDB using `MONGODB_URI` and `DB_NAME` from `.env` (see `.env.example`). The database name defaults to `iloveplants`. - `server.ts` starts Apollo Server on `PORT` (default 3001) with the schema and resolvers below. - `schema.ts` defines the GraphQL schema (`typeDefs`). -- `resolvers.ts` has the resolvers for plants and users, and validates user input. +- `resolvers/` has the resolvers, split like the GraphQL operations in the frontend: `plants.ts` has the plant queries, `users.ts` has the user queries and mutations and validates user input, `helpers.ts` has the collections and helpers both use, and `index.ts` puts them together. - `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches, and the counts of how many plants each filter value would give on Explore Plants. - `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#design-choices-made-for-scalability)). - `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments. @@ -141,7 +141,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f **Types** - `Plant`: `id`, `name`, `imageURL`, `scientificName`, `description`, `watering`, `sunlight`, `careLevel` -- `PlantPage`: `plants`, `totalCount`, `filterCounts`. `FilterCounts` has `watering`, `sunlight` and `careLevel`, each a list of `OptionCount` (`value`, `count`). Both `explorePlants` and `myMatches` return it, and share the code that builds it (`findPlantPage` in `resolvers.ts`). +- `PlantPage`: `plants`, `totalCount`, `filterCounts`. `FilterCounts` has `watering`, `sunlight` and `careLevel`, each a list of `OptionCount` (`value`, `count`). Both `explorePlants` and `myMatches` return it, and share the code that builds it (`findPlantPage` in `resolvers/plants.ts`). - `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlantIds`, `createdAt` `User.matchedPlantIds` only returns the ids, so the pages that just need to know whether a plant is matched do not fetch the whole plants with images. The plants themselves are fetched one page at a time with `myMatches`, which only shows and counts plants that still exist (for example after a reseed). @@ -203,7 +203,7 @@ One document per user. There is no login: a user is created the first time someo | `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlantIds`, and the plants through `myMatches` | | `createdAt` | Date | When the user was created | `createdAt` (ISO string) | -A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers.ts` and must match the ids used in the frontend (`ProfilePage.tsx` and `plantOwnerTest.ts`). The preference ids are the keys of `PREFERENCE_MATCHERS` in `queryBuilders.ts`, so the list used for validation and the list used for scoring cannot get out of sync. The avatar id `snake-plant` is kept as it is, since it is already stored on existing users. +A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers/users.ts` and must match the ids used in the frontend (`ProfilePage.tsx` and `plantOwnerTest.ts`). The preference ids are the keys of `PREFERENCE_MATCHERS` in `queryBuilders.ts`, so the list used for validation and the list used for scoring cannot get out of sync. The avatar id `snake-plant` is kept as it is, since it is already stored on existing users. Matches only store the plant id, not a copy of the plant. That keeps user documents small and means the user always sees the current plant data. @@ -289,7 +289,7 @@ T03-Project-2/ │ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env) │ │ ├── queryBuilders.ts # Filters and sort stages for searching, filtering and sorting plants │ │ ├── indexes.ts # Database indexes, created when the server starts -│ │ ├── resolvers.ts # GraphQL resolvers for plants and users +│ │ ├── resolvers/ # GraphQL resolvers: plants.ts, users.ts, shared helpers.ts and index.ts │ │ ├── schema.ts # GraphQL schema │ │ ├── server.ts # Starts Apollo Server │ │ └── types.ts # TypeScript types for documents, GraphQL types and arguments From da974364ee962d895d302a3b88ffba0256e2fa1e Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Mon, 23 Nov 2026 11:46:35 +0100 Subject: [PATCH 4/6] Define PAGE_SIZE only once and use --- backend/src/resolvers/plants.ts | 7 +------ backend/src/schema.ts | 12 +++++++++--- frontend/src/graphql/plants/queries.ts | 3 +++ .../src/pages/explorePlants/ExplorePlantsPage.tsx | 3 +-- frontend/src/pages/myMatches/MyMatchesPage.tsx | 3 +-- frontend/src/tests/ExplorePlantsPage.test.tsx | 4 ++-- frontend/src/tests/MyMatchesPage.test.tsx | 8 +++++++- 7 files changed, 24 insertions(+), 16 deletions(-) diff --git a/backend/src/resolvers/plants.ts b/backend/src/resolvers/plants.ts index 1163064c..d1b6ddaa 100644 --- a/backend/src/resolvers/plants.ts +++ b/backend/src/resolvers/plants.ts @@ -15,14 +15,9 @@ import type { PlantFilterArgs, PlantPage, } from "../types.js"; +import { DEFAULT_PAGE_SIZE, MAX_LIMIT } from "../schema.js"; import { plants, toObjectId } from "./helpers.js"; -// The most plants one request can ask for. The plants include their images, -// so without a limit one request could fetch the whole collection. -const MAX_LIMIT = 50; -// The page size on Explore Plants and My Matches, the same as the schema default -const DEFAULT_PAGE_SIZE = 12; - // Keeps limit between 1 and MAX_LIMIT, and offset at 0 or more, so a bad value // from the client gives a valid page instead of an error from MongoDB. // null is possible when the client sends it explicitly. diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 920d2c89..d6fa118f 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,7 +1,13 @@ +// The most plants one request can ask for. The plants include their images, +// so without a limit one request could fetch the whole collection. +export const MAX_LIMIT = 50; +// The page size on Explore Plants and My Matches when the client sends no limit +export const DEFAULT_PAGE_SIZE = 12; + // The GraphQL schema. The resolvers are in the resolvers folder. export const typeDefs = ` type Query{ - getPlants(limit: Int = 50, excludeIds: [ID!], preferences: [String!]): [Plant] + getPlants(limit: Int = ${MAX_LIMIT}, excludeIds: [ID!], preferences: [String!]): [Plant] explorePlants( search: String sunlight: String @@ -9,7 +15,7 @@ export const typeDefs = ` careLevel: String sort: String preferences: [String!] - limit: Int = 12 + limit: Int = ${DEFAULT_PAGE_SIZE} offset: Int = 0 ): PlantPage! getUser(userId: ID!): User @@ -20,7 +26,7 @@ export const typeDefs = ` watering: String careLevel: String sort: String - limit: Int = 12 + limit: Int = ${DEFAULT_PAGE_SIZE} offset: Int = 0 ): PlantPage! } diff --git a/frontend/src/graphql/plants/queries.ts b/frontend/src/graphql/plants/queries.ts index 46bfaf1d..05480a2a 100644 --- a/frontend/src/graphql/plants/queries.ts +++ b/frontend/src/graphql/plants/queries.ts @@ -2,6 +2,9 @@ import { gql } from "@apollo/client"; import type { Plant } from "../../types/Plant"; import { FILTER_COUNT_FIELDS, PLANT_FIELDS } from "../fragments/plantFragments"; +// The number of plants on each page of Explore Plants and My Matches +export const PAGE_SIZE = 12; + // Used by the Plant Match deck (usePlantDeck). Plants already in the deck are // excluded, and plants matching the most preferences come first. export const GET_PLANTS = gql` diff --git a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx index 2e06c828..7d799e64 100644 --- a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx @@ -4,6 +4,7 @@ import { useDebounce } from "../../hooks/useDebounce"; import { useExploreParams } from "../../hooks/useExploreParams.ts"; import { EXPLORE_PLANTS, + PAGE_SIZE, type ExplorePlantsData, } from "../../graphql/plants/queries.ts"; import PlantCard from "../../components/plantCard/PlantCard.tsx"; @@ -14,8 +15,6 @@ import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; import { useUser } from "../../context/UserContext"; import "./ExplorePlantsPage.css"; -const PAGE_SIZE = 12; - const SORT_OPTIONS = ["name_asc", "name_desc", "watering_asc", "careLevel_asc"]; // Plants matching the most of the user's preferences first. Only offered when diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index 8d0543f0..8e8f78d5 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -11,8 +11,7 @@ import { useMyMatchesParams } from "../../hooks/useMyMatchesParams.ts"; import { useDebounce } from "../../hooks/useDebounce.ts"; import { useUser } from "../../context/UserContext"; import { MY_MATCHES, type MyMatchesData } from "../../graphql/user/queries"; - -const PAGE_SIZE = 12; +import { PAGE_SIZE } from "../../graphql/plants/queries"; const SORT_OPTIONS = ["newest", "oldest", "name_asc", "name_desc"]; diff --git a/frontend/src/tests/ExplorePlantsPage.test.tsx b/frontend/src/tests/ExplorePlantsPage.test.tsx index 39b2f6e5..e15a27c2 100644 --- a/frontend/src/tests/ExplorePlantsPage.test.tsx +++ b/frontend/src/tests/ExplorePlantsPage.test.tsx @@ -5,7 +5,7 @@ import { MockedProvider } from "@apollo/client/testing/react"; import { MemoryRouter, useLocation } from "react-router-dom"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import ExplorePlantsPage from "../pages/explorePlants/ExplorePlantsPage"; -import { EXPLORE_PLANTS } from "../graphql/plants/queries"; +import { EXPLORE_PLANTS, PAGE_SIZE } from "../graphql/plants/queries"; // Mock i18next: return the key as the translation, with the count for the number // of results and the page numbers for the page counter @@ -79,7 +79,7 @@ const DEFAULT_VARIABLES: Variables = { careLevel: null, sort: "name_asc", preferences: null, - limit: 12, + limit: PAGE_SIZE, offset: 0, }; diff --git a/frontend/src/tests/MyMatchesPage.test.tsx b/frontend/src/tests/MyMatchesPage.test.tsx index a6a0c81c..0531d178 100644 --- a/frontend/src/tests/MyMatchesPage.test.tsx +++ b/frontend/src/tests/MyMatchesPage.test.tsx @@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; import MyMatchesPage from "../pages/myMatches/MyMatchesPage"; import type { Plant } from "../types/Plant"; +import { PAGE_SIZE } from "../graphql/plants/queries"; const { removeUserMatch, useQuery, useUser } = vi.hoisted(() => ({ removeUserMatch: vi.fn(), @@ -135,7 +136,12 @@ describe("myMatchesPage", () => { render(); expect(useQuery.mock.lastCall?.[1]).toMatchObject({ - variables: { userId: "user-1", sort: "newest", limit: 12, offset: 0 }, + variables: { + userId: "user-1", + sort: "newest", + limit: PAGE_SIZE, + offset: 0, + }, skip: false, fetchPolicy: "cache-and-network", }); From 9393d4e8886cc7db0bde1637f2d1634c5f4c9a43 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Mon, 23 Nov 2026 12:34:10 +0100 Subject: [PATCH 5/6] Fix outdated documentation --- backend/src/queryBuilders.ts | 20 +++--- backend/src/resolvers/users.ts | 4 +- docs/architecture.md | 20 +++--- docs/quality.md | 4 +- docs/tests.md | 10 ++- e2e/apiUserProfile.spec.ts | 20 ++++++ frontend/src/App.tsx | 14 ++-- frontend/src/AppRoutes.tsx | 16 ++--- frontend/src/components/header/Header.tsx | 2 +- .../src/components/plantCard/PlantCard.tsx | 2 +- .../src/components/plantCard/plantTraits.ts | 2 +- .../PlantPreferenceChips.tsx | 4 +- .../plantPreferences/PlantPreferences.tsx | 33 ++------- .../plantSearchForm/plantFilters.ts | 28 +++++++- .../sidebarButtons/LanguageSwitcher.tsx | 4 +- frontend/src/hooks/useExploreParams.ts | 15 ++--- frontend/src/hooks/useMyMatchesParams.ts | 35 +++++----- frontend/src/hooks/usePreferences.ts | 44 ++++++++++++ frontend/src/hooks/useSessionState.ts | 33 +++++---- frontend/src/i18n/locales/en/translation.json | 1 + frontend/src/i18n/locales/no/translation.json | 1 + frontend/src/main.tsx | 4 +- .../pages/explorePlants/ExplorePlantsPage.tsx | 29 ++++---- .../src/pages/myMatches/MyMatchesPage.tsx | 67 ++++++++++--------- .../src/pages/plantMatch/PlantMatchPage.tsx | 16 ++--- .../plantOwnerTest/PlantOwnerTestPage.tsx | 4 +- .../plantOwnerTest/SuggestedPreferences.tsx | 39 ++--------- .../pages/plantOwnerTest/plantOwnerTest.ts | 11 +-- frontend/src/pages/profile/ProfilePage.tsx | 67 ++++++++++--------- frontend/src/tests/App.test.tsx | 8 +-- frontend/src/tests/MyMatchesPage.test.tsx | 15 +++++ .../src/tests/PlantOwnerTestPage.test.tsx | 4 +- frontend/src/types/ProfilePicture.ts | 37 ++++++++++ 33 files changed, 351 insertions(+), 262 deletions(-) create mode 100644 frontend/src/hooks/usePreferences.ts create mode 100644 frontend/src/types/ProfilePicture.ts diff --git a/backend/src/queryBuilders.ts b/backend/src/queryBuilders.ts index 10fd207f..08c9266b 100644 --- a/backend/src/queryBuilders.ts +++ b/backend/src/queryBuilders.ts @@ -14,9 +14,11 @@ const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Filter values come in as "full_sun", the database has "full sun" const normalize = (s: string) => escapeRegex(s.replace(/_/g, " ").trim()); -// Order from low to high. -const SORT_ORDERS = { +// The values each filter can have, from low to high. Must match PLANT_FILTERS in +// frontend/src/components/plantSearchForm/plantFilters.ts +export const FILTER_OPTIONS: Record = { watering: ["minimum", "average", "frequent"], + sunlight: ["full_sun", "part_shade", "filtered_shade"], careLevel: ["low", "medium", "high"], }; @@ -61,7 +63,9 @@ export const buildSortStages = ( return [ { $addFields: { - sortRank: rankOf(SORT_ORDERS.watering, { $toLower: "$watering" }), + sortRank: rankOf(FILTER_OPTIONS.watering, { + $toLower: "$watering", + }), }, }, { $sort: { sortRank: 1, commonName: 1, _id: 1 } }, @@ -71,7 +75,7 @@ export const buildSortStages = ( return [ { $addFields: { - sortRank: rankOf(SORT_ORDERS.careLevel, { + sortRank: rankOf(FILTER_OPTIONS.careLevel, { $let: { vars: { c: { $toLower: { $ifNull: ["$careLevel", ""] } } }, in: { @@ -149,14 +153,6 @@ export const buildPlantFilter = (args: PlantFilterArgs): Filter => { return filter; }; -// The values each filter can have. Must match PLANT_FILTERS in -// frontend/src/components/plantSearchForm/plantFilters.ts -export const FILTER_OPTIONS: Record = { - watering: ["minimum", "average", "frequent"], - sunlight: ["full_sun", "part_shade", "filtered_shade"], - careLevel: ["low", "medium", "high"], -}; - // The name of one count in the $facet result, e.g. "watering:minimum" const facetKey = (param: string, value: string) => `${param}:${value}`; diff --git a/backend/src/resolvers/users.ts b/backend/src/resolvers/users.ts index 9faedf78..b8c68751 100644 --- a/backend/src/resolvers/users.ts +++ b/backend/src/resolvers/users.ts @@ -22,8 +22,8 @@ import { findPlantPage } from "./plants.js"; const NAME_MAX_LENGTH = 40; const DESCRIPTION_MAX_LENGTH = 100; -// Must match the avatar ids in frontend/src/pages/profile/ProfilePage.tsx and the -// result ids in frontend/src/pages/plantOwnerTest/plantOwnerTest.ts +// Must match AVATAR_IDS and PLANT_OWNER_TYPES in +// frontend/src/types/ProfilePicture.ts const PROFILE_PICTURES = [ "default", "monstera", diff --git a/docs/architecture.md b/docs/architecture.md index 36cd747a..05271392 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -49,9 +49,9 @@ The frontend is built with React and TypeScript (Vite). | `/plantOwnerTest` | `PlantOwnerTestPage` | A quiz whose result can be set as the profile picture, and that suggests preferences | | `*` | `NotFoundPage` | 404 page for unknown paths, with a link back to Plant Match | -- **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). +- **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile`, `usePreferences` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)). - **Error messages:** `ErrorMessageProvider` (`context/ErrorMessageContext.tsx`) wraps the app and makes `showError()` available through `useErrorMessage()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails. -- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text). `useExploreParams` keeps the Explore search, filters, sort order and page in the URL, and sends the user back to page 1 when the search, a filter or the sort order changes. It uses `useUrlParams`, which reads the page number and updates the URL (with React Router's `useSearchParams`). `useMyMatchesParams` does the same for My Matches, but keeps the search, filters and sort order in `sessionStorage` with `useSessionState`, since the matches belong to the user in this browser and a link to them could not be shared. +- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays search and profile saves while the user types. `useExploreParams` keeps the Explore search, filters, sort and page in the URL, and `useMyMatchesParams` keeps them in `sessionStorage` for My Matches, since a link to the user's matches could not be shared. `usePreferences` saves the preferences, both on the profile page and after the plant owner test. - `usePlantDeck` keeps the remaining Plant Match cards in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored. - **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `PlantSearchForm` is the search field, filters, sort menu and reset button used on both Explore Plants and My Matches (the filters are listed once in `plantFilters.ts`), `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (✿) or removes it (✖), `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages. - **Plant Owner Test:** The questions, results and suggestions are data in `pages/plantOwnerTest/plantOwnerTest.ts`, so the page only shows them. `getPlantOwnerResult()` gives the result from the location and watering answers. `getSuggestedPreferences()` gives three preference ids from the answers and the result: @@ -59,14 +59,14 @@ The frontend is built with React and TypeScript (Vite). - **Light** from the light answer. There is no preference for partial sun, so it suggests `partShade`, since those plants are listed as "part sun/part shade" in the data and match the part shade preference. - **Care level** from the result where its description says something about care: `easyCare` for the minimalists ("hardy plants") and `hardCare` for the dreaming city gardener and the garden expert ("a lot of attention"). The average gardeners get it from the time answer (10 minutes: `easyCare`, 30 minutes or 1 hour: `mediumCare`, 1 day: `hardCare`). - `SuggestedPreferences.tsx` shows the suggestions that the user does not already have as toggle buttons, all chosen from the start. Nothing is saved until the user clicks "Add to my preferences", which runs `updateUserPreferences` with the saved preferences plus the chosen suggestions, so no preference is removed. It uses an optimistic response like the buttons on the profile page, so the profile and Plant Match are updated at once. The suggestions are shown above "Use as profile picture", since that button takes the user to the profile page. + `SuggestedPreferences.tsx` shows the suggestions the user does not already have, all chosen from the start. Clicking "Add to my preferences" adds the chosen ones to the saved preferences, so none are removed. - **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). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. -- **Shared types:** `Plant`, `User` and `Preference` are defined in `types/`. +- **Shared types:** `Plant` and `User` are defined in `types/`, together with the ids that are also checked in the backend: the preferences (`Preference.ts`) and the profile pictures (`ProfilePicture.ts`). ### Communication with the backend @@ -93,7 +93,7 @@ Each file also exports the TypeScript type for the result of its operations (for The operations used to be spread across the context, a page and a hook, and we moved them into one folder after feedback, and because one of our main goals is that the app should scale: - **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. -- **The user operations are shared.** They are used by `UserProvider`, two hooks and a component, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. +- **The user operations are shared.** They are used by `UserProvider`, three hooks and My Matches, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. - **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. - **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and `myMatches`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. - **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. @@ -112,7 +112,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f - `server.ts` starts Apollo Server on `PORT` (default 3001) with the schema and resolvers below. - `schema.ts` defines the GraphQL schema (`typeDefs`). - `resolvers/` has the resolvers, split like the GraphQL operations in the frontend: `plants.ts` has the plant queries, `users.ts` has the user queries and mutations and validates user input, `helpers.ts` has the collections and helpers both use, and `index.ts` puts them together. -- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches, and the counts of how many plants each filter value would give on Explore Plants. +- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches, and the counts of how many plants each filter value would give. - `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#design-choices-made-for-scalability)). - `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments. - `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below). @@ -203,7 +203,7 @@ One document per user. There is no login: a user is created the first time someo | `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlantIds`, and the plants through `myMatches` | | `createdAt` | Date | When the user was created | `createdAt` (ISO string) | -A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers/users.ts` and must match the ids used in the frontend (`ProfilePage.tsx` and `plantOwnerTest.ts`). The preference ids are the keys of `PREFERENCE_MATCHERS` in `queryBuilders.ts`, so the list used for validation and the list used for scoring cannot get out of sync. The avatar id `snake-plant` is kept as it is, since it is already stored on existing users. +A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids in `resolvers/users.ts` must match the ids in `frontend/src/types/`, which the API tests check. Matches only store the plant id, not a copy of the plant. That keeps user documents small and means the user always sees the current plant data. @@ -236,7 +236,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`, 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. +- **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 search, filters and 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. @@ -311,7 +311,7 @@ T03-Project-2/ │ │ ├── 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, useMyMatchesParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck, useDismissibleTooltip) +│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useMyMatchesParams, useSessionState, useProfile, usePreferences, useMatchedPlants, useNewMatches, usePlantDeck, useDismissibleTooltip) │ │ ├── i18n/ # Translation setup and locale files (no, en) │ │ ├── pages/ # One folder per page/route, each with a Page.tsx and a matching .css file │ │ │ ├── explorePlants/ # ExplorePlantsPage @@ -321,7 +321,7 @@ T03-Project-2/ │ │ │ ├── plantOwnerTest/ # PlantOwnerTestPage, SuggestedPreferences, and plantOwnerTest.ts with the questions, results and suggestions │ │ │ └── profile/ # ProfilePage │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) -│ │ ├── types/ # Shared TypeScript types (Plant, User, Preference) +│ │ ├── types/ # Shared TypeScript types and ids (Plant, User, Preference, ProfilePicture) │ │ ├── AppRoutes.tsx # Route definitions │ │ └── main.tsx # Application entry point (Apollo Client, UserProvider, router) │ ├── .env.production # GraphQL URL for the deployed app diff --git a/docs/quality.md b/docs/quality.md index 6b08bd55..4dfa5951 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -89,7 +89,7 @@ We considered sustainability through both our design choices and our approach to - **Inline SVG icons without an icon library:** The application only needs a few icons (search, sort, and the sun and moon on the theme button), so we draw them ourselves as small inline SVG components instead of installing an icon library such as `react-icons`. This keeps the project to one fewer dependency that has to be downloaded, installed and kept up to date, and the icons are part of the JavaScript the page already loads, so they need no extra requests or icon font. SVGs are also vector graphics, so they stay sharp at any size and zoom level without image files in several resolutions. -- **Debouncing:** On the Explore Plants page, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost. +- **Debouncing:** On Explore Plants and My Matches, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost. - **Filter counts in one query:** The number of plants for every filter value on Explore Plants is counted in the same request as the results, in one database query, instead of one request per value. Values that would give no plants can't be chosen, so the user does not send requests that only return an empty list. @@ -107,7 +107,7 @@ We considered sustainability through both our design choices and our approach to - **Color palette and contrast:** We used a limited color palette to maintain a consistent visual identity across the application. We also checked the contrast between our chosen colors to help ensure that text and other interface elements remain distinguishable and in line with accessibility requirements. See [Accessibility](#accessibility). -- **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `PlantSearchForm` (search, filters, sort menu and reset), `Pagination` and `MatchButton` are shared by Explore Plants and My Matches, so the two pages look and work the same, and `ErrorMessage` shows error messages on every page. The filters are defined in one list (`plantFilters.ts`), so a new filter only needs one new line in the frontend. +- **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `PlantSearchForm` (search, filters, sort menu and reset), `Pagination` and `MatchButton` are shared by Explore Plants and My Matches, so the two pages look and work the same, and `ErrorMessage` shows error messages on every page. The filters are defined in one list (`plantFilters.ts`), which the search form, the URL, `sessionStorage` and the query variables all use. A new filter also needs a variable in the GraphQL queries, its texts in the translation files, and support in the backend. - **Keeping the previous results while loading:** On Explore Plants, the previous results and the number of results stay on screen, slightly dimmed, while new ones load (with Apollo's `previousData`). The page does not flicker or jump when the search, a filter or the page changes, and the loading text is only shown the first time. diff --git a/docs/tests.md b/docs/tests.md index 62bb19f5..1aea6422 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -104,7 +104,7 @@ To watch an e2e test, open UI mode, run a test, and expand it to choose the desk Test coverage for the backend -The frontend coverage counts every source file in `frontend/src`, not only the files a test happens to import, so files without tests are shown with 0 % instead of being left out. Only the test files themselves, type declarations (`.d.ts`) and `main.tsx`, which only starts the app, are left out. Files that only contain TypeScript types (`types.ts` in the backend and the files in `types/` in the frontend) are also shown with 0 %, since types are removed when the code is compiled, so there is no code to run. +The frontend coverage counts every source file in `frontend/src`, not only the files a test happens to import, so files without tests are shown with 0 % instead of being left out. Only the test files themselves, type declarations (`.d.ts`) and `main.tsx`, which only starts the app, are left out. Files that only contain TypeScript types (`types.ts` in the backend, and `Plant.ts` and `User.ts` in `types/` in the frontend) are also shown with 0 %, since types are removed when the code is compiled, so there is no code to run. The coverage only counts the Vitest tests. Code that is only run by the end-to-end tests is shown as not covered, even when it is tested there. @@ -141,7 +141,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `LanguageSwitcher.test.tsx` - The button text and accessible name in both languages, that clicking switches to the other language, and snapshots for both languages. - `MyMatchesPage.test.tsx` - - Loading and empty state: a message when there are no matches (without the count, sorting or pages), and the loading state while the user or the matches are fetched. + - Loading and empty state: a message when there are no matches (without the count, sorting or pages), the loading state while the user or the matches are fetched, and an error message when the matches cannot be fetched. - Fetching: the first page with the newest first by default, fetched again each time the page is opened, the sort order saved earlier in the session used while the page starts at 1, and saved matches shown and removed. - Sorting and pages: the number of matches next to the sort menu in an `aria-live` region that stays on the page, so "no matches" is also announced, moving between pages, a new sort order saved in `sessionStorage` and going back to page 1, and going to the last page when the current page no longer exists. - Search and filters: a chosen filter is sent, saved in `sessionStorage` and goes back to page 1, the search is sent after the debounce delay, search and filters saved earlier in the session are restored, the number of matches for each filter value with empty values disabled, a message in an `aria-live` region under the filters when no matches fit, like on Explore Plants (with the search and filters still on screen), a separate count when the list is filtered, and reset clearing the search, the filters and the sort order. The search and filters are hidden when the user has no matches at all. @@ -160,12 +160,14 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - Going on is only possible with an answer, an earlier answer is shown when going back, the result is shown with its picture, the result can be saved as profile picture, an error is shown when saving fails, the page says so when the result already is the profile picture, and the test can be taken again with no answers. - Suggested preferences: all are chosen from the start, those already saved are not suggested again, the chosen ones are added to the saved preferences, nothing is saved before the user clicks the add button (which is disabled when nothing is chosen), the page says so when all suggestions already are preferences, an error is shown when saving fails or the user is not found, and saving can be tried again. - `PlantPreferences.test.tsx` - - Saved preferences are marked, also with `aria-pressed` for screen readers, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists. + - A button for every preference, in order, saved preferences are marked, also with `aria-pressed` for screen readers, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists. - `ProfilePage.test.tsx` - The name, the image alt text and a screen reader prefix for the description, the preferences tab open by default (`aria-pressed`), the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, and that a picture from the plant owner test is shown but not offered in the chooser. - Saving the profile text at once when a field loses focus, when the user leaves the page and when the tab is reloaded or closed, without saving the same text twice. - `Sidebar.test.tsx` - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, that only the current page is marked as active, that focus moves to the close button when it opens, and that Escape closes it. +- `SidebarNewMatches.test.tsx` + - The badge on My Matches counts only matches made while the app is open, not a match that is removed again, and counts a match the user already had as new if it is removed and added again. It is cleared when My Matches is opened. - `ThemeToggle.test.tsx` - Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked. - `translationKeys.test.tsx` @@ -273,6 +275,8 @@ Saving preferences is already covered by `apiUserProfile`, and how preferences d **Profile (`uiUserProfile`):** changing name, description and avatar is shown at once and is still there after a reload, so the changes are stored in the database. +The frontend and backend have their own lists of preference and profile picture ids. `apiUserProfile` sends every id from `frontend/src/types/` to the backend and checks that all are accepted, so the test fails if an id is added in the frontend but not in the backend. + Saving the profile is debounced by 500 ms, and the text is also saved at once when a field loses focus. The test waits until the save request has reached the backend before reloading, instead of waiting a fixed time, so it does not depend on the length of the debounce. **Pictures (`uiImages`):** checks that every picture in the app is actually downloaded and decoded by the browser: the default profile picture, the seven avatars, the six pictures from the plant owner test and the placeholder on plant cards without an image. The component tests run in jsdom, which never loads images, so they only check the `src` attribute and would still pass if a file was missing or broken. An image counts as loaded when it has a natural width larger than 0. diff --git a/e2e/apiUserProfile.spec.ts b/e2e/apiUserProfile.spec.ts index bb26b315..69a7247a 100644 --- a/e2e/apiUserProfile.spec.ts +++ b/e2e/apiUserProfile.spec.ts @@ -1,6 +1,10 @@ import { test, expect } from "@playwright/test"; import { graphql, createUser, CREATE_USER, GET_USER } from "./helpers/graphql"; import { PREFERENCE_IDS } from "../frontend/src/types/Preference"; +import { + AVATAR_IDS, + PLANT_OWNER_TYPES, +} from "../frontend/src/types/ProfilePicture"; // Tests the user profile in the API: a new user's defaults, name, description, // avatar and preferences, and that invalid values are rejected. @@ -101,6 +105,22 @@ test.describe("typical use", () => { ); }); + // The same for the profile pictures: every avatar and every test result + test("accepts every profile picture the frontend has", async ({ + request, + }) => { + const userId = await createUser(request); + + for (const profilePicture of [...AVATAR_IDS, ...PLANT_OWNER_TYPES]) { + const result = await graphql(request, UPDATE_PROFILE, { + userId, + profilePicture, + }); + expect(result.errors).toBeUndefined(); + expect(result.data.updateUserProfile.profilePicture).toBe(profilePicture); + } + }); + test("only the fields that are sent are changed", async ({ request }) => { const userId = await createUser(request); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 3a751727..88cdc1cd 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,13 +1,13 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; -import "./App.css"; 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"; +import AppRoutes from "./AppRoutes"; +import { ErrorMessageProvider } from "./context/ErrorMessageContext"; +import Walkthrough from "./components/walkthrough/Walkthrough"; +import { stepForPath } from "./components/walkthrough/walkthroughSteps"; +import "./App.css"; // Remembers that the user has seen the walkthrough, so it only opens by // itself on the first visit @@ -30,7 +30,7 @@ function markWalkthroughSeen() { } } -function App() { +export default function App() { const { t } = useTranslation(); const [isSidebarOpen, setIsSidebarOpen] = useState(false); const mainContentRef = useRef(null); @@ -159,5 +159,3 @@ function App() { ); } - -export default App; diff --git a/frontend/src/AppRoutes.tsx b/frontend/src/AppRoutes.tsx index 7bf7d267..b995da8a 100644 --- a/frontend/src/AppRoutes.tsx +++ b/frontend/src/AppRoutes.tsx @@ -1,16 +1,16 @@ import { lazy, Suspense } from "react"; import { Route, Routes } from "react-router-dom"; -import PlantMatchPage from "./pages/plantMatch/PlantMatchPage.tsx"; +import PlantMatchPage from "./pages/plantMatch/PlantMatchPage"; const ExplorePlantsPage = lazy( - () => import("./pages/explorePlants/ExplorePlantsPage.tsx"), + () => import("./pages/explorePlants/ExplorePlantsPage"), ); -const MyMatchesPage = lazy(() => import("./pages/myMatches/MyMatchesPage.tsx")); -const ProfilePage = lazy(() => import("./pages/profile/ProfilePage.tsx")); +const MyMatchesPage = lazy(() => import("./pages/myMatches/MyMatchesPage")); +const ProfilePage = lazy(() => import("./pages/profile/ProfilePage")); const PlantOwnerTestPage = lazy( - () => import("./pages/plantOwnerTest/PlantOwnerTestPage.tsx"), + () => import("./pages/plantOwnerTest/PlantOwnerTestPage"), ); -const NotFoundPage = lazy(() => import("./pages/notFound/NotFoundPage.tsx")); +const NotFoundPage = lazy(() => import("./pages/notFound/NotFoundPage")); // eslint-disable-next-line react-refresh/only-export-components export const ROUTES = { @@ -22,7 +22,7 @@ export const ROUTES = { notFound: "*", } as const; -function AppRoutes() { +export default function AppRoutes() { return ( @@ -36,5 +36,3 @@ function AppRoutes() { ); } - -export default AppRoutes; diff --git a/frontend/src/components/header/Header.tsx b/frontend/src/components/header/Header.tsx index f1378271..35a37537 100644 --- a/frontend/src/components/header/Header.tsx +++ b/frontend/src/components/header/Header.tsx @@ -1,8 +1,8 @@ -import "./Header.css"; import type { Ref } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; import { ROUTES } from "../../AppRoutes"; +import "./Header.css"; type HeaderProps = { isSidebarOpen: boolean; diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index 9f7cf969..99c170cb 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -1,10 +1,10 @@ import { useEffect, useRef, useState } from "react"; import type { KeyboardEvent } from "react"; import { useTranslation } from "react-i18next"; -import "./PlantCard.css"; import PlantPreferenceChips from "../plantPreferenceChips/PlantPreferenceChips"; import type { Plant } from "../../types/Plant"; import { traitLabel } from "./plantTraits"; +import "./PlantCard.css"; type PlantCardData = Omit; diff --git a/frontend/src/components/plantCard/plantTraits.ts b/frontend/src/components/plantCard/plantTraits.ts index 1cc3ff14..09ff841c 100644 --- a/frontend/src/components/plantCard/plantTraits.ts +++ b/frontend/src/components/plantCard/plantTraits.ts @@ -1,4 +1,4 @@ -import type { PreferenceId } from "../../types/Preference.ts"; +import type { PreferenceId } from "../../types/Preference"; // The watering, sunlight and care values come from Perenual in English, and // are not consistent: the casing varies, and "Medium" and "Moderate" (and "Low" diff --git a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx index f769e2e7..14a3c76c 100644 --- a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx +++ b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx @@ -1,6 +1,6 @@ import { useTranslation } from "react-i18next"; -import { useUser } from "../../context/UserContext.tsx"; -import { getPlantPreferences } from "../plantCard/plantTraits.ts"; +import { useUser } from "../../context/UserContext"; +import { getPlantPreferences } from "../plantCard/plantTraits"; import "./PlantPreferenceChips.css"; type PlantPreferenceChipsProps = { diff --git a/frontend/src/components/plantPreferences/PlantPreferences.tsx b/frontend/src/components/plantPreferences/PlantPreferences.tsx index 966caaa1..7436da3e 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.tsx +++ b/frontend/src/components/plantPreferences/PlantPreferences.tsx @@ -1,11 +1,6 @@ -import { useMutation } from "@apollo/client/react"; import { useTranslation } from "react-i18next"; -import { useUser } from "../../context/UserContext.tsx"; -import { - UPDATE_USER_PREFERENCES, - type UpdateUserPreferencesData, -} from "../../graphql/user/mutations.ts"; -import { PREFERENCE_IDS } from "../../types/Preference.ts"; +import { usePreferences } from "../../hooks/usePreferences"; +import { PREFERENCE_IDS } from "../../types/Preference"; import "./PlantPreferences.css"; // Display plant preferences @@ -13,15 +8,10 @@ export default function PlantPreferences() { const { t } = useTranslation(); // Saved preferences come from the database through UserContext - const { userId, user } = useUser(); - const selected = user?.preferences ?? []; - - const [updatePreferences] = useMutation( - UPDATE_USER_PREFERENCES, - ); + const { preferences: selected, canSave, savePreferences } = usePreferences(); function handleClick(id: string) { - if (!userId) return; + if (!canSave) return; let updatedPreferences: string[]; @@ -31,20 +21,7 @@ export default function PlantPreferences() { updatedPreferences = [...selected, id]; } - // Save to the database. The optimistic response updates the cache right away, - // so the buttons and the plant cards change without waiting for the server. - updatePreferences({ - variables: { userId, preferences: updatedPreferences }, - optimisticResponse: { - updateUserPreferences: { - __typename: "User", - id: userId, - preferences: updatedPreferences, - }, - }, - }).catch(() => { - // Apollo rolls the buttons back if the server fails - }); + savePreferences(updatedPreferences); } // Button for each preference diff --git a/frontend/src/components/plantSearchForm/plantFilters.ts b/frontend/src/components/plantSearchForm/plantFilters.ts index 9530c92d..23ca9de5 100644 --- a/frontend/src/components/plantSearchForm/plantFilters.ts +++ b/frontend/src/components/plantSearchForm/plantFilters.ts @@ -1,7 +1,9 @@ // The filters on Explore Plants and My Matches: the name of the filter, the // translation key for the label, and the values to choose from. Must match -// FILTER_OPTIONS in backend/src/queryBuilders.ts. A new filter only needs a -// new line here (and in the backend). +// FILTER_OPTIONS in backend/src/queryBuilders.ts. The search form, the URL, +// sessionStorage and the query variables all use this list, so a new filter +// only needs a new line here. In the backend it also needs to be in the +// schema and in buildPlantFilter, and in the queries in graphql/. export const PLANT_FILTERS = [ { param: "watering", @@ -22,3 +24,25 @@ export const PLANT_FILTERS = [ export type FilterParam = (typeof PLANT_FILTERS)[number]["param"]; export type PlantFilters = Record; + +// Makes an object with one value for each filter, the filters read from +// the URL, or the filters as query variables +export function mapFilters( + value: (param: FilterParam) => T, +): Record { + return Object.fromEntries( + PLANT_FILTERS.map(({ param }) => [param, value(param)]), + ) as Record; +} + +// The filters as query variables. "All" is an empty value, which is sent as null. +export const filterVariables = (filters: PlantFilters) => + mapFilters((param) => filters[param] || null); + +// The sort order with the plants matching the most of the user's preferences +// first. Only offered when the user has chosen preferences, since it would +// be the same as the default order otherwise. +export const PREFERENCES_SORT = "preferences"; + +// How long to wait after the user stops typing before searching, in ms +export const SEARCH_DEBOUNCE_MS = 300; diff --git a/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx b/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx index a7ca27c7..21d8854a 100644 --- a/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx +++ b/frontend/src/components/sidebarButtons/LanguageSwitcher.tsx @@ -3,7 +3,7 @@ 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. -function LanguageSwitcher() { +export default function LanguageSwitcher() { const { i18n } = useTranslation(); const isNorwegian = i18n.language !== "en"; @@ -24,5 +24,3 @@ function LanguageSwitcher() { ); } - -export default LanguageSwitcher; diff --git a/frontend/src/hooks/useExploreParams.ts b/frontend/src/hooks/useExploreParams.ts index ff9c6e87..683f0a9f 100644 --- a/frontend/src/hooks/useExploreParams.ts +++ b/frontend/src/hooks/useExploreParams.ts @@ -1,5 +1,8 @@ import { useUrlParams } from "./useUrlParams"; -import type { FilterParam } from "../components/plantSearchForm/plantFilters"; +import { + mapFilters, + type FilterParam, +} from "../components/plantSearchForm/plantFilters"; const DEFAULT_SORT = "name_asc"; @@ -11,11 +14,7 @@ export function useExploreParams() { return { search: get("search"), - filters: { - watering: get("watering"), - sunlight: get("sunlight"), - careLevel: get("careLevel"), - }, + filters: mapFilters(get), sort: get("sort") || DEFAULT_SORT, page, @@ -29,9 +28,7 @@ export function useExploreParams() { reset: () => update({ search: null, - watering: null, - sunlight: null, - careLevel: null, + ...mapFilters(() => null), sort: null, page: null, }), diff --git a/frontend/src/hooks/useMyMatchesParams.ts b/frontend/src/hooks/useMyMatchesParams.ts index c6f57f1f..add87dd9 100644 --- a/frontend/src/hooks/useMyMatchesParams.ts +++ b/frontend/src/hooks/useMyMatchesParams.ts @@ -1,8 +1,9 @@ -import { useState } from "react"; -import { useSessionState } from "./useSessionState"; -import type { - FilterParam, - PlantFilters, +import { useEffect, useState } from "react"; +import { readSession, useSessionState, writeSession } from "./useSessionState"; +import { + mapFilters, + type FilterParam, + type PlantFilters, } from "../components/plantSearchForm/plantFilters"; const DEFAULT_SORT = "newest"; @@ -15,18 +16,18 @@ const DEFAULT_SORT = "newest"; // matches, which come first with the newest first, are seen right away. export function useMyMatchesParams() { const [search, setSearchState] = useSessionState("myMatches.search"); - const [watering, setWatering] = useSessionState("myMatches.watering"); - const [sunlight, setSunlight] = useSessionState("myMatches.sunlight"); - const [careLevel, setCareLevel] = useSessionState("myMatches.careLevel"); const [sort, setSortState] = useSessionState("myMatches.sort", DEFAULT_SORT); const [page, setPage] = useState(1); - const filters: PlantFilters = { watering, sunlight, careLevel }; - const setters: Record void> = { - watering: setWatering, - sunlight: setSunlight, - careLevel: setCareLevel, - }; + // Each filter has its own key, for example "myMatches.watering" + const [filters, setFilters] = useState(() => + mapFilters((param) => readSession(`myMatches.${param}`)), + ); + useEffect(() => { + for (const [param, value] of Object.entries(filters)) { + writeSession(`myMatches.${param}`, value); + } + }, [filters]); return { search, @@ -40,7 +41,7 @@ export function useMyMatchesParams() { setPage(1); }, setFilter: (param: FilterParam, value: string) => { - setters[param](value); + setFilters((previous) => ({ ...previous, [param]: value })); setPage(1); }, setSort: (value: string) => { @@ -50,9 +51,7 @@ export function useMyMatchesParams() { setPage, reset: () => { setSearchState(""); - setWatering(""); - setSunlight(""); - setCareLevel(""); + setFilters(mapFilters(() => "")); setSortState(DEFAULT_SORT); setPage(1); }, diff --git a/frontend/src/hooks/usePreferences.ts b/frontend/src/hooks/usePreferences.ts new file mode 100644 index 00000000..a1172241 --- /dev/null +++ b/frontend/src/hooks/usePreferences.ts @@ -0,0 +1,44 @@ +import { useMutation } from "@apollo/client/react"; +import { useUser } from "../context/UserContext"; +import { + UPDATE_USER_PREFERENCES, + type UpdateUserPreferencesData, +} from "../graphql/user/mutations"; + +// The user's saved preferences, and saving new ones. Used by the buttons on +// the profile page and the suggestions after the plant owner test. +export function usePreferences() { + const { userId, user } = useUser(); + const preferences = user?.preferences ?? []; + + const [updatePreferences] = useMutation( + UPDATE_USER_PREFERENCES, + ); + + // Saves the whole list. The optimistic response updates the cache right + // away, so the buttons and the plant cards change without waiting for the + // server, and Apollo rolls them back if the server fails. + // Returns whether the preferences were saved. + async function savePreferences(next: string[]): Promise { + if (!userId) return false; + try { + const result = await updatePreferences({ + variables: { userId, preferences: next }, + optimisticResponse: { + updateUserPreferences: { + __typename: "User", + id: userId, + preferences: next, + }, + }, + }); + // null means the user was not found in the database + return Boolean(result.data?.updateUserPreferences); + } catch { + return false; + } + } + + // The preferences can only be saved once the user exists + return { preferences, canSave: Boolean(userId), savePreferences }; +} diff --git a/frontend/src/hooks/useSessionState.ts b/frontend/src/hooks/useSessionState.ts index 41a8013e..e66a86ef 100644 --- a/frontend/src/hooks/useSessionState.ts +++ b/frontend/src/hooks/useSessionState.ts @@ -1,21 +1,28 @@ import { useEffect, useState } from "react"; +export function readSession(key: string, initialValue = "") { + try { + return sessionStorage.getItem(key) ?? initialValue; + } catch { + return initialValue; + } +} + +export function writeSession(key: string, value: string) { + try { + sessionStorage.setItem(key, value); + } catch { + // Storage can fail (private mode, full quota). The app still works, + // the value just won't be remembered. + } +} + +// A string state that is also kept in sessionStorage export function useSessionState(key: string, initialValue = "") { - const [value, setValue] = useState(() => { - try { - return sessionStorage.getItem(key) ?? initialValue; - } catch { - return initialValue; - } - }); + const [value, setValue] = useState(() => readSession(key, initialValue)); useEffect(() => { - try { - sessionStorage.setItem(key, value); - } catch { - // Storage can fail (private mode, full quota). The app still works, - // the value just won't be remembered. - } + writeSession(key, value); }, [key, value]); return [value, setValue] as const; diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 7889c351..de16c6fe 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -87,6 +87,7 @@ }, "myMatchesPage": { "loading": "Loading your matches...", + "error": "Could not load your matches. Please try again later.", "noMatches": "You have no matches yet. Press the flower on the match page to match with a plant.", "removeMatch": "Remove from My Matches", "matchCount_one": "You have {{count}} match", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index 80637805..03cf56f0 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -87,6 +87,7 @@ }, "myMatchesPage": { "loading": "Laster matchene dine...", + "error": "Kunne ikke hente matchene dine. Prøv igjen senere.", "noMatches": "Du har ingen matcher ennå. Trykk på blomsten på match-siden for å matche med en plante.", "removeMatch": "Fjern fra Mine Matches", "matchCount_one": "Du har {{count}} match", diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 8f8ad395..3eb48848 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -3,10 +3,10 @@ import { createRoot } from "react-dom/client"; import { HashRouter } from "react-router-dom"; import "./index.css"; import "./i18n"; -import App from "./App.tsx"; +import App from "./App"; import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client"; import { ApolloProvider } from "@apollo/client/react"; -import { UserProvider } from "./context/UserContext.tsx"; +import { UserProvider } from "./context/UserContext"; const client = new ApolloClient({ link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL ?? "/graphql" }), diff --git a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx index 7d799e64..d6efcc11 100644 --- a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx @@ -1,26 +1,27 @@ import { useTranslation } from "react-i18next"; import { useQuery } from "@apollo/client/react"; import { useDebounce } from "../../hooks/useDebounce"; -import { useExploreParams } from "../../hooks/useExploreParams.ts"; +import { useExploreParams } from "../../hooks/useExploreParams"; import { EXPLORE_PLANTS, PAGE_SIZE, type ExplorePlantsData, -} from "../../graphql/plants/queries.ts"; -import PlantCard from "../../components/plantCard/PlantCard.tsx"; -import Pagination from "../../components/pagination/Pagination.tsx"; -import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm.tsx"; -import MatchButton from "../../components/matchButton/MatchButton.tsx"; -import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; +} from "../../graphql/plants/queries"; +import PlantCard from "../../components/plantCard/PlantCard"; +import Pagination from "../../components/pagination/Pagination"; +import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm"; +import { + filterVariables, + PREFERENCES_SORT, + SEARCH_DEBOUNCE_MS, +} from "../../components/plantSearchForm/plantFilters"; +import MatchButton from "../../components/matchButton/MatchButton"; +import { useMatchedPlants } from "../../hooks/useMatchedPlants"; import { useUser } from "../../context/UserContext"; import "./ExplorePlantsPage.css"; const SORT_OPTIONS = ["name_asc", "name_desc", "watering_asc", "careLevel_asc"]; -// Plants matching the most of the user's preferences first. Only offered when -// the user has chosen preferences, since it would be the same as A–Z otherwise. -const PREFERENCES_SORT = "preferences"; - export default function ExplorePlantsPage() { const { t } = useTranslation(); @@ -36,7 +37,7 @@ export default function ExplorePlantsPage() { setPage, reset, } = useExploreParams(); - const debouncedSearch = useDebounce(search, 300); + const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS); // The user's saved preferences, for sorting by the best match. Explore has // no user of its own in the backend, so they are sent with the query. @@ -59,9 +60,7 @@ export default function ExplorePlantsPage() { } = useQuery(EXPLORE_PLANTS, { variables: { search: debouncedSearch || null, - watering: filters.watering || null, - sunlight: filters.sunlight || null, - careLevel: filters.careLevel || null, + ...filterVariables(filters), sort: activeSort, preferences: activeSort === PREFERENCES_SORT ? preferences : null, limit: PAGE_SIZE, diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index 8e8f78d5..7da4b68d 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -1,25 +1,26 @@ import { 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"; -import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm.tsx"; -import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; -import { useMyMatchesParams } from "../../hooks/useMyMatchesParams.ts"; -import { useDebounce } from "../../hooks/useDebounce.ts"; +import MatchButton from "../../components/matchButton/MatchButton"; +import PlantCard from "../../components/plantCard/PlantCard"; +import Pagination from "../../components/pagination/Pagination"; +import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm"; +import { + filterVariables, + PREFERENCES_SORT, + SEARCH_DEBOUNCE_MS, +} from "../../components/plantSearchForm/plantFilters"; +import { useMatchedPlants } from "../../hooks/useMatchedPlants"; +import { useMyMatchesParams } from "../../hooks/useMyMatchesParams"; +import { useDebounce } from "../../hooks/useDebounce"; import { useUser } from "../../context/UserContext"; import { MY_MATCHES, type MyMatchesData } from "../../graphql/user/queries"; import { PAGE_SIZE } from "../../graphql/plants/queries"; +import "./MyMatchesPage.css"; const SORT_OPTIONS = ["newest", "oldest", "name_asc", "name_desc"]; -// Matches with the most of the user's preferences first. Only offered when the -// user has chosen preferences. The backend reads them from the user. -const PREFERENCES_SORT = "preferences"; - -function MyMatchesPage() { +export default function MyMatchesPage() { const { t } = useTranslation(); const { userId, user, loading: userLoading } = useUser(); const hasPreferences = (user?.preferences ?? []).length > 0; @@ -38,7 +39,7 @@ function MyMatchesPage() { setPage, reset, } = useMyMatchesParams(); - const debouncedSearch = useDebounce(search, 300); + const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS); // A saved sort by preferences when the user no longer has any falls back // to the default order, newest first const activeSort = @@ -48,13 +49,14 @@ function MyMatchesPage() { data: currentData, previousData, loading: matchesLoading, + error, } = useQuery(MY_MATCHES, { variables: { userId, search: debouncedSearch || null, - watering: filters.watering || null, - sunlight: filters.sunlight || null, - careLevel: filters.careLevel || null, + ...filterVariables(filters), + // Sorting by preferences uses the preferences saved on the user, which + // the backend reads itself sort: activeSort, limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE, @@ -67,8 +69,9 @@ function MyMatchesPage() { // While new results load, the previous ones stay on screen, like on // Explore Plants, so the page does not flicker when the search, a filter - // or the page changes - const data = currentData ?? previousData; + // or the page changes. If the matches could not be fetched, nothing is + // shown, so the page does not say that the user has no matches. + const data = error ? undefined : (currentData ?? previousData); const plants = data?.myMatches.plants ?? []; const totalCount = data?.myMatches.totalCount ?? 0; const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE)); @@ -100,15 +103,17 @@ function MyMatchesPage() { // none. When the search or filters give no matches, it is empty, and the // message is shown in the box under the filters instead, like on Explore Plants. const noneFit = !loading && totalCount === 0 && shownFiltered; - const status = loading - ? t("myMatchesPage.loading") - : totalCount > 0 - ? shownFiltered - ? t("myMatchesPage.filteredCount", { count: totalCount }) - : t("myMatchesPage.matchCount", { count: totalCount }) - : shownFiltered - ? "" - : t("myMatchesPage.noMatches"); + const status = error + ? t("myMatchesPage.error") + : loading + ? t("myMatchesPage.loading") + : totalCount > 0 + ? shownFiltered + ? t("myMatchesPage.filteredCount", { count: totalCount }) + : t("myMatchesPage.matchCount", { count: totalCount }) + : shownFiltered + ? "" + : t("myMatchesPage.noMatches"); return (
@@ -133,7 +138,7 @@ function MyMatchesPage() { {/* Hidden only when the user has no matches at all, so the search and filters stay on screen when they give no results and can be changed */} - {!loading && (totalCount > 0 || shownFiltered) && ( + {!loading && !error && (totalCount > 0 || shownFiltered) && ( 0 || shownFiltered) && ( + {!loading && !error && (totalCount > 0 || shownFiltered) && (
@@ -196,5 +201,3 @@ function MyMatchesPage() {
); } - -export default MyMatchesPage; diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index 92176364..845dbf73 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -1,12 +1,12 @@ -import "./PlantMatchPage.css"; import { useTranslation } from "react-i18next"; -import PlantCard from "../../components/plantCard/PlantCard.tsx"; -import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; -import { usePlantDeck } from "../../hooks/usePlantDeck.ts"; -import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip.ts"; -import { ROUTES } from "../../AppRoutes.tsx"; +import PlantCard from "../../components/plantCard/PlantCard"; +import { useMatchedPlants } from "../../hooks/useMatchedPlants"; +import { usePlantDeck } from "../../hooks/usePlantDeck"; +import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip"; +import { ROUTES } from "../../AppRoutes"; +import "./PlantMatchPage.css"; -function PlantMatchPage() { +export default function PlantMatchPage() { const { t } = useTranslation(); const { addMatch } = useMatchedPlants(); const { @@ -131,5 +131,3 @@ function PlantMatchPage() { ); } - -export default PlantMatchPage; diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx index d8b7b213..1e8a77ab 100644 --- a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx @@ -2,14 +2,14 @@ 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 { useProfile } from "../../hooks/useProfile"; import { plantOwnerTest, resultImages, getPlantOwnerResult, getSuggestedPreferences, - type PlantOwnerType, } from "./plantOwnerTest"; +import type { PlantOwnerType } from "../../types/ProfilePicture"; import SuggestedPreferences from "./SuggestedPreferences"; import "./PlantOwnerTestPage.css"; diff --git a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx index bf6286ac..c2d185f1 100644 --- a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx +++ b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx @@ -1,12 +1,7 @@ -import { useMutation } from "@apollo/client/react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; -import { useUser } from "../../context/UserContext.tsx"; -import { - UPDATE_USER_PREFERENCES, - type UpdateUserPreferencesData, -} from "../../graphql/user/mutations.ts"; -import type { PreferenceId } from "../../types/Preference.ts"; +import { usePreferences } from "../../hooks/usePreferences"; +import type { PreferenceId } from "../../types/Preference"; type SuggestedPreferencesProps = { // Preference ids suggested by the test @@ -19,12 +14,7 @@ export default function SuggestedPreferences({ suggestions, }: SuggestedPreferencesProps) { const { t } = useTranslation(); - const { userId, user } = useUser(); - const saved = user?.preferences ?? []; - - const [updatePreferences] = useMutation( - UPDATE_USER_PREFERENCES, - ); + const { preferences: saved, canSave, savePreferences } = usePreferences(); // The suggestions the user wants to add. All are chosen to begin with. const [chosen, setChosen] = useState(suggestions); @@ -43,28 +33,11 @@ export default function SuggestedPreferences({ } async function addPreferences() { - if (!userId || toAdd.length === 0) return; + if (!canSave || toAdd.length === 0) return; // Added to the preferences the user already has, none are removed - const updatedPreferences = [...saved, ...toAdd]; - try { - const result = await updatePreferences({ - variables: { userId, preferences: updatedPreferences }, - // Updates the profile and plant cards right away - optimisticResponse: { - updateUserPreferences: { - __typename: "User", - id: userId, - preferences: updatedPreferences, - }, - }, - }); - // null means the user was not found in the database - setStatus(result.data?.updateUserPreferences ? "added" : "failed"); - } catch { - // Apollo rolls the preferences back if the server fails - setStatus("failed"); - } + const added = await savePreferences([...saved, ...toAdd]); + setStatus(added ? "added" : "failed"); } if (suggestions.length === 0) return null; diff --git a/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts index 9b155b40..e298382f 100644 --- a/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts +++ b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts @@ -6,15 +6,8 @@ import cityGardenerDreaming from "../../assets/plantQuiz/cityGardenerDreaming.we import countryMinimalist from "../../assets/plantQuiz/countryMinimalist.webp"; import averageCountryGardener from "../../assets/plantQuiz/averageCountryGardener.webp"; import gardenExpert from "../../assets/plantQuiz/gardenExpert.webp"; -import type { PreferenceId } from "../../types/Preference.ts"; - -export type PlantOwnerType = - | "cityMinimalist" - | "averageCityGardener" - | "cityGardenerDreaming" - | "countryMinimalist" - | "averageCountryGardener" - | "gardenExpert"; +import type { PreferenceId } from "../../types/Preference"; +import type { PlantOwnerType } from "../../types/ProfilePicture"; interface QuizQuestion { id: string; diff --git a/frontend/src/pages/profile/ProfilePage.tsx b/frontend/src/pages/profile/ProfilePage.tsx index d0792b7b..fef2f65b 100644 --- a/frontend/src/pages/profile/ProfilePage.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -1,8 +1,7 @@ -import "./ProfilePage.css"; import profileImg from "../../assets/avatars/profile.webp"; import { useTranslation } from "react-i18next"; import { useState } from "react"; -import PlantPreferences from "../../components/plantPreferences/PlantPreferences.tsx"; +import PlantPreferences from "../../components/plantPreferences/PlantPreferences"; import monstera from "../../assets/avatars/monstera.webp"; import anthurium from "../../assets/avatars/anthurium.webp"; import fern from "../../assets/avatars/fern.webp"; @@ -10,12 +9,35 @@ import orchid from "../../assets/avatars/orchid.webp"; import pothos from "../../assets/avatars/pothos.webp"; import snakePlant from "../../assets/avatars/snakePlant.webp"; import succulent from "../../assets/avatars/succulent.webp"; -import { useProfile } from "../../hooks/useProfile.ts"; -import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip.ts"; +import { useProfile } from "../../hooks/useProfile"; +import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip"; +import { resultImages } from "../plantOwnerTest/plantOwnerTest"; import { - resultImages, - type PlantOwnerType, -} from "../plantOwnerTest/plantOwnerTest.ts"; + AVATAR_IDS, + isAvatarId, + isPlantOwnerType, + type AvatarId, +} from "../../types/ProfilePicture"; +import "./ProfilePage.css"; + +// The picture and the name (translation key) of each avatar +const AVATARS: Record = { + monstera: { src: monstera, nameKey: "profile.monstera" }, + pothos: { src: pothos, nameKey: "profile.pothos" }, + "snake-plant": { src: snakePlant, nameKey: "profile.snakePlant" }, + anthurium: { src: anthurium, nameKey: "profile.anthurium" }, + succulent: { src: succulent, nameKey: "profile.succulent" }, + fern: { src: fern, nameKey: "profile.fern" }, + orchid: { src: orchid, nameKey: "profile.orchid" }, +}; + +// The picture for a saved profilePicture. Pictures from the plant owner test +// are not in the chooser, can only be set by taking the test. +function profilePictureSrc(id: string): string { + if (isAvatarId(id)) return AVATARS[id].src; + if (isPlantOwnerType(id)) return resultImages[id]; + return profileImg; +} export default function ProfilePage() { const { t } = useTranslation(); @@ -32,22 +54,7 @@ export default function ProfilePage() { const shownName = name ?? t("profile.name"); const shownDescription = description ?? t("profile.description"); - const avatars = [ - { id: "monstera", name: t("profile.monstera"), src: monstera }, - { id: "pothos", name: t("profile.pothos"), src: pothos }, - { id: "snake-plant", name: t("profile.snakePlant"), src: snakePlant }, - { id: "anthurium", name: t("profile.anthurium"), src: anthurium }, - { id: "succulent", name: t("profile.succulent"), src: succulent }, - { id: "fern", name: t("profile.fern"), src: fern }, - { id: "orchid", name: t("profile.orchid"), src: orchid }, - ]; - - // Pictures from the plant owner test are not in the chooser above, - // so they can only be set by taking the test - const currentAvatar = - avatars.find((avatar) => avatar.id === profilePicture)?.src ?? - resultImages[profilePicture as PlantOwnerType] ?? - profileImg; + const currentAvatar = profilePictureSrc(profilePicture); const infoTooltip = useDismissibleTooltip(); @@ -163,19 +170,19 @@ export default function ProfilePage() {

{t("profile.avatarChooser")}

- {avatars.map((avatar) => ( + {AVATAR_IDS.map((id) => ( ))}
diff --git a/frontend/src/tests/App.test.tsx b/frontend/src/tests/App.test.tsx index bc9b3293..13f52a4f 100644 --- a/frontend/src/tests/App.test.tsx +++ b/frontend/src/tests/App.test.tsx @@ -11,16 +11,16 @@ vi.mock("react-i18next", () => ({ // The pages have their own tests, so they are replaced by stand-ins here. // This keeps the test about which page each route shows. -vi.mock("../pages/plantMatch/PlantMatchPage.tsx", () => ({ +vi.mock("../pages/plantMatch/PlantMatchPage", () => ({ default: () =>

plant match page

, })); -vi.mock("../pages/explorePlants/ExplorePlantsPage.tsx", () => ({ +vi.mock("../pages/explorePlants/ExplorePlantsPage", () => ({ default: () =>

explore page

, })); -vi.mock("../pages/myMatches/MyMatchesPage.tsx", () => ({ +vi.mock("../pages/myMatches/MyMatchesPage", () => ({ default: () =>

my matches page

, })); -vi.mock("../pages/profile/ProfilePage.tsx", () => ({ +vi.mock("../pages/profile/ProfilePage", () => ({ default: () =>

profile page

, })); vi.mock("../components/sidebarButtons/LanguageSwitcher", () => ({ diff --git a/frontend/src/tests/MyMatchesPage.test.tsx b/frontend/src/tests/MyMatchesPage.test.tsx index 0531d178..21ddec37 100644 --- a/frontend/src/tests/MyMatchesPage.test.tsx +++ b/frontend/src/tests/MyMatchesPage.test.tsx @@ -121,6 +121,21 @@ describe("myMatchesPage", () => { ).not.toBeInTheDocument(); }); + it("shows an error instead of the no matches message when the query fails", () => { + useQuery.mockReturnValue({ + data: undefined, + loading: false, + error: new Error("Network error"), + }); + render(); + + expect(screen.getByText("myMatchesPage.error")).toBeInTheDocument(); + expect( + screen.queryByText("myMatchesPage.noMatches"), + ).not.toBeInTheDocument(); + expect(screen.queryByRole("search")).not.toBeInTheDocument(); + }); + it("shows the loading state while the user is being fetched", () => { mockUser(true); mockMatches([]); diff --git a/frontend/src/tests/PlantOwnerTestPage.test.tsx b/frontend/src/tests/PlantOwnerTestPage.test.tsx index 46a6852e..87608f6f 100644 --- a/frontend/src/tests/PlantOwnerTestPage.test.tsx +++ b/frontend/src/tests/PlantOwnerTestPage.test.tsx @@ -1,11 +1,11 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; -import PlantOwnerTestPage from "../pages/plantOwnerTest/PlantOwnerTestPage.tsx"; +import PlantOwnerTestPage from "../pages/plantOwnerTest/PlantOwnerTestPage"; import { getPlantOwnerResult, getSuggestedPreferences, -} from "../pages/plantOwnerTest/plantOwnerTest.ts"; +} from "../pages/plantOwnerTest/plantOwnerTest"; const { updateProfile, updatePreferences, useUser, navigate } = vi.hoisted( () => ({ diff --git a/frontend/src/types/ProfilePicture.ts b/frontend/src/types/ProfilePicture.ts new file mode 100644 index 00000000..da9502e7 --- /dev/null +++ b/frontend/src/types/ProfilePicture.ts @@ -0,0 +1,37 @@ +// The ids that can be saved as a user's profilePicture. Must match +// PROFILE_PICTURES in backend/src/resolvers/users.ts. "default" is the picture +// a new user starts with. + +// The avatars the user can choose on the profile page, in the order they are +// shown. "snake-plant" is kept as it is, since it is already stored on +// existing users. +export const AVATAR_IDS = [ + "monstera", + "pothos", + "snake-plant", + "anthurium", + "succulent", + "fern", + "orchid", +] as const; + +export type AvatarId = (typeof AVATAR_IDS)[number]; + +// The results of the plant owner test. The user can use their result as +// profile picture after the test. +export const PLANT_OWNER_TYPES = [ + "cityMinimalist", + "averageCityGardener", + "cityGardenerDreaming", + "countryMinimalist", + "averageCountryGardener", + "gardenExpert", +] as const; + +export type PlantOwnerType = (typeof PLANT_OWNER_TYPES)[number]; + +export const isAvatarId = (id: string): id is AvatarId => + (AVATAR_IDS as readonly string[]).includes(id); + +export const isPlantOwnerType = (id: string): id is PlantOwnerType => + (PLANT_OWNER_TYPES as readonly string[]).includes(id); From c5a3af95ee578524f57026ada77cd0a3f5aad908 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Mon, 23 Nov 2026 12:56:05 +0100 Subject: [PATCH 6/6] updated icon in link --- frontend/index.html | 2 +- frontend/public/heart.webp | Bin 0 -> 1888 bytes 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 frontend/public/heart.webp diff --git a/frontend/index.html b/frontend/index.html index 0440c963..4378d1f9 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,7 +2,7 @@ - + I <3 plants Vaz!Jt}D37Vh*7%W8+EQYW)K!yng8Whu?5VB7a2_VCS!jLK^OGC_qQItpk2>=8j z<{$`Sjyci*1Zjbwpcpg-L1aLX6hr|*!60Y=l>k8j5(o{$bn;d#1wrT#O%Mz=087IY z6aplPC#VFd779bkAt(e$-lP}fwHPwJJo>{ygZ@;0%!jsYw8gP4n}^LhbDQs6HwQ6J z8}&cJ>tT+PZO?iLT2R~DzCJZt+P~eGYZOKZBwz@Xe{Gk+=3~#VbQT70U)$B>^)g*{ zfxqdxkNNYj)93I1^D#MS3jkzDl6thZZQHhOYp}L$+qUmZTPs$y*w6-A;KW0v6%$i!UR3z8 zuM}i8yq?G^AS`Kn3S$SQq~BD<;se+JfLbpRS=z zz4UWos)pA3z*JZng*Us#&sd}3U0DH?8);F9lbZd=SPij%1CV>;qd>R%o{j?T?txKY zY!vL*-&hUySOdiSwNbzuG8+xJ{~m^+QOJ{@TnQl4AqXur>?xs!odI|j00({$N|$e} zM!t2j?bqlJB`c;07)X_8DFsX*Q+G{5C(->x8YCKdhD3=NNOL2J3f7lplP04t$#qT0 zP>w#7a8mr8NQp!z!|Nz1tqcojVI-)iiRr}aMhzBkEH$if6*M_nw6^pJMcYn~?SjQ+ z(u18?Wi>&4vD#Cly;uV%5{fmKA}mx)CPmnabW@YGkVr*nQbeRWG^r!fIhr_;I?%+5 z)SD(OQh%BRA`PU86X_65tVl;_5{eYiBoOHzngk+srim|7TbhI-)uRcE^n@l>q;fQ= zAkqh#Sdn-mRKo9l=|DPWJi&lglMMV2D zff~LMjrUU{WZ`R5!x!&XA}tb)c)XhyjwO6bi$I1iD=D$k$iQ7F(UqnAGl>rNPdRuW z9Rim0DIEe?VrEgnx3X|uDpY1^zbvJJ`63UWr@?uaIBo_7#yXj}G6f7v9lHR3hUMY_ ze*w$B1$)C;`s>NK3qtw$U)+TZV7}>?vkn5Tj=9d z02ANHz*5Rz9@N#aREOa{jiX)+c?tGpKmPO{qnQD2{k z;!I!F9gSht8>hB`mep?#sO)g8he3N(U4vph9NPY>+8^s-(VSA#kysCprmu<)TE?U~ zsh(q&k=aW%$0Ll+9%?z^Vf3s@PJ1|gtBwwg)$>V;2pO-Hvs7Rkdzh^@1-`6?jN2=T z&`qhv*ey8;w#+9Ue#@po78GR+-(3!uUy*VAa0XPX?s{0hxd5isFBs1+*Fv=tu+APcZ2TaAU1LQFAOvlJ+ z8ID>e>HPiEQhDh!rQ?%?vaWXD5P5)Rb%EW6PRd0?KW88C(t`ByI zu=pKQHhx&{jm+!O_Up0S+WU#g+dX#%d}RW+Ps#-sVG>u(&MDiBsa)b!&Scm0=v;AH zPE0D!l>TGsuZ@4iw7xm|SH`?xYUkbgb93)_^!~K>XSUs9ihmvOqeF2_^GN6Korv+s a-ZDvR-I^(1Ws0lJv@iCAfBXNp9{~U$Wq67J literal 0 HcmV?d00001