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 (
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 `