diff --git a/README.md b/README.md index 7d248fa5..0e8e4ea7 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 common or scientific 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. The search, filters, sorting, and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. 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/package-lock.json b/backend/package-lock.json index b5a989db..fa82f41f 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1114,7 +1114,6 @@ "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/oxc-project" } @@ -1195,7 +1194,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1213,7 +1211,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1231,7 +1228,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1249,7 +1245,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1267,7 +1262,6 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1285,7 +1279,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1303,7 +1296,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1321,7 +1313,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1339,7 +1330,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1357,7 +1347,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1375,7 +1364,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1393,7 +1381,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1411,7 +1398,6 @@ "os": [ "openharmony" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1429,7 +1415,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1447,7 +1432,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -1457,8 +1441,7 @@ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/chai": { "version": "5.2.3", @@ -1511,6 +1494,7 @@ "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~8.9.0" } @@ -1575,6 +1559,7 @@ "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.72.1", "@typescript-eslint/types": "8.72.1", @@ -1766,6 +1751,7 @@ "integrity": "sha512-4KpkGdIrSqBihx/JyP/e+S+IKB98etg1XDQiLAxksLfcShnwi1VReGeOT9NI43hLHbknosKp/1CCLn9Zgcs8mg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/istanbul-lib-coverage": "^1.0.2", @@ -1868,6 +1854,7 @@ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1999,6 +1986,7 @@ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", "dev": true, "license": "Apache-2.0", + "peer": true, "peerDependencies": { "bare-abort-controller": "*" }, @@ -2346,7 +2334,6 @@ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "dev": true, "license": "Apache-2.0", - "peer": true, "engines": { "node": ">=8" } @@ -2499,6 +2486,7 @@ "integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==", "dev": true, "license": "MIT", + "peer": true, "workspaces": [ "packages/*" ], @@ -2965,6 +2953,7 @@ "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz", "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==", "license": "MIT", + "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -3206,6 +3195,7 @@ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -3230,7 +3220,6 @@ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", - "peer": true, "dependencies": { "detect-libc": "^2.0.3" }, @@ -3268,7 +3257,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3290,7 +3278,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3312,7 +3299,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3334,7 +3320,6 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3356,7 +3341,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3378,7 +3362,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3400,7 +3383,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3422,7 +3404,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3444,7 +3425,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3466,7 +3446,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3488,7 +3467,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -3827,7 +3805,6 @@ } ], "license": "MIT", - "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -4036,8 +4013,7 @@ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/picomatch": { "version": "4.0.7", @@ -4150,7 +4126,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", @@ -4245,7 +4220,6 @@ "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@oxc-project/types": "=0.155.0", "@rolldown/pluginutils": "^1.0.0" @@ -4638,6 +4612,7 @@ "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "~0.28.0" }, @@ -4715,6 +4690,7 @@ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -4867,6 +4843,7 @@ "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.5", diff --git a/backend/src/helpers.ts b/backend/src/helpers.ts index cddb4f09..77c4733d 100644 --- a/backend/src/helpers.ts +++ b/backend/src/helpers.ts @@ -90,3 +90,42 @@ export const buildExploreFilter = ( } return filter; }; + +// 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". +export 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 +export const matchScore = (preferences: string[]): Document => ({ + $add: preferences.map((p) => ({ $cond: [PREFERENCE_MATCHERS[p], 1, 0] })), +}); diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 2a9c06e6..f9d37a85 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -2,7 +2,12 @@ import { GraphQLError } from "graphql"; import { ObjectId } from "mongodb"; import type { Document, WithId } from "mongodb"; import { db } from "./db.js"; -import { buildExploreFilter, buildSortStages } from "./helpers.js"; +import { + buildExploreFilter, + buildSortStages, + matchScore, + PREFERENCE_MATCHERS, +} from "./helpers.js"; import type { ExplorePlantsArgs, GetPlantsArgs, @@ -116,13 +121,38 @@ export 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 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>([ - { - $sample: { - size: args.limit, - }, - }, + { $match: { _id: { $nin: excluded } } }, + ...orderStages, { $project: { commonName: 1, diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 7971be29..5fcc657b 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,7 +1,7 @@ // The GraphQL schema. The resolvers are in resolvers.ts. export const typeDefs = ` type Query{ - getPlants(limit: Int = 50, offset: Int = 0): [Plant] + getPlants(limit: Int = 50, excludeIds: [ID!], preferences: [String!]): [Plant] explorePlants( search: String sunlight: String diff --git a/backend/src/types.ts b/backend/src/types.ts index 4cba72f3..e05cee7f 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -27,7 +27,11 @@ export interface Plant { export 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; + // The user's preferences. Plants matching the most of them come first. + preferences?: string[] | null; } export interface ExplorePlantsArgs { diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index f29d928b..5e61a1ea 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -260,6 +260,80 @@ 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([]); + }); + + 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/docs/architecture.md b/docs/architecture.md index 5bf8baa7..19a0cd5c 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`; `HashRouter` provides the client-side routes, including Explore query parameters after the hash. 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), `useSearchParams` keeps Explore search, filters, sorting and page in the URL, and `useSessionState` stores state in `sessionStorage` for features that still use it. @@ -73,11 +73,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 common or scientific 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 common or scientific 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** @@ -235,7 +235,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 b9703b7d..c83c81c4 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 across common and scientific names 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 across common and scientific names 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/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index b9ed05ea..878d94a2 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -38,7 +38,11 @@ async function setTheme(page: Page, theme: "light" | "dark") { // Each page and an element that shows the page has finished loading const PAGES = [ { name: "PlantMatch", path: "", loaded: ".plant-card-front" }, - { name: "ExplorePlants", path: "#/explorePlants", loaded: ".plant-grid > li" }, + { + name: "ExplorePlants", + path: "#/explorePlants", + loaded: ".plant-grid > li", + }, { name: "MyMatches", path: "#/my-matches", loaded: ".matches-grid" }, { name: "Profile", path: "#/profile", loaded: "main.profile" }, { diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1fc7b788..9ef16e6a 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -148,6 +148,7 @@ "version": "7.29.7", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -457,6 +458,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=20.19.0" }, @@ -501,6 +503,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=20.19.0" } @@ -1112,8 +1115,7 @@ "node_modules/@types/aria-query": { "version": "5.0.4", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/chai": { "version": "5.2.3", @@ -1148,6 +1150,7 @@ "version": "24.13.6", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~7.18.0" } @@ -1156,6 +1159,7 @@ "version": "19.3.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -1164,6 +1168,7 @@ "version": "19.3.0", "dev": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^19.3.0" } @@ -1207,6 +1212,7 @@ "version": "8.70.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/types": "8.70.0", @@ -1419,6 +1425,7 @@ "version": "5.0.5", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/istanbul-lib-coverage": "^1.0.2", @@ -1539,6 +1546,7 @@ "version": "8.18.0", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1573,7 +1581,6 @@ "version": "5.0.1", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -1582,7 +1589,6 @@ "version": "5.2.0", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -1677,6 +1683,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.11.23", "caniuse-lite": "^1.0.30001810", @@ -1838,8 +1845,7 @@ "node_modules/dom-accessibility-api": { "version": "0.5.16", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/electron-to-chromium": { "version": "1.5.433", @@ -1885,6 +1891,7 @@ "version": "10.11.0", "dev": true, "license": "MIT", + "peer": true, "workspaces": [ "packages/*" ], @@ -2176,6 +2183,7 @@ "node_modules/graphql": { "version": "16.14.2", "license": "MIT", + "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -2257,6 +2265,7 @@ } ], "license": "MIT", + "peer": true, "peerDependencies": { "typescript": "^5 || ^6 || ^7" }, @@ -2406,6 +2415,7 @@ "version": "5.6.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -2705,7 +2715,6 @@ "version": "1.5.0", "dev": true, "license": "MIT", - "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -2938,7 +2947,6 @@ "version": "27.5.1", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -2975,6 +2983,7 @@ "node_modules/react": { "version": "19.3.0", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -2982,6 +2991,7 @@ "node_modules/react-dom": { "version": "19.3.0", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.28.0" }, @@ -3026,8 +3036,7 @@ "node_modules/react-is": { "version": "17.0.2", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/react-router": { "version": "7.18.4", @@ -3300,6 +3309,7 @@ "version": "6.0.3", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -3391,6 +3401,7 @@ "version": "8.3.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", @@ -3467,6 +3478,7 @@ "version": "5.0.5", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.5", @@ -3650,6 +3662,7 @@ "version": "4.6.5", "dev": true, "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } 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 new file mode 100644 index 00000000..aa612c07 --- /dev/null +++ b/frontend/src/hooks/usePlantDeck.ts @@ -0,0 +1,119 @@ +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. +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!], $preferences: [String!]) { + getPlants( + limit: $limit + excludeIds: $excludeIds + preferences: $preferences + ) { + id + name + imageURL + scientificName + description + watering + sunlight + careLevel + } + } +`; + +export type GetPlantsData = { + getPlants: Plant[]; +}; + +// 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. +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); + 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()); + + // 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; + setLoading(true); + try { + const { data, error: queryError } = await client.query({ + query: GET_PLANTS, + variables: { + limit: PLANT_BATCH_SIZE, + excludeIds: [...seenIds.current], + preferences: preferences.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. + // Waits for the user, so the first batch is already sorted by preferences. + useEffect(() => { + if ( + !userLoading && + hasMore && + plants.length - index <= PREFETCH_THRESHOLD + ) { + void loadMore(); + } + }, [index, plants.length, hasMore, loadMore, userLoading]); + + 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 || userLoading) && !plant, + error: plant ? undefined : error, + noMorePlants: !plant && !hasMore && !loading, + } as const; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 20328f68..4d6388c8 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 ✿", 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..55346d0f 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,95 @@ 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: [], + preferences: [], + }); + + // 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(); + }); + + 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(); + }); }); diff --git a/package-lock.json b/package-lock.json index 1a9f7802..27f9eaa3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -161,6 +161,7 @@ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", "dev": true, "license": "Apache-2.0", + "peer": true, "peerDependencies": { "bare-abort-controller": "*" }, @@ -813,6 +814,7 @@ "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "playwright-core": "cli.js" },