From 47305da0eb003674c7c460159ca0b0ccda8dc14b Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Thu, 5 Nov 2026 15:40:44 +0100 Subject: [PATCH 1/3] Fetch plants in small batches instead of loading 60 at once --- backend/src/server.ts | 13 +- backend/tests/server.test.ts | 20 +++ frontend/src/hooks/usePlantDeck.ts | 99 ++++++++++++ .../src/pages/plantMatch/PlantMatchPage.tsx | 50 +----- frontend/src/tests/PlantMatchPage.test.tsx | 142 +++++++++++++++--- 5 files changed, 258 insertions(+), 66 deletions(-) create mode 100644 frontend/src/hooks/usePlantDeck.ts diff --git a/backend/src/server.ts b/backend/src/server.ts index 99a33ee7..49ecb395 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -32,7 +32,9 @@ interface Plant { interface GetPlantsArgs { limit: number; - offset: number; + // 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. + excludeIds?: string[] | null; } interface ExplorePlantsArgs { @@ -129,7 +131,7 @@ const users = db.collection("users"); const typeDefs = ` type Query{ - getPlants(limit: Int = 50, offset: Int = 0): [Plant] + getPlants(limit: Int = 50, excludeIds: [ID!]): [Plant] explorePlants( search: String sunlight: String @@ -298,8 +300,15 @@ const resolvers = { _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 excluded = (args.excludeIds ?? []).flatMap((id) => { + const objectId = toObjectId(id); + return objectId ? [objectId] : []; + }); const docs = await plants .aggregate>([ + { $match: { _id: { $nin: excluded } } }, { $sample: { size: args.limit, diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index 8c2b18bf..5b5d935f 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -259,6 +259,26 @@ describe("plants", () => { expect(new Set(ids).size).toBe(3); }); + it("getPlants leaves out excluded plants and returns none when all are excluded", async () => { + const all = await execute<{ getPlants: { id: string }[] }>( + "query { getPlants { id } }", + ); + const allIds = all.data!.getPlants.map((p) => p.id); + const [kept, ...excluded] = allIds; + + const result = await execute<{ getPlants: { id: string }[] }>( + "query ($ids: [ID!]) { getPlants(excludeIds: $ids) { id } }", + { ids: [...excluded, "not-an-id"] }, + ); + expect(result.data!.getPlants.map((p) => p.id)).toEqual([kept]); + + const none = await execute<{ getPlants: { id: string }[] }>( + "query ($ids: [ID!]) { getPlants(excludeIds: $ids) { id } }", + { ids: allIds }, + ); + expect(none.data!.getPlants).toEqual([]); + }); + it("uses the stored image data before the image URL", async () => { await db.collection("plants").deleteMany({}); await insertPlants( diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts new file mode 100644 index 00000000..207d548a --- /dev/null +++ b/frontend/src/hooks/usePlantDeck.ts @@ -0,0 +1,99 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { gql } from "@apollo/client"; +import { useApolloClient } from "@apollo/client/react"; +import type { Plant } from "../types/Plant"; + +// How many plants are fetched per request. Keep it between 5 and 10. +export const PLANT_BATCH_SIZE = 8; + +// The next batch is fetched when this many cards (or fewer) are left in the deck +export const PREFETCH_THRESHOLD = 3; + +export const GET_PLANTS = gql` + query GetPlants($limit: Int, $excludeIds: [ID!]) { + getPlants(limit: $limit, excludeIds: $excludeIds) { + id + name + imageURL + scientificName + description + watering + sunlight + careLevel + } + } +`; + +export type GetPlantsData = { + getPlants: Plant[]; +}; + +// A deck of random plants that is loaded in small batches while the user swipes. +// Plants already in the deck are excluded by the backend, so a plant is never +// shown twice while the page is open. +export function usePlantDeck() { + const client = useApolloClient(); + const [plants, setPlants] = useState([]); + const [index, setIndex] = useState(0); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(); + const [hasMore, setHasMore] = useState(true); + + // Refs, so a second call in the same render can't start a duplicate request + const inFlight = useRef(false); + const seenIds = useRef(new Set()); + + const loadMore = useCallback(async () => { + if (inFlight.current) return; + inFlight.current = true; + setLoading(true); + try { + const { data, error: queryError } = await client.query({ + query: GET_PLANTS, + variables: { + limit: PLANT_BATCH_SIZE, + excludeIds: [...seenIds.current], + }, + fetchPolicy: "no-cache", + }); + if (queryError) throw queryError; + + const received = data?.getPlants ?? []; + const batch = received.filter((p) => !seenIds.current.has(p.id)); + batch.forEach((p) => seenIds.current.add(p.id)); + + setPlants((current) => [...current, ...batch]); + setError(undefined); + // A short or empty batch means the backend has run out of plants + if (received.length < PLANT_BATCH_SIZE || batch.length === 0) { + setHasMore(false); + } + } catch (e) { + setError(e instanceof Error ? e : new Error(String(e))); + } finally { + inFlight.current = false; + setLoading(false); + } + }, [client]); + + // Fetch the first batch, and the next one when the deck is nearly empty. + // After a failed request it tries again on the next swipe. + useEffect(() => { + if (hasMore && plants.length - index <= PREFETCH_THRESHOLD) { + void loadMore(); + } + }, [index, plants.length, hasMore, loadMore]); + + const next = useCallback(() => setIndex((current) => current + 1), []); + + const plant = plants[index]; + + return { + plant, + next, + // Only true while there is no card to show, background loads stay hidden + loading: loading && !plant, + error: plant ? undefined : error, + noMorePlants: !plant && !hasMore && !loading, + } as const; +} diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index b8e93f8f..9c32a882 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -1,53 +1,19 @@ -import { useState } from "react"; import "./PlantMatchPage.css"; import { useTranslation } from "react-i18next"; -import { gql } from "@apollo/client"; -import { useQuery } from "@apollo/client/react"; import PlantCard from "../../components/plantCard/PlantCard.tsx"; import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; -import type { Plant } from "../../types/Plant.ts"; - -const GET_PLANTS = gql` - query GetPlants($limit: Int, $offset: Int) { - getPlants(limit: $limit, offset: $offset) { - id - name - imageURL - scientificName - description - watering - sunlight - careLevel - } - } -`; - -type GetPlantsData = { - getPlants: Plant[]; -}; +import { usePlantDeck } from "../../hooks/usePlantDeck.ts"; function PlantMatchPage() { const { t } = useTranslation(); - const [currentPlant, setCurrentPlant] = useState(0); const { addMatch } = useMatchedPlants(); - - const { data, loading, error } = useQuery(GET_PLANTS, { - variables: { - limit: 60, - offset: 0, - }, - }); - - const plant = data?.getPlants[currentPlant]; - - const noMorePlants = - !!data && - data.getPlants.length > 0 && - currentPlant >= data.getPlants.length; - - const goToNextPlant = () => { - setCurrentPlant((current) => current + 1); - }; + const { + plant, + next: goToNextPlant, + loading, + error, + noMorePlants, + } = usePlantDeck(); const matchPlant = () => { if (plant) addMatch(plant); diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index a5792aaf..93a34f4b 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -1,14 +1,16 @@ -import { fireEvent, render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, it, expect, vi } from "vitest"; import PlantMatchPage from "../pages/plantMatch/PlantMatchPage"; +import { PLANT_BATCH_SIZE, PREFETCH_THRESHOLD } from "../hooks/usePlantDeck"; +import type { Plant } from "../types/Plant"; -const { useQuery, addUserMatch, useUser } = vi.hoisted(() => ({ - useQuery: vi.fn(), +const { query, addUserMatch, useUser } = vi.hoisted(() => ({ + query: vi.fn(), addUserMatch: vi.fn(), useUser: vi.fn(), })); vi.mock("@apollo/client/react", () => ({ - useQuery, + useApolloClient: () => ({ query }), useMutation: () => [addUserMatch], })); vi.mock("../context/UserContext", () => ({ useUser })); @@ -16,7 +18,7 @@ vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); -const plants = ["Hydrangea", "Orchid"].map((name, id) => ({ +const makePlant = (name: string, id: number): Plant => ({ id: String(id), name, imageURL: null, @@ -25,7 +27,31 @@ const plants = ["Hydrangea", "Orchid"].map((name, id) => ({ watering: "Average", sunlight: ["Full sun"], careLevel: "Easy", -})); +}); + +const plants = ["Hydrangea", "Orchid"].map(makePlant); + +// The backend answers with the plants that are not in excludeIds, in batches +function mockBackend(all: Plant[]) { + query.mockImplementation( + async ({ + variables, + }: { + variables: { limit: number; excludeIds: string[] }; + }) => ({ + data: { + getPlants: all + .filter((p) => !variables.excludeIds.includes(p.id)) + .slice(0, variables.limit), + }, + }), + ); +} + +const skip = () => + fireEvent.click( + screen.getByRole("button", { name: "plantMatchPage.skipPlant" }), + ); // A user with the given saved preferences and no matches yet function mockUser(preferences: string[] = []) { @@ -45,32 +71,30 @@ function mockUser(preferences: string[] = []) { beforeEach(() => { addUserMatch.mockClear(); + query.mockReset(); mockUser(); - useQuery.mockReturnValue({ - data: { getPlants: plants }, - loading: false, - error: undefined, - }); + mockBackend(plants); }); describe("PlantMatchPage", () => { - it("shows instructions and the first plant", () => { + it("shows instructions and the first plant", async () => { render(); expect( screen.getByRole("heading", { name: "plantMatchPage.howToMatch" }), ).toBeInTheDocument(); - expect(screen.getAllByText("Hydrangea").length).toBeGreaterThan(0); + expect((await screen.findAllByText("Hydrangea")).length).toBeGreaterThan(0); }); it.each(["plantMatchPage.skipPlant", "plantMatchPage.likePlant"])( "advances to the next plant with %s and shows the empty card at the end", - (button) => { + async (button) => { render(); + await screen.findAllByText("Hydrangea"); fireEvent.click(screen.getByRole("button", { name: button })); expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); fireEvent.click(screen.getByRole("button", { name: button })); expect( - screen.getByRole("heading", { + await screen.findByRole("heading", { name: "plantMatchPage.noMorePlantsTitle", }), ).toBeInTheDocument(); @@ -78,8 +102,9 @@ describe("PlantMatchPage", () => { }, ); - it("saves a liked plant as a match, but not a skipped one", () => { + it("saves a liked plant as a match, but not a skipped one", async () => { render(); + await screen.findAllByText("Hydrangea"); fireEvent.click( screen.getByRole("button", { name: "plantMatchPage.skipPlant" }), ); @@ -93,23 +118,23 @@ describe("PlantMatchPage", () => { }); it("shows the loading state", () => { - useQuery.mockReturnValue({ loading: true }); + query.mockReturnValue(new Promise(() => {})); render(); expect(screen.getByText("plantMatchPage.loading")).toBeInTheDocument(); }); - it("shows the error card", () => { - useQuery.mockReturnValue({ loading: false, error: new Error("Offline") }); + it("shows the error card", async () => { + query.mockRejectedValue(new Error("Offline")); render(); expect( - screen.getByRole("heading", { name: "plantMatchPage.error" }), + await screen.findByRole("heading", { name: "plantMatchPage.error" }), ).toBeInTheDocument(); }); - it("highlights card preferences saved on the profile", () => { + it("highlights card preferences saved on the profile", async () => { mockUser(["averageWater"]); render(); - expect(screen.getByText("preferences.averageWater")).toHaveClass( + expect(await screen.findByText("preferences.averageWater")).toHaveClass( "is-match", ); expect(screen.getByText("preferences.fullSun")).not.toHaveClass("is-match"); @@ -120,4 +145,77 @@ describe("PlantMatchPage", () => { screen.getByRole("group", { name: "preferences.fullSun" }), ).not.toHaveAttribute("aria-description"); }); + + it("loads plants in batches and fetches the next batch near the end", async () => { + const many = Array.from({ length: PLANT_BATCH_SIZE * 2 + 2 }, (_, i) => + makePlant(`Plant ${i}`, i), + ); + mockBackend(many); + render(); + await screen.findAllByText("Plant 0"); + + expect(query).toHaveBeenCalledTimes(1); + expect(query.mock.calls[0][0].variables).toEqual({ + limit: PLANT_BATCH_SIZE, + excludeIds: [], + }); + + // No new request until only PREFETCH_THRESHOLD cards are left + for (let i = 0; i < PLANT_BATCH_SIZE - PREFETCH_THRESHOLD - 1; i++) skip(); + expect(query).toHaveBeenCalledTimes(1); + skip(); + await waitFor(() => expect(query).toHaveBeenCalledTimes(2)); + expect(query.mock.calls[1][0].variables.excludeIds).toEqual( + many.slice(0, PLANT_BATCH_SIZE).map((p) => p.id), + ); + + // Swipe through every plant: each one is shown exactly once, then the end card + for (let i = PLANT_BATCH_SIZE - PREFETCH_THRESHOLD; i < many.length; i++) { + expect((await screen.findAllByText(`Plant ${i}`)).length).toBeGreaterThan( + 0, + ); + skip(); + } + expect( + await screen.findByRole("heading", { + name: "plantMatchPage.noMorePlantsTitle", + }), + ).toBeInTheDocument(); + // The last batch was short, so no more requests are made + expect(query).toHaveBeenCalledTimes(3); + }); + + it("does not start a second request while one is in progress", async () => { + const many = Array.from({ length: PLANT_BATCH_SIZE * 3 }, (_, i) => + makePlant(`Plant ${i}`, i), + ); + mockBackend(many); + render(); + await screen.findAllByText("Plant 0"); + + let resolve: (value: unknown) => void = () => {}; + query.mockImplementationOnce(() => new Promise((r) => (resolve = r))); + for (let i = 0; i < PLANT_BATCH_SIZE - 1; i++) skip(); + expect(query).toHaveBeenCalledTimes(2); + + resolve({ + data: { getPlants: many.slice(PLANT_BATCH_SIZE, PLANT_BATCH_SIZE * 2) }, + }); + expect( + await screen.findAllByText(`Plant ${PLANT_BATCH_SIZE - 1}`), + ).not.toHaveLength(0); + }); + + it("shows the end card when there are no plants at all", async () => { + mockBackend([]); + render(); + expect( + await screen.findByRole("heading", { + name: "plantMatchPage.noMorePlantsTitle", + }), + ).toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "plantMatchPage.likePlant" }), + ).toBeDisabled(); + }); }); From 45c12ba7a84baf2ba903660a591955600e1583f6 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Thu, 5 Nov 2026 15:52:43 +0100 Subject: [PATCH 2/3] Sort Plant Match by user preferences --- README.md | 4 +- backend/src/server.ts | 71 +++++++++++++++++-- backend/tests/server.test.ts | 54 ++++++++++++++ .../PlantPreferenceChips.tsx | 3 +- frontend/src/hooks/usePlantDeck.ts | 32 +++++++-- frontend/src/tests/PlantMatchPage.test.tsx | 18 +++++ 6 files changed, 167 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index a62a00f7..4093f6d5 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ http://it2810-03.idi.ntnu.no/project2/ ## Core features -- **Plant Match:** Shows random plants one at a time. Click ✿ to like a plant or ✖ to skip it. -- **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, but the preferences do not change which plants are shown. +- **Plant Match:** Shows plants one at a time, best matches for your preferences first. Click ✿ to like a plant or ✖ to skip it. +- **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, and Plant Match shows the plants that match the most of your preferences first. Without preferences, the plants come in random order. - **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants. You can also remove plants from the list. - **Explore Plants:** Search the plant collection by name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the results are split into pages. You can also add plants to My Matches from here. - **Plant details:** Each plant card shows an image, the scientific name, a description and care information (watering, sunlight and care level). Flip the card to read more about the plant. diff --git a/backend/src/server.ts b/backend/src/server.ts index 49ecb395..efce4a3f 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -35,6 +35,8 @@ interface GetPlantsArgs { // 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. excludeIds?: string[] | null; + // The user's preferences. Plants matching the most of them come first. + preferences?: string[] | null; } interface ExplorePlantsArgs { @@ -131,7 +133,7 @@ const users = db.collection("users"); const typeDefs = ` type Query{ - getPlants(limit: Int = 50, excludeIds: [ID!]): [Plant] + getPlants(limit: Int = 50, excludeIds: [ID!], preferences: [String!]): [Plant] explorePlants( search: String sunlight: String @@ -294,6 +296,45 @@ const buildSortStages = (sort?: string): Document[] => { } }; +// Lowercased field value, missing values become "" +const lower = (field: string): Document => ({ + $toLower: { $ifNull: [field, ""] }, +}); + +// True if any of the plant's sunlight values contains the text, +// e.g. "part shade" also matches "part sun/part shade" +const sunlightIncludes = (text: string): Document => ({ + $anyElementTrue: [ + { + $map: { + input: { $ifNull: ["$sunlight", []] }, + as: "s", + in: { $regexMatch: { input: { $toLower: "$$s" }, regex: text } }, + }, + }, + ], +}); + +// How each preference id maps to the plant attributes. Must match +// frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx. +// The data uses "Low" for easy care and both "Medium" and "Moderate". +const PREFERENCE_MATCHERS: Record = { + minimumWater: { $eq: [lower("$watering"), "minimum"] }, + averageWater: { $eq: [lower("$watering"), "average"] }, + frequentWater: { $eq: [lower("$watering"), "frequent"] }, + fullSun: sunlightIncludes("full sun"), + partShade: sunlightIncludes("part shade"), + filteredShade: sunlightIncludes("filtered shade"), + easyCare: { $in: [lower("$careLevel"), ["low", "easy"]] }, + mediumCare: { $in: [lower("$careLevel"), ["medium", "moderate"]] }, + hardCare: { $eq: [lower("$careLevel"), "high"] }, +}; + +// The number of the given preferences that a plant matches +const matchScore = (preferences: string[]): Document => ({ + $add: preferences.map((p) => ({ $cond: [PREFERENCE_MATCHERS[p], 1, 0] })), +}); + const resolvers = { Query: { getPlants: async ( @@ -306,14 +347,32 @@ const resolvers = { const objectId = toObjectId(id); return objectId ? [objectId] : []; }); + const preferences = [...new Set(args.preferences ?? [])].filter((p) => + Object.hasOwn(PREFERENCE_MATCHERS, p), + ); + + // 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: args.limit } }] + : [ + { + $addFields: { + matchScore: matchScore(preferences), + shuffle: { $rand: {} }, + }, + }, + { $sort: { matchScore: -1, shuffle: 1 } }, + { $limit: args.limit }, + ]; + const docs = await plants .aggregate>([ { $match: { _id: { $nin: excluded } } }, - { - $sample: { - size: args.limit, - }, - }, + ...orderStages, { $project: { commonName: 1, diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index 5b5d935f..4d6ec0a2 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -279,6 +279,60 @@ describe("plants", () => { expect(none.data!.getPlants).toEqual([]); }); + const GET_PLANTS = ` + query ($limit: Int, $ids: [ID!], $preferences: [String!]) { + getPlants(limit: $limit, excludeIds: $ids, preferences: $preferences) { id name } + } + `; + + // Fetches every plant in batches, the same way Plant Match does + async function fetchAllInBatches(preferences: string[], limit = 2) { + const all: { id: string; name: string }[] = []; + for (;;) { + const result = await execute<{ + getPlants: { id: string; name: string }[]; + }>(GET_PLANTS, { limit, ids: all.map((p) => p.id), preferences }); + all.push(...result.data!.getPlants); + if (result.data!.getPlants.length < limit) return all.map((p) => p.name); + } + } + + it("getPlants puts the plants matching the most preferences first, across batches", async () => { + // Daisy matches 3, Basil (Moderate, part shade) and Fern (giant) match 2, the rest 0 + const names = await fetchAllInBatches([ + "averageWater", + "mediumCare", + "partShade", + ]); + + expect(names).toHaveLength(PLANTS.length); + expect(names[0]).toBe("Daisy"); + expect(new Set(names.slice(1, 3))).toEqual( + new Set(["Basil", "Fern (giant)"]), + ); + expect(new Set(names.slice(3))).toEqual( + new Set(["Aloe", "Cactus", "Fern"]), + ); + }); + + it("getPlants counts Low care as easy care", async () => { + // Aloe: minimum water, Low care and full sun + const names = await fetchAllInBatches([ + "minimumWater", + "easyCare", + "fullSun", + ]); + expect(names[0]).toBe("Aloe"); + }); + + it("getPlants ignores unknown preferences and works without preferences", async () => { + for (const preferences of [[], ["toString", "notAPreference"]]) { + const names = await fetchAllInBatches(preferences); + expect(new Set(names)).toEqual(new Set(PLANTS.map((p) => p.commonName))); + expect(names).toHaveLength(PLANTS.length); + } + }); + it("uses the stored image data before the image URL", async () => { await db.collection("plants").deleteMany({}); await insertPlants( diff --git a/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx b/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx index b9c88bbe..6bfc434e 100644 --- a/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx +++ b/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx @@ -58,7 +58,8 @@ export default function PlantPreferenceChips({ // Care level const care = careLevel?.toLowerCase(); - if (care === "easy") { + // The data uses "Low" for easy care. Must match PREFERENCE_MATCHERS in backend/src/server.ts + if (care === "easy" || care === "low") { carePreferences.push("easyCare"); } diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 207d548a..5560fc09 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { gql } from "@apollo/client"; import { useApolloClient } from "@apollo/client/react"; +import { useUser } from "../context/UserContext"; import type { Plant } from "../types/Plant"; // How many plants are fetched per request. Keep it between 5 and 10. @@ -10,8 +11,12 @@ export const PLANT_BATCH_SIZE = 8; export const PREFETCH_THRESHOLD = 3; export const GET_PLANTS = gql` - query GetPlants($limit: Int, $excludeIds: [ID!]) { - getPlants(limit: $limit, excludeIds: $excludeIds) { + query GetPlants($limit: Int, $excludeIds: [ID!], $preferences: [String!]) { + getPlants( + limit: $limit + excludeIds: $excludeIds + preferences: $preferences + ) { id name imageURL @@ -30,9 +35,11 @@ export type GetPlantsData = { // A deck of random plants that is loaded in small batches while the user swipes. // Plants already in the deck are excluded by the backend, so a plant is never -// shown twice while the page is open. +// shown twice while the page is open. Plants matching the most of the user's +// preferences come first. Without preferences the order is random. export function usePlantDeck() { const client = useApolloClient(); + const { user, loading: userLoading } = useUser(); const [plants, setPlants] = useState([]); const [index, setIndex] = useState(0); const [loading, setLoading] = useState(false); @@ -43,6 +50,13 @@ export function usePlantDeck() { const inFlight = useRef(false); const seenIds = useRef(new Set()); + // Read when a batch is fetched, so new preferences don't restart the deck + // Declared before the fetch effect, so it runs first + const preferences = useRef([]); + useEffect(() => { + preferences.current = user?.preferences ?? []; + }, [user]); + const loadMore = useCallback(async () => { if (inFlight.current) return; inFlight.current = true; @@ -53,6 +67,7 @@ export function usePlantDeck() { variables: { limit: PLANT_BATCH_SIZE, excludeIds: [...seenIds.current], + preferences: preferences.current, }, fetchPolicy: "no-cache", }); @@ -78,11 +93,16 @@ export function usePlantDeck() { // Fetch the first batch, and the next one when the deck is nearly empty. // After a failed request it tries again on the next swipe. + // Waits for the user, so the first batch is already sorted by preferences. useEffect(() => { - if (hasMore && plants.length - index <= PREFETCH_THRESHOLD) { + if ( + !userLoading && + hasMore && + plants.length - index <= PREFETCH_THRESHOLD + ) { void loadMore(); } - }, [index, plants.length, hasMore, loadMore]); + }, [index, plants.length, hasMore, loadMore, userLoading]); const next = useCallback(() => setIndex((current) => current + 1), []); @@ -92,7 +112,7 @@ export function usePlantDeck() { plant, next, // Only true while there is no card to show, background loads stay hidden - loading: loading && !plant, + loading: (loading || userLoading) && !plant, error: plant ? undefined : error, noMorePlants: !plant && !hasMore && !loading, } as const; diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 93a34f4b..55346d0f 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -158,6 +158,7 @@ describe("PlantMatchPage", () => { expect(query.mock.calls[0][0].variables).toEqual({ limit: PLANT_BATCH_SIZE, excludeIds: [], + preferences: [], }); // No new request until only PREFETCH_THRESHOLD cards are left @@ -218,4 +219,21 @@ describe("PlantMatchPage", () => { screen.getByRole("button", { name: "plantMatchPage.likePlant" }), ).toBeDisabled(); }); + + it("sends the user's preferences so the best matches come first", async () => { + mockUser(["averageWater", "fullSun"]); + render(); + await screen.findAllByText("Hydrangea"); + expect(query.mock.calls[0][0].variables.preferences).toEqual([ + "averageWater", + "fullSun", + ]); + }); + + it("waits for the user before fetching the first batch", () => { + useUser.mockReturnValue({ userId: "user-1", user: null, loading: true }); + render(); + expect(query).not.toHaveBeenCalled(); + expect(screen.getByText("plantMatchPage.loading")).toBeInTheDocument(); + }); }); From 0af2125b3f6ab6247d907c6f095f041532535252 Mon Sep 17 00:00:00 2001 From: ninaflaaten Date: Fri, 6 Nov 2026 14:19:11 +0100 Subject: [PATCH 3/3] Update docs for getPlants batches and preference sorting --- docs/architecture.md | 26 +++++++++---------- docs/tests.md | 6 +++-- frontend/src/hooks/usePlantDeck.ts | 2 +- frontend/src/i18n/locales/en/translation.json | 2 +- 4 files changed, 19 insertions(+), 17 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index efbe3d50..c8ad9953 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -38,13 +38,13 @@ The frontend is built with React and TypeScript (Vite). - **Routing:** Routes are defined in `AppRoutes.tsx` with React Router, and the app is served under the base path `/project2/`. Vite defines this base in `frontend/vite.config.ts`; `BrowserRouter` uses the same value through `import.meta.env.BASE_URL`. All pages except the start page are lazy-loaded. - | Route | Page | Purpose | - | ----------------- | ---------------- | -------------------------------------------------------------- | - | `/` | `PlantMatchPage` | Swipe through random plants (`getPlants`) and match with them | - | `/explorePlants` | `ExplorePlants` | Search, filter, sort and paginate all plants (`explorePlants`) | - | `/my-matches` | `MyMatchesPage` | List and remove the user's matched plants | - | `/profile` | `Profile` | Edit name, description, profile picture and preferences | - | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | + | Route | Page | Purpose | + | ----------------- | ---------------- | ----------------------------------------------------------------- | + | `/` | `PlantMatchPage` | Swipe through plants (`getPlants`), best preference matches first | + | `/explorePlants` | `ExplorePlants` | Search, filter, sort and paginate all plants (`explorePlants`) | + | `/my-matches` | `MyMatchesPage` | List and remove the user's matched plants | + | `/profile` | `Profile` | Edit name, description, profile picture and preferences | + | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | - **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. All user queries and mutations live in `context/userQueries.ts`. - **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), and `useSessionState` stores state in `sessionStorage`. @@ -69,11 +69,11 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f **Queries** -| Query | Description | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `getPlants(limit = 50, offset = 0): [Plant]` | Returns `limit` random plants (MongoDB `$sample`). Used by the match page. `offset` is accepted but has no effect, since the plants are random. | -| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on name (case-insensitive), filter on sunlight, watering and care level, sort and paginate. Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | -| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | +| Query | Description | +| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. | +| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on name (case-insensitive), filter on sunlight, watering and care level, sort and paginate. Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | +| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | **Mutations** @@ -226,7 +226,7 @@ T03-Project-2/ │ │ ├── assets/ # Static images │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file │ │ ├── context/ # UserProvider and the GraphQL queries and mutations for the user -│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useSessionState, useProfile, useMatchedPlants) +│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useSessionState, useProfile, useMatchedPlants, usePlantDeck) │ │ ├── i18n/ # Translation setup and locale files (no, en) │ │ ├── pages/ # One folder per page/route with a matching .css file │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) diff --git a/docs/tests.md b/docs/tests.md index a967dc07..b69fc91d 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -130,6 +130,8 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - The back of the card shows the whole plant after clicking information, missing facts and images are shown as unknown, and watering, sunlight and care level are turned into the right preference chips. - `PlantMatchPage.test.tsx` - The instructions and the first plant, going to the next plant with like and dislike and the empty card at the end, that a liked plant is saved as a match and a skipped one is not, the loading and error states, and that preferences saved on the profile are highlighted on the card. + - Loading in batches: the first batch is fetched with the batch size and no excluded plants, the next batch is only fetched when few cards are left and leaves out the plants already shown, every plant is shown exactly once, no more requests are made after a short batch, and a second request is not started while one is in progress. + - Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all. - `PlantOwnerTest.test.tsx` - The result for all six combinations of answers, and that the time and light answers do not change it. - 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. @@ -167,7 +169,7 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in - Connecting to the database in `MONGODB_URI` and `DB_NAME`, using `iloveplants` when `DB_NAME` is not set, and the error messages when `MONGODB_URI` is missing or empty, is not a MongoDB address, or MongoDB cannot be reached (for example when the SSH tunnel is down). - `server.test.ts` - Starting the server: the default port 3001, the port in `PORT`, and stopping with the error when the port is in use. - - Plants: random plants from `getPlants`, stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, and all sort orders. + - Plants: `getPlants` returns the plants that match the most of the user's preferences first, also when they are fetched in batches ("Low" counts as easy care), random plants when there are no preferences or only unknown ones, and leaves out the plants in `excludeIds` (returning none when all are excluded). Also stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, and all sort orders. - Users: creating and fetching users, updating the profile (trimming text, storing empty text and `null` as `null`, and only changing the sent fields), the plant owner test results as profile pictures, preferences without duplicates, adding and removing matches in order, and skipping matched plants that were deleted. - Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name or description, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and the server passes on a database error and keeps running. @@ -220,7 +222,7 @@ Each file covers one scenario, and API and UI tests for the same feature come in - Liking a plant on PlantMatch adds it to MyMatches, where it can be removed. - Adding a plant from ExplorePlants adds it to MyMatches and disables its ✿ button. -PlantMatch shows random plants, so the test remembers the name of the liked plant and checks that it is the same plant that ends up in MyMatches. +The test user has no preferences, so PlantMatch shows the plants in random order. The test therefore remembers the name of the liked plant and checks that it is the same plant that ends up in MyMatches. **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. diff --git a/frontend/src/hooks/usePlantDeck.ts b/frontend/src/hooks/usePlantDeck.ts index 5560fc09..aa612c07 100644 --- a/frontend/src/hooks/usePlantDeck.ts +++ b/frontend/src/hooks/usePlantDeck.ts @@ -33,7 +33,7 @@ export type GetPlantsData = { getPlants: Plant[]; }; -// A deck of random plants that is loaded in small batches while the user swipes. +// A deck of plants that is loaded in small batches while the user swipes. // Plants already in the deck are excluded by the backend, so a plant is never // shown twice while the page is open. Plants matching the most of the user's // preferences come first. Without preferences the order is random. diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 6d468c2e..f5f6ff8b 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -26,7 +26,7 @@ "loading": "Loading plants...", "error": "Could not load plants. Please try again later.", "noMorePlantsTitle": "Done!", - "noMorePlants": "No more plants to show. Reload to go agian!" + "noMorePlants": "No more plants to show. Reload to go again!" }, "preferences": { "title": "Plant preferences ✿",