From 0b29f5dfe064a6d676120f77697e78ef7bdd693e Mon Sep 17 00:00:00 2001 From: Alexandra Date: Sat, 24 Oct 2026 11:26:14 +0200 Subject: [PATCH 1/5] Added userDB to the server file, added query, types, mutations and resolvers --- backend/src/server.ts | 248 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 247 insertions(+), 1 deletion(-) diff --git a/backend/src/server.ts b/backend/src/server.ts index 1fad6d11..331a810e 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,9 +1,11 @@ import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; +import { GraphQLError } from "graphql"; +import { ObjectId } from "mongodb"; import type { Document, Filter, WithId } from "mongodb"; import { db } from "./db.js"; -// The shape of a plant document in MongoDB (only the fields we read) +// The shape of a plant document in MongoDB interface PlantDoc { commonName: string; // Base64-encoded Perenual image as a data URI, stored by seedDataFetch.js @@ -43,7 +45,79 @@ interface ExplorePlantsArgs { offset?: number; } +// The shape of a user document in MongoDB. _id is added by MongoDB. +interface UserDoc { + // null means the user has not chosen one, the frontend shows a translated default + name: string | null; + description: string | null; + profilePicture: string; + preferences: string[]; + // Only the plant ids are stored, the plants are looked up in User.matchedPlants + matchedPlantIds: ObjectId[]; + createdAt: Date; +} + +// The shape of a User in the GraphQL API. matchedPlantIds is not in the schema, +// it is only passed on to the User.matchedPlants resolver. +interface User { + id: string; + name: string | null; + description: string | null; + profilePicture: string; + preferences: string[]; + matchedPlantIds: ObjectId[]; + createdAt: string; +} + +interface UserIdArgs { + userId: string; +} + +interface UpdateUserProfileArgs extends UserIdArgs { + name?: string | null; + description?: string | null; + profilePicture?: string | null; +} + +interface UpdateUserPreferencesArgs extends UserIdArgs { + preferences: string[]; +} + +interface UserMatchArgs extends UserIdArgs { + plantId: string; +} + +// 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/Profile.tsx +const PROFILE_PICTURES = [ + "default", + "monstera", + "pothos", + "snake-plant", + "anthurium", + "succulent", + "fern", + "orchid", +]; + +// Must match the preference ids in frontend/src/pages/profile/Profile.tsx +const PREFERENCES = [ + "minimumWater", + "averageWater", + "frequentWater", + "fullSun", + "partShade", + "filteredShade", + "easyCare", + "mediumCare", + "hardCare", +]; + const plants = db.collection("plants"); +const users = db.collection("users"); const typeDefs = ` type Query{ @@ -57,6 +131,20 @@ const typeDefs = ` limit: Int = 12 offset: Int = 0 ): PlantPage! + getUser(userId: ID!): User + } + + type Mutation { + createUser: User! + updateUserProfile( + userId: ID! + name: String + description: String + profilePicture: String + ): User + updateUserPreferences(userId: ID!, preferences: [String!]!): User + addUserMatch(userId: ID!, plantId: ID!): User + removeUserMatch(userId: ID!, plantId: ID!): User } type PlantPage { @@ -74,6 +162,16 @@ const typeDefs = ` sunlight: [String] careLevel: String } + + type User { + id: ID! + name: String + description: String + profilePicture: String! + preferences: [String!]! + matchedPlants: [Plant!]! + createdAt: String! + } `; const toPlant = (doc: WithId): Plant => ({ @@ -87,6 +185,49 @@ const toPlant = (doc: WithId): Plant => ({ 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; +}; + +// 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; +}; + // Escape user input so it can't be interpreted as regex const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); @@ -211,6 +352,111 @@ const resolvers = { return { plants: docs.map(toPlant), totalCount }; }, + + 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; + }, + }, + + 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: { + // Looks up the matched plants, in the order they were matched. + // Ids of plants that no longer exist (e.g. after a reseed) are skipped. + matchedPlants: async (user: User): Promise => { + if (user.matchedPlantIds.length === 0) return []; + const docs = await plants + .find({ _id: { $in: user.matchedPlantIds } }) + .toArray(); + const byId = new Map(docs.map((doc) => [doc._id.toString(), doc])); + return user.matchedPlantIds.flatMap((id) => { + const doc = byId.get(id.toString()); + return doc ? [toPlant(doc)] : []; + }); + }, }, }; From e0de81fb9dc50670066ced1329a41ddc566378ce Mon Sep 17 00:00:00 2001 From: Alexandra Date: Sat, 24 Oct 2026 11:55:58 +0200 Subject: [PATCH 2/5] made plants to a seperate collection and renamed DB, and created collection users --- backend/.env.example | 2 +- backend/README.md | 2 +- backend/package-lock.json | 7 ------- backend/seedDataFetch.js | 4 +--- backend/src/db.ts | 2 +- frontend/package-lock.json | 33 ++++++++++----------------------- 6 files changed, 14 insertions(+), 36 deletions(-) diff --git a/backend/.env.example b/backend/.env.example index 13a7987c..eb24f001 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,4 +1,4 @@ MONGODB_URI=mongodb://localhost:27017 -DB_NAME=plants +DB_NAME=iloveplants PERENUAL_API_KEY= PORT=3001 diff --git a/backend/README.md b/backend/README.md index 0b189b0a..474fd160 100644 --- a/backend/README.md +++ b/backend/README.md @@ -72,7 +72,7 @@ Da er DB koblingen satt opp riktig Kjør med SSH-tunnelen oppe og `PERENUAL_API_KEY` satt i `.env`: ```bash -npm run seed:reset # sletter HELE databasen og laster alt inn på nytt +npm run seed:reset # sletter plante databasen og laster alt inn på nytt npm run seed # fyller bare inn det som mangler ``` diff --git a/backend/package-lock.json b/backend/package-lock.json index 5375169d..bdaacda7 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1177,7 +1177,6 @@ "integrity": "sha512-oM/5sAqz/l1v/zYK1qTOPrn2+JIrBGC1V6uNYucRO5gh6eT9vWJ/RhPbGE59byvZEUQ4VP6XkLBaS5Jti5jpvw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.71.1", "@typescript-eslint/types": "8.71.1", @@ -1381,7 +1380,6 @@ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1823,7 +1821,6 @@ "integrity": "sha512-npHjrHb2o4ehH3mE+YuxABR+0gyb0aVWCIolgJDArwCiHEIsonBm3ZKjel5b0U5+a+MbEvIyRCGCzD3eKKK2NA==", "dev": true, "license": "MIT", - "peer": true, "workspaces": [ "packages/*" ], @@ -2214,7 +2211,6 @@ "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz", "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==", "license": "MIT", - "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -2435,7 +2431,6 @@ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -2792,7 +2787,6 @@ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -3237,7 +3231,6 @@ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/backend/seedDataFetch.js b/backend/seedDataFetch.js index 13a656a3..5839b879 100644 --- a/backend/seedDataFetch.js +++ b/backend/seedDataFetch.js @@ -254,14 +254,12 @@ async function fetchPlantDetails() { } } -// ---------- Kjøring ---------- - try { // Sjekk nøkkelen før noe slettes, ellers står vi igjen med en tom database if (!API_KEY) throw new Error("PERENUAL_API_KEY mangler i .env"); if (RESET) { console.log(`Sletter hele databasen "${db.databaseName}"...`); - await db.dropDatabase(); + await plants.drop(); } await plants.createIndex({ perenualId: 1 }, { unique: true }); await fetchPlantList(); diff --git a/backend/src/db.ts b/backend/src/db.ts index 08b2873b..089ba591 100644 --- a/backend/src/db.ts +++ b/backend/src/db.ts @@ -11,4 +11,4 @@ export const client = new MongoClient(process.env.MONGODB_URI); await client.connect(); console.log("Connected to MongoDB"); -export const db = client.db(process.env.DB_NAME ?? "plants"); +export const db = client.db(process.env.DB_NAME ?? "iloveplants"); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 9ef16e6a..1fc7b788 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -148,7 +148,6 @@ "version": "7.29.7", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -458,7 +457,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=20.19.0" }, @@ -503,7 +501,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=20.19.0" } @@ -1115,7 +1112,8 @@ "node_modules/@types/aria-query": { "version": "5.0.4", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@types/chai": { "version": "5.2.3", @@ -1150,7 +1148,6 @@ "version": "24.13.6", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~7.18.0" } @@ -1159,7 +1156,6 @@ "version": "19.3.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -1168,7 +1164,6 @@ "version": "19.3.0", "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "@types/react": "^19.3.0" } @@ -1212,7 +1207,6 @@ "version": "8.70.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/types": "8.70.0", @@ -1425,7 +1419,6 @@ "version": "5.0.5", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@bcoe/v8-coverage": "^1.0.2", "@vitest/istanbul-lib-coverage": "^1.0.2", @@ -1546,7 +1539,6 @@ "version": "8.18.0", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1581,6 +1573,7 @@ "version": "5.0.1", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -1589,6 +1582,7 @@ "version": "5.2.0", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=10" }, @@ -1683,7 +1677,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.11.23", "caniuse-lite": "^1.0.30001810", @@ -1845,7 +1838,8 @@ "node_modules/dom-accessibility-api": { "version": "0.5.16", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/electron-to-chromium": { "version": "1.5.433", @@ -1891,7 +1885,6 @@ "version": "10.11.0", "dev": true, "license": "MIT", - "peer": true, "workspaces": [ "packages/*" ], @@ -2183,7 +2176,6 @@ "node_modules/graphql": { "version": "16.14.2", "license": "MIT", - "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -2265,7 +2257,6 @@ } ], "license": "MIT", - "peer": true, "peerDependencies": { "typescript": "^5 || ^6 || ^7" }, @@ -2415,7 +2406,6 @@ "version": "5.6.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -2715,6 +2705,7 @@ "version": "1.5.0", "dev": true, "license": "MIT", + "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -2947,6 +2938,7 @@ "version": "27.5.1", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -2983,7 +2975,6 @@ "node_modules/react": { "version": "19.3.0", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -2991,7 +2982,6 @@ "node_modules/react-dom": { "version": "19.3.0", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.28.0" }, @@ -3036,7 +3026,8 @@ "node_modules/react-is": { "version": "17.0.2", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/react-router": { "version": "7.18.4", @@ -3309,7 +3300,6 @@ "version": "6.0.3", "devOptional": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -3401,7 +3391,6 @@ "version": "8.3.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", @@ -3478,7 +3467,6 @@ "version": "5.0.5", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.5", @@ -3662,7 +3650,6 @@ "version": "4.6.5", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } From 71e1778c322d98d7904aa5586598e956c5823073 Mon Sep 17 00:00:00 2001 From: Alexandra Date: Sat, 24 Oct 2026 12:41:23 +0200 Subject: [PATCH 3/5] Made context functionality for users that can be reused in the other components --- frontend/src/context/UserContex.tsx | 41 ++++++++++ frontend/src/context/UserContext.tsx | 92 +++++++++++++++++++++ frontend/src/context/userQueries.ts | 114 +++++++++++++++++++++++++++ frontend/src/main.tsx | 9 ++- 4 files changed, 253 insertions(+), 3 deletions(-) create mode 100644 frontend/src/context/UserContex.tsx create mode 100644 frontend/src/context/UserContext.tsx create mode 100644 frontend/src/context/userQueries.ts diff --git a/frontend/src/context/UserContex.tsx b/frontend/src/context/UserContex.tsx new file mode 100644 index 00000000..bda46074 --- /dev/null +++ b/frontend/src/context/UserContex.tsx @@ -0,0 +1,41 @@ +import { useMutation, useQuery } from "@apollo/client/react"; +import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; +import { CREATE_USER, GET_USER, type CreateUserData, type GetUserData, type User } from "./userQueries"; + +type UserContextValue = { userId: string | null; user: User | null; loading: boolean }; + +// Standardverdi: komponenter (og tester) uten UserProvider får "ingen bruker" i stedet for en krasj +const UserContext = createContext({ userId: null, user: null, loading: false }); + +export function UserProvider({ children }: { children: ReactNode }) { + const [userId, setUserId] = useState(readUserId); // try/catch rundt localStorage + + const { data, loading, error } = useQuery(GET_USER, { + variables: { userId: userId ?? "" }, + skip: !userId, + }); + const [createUser] = useMutation(CREATE_USER); + const creating = useRef(false); + + // Mangler: ingen id lagret, ELLER id-en finnes ikke i databasen lenger + const userMissing = !userId || (!loading && !error && data?.getUser === null); + + useEffect(() => { + if (!userMissing || creating.current) return; + creating.current = true; + createUser() + .then(({ data }) => { + const id = data?.createUser.id; + if (id) { + saveUserId(id); // localStorage.setItem("userId", id) i try/catch + setUserId(id); + } + }) + .finally(() => { creating.current = false; }); + }, [userMissing, createUser]); + + const value = { userId, user: data?.getUser ?? null, loading }; + return {children}; +} + +export const useUser = () => useContext(UserContext); diff --git a/frontend/src/context/UserContext.tsx b/frontend/src/context/UserContext.tsx new file mode 100644 index 00000000..97986dcc --- /dev/null +++ b/frontend/src/context/UserContext.tsx @@ -0,0 +1,92 @@ +import { useMutation, useQuery } from "@apollo/client/react"; +import { + createContext, + useContext, + useEffect, + useRef, + useState, + type ReactNode, +} from "react"; +import { + CREATE_USER, + GET_USER, + type CreateUserData, + type GetUserData, + type User, +} from "./userQueries"; + +// The only user data kept in the browser. Everything else is in the database. +const STORAGE_KEY = "userId"; + +function readUserId(): string | null { + try { + return localStorage.getItem(STORAGE_KEY); + } catch { + return null; + } +} + +function saveUserId(id: string) { + try { + localStorage.setItem(STORAGE_KEY, id); + } catch { + // Storage can fail (private mode, full quota). The app still works, + // but a new user is created on the next visit. + } +} + +type UserContextValue = { + userId: string | null; + user: User | null; + loading: boolean; +}; + +// Default value: components (and tests) without a UserProvider get "no user" instead of a crash +const UserContext = createContext({ + userId: null, + user: null, + loading: false, +}); + +export function UserProvider({ children }: { children: ReactNode }) { + const [userId, setUserId] = useState(readUserId); + + const { data, loading, error } = useQuery(GET_USER, { + variables: { userId: userId ?? "" }, + // No id yet, so there is nothing to ask for + skip: !userId, + }); + const [createUser] = useMutation(CREATE_USER); + + // Stops StrictMode (which runs effects twice) from creating two users + const creating = useRef(false); + + // No id saved, or the saved id no longer exists in the database. + // If the backend is down (error), we wait instead of creating a new user. + const userMissing = !userId || (!loading && !error && data?.getUser === null); + + useEffect(() => { + if (!userMissing || creating.current) return; + creating.current = true; + createUser() + .then(({ data }) => { + const id = data?.createUser.id; + if (id) { + saveUserId(id); + setUserId(id); + } + }) + .catch(() => { + // Backend unreachable. The app still works, just without saved data. + }) + .finally(() => { + creating.current = false; + }); + }, [userMissing, createUser]); + + const value = { userId, user: data?.getUser ?? null, loading }; + return {children}; +} + +// eslint-disable-next-line react-refresh/only-export-components +export const useUser = () => useContext(UserContext); diff --git a/frontend/src/context/userQueries.ts b/frontend/src/context/userQueries.ts new file mode 100644 index 00000000..36558774 --- /dev/null +++ b/frontend/src/context/userQueries.ts @@ -0,0 +1,114 @@ +import { gql } from "@apollo/client"; +import type { Plant } from "../types/Plant"; + +// The user fields every query and mutation asks for. Using the same fields +// everywhere lets Apollo's cache update the user on all pages at once. +const USER_FIELDS = gql` + fragment UserFields on User { + id + name + description + profilePicture + preferences + matchedPlants { + id + name + imageURL + scientificName + description + watering + sunlight + careLevel + } + } +`; + +export const GET_USER = gql` + query GetUser($userId: ID!) { + getUser(userId: $userId) { + ...UserFields + } + } + ${USER_FIELDS} +`; + +export const CREATE_USER = gql` + mutation CreateUser { + createUser { + ...UserFields + } + } + ${USER_FIELDS} +`; + +export const ADD_USER_MATCH = gql` + mutation AddUserMatch($userId: ID!, $plantId: ID!) { + addUserMatch(userId: $userId, plantId: $plantId) { + ...UserFields + } + } + ${USER_FIELDS} +`; + +export const REMOVE_USER_MATCH = gql` + mutation RemoveUserMatch($userId: ID!, $plantId: ID!) { + removeUserMatch(userId: $userId, plantId: $plantId) { + ...UserFields + } + } + ${USER_FIELDS} +`; + +export const UPDATE_USER_PROFILE = gql` + mutation UpdateUserProfile( + $userId: ID! + $name: String + $description: String + $profilePicture: String + ) { + updateUserProfile( + userId: $userId + name: $name + description: $description + profilePicture: $profilePicture + ) { + id + name + description + profilePicture + } + } +`; + +export const UPDATE_USER_PREFERENCES = gql` + mutation UpdateUserPreferences($userId: ID!, $preferences: [String!]!) { + updateUserPreferences(userId: $userId, preferences: $preferences) { + id + preferences + } + } +`; + +// A user as returned by the queries above +export type User = { + id: string; + name: string | null; + description: string | null; + profilePicture: string; + preferences: string[]; + matchedPlants: Plant[]; +}; + +export type GetUserData = { getUser: User | null }; +export type CreateUserData = { createUser: User }; +export type AddUserMatchData = { addUserMatch: User | null }; +export type RemoveUserMatchData = { removeUserMatch: User | null }; +export type UpdateUserProfileData = { + updateUserProfile: Pick< + User, + "id" | "name" | "description" | "profilePicture" + > | null; +}; +export type UpdateUserPreferencesData = { + updateUserPreferences: Pick | null; +}; diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 72a8fc6e..32a2d483 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -6,6 +6,7 @@ import "./i18n"; import App from "./App.tsx"; import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client"; import { ApolloProvider } from "@apollo/client/react"; +import { UserProvider } from "./context/UserContext.tsx"; const clienten = new ApolloClient({ link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL ?? "/graphql" }), @@ -15,9 +16,11 @@ const clienten = new ApolloClient({ createRoot(document.getElementById("root")!).render( - - - + + + + + , ); From 9b22f917df39a72c86ffeb366ce9761879ccda6c Mon Sep 17 00:00:00 2001 From: Alexandra Date: Sat, 24 Oct 2026 13:10:34 +0200 Subject: [PATCH 4/5] Implemented the last functionality related to the userDB in the frotend --- README.md | 1 + .../PlantPreferenceChips.tsx | 25 +------- .../plantPreferences/PlantPreferences.tsx | 47 ++++++++------- frontend/src/context/UserContex.tsx | 41 ------------- frontend/src/context/UserContext.tsx | 20 +++++++ frontend/src/context/userQueries.ts | 13 +++-- frontend/src/hooks/useMatchedPlants.ts | 38 ++++--------- frontend/src/hooks/useProfile.ts | 56 ++++++++++++++++++ frontend/src/pages/profile/Profile.tsx | 57 +++++++------------ 9 files changed, 148 insertions(+), 150 deletions(-) delete mode 100644 frontend/src/context/UserContex.tsx create mode 100644 frontend/src/hooks/useProfile.ts diff --git a/README.md b/README.md index 9a54afd0..bf1b6c08 100644 --- a/README.md +++ b/README.md @@ -144,3 +144,4 @@ and work practices. ## Known issues TODO! +If you type and switch pages within half a second after updating your profile, the last few letters are not saved, because the debounce didn't have time to send. \ No newline at end of file diff --git a/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx b/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx index b9da76fc..b9c88bbe 100644 --- a/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx +++ b/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx @@ -1,5 +1,5 @@ -import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import { useUser } from "../../context/UserContext.tsx"; import "./PlantPreferenceChips.css"; type Props = { @@ -15,27 +15,8 @@ export default function PlantPreferenceChips({ }: Props) { const { t } = useTranslation(); - const [selectedPreferences, setSelectedPreferences] = useState([]); - - useEffect(() => { - function loadPreferences() { - const savedPreferences = localStorage.getItem("plantPreferences"); - - if (savedPreferences) { - setSelectedPreferences(JSON.parse(savedPreferences)); - } else { - setSelectedPreferences([]); - } - } - - loadPreferences(); - - window.addEventListener("preferencesChanged", loadPreferences); - - return () => { - window.removeEventListener("preferencesChanged", loadPreferences); - }; - }, []); + // Re-renders on its own when the preferences change, since they come from the Apollo cache + const selectedPreferences = useUser().user?.preferences ?? []; const wateringPreferences: string[] = []; const sunlightPreferences: string[] = []; diff --git a/frontend/src/components/plantPreferences/PlantPreferences.tsx b/frontend/src/components/plantPreferences/PlantPreferences.tsx index a8aa2725..b381e20e 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.tsx +++ b/frontend/src/components/plantPreferences/PlantPreferences.tsx @@ -1,5 +1,10 @@ -import { useState } from "react"; +import { useMutation } from "@apollo/client/react"; import { useTranslation } from "react-i18next"; +import { useUser } from "../../context/UserContext.tsx"; +import { + UPDATE_USER_PREFERENCES, + type UpdateUserPreferencesData, +} from "../../context/userQueries.ts"; import type { Preference } from "../../types/Preference.ts"; import "./PlantPreferences.css"; @@ -11,18 +16,17 @@ type Props = { export default function PlantPreferences({ preferences }: Props) { const { t } = useTranslation(); - const [selected, setSelected] = useState(() => { - // get saved preferences when the page loads - const savedPreferences = localStorage.getItem("plantPreferences"); + // Saved preferences come from the database through UserContext + const { userId, user } = useUser(); + const selected = user?.preferences ?? []; - if (savedPreferences) { - return JSON.parse(savedPreferences); - } - - return []; - }); + const [updatePreferences] = useMutation( + UPDATE_USER_PREFERENCES, + ); function handleClick(id: string) { + if (!userId) return; + let updatedPreferences: string[]; if (selected.includes(id)) { @@ -31,15 +35,20 @@ export default function PlantPreferences({ preferences }: Props) { updatedPreferences = [...selected, id]; } - setSelected(updatedPreferences); - - // Save selected preferences to stay after reload - localStorage.setItem( - "plantPreferences", - JSON.stringify(updatedPreferences), - ); - // tell plant cards that preferences have changed - window.dispatchEvent(new Event("preferencesChanged")); + // 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 + }); } // Button for each preference diff --git a/frontend/src/context/UserContex.tsx b/frontend/src/context/UserContex.tsx deleted file mode 100644 index bda46074..00000000 --- a/frontend/src/context/UserContex.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { useMutation, useQuery } from "@apollo/client/react"; -import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; -import { CREATE_USER, GET_USER, type CreateUserData, type GetUserData, type User } from "./userQueries"; - -type UserContextValue = { userId: string | null; user: User | null; loading: boolean }; - -// Standardverdi: komponenter (og tester) uten UserProvider får "ingen bruker" i stedet for en krasj -const UserContext = createContext({ userId: null, user: null, loading: false }); - -export function UserProvider({ children }: { children: ReactNode }) { - const [userId, setUserId] = useState(readUserId); // try/catch rundt localStorage - - const { data, loading, error } = useQuery(GET_USER, { - variables: { userId: userId ?? "" }, - skip: !userId, - }); - const [createUser] = useMutation(CREATE_USER); - const creating = useRef(false); - - // Mangler: ingen id lagret, ELLER id-en finnes ikke i databasen lenger - const userMissing = !userId || (!loading && !error && data?.getUser === null); - - useEffect(() => { - if (!userMissing || creating.current) return; - creating.current = true; - createUser() - .then(({ data }) => { - const id = data?.createUser.id; - if (id) { - saveUserId(id); // localStorage.setItem("userId", id) i try/catch - setUserId(id); - } - }) - .finally(() => { creating.current = false; }); - }, [userMissing, createUser]); - - const value = { userId, user: data?.getUser ?? null, loading }; - return {children}; -} - -export const useUser = () => useContext(UserContext); diff --git a/frontend/src/context/UserContext.tsx b/frontend/src/context/UserContext.tsx index 97986dcc..eff82948 100644 --- a/frontend/src/context/UserContext.tsx +++ b/frontend/src/context/UserContext.tsx @@ -26,6 +26,24 @@ function readUserId(): string | null { } } +// Keys from before user data moved to the database. Nothing reads them any more, +// so they are removed to keep old data from lying around in the browser. +const LEGACY_KEYS = [ + "plantPreferences", + "matchedPlants", + "profileName", + "description", + "profileAvatar", +]; + +function removeLegacyKeys() { + try { + LEGACY_KEYS.forEach((key) => localStorage.removeItem(key)); + } catch { + // Storage not available, so there is nothing to clean up + } +} + function saveUserId(id: string) { try { localStorage.setItem(STORAGE_KEY, id); @@ -51,6 +69,8 @@ const UserContext = createContext({ export function UserProvider({ children }: { children: ReactNode }) { const [userId, setUserId] = useState(readUserId); + useEffect(removeLegacyKeys, []); + const { data, loading, error } = useQuery(GET_USER, { variables: { userId: userId ?? "" }, // No id yet, so there is nothing to ask for diff --git a/frontend/src/context/userQueries.ts b/frontend/src/context/userQueries.ts index 36558774..790921a9 100644 --- a/frontend/src/context/userQueries.ts +++ b/frontend/src/context/userQueries.ts @@ -103,12 +103,15 @@ export type GetUserData = { getUser: User | null }; export type CreateUserData = { createUser: User }; export type AddUserMatchData = { addUserMatch: User | null }; export type RemoveUserMatchData = { removeUserMatch: User | null }; +// __typename is needed when these are used in an optimisticResponse export type UpdateUserProfileData = { - updateUserProfile: Pick< - User, - "id" | "name" | "description" | "profilePicture" - > | null; + updateUserProfile: + | (Pick & { + __typename?: "User"; + }) + | null; }; export type UpdateUserPreferencesData = { - updateUserPreferences: Pick | null; + updateUserPreferences: + (Pick & { __typename?: "User" }) | null; }; diff --git a/frontend/src/hooks/useMatchedPlants.ts b/frontend/src/hooks/useMatchedPlants.ts index 136bd529..9ded3b9f 100644 --- a/frontend/src/hooks/useMatchedPlants.ts +++ b/frontend/src/hooks/useMatchedPlants.ts @@ -1,39 +1,23 @@ -import { useEffect, useState } from "react"; +import { useMutation } from "@apollo/client/react"; +import { useUser } from "../context/UserContext"; +import { ADD_USER_MATCH, REMOVE_USER_MATCH } from "../context/userQueries"; import type { Plant } from "../types/Plant"; -const STORAGE_KEY = "matchedPlants"; - -function readMatches(): Plant[] { - try { - const stored = localStorage.getItem(STORAGE_KEY); - return stored ? (JSON.parse(stored) as Plant[]) : []; - } catch { - return []; - } -} - export function useMatchedPlants() { - const [matches, setMatches] = useState(readMatches); + const { userId, user } = useUser(); + const [addUserMatch] = useMutation(ADD_USER_MATCH); + const [removeUserMatch] = useMutation(REMOVE_USER_MATCH); - useEffect(() => { - try { - localStorage.setItem(STORAGE_KEY, JSON.stringify(matches)); - } catch { - // Storage can fail (private mode, full quota). The app still works, - // the matches just won't be remembered. - } - }, [matches]); + const matches = user?.matchedPlants ?? []; const addMatch = (plant: Plant) => { - setMatches((current) => - current.some((match) => match.id === plant.id) - ? current - : [...current, plant], - ); + if (!userId || matches.some((m) => m.id === plant.id)) return; + addUserMatch({ variables: { userId, plantId: plant.id } }); }; const removeMatch = (id: string) => { - setMatches((current) => current.filter((match) => match.id !== id)); + if (!userId) return; + removeUserMatch({ variables: { userId, plantId: id } }); }; return { matches, addMatch, removeMatch } as const; diff --git a/frontend/src/hooks/useProfile.ts b/frontend/src/hooks/useProfile.ts new file mode 100644 index 00000000..5f09fbc2 --- /dev/null +++ b/frontend/src/hooks/useProfile.ts @@ -0,0 +1,56 @@ +import { useMutation } from "@apollo/client/react"; +import { useEffect, useState } from "react"; +import { useUser } from "../context/UserContext"; +import { + UPDATE_USER_PROFILE, + type UpdateUserProfileData, +} from "../context/userQueries"; +import { useDebounce } from "./useDebounce"; + +export function useProfile() { + const { userId, user } = useUser(); + const [updateProfile] = + useMutation(UPDATE_USER_PROFILE); + + // What the user has typed, shown right away but saved only after they stop typing + const [draft, setDraft] = useState<{ name?: string; description?: string }>( + {}, + ); + const savedDraft = useDebounce(draft, 500); + + useEffect(() => { + if (!userId || Object.keys(savedDraft).length === 0) return; + updateProfile({ variables: { userId, ...savedDraft } }).catch(() => { + // Backend unreachable. The text stays on screen, it just isn't saved. + }); + }, [userId, savedDraft, updateProfile]); + + const setProfilePicture = (profilePicture: string) => { + if (!userId) return; + updateProfile({ + variables: { userId, profilePicture }, + // Shows the new picture right away instead of waiting for the server + optimisticResponse: { + updateUserProfile: { + __typename: "User", + id: userId, + name: user?.name ?? null, + description: user?.description ?? null, + profilePicture, + }, + }, + }).catch(() => { + // Apollo rolls the picture back if the server fails + }); + }; + + return { + name: draft.name ?? user?.name ?? null, + description: draft.description ?? user?.description ?? null, + profilePicture: user?.profilePicture ?? "default", + setName: (name: string) => setDraft((d) => ({ ...d, name })), + setDescription: (description: string) => + setDraft((d) => ({ ...d, description })), + setProfilePicture, + }; +} diff --git a/frontend/src/pages/profile/Profile.tsx b/frontend/src/pages/profile/Profile.tsx index 496d6004..72f2f56b 100644 --- a/frontend/src/pages/profile/Profile.tsx +++ b/frontend/src/pages/profile/Profile.tsx @@ -2,7 +2,7 @@ import "./Profile.css"; import profileImg from "../../assets/profile.png"; import type { Preference } from "../../types/Preference.ts"; import { useTranslation } from "react-i18next"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import PlantPreferences from "../../components/plantPreferences/PlantPreferences.tsx"; import monstera from "../../assets/avatars/monstera.png"; import anthurium from "../../assets/avatars/anthurium.png"; @@ -11,21 +11,21 @@ import orchid from "../../assets/avatars/orchid.png"; import pothos from "../../assets/avatars/pothos.png"; import snakePlant from "../../assets/avatars/snake-plant.png"; import succulent from "../../assets/avatars/succulent.png"; +import { useProfile } from "../../hooks/useProfile.ts"; export default function Profile() { const { t } = useTranslation(); - const [name, setName] = useState( - () => localStorage.getItem("profileName") ?? t("profile.name"), - ); - - const [description, setDescription] = useState( - () => localStorage.getItem("description") ?? t("profile.description"), - ); - - const [selectedAvatar, setSelectedAvatar] = useState( - () => localStorage.getItem("profileAvatar") ?? "default", - ); + const { + name, + description, + profilePicture, + setName, + setDescription, + setProfilePicture, + } = useProfile(); + const shownName = name ?? t("profile.name"); + const shownDescription = description ?? t("profile.description"); const avatars = [ { id: "monstera", name: t("profile.monstera"), src: monstera }, @@ -38,22 +38,7 @@ export default function Profile() { ]; const currentAvatar = - selectedAvatar === "default" - ? profileImg - : (avatars.find((avatar) => avatar.id === selectedAvatar)?.src ?? - profileImg); - - useEffect(() => { - localStorage.setItem("profileName", name); - }, [name]); - - useEffect(() => { - localStorage.setItem("description", description); - }, [description]); - - useEffect(() => { - localStorage.setItem("profileAvatar", selectedAvatar); - }, [selectedAvatar]); + avatars.find((avatar) => avatar.id === profilePicture)?.src ?? profileImg; const [activeTab, setActiveTab] = useState<"preferences" | "editProfile">( "preferences", @@ -79,15 +64,15 @@ export default function Profile() { {`${t("profile.imageAlt")}:
-

{name}

+

{shownName}

{t("profile.descriptionLabel")}:{" "} - {description} + {shownDescription}

@@ -123,7 +108,7 @@ export default function Profile() { setName(event.target.value)} maxLength={40} placeholder={t("profile.placeholderName")} @@ -133,7 +118,7 @@ export default function Profile() { setDescription(event.target.value)} maxLength={100} placeholder={t("profile.placeholderAbout")} @@ -146,11 +131,11 @@ export default function Profile() { key={avatar.id} type="button" className={`avatar-option ${ - selectedAvatar === avatar.id ? "selected" : "" + profilePicture === avatar.id ? "selected" : "" }`} - onClick={() => setSelectedAvatar(avatar.id)} + onClick={() => setProfilePicture(avatar.id)} aria-label={`Choose ${avatar.name}`} - aria-pressed={selectedAvatar === avatar.id} + aria-pressed={profilePicture === avatar.id} > {avatar.name} {avatar.name} From b039c28c2974221d03210d02412a372631d5f93b Mon Sep 17 00:00:00 2001 From: Alexandra Date: Sat, 24 Oct 2026 13:19:57 +0200 Subject: [PATCH 5/5] Removed unsused code, connected code and added transaltions for loading page --- docs/ARCHITECTURE.md | 2 ++ frontend/src/hooks/useMatchedPlants.ts | 15 ++++++++++----- frontend/src/i18n/locales/en/translation.json | 1 + frontend/src/i18n/locales/no/translation.json | 1 + .../src/pages/explorePlants/ExplorePlants.tsx | 2 +- frontend/src/pages/myMatches/MyMatchesPage.tsx | 8 ++++++-- frontend/src/utils/isPreferenceMatch.ts | 3 --- 7 files changed, 21 insertions(+), 11 deletions(-) delete mode 100644 frontend/src/utils/isPreferenceMatch.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d42ead83..a56311d1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,5 +1,7 @@ # Architecture +TODO: updated with new arciture + This document describes how the data flows from the API to the frontend, how the frontend, backend and database fit together. It also describes the plant data and the Perenual API and why we chose GraphQL and MongoDB. The folder structure is shown at the end of this document. diff --git a/frontend/src/hooks/useMatchedPlants.ts b/frontend/src/hooks/useMatchedPlants.ts index 9ded3b9f..f27d8e43 100644 --- a/frontend/src/hooks/useMatchedPlants.ts +++ b/frontend/src/hooks/useMatchedPlants.ts @@ -1,12 +1,17 @@ import { useMutation } from "@apollo/client/react"; import { useUser } from "../context/UserContext"; -import { ADD_USER_MATCH, REMOVE_USER_MATCH } from "../context/userQueries"; +import { + ADD_USER_MATCH, + REMOVE_USER_MATCH, + type AddUserMatchData, + type RemoveUserMatchData, +} from "../context/userQueries"; import type { Plant } from "../types/Plant"; export function useMatchedPlants() { - const { userId, user } = useUser(); - const [addUserMatch] = useMutation(ADD_USER_MATCH); - const [removeUserMatch] = useMutation(REMOVE_USER_MATCH); + const { userId, user, loading } = useUser(); + const [addUserMatch] = useMutation(ADD_USER_MATCH); + const [removeUserMatch] = useMutation(REMOVE_USER_MATCH); const matches = user?.matchedPlants ?? []; @@ -20,5 +25,5 @@ export function useMatchedPlants() { removeUserMatch({ variables: { userId, plantId: id } }); }; - return { matches, addMatch, removeMatch } as const; + return { matches, loading, addMatch, removeMatch } as const; } diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 8969db62..f5666116 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -76,6 +76,7 @@ "alreadyMatched": "Already in My Matches" }, "myMatchesPage": { + "loading": "Loading your matches...", "noMatches": "You have no matches yet. Press the flower on the match page to match with a plant.", "removeMatch": "Remove the match" }, diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index bfebbc1b..b1389d44 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -76,6 +76,7 @@ "alreadyMatched": "Allerede i Mine Matches" }, "myMatchesPage": { + "loading": "Laster matchene dine...", "noMatches": "Du har ingen matcher ennå. Trykk på blomsten på match-siden for å matche med en plante.", "removeMatch": "Fjern matchen" }, diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index 6a03e44b..7a3c9c77 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -20,7 +20,7 @@ const SORT_OPTIONS = ["name_asc", "name_desc", "watering_asc", "careLevel_asc"]; export default function ExplorePlants() { const { t } = useTranslation(); - // Same hook as PlantMatch, so both pages share the same matches + // Matches come from the user in the database, so every page sees the same list const { matches, addMatch } = useMatchedPlants(); const [search, setSearch] = useSessionState("ExplorePlants.search"); diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index e826003d..f05c57ab 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -6,12 +6,16 @@ import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; function MyMatchesPage() { const { t } = useTranslation(); - const { matches, removeMatch } = useMatchedPlants(); + const { matches, loading, removeMatch } = useMatchedPlants(); return (
- {matches.length === 0 &&

{t("myMatchesPage.noMatches")}

} + {/* Without the loading check, "no matches" flashes while the user is fetched */} + {loading &&

{t("myMatchesPage.loading")}

} + {!loading && matches.length === 0 && ( +

{t("myMatchesPage.noMatches")}

+ )} {matches.map((plant) => (
diff --git a/frontend/src/utils/isPreferenceMatch.ts b/frontend/src/utils/isPreferenceMatch.ts deleted file mode 100644 index b067cbaa..00000000 --- a/frontend/src/utils/isPreferenceMatch.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function isPreferenceMatch(trait: string, userPreferences: string[]) { - return userPreferences.includes(trait); -}