diff --git a/backend/src/queryBuilders.ts b/backend/src/queryBuilders.ts index ced5792b..e0e23a90 100644 --- a/backend/src/queryBuilders.ts +++ b/backend/src/queryBuilders.ts @@ -14,6 +14,14 @@ 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()); +// 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"], +}; + // Sorted by name A–Z, with _id as a tie-breaker so the order is stable. // Uses the index from indexes.ts. const BY_NAME = { commonName: 1, _id: 1 } as const; @@ -149,15 +157,6 @@ export const buildPlantFilter = (args: PlantFilterArgs): Filter => { return filter; }; -// The values each filter can have, from low to high, so the watering and -// care level sort orders use them too. 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}`; @@ -223,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/backend/src/resolvers.ts b/backend/src/resolvers.ts deleted file mode 100644 index 7b57f65c..00000000 --- a/backend/src/resolvers.ts +++ /dev/null @@ -1,361 +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, - PaginationArgs, - 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", - "snakePlant", - "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 & PaginationArgs, - 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..3b745731 --- /dev/null +++ b/backend/src/resolvers/plants.ts @@ -0,0 +1,139 @@ +import type { Document, Filter, WithId } from "mongodb"; +import { + buildPlantFilter, + buildFilterCountStages, + buildSortStages, + knownPreferences, + matchScore, + toFilterCounts, +} from "../queryBuilders.js"; +import type { + ExplorePlantsArgs, + GetPlantsArgs, + PaginationArgs, + Plant, + PlantDoc, + PlantFilterArgs, + PlantPage, +} from "../types.js"; +import { DEFAULT_PAGE_SIZE, MAX_LIMIT } from "../schema.js"; +import { plants, toObjectId } from "./helpers.js"; + +// 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 & PaginationArgs, + 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..c43a561f --- /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 AVATAR_IDS and PLANT_OWNER_TYPES in +// frontend/src/types/ProfilePicture.ts +const PROFILE_PICTURES = [ + "default", + "monstera", + "pothos", + "snakePlant", + "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 c2f0f33e..458580c9 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -1,7 +1,13 @@ -// The GraphQL schema. The resolvers are in resolvers.ts. +// 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/backend/src/server.ts b/backend/src/server.ts index fe5bca79..8d66699e 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 6a5c8bee..b81a5c47 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. @@ -44,7 +44,7 @@ export interface PlantFilterArgs { } // The sort order and page, on Explore Plants and My Matches. -// 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 export interface PaginationArgs { sort?: string; limit?: number | null; diff --git a/docs/architecture.md b/docs/architecture.md index dac4e104..351608f1 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. - **Swiping on Plant Match:** `PlantMatchPage` wraps the card in an element that follows the pointer (mouse, finger or pen) with Pointer Events. Dragging the card more than 100 px to the right matches the plant, and to the left skips it. A shorter drag springs back, a movement of less than 8 px counts as a tap and flips the card as before, and a movement that is mostly up or down is left to the browser, so the page can still be scrolled. The ♥ and ✖ buttons do the same as a swipe. The card then flies off to that side for 300 ms before the next card is shown. The match is saved at once, before the animation, so it is not lost if the user leaves the page while the card is moving. When the user prefers reduced motion, the next card is shown at once. - **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 (✖), `HeartIcon` is the SVG heart used on the match buttons and on Plant Match, `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. @@ -60,14 +60,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 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 saves the saved preferences plus the chosen suggestions with `usePreferences`, 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 the same order as the pages in the sidebar. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page. - **`App.tsx` decides when it is open:** The walkthrough opens by itself when `walkthroughSeen` is not in `localStorage`, and the key is set when it is closed, so it is only shown once. The ? button in the `Header` opens it again at the step for the current page (`stepForPath`). When it closes, focus goes back to the ? button, except when the "Go to" link has moved the user to another page, where focus moves to the start of the new page like for any other navigation. - **`Walkthrough.tsx` shows one step at a time:** It uses the native `` element with `showModal()`, so the browser grays out the page behind, keeps keyboard focus inside the dialog and closes it with Escape. It can also be closed with ×, Finish or a click outside the box. The user moves between steps with Back and Next or the arrow keys, and steps about a page have a "Go to" link that opens the page and closes the walkthrough. The `LanguageSwitcher` from the sidebar is reused at the bottom of the dialog, so the language can be changed without leaving the walkthrough. This matters on mobile, where the sidebar is hidden behind the menu button. The text of all steps is placed in the same CSS grid cell, and only the current step is visible (the others have `visibility: hidden`, `aria-hidden` and `inert`), so the box always has the height of the longest step and does not change size between steps. -- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. `plantPreferenceIds()` in the same file uses the same keys to find which preference ids a plant matches, which the preference chips on the plant cards use. The preference ids on the profile page are a plain list, and their texts are found in the translation files under `preferences.`. -- **Shared types:** `Plant` and `User` are defined in `types/`. +- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). The watering, sunlight and care values on the plant cards come from Perenual in English, so `plantTraits.ts` maps each known value to a translation key. Values it does not know are shown as they are, and the plant names and descriptions stay in English. `getPlantPreferences()` in the same file uses the same keys to find which preferences a plant matches, which the preference chips on the plant cards use. +- **Shared types:** `Plant` and `User` are defined in `types/`, together with the ids that are also checked in the backend: the preferences (`Preference.ts`) and the profile pictures (`ProfilePicture.ts`). ### Communication with the backend @@ -94,7 +94,7 @@ Each file also exports the TypeScript type for the result of its operations (for The operations used to be spread across the context, a page and a hook, and we moved them into one folder after feedback, and because one of our main goals is that the app should scale: - **One place to look.** All requests the frontend can send are in one folder, so it is easy to compare them with the backend schema and to see what a schema change affects. -- **The user operations are shared.** They are used by `UserProvider`, two hooks and a component, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. +- **The user operations are shared.** They are used by `UserProvider`, three hooks and My Matches, so they do not belong to any one of them. Keeping them in `context/` made it look like they were part of the context. - **One rule for new features.** A new domain (for example comments) gets its own folder, such as `graphql/comments/`, instead of each developer deciding where its queries should go. - **Shared fragments.** The plant fields used to be written out three times (in `getPlants`, `explorePlants` and `myMatches`). They are now defined once in `PlantFields`, so a new plant field only has to be added in one place, and every plant in the Apollo cache has the same fields. - **Ready for code generation.** Because all operations are in one folder, a tool like GraphQL Code Generator could later generate the result types from the backend schema (`documents: "src/graphql/**/*.ts"`) instead of us writing them by hand. @@ -112,8 +112,8 @@ 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. -- `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. +- `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. - `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#design-choices-made-for-scalability)). - `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments. - `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below). @@ -142,7 +142,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). @@ -204,7 +204,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 was `snake-plant` before, and `migrations.ts` renames it to `snakePlant` on existing users when the server starts. +A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids in `resolvers/users.ts` must match the ids in `frontend/src/types/`, which the API tests check. The avatar id was `snake-plant` before, and `migrations.ts` renames it to `snakePlant` on existing users when the server starts. 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. @@ -237,7 +237,7 @@ When the app starts, `UserProvider` reads `userId` from `localStorage` and runs ## Design choices made for scalability -- **Use of MongoDB over browser storage.** All user data (profile, preferences and matches) is stored in MongoDB. The browser only keeps small values that do not need the server: `localStorage` holds the `userId`, the chosen theme and language and whether the walkthrough has been seen, and `sessionStorage` holds the sort order on My Matches and the cards left on Plant Match (see [Where state is kept](#where-state-is-kept)). Browser storage is limited to about 5 MB per site and only exists in that one browser, where the server cannot use it. By storing user data in MongoDB, there is no practical limit to how many plants a user can save, more user information can easily be added later, and the data can be used by the backend. +- **Use of MongoDB over browser storage.** All user data (profile, preferences and matches) is stored in MongoDB. The browser only keeps small values that do not need the server: `localStorage` holds the `userId`, the chosen theme and language and whether the walkthrough has been seen, and `sessionStorage` holds the search, filters and sort order on My Matches and the cards left on Plant Match (see [Where state is kept](#where-state-is-kept)). Browser storage is limited to about 5 MB per site and only exists in that one browser, where the server cannot use it. By storing user data in MongoDB, there is no practical limit to how many plants a user can save, more user information can easily be added later, and the data can be used by the backend. - **Plant data does not depend on Perenual.** The number of users does not affect the number of requests to Perenual, since the app only reads from our own database. It also makes it possible to fetch more plants later if one wants to. - **The server does the heavy work.** Searching, filtering, sorting and pagination run as MongoDB queries, so the frontend only receives one page of plants at a time (12 by default) together with the total count. This works the same whether the collection has a hundred or many thousand plants, and keeps responses small so pages load faster. - **Index for sorting by name.** Sorting by name (A–Z, the default, and Z–A) uses an index on `commonName` and `_id`, created by `indexes.ts` when the server starts. The plants are then read in order from the index instead of being sorted in memory, which matters more the larger the collection gets. Lookups by id (users, matches and plants) already use the `_id` index that MongoDB creates on every collection. @@ -290,7 +290,8 @@ 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 +│ │ ├── migrations.ts # Updates old data when the server starts +│ │ ├── 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 @@ -312,7 +313,7 @@ T03-Project-2/ │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file (walkthrough/ has the guide and its steps) │ │ ├── context/ # UserProvider and useUser() for the current user, ErrorMessageProvider and useErrorMessage() for error messages │ │ ├── graphql/ # All GraphQL queries, mutations and fragments, grouped by domain (fragments/, plants/, user/) -│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useMyMatchesParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck, useDismissibleTooltip) +│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useMyMatchesParams, useSessionState, useProfile, usePreferences, useMatchedPlants, useNewMatches, usePlantDeck, useDismissibleTooltip) │ │ ├── i18n/ # Translation setup and locale files (no, en) │ │ ├── pages/ # One folder per page/route, each with a Page.tsx and a matching .css file │ │ │ ├── explorePlants/ # ExplorePlantsPage @@ -322,7 +323,7 @@ T03-Project-2/ │ │ │ ├── plantOwnerTest/ # PlantOwnerTestPage, SuggestedPreferences, and plantOwnerTest.ts with the questions, results and suggestions │ │ │ └── profile/ # ProfilePage │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) -│ │ ├── types/ # Shared TypeScript types (Plant, User) +│ │ ├── types/ # Shared TypeScript types and ids (Plant, User, Preference, ProfilePicture) │ │ ├── AppRoutes.tsx # Route definitions │ │ └── main.tsx # Application entry point (Apollo Client, UserProvider, router) │ ├── .env.production # GraphQL URL for the deployed app diff --git a/docs/quality.md b/docs/quality.md index 123e1cf6..e7e8a884 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -91,7 +91,7 @@ We considered sustainability through both our design choices and our approach to - **Inline SVG icons without an icon library:** The application only needs a few icons (search, sort, the heart on the match buttons, and the sun and moon on the theme button), so we draw them ourselves as small inline SVG components instead of installing an icon library such as `react-icons`. This keeps the project to one fewer dependency that has to be downloaded, installed and kept up to date, and the icons are part of the JavaScript the page already loads, so they need no extra requests or icon font. SVGs are also vector graphics, so they stay sharp at any size and zoom level without image files in several resolutions. -- **Debouncing:** On the Explore Plants page, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost. +- **Debouncing:** On Explore Plants and My Matches, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost. - **Filter counts in one query:** The number of plants for every filter value on Explore Plants is counted in the same request as the results, in one database query, instead of one request per value. Values that would give no plants can't be chosen, so the user does not send requests that only return an empty list. @@ -109,7 +109,7 @@ We considered sustainability through both our design choices and our approach to - **Color palette and contrast:** We used a limited color palette to maintain a consistent visual identity across the application. We also checked the contrast between our chosen colors to help ensure that text and other interface elements remain distinguishable and in line with accessibility requirements. See [Accessibility](#accessibility). -- **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `PlantSearchForm` (search, filters, sort menu and reset), `Pagination` and `MatchButton` are shared by Explore Plants and My Matches, so the two pages look and work the same, and `ErrorMessage` shows error messages on every page. The filters are defined in one list (`plantFilters.ts`), so a new filter only needs one new line in the frontend. +- **Reusable components:** Shared UI is kept in reusable components, so the pages look and work the same way and changes only need to be made in one place. This makes the application easier to maintain. The Header, Sidebar and plant cards are used across pages, `PlantSearchForm` (search, filters, sort menu and reset), `Pagination` and `MatchButton` are shared by Explore Plants and My Matches, so the two pages look and work the same, and `ErrorMessage` shows error messages on every page. The filters are defined in one list (`plantFilters.ts`), which the search form, the URL, `sessionStorage` and the query variables all use. A new filter also needs a variable in the GraphQL queries, its texts in the translation files, and support in the backend. - **Keeping the previous results while loading:** On Explore Plants, the previous results and the number of results stay on screen, slightly dimmed, while new ones load (with Apollo's `previousData`). The page does not flicker or jump when the search, a filter or the page changes, and the loading text is only shown the first time. diff --git a/docs/tests.md b/docs/tests.md index aa357c91..a15322f1 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -104,7 +104,7 @@ To watch an e2e test, open UI mode, run a test, and expand it to choose the desk Test coverage for the backend -The frontend coverage counts every source file in `frontend/src`, not only the files a test happens to import, so files without tests are shown with 0 % instead of being left out. Only the test files themselves, type declarations (`.d.ts`) and `main.tsx`, which only starts the app, are left out. Files that only contain TypeScript types (`types.ts` in the backend and the files in `types/` in the frontend) are also shown with 0 %, since types are removed when the code is compiled, so there is no code to run. +The frontend coverage counts every source file in `frontend/src`, not only the files a test happens to import, so files without tests are shown with 0 % instead of being left out. Only the test files themselves, type declarations (`.d.ts`) and `main.tsx`, which only starts the app, are left out. Files that only contain TypeScript types (`types.ts` in the backend, and `Plant.ts` and `User.ts` in `types/` in the frontend) are also shown with 0 %, since types are removed when the code is compiled, so there is no code to run. The coverage only counts the Vitest tests. Code that is only run by the end-to-end tests is shown as not covered, even when it is tested there. @@ -141,7 +141,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - `LanguageSwitcher.test.tsx` - The button text and accessible name in both languages, that clicking switches to the other language, and snapshots for both languages. - `MyMatchesPage.test.tsx` - - Loading and empty state: a message when there are no matches (without the count, sorting or pages), and the loading state while the user or the matches are fetched. + - Loading and empty state: a message when there are no matches (without the count, sorting or pages), the loading state while the user or the matches are fetched, and an error message when the matches cannot be fetched. - Fetching: the first page with the newest first by default, fetched again each time the page is opened, the sort order saved earlier in the session used while the page starts at 1, and saved matches shown and removed. - Sorting and pages: the number of matches next to the sort menu in an `aria-live` region that stays on the page, so "no matches" is also announced, moving between pages, a new sort order saved in `sessionStorage` and going back to page 1, and going to the last page when the current page no longer exists. - Search and filters: a chosen filter is sent, saved in `sessionStorage` and goes back to page 1, the search is sent after the debounce delay, search and filters saved earlier in the session are restored, the number of matches for each filter value with empty values disabled, a message in an `aria-live` region under the filters when no matches fit, like on Explore Plants (with the search and filters still on screen), a separate count when the list is filtered, and reset clearing the search, the filters and the sort order. The search and filters are hidden when the user has no matches at all. @@ -160,12 +160,14 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co - Going on is only possible with an answer, an earlier answer is shown when going back, the result is shown with its picture, the result can be saved as profile picture, an error is shown when saving fails, the page says so when the result already is the profile picture, and the test can be taken again with no answers. - Suggested preferences: all are chosen from the start, those already saved are not suggested again, the chosen ones are added to the saved preferences, nothing is saved before the user clicks the add button (which is disabled when nothing is chosen), the page says so when all suggestions already are preferences, an error is shown when saving fails or the user is not found, and saving can be tried again. - `PlantPreferences.test.tsx` - - Saved preferences are marked, also with `aria-pressed` for screen readers, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists. + - A button for every preference, in order, saved preferences are marked, also with `aria-pressed` for screen readers, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists. - `ProfilePage.test.tsx` - The name, the image alt text and a screen reader prefix for the description, the preferences tab open by default (`aria-pressed`), the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, and that a picture from the plant owner test is shown but not offered in the chooser. - Saving the profile text at once when a field loses focus, when the user leaves the page and when the tab is reloaded or closed, without saving the same text twice. - `Sidebar.test.tsx` - The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, that only the current page is marked as active, that focus moves to the close button when it opens, and that Escape closes it. +- `SidebarNewMatches.test.tsx` + - The badge on My Matches counts only matches made while the app is open, not a match that is removed again, and counts a match the user already had as new if it is removed and added again. It is cleared when My Matches is opened. - `ThemeToggle.test.tsx` - Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked. - `translationKeys.test.tsx` @@ -273,6 +275,8 @@ Saving preferences is already covered by `apiUserProfile`, and how preferences d **Profile (`uiUserProfile`):** changing name, description and avatar is shown at once and is still there after a reload, so the changes are stored in the database. +The frontend and backend have their own lists of preference and profile picture ids. `apiUserProfile` sends every id from `frontend/src/types/` to the backend and checks that all are accepted, so the test fails if an id is added in the frontend but not in the backend. + Saving the profile is debounced by 500 ms, and the text is also saved at once when a field loses focus. The test waits until the save request has reached the backend before reloading, instead of waiting a fixed time, so it does not depend on the length of the debounce. **Pictures (`uiImages`):** checks that every picture in the app is actually downloaded and decoded by the browser: the default profile picture, the seven avatars, the six pictures from the plant owner test and the placeholder on plant cards without an image. The component tests run in jsdom, which never loads images, so they only check the `src` attribute and would still pass if a file was missing or broken. An image counts as loaded when it has a natural width larger than 0. diff --git a/e2e/apiUserProfile.spec.ts b/e2e/apiUserProfile.spec.ts index 9fc67922..69a7247a 100644 --- a/e2e/apiUserProfile.spec.ts +++ b/e2e/apiUserProfile.spec.ts @@ -1,9 +1,13 @@ import { test, expect } from "@playwright/test"; import { graphql, createUser, CREATE_USER, GET_USER } from "./helpers/graphql"; +import { PREFERENCE_IDS } from "../frontend/src/types/Preference"; +import { + AVATAR_IDS, + PLANT_OWNER_TYPES, +} from "../frontend/src/types/ProfilePicture"; // Tests the user profile in the API: a new user's defaults, name, description, // avatar and preferences, and that invalid values are rejected. - const UPDATE_PROFILE = ` mutation UpdateProfile( $userId: ID! @@ -86,6 +90,37 @@ 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, + ); + }); + + // The same for the profile pictures: every avatar and every test result + test("accepts every profile picture the frontend has", async ({ + request, + }) => { + const userId = await createUser(request); + + for (const profilePicture of [...AVATAR_IDS, ...PLANT_OWNER_TYPES]) { + const result = await graphql(request, UPDATE_PROFILE, { + userId, + profilePicture, + }); + expect(result.errors).toBeUndefined(); + expect(result.data.updateUserProfile.profilePicture).toBe(profilePicture); + } + }); + test("only the fields that are sent are changed", async ({ request }) => { const userId = await createUser(request); diff --git a/frontend/index.html b/frontend/index.html index 387cdd7a..4378d1f9 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,6 +2,7 @@ + I <3 plants (null); @@ -159,5 +159,3 @@ function App() { ); } - -export default App; diff --git a/frontend/src/AppRoutes.tsx b/frontend/src/AppRoutes.tsx index 944052a3..b995da8a 100644 --- a/frontend/src/AppRoutes.tsx +++ b/frontend/src/AppRoutes.tsx @@ -22,7 +22,7 @@ export const ROUTES = { notFound: "*", } as const; -function AppRoutes() { +export default function AppRoutes() { return ( @@ -36,5 +36,3 @@ function AppRoutes() { ); } - -export default AppRoutes; diff --git a/frontend/src/components/header/Header.tsx b/frontend/src/components/header/Header.tsx index f1378271..35a37537 100644 --- a/frontend/src/components/header/Header.tsx +++ b/frontend/src/components/header/Header.tsx @@ -1,8 +1,8 @@ -import "./Header.css"; import type { Ref } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; import { ROUTES } from "../../AppRoutes"; +import "./Header.css"; type HeaderProps = { isSidebarOpen: boolean; diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index 9f7cf969..99c170cb 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -1,10 +1,10 @@ import { useEffect, useRef, useState } from "react"; import type { KeyboardEvent } from "react"; import { useTranslation } from "react-i18next"; -import "./PlantCard.css"; import PlantPreferenceChips from "../plantPreferenceChips/PlantPreferenceChips"; import type { Plant } from "../../types/Plant"; import { traitLabel } from "./plantTraits"; +import "./PlantCard.css"; type PlantCardData = Omit; diff --git a/frontend/src/components/plantCard/plantTraits.ts b/frontend/src/components/plantCard/plantTraits.ts index 852e08e4..707c9462 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"; + // 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 = { 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. @@ -39,51 +46,48 @@ export function traitLabel( return key ? t(`plantCard.values.${trait}.${key}`) : value; } -// 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 preference for each watering and care key in TRAIT_KEYS +const WATERING_PREFERENCES: Record = { + minimum: "minimumWater", + average: "averageWater", + frequent: "frequentWater", +}; -// The preference id each trait key matches. "Part sun/part shade" matches the -// part shade preference. -const PREFERENCE_IDS: Record> = { - watering: { - minimum: "minimumWater", - average: "averageWater", - frequent: "frequentWater", - }, - sunlight: { - fullSun: "fullSun", - partShade: "partShade", - filteredShade: "filteredShade", - partSunPartShade: "partShade", - }, - careLevel: { - low: "easyCare", - medium: "mediumCare", - high: "hardCare", - }, +const CARE_PREFERENCES: Record = { + low: "easyCare", + medium: "mediumCare", + high: "hardCare", }; -// The preference ids a plant matches, in the order watering, sunlight, care -// level, without duplicates and with at most two per trait, so the chips fit -// on the card. Values that are not known are left out. -export function plantPreferenceIds(plant: { - watering?: string | null; - sunlight?: string[] | null; - careLevel?: string | null; -}): string[] { - const values: Record = { - watering: [plant.watering], - sunlight: plant.sunlight ?? [], - careLevel: [plant.careLevel], - }; - return (Object.keys(values) as Trait[]).flatMap((trait) => { - const ids = values[trait].flatMap((value) => { - const key = value ? traitKey(trait, value) : undefined; - return key ? [PREFERENCE_IDS[trait][key]] : []; - }); - return [...new Set(ids)].slice(0, 2); - }); +// 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 54ce3fb4..14a3c76c 100644 --- a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx +++ b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx @@ -1,6 +1,6 @@ import { useTranslation } from "react-i18next"; import { useUser } from "../../context/UserContext"; -import { plantPreferenceIds } from "../plantCard/plantTraits"; +import { getPlantPreferences } from "../plantCard/plantTraits"; import "./PlantPreferenceChips.css"; type PlantPreferenceChipsProps = { @@ -19,13 +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 ?? []; - // Which preferences the plant matches. The same rules as - // PREFERENCE_MATCHERS in backend/src/queryBuilders.ts - const plantPreferences = plantPreferenceIds({ - watering, - sunlight, - careLevel, - }); + 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 f0001965..7436da3e 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.tsx +++ b/frontend/src/components/plantPreferences/PlantPreferences.tsx @@ -1,33 +1,17 @@ -import { useMutation } from "@apollo/client/react"; import { useTranslation } from "react-i18next"; -import { useUser } from "../../context/UserContext"; -import { - UPDATE_USER_PREFERENCES, - type UpdateUserPreferencesData, -} from "../../graphql/user/mutations"; +import { usePreferences } from "../../hooks/usePreferences"; +import { PREFERENCE_IDS } from "../../types/Preference"; import "./PlantPreferences.css"; -type PlantPreferencesProps = { - // Preference ids. The text for each is in translation.json under preferences. - preferences: string[]; -}; - // Display plant preferences -export default function PlantPreferences({ - preferences, -}: PlantPreferencesProps) { +export default function PlantPreferences() { const { t } = useTranslation(); // Saved preferences come from the database through UserContext - const { userId, user } = useUser(); - const selected = user?.preferences ?? []; - - const [updatePreferences] = useMutation( - UPDATE_USER_PREFERENCES, - ); + const { preferences: selected, canSave, savePreferences } = usePreferences(); function handleClick(id: string) { - if (!userId) return; + if (!canSave) return; let updatedPreferences: string[]; @@ -37,26 +21,13 @@ export default function PlantPreferences({ updatedPreferences = [...selected, id]; } - // Save to the database. The optimistic response updates the cache right away, - // so the buttons and the plant cards change without waiting for the server. - updatePreferences({ - variables: { userId, preferences: updatedPreferences }, - optimisticResponse: { - updateUserPreferences: { - __typename: "User", - id: userId, - preferences: updatedPreferences, - }, - }, - }).catch(() => { - // Apollo rolls the buttons back if the server fails - }); + savePreferences(updatedPreferences); } // Button for each preference return (
- {preferences.map((id) => ( + {PREFERENCE_IDS.map((id) => ( ); } - -export default LanguageSwitcher; 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/hooks/useExploreParams.ts b/frontend/src/hooks/useExploreParams.ts index ff9c6e87..683f0a9f 100644 --- a/frontend/src/hooks/useExploreParams.ts +++ b/frontend/src/hooks/useExploreParams.ts @@ -1,5 +1,8 @@ import { useUrlParams } from "./useUrlParams"; -import type { FilterParam } from "../components/plantSearchForm/plantFilters"; +import { + mapFilters, + type FilterParam, +} from "../components/plantSearchForm/plantFilters"; const DEFAULT_SORT = "name_asc"; @@ -11,11 +14,7 @@ export function useExploreParams() { return { search: get("search"), - filters: { - watering: get("watering"), - sunlight: get("sunlight"), - careLevel: get("careLevel"), - }, + filters: mapFilters(get), sort: get("sort") || DEFAULT_SORT, page, @@ -29,9 +28,7 @@ export function useExploreParams() { reset: () => update({ search: null, - watering: null, - sunlight: null, - careLevel: null, + ...mapFilters(() => null), sort: null, page: null, }), diff --git a/frontend/src/hooks/useMyMatchesParams.ts b/frontend/src/hooks/useMyMatchesParams.ts index c6f57f1f..add87dd9 100644 --- a/frontend/src/hooks/useMyMatchesParams.ts +++ b/frontend/src/hooks/useMyMatchesParams.ts @@ -1,8 +1,9 @@ -import { useState } from "react"; -import { useSessionState } from "./useSessionState"; -import type { - FilterParam, - PlantFilters, +import { useEffect, useState } from "react"; +import { readSession, useSessionState, writeSession } from "./useSessionState"; +import { + mapFilters, + type FilterParam, + type PlantFilters, } from "../components/plantSearchForm/plantFilters"; const DEFAULT_SORT = "newest"; @@ -15,18 +16,18 @@ const DEFAULT_SORT = "newest"; // matches, which come first with the newest first, are seen right away. export function useMyMatchesParams() { const [search, setSearchState] = useSessionState("myMatches.search"); - const [watering, setWatering] = useSessionState("myMatches.watering"); - const [sunlight, setSunlight] = useSessionState("myMatches.sunlight"); - const [careLevel, setCareLevel] = useSessionState("myMatches.careLevel"); const [sort, setSortState] = useSessionState("myMatches.sort", DEFAULT_SORT); const [page, setPage] = useState(1); - const filters: PlantFilters = { watering, sunlight, careLevel }; - const setters: Record void> = { - watering: setWatering, - sunlight: setSunlight, - careLevel: setCareLevel, - }; + // Each filter has its own key, for example "myMatches.watering" + const [filters, setFilters] = useState(() => + mapFilters((param) => readSession(`myMatches.${param}`)), + ); + useEffect(() => { + for (const [param, value] of Object.entries(filters)) { + writeSession(`myMatches.${param}`, value); + } + }, [filters]); return { search, @@ -40,7 +41,7 @@ export function useMyMatchesParams() { setPage(1); }, setFilter: (param: FilterParam, value: string) => { - setters[param](value); + setFilters((previous) => ({ ...previous, [param]: value })); setPage(1); }, setSort: (value: string) => { @@ -50,9 +51,7 @@ export function useMyMatchesParams() { setPage, reset: () => { setSearchState(""); - setWatering(""); - setSunlight(""); - setCareLevel(""); + setFilters(mapFilters(() => "")); setSortState(DEFAULT_SORT); setPage(1); }, diff --git a/frontend/src/hooks/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/hooks/usePreferences.ts b/frontend/src/hooks/usePreferences.ts new file mode 100644 index 00000000..a1172241 --- /dev/null +++ b/frontend/src/hooks/usePreferences.ts @@ -0,0 +1,44 @@ +import { useMutation } from "@apollo/client/react"; +import { useUser } from "../context/UserContext"; +import { + UPDATE_USER_PREFERENCES, + type UpdateUserPreferencesData, +} from "../graphql/user/mutations"; + +// The user's saved preferences, and saving new ones. Used by the buttons on +// the profile page and the suggestions after the plant owner test. +export function usePreferences() { + const { userId, user } = useUser(); + const preferences = user?.preferences ?? []; + + const [updatePreferences] = useMutation( + UPDATE_USER_PREFERENCES, + ); + + // Saves the whole list. The optimistic response updates the cache right + // away, so the buttons and the plant cards change without waiting for the + // server, and Apollo rolls them back if the server fails. + // Returns whether the preferences were saved. + async function savePreferences(next: string[]): Promise { + if (!userId) return false; + try { + const result = await updatePreferences({ + variables: { userId, preferences: next }, + optimisticResponse: { + updateUserPreferences: { + __typename: "User", + id: userId, + preferences: next, + }, + }, + }); + // null means the user was not found in the database + return Boolean(result.data?.updateUserPreferences); + } catch { + return false; + } + } + + // The preferences can only be saved once the user exists + return { preferences, canSave: Boolean(userId), savePreferences }; +} diff --git a/frontend/src/hooks/useSessionState.ts b/frontend/src/hooks/useSessionState.ts index 41a8013e..e66a86ef 100644 --- a/frontend/src/hooks/useSessionState.ts +++ b/frontend/src/hooks/useSessionState.ts @@ -1,21 +1,28 @@ import { useEffect, useState } from "react"; +export function readSession(key: string, initialValue = "") { + try { + return sessionStorage.getItem(key) ?? initialValue; + } catch { + return initialValue; + } +} + +export function writeSession(key: string, value: string) { + try { + sessionStorage.setItem(key, value); + } catch { + // Storage can fail (private mode, full quota). The app still works, + // the value just won't be remembered. + } +} + +// A string state that is also kept in sessionStorage export function useSessionState(key: string, initialValue = "") { - const [value, setValue] = useState(() => { - try { - return sessionStorage.getItem(key) ?? initialValue; - } catch { - return initialValue; - } - }); + const [value, setValue] = useState(() => readSession(key, initialValue)); useEffect(() => { - try { - sessionStorage.setItem(key, value); - } catch { - // Storage can fail (private mode, full quota). The app still works, - // the value just won't be remembered. - } + writeSession(key, value); }, [key, value]); return [value, setValue] as const; diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 05057acb..34d95c78 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -87,6 +87,7 @@ }, "myMatchesPage": { "loading": "Loading your matches...", + "error": "Could not load your matches. Please try again later.", "noMatches": "You have no matches yet. Press the heart on the match page to match with a plant.", "removeMatch": "Remove from My Matches", "matchCount_one": "You have {{count}} match", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index 3a36b2f9..08aae760 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -87,6 +87,7 @@ }, "myMatchesPage": { "loading": "Laster matchene dine...", + "error": "Kunne ikke hente matchene dine. Prøv igjen senere.", "noMatches": "Du har ingen matcher ennå. Trykk på hjertet på match-siden for å matche med en plante.", "removeMatch": "Fjern fra Mine Matches", "matchCount_one": "Du har {{count}} match", diff --git a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx index 793158d2..d6efcc11 100644 --- a/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlantsPage.tsx @@ -4,24 +4,24 @@ import { useDebounce } from "../../hooks/useDebounce"; import { useExploreParams } from "../../hooks/useExploreParams"; import { EXPLORE_PLANTS, + PAGE_SIZE, type ExplorePlantsData, } from "../../graphql/plants/queries"; import PlantCard from "../../components/plantCard/PlantCard"; import Pagination from "../../components/pagination/Pagination"; import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm"; +import { + filterVariables, + PREFERENCES_SORT, + SEARCH_DEBOUNCE_MS, +} from "../../components/plantSearchForm/plantFilters"; import MatchButton from "../../components/matchButton/MatchButton"; import { useMatchedPlants } from "../../hooks/useMatchedPlants"; import { useUser } from "../../context/UserContext"; import "./ExplorePlantsPage.css"; -const 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 -// the user has chosen preferences, since it would be the same as A–Z otherwise. -const PREFERENCES_SORT = "preferences"; - export default function ExplorePlantsPage() { const { t } = useTranslation(); @@ -37,7 +37,7 @@ export default function ExplorePlantsPage() { setPage, reset, } = useExploreParams(); - const debouncedSearch = useDebounce(search, 300); + const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS); // The user's saved preferences, for sorting by the best match. Explore has // no user of its own in the backend, so they are sent with the query. @@ -60,9 +60,7 @@ export default function ExplorePlantsPage() { } = useQuery(EXPLORE_PLANTS, { variables: { search: debouncedSearch || null, - watering: filters.watering || null, - sunlight: filters.sunlight || null, - careLevel: filters.careLevel || null, + ...filterVariables(filters), sort: activeSort, preferences: activeSort === PREFERENCES_SORT ? preferences : null, limit: PAGE_SIZE, diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index 24232985..7da4b68d 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -2,25 +2,25 @@ import { useState } from "react"; import { useTranslation } from "react-i18next"; import { useQuery } from "@apollo/client/react"; import MatchButton from "../../components/matchButton/MatchButton"; -import "./MyMatchesPage.css"; import PlantCard from "../../components/plantCard/PlantCard"; import Pagination from "../../components/pagination/Pagination"; import PlantSearchForm from "../../components/plantSearchForm/PlantSearchForm"; +import { + filterVariables, + PREFERENCES_SORT, + SEARCH_DEBOUNCE_MS, +} from "../../components/plantSearchForm/plantFilters"; import { useMatchedPlants } from "../../hooks/useMatchedPlants"; import { useMyMatchesParams } from "../../hooks/useMyMatchesParams"; import { useDebounce } from "../../hooks/useDebounce"; import { useUser } from "../../context/UserContext"; import { MY_MATCHES, type MyMatchesData } from "../../graphql/user/queries"; - -const PAGE_SIZE = 12; +import { PAGE_SIZE } from "../../graphql/plants/queries"; +import "./MyMatchesPage.css"; const SORT_OPTIONS = ["newest", "oldest", "name_asc", "name_desc"]; -// Matches with the most of the user's preferences first. Only offered when the -// user has chosen preferences. The backend reads them from the user. -const PREFERENCES_SORT = "preferences"; - -function MyMatchesPage() { +export default function MyMatchesPage() { const { t } = useTranslation(); const { userId, user, loading: userLoading } = useUser(); const hasPreferences = (user?.preferences ?? []).length > 0; @@ -39,7 +39,7 @@ function MyMatchesPage() { setPage, reset, } = useMyMatchesParams(); - const debouncedSearch = useDebounce(search, 300); + const debouncedSearch = useDebounce(search, SEARCH_DEBOUNCE_MS); // A saved sort by preferences when the user no longer has any falls back // to the default order, newest first const activeSort = @@ -49,13 +49,14 @@ function MyMatchesPage() { data: currentData, previousData, loading: matchesLoading, + error, } = useQuery(MY_MATCHES, { variables: { userId, search: debouncedSearch || null, - watering: filters.watering || null, - sunlight: filters.sunlight || null, - careLevel: filters.careLevel || null, + ...filterVariables(filters), + // Sorting by preferences uses the preferences saved on the user, which + // the backend reads itself sort: activeSort, limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE, @@ -68,8 +69,9 @@ function MyMatchesPage() { // While new results load, the previous ones stay on screen, like on // Explore Plants, so the page does not flicker when the search, a filter - // or the page changes - const data = currentData ?? previousData; + // or the page changes. If the matches could not be fetched, nothing is + // shown, so the page does not say that the user has no matches. + const data = error ? undefined : (currentData ?? previousData); const plants = data?.myMatches.plants ?? []; const totalCount = data?.myMatches.totalCount ?? 0; const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE)); @@ -101,15 +103,17 @@ function MyMatchesPage() { // none. When the search or filters give no matches, it is empty, and the // message is shown in the box under the filters instead, like on Explore Plants. const noneFit = !loading && totalCount === 0 && shownFiltered; - const status = loading - ? t("myMatchesPage.loading") - : totalCount > 0 - ? shownFiltered - ? t("myMatchesPage.filteredCount", { count: totalCount }) - : t("myMatchesPage.matchCount", { count: totalCount }) - : shownFiltered - ? "" - : t("myMatchesPage.noMatches"); + const status = error + ? t("myMatchesPage.error") + : loading + ? t("myMatchesPage.loading") + : totalCount > 0 + ? shownFiltered + ? t("myMatchesPage.filteredCount", { count: totalCount }) + : t("myMatchesPage.matchCount", { count: totalCount }) + : shownFiltered + ? "" + : t("myMatchesPage.noMatches"); return (
@@ -134,7 +138,7 @@ function MyMatchesPage() { {/* Hidden only when the user has no matches at all, so the search and filters stay on screen when they give no results and can be changed */} - {!loading && (totalCount > 0 || shownFiltered) && ( + {!loading && !error && (totalCount > 0 || shownFiltered) && ( 0 || shownFiltered) && ( + {!loading && !error && (totalCount > 0 || shownFiltered) && (
@@ -197,5 +201,3 @@ function MyMatchesPage() {
); } - -export default MyMatchesPage; diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index 9a4480ea..8cb1ab4c 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -1,4 +1,3 @@ -import "./PlantMatchPage.css"; import { useEffect, useRef, useState } from "react"; import type { MouseEvent, PointerEvent } from "react"; import { useTranslation } from "react-i18next"; @@ -8,6 +7,7 @@ import { useMatchedPlants } from "../../hooks/useMatchedPlants"; import { usePlantDeck } from "../../hooks/usePlantDeck"; import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip"; import { ROUTES } from "../../AppRoutes"; +import "./PlantMatchPage.css"; // How far (px) the card must be dragged before letting go counts as a swipe const SWIPE_THRESHOLD = 100; @@ -27,7 +27,7 @@ function shouldAnimate() { ); } -function PlantMatchPage() { +export default function PlantMatchPage() { const { t } = useTranslation(); const { addMatch } = useMatchedPlants(); const { @@ -248,5 +248,3 @@ function PlantMatchPage() { ); } - -export default PlantMatchPage; diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx index a86d0b5a..1e8a77ab 100644 --- a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx +++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx @@ -8,8 +8,8 @@ import { resultImages, getPlantOwnerResult, getSuggestedPreferences, - type PlantOwnerType, } from "./plantOwnerTest"; +import type { PlantOwnerType } from "../../types/ProfilePicture"; import SuggestedPreferences from "./SuggestedPreferences"; import "./PlantOwnerTestPage.css"; diff --git a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx index 7fff94d2..c2d185f1 100644 --- a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx +++ b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx @@ -1,15 +1,11 @@ -import { useMutation } from "@apollo/client/react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; -import { useUser } from "../../context/UserContext"; -import { - UPDATE_USER_PREFERENCES, - type UpdateUserPreferencesData, -} from "../../graphql/user/mutations"; +import { usePreferences } from "../../hooks/usePreferences"; +import type { PreferenceId } from "../../types/Preference"; type SuggestedPreferencesProps = { // Preference ids suggested by the test - suggestions: string[]; + suggestions: PreferenceId[]; }; // Shows the preferences suggested by the plant owner test. The user chooses @@ -18,22 +14,17 @@ export default function SuggestedPreferences({ suggestions, }: SuggestedPreferencesProps) { const { t } = useTranslation(); - const { userId, user } = useUser(); - const saved = user?.preferences ?? []; - - const [updatePreferences] = useMutation( - UPDATE_USER_PREFERENCES, - ); + const { preferences: saved, canSave, savePreferences } = usePreferences(); // The suggestions the user wants to add. All are chosen to begin with. - const [chosen, setChosen] = useState(suggestions); + 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) @@ -42,28 +33,11 @@ export default function SuggestedPreferences({ } async function addPreferences() { - if (!userId || toAdd.length === 0) return; + if (!canSave || toAdd.length === 0) return; // Added to the preferences the user already has, none are removed - const updatedPreferences = [...saved, ...toAdd]; - try { - const result = await updatePreferences({ - variables: { userId, preferences: updatedPreferences }, - // Updates the profile and plant cards right away - optimisticResponse: { - updateUserPreferences: { - __typename: "User", - id: userId, - preferences: updatedPreferences, - }, - }, - }); - // null means the user was not found in the database - setStatus(result.data?.updateUserPreferences ? "added" : "failed"); - } catch { - // Apollo rolls the preferences back if the server fails - setStatus("failed"); - } + const added = await savePreferences([...saved, ...toAdd]); + setStatus(added ? "added" : "failed"); } if (suggestions.length === 0) return null; diff --git a/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts index ccfaed4f..e298382f 100644 --- a/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts +++ b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts @@ -6,14 +6,8 @@ import cityGardenerDreaming from "../../assets/plantQuiz/cityGardenerDreaming.we import countryMinimalist from "../../assets/plantQuiz/countryMinimalist.webp"; import averageCountryGardener from "../../assets/plantQuiz/averageCountryGardener.webp"; import gardenExpert from "../../assets/plantQuiz/gardenExpert.webp"; - -export type PlantOwnerType = - | "cityMinimalist" - | "averageCityGardener" - | "cityGardenerDreaming" - | "countryMinimalist" - | "averageCountryGardener" - | "gardenExpert"; +import type { PreferenceId } from "../../types/Preference"; +import type { PlantOwnerType } from "../../types/ProfilePicture"; interface QuizQuestion { id: string; @@ -59,20 +53,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 +77,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 +92,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 213c3aba..2b029bb4 100644 --- a/frontend/src/pages/profile/ProfilePage.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -1,4 +1,3 @@ -import "./ProfilePage.css"; import profileImg from "../../assets/avatars/profile.webp"; import { useTranslation } from "react-i18next"; import { useState } from "react"; @@ -12,26 +11,33 @@ import snakePlant from "../../assets/avatars/snakePlant.webp"; import succulent from "../../assets/avatars/succulent.webp"; import { useProfile } from "../../hooks/useProfile"; import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip"; +import { resultImages } from "../plantOwnerTest/plantOwnerTest"; import { - resultImages, - type PlantOwnerType, -} from "../plantOwnerTest/plantOwnerTest"; - -// The preferences the user can choose. Must match PREFERENCE_MATCHERS in -// backend/src/queryBuilders.ts -const PREFERENCES = [ - "minimumWater", - "averageWater", - "frequentWater", - - "fullSun", - "partShade", - "filteredShade", + AVATAR_IDS, + isAvatarId, + isPlantOwnerType, + type AvatarId, +} from "../../types/ProfilePicture"; +import "./ProfilePage.css"; - "easyCare", - "mediumCare", - "hardCare", -]; +// The picture and the name (translation key) of each avatar +const AVATARS: Record = { + monstera: { src: monstera, nameKey: "profile.monstera" }, + pothos: { src: pothos, nameKey: "profile.pothos" }, + snakePlant: { src: snakePlant, nameKey: "profile.snakePlant" }, + anthurium: { src: anthurium, nameKey: "profile.anthurium" }, + succulent: { src: succulent, nameKey: "profile.succulent" }, + fern: { src: fern, nameKey: "profile.fern" }, + orchid: { src: orchid, nameKey: "profile.orchid" }, +}; + +// The picture for a saved profilePicture. Pictures from the plant owner test +// are not in the chooser, can only be set by taking the test. +function profilePictureSrc(id: string): string { + if (isAvatarId(id)) return AVATARS[id].src; + if (isPlantOwnerType(id)) return resultImages[id]; + return profileImg; +} export default function ProfilePage() { const { t } = useTranslation(); @@ -48,22 +54,7 @@ export default function ProfilePage() { const shownName = name ?? t("profile.name"); const shownDescription = description ?? t("profile.description"); - const avatars = [ - { id: "monstera", name: t("profile.monstera"), src: monstera }, - { id: "pothos", name: t("profile.pothos"), src: pothos }, - { id: "snakePlant", name: t("profile.snakePlant"), src: snakePlant }, - { id: "anthurium", name: t("profile.anthurium"), src: anthurium }, - { id: "succulent", name: t("profile.succulent"), src: succulent }, - { id: "fern", name: t("profile.fern"), src: fern }, - { id: "orchid", name: t("profile.orchid"), src: orchid }, - ]; - - // Pictures from the plant owner test are not in the chooser above, - // so they can only be set by taking the test - const currentAvatar = - avatars.find((avatar) => avatar.id === profilePicture)?.src ?? - resultImages[profilePicture as PlantOwnerType] ?? - profileImg; + const currentAvatar = profilePictureSrc(profilePicture); const infoTooltip = useDismissibleTooltip(); @@ -139,7 +130,7 @@ export default function ProfilePage() {

- + )} @@ -179,19 +170,19 @@ export default function ProfilePage() {

{t("profile.avatarChooser")}

- {avatars.map((avatar) => ( + {AVATAR_IDS.map((id) => ( ))}
diff --git a/frontend/src/tests/ExplorePlantsPage.test.tsx b/frontend/src/tests/ExplorePlantsPage.test.tsx index d039ad68..1c2c0792 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..21ddec37 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(), @@ -120,6 +121,21 @@ describe("myMatchesPage", () => { ).not.toBeInTheDocument(); }); + it("shows an error instead of the no matches message when the query fails", () => { + useQuery.mockReturnValue({ + data: undefined, + loading: false, + error: new Error("Network error"), + }); + render(); + + expect(screen.getByText("myMatchesPage.error")).toBeInTheDocument(); + expect( + screen.queryByText("myMatchesPage.noMatches"), + ).not.toBeInTheDocument(); + expect(screen.queryByRole("search")).not.toBeInTheDocument(); + }); + it("shows the loading state while the user is being fetched", () => { mockUser(true); mockMatches([]); @@ -135,7 +151,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", }); diff --git a/frontend/src/tests/PlantPreferences.test.tsx b/frontend/src/tests/PlantPreferences.test.tsx index 48f0bcf3..621bc295 100644 --- a/frontend/src/tests/PlantPreferences.test.tsx +++ b/frontend/src/tests/PlantPreferences.test.tsx @@ -2,6 +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 { PREFERENCE_IDS } from "../types/Preference"; const { updatePreferences, useUser } = vi.hoisted(() => ({ updatePreferences: vi.fn(), @@ -15,8 +16,6 @@ vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); -const preferences = ["averageWater", "fullSun"]; - function mockUser(selected: string[], userId: string | null = "user-1") { useUser.mockReturnValue({ userId, @@ -35,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" }), @@ -49,7 +57,7 @@ describe("PlantPreferences", () => { it("marks the preferences saved on the user", () => { mockUser(["fullSun"]); - render(); + render(); expect( screen.getByRole("button", { name: "preferences.fullSun" }), @@ -61,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" }), @@ -80,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" }), @@ -92,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" }), @@ -103,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/tests/SidebarNewMatches.test.tsx b/frontend/src/tests/SidebarNewMatches.test.tsx index 0e0b0c78..a24661d2 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(); diff --git a/frontend/src/types/Preference.ts b/frontend/src/types/Preference.ts new file mode 100644 index 00000000..40900b0e --- /dev/null +++ b/frontend/src/types/Preference.ts @@ -0,0 +1,16 @@ +// 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]; diff --git a/frontend/src/types/ProfilePicture.ts b/frontend/src/types/ProfilePicture.ts new file mode 100644 index 00000000..eff7e538 --- /dev/null +++ b/frontend/src/types/ProfilePicture.ts @@ -0,0 +1,36 @@ +// The ids that can be saved as a user's profilePicture. Must match +// PROFILE_PICTURES in backend/src/resolvers/users.ts. "default" is the picture +// a new user starts with. + +// The avatars the user can choose on the profile page, in the order they are +// shown. +export const AVATAR_IDS = [ + "monstera", + "pothos", + "snakePlant", + "anthurium", + "succulent", + "fern", + "orchid", +] as const; + +export type AvatarId = (typeof AVATAR_IDS)[number]; + +// The results of the plant owner test. The user can use their result as +// profile picture after the test. +export const PLANT_OWNER_TYPES = [ + "cityMinimalist", + "averageCityGardener", + "cityGardenerDreaming", + "countryMinimalist", + "averageCountryGardener", + "gardenExpert", +] as const; + +export type PlantOwnerType = (typeof PLANT_OWNER_TYPES)[number]; + +export const isAvatarId = (id: string): id is AvatarId => + (AVATAR_IDS as readonly string[]).includes(id); + +export const isPlantOwnerType = (id: string): id is PlantOwnerType => + (PLANT_OWNER_TYPES as readonly string[]).includes(id);