diff --git a/README.md b/README.md index 6884b24a..b11bccd5 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,9 @@ http://it2810-03.idi.ntnu.no/project2/ ## Core features - **Plant Match:** Shows plants one at a time, best matches for your preferences first. Click ✿ to like a plant or ✖ to skip it. -- **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, and Plant Match shows the plants that match the most of your preferences first. Without preferences, the plants come in random order. +- **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, and Plant Match shows the plants that match the most of your preferences first. Changing your preferences starts Plant Match over with a newly ordered deck. Without preferences, the plants come in random order. - **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants, with the number of matches shown above. Sort them by newest, oldest or name (A–Z or Z–A), and move between pages when there are many. The sort order is remembered for the session, also when you go to another page and back. You can also remove plants from the list. -- **Explore Plants:** Search the plant collection by common or scientific name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the number of results is shown above the plants. The results are split into pages, and you can jump straight to any page. The search, filters, sorting and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. Add a plant to My Matches with the ✿ button, and click it again to remove it. +- **Explore Plants:** Search the plant collection by common or scientific name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the number of results is shown above the plants. The results are split into pages, and you can jump straight to any page. The search, filters, sorting and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. Add a plant to My Matches with the ✿ button, which then turns into ✖, and click it again to remove it. - **Plant details:** Each plant card shows an image, the scientific name, a description and care information (watering, sunlight and care level). Flip the card to read more about the plant. - **Profile:** Your name, description, avatar and preferences are saved in the database. - **Plant Owner Test:** A short quiz that tells you what kind of plant owner you are. Each result has its own picture, which you can only get through the test, and you can save it as your profile picture. @@ -52,7 +52,7 @@ npm run install:all This installs the dependencies for the repo root, `backend` and `frontend`. -### 2. Create the backend `.env` file (in the VSC terminal window) +### 2. Create the backend `.env` file (in the VS Code terminal) ```bash cp backend/.env.example backend/.env @@ -60,7 +60,7 @@ cp backend/.env.example backend/.env The default values work as they are. `.env` is ignored by git and must never be committed. -### 3. Open an SSH tunnel to the database (in PC terminal window) +### 3. Open an SSH tunnel to the database (in a separate PC-terminal) Open a **separate terminal**, replace `` with your username and run the command below. @@ -70,7 +70,7 @@ After you enter your password, the command looks like it hangs. That means the t ssh -N -L 27017:localhost:27017 @it2810-03.idi.ntnu.no ``` -### 4. Start the app (in the VSC terminal window) +### 4. Start the app (in the VS Code terminal) From the repo root: @@ -92,11 +92,11 @@ Browser ──> Apache (port 80, /project2) serves the built frontend ### Backend -The backend runs with pm2, which keeps it running in the background and restarts it if it crashes or the VM reboots. The backend reads `MONGODB_URI=mongodb://localhost:27017`, `DB_NAME=iloveplants` and `PORT=3001` from `backend/.env` on the VM (see `.env.example`). If the backend stops, see [How to start the backend if it stops](../T03-Project-2/docs/architecture.md) . +The backend runs with pm2, which keeps it running in the background and restarts it if it crashes or the VM reboots. The backend reads `MONGODB_URI=mongodb://localhost:27017`, `DB_NAME=iloveplants` and `PORT=3001` from `backend/.env` on the VM (see `.env.example`). ### Frontend -The frontend runs on the VM by using Apache serves. It was copied to the folder Apache serves for `/project2`. The build reads `VITE_GRAPHQL_URL` from [frontend/.env.production](frontend/.env.production), so the deployed app sends its requests to the backend on port 3001 on the VM. +Apache serves the built frontend on the VM. The build was copied to the folder Apache serves for `/project2`. The build reads `VITE_GRAPHQL_URL` from [frontend/.env.production](frontend/.env.production), so the deployed app sends its requests to the backend on port 3001 on the VM. ### Database @@ -104,17 +104,9 @@ MongoDB is installed directly on the VM and only listens on `127.0.0.1`, so it c ## Testing -The application is tested on three levels: +The application is tested on three levels: component tests for the frontend (Vitest and React Testing Library), backend tests against an in-memory MongoDB (Vitest and mongodb-memory-server), and end-to-end and API tests with Playwright, which also check all pages against WCAG 2.1 AA with axe. None of the tests use the database on the VM, so they need neither the VPN nor the SSH tunnel. -- **Frontend:** Pages, components and hooks are tested with **Vitest** and **React Testing Library** in a simulated browser (**jsdom**). Calls to the backend are mocked, so the backend does not need to be running. -- **Backend:** The database connection and the GraphQL server are tested with **Vitest** against a real MongoDB that runs in memory (**mongodb-memory-server**). The tests never use the database on the VM, so they do not need the VPN or the SSH tunnel. MongoDB is downloaded once the first time the backend tests run. -- **End-to-end:** Longer user journeys and the GraphQL API are tested with **Playwright**, against the real backend and a built frontend with a separate in-memory test database. The tests run on both desktop and mobile, and check all pages against WCAG 2.1 AA with **axe**. - -See [tests.md](docs/tests.md) for what the test files cover, the e2e setup, the scenarios and what the tests found. - -### Run the tests - -Run these from the repo root: +Run the tests from the repo root: ```bash npm run test:frontend @@ -123,39 +115,20 @@ npm run test:e2e ``` The first time you run the e2e tests, install the browser with `npx playwright install chromium`. -Use `npm run test:e2e:ui` to step through the tests in Playwright's UI mode, or -`npm run test:e2e:headed` to watch them in a browser. - -### Run the tests with coverage - -```bash -# Coverage for only the frontend or only the backend -npm run test:frontend -- --coverage -npm run test:backend -- --coverage -``` - -The coverage table is printed in the terminal. A detailed report is saved in `frontend/coverage/index.html` and `backend/coverage/index.html`, which you can open in a browser to see which lines are not tested. ### Test coverage | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 96.7 % | 94.82 % | 92.92 % | 98.33 % | +| Frontend | 96.95 % | 92.75 % | 95.31 % | 97.67 % | | Backend | 100 % | 100 % | 100 % | 100 % | -- Frontend test coverage: - -Test coverage for the frontend - -- Backend test coverage: - -Test coverage for the backend +See [tests.md](docs/tests.md) for the test strategy, more ways to run the tests, how to run the tests with coverage and screenshots of the coverage reports, what the test files cover and what the tests found. ## Quality and design -See [quality.md](docs/quality.md) for Lighthouse results, testing, accessibility, design choices, sustainable web development and work practices. +See [quality.md](docs/quality.md) for work practices, accessibility, sustainable web development and design choices. ## Known issues -- Information on plant card does not translate to Norwegian. -- There is no login. The user id is stored in the browser, so the profile and matches belong to that browser and cannot be reached from other devices, and anyone who knows a user id can change that user, since the id is sent with every request. Login would solve both, and is a possible next step. +- The plant information on the plant cards is not translated to Norwegian. diff --git a/backend/package-lock.json b/backend/package-lock.json index b5a989db..a6dc9902 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -268,9 +268,9 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.29.11", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.11.tgz", - "integrity": "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz", + "integrity": "sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==", "dev": true, "license": "MIT", "engines": { @@ -288,9 +288,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.29.11", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.11.tgz", - "integrity": "sha512-OZ6+oaK7GMyg3IfCpj8JOmn8n+w2rJbDT0LLfVDTLb1ZFeKDh3AiNELgCMUw175IJHSkLl74hG0M0VLsvx+gag==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.13.tgz", + "integrity": "sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==", "dev": true, "license": "MIT", "dependencies": { @@ -351,6 +351,43 @@ "keyv": "^5.6.0" } }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -826,9 +863,9 @@ } }, "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.3.tgz", + "integrity": "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==", "dev": true, "license": "MIT", "engines": { @@ -1100,18 +1137,41 @@ "license": "MIT" }, "node_modules/@mongodb-js/saslprep": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.1.tgz", - "integrity": "sha512-D4CQtk9IwjCLAvCf1xvHEod3960q8XMUzfmdRU9qjUNlHnesGuTOvJcOTaPm9koZ1caUKA2aTbszZiAkcmSgmg==", + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.3.tgz", + "integrity": "sha512-aHGFvT95c82CoQ7hb6qXpz8Hcc5PJb3ZtQ+P01QDBbyQday0mjcrJPeNJOHCgWe0pGX0zKmKP+1mWi/I/BCX9Q==", "license": "MIT", "dependencies": { "sparse-bitfield": "^3.0.3" } }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, "node_modules/@oxc-project/types": { - "version": "0.155.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", - "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, "license": "MIT", "peer": true, @@ -1183,9 +1243,9 @@ "license": "BSD-3-Clause" }, "node_modules/@rolldown/binding-android-arm-eabi": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", - "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", "cpu": [ "arm" ], @@ -1201,9 +1261,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", - "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", "cpu": [ "arm64" ], @@ -1219,9 +1279,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", - "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", "cpu": [ "arm64" ], @@ -1237,9 +1297,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", - "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", "cpu": [ "x64" ], @@ -1255,9 +1315,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", - "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", "cpu": [ "x64" ], @@ -1273,9 +1333,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", - "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", "cpu": [ "arm" ], @@ -1291,9 +1351,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", - "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", "cpu": [ "arm64" ], @@ -1309,9 +1369,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", - "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", "cpu": [ "arm64" ], @@ -1327,9 +1387,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", - "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", "cpu": [ "ppc64" ], @@ -1345,9 +1405,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", - "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", "cpu": [ "s390x" ], @@ -1363,9 +1423,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", - "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", "cpu": [ "x64" ], @@ -1381,9 +1441,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", - "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", "cpu": [ "x64" ], @@ -1399,9 +1459,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", - "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", "cpu": [ "arm64" ], @@ -1416,10 +1476,30 @@ "node": "^20.19.0 || >=22.12.0" } }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", - "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", "cpu": [ "arm64" ], @@ -1435,9 +1515,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", - "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", "cpu": [ "x64" ], @@ -1453,13 +1533,25 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", - "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", "dev": true, "license": "MIT", "peer": true }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -1486,9 +1578,9 @@ "license": "MIT" }, "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", "dev": true, "license": "MIT" }, @@ -1506,9 +1598,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "26.6.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", - "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", "dev": true, "license": "MIT", "dependencies": { @@ -1531,17 +1623,17 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", - "integrity": "sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz", + "integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/type-utils": "8.72.1", - "@typescript-eslint/utils": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/type-utils": "8.72.2", + "@typescript-eslint/utils": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" @@ -1554,7 +1646,7 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.72.1", + "@typescript-eslint/parser": "^8.72.2", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } @@ -1570,16 +1662,16 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.1.tgz", - "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz", + "integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3" }, "engines": { @@ -1595,14 +1687,14 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.1.tgz", - "integrity": "sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz", + "integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.72.1", - "@typescript-eslint/types": "^8.72.1", + "@typescript-eslint/tsconfig-utils": "^8.72.2", + "@typescript-eslint/types": "^8.72.2", "debug": "^4.4.3" }, "engines": { @@ -1617,14 +1709,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.1.tgz", - "integrity": "sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz", + "integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1" + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1635,9 +1727,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.1.tgz", - "integrity": "sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz", + "integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==", "dev": true, "license": "MIT", "engines": { @@ -1652,15 +1744,15 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.1.tgz", - "integrity": "sha512-iY2wlmyrXJmx4yxUGP3aYCFF3cA/6ShddOKmLU2dx7LnEykbAM8WThlxZEfd1NddqceF6eJmZUayxx9oKIYNlg==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz", + "integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, @@ -1677,9 +1769,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.1.tgz", - "integrity": "sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz", + "integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==", "dev": true, "license": "MIT", "engines": { @@ -1691,16 +1783,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.1.tgz", - "integrity": "sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz", + "integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.72.1", - "@typescript-eslint/tsconfig-utils": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", + "@typescript-eslint/project-service": "8.72.2", + "@typescript-eslint/tsconfig-utils": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", @@ -1719,16 +1811,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.1.tgz", - "integrity": "sha512-5v5liypurJBFHCBNqh/RjsymAD+VWcE0djuGY/BUqp5fC3Qn+luWDEksjuTtWjPn6i5zQlUtkZCRG/CYG0yCkA==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz", + "integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1" + "@typescript-eslint/scope-manager": "8.72.2", + "@typescript-eslint/types": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1743,13 +1835,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.1.tgz", - "integrity": "sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz", + "integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.72.1", + "@typescript-eslint/types": "8.72.2", "eslint-visitor-keys": "^5.0.0" }, "engines": { @@ -1761,15 +1853,15 @@ } }, "node_modules/@vitest/coverage-v8": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.0.5.tgz", - "integrity": "sha512-4KpkGdIrSqBihx/JyP/e+S+IKB98etg1XDQiLAxksLfcShnwi1VReGeOT9NI43hLHbknosKp/1CCLn9Zgcs8mg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-5.1.0.tgz", + "integrity": "sha512-OY9aShBQG5KOIw2zCo9fDoCHI9RHliNHJ//nM7m6jGg41Hyke9JOGWmeMlK74xYErsxMoK8mIB3gAeEyFVA7LA==", "dev": true, "license": "MIT", "dependencies": { "@bcoe/v8-coverage": "^1.0.2", - "@vitest/istanbul-lib-coverage": "^1.0.2", - "@vitest/istanbul-lib-report": "^1.0.2", + "@vitest/istanbul-lib-coverage": "^2.1.0", + "@vitest/istanbul-lib-report": "^2.1.0", "ast-v8-to-istanbul": "^1.0.7", "magicast": "^0.5.5", "obug": "^3.0.0", @@ -1780,8 +1872,8 @@ "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "@vitest/browser": "5.0.5", - "vitest": "5.0.5" + "@vitest/browser": "5.1.0", + "vitest": "5.1.0" }, "peerDependenciesMeta": { "@vitest/browser": { @@ -1790,9 +1882,9 @@ } }, "node_modules/@vitest/istanbul-lib-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-1.0.2.tgz", - "integrity": "sha512-9J/JMwOf9AoJhAywhrn7ScKTL38hsWQP/qPG60OtaAFcQ5OXPwKsxZFlbnuCKmZ61m8/lGgHYnFpdyQZUvG/iA==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-coverage/-/istanbul-lib-coverage-2.1.0.tgz", + "integrity": "sha512-WOjuS+xcjSIy7ruYBQ+9BUcV7XZQ0FyVcbWbWxW9TRx/kLGx5SQaeFRIFDJxjNplb6YsT7SpKo2zuXXUo91OIQ==", "dev": true, "license": "MIT", "engines": { @@ -1800,27 +1892,27 @@ } }, "node_modules/@vitest/istanbul-lib-report": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-1.0.2.tgz", - "integrity": "sha512-gUsfXZJbzPamoIY5TvHFiMMoXESBrUMo+xqaj+rYrWI69+EnvRlYBlP96ZnHPY4vX8kyUpgAnFUCg5wZG/HkDQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@vitest/istanbul-lib-report/-/istanbul-lib-report-2.1.0.tgz", + "integrity": "sha512-+ZFta25nWtGCOBG9/IET8w1RO5Oawsd6H8Uf6AJ9EA/StFuKVtKAEJEJ6uRt84OH+T4YkI0ASmIHAhRA+0KVxw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/istanbul-lib-coverage": "1.0.2" + "@vitest/istanbul-lib-coverage": "2.1.0" }, "engines": { "node": ">=22" } }, "node_modules/@vitest/mocker": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", - "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", "dev": true, "license": "MIT", "dependencies": { "@jridgewell/trace-mapping": "0.3.31", - "@vitest/spy": "5.0.5", + "@vitest/spy": "5.1.0", "estree-walker": "^3.0.3", "magic-string": "^1.4.3" }, @@ -1841,9 +1933,9 @@ } }, "node_modules/@vitest/spy": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", - "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", "dev": true, "license": "MIT", "funding": { @@ -1851,12 +1943,12 @@ } }, "node_modules/@whatwg-node/promise-helpers": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@whatwg-node/promise-helpers/-/promise-helpers-2.0.1.tgz", - "integrity": "sha512-ziVgm01A9irPLVBaUFei64qp771BrDXldbv5pY6kgFgNtA+7zq8ux6nj/6w8bELGH/+Ttnc76ox04HIjU8nqvg==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@whatwg-node/promise-helpers/-/promise-helpers-2.0.2.tgz", + "integrity": "sha512-RKVGTBAuYfObHxUFjlTFmlDndmuXBxkN56yj3z6EQpNpT55R/xaMhTi4+9yXZ5UoDXbKLAsZHCP8ycoWHM/Vdg==", "license": "MIT", "dependencies": { - "tslib": "^2.6.3" + "tslib": "^2.9.1" }, "engines": { "node": ">=22.15.0" @@ -1923,9 +2015,9 @@ } }, "node_modules/ast-v8-to-istanbul": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.7.tgz", - "integrity": "sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", "dev": true, "license": "MIT", "dependencies": { @@ -1993,6 +2085,16 @@ "node": "18 || 20 || >=22" } }, + "node_modules/bare-buffer": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.7.1.tgz", + "integrity": "sha512-cIjZnSO+y89ykVX9x96OVnA6tGORBn7vGJ/e3PCbBHMEyfMNG/ixzOS0lLa6saMlWcs69bSKjxFyDwjK152OMg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "bare": ">=1.20.0" + } + }, "node_modules/bare-events": { "version": "2.9.2", "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz", @@ -2069,12 +2171,13 @@ } }, "node_modules/bare-url": { - "version": "2.5.5", - "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.5.tgz", - "integrity": "sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q==", + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.6.tgz", + "integrity": "sha512-iqkXHkW65De+BT14nHLiBFbNuJ/DdMrZaVNJ1IXPctpK6b1olUJ5Qmy8QBvwROajTiGztso2n82kFEvCsNG7Rg==", "dev": true, "license": "Apache-2.0", "dependencies": { + "bare-buffer": "^3.0.0", "bare-path": "^3.0.0" } }, @@ -2116,9 +2219,9 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2129,9 +2232,9 @@ } }, "node_modules/bson": { - "version": "7.3.3", - "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.3.tgz", - "integrity": "sha512-oz3LwE3qGEhTCSyhzQRLY3Bj1NLOsjFMf6tcmY5J8M+3R7EVcmoBfSHWvjUK3yXCLDUsGpIuB3aQL4nDZ1EV/g==", + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/bson/-/bson-7.3.4.tgz", + "integrity": "sha512-eb33j2Ha6xgygjJ8bhI3sYaI9cLAbSaopZLRJQ5/rxk32XyBSoVVcbeHIzVGJx1SyQpyyoElkoEZgQrg+RVVoA==", "license": "Apache-2.0", "engines": { "node": ">=20.19.0" @@ -2352,12 +2455,12 @@ } }, "node_modules/dotenv": { - "version": "18.0.9", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.9.tgz", - "integrity": "sha512-3fVOW4cB02R066PUSwn8O4TJyz9NckQl7F81blIbaq9jKBm2tSmOKky7ZHIXzGvkVPXCSn6jkpziBPZdGFs8Tw==", + "version": "18.0.10", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.10.tgz", + "integrity": "sha512-89FAA1xchzK2mxVWdr5F/0rldwiueXs6zJM86rO66EzekR1iBdiXRthyG+m5GvkJaFH3C2LESzamTkgndmLT2A==", "license": "BSD-2-Clause", "bin": { - "dotenv": "dist/index.cjs" + "dotenv": "dist/cli.cjs" }, "engines": { "node": ">=12" @@ -2387,12 +2490,16 @@ "license": "MIT" }, "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", + "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", "license": "MIT", "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/es-define-property": { @@ -2494,9 +2601,9 @@ } }, "node_modules/eslint": { - "version": "10.13.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.13.0.tgz", - "integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==", + "version": "10.14.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.14.0.tgz", + "integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==", "dev": true, "license": "MIT", "workspaces": [ @@ -2509,7 +2616,7 @@ "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", - "@humanfs/node": "^0.16.6", + "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", @@ -2530,7 +2637,7 @@ "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.5", + "minimatch": "^10.2.6", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, @@ -2826,9 +2933,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", - "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", "dev": true, "funding": [ { @@ -2936,9 +3043,9 @@ } }, "node_modules/globals": { - "version": "17.13.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz", - "integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==", + "version": "17.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", + "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", "dev": true, "license": "MIT", "engines": { @@ -2961,9 +3068,9 @@ } }, "node_modules/graphql": { - "version": "16.14.2", - "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz", - "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==", + "version": "16.15.0", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.15.0.tgz", + "integrity": "sha512-32kz9FecohDiC/tgcViwnRXM7HFBVTPiW7pHO+DikKOI5KjhU/jNULOReXsrFqt2WAYbE9xFXsTffJw6iTO8qw==", "license": "MIT", "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" @@ -3586,9 +3693,9 @@ } }, "node_modules/make-dir/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "dev": true, "license": "ISC", "bin": { @@ -3665,9 +3772,9 @@ } }, "node_modules/mongodb": { - "version": "7.7.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.7.0.tgz", - "integrity": "sha512-XG1xXEqyouAV8GCb3PuRaujofeXKpAJAPvXYWZgHl6Dz4QHSJ1nRLl0+GpqaLTwKvC0RFE9truOur34RNFY1nw==", + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-7.8.0.tgz", + "integrity": "sha512-p2NKagbQ41+daACG/ZSvhTzeAo+DoEyWE9Cmpf/SyP3pTC43+X0mwKE/44PpKtCxp5wOxnXz+t2pXEZRSkt9Yg==", "license": "Apache-2.0", "dependencies": { "@mongodb-js/saslprep": "^1.5.0", @@ -4200,9 +4307,9 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.17.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.0.tgz", - "integrity": "sha512-5LK5BZ2XDHMvcUJaf0CQ5HL3aVgKbpklvByC7qLSxYkfE8COEEbJg5xCHWCTqzqi0Gs4Jn5Mv5v3R38W6edscA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", @@ -4240,14 +4347,14 @@ } }, "node_modules/rolldown": { - "version": "1.2.15", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", - "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "@oxc-project/types": "=0.155.0", + "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -4257,21 +4364,22 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm-eabi": "1.2.15", - "@rolldown/binding-android-arm64": "1.2.15", - "@rolldown/binding-darwin-arm64": "1.2.15", - "@rolldown/binding-darwin-x64": "1.2.15", - "@rolldown/binding-freebsd-x64": "1.2.15", - "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", - "@rolldown/binding-linux-arm64-gnu": "1.2.15", - "@rolldown/binding-linux-arm64-musl": "1.2.15", - "@rolldown/binding-linux-ppc64-gnu": "1.2.15", - "@rolldown/binding-linux-s390x-gnu": "1.2.15", - "@rolldown/binding-linux-x64-gnu": "1.2.15", - "@rolldown/binding-linux-x64-musl": "1.2.15", - "@rolldown/binding-openharmony-arm64": "1.2.15", - "@rolldown/binding-win32-arm64-msvc": "1.2.15", - "@rolldown/binding-win32-x64-msvc": "1.2.15" + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, "node_modules/safe-buffer": { @@ -4301,9 +4409,9 @@ "license": "MIT" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -4532,9 +4640,9 @@ } }, "node_modules/tinybench": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", - "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "dev": true, "license": "MIT", "engines": { @@ -4627,9 +4735,9 @@ } }, "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "license": "0BSD" }, "node_modules/tsx": { @@ -4724,16 +4832,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.1.tgz", - "integrity": "sha512-3Li9FfPmQp45nxEtFD1ZCrYFI3cYK5kpyNtmm1H7lMagm8u9sy6PTjy3ytwQZs7KNukOyKFHAZ6z6GjYFeaeXw==", + "version": "8.72.2", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.2.tgz", + "integrity": "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.72.1", - "@typescript-eslint/parser": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1" + "@typescript-eslint/eslint-plugin": "8.72.2", + "@typescript-eslint/parser": "8.72.2", + "@typescript-eslint/typescript-estree": "8.72.2", + "@typescript-eslint/utils": "8.72.2" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4783,17 +4891,17 @@ } }, "node_modules/vite": { - "version": "8.3.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", - "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", - "postcss": "^8.5.30", - "rolldown": "~1.2.14", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", "tinyglobby": "^0.2.17" }, "bin": { @@ -4862,14 +4970,14 @@ } }, "node_modules/vitest": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", - "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", "dev": true, "license": "MIT", "dependencies": { "@types/chai": "^5.2.2", - "@vitest/mocker": "5.0.5", + "@vitest/mocker": "5.1.0", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", @@ -4895,12 +5003,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "5.0.5", - "@vitest/browser-preview": "5.0.5", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", - "@vitest/coverage-istanbul": "5.0.5", - "@vitest/coverage-v8": "5.0.5", - "@vitest/ui": "5.0.5", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" diff --git a/backend/src/db.ts b/backend/src/db.ts index 089ba591..e19eccf0 100644 --- a/backend/src/db.ts +++ b/backend/src/db.ts @@ -3,7 +3,7 @@ import { MongoClient } from "mongodb"; if (!process.env.MONGODB_URI) { throw new Error( - "MONGODB_URI mangler. Kopier .env.example til .env og fyll inn.", + "MONGODB_URI is missing. Copy .env.example to .env and fill it in.", ); } diff --git a/backend/src/queryBuilders.ts b/backend/src/queryBuilders.ts index edf376df..39d7b74e 100644 --- a/backend/src/queryBuilders.ts +++ b/backend/src/queryBuilders.ts @@ -4,21 +4,19 @@ import type { ExplorePlantsArgs, PlantDoc } from "./types.js"; // Helpers for searching, filtering and sorting plants // Escape user input so it can't be interpreted as regex -export const escapeRegex = (s: string) => - s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // Filter values come in as "full_sun", the database has "full sun" -export const normalize = (s: string) => - escapeRegex(s.replace(/_/g, " ").trim()); +const normalize = (s: string) => escapeRegex(s.replace(/_/g, " ").trim()); // Order from low to high. -export const SORT_ORDERS = { +const SORT_ORDERS = { watering: ["minimum", "average", "frequent"], careLevel: ["low", "medium", "high"], }; // Position in the order list, unknown or missing values go last -export const rankOf = (order: string[], value: unknown): Document => ({ +const rankOf = (order: string[], value: unknown): Document => ({ $let: { vars: { i: { $indexOfArray: [order, value] } }, in: { $cond: [{ $lt: ["$$i", 0] }, 999, "$$i"] }, @@ -142,7 +140,8 @@ const sunlightIncludes = (text: string): Document => ({ }); // How each preference id maps to the plant attributes. Must match -// frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.tsx. +// frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx +// and the preference ids in frontend/src/pages/profile/ProfilePage.tsx. // 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 index 691f069f..ecdd4101 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -27,8 +27,8 @@ import type { const NAME_MAX_LENGTH = 40; const DESCRIPTION_MAX_LENGTH = 100; -// Must match the avatar ids in frontend/src/pages/profile/Profile.tsx and the -// result ids in frontend/src/pages/plantOwnerTest/plantownertest.ts +// 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", @@ -47,18 +47,23 @@ const PROFILE_PICTURES = [ "gardenExpert", ]; -// Must match the preference ids in frontend/src/pages/profile/Profile.tsx -const PREFERENCES = [ - "minimumWater", - "averageWater", - "frequentWater", - "fullSun", - "partShade", - "filteredShade", - "easyCare", - "mediumCare", - "hardCare", -]; +// 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"); @@ -125,6 +130,7 @@ export const resolvers = { ): 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] : []; @@ -139,7 +145,7 @@ export const resolvers = { // the last one stopped, so the whole stack is in score order. const orderStages: Document[] = preferences.length === 0 - ? [{ $sample: { size: args.limit } }] + ? [{ $sample: { size: limit } }] : [ { $addFields: { @@ -148,7 +154,7 @@ export const resolvers = { }, }, { $sort: { matchScore: -1, shuffle: 1 } }, - { $limit: args.limit }, + { $limit: limit }, ]; const docs = await plants @@ -183,8 +189,8 @@ export const resolvers = { .aggregate>([ { $match: filter }, ...buildSortStages(args.sort), - { $skip: args.offset }, - { $limit: args.limit }, + { $skip: clampOffset(args.offset) }, + { $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) }, ]) .toArray(), plants.countDocuments(filter), @@ -224,8 +230,8 @@ export const resolvers = { .aggregate>([ { $match: filter }, ...buildMatchSortStages(args.sort, matchedPlantIds), - { $skip: args.offset }, - { $limit: args.limit }, + { $skip: clampOffset(args.offset) }, + { $limit: clampLimit(args.limit, DEFAULT_PAGE_SIZE) }, ]) .toArray(), plants.countDocuments(filter), diff --git a/backend/src/server.ts b/backend/src/server.ts index 7992389d..c26a8983 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -14,4 +14,4 @@ const { url } = await startStandaloneServer(server, { listen: { port: Number(process.env.PORT) || 3001 }, }); -console.log(`Server Running at:${url}`); +console.log(`Server running at: ${url}`); diff --git a/backend/src/types.ts b/backend/src/types.ts index bfc6a0d9..b0e4f0a8 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -26,7 +26,8 @@ export interface Plant { } export interface GetPlantsArgs { - limit: number; + // Null if the client sends null explicitly, see clampLimit in resolvers.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. excludeIds?: string[] | null; @@ -40,8 +41,8 @@ export interface ExplorePlantsArgs { watering?: string; careLevel?: string; sort?: string; - limit?: number; - offset?: number; + limit?: number | null; + offset?: number | null; } // The shape of a user document in MongoDB. _id is added by MongoDB. @@ -89,6 +90,6 @@ export interface UserMatchArgs extends UserIdArgs { export interface MyMatchesArgs extends UserIdArgs { sort?: string; - limit: number; - offset: number; + limit?: number | null; + offset?: number | null; } diff --git a/backend/tests/db.test.ts b/backend/tests/db.test.ts index 435245a0..c0dd21f9 100644 --- a/backend/tests/db.test.ts +++ b/backend/tests/db.test.ts @@ -64,7 +64,7 @@ describe("db", () => { vi.stubEnv("MONGODB_URI", uri); await expect(importDb()).rejects.toThrow( - "MONGODB_URI mangler. Kopier .env.example til .env og fyll inn.", + "MONGODB_URI is missing. Copy .env.example to .env and fill it in.", ); }, ); diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index c99392c1..5d4b8661 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -172,7 +172,7 @@ describe("starting the server", () => { expect(options.listen.port).toBe(3001); expect(console.log).toHaveBeenCalledWith( - "Server Running at:http://localhost:3001/", + "Server running at: http://localhost:3001/", ); }); @@ -419,6 +419,32 @@ describe("plants", () => { }); }); + it("keeps a too small limit and a negative offset within valid bounds", async () => { + // limit 0 and a negative offset would make MongoDB throw, so they become + // the smallest valid values instead + expect(await explore({ limit: 0, offset: -5 })).toEqual({ + names: ["Aloe"], + totalCount: 6, + }); + // null (sent explicitly) gives the default page from the start + expect((await explore({ limit: null, offset: null })).names).toHaveLength( + 6, + ); + }); + + it("never returns more than 50 plants in one request", async () => { + const many = Array.from({ length: 55 }, (_, i) => ({ + commonName: `Extra ${String(i).padStart(2, "0")}`, + })); + await insertPlants(...many); + + expect((await explore({ limit: 1000 })).names).toHaveLength(50); + const result = await execute<{ getPlants: { id: string }[] }>( + "query { getPlants(limit: 1000) { id } }", + ); + expect(result.data!.getPlants).toHaveLength(50); + }); + it.each([ ["name_desc", ["Fern (giant)", "Fern", "Daisy", "Cactus", "Basil", "Aloe"]], // Unknown values go last diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 24c146de..87fbd38c 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -12,7 +12,7 @@ AI was used as an assistant throughout the development of the web application. T - **Generating pictures:** the avatar pictures on the profile page and the placeholder picture for plants without an image were made with AI. - **Refactoring:** splitting large files containing a lot of logic into smaller components and hooks. -## Examples +## Concrete examples of AI use ### The seed script diff --git a/docs/architecture.md b/docs/architecture.md index 153b1993..e556b12c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,11 +20,12 @@ Perenual API → seedDataFetch.js ─┐ │ GraphQL over HTTP (/graphql) │ Frontend: React + Apollo Client - (localStorage: userId, URL: Explore state, - sessionStorage: My Matches sort order) + (localStorage: userId, theme, language, + URL: Explore state, + sessionStorage: My Matches sort, Plant Match deck) ``` -The plant data is fetched from the Perenual API once and stored in our own database. The data was loaded using the seedDataFetch.js file. About 120 plants where loaded. The number is an estimate as we have not verified each plants response to the fetch operation. The frontend never talks to the database directly. All data goes through the GraphQL API in the backend: +The plant data was fetched from the Perenual API once with the script `seedDataFetch.js` and stored in our own database, which has 120 plants. The frontend never talks to the database directly. All data goes through the GraphQL API in the backend: 1. The frontend sends a GraphQL request to the backend (for example `explorePlants` with search, filters and pagination, or `addUserMatch` when the user likes a plant). 2. Apollo Server runs the matching resolver, which reads from or writes to the `plants` or `users` collection in MongoDB. @@ -39,18 +40,19 @@ The frontend is built with React and TypeScript (Vite). - **Routing:** Routes are defined in `AppRoutes.tsx` with React Router, and the app is served under the base path `/project2/`. Vite defines this base in `frontend/vite.config.ts`; `HashRouter` provides the client-side routes, including Explore query parameters after the hash. All pages except the start page are lazy-loaded. Any path that does not match a route shows the 404 page, and the header shows the "Page not found" title for it. - | Route | Page | Purpose | - | ----------------- | ---------------- | ---------------------------------------------------------------- | - | `/` | `PlantMatchPage` | Swipe through random plants (`getPlants`) and match with them | - | `/explorePlants` | `ExplorePlants` | Search, filter, sort and paginate all plants (`explorePlants`) | - | `/my-matches` | `MyMatchesPage` | List, sort, paginate and remove the user's matches (`myMatches`) | - | `/profile` | `Profile` | Edit name, description, profile picture and preferences | - | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | - | `*` | `NotFound` | 404 page for unknown paths, with a link back to Plant Match | + | Route | Page | Purpose | + | ----------------- | -------------------- | ------------------------------------------------------------------------ | + | `/` | `PlantMatchPage` | Swipe through preference-ranked plants (`getPlants`) and match with them | + | `/explorePlants` | `ExplorePlantsPage` | Search, filter, sort and paginate all plants (`explorePlants`) | + | `/myMatches` | `MyMatchesPage` | List, sort, paginate and remove the user's matches (`myMatches`) | + | `/profile` | `ProfilePage` | Edit name, description, profile picture and preferences | + | `/plantOwnerTest` | `PlantOwnerTestPage` | A quiz whose result can be set as the profile picture | + | `*` | `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)). - **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`). `useSessionState` stores state in `sessionStorage`, for example the sort order on My Matches. +- `usePlantDeck` keeps the remaining Plant Match cards in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored. - **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `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 (✖), and `ErrorMessage` shows a short error message. The components take already translated texts, so they can be used on other pages. - **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). - **Shared types:** `Plant`, `User` and `Preference` are defined in `types/`. @@ -77,7 +79,7 @@ graphql/ Each file also exports the TypeScript type for the result of its operations (for example `GetPlantsData` and `ExplorePlantsData`). The shared `Plant` and `User` types are in `types/`. Pages, hooks and the context only import the operations they use, for example `usePlantDeck` imports `GET_PLANTS` and `useMatchedPlants` imports `ADD_USER_MATCH` and `REMOVE_USER_MATCH`. -Earlier the operations were spread across three places: the user operations in `context/userQueries.ts`, `EXPLORE_PLANTS` next to the Explore Plants page and `GET_PLANTS` inside the `usePlantDeck` hook. We moved them into one folder after feedback, and because one of our main goals is that the app should scale: +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. @@ -89,7 +91,7 @@ We considered keeping each query next to the component that uses it (colocation) ### Apollo cache -All user queries and mutations ask for the same `UserFields` fragment, so when one page changes the user (for example adds a match), Apollo's cache updates the user on every page at once. Changing the profile picture uses an optimistic response, so the new picture is shown before the server has answered. The fragment only has the ids of the matched plants (`matchedPlantIds`), so the user stays small however many matches there are. Adding and removing a match returns the whole list of ids, so the cache replaces it instead of merging it with the old list. My Matches fetches its plants with its own `myMatches` query, which is fetched again when a match is added or removed, and every time the page is opened. +All user queries and mutations ask for the same `UserFields` fragment, so when one page changes the user (for example adds a match), Apollo's cache updates the user on every page at once. Changing the profile picture uses an optimistic response, so the new picture is shown before the server has answered. The fragment only has the ids of the matched plants (`matchedPlantIds`), so the user stays small however many matches there are. Adding and removing a match returns the whole list of ids, so the cache replaces it instead of merging it with the old list. My Matches fetches its plants with its own `myMatches` query. When a match is added or removed, the saved My Matches pages are removed from the cache, so My Matches is fetched again at once if it is open, or the next time it is opened, and never shows an old list. ## Backend: GraphQL with Apollo Server @@ -100,7 +102,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f - `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. -- `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#scalability)). +- `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). @@ -108,12 +110,12 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f **Queries** -| Query | Description | -| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. | -| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate. Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | -| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | -| `myMatches(userId, sort, limit = 12, offset = 0): PlantPage!` | Returns one page of the user's matched plants and `totalCount`. Sort can be `oldest`, `name_asc` or `name_desc`; the default is newest first. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. | +| Query | Description | +| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants (at most 50) for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. | +| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate (`limit` is kept between 1 and 50, and a negative `offset` counts as 0). Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | +| `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | +| `myMatches(userId, sort, limit = 12, offset = 0): PlantPage!` | Returns one page of the user's matched plants and `totalCount` (`limit` and `offset` are kept within the same bounds as in `explorePlants`). Sort can be `oldest`, `name_asc` or `name_desc`; the default is newest first. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. | **Mutations** @@ -137,11 +139,11 @@ Invalid input from the client gives a GraphQL error with the code `BAD_USER_INPU ## Database: MongoDB -The database `iloveplants` has two collections: `plants` and `users`. Both the plant and user information was chosen to be stored in MongoDB to make the app scalable. This means that more plants and users can be added, and each of these objects can have more attributes than if other storage options, such as local and session storage, had been chosen. MongoDB was also chosen because of its flexible schema. +The database `iloveplants` has two collections: `plants` and `users`. We chose to store both the plants and the users in MongoDB to make the app scalable. More plants and users can be added, and each of them can have more fields than if browser storage, such as `localStorage` or `sessionStorage`, had been used. MongoDB was also chosen because of its flexible schema. ### The `plants` collection -One document per plant species. The documents were written by `seedDataFetch.js` with data fetched from the Perenual API. The running app only reads them. There is a unique index on `perenualId`, used by the seed script, and an index on `commonName` and `_id` for sorting by name (see [Scalability](#scalability)). +One document per plant species. The documents were written by `seedDataFetch.js` with data fetched from the Perenual API. The running app only reads them. There is a unique index on `perenualId`, used by the seed script, and an index on `commonName` and `_id` for sorting by name (see [Scalability](#design-choices-made-for-scalability)). | Field | Type | Source / description | Exposed in GraphQL as | | -------------------- | -------------- | ------------------------------------------------------------------------------------ | --------------------- | @@ -190,16 +192,16 @@ 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 (`Profile.tsx` and `plantownertest.ts`). +A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers.ts` and must match the ids used in the frontend (`ProfilePage.tsx` and `plantOwnerTest.ts`). The preference ids are the keys of `PREFERENCE_MATCHERS` in `queryBuilders.ts`, so the list used for validation and the list used for scoring cannot get out of sync. The avatar id `snake-plant` is kept as it is, since it is already stored on existing users. 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. -### Why MongoDB +### Why MongoDB was used We store the data in MongoDB, a document database. It is a good fit for this data: -- **The data is already documents.** Perenual returns JSON with nested objects and lists (such as sunlight requirements and scientific names). Each plant becomes one document with almost the same shape, so there is no need to split it into several tables and join them back together. This limits the cleaning needed. -- **Plants have different fields.** Some plants have information that others lack. A document database handles optional fields naturally, without many empty columns. +- **The data from Perenual is already documents.** Perenual returns JSON with nested objects and lists (such as sunlight requirements and scientific names). Each plant becomes one document with almost the same shape, so there is no need to split it into several tables and join them back together. This limits the cleaning needed. +- **Plants have different fields.** Some plants have information that others lack. A document database handles optional fields naturally, without many empty columns, which would be inefficient. - **It is simple to update.** The seed script first inserts a basic entry for each plant, and later adds details to the same document (an upsert keyed on `perenualId`). User updates are single atomic operations such as `$set`, `$addToSet` and `$pull`. The trade-off in using a NoSQL database such as MongoDB compared to a relational database such as MySQL is that it does not enforce relationships between collections. That matters little here: the plant collection is read-only for the app, and the only reference between the collections is `users.matchedPlantIds`. `addUserMatch` checks that the plant exists before storing the id, and `myMatches` skips ids that no longer point to a plant. @@ -211,9 +213,9 @@ MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be r | Where | What | Why | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | -| `localStorage` | Only the key `userId` | Lets the browser find its user again on the next visit, without a login | +| `localStorage` | The user id (`userId`), the theme (`theme`) and the language (`language`) | Lets the browser find its user again on the next visit without a login, and keeps the chosen theme and language between visits | | URL parameters | Explore search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`) via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | -| `sessionStorage` | The sort order on My Matches (`myMatches.sort`), and other features that use `useSessionState`, such as the language switcher | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | +| `sessionStorage` | The sort order on My Matches (`myMatches.sort`) and the cards left on Plant Match (`plantMatch.deck`) | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | | Apollo in-memory cache | Query results (plants and the current user) | Avoids asking the backend again for data the app already has, and keeps all pages in sync | | React state | Short-lived UI state, such as the current plant on the match page and unsaved profile text | Only matters while the component is shown | @@ -221,9 +223,9 @@ User data used to be stored in `localStorage`. `UserProvider` now removes the ol When the app starts, `UserProvider` reads `userId` from `localStorage` and runs `getUser`. If there is no id, or the id no longer exists in the database, it runs `createUser` and saves the new id. If the backend cannot be reached, it does not create a new user, and the app still works without saved data. -## Scalability +## Design choices made for scalability -- **Use of MongoDB over local storage.** Local storage is only used for the `userId`, while the rest of the user information is stored in MongoDB. This makes it easy to add more user information later. Local 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, 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` and the chosen theme and language, 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. - **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. @@ -236,12 +238,15 @@ When the app starts, `UserProvider` reads `userId` from `localStorage` and runs - **GraphQL operations in one folder.** All queries, mutations and fragments are in `frontend/src/graphql/`, grouped by domain, with shared fragments for the plant and user fields. New features get their own folder, and a schema change only has to be followed up in one place (see [GraphQL operations](#graphql-operations-in-the-frontend)). - **Small user documents and responses.** Matches are stored as plant ids, and user updates only touch one document. Only the ids are sent with the user, and My Matches fetches one page of plants at a time, so the responses do not grow with the number of matches. - **Less traffic from the client.** Search input is debounced, results are cached by Apollo, and pages other than the start page are lazy-loaded. -- **Limitation: plant images are stored as base64 in the database.** Each plant image is stored as a base64 data URI in `imageData` (see [Data source: the Perenual API](#data-source-the-perenual-api)), instead of as an image file on the VM. This limits how well the solution scales: + +## Limitations of the architecture + +- **Plant images are stored as base64 in the database.** Each plant image is stored as a base64 data URI in `imageData` (see [Data source: the Perenual API](#data-source-the-perenual-api)), instead of as an image file on the VM. This limits how well the solution scales: - **More space:** Base64 turns every 3 bytes into 4 characters, so an image takes about 33% more space than the same file on disk. This makes the database larger, and the difference grows with every plant that is added. - **Larger responses:** The resolver returns `imageData` in the `imageURL` field, so the images are sent inside the GraphQL response. A page of 12 plants therefore contains 12 full images, and the response cannot be returned before all of them are included. The browser cannot start loading one image while it waits for the rest, or skip images that are not visible. - **Weaker caching:** Image files could be cached by the browser and Apache, and reused across pages and visits. The base64 strings are instead stored in the Apollo cache together with the rest of the data, and are downloaded again each time a query is not answered from the cache. - **Why we chose it anyway:** The image URLs from Perenual expire after 24 hours, so the images had to be stored by us. Storing them in the same document as the rest of the plant data was the simplest solution: the seed script writes everything to MongoDB in one step, the backend and the frontend need no extra setup to serve or find image files, and the image always belongs to the right plant, since the plant and its image are stored and deleted together. With the number of plants in our database and with a reasonable number of more, the extra space and larger responses are acceptable, and pagination keeps each response limited to one page. + **Why we chose it anyway:** The image URLs from Perenual expire after 24 hours, so the images had to be stored by us. Storing them in the same document as the rest of the plant data was the simplest solution: the seed script writes everything to MongoDB in one step, the backend and the frontend need no extra setup to serve or find image files, and the image always belongs to the right plant, since the plant and its image are stored and deleted together. With the 120 plants in our database, and a reasonable number more, the extra space and larger responses are acceptable, and pagination keeps each response limited to one page. **How it could be improved:** If the collection grows much larger, the images should be stored as files on the VM (or in a separate file storage) and served by Apache, with only the path stored in MongoDB. The images would then take less space, be cached by the browser, and load separately from the plant data. @@ -281,16 +286,29 @@ T03-Project-2/ │ ├── seedDataFetch.js # Script that fetches plant data from the Perenual API and stores it in MongoDB │ └── .env.example # Template for required environment variables ├── docs/ # Project documentation (architecture, tests, quality, AI usage), media/ has the coverage images -├── e2e/ # Playwright e2e and API tests, test data (fixtures/) and the in-memory test database +├── e2e/ # Playwright e2e and API tests +│ ├── fixtures/ # The 20 test plants +│ ├── helpers/ # Shared helpers for GraphQL requests and navigation +│ ├── api*.spec.ts # API tests, GraphQL requests straight to the backend +│ ├── ui*.spec.ts # UI tests in the browser, including accessibility (uiAccessibility.spec.ts) +│ ├── globalSetup.ts # Empties the test database and adds the test plants before the tests +│ ├── startTestDb.mjs # Starts the in-memory test database +│ └── testDb.ts # Shared settings for the test database (name, port, URI) ├── frontend/ │ ├── src/ │ │ ├── assets/ # Static images │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file │ │ ├── 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, useSessionState, useProfile, useMatchedPlants, usePlantDeck) +│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck, useDismissibleTooltip) │ │ ├── i18n/ # Translation setup and locale files (no, en) -│ │ ├── pages/ # One folder per page/route with a matching .css file +│ │ ├── pages/ # One folder per page/route, each with a Page.tsx and a matching .css file +│ │ │ ├── explorePlants/ # ExplorePlantsPage +│ │ │ ├── myMatches/ # MyMatchesPage +│ │ │ ├── notFound/ # NotFoundPage +│ │ │ ├── plantMatch/ # PlantMatchPage +│ │ │ ├── plantOwnerTest/ # PlantOwnerTestPage, and plantOwnerTest.ts with the questions and results +│ │ │ └── profile/ # ProfilePage │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) │ │ ├── types/ # Shared TypeScript types (Plant, User, Preference) │ │ ├── AppRoutes.tsx # Route definitions @@ -302,15 +320,33 @@ T03-Project-2/ └── README.md # Project overview, how to run, test and deploy the application ``` +### Naming conventions + +- **PascalCase** for React components and their files (`PlantCard.tsx`, `SortMenu.css`), and for TypeScript types (`Plant`, `PlantCardProps`). Every page component ends in `Page` (`ExplorePlantsPage`), and test files are named after what they test (`ExplorePlantsPage.test.tsx`). +- **camelCase** for variables, functions, hooks (`useMatchedPlants`), folders, routes (`/myMatches`), translation sections and keys (`explorePlantsPage.search`), and all other files, including images and e2e helpers (`snakePlant.png`, `globalSetup.ts`). +- **UPPER_SNAKE_CASE** for module-level constants that never change (`ROUTES`, `PAGE_SIZE`, `GET_PLANTS`, `LANGUAGE_STORAGE_KEY`). + ## How to start the backend if it stops -On the VM, the backend runs in pm2 under the name `plants-backend`, as the user `alexajah`, from `/home/alexajah/T03-Project-2/backend`. pm2 restarts it if it crashes or the VM reboots. The backend reads `MONGODB_URI=mongodb://localhost:27017`, `DB_NAME=iloveplants` and `PORT=3001` from `backend/.env` on the VM (see `.env.example`). +On the VM, the backend runs in pm2 under the name `plants-backend`, as the user `alexajah`, from `/home/alexajah/T03-Project-2/backend`. pm2 restarts it if it crashes or the VM reboots. + +The backend reads the following variables from `backend/.env` on the VM (see `.env.example`): + +- `MONGODB_URI=mongodb://localhost:27017` +- `DB_NAME=iloveplants` +- `PORT=3001` + +Log in with: + +```bash +ssh @it2810-03.idi.ntnu.no +``` -Log in with `ssh @it2810-03.idi.ntnu.no`. If you are not `alexajah` put `sudo -u alexajah` in front of the pm2 commands, since pm2 only shows the processes of the user who started them. +If you are not `alexajah`, put `sudo -u alexajah` in front of the pm2 commands, since pm2 only shows the processes of the user who started them. ```bash -pm2 list # is plants-backend online? -pm2 restart plants-backend # start it again if it is not +pm2 list # is plants-backend online? +pm2 restart plants-backend # start it again if it is not ``` -If the logs show that the backend cannot connect to MongoDB, the database has stopped, and must be started before the backend is restarted. +If the logs show that the backend cannot connect to MongoDB, the database has stopped and must be started before the backend is restarted. diff --git a/docs/media/coverageBackend.png b/docs/media/coverageBackend.png index b93dc85e..be1fcb4b 100644 Binary files a/docs/media/coverageBackend.png and b/docs/media/coverageBackend.png differ diff --git a/docs/media/coverageFrontend.png b/docs/media/coverageFrontend.png index 0adc9625..c62a5d16 100644 Binary files a/docs/media/coverageFrontend.png and b/docs/media/coverageFrontend.png differ diff --git a/docs/quality.md b/docs/quality.md index 17ea99f4..9f805ddd 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -1,18 +1,18 @@ # Quality -This document describes how we have worked to ensure the quality of the application through work practices, testing, accessibility, sustainable web development and design choices. +This document describes how we have worked to ensure the quality of the application through work practices, accessibility, sustainable web development and design choices. Testing is described in its own document, [tests.md](tests.md), which covers the test strategy, how to run the tests, the coverage and what the tests found. ## Quality aspects - Work practices: [Work practices](#work-practices) -- Testing: [Testing](#method-behind-testing) +- Testing: [tests.md](tests.md) - Accessibility: [Accessibility](#accessibility) - Sustainable web development: [Sustainable web development](#sustainable-web-development) - Design choices: [Design choices](#design-choices) ### Continuous integration -GitHub Actions ([.github/workflows/ci.yml](../.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, and runs lint, tests for both the backend and the frontend. +GitHub Actions ([.github/workflows/ci.yml](../.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, runs lint, tests and a build for both the backend and the frontend, and runs the end-to-end tests. ## Work practices @@ -23,50 +23,35 @@ GitHub Actions ([.github/workflows/ci.yml](../.github/workflows/ci.yml)) runs on 2. **All review comments had to be resolved.** We addressed each comment by making the necessary changes or explaining why no changes were needed, and marked the conversation as resolved. 3. **New commits after approval required another review.** Pushing new commits dismissed the previous approval, ensuring that the code being merged had been reviewed in its final state. -- In addition to writing automated tests, we manually tested the application throughout development to identify issues and verify its functionality. +- In addition to writing automated tests, we tested the application manually throughout development, on both desktop and mobile (see [Manual testing](tests.md#manual-testing)). - As part of our code review process, team members checked out pull requests locally and tested the new functionality before approving changes. This helped us verify that changes worked as expected in practice, rather than relying solely on code review. -## Method behind testing - -Automated tests help ensure that the application works as intended and that new changes do not break existing functionality. The application is tested on three levels: component tests check each part of the frontend in isolation, backend tests check every GraphQL query and mutation against a real database, and end-to-end tests check that the whole application works together the way a user experiences it, on both desktop and mobile. - -All tests run in GitHub Actions on every pull request, so a pull request that breaks a test cannot be merged unnoticed. The end-to-end tests also check all pages against WCAG 2.1 AA, which helped us find and fix accessibility problems that the other tests did not catch. - -See [tests.md](tests.md) for the test strategy, the coverage, the results and how to run the tests. - ## Accessibility The app includes the following accessibility features: - **Page structure:** Semantic `header`, `nav`, `main` and `article` elements organise the content. Sidebar navigation has an accessible name, and the current page is marked with `aria-current="page"`. -- **Keyboard controls:** Navigation uses links, and actions use native buttons. Sidebar links, pagination, sorting controls and avatar options have explicit focus styles. Plant Match instructions are also shown when their control receives focus. The sort menu can be used with the arrow keys, Home, End and Tab, focus moves into the menu when it opens, and back to the sort button when it is closed with Escape or an option is chosen. A "Skip to content" link is the first thing keyboard users reach on every page, so they can jump past the sidebar. When the user goes to another page, focus moves to the start of the page, like when a normal web page loads, so the next Tab shows the skip link again. The app uses HashRouter, so the link moves focus with JavaScript instead of a normal `#` link, which would have changed the route. +- **Keyboard controls:** Navigation uses links, and actions use native buttons. Sidebar links, pagination, sorting controls and avatar options have explicit focus styles. Plant Match instructions are also shown when their control receives focus. The sort menu can be used with the arrow keys, Home and End, focus moves into the menu when it opens, and back to the sort button when it is closed with Escape or an option is chosen. Tab leaves the menu and closes it. On mobile, the sidebar is hidden from the keyboard and screen readers while it is closed. Focus moves into it when it opens, Escape closes it, and focus then goes back to the menu button. The "i" help texts on Plant Match and Profile are linked to their button with `aria-describedby`, and can be hidden with Escape without moving the mouse or focus. A "Skip to content" link is the first thing keyboard users reach on every page, so they can jump past the sidebar. When the user goes to another page, focus moves to the start of the page, like when a normal web page loads, so the next Tab shows the skip link again. The app uses HashRouter, so the link moves focus with JavaScript instead of a normal `#` link, which would have changed the route. - **Forms and images:** Search, filters and profile inputs have associated labels. Plant images use the plant name as alternative text, and profile and avatar images also include alternative text. -- **Control states:** The sort menu exposes its expanded state, and sort and avatar choices expose their selected state with ARIA attributes. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes. The match button on the plant cards shows ✿ to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. If adding or removing a match fails, an error message is shown at the top of the screen in a `role="alert"` region, so screen readers read it at once without moving focus. +- **Control states:** The sort menu and the mobile menu button expose their expanded state and which element they control. Sort, avatar and preference choices and the profile tabs expose their selected state with `aria-pressed`. The preference chips on the plant cards are a list, and a chip that matches the user's preferences also says so in text that only screen readers read, so the information is not given by colour alone. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes, including "no matches" when the last match is removed. Every page has one `h1` (the page title in the header) and a `main` landmark. The match button on the plant cards shows ✿ to add a plant to My Matches and ✖ to remove it, and its accessible name and tooltip say what a click does. If adding or removing a match fails, an error message is shown at the top of the screen in a `role="alert"` region, so screen readers read it at once without moving focus. - **Plant cards:** The inactive side of a flipped card is hidden from assistive technology with `aria-hidden`, and its information button is removed from the keyboard tab order. -- **Reduced motion:** The card flip and My Matches hover transitions are disabled when the user requests reduced motion. - -- **Automated and manual testing:** The end-to-end tests check all pages against WCAG 2.1 AA with axe, in both light and dark mode, and the app has been tested manually with the keyboard only and at 200 % zoom. See [tests.md](tests.md#end-to-end-and-api-tests) for the results, including two problems the tests found. +- **Reduced motion:** When the user has asked for reduced motion in their system settings, the plant card flip and hover effects, the animation of the error message and the hover effects in the Plant Owner Test are turned off. -- **axe DevTools:** Axe Accessibility Testing found no automatic accessibility issues on the page when tested against WCAG 2.1 AA. +- **Testing:** The end-to-end tests check all pages against WCAG 2.1 AA with axe, in both light and dark mode, and the component tests check accessible names, navigation state and sorting states. The axe DevTools extension found no issues, and the deployed app scored 100 for accessibility in Lighthouse. The app has also been tested manually with the keyboard only and at 200 % zoom. See [tests.md](tests.md#accessibility) for the results, including two problems the tests found. -- **Colour contrast:** We tested the contrast between our chosen colours to help ensure that text and interface elements are distinguishable from their backgrounds using a contrast checker. The contrast checker checked our colours pass WCAG 2.1 accessibility guidelines. This was also tested in the e2e test for both dark and light mode see [tests.md](tests.md#accessibility). +- **Colour contrast:** We checked the contrast between our chosen colours with manual testing, a colour contrast checker, Lighthouse and the end-to-end tests, to make sure that text and interface elements are distinguishable from their backgrounds and meet the WCAG 2.1 accessibility guidelines. The end-to-end tests check every page in both light and dark mode (see [tests.md](tests.md#accessibility)). - **Language support:** The application supports both Norwegian and English, allowing users to choose their preferred language. The accessible names of buttons and landmarks, such as the menu buttons and the sidebar navigation, are translated too, so screen readers read them in the chosen language. -- **Responsive layout:** We tested the application on both mobile and desktop devices. Manual testing helped us identify usability issues and make adjustments to the mobile layout. - -- The deployed production version received an Accessibility score of **100 in Lighthouse** in our latest reported run. Automated component tests also check selected accessible names, navigation state and sorting states. - ## Sustainable web development -We considered sustainability through both our design choices -and our approach to data handling. +We considered sustainability through both our design choices and our approach to data handling. - **Limited colour palette:** We use a limited number of colours throughout the application to maintain a consistent design and follow the principle of avoiding unnecessary use of colours. @@ -78,16 +63,20 @@ and our approach to data handling. - **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset. Sorting by name uses a database index, so the server does not have to sort the whole collection for every request. Only the ids of the user's matches are sent with the user, and My Matches fetches one page of plants at a time, so the plant images are only sent when they are shown. -- **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. +- **Inline SVG icons without an icon library:** The application only needs a few icons (search, sort, 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. -## Design Choices +- **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. -- **Figma prototype:** Before development began, we created a prototype in Figma to establish a shared visual direction and agree on the layout and appearance of the application. This gave the group a common starting point before implementation. +## Design choices - **Colour palette and contrast:** We used a limited colour palette to maintain a consistent visual identity across the application. We also checked the contrast between our chosen colours 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, `Pagination`, `SortMenu` and `MatchButton` are shared by Explore Plants and My Matches, and `ErrorMessage` shows error messages on every page. The filters on Explore Plants are defined in one list of `FilterSelect` components, so a new filter only needs one new line. +- **Consistent icons:** All icons are inline SVG components in [Icons.tsx](../frontend/src/components/icons/Icons.tsx) and [ThemeIcons.tsx](../frontend/src/components/sidebarButtons/ThemeIcons.tsx), drawn on the same 24 × 24 grid. They use `currentColor`, so they follow the text colour in both light and dark mode, and they are sized with `font-size`, so they scale with the text around them. They are marked with `aria-hidden` and `focusable="false"`, since the search field and the buttons they are in already have accessible names, so screen readers do not read the icons twice. Because we drew the icons ourselves, there are no third-party licences to credit. + - **Responsive design:** We designed the application for both desktop and mobile screens. The layout adapts to different screen sizes to ensure that the content and navigation remain usable across devices. - **Page not found:** Unknown addresses show a 404 page instead of a blank page. It links back to Plant Match, and tells the user they can choose another page in the sidebar on desktop or the menu on mobile, so the hint matches the navigation they actually see. + +- **No login:** The user id is stored in the browser, so the profile and matches belong to that browser and cannot be reached from other devices, and anyone who knows a user id can change that user, since the id is sent with every request. Login would solve both and is a possible next step. We actively chose not to implement login, because we felt it was more important that the app is quick to start using than that the data can be reached from several devices. diff --git a/docs/tests.md b/docs/tests.md index eaa27624..62ff2231 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -17,10 +17,11 @@ - [Finding: colour contrast measured during a transition](#finding-colour-contrast-measured-during-a-transition) - [Limitations of the automatic accessibility tests](#limitations-of-the-automatic-accessibility-tests) - [Manual testing](#manual-testing) + - [Lighthouse](#lighthouse) ## Test strategy -The application is tested on three levels, each with its own purpose: +Automated tests help ensure that the application works as intended and that new changes do not break existing functionality. The application is tested on three levels, each with its own purpose: | Level | Tools | What it tests | Data | | -------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | @@ -34,6 +35,8 @@ All levels test both **typical use** (searching, filtering, matching plants, edi None of the tests use the database on the VM, so they need neither the VPN nor the SSH tunnel. +All tests run in GitHub Actions on every pull request (see [Continuous integration](quality.md#continuous-integration)), so a pull request that breaks a test cannot be merged unnoticed. The end-to-end tests also check all pages against WCAG 2.1 AA, which helped us find and fix accessibility problems that the other tests did not catch (see [Accessibility](#accessibility)). + ## Run the tests The first time the e2e tests run, install the browser with `npx playwright install chromium`. The first time the backend or e2e tests run, MongoDB is downloaded once. The e2e tests also build the backend and frontend, so they take a little longer the first time. @@ -80,13 +83,11 @@ If some tests fail, a report can still be made with `npx vitest run --coverage - To watch an e2e test, open UI mode, run a test, and expand it to choose the desktop or mobile run. The trace shows every step the test took, with a screenshot of the page before and after each action, the network requests and the browser console. -All tests also run in GitHub Actions on every pull request, see [Continuous integration](../README.md#continuous-integration) in the README. - ## Test coverage | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 96.7 % | 94.73 % | 92.92 % | 98.33 % | +| Frontend | 96.95 % | 92.75 % | 95.31 % | 97.67 % | | Backend | 100 % | 100 % | 100 % | 100 % | - Frontend test coverage: @@ -97,7 +98,7 @@ All tests also run in GitHub Actions on every pull request, see [Continuous inte 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. +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 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. @@ -112,7 +113,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - The skip link is the first thing a keyboard user reaches and moves focus to the main content without changing the route, and when the user goes to another page, focus moves to the start of the page so the next Tab goes to the skip link. - `ErrorMessageContext.test.tsx` - The message is shown in an `alert` region, hidden after six seconds, replaced by a new message with the time started again, and nothing happens without a provider. -- `ExplorePage.test.tsx` +- `ExplorePlantsPage.test.tsx` - Loading, error and empty results: a loading message, an error message when the query fails, and a message without page navigation when nothing matches. - Search, filters and sorting: the search text is only sent after the debounce delay, the chosen filters and sort order are sent in the query, the selected sort is visible and included in the sort button's accessible name, and the sort menu closes with Escape and with a click outside. - Number of results: the total number for the whole result is shown, not only the plants on the page, it updates when a filter changes, it is in an `aria-live` region, and it is hidden while loading and when nothing matches. @@ -124,40 +125,40 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `FilterSelect.test.tsx` - A labelled dropdown with "All" as the first option, showing the selected value and reporting a new choice, including going back to "All". - `SortMenu.test.tsx` - - The selected option in the button's accessible name, opening the menu with focus on the selected option, moving between the options with the arrow keys, Home, End, Tab and Shift+Tab, choosing an option, and closing with Escape or a click outside, with focus going back to the button. + - The selected option in the button's accessible name, opening the menu with focus on the selected option, moving between the options with the arrow keys, Home and End, that the button is linked to the list with `aria-controls` and the menu closes when Tab moves focus out of it, choosing an option, and closing with Escape or a click outside, with focus going back to the button. - `getPageItems.test.ts` - Which page numbers are shown: every page when there are few, the first pages near the start, the last pages near the end, the current page and its neighbours in the middle, "…" never hiding just one page, and never more than seven items however many pages there are. - `Header.test.tsx` - - Shows the right title for each page, including the "Page not found" title for unknown paths, and opens the sidebar with the menu button. -- `LanguageSettings.test.tsx` + - Shows the right title for each page, including the "Page not found" title for unknown paths, opens the sidebar with the menu button, and that the menu button tells screen readers whether the sidebar is open (`aria-expanded`, `aria-controls`). +- `i18n.test.tsx` - Switching language changes the content at once and is kept after a reload, an unsupported saved language falls back to Norwegian, and switching works when browser storage is blocked. - `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. - 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, 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. -- `NotFound.test.tsx` + - 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. +- `NotFoundPage.test.tsx` - An unknown path shows the 404 page, with a link back to Plant Match. - `PlantCard.test.tsx` - The back of the card shows the whole plant after clicking information, missing facts and images are shown as unknown, and watering, sunlight and care level are turned into the right preference chips. - `PlantMatchPage.test.tsx` - - The instructions and the first plant, going to the next plant with like and dislike and the empty card at the end, that a liked plant is saved as a match and a skipped one is not, the loading and error states, and that preferences saved on the profile are highlighted on the card. + - The instructions and the first plant, going to the next plant with like and dislike and the empty card at the end, that a liked plant is saved as a match and a skipped one is not, the loading and error states, that preferences saved on the profile are highlighted on the card and also said in text for screen readers, and that the info button is described by the instructions, which Escape hides. - Loading in batches: the first batch is fetched with the batch size and no excluded plants, the next batch is only fetched when few cards are left and leaves out the plants already shown, every plant is shown exactly once, no more requests are made after a short batch, and a second request is not started while one is in progress. - - Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all. -- `PlantOwnerTest.test.tsx` + - Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, changing preferences starts a new deck with the updated ordering, nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all. +- `PlantOwnerTestPage.test.tsx` - The result for all six combinations of answers, and that the time and light answers do not change it. - Going on is only possible with an answer, an earlier answer is shown when going back, the result is shown with its picture, the result can be saved as profile picture, an error is shown when saving fails, the page says so when the result already is the profile picture, and the test can be taken again with no answers. - `PlantPreferences.test.tsx` - - Saved preferences are marked, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists. -- `Profile.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. +- `ProfilePage.test.tsx` - The name, the image alt text and a screen reader prefix for the description, the preferences tab by default, the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, that a picture from the plant owner test is shown but not offered in the chooser, and a snapshot. - 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, and that only the current page is marked as active. + - 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. - `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. -- `Translation.test.tsx` +- `translationKeys.test.tsx` - The Norwegian and English translation files have exactly the same keys, so no text is missing in either language. - `UserContext.test.tsx` - No user without a provider, loading the user saved in the browser, creating and saving a new user on the first visit, creating a new user when the saved one no longer exists, keeping the saved user when the backend is down, working on when creating a user fails, and removing old user data left in the browser. @@ -166,7 +167,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `useExploreParams.test.tsx` - Default values when the URL has no parameters, reading search, filters, sorting and page from the URL, page 1 for an invalid page number, going back to page 1 when the search, a filter or the sort order changes, keeping the other parameters when the page changes, removing a parameter that is set to an empty value, and clearing all Explore parameters on reset. - `useMatchedPlants.test.tsx` - - The ids of the matched plants, adding and removing a match with no message when it works, an error message when the request fails or the user is not found, and nothing sent when there is no user or the plant is already matched. + - The ids of the matched plants, that My Matches is removed from the cache when a match is added or removed, adding and removing a match with no message when it works, an error message when the request fails or the user is not found, and nothing sent when there is no user or the plant is already matched. - `useSessionState.test.ts` - Default and initial values, reading and saving in `sessionStorage`, keeping the value when the hook is mounted again, and working on when reading or saving fails. @@ -180,7 +181,7 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in - Connecting to the database in `MONGODB_URI` and `DB_NAME`, using `iloveplants` when `DB_NAME` is not set, and the error messages when `MONGODB_URI` is missing or empty, is not a MongoDB address, or MongoDB cannot be reached (for example when the SSH tunnel is down). - `server.test.ts` - Starting the server: the default port 3001, the port in `PORT`, and stopping with the error when the port is in use. - - Plants: `getPlants` returns the plants that match the most of the user's preferences first, also when they are fetched in batches ("Low" counts as easy care), random plants when there are no preferences or only unknown ones, and leaves out the plants in `excludeIds` (returning none when all are excluded). Also stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search across common and scientific names with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, and all sort orders. + - Plants: `getPlants` returns the plants that match the most of the user's preferences first, also when they are fetched in batches ("Low" counts as easy care), random plants when there are no preferences or only unknown ones, and leaves out the plants in `excludeIds` (returning none when all are excluded). Also stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search across common and scientific names with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, that `limit` and `offset` are kept within valid bounds (at most 50 plants per request), and all sort orders. - Users: creating and fetching users, updating the profile (trimming text, storing empty text and `null` as `null`, and only changing the sent fields), the plant owner test results as profile pictures, preferences without duplicates, and adding and removing matches in order. - My matches: `myMatches` sorts by newest (the default), oldest, A–Z and Z–A, returns one page at a time with the total count, leaves out and does not count matched plants that were deleted, and returns an empty page for a user without matches and for an unknown or malformed user id. - Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name or description, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and the server passes on a database error and keeps running. @@ -199,13 +200,13 @@ The tests run in an environment as close to production as possible: a real brows | Server | Port | Purpose | | ---------------------------------------------- | ----- | --------------------------------------------------------------------------------------------------- | -| In-memory MongoDB (`e2e/start-test-db.mjs`) | 27018 | A separate test database, so the tests never touch the development data on the VM | +| In-memory MongoDB (`e2e/startTestDb.mjs`) | 27018 | A separate test database, so the tests never touch the development data on the VM | | Backend (`npm run build` + `npm run start`) | 3002 | The real GraphQL backend, pointed at the test database through `MONGODB_URI` and `DB_NAME` | | Frontend (`npm run build` + `npm run preview`) | 4173 | The built app, with `VITE_GRAPHQL_URL` overridden so it talks to the test backend instead of the VM | The ports differ from the dev setup (27017 for the SSH tunnel, 3001 for the dev backend), so the tests can run while the dev servers are running. -Before the tests start, `e2e/global-setup.ts` empties the test database and fills it with the 20 plants in `e2e/fixtures/plants.json`. Every test run therefore starts from exactly the same data, which lets the tests check exact results (for example that searching for "plant" gives exactly two plants). The fixture plants were chosen to cover the cases we want to test: both "Medium" and "Moderate" as care level, a plant without a care level, and more than 12 plants so there are two pages. +Before the tests start, `e2e/globalSetup.ts` empties the test database and fills it with the 20 plants in `e2e/fixtures/plants.json`. Every test run therefore starts from exactly the same data, which lets the tests check exact results (for example that searching for "plant" gives exactly two plants). The fixture plants were chosen to cover the cases we want to test: both "Medium" and "Moderate" as care level, a plant without a care level, and more than 12 plants so there are two pages. The tests run in three Playwright projects: @@ -297,8 +298,14 @@ Automatic testing only finds some accessibility problems, and the tests only che The group has tested the application manually in Chrome on Mac and on a mobile phone throughout development, using all pages and features on both. This testing led to adjustments such as improvements to the mobile layout. Here are some examples: -**Keyboard only:** all pages have been tested with Tab, Shift+Tab, Enter and Escape only. All links and buttons can be reached and used, the focus is visible at all times, and in the sort menu, focus moves into the menu when it opens and back to the sort button when it closes. The first Tab on every page shows the "Skip to content" link, which jumps past the sidebar, and the same happens after going to another page. +**Keyboard only:** all pages have been tested with Tab, Shift+Tab, Enter and Escape only. All links and buttons can be reached and used, the focus is visible at all times, in the sort menu, focus moves into the menu when it opens and back to the sort button when it closes, and on mobile, focus moves into the sidebar when it opens and back to the menu button when it closes. The "i" help texts can be closed with Escape. The first Tab on every page shows the "Skip to content" link, which jumps past the sidebar, and the same happens after going to another page. **Finding: the skip link hid the search field.** The first version scrolled the content up behind the sticky header, which the component tests did not catch, since jsdom does not scroll. The link now moves focus without scrolling. **Zoom to 200 %:** on a laptop screen, the app switches to the mobile layout at 200 % zoom. The sidebar is hidden and can be opened with the menu button in the header, so the layout adapts to the larger text instead of needing horizontal scrolling (WCAG 1.4.4 and 1.4.10). + +## Lighthouse + +We ran Lighthouse in Chrome DevTools on the deployed app on the VM. Lighthouse audits a page for performance, accessibility, best practices and SEO. The app passed the accessibility audit with a score of **100**, so Lighthouse found no problems with, for example, colour contrast, labels or alternative text. Lighthouse was also one of the tools we used to check the colour contrast (see [Accessibility](quality.md#accessibility) in quality.md). + +Like axe, Lighthouse only finds problems that can be detected automatically, so it does not replace the manual testing above. diff --git a/e2e/global-setup.ts b/e2e/globalSetup.ts similarity index 92% rename from e2e/global-setup.ts rename to e2e/globalSetup.ts index 4b0588ba..8d9f5194 100644 --- a/e2e/global-setup.ts +++ b/e2e/globalSetup.ts @@ -1,6 +1,6 @@ import { readFile } from "node:fs/promises"; import { MongoClient } from "mongodb"; -import { E2E_DB_NAME, E2E_MONGODB_URI } from "./test-db"; +import { E2E_DB_NAME, E2E_MONGODB_URI } from "./testDb"; // Runs once before all tests: empties the test database and fills it with fixed plants, // so every test run starts from exactly the same data. diff --git a/e2e/start-test-db.mjs b/e2e/startTestDb.mjs similarity index 100% rename from e2e/start-test-db.mjs rename to e2e/startTestDb.mjs diff --git a/e2e/test-db.ts b/e2e/testDb.ts similarity index 91% rename from e2e/test-db.ts rename to e2e/testDb.ts index 298eba73..3d5d4e1c 100644 --- a/e2e/test-db.ts +++ b/e2e/testDb.ts @@ -1,4 +1,4 @@ -// Shared settings for the test database, used by playwright.config.ts and global-setup.ts. +// Shared settings for the test database, used by playwright.config.ts and globalSetup.ts. // Port 27018 so it does not collide with the SSH tunnel to the VM on 27017. export const E2E_DB_PORT = 27018; export const E2E_MONGODB_URI = `mongodb://127.0.0.1:${E2E_DB_PORT}`; diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts index ac2310e0..774d724e 100644 --- a/e2e/uiAccessibility.spec.ts +++ b/e2e/uiAccessibility.spec.ts @@ -298,7 +298,7 @@ const PAGES = [ path: "#/explorePlants", loaded: ".plant-grid > li", }, - { name: "MyMatches", path: "#/my-matches", loaded: ".matches-grid" }, + { name: "MyMatches", path: "#/myMatches", loaded: ".matches-grid" }, { name: "Profile", path: "#/profile", loaded: "main.profile" }, { name: "PlantOwnerTest", @@ -414,7 +414,7 @@ for (const theme of THEMES) { await addButton.click(); await expect(addButton).toHaveClass(/add-match-button--matched/); - await page.goto("#/my-matches"); + await page.goto("#/myMatches"); await expect(page.locator(".plant-card-match")).toHaveCount(1); await setTheme(page, theme); await checkAccessibility(page); diff --git a/e2e/uiImages.spec.ts b/e2e/uiImages.spec.ts index cf026857..ef403ebd 100644 --- a/e2e/uiImages.spec.ts +++ b/e2e/uiImages.spec.ts @@ -105,7 +105,7 @@ test("the placeholder picture loads on plant cards without an image", async ({ (element) => getComputedStyle(element, "::before").backgroundImage, ); const url = backgroundImage.match(/url\("?(.*?)"?\)/)?.[1]; - expect(url).toContain("plant-placeholder.png"); + expect(url).toContain("plantPlaceholder.png"); expect(await loadImageWidth(page, url!)).toBeGreaterThan(0); }); diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index c5012cca..09313dd6 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -23,7 +23,7 @@ test("user can like a plant in PlantMatch, find it in MyMatches and remove the m await likeButton.click(); await openSidebar(page); - await page.locator('a[href$="/my-matches"]').click(); + await page.locator('a[href$="/myMatches"]').click(); const matchCards = page.locator(".plant-card-match"); await expect(matchCards).toHaveCount(1); @@ -55,7 +55,7 @@ test("user can add a plant from ExplorePlants, find it in MyMatches and remove i await expect(matchButton).toBeEnabled(); await openSidebar(page); - await page.locator('a[href$="/my-matches"]').click(); + await page.locator('a[href$="/myMatches"]').click(); await expect(matchCards).toHaveCount(1); await expect(matchCards.first()).toContainText("Aloe Vera"); @@ -68,7 +68,7 @@ test("user can add a plant from ExplorePlants, find it in MyMatches and remove i await expect(matchButton).not.toHaveClass(/add-match-button--matched/); await openSidebar(page); - await page.locator('a[href$="/my-matches"]').click(); + await page.locator('a[href$="/myMatches"]').click(); await expect(matchCards).toHaveCount(0); }); @@ -92,7 +92,7 @@ test("user can sort the matches in MyMatches and move between pages", async ({ await expect(lastButton).toHaveClass(/add-match-button--matched/); await openSidebar(page); - await page.locator('a[href$="/my-matches"]').click(); + await page.locator('a[href$="/myMatches"]').click(); const matchCards = page.locator(".plant-card-match"); // 13 matches: the count, and 12 on the first page with the newest first @@ -115,7 +115,7 @@ test("user can sort the matches in MyMatches and move between pages", async ({ await openSidebar(page); await page.locator('a[href$="/explorePlants"]').click(); await openSidebar(page); - await page.locator('a[href$="/my-matches"]').click(); + await page.locator('a[href$="/myMatches"]').click(); await expect(matchCards.first()).toContainText("Aloe Vera"); // ... and after a reload diff --git a/e2e/uiUserProfile.spec.ts b/e2e/uiUserProfile.spec.ts index fe0b0f74..e29b1a6f 100644 --- a/e2e/uiUserProfile.spec.ts +++ b/e2e/uiUserProfile.spec.ts @@ -18,7 +18,7 @@ test("user can update profile and avatar, and navigate between pages", async ({ name: /edit profile|endre profil/i, }); const nameField = page.locator("#profile-name"); - const descriptionField = page.locator("#description"); + const descriptionField = page.locator("#profile-description"); // New users have the profile picture "default", which is not in the list, // so no avatar is selected from the start const chosenAvatar = page.locator("button.avatar-option").first(); @@ -42,7 +42,9 @@ test("user can update profile and avatar, and navigate between pages", async ({ await descriptionField.fill("Loves green plants"); await chosenAvatar.click(); - await expect(page.locator("main.profile h1")).toContainText("John"); + await expect(page.locator("main.profile .profile-text h2")).toContainText( + "John", + ); await expect(chosenAvatar).toHaveAttribute("aria-pressed", "true"); // Saving is debounced: wait until the changes have reached the backend @@ -51,7 +53,9 @@ test("user can update profile and avatar, and navigate between pages", async ({ await test.step("the changes are stored after a reload", async () => { await page.reload(); - await expect(page.locator("main.profile h1")).toContainText("John"); + await expect(page.locator("main.profile .profile-text h2")).toContainText( + "John", + ); await expect(page.locator("main.profile")).toContainText( "Loves green plants", ); diff --git a/frontend/index.html b/frontend/index.html index c54a9723..0440c963 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,6 +5,10 @@ I <3 plants +
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1fc7b788..6cf14bd2 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -14,7 +14,6 @@ "react": "^19.2.8", "react-dom": "^19.2.8", "react-i18next": "^17.0.14", - "react-icons": "^5.7.0", "react-router-dom": "^7.18.4" }, "devDependencies": { @@ -3014,15 +3013,6 @@ } } }, - "node_modules/react-icons": { - "version": "5.7.0", - "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.7.0.tgz", - "integrity": "sha512-LBLy340Rzqy6+/yVhZKT3B/QpP1BZaesGqasf09HPOBzRarcDIFH0WwXlXQfE7q7ipxK4MSiC5DIBWURCny6fw==", - "license": "MIT", - "peerDependencies": { - "react": "*" - } - }, "node_modules/react-is": { "version": "17.0.2", "dev": true, diff --git a/frontend/package.json b/frontend/package.json index f42a96ab..99f851fe 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -17,7 +17,6 @@ "react": "^19.2.8", "react-dom": "^19.2.8", "react-i18next": "^17.0.14", - "react-icons": "^5.7.0", "react-router-dom": "^7.18.4" }, "devDependencies": { diff --git a/frontend/public/plant-placeholder.png b/frontend/public/plantPlaceholder.png similarity index 100% rename from frontend/public/plant-placeholder.png rename to frontend/public/plantPlaceholder.png diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0a9ba12b..37257b16 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; import "./App.css"; @@ -26,13 +26,31 @@ function App() { pageStartRef.current?.focus({ preventScroll: true }); }, [pathname]); + const sidebarRef = useRef(null); + const menuButtonRef = useRef(null); + const openSidebar = () => { setIsSidebarOpen(true); }; - const closeSidebar = () => { + // useCallback, since the Sidebar uses it in an effect + const closeSidebar = useCallback(() => { setIsSidebarOpen(false); - }; + }, []); + + // When the sidebar closes with focus inside it (close button, Escape, or a + // link to the page that is already open), focus goes back to the menu + // button, so it is not lost in the hidden sidebar. Declared after the + // effect above, so a link to another page still moves focus to the page start. + const wasSidebarOpen = useRef(isSidebarOpen); + useEffect(() => { + const wasOpen = wasSidebarOpen.current; + wasSidebarOpen.current = isSidebarOpen; + if (!wasOpen || isSidebarOpen) return; + if (sidebarRef.current?.contains(document.activeElement)) { + menuButtonRef.current?.focus(); + } + }, [isSidebarOpen]); return ( @@ -55,8 +73,16 @@ function App() { {t("app.skipToContent")} - -
+ +
{/* tabIndex -1 lets the skip link focus it, without adding it to the tab order */}
import("./pages/explorePlants/ExplorePlants.tsx"), +const ExplorePlantsPage = lazy( + () => import("./pages/explorePlants/ExplorePlantsPage.tsx"), ); const MyMatchesPage = lazy(() => import("./pages/myMatches/MyMatchesPage.tsx")); -const Profile = lazy(() => import("./pages/profile/Profile.tsx")); -const PlantOwnerTest = lazy( - () => import("./pages/plantOwnerTest/PlantOwnerTest.tsx"), +const ProfilePage = lazy(() => import("./pages/profile/ProfilePage.tsx")); +const PlantOwnerTestPage = lazy( + () => import("./pages/plantOwnerTest/PlantOwnerTestPage.tsx"), ); -const NotFound = lazy(() => import("./pages/notFound/NotFound.tsx")); +const NotFoundPage = lazy(() => import("./pages/notFound/NotFoundPage.tsx")); // eslint-disable-next-line react-refresh/only-export-components export const ROUTES = { plantMatch: "/", explore: "/explorePlants", - myMatches: "/my-matches", + myMatches: "/myMatches", profile: "/profile", plantOwnerTest: "/plantOwnerTest", notFound: "*", @@ -27,11 +27,11 @@ function AppRoutes() { } /> - } /> + } /> } /> - } /> - } /> - } /> + } /> + } /> + } /> ); diff --git a/frontend/src/assets/avatars/snake-plant.png b/frontend/src/assets/avatars/snakePlant.png similarity index 100% rename from frontend/src/assets/avatars/snake-plant.png rename to frontend/src/assets/avatars/snakePlant.png diff --git a/frontend/src/assets/plantQuiz/average_city_gardener.png b/frontend/src/assets/plantQuiz/averageCityGardener.png similarity index 100% rename from frontend/src/assets/plantQuiz/average_city_gardener.png rename to frontend/src/assets/plantQuiz/averageCityGardener.png diff --git a/frontend/src/assets/plantQuiz/average_country_gardener.png b/frontend/src/assets/plantQuiz/averageCountryGardener.png similarity index 100% rename from frontend/src/assets/plantQuiz/average_country_gardener.png rename to frontend/src/assets/plantQuiz/averageCountryGardener.png diff --git a/frontend/src/assets/plantQuiz/city_dreamer.png b/frontend/src/assets/plantQuiz/cityGardenerDreaming.png similarity index 100% rename from frontend/src/assets/plantQuiz/city_dreamer.png rename to frontend/src/assets/plantQuiz/cityGardenerDreaming.png diff --git a/frontend/src/assets/plantQuiz/city_minimalist.png b/frontend/src/assets/plantQuiz/cityMinimalist.png similarity index 100% rename from frontend/src/assets/plantQuiz/city_minimalist.png rename to frontend/src/assets/plantQuiz/cityMinimalist.png diff --git a/frontend/src/assets/plantQuiz/country_minimalist.png b/frontend/src/assets/plantQuiz/countryMinimalist.png similarity index 100% rename from frontend/src/assets/plantQuiz/country_minimalist.png rename to frontend/src/assets/plantQuiz/countryMinimalist.png diff --git a/frontend/src/assets/plantQuiz/garden_expert.png b/frontend/src/assets/plantQuiz/gardenExpert.png similarity index 100% rename from frontend/src/assets/plantQuiz/garden_expert.png rename to frontend/src/assets/plantQuiz/gardenExpert.png diff --git a/frontend/src/components/header/Header.tsx b/frontend/src/components/header/Header.tsx index 8318c1a2..a5927763 100644 --- a/frontend/src/components/header/Header.tsx +++ b/frontend/src/components/header/Header.tsx @@ -1,4 +1,5 @@ import "./Header.css"; +import type { Ref } from "react"; import { useTranslation } from "react-i18next"; import { useLocation } from "react-router-dom"; import { ROUTES } from "../../AppRoutes"; @@ -6,6 +7,7 @@ import { ROUTES } from "../../AppRoutes"; type HeaderProps = { isSidebarOpen: boolean; onOpenSidebar: () => void; + menuButtonRef?: Ref; }; // Maps each route path to the translation key used for its title @@ -17,7 +19,11 @@ const pageTitles: Record = { [ROUTES.plantOwnerTest]: "sidebar.plantOwnerTest", }; -export default function Header({ isSidebarOpen, onOpenSidebar }: HeaderProps) { +export default function Header({ + isSidebarOpen, + onOpenSidebar, + menuButtonRef, +}: HeaderProps) { const { t } = useTranslation(); const { pathname } = useLocation(); @@ -27,9 +33,13 @@ export default function Header({ isSidebarOpen, onOpenSidebar }: HeaderProps) { return (
diff --git a/frontend/src/components/icons/Icons.tsx b/frontend/src/components/icons/Icons.tsx new file mode 100644 index 00000000..3e21eb17 --- /dev/null +++ b/frontend/src/components/icons/Icons.tsx @@ -0,0 +1,54 @@ +// Simple inline SVG icons, drawn the same way as ThemeIcons.tsx. They use +// currentColor, so the color comes from CSS, and are 1em in size, so they +// can be scaled with font-size. aria-hidden, since the control they are in +// already has a label for screen readers. + +type IconProps = { className?: string }; + +export function SearchIcon({ className }: IconProps) { + return ( + + ); +} + +export function SortIcon({ className }: IconProps) { + return ( + + ); +} diff --git a/frontend/src/components/matchButton/MatchButton.tsx b/frontend/src/components/matchButton/MatchButton.tsx index 2bf563b2..26b52695 100644 --- a/frontend/src/components/matchButton/MatchButton.tsx +++ b/frontend/src/components/matchButton/MatchButton.tsx @@ -1,6 +1,6 @@ import "./MatchButton.css"; -type Props = { +type MatchButtonProps = { isMatched: boolean; // Says what the button does, shown as a tooltip and read by screen readers label: string; @@ -16,7 +16,7 @@ export default function MatchButton({ label, onClick, className, -}: Props) { +}: MatchButtonProps) { const classes = [ "add-match-button", isMatched && "add-match-button--matched", diff --git a/frontend/src/components/pagination/getPageItems.ts b/frontend/src/components/pagination/getPageItems.ts index 395de1ef..11300eba 100644 --- a/frontend/src/components/pagination/getPageItems.ts +++ b/frontend/src/components/pagination/getPageItems.ts @@ -1,5 +1,5 @@ // One item in the page list: a page number or an ellipsis ("…") -export type PageItem = number | "ellipsis-start" | "ellipsis-end"; +type PageItem = number | "ellipsis-start" | "ellipsis-end"; const range = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, i) => from + i); diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css index 0407c3f5..550fe658 100644 --- a/frontend/src/components/plantCard/PlantCard.css +++ b/frontend/src/components/plantCard/PlantCard.css @@ -229,7 +229,7 @@ content: ""; position: absolute; inset: 0; - background: url("/plant-placeholder.png") center / cover no-repeat; + background: url("/plantPlaceholder.png") center / cover no-repeat; } .plant-card-front .plant-card-preferences { diff --git a/frontend/src/components/plantCard/PlantCard.tsx b/frontend/src/components/plantCard/PlantCard.tsx index 1a506d71..ca6312d8 100644 --- a/frontend/src/components/plantCard/PlantCard.tsx +++ b/frontend/src/components/plantCard/PlantCard.tsx @@ -7,13 +7,17 @@ import type { Plant } from "../../types/Plant"; type PlantCardData = Omit; -type Props = { +type PlantCardProps = { plant: PlantCardData; size?: "large" | "compact"; onInfo?: () => void; }; -export default function PlantCard({ plant, size = "large", onInfo }: Props) { +export default function PlantCard({ + plant, + size = "large", + onInfo, +}: PlantCardProps) { const { name, imageURL, diff --git a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css index a99a7de8..5791f5a5 100644 --- a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css +++ b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.css @@ -4,11 +4,27 @@ justify-content: flex-start; gap: 8px; - margin-top: 12px; + margin: 12px 0 0; padding: 0 16px; + list-style: none; +} + +.plant-card-preferences li { + display: flex; +} + +.plant-card-preferences .visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; } .plant-preference-chip { + flex-shrink: 0; + padding: 7px 13px; border-radius: 999px; diff --git a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx index 6bfc434e..c71f9a2b 100644 --- a/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx +++ b/frontend/src/components/plantPreferenceChips/PlantPreferenceChips.tsx @@ -2,7 +2,7 @@ import { useTranslation } from "react-i18next"; import { useUser } from "../../context/UserContext.tsx"; import "./PlantPreferenceChips.css"; -type Props = { +type PlantPreferenceChipsProps = { watering?: string | null; sunlight?: string[] | null; careLevel?: string | null; @@ -12,7 +12,7 @@ export default function PlantPreferenceChips({ watering, sunlight, careLevel, -}: Props) { +}: PlantPreferenceChipsProps) { const { t } = useTranslation(); // Re-renders on its own when the preferences change, since they come from the Apollo cache @@ -58,7 +58,7 @@ export default function PlantPreferenceChips({ // Care level const care = careLevel?.toLowerCase(); - // The data uses "Low" for easy care. Must match PREFERENCE_MATCHERS in backend/src/server.ts + // The data uses "Low" for easy care. Must match PREFERENCE_MATCHERS in backend/src/queryBuilders.ts if (care === "easy" || care === "low") { carePreferences.push("easyCare"); } @@ -81,30 +81,33 @@ export default function PlantPreferenceChips({ return null; } + // A list, so screen readers say how many chips there are. Whether a chip + // matches the user's preferences is shown with colour, so it is also + // said in a text that is only read by screen readers. return ( -
{plantPreferences.map((preference) => { const isMatch = selectedPreferences.includes(preference); - const label = t(`preferences.${preference}`); return ( - - {label} - +
  • + + {t(`preferences.${preference}`)} + + {isMatch && ( + + {" "} + ({t("plantCard.matchesPreferences")}) + + )} +
  • ); })} -
    + ); } diff --git a/frontend/src/components/plantPreferences/PlantPreferences.tsx b/frontend/src/components/plantPreferences/PlantPreferences.tsx index 69f306c7..f6c18f7a 100644 --- a/frontend/src/components/plantPreferences/PlantPreferences.tsx +++ b/frontend/src/components/plantPreferences/PlantPreferences.tsx @@ -8,12 +8,14 @@ import { import type { Preference } from "../../types/Preference.ts"; import "./PlantPreferences.css"; -type Props = { +type PlantPreferencesProps = { preferences: Preference[]; }; // Display plant preferences -export default function PlantPreferences({ preferences }: Props) { +export default function PlantPreferences({ + preferences, +}: PlantPreferencesProps) { const { t } = useTranslation(); // Saved preferences come from the database through UserContext @@ -57,7 +59,9 @@ export default function PlantPreferences({ preferences }: Props) { {preferences.map((preference) => (
    - {loading &&

    {t("ExplorePlants.loading")}

    } - {error &&

    {t("ExplorePlants.error")}

    } + {loading &&

    {t("explorePlantsPage.loading")}

    } + {error &&

    {t("explorePlantsPage.error")}

    } {!loading && !error && plants.length === 0 && ( -

    {t("ExplorePlants.noResults")}

    +

    {t("explorePlantsPage.noResults")}

    )} {/* aria-live so screen readers hear the new count when search or filters change */}

    {!loading && !error && totalCount > 0 - ? t("ExplorePlants.resultsCount", { count: totalCount }) + ? t("explorePlantsPage.resultsCount", { count: totalCount }) : ""}

    @@ -148,8 +149,8 @@ export default function ExplorePlants() { // The button adds the plant to My Matches, or removes it if it is already there const isMatched = matchedPlantIds.includes(plant.id); const matchLabel = isMatched - ? t("ExplorePlants.removeMatch") - : t("ExplorePlants.addMatch"); + ? t("explorePlantsPage.removeMatch") + : t("explorePlantsPage.addMatch"); return (
  • diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index 3068890e..b3490641 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -64,13 +64,20 @@ function MyMatchesPage() { return (
    - {/* Without the loading check, "no matches" flashes while the matches are fetched */} - {totalCount > 0 && ( -
    - {/* aria-live so screen readers hear the new count when a match is removed */} -

    - {t("myMatchesPage.matchCount", { count: totalCount })} -

    +
    + {/* One status line that is always on the page, with aria-live, so + screen readers hear every change: the number of matches when + one is removed, and also "no matches" when the last one is + removed. While loading it says so, so "no matches" does not + flash before the matches are fetched. */} +

    + {loading + ? t("myMatchesPage.loading") + : totalCount > 0 + ? t("myMatchesPage.matchCount", { count: totalCount }) + : t("myMatchesPage.noMatches")} +

    + {totalCount > 0 && ( -
    - )} - {loading &&

    {t("myMatchesPage.loading")}

    } - {!loading && totalCount === 0 &&

    {t("myMatchesPage.noMatches")}

    } + )} +
    {plants.map((plant) => (
    diff --git a/frontend/src/pages/notFound/NotFound.css b/frontend/src/pages/notFound/NotFoundPage.css similarity index 100% rename from frontend/src/pages/notFound/NotFound.css rename to frontend/src/pages/notFound/NotFoundPage.css diff --git a/frontend/src/pages/notFound/NotFound.tsx b/frontend/src/pages/notFound/NotFoundPage.tsx similarity index 92% rename from frontend/src/pages/notFound/NotFound.tsx rename to frontend/src/pages/notFound/NotFoundPage.tsx index b72885c5..0561fc8e 100644 --- a/frontend/src/pages/notFound/NotFound.tsx +++ b/frontend/src/pages/notFound/NotFoundPage.tsx @@ -1,10 +1,10 @@ import { Link } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { ROUTES } from "../../AppRoutes"; -import "./NotFound.css"; +import "./NotFoundPage.css"; // Shown for every path that does not match a route in AppRoutes -export default function NotFound() { +export default function NotFoundPage() { const { t } = useTranslation(); return ( diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.css b/frontend/src/pages/plantMatch/PlantMatchPage.css index 34a6136b..a75e596b 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.css +++ b/frontend/src/pages/plantMatch/PlantMatchPage.css @@ -76,6 +76,13 @@ pointer-events: auto; } +/* Hidden with Escape (see useDismissibleTooltip) */ +.match-info.is-dismissed .match-info-box { + opacity: 0; + visibility: hidden; + pointer-events: none; +} + .match-info-box h3 { margin: 0 0 22px; color: var(--pink-text); diff --git a/frontend/src/pages/plantMatch/PlantMatchPage.tsx b/frontend/src/pages/plantMatch/PlantMatchPage.tsx index ef9dc70d..cfa47d7f 100644 --- a/frontend/src/pages/plantMatch/PlantMatchPage.tsx +++ b/frontend/src/pages/plantMatch/PlantMatchPage.tsx @@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next"; import PlantCard from "../../components/plantCard/PlantCard.tsx"; import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; import { usePlantDeck } from "../../hooks/usePlantDeck.ts"; +import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip.ts"; function PlantMatchPage() { const { t } = useTranslation(); @@ -15,6 +16,7 @@ function PlantMatchPage() { noMorePlants, restart, } = usePlantDeck(); + const infoTooltip = useDismissibleTooltip(); const matchPlant = () => { if (plant) addMatch(plant); @@ -25,6 +27,7 @@ function PlantMatchPage() {
    -
    +
    +
    ); } return ( -
    +
    -

    {t("plantQuiz.title")}

    + {/* h2, since the page heading (h1) is in the Header */} +

    {t("plantQuiz.title")}

    {t("plantQuiz.subtitle")}

    -

    +

    {t(`plantQuiz.questions.${question.id}.title`)} -

    +
    {question.options.map((option) => ( @@ -156,6 +157,6 @@ export default function PlantOwnerTest() { {isLastQuestion ? t("plantQuiz.finish") : t("plantQuiz.next")}
    -
    +
    ); } diff --git a/frontend/src/pages/plantOwnerTest/plantownertest.ts b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts similarity index 75% rename from frontend/src/pages/plantOwnerTest/plantownertest.ts rename to frontend/src/pages/plantOwnerTest/plantOwnerTest.ts index 07a3e6eb..1a750b29 100644 --- a/frontend/src/pages/plantOwnerTest/plantownertest.ts +++ b/frontend/src/pages/plantOwnerTest/plantOwnerTest.ts @@ -1,11 +1,11 @@ -// the actual test for the plantowner test +// The questions and results of the plant owner test -import cityMinimalist from "../../assets/plantQuiz/city_minimalist.png"; -import averageCityGardener from "../../assets/plantQuiz/average_city_gardener.png"; -import cityGardenerDreaming from "../../assets/plantQuiz/city_dreamer.png"; -import countryMinimalist from "../../assets/plantQuiz/country_minimalist.png"; -import averageCountryGardener from "../../assets/plantQuiz/average_country_gardener.png"; -import gardenExpert from "../../assets/plantQuiz/garden_expert.png"; +import cityMinimalist from "../../assets/plantQuiz/cityMinimalist.png"; +import averageCityGardener from "../../assets/plantQuiz/averageCityGardener.png"; +import cityGardenerDreaming from "../../assets/plantQuiz/cityGardenerDreaming.png"; +import countryMinimalist from "../../assets/plantQuiz/countryMinimalist.png"; +import averageCountryGardener from "../../assets/plantQuiz/averageCountryGardener.png"; +import gardenExpert from "../../assets/plantQuiz/gardenExpert.png"; export type PlantOwnerType = | "cityMinimalist" @@ -15,7 +15,7 @@ export type PlantOwnerType = | "averageCountryGardener" | "gardenExpert"; -export interface QuizQuestion { +interface QuizQuestion { id: string; options: string[]; } diff --git a/frontend/src/pages/profile/Profile.css b/frontend/src/pages/profile/ProfilePage.css similarity index 95% rename from frontend/src/pages/profile/Profile.css rename to frontend/src/pages/profile/ProfilePage.css index f1f11bb7..e2dcf5dd 100644 --- a/frontend/src/pages/profile/Profile.css +++ b/frontend/src/pages/profile/ProfilePage.css @@ -17,7 +17,7 @@ border-radius: 50%; } -.profile-text h1 { +.profile-text h2 { margin-top: 0; padding-top: 20px; } @@ -82,6 +82,12 @@ visibility: visible; } +/* Hidden with Escape (see useDismissibleTooltip) */ +.preferences-info.is-dismissed .preferences-info-box { + opacity: 0; + visibility: hidden; +} + .profile-tabs { width: 700px; height: 55px; diff --git a/frontend/src/pages/profile/Profile.tsx b/frontend/src/pages/profile/ProfilePage.tsx similarity index 72% rename from frontend/src/pages/profile/Profile.tsx rename to frontend/src/pages/profile/ProfilePage.tsx index 0a6c05a6..71e96f1b 100644 --- a/frontend/src/pages/profile/Profile.tsx +++ b/frontend/src/pages/profile/ProfilePage.tsx @@ -1,4 +1,4 @@ -import "./Profile.css"; +import "./ProfilePage.css"; import profileImg from "../../assets/avatars/profile.png"; import type { Preference } from "../../types/Preference.ts"; import { useTranslation } from "react-i18next"; @@ -9,15 +9,32 @@ import anthurium from "../../assets/avatars/anthurium.png"; import fern from "../../assets/avatars/fern.png"; import orchid from "../../assets/avatars/orchid.png"; import pothos from "../../assets/avatars/pothos.png"; -import snakePlant from "../../assets/avatars/snake-plant.png"; +import snakePlant from "../../assets/avatars/snakePlant.png"; import succulent from "../../assets/avatars/succulent.png"; import { useProfile } from "../../hooks/useProfile.ts"; +import { useDismissibleTooltip } from "../../hooks/useDismissibleTooltip.ts"; import { resultImages, type PlantOwnerType, -} from "../plantOwnerTest/plantownertest.ts"; +} from "../plantOwnerTest/plantOwnerTest.ts"; -export default function Profile() { +// The preferences the user can choose. Must match PREFERENCE_MATCHERS in +// backend/src/queryBuilders.ts +const PREFERENCES: Preference[] = [ + { id: "minimumWater", translationKey: "preferences.minimumWater" }, + { id: "averageWater", translationKey: "preferences.averageWater" }, + { id: "frequentWater", translationKey: "preferences.frequentWater" }, + + { id: "fullSun", translationKey: "preferences.fullSun" }, + { id: "partShade", translationKey: "preferences.partShade" }, + { id: "filteredShade", translationKey: "preferences.filteredShade" }, + + { id: "easyCare", translationKey: "preferences.easyCare" }, + { id: "mediumCare", translationKey: "preferences.mediumCare" }, + { id: "hardCare", translationKey: "preferences.hardCare" }, +]; + +export default function ProfilePage() { const { t } = useTranslation(); const { @@ -35,7 +52,7 @@ export default function Profile() { const avatars = [ { id: "monstera", name: t("profile.monstera"), src: monstera }, { id: "pothos", name: t("profile.pothos"), src: pothos }, - { id: "snake-plant", name: t("profile.snake-plant"), src: snakePlant }, + { id: "snake-plant", 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 }, @@ -49,24 +66,12 @@ export default function Profile() { resultImages[profilePicture as PlantOwnerType] ?? profileImg; + const infoTooltip = useDismissibleTooltip(); + const [activeTab, setActiveTab] = useState<"preferences" | "editProfile">( "preferences", ); - const preferences: Preference[] = [ - { id: "minimumWater", translationKey: "preferences.minimumWater" }, - { id: "averageWater", translationKey: "preferences.averageWater" }, - { id: "frequentWater", translationKey: "preferences.frequentWater" }, - - { id: "fullSun", translationKey: "preferences.fullSun" }, - { id: "partShade", translationKey: "preferences.partShade" }, - { id: "filteredShade", translationKey: "preferences.filteredShade" }, - - { id: "easyCare", translationKey: "preferences.easyCare" }, - { id: "mediumCare", translationKey: "preferences.mediumCare" }, - { id: "hardCare", translationKey: "preferences.hardCare" }, - ]; - return (
    @@ -76,7 +81,7 @@ export default function Profile() { alt={`${t("profile.imageAlt")}: ${shownName}`} />
    -

    {shownName}

    +

    {shownName}

    {t("profile.descriptionLabel")}:{" "} @@ -88,14 +93,18 @@ export default function Profile() {

    - +
    )} {activeTab === "editProfile" && (
    -

    ⚙︎ {t("profile.editProfile")}

    +

    + {t("profile.editProfile")} +

    - + setDescription(event.target.value)} diff --git a/frontend/src/tests/App.test.tsx b/frontend/src/tests/App.test.tsx index ca3f4b1b..6294d3c2 100644 --- a/frontend/src/tests/App.test.tsx +++ b/frontend/src/tests/App.test.tsx @@ -14,13 +14,13 @@ vi.mock("react-i18next", () => ({ vi.mock("../pages/plantMatch/PlantMatchPage.tsx", () => ({ default: () =>

    plant match page

    , })); -vi.mock("../pages/explorePlants/ExplorePlants.tsx", () => ({ +vi.mock("../pages/explorePlants/ExplorePlantsPage.tsx", () => ({ default: () =>

    explore page

    , })); vi.mock("../pages/myMatches/MyMatchesPage.tsx", () => ({ default: () =>

    my matches page

    , })); -vi.mock("../pages/profile/Profile.tsx", () => ({ +vi.mock("../pages/profile/ProfilePage.tsx", () => ({ default: () =>

    profile page

    , })); vi.mock("../components/sidebarButtons/LanguageSwitcher", () => ({ diff --git a/frontend/src/tests/ExplorePage.test.tsx b/frontend/src/tests/ExplorePlantsPage.test.tsx similarity index 85% rename from frontend/src/tests/ExplorePage.test.tsx rename to frontend/src/tests/ExplorePlantsPage.test.tsx index 84229875..d216738b 100644 --- a/frontend/src/tests/ExplorePage.test.tsx +++ b/frontend/src/tests/ExplorePlantsPage.test.tsx @@ -4,7 +4,7 @@ import userEvent from "@testing-library/user-event"; import { MockedProvider } from "@apollo/client/testing/react"; import { MemoryRouter, useLocation } from "react-router-dom"; import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import ExplorePlants from "../pages/explorePlants/ExplorePlants"; +import ExplorePlantsPage from "../pages/explorePlants/ExplorePlantsPage"; import { EXPLORE_PLANTS } from "../graphql/plants/queries"; // Mock i18next: return the key as the translation, with the count for the number @@ -116,7 +116,7 @@ function setup( const view = render( - + {includeLocationProbe && } , @@ -134,7 +134,7 @@ async function advanceDebounce() { }); } -describe("ExplorePlants", () => { +describe("ExplorePlantsPage", () => { beforeEach(() => { // shouldAdvanceTime keeps userEvent and findBy* from hanging with fake timers vi.useFakeTimers({ shouldAdvanceTime: true }); @@ -154,10 +154,10 @@ describe("ExplorePlants", () => { it("shows a loading message and then one card per plant", async () => { setup([mockResponse({})]); - expect(screen.getByText("ExplorePlants.loading")).toBeInTheDocument(); + expect(screen.getByText("explorePlantsPage.loading")).toBeInTheDocument(); expect(await screen.findAllByTestId("plant-card")).toHaveLength(3); expect( - screen.queryByText("ExplorePlants.loading"), + screen.queryByText("explorePlantsPage.loading"), ).not.toBeInTheDocument(); expect(cardNames()).toEqual(["Plant 1", "Plant 2", "Plant 3"]); }); @@ -171,7 +171,7 @@ describe("ExplorePlants", () => { ]); expect( - await screen.findByText("ExplorePlants.error"), + await screen.findByText("explorePlantsPage.error"), ).toBeInTheDocument(); expect(cards()).toHaveLength(0); }); @@ -180,7 +180,7 @@ describe("ExplorePlants", () => { setup([mockResponse({}, [])]); expect( - await screen.findByText("ExplorePlants.noResults"), + await screen.findByText("explorePlantsPage.noResults"), ).toBeInTheDocument(); expect(cards()).toHaveLength(0); expect(screen.queryByRole("navigation")).not.toBeInTheDocument(); @@ -208,14 +208,16 @@ describe("ExplorePlants", () => { await waitFor(() => expect(cardNames()).toEqual(["Rose 1", "Rose 2"])); // One single request for "rose", none for "r", "ro" or "ros" expect(search.result).toHaveBeenCalledTimes(1); - expect(screen.queryByText("ExplorePlants.error")).not.toBeInTheDocument(); + expect( + screen.queryByText("explorePlantsPage.error"), + ).not.toBeInTheDocument(); }); it.each<[keyof Variables, string, string]>([ - ["watering", "ExplorePlants.watering", "minimum"], - ["sunlight", "ExplorePlants.sunlight", "part_shade"], - ["sunlight", "ExplorePlants.sunlight", "filtered_shade"], - ["careLevel", "ExplorePlants.careLevel", "high"], + ["watering", "explorePlantsPage.watering", "minimum"], + ["sunlight", "explorePlantsPage.sunlight", "part_shade"], + ["sunlight", "explorePlantsPage.sunlight", "filtered_shade"], + ["careLevel", "explorePlantsPage.careLevel", "high"], ])( "sends the selected %s filter in the query", async (variable, label, value) => { @@ -242,7 +244,7 @@ describe("ExplorePlants", () => { await screen.findAllByTestId("plant-card"); const sortButton = screen.getByRole("button", { - name: "ExplorePlants.sort: ExplorePlants.name_asc", + name: "explorePlantsPage.sort: explorePlantsPage.name_asc", }); expect(sortButton).toHaveAttribute("aria-expanded", "false"); @@ -250,16 +252,18 @@ describe("ExplorePlants", () => { expect(sortButton).toHaveAttribute("aria-expanded", "true"); // The default sort order is marked as the active choice expect( - screen.getByRole("button", { name: "ExplorePlants.name_asc" }), + screen.getByRole("button", { name: "explorePlantsPage.name_asc" }), ).toHaveAttribute("aria-pressed", "true"); await user.click( - screen.getByRole("button", { name: "ExplorePlants.watering_asc" }), + screen.getByRole("button", { name: "explorePlantsPage.watering_asc" }), ); expect(await screen.findByText("Sorted 1")).toBeInTheDocument(); expect( - screen.queryByRole("button", { name: "ExplorePlants.watering_asc" }), + screen.queryByRole("button", { + name: "explorePlantsPage.watering_asc", + }), ).not.toBeInTheDocument(); }); @@ -268,10 +272,10 @@ describe("ExplorePlants", () => { await screen.findAllByTestId("plant-card"); const sortButton = screen.getByRole("button", { - name: "ExplorePlants.sort: ExplorePlants.name_asc", + name: "explorePlantsPage.sort: explorePlantsPage.name_asc", }); const option = () => - screen.queryByRole("button", { name: "ExplorePlants.name_desc" }); + screen.queryByRole("button", { name: "explorePlantsPage.name_desc" }); await user.click(sortButton); expect(option()).toBeInTheDocument(); @@ -292,7 +296,7 @@ describe("ExplorePlants", () => { setup([mockResponse({}, makePlants(12), 30)]); await screen.findAllByTestId("plant-card"); - const count = screen.getByText("ExplorePlants.resultsCount 30"); + const count = screen.getByText("explorePlantsPage.resultsCount 30"); expect(count).toHaveAttribute("aria-live", "polite"); expect(cards()).toHaveLength(12); }); @@ -303,15 +307,15 @@ describe("ExplorePlants", () => { makePlants(5, 1, "High"), ); const { user } = setup([mockResponse({}, makePlants(12), 30), filtered]); - await screen.findByText("ExplorePlants.resultsCount 30"); + await screen.findByText("explorePlantsPage.resultsCount 30"); await user.selectOptions( - screen.getByLabelText("ExplorePlants.careLevel"), + screen.getByLabelText("explorePlantsPage.careLevel"), "high", ); expect( - await screen.findByText("ExplorePlants.resultsCount 5"), + await screen.findByText("explorePlantsPage.resultsCount 5"), ).toBeInTheDocument(); }); @@ -321,7 +325,7 @@ describe("ExplorePlants", () => { // Still loading expect(screen.queryByText(/resultsCount/)).not.toBeInTheDocument(); - await screen.findByText("ExplorePlants.noResults"); + await screen.findByText("explorePlantsPage.noResults"); expect(screen.queryByText(/resultsCount/)).not.toBeInTheDocument(); }); }); @@ -381,7 +385,7 @@ describe("ExplorePlants", () => { ).toBeInTheDocument(); await user.selectOptions( - screen.getByLabelText("ExplorePlants.careLevel"), + screen.getByLabelText("explorePlantsPage.careLevel"), "high", ); @@ -439,13 +443,13 @@ describe("ExplorePlants", () => { ); expect(screen.getByRole("searchbox")).toHaveValue("rose"); - expect(screen.getByLabelText("ExplorePlants.watering")).toHaveValue( + expect(screen.getByLabelText("explorePlantsPage.watering")).toHaveValue( "minimum", ); - expect(screen.getByLabelText("ExplorePlants.sunlight")).toHaveValue( + expect(screen.getByLabelText("explorePlantsPage.sunlight")).toHaveValue( "part_shade", ); - expect(screen.getByLabelText("ExplorePlants.careLevel")).toHaveValue( + expect(screen.getByLabelText("explorePlantsPage.careLevel")).toHaveValue( "high", ); expect(await screen.findByText("Restored 13")).toBeInTheDocument(); @@ -473,12 +477,12 @@ describe("ExplorePlants", () => { await user.type(screen.getByRole("searchbox"), "ro"); await user.selectOptions( - screen.getByLabelText("ExplorePlants.watering"), + screen.getByLabelText("explorePlantsPage.watering"), "minimum", ); await screen.findByText("Filtered 1"); await user.selectOptions( - screen.getByLabelText("ExplorePlants.careLevel"), + screen.getByLabelText("explorePlantsPage.careLevel"), "high", ); await screen.findByText("Filtered again 1"); @@ -487,12 +491,16 @@ describe("ExplorePlants", () => { ); await user.click( - screen.getByRole("button", { name: "ExplorePlants.reset" }), + screen.getByRole("button", { name: "explorePlantsPage.reset" }), ); expect(screen.getByRole("searchbox")).toHaveValue(""); - expect(screen.getByLabelText("ExplorePlants.watering")).toHaveValue(""); - expect(screen.getByLabelText("ExplorePlants.careLevel")).toHaveValue(""); + expect(screen.getByLabelText("explorePlantsPage.watering")).toHaveValue( + "", + ); + expect(screen.getByLabelText("explorePlantsPage.careLevel")).toHaveValue( + "", + ); expect(await screen.findByText("Plant 1")).toBeInTheDocument(); expect(screen.getByTestId("location-search")).toHaveTextContent(""); }); @@ -506,7 +514,9 @@ describe("ExplorePlants", () => { await screen.findAllByTestId("plant-card"); await user.click( - screen.getAllByRole("button", { name: "ExplorePlants.addMatch" })[0], + screen.getAllByRole("button", { + name: "explorePlantsPage.addMatch", + })[0], ); expect(matchedPlants.addMatch).toHaveBeenCalledWith( @@ -522,13 +532,15 @@ describe("ExplorePlants", () => { // Still clickable, and shows an X instead of the flower const removeButton = screen.getByRole("button", { - name: "ExplorePlants.removeMatch", + name: "explorePlantsPage.removeMatch", }); expect(removeButton).toBeEnabled(); expect(removeButton).toHaveClass("add-match-button--matched"); expect(removeButton).toHaveTextContent("✖"); expect( - screen.getAllByRole("button", { name: "ExplorePlants.addMatch" })[0], + screen.getAllByRole("button", { + name: "explorePlantsPage.addMatch", + })[0], ).toHaveTextContent("✿"); await user.click(removeButton); @@ -538,31 +550,33 @@ describe("ExplorePlants", () => { }); }); - // Accessibility: the page has a search landmark, a heading, a labelled + // Accessibility: the page has a main and a search landmark, a labelled // page navigation, and every input and filter has an accessible name. + // The page heading (h1) comes from the Header, so the page has none itself. describe("accessibility", () => { - it("has a search landmark, a heading and labelled controls", async () => { + it("has landmarks, no extra h1 and labelled controls", async () => { setup([mockResponse({}, makePlants(12), 30)]); await screen.findAllByTestId("plant-card"); + expect(screen.getByRole("main")).toBeInTheDocument(); expect(screen.getByRole("search")).toBeInTheDocument(); expect( - screen.getByRole("heading", { level: 1, name: "explore.title" }), - ).toBeInTheDocument(); + screen.queryByRole("heading", { level: 1 }), + ).not.toBeInTheDocument(); expect( - screen.getByRole("searchbox", { name: "ExplorePlants.search" }), + screen.getByRole("searchbox", { name: "explorePlantsPage.search" }), ).toBeInTheDocument(); expect( screen.getByRole("navigation", { name: "pagination.label" }), ).toBeInTheDocument(); expect( - screen.getByLabelText("ExplorePlants.watering"), + screen.getByLabelText("explorePlantsPage.watering"), ).toBeInTheDocument(); expect( - screen.getByLabelText("ExplorePlants.sunlight"), + screen.getByLabelText("explorePlantsPage.sunlight"), ).toBeInTheDocument(); expect( - screen.getByLabelText("ExplorePlants.careLevel"), + screen.getByLabelText("explorePlantsPage.careLevel"), ).toBeInTheDocument(); }); }); @@ -581,7 +595,7 @@ describe("ExplorePlants", () => { it("matches the snapshot of the page with no results", async () => { const { container } = setup([mockResponse({}, [])]); - await screen.findByText("ExplorePlants.noResults"); + await screen.findByText("explorePlantsPage.noResults"); expect(container).toMatchSnapshot(); }); @@ -592,7 +606,7 @@ describe("ExplorePlants", () => { await user.click( screen.getByRole("button", { - name: "ExplorePlants.sort: ExplorePlants.name_asc", + name: "explorePlantsPage.sort: explorePlantsPage.name_asc", }), ); diff --git a/frontend/src/tests/Header.test.tsx b/frontend/src/tests/Header.test.tsx index e41a527f..785a0ac7 100644 --- a/frontend/src/tests/Header.test.tsx +++ b/frontend/src/tests/Header.test.tsx @@ -19,6 +19,20 @@ function renderHeader(route: string, onOpenSidebar = vi.fn()) { } describe("Header", () => { + it("tells screen readers whether the sidebar it controls is open", () => { + render( + +
    + , + ); + const menuButton = screen.getByRole("button", { + name: "sidebar.openSidebar", + }); + + expect(menuButton).toHaveAttribute("aria-expanded", "true"); + expect(menuButton).toHaveAttribute("aria-controls", "sidebar"); + }); + it.each([ [ROUTES.plantMatch, "sidebar.plantMatch"], [ROUTES.explore, "sidebar.explorePlants"], diff --git a/frontend/src/tests/LanguageSwitcher.test.tsx b/frontend/src/tests/LanguageSwitcher.test.tsx index 7ff3f30a..1518a0f9 100644 --- a/frontend/src/tests/LanguageSwitcher.test.tsx +++ b/frontend/src/tests/LanguageSwitcher.test.tsx @@ -3,12 +3,6 @@ import userEvent from "@testing-library/user-event"; import { describe, it, expect, vi, beforeEach } from "vitest"; import LanguageSwitcher from "../components/sidebarButtons/LanguageSwitcher"; -// The language choice is stored in sessionStorage, so clear it between tests -// to stop one test's click from deciding the next test's starting language -beforeEach(() => { - sessionStorage.clear(); -}); - const changeLanguage = vi.fn(); let mockLanguage = "no"; diff --git a/frontend/src/tests/MyMatchesPage.test.tsx b/frontend/src/tests/MyMatchesPage.test.tsx index 5e05659c..0e2d5a6e 100644 --- a/frontend/src/tests/MyMatchesPage.test.tsx +++ b/frontend/src/tests/MyMatchesPage.test.tsx @@ -75,7 +75,11 @@ describe("myMatchesPage", () => { mockMatches([]); render(); - expect(screen.getByText("myMatchesPage.noMatches")).toBeInTheDocument(); + // In the live region, so it is also read when the last match is removed + expect(screen.getByText("myMatchesPage.noMatches")).toHaveAttribute( + "aria-live", + "polite", + ); expect( screen.queryByText("myMatchesPage.matchCount"), ).not.toBeInTheDocument(); diff --git a/frontend/src/tests/NotFound.test.tsx b/frontend/src/tests/NotFoundPage.test.tsx similarity index 96% rename from frontend/src/tests/NotFound.test.tsx rename to frontend/src/tests/NotFoundPage.test.tsx index c0dfea63..b3f1cd70 100644 --- a/frontend/src/tests/NotFound.test.tsx +++ b/frontend/src/tests/NotFoundPage.test.tsx @@ -7,7 +7,7 @@ vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }), })); -describe("NotFound", () => { +describe("NotFoundPage", () => { it("is shown for an unknown path and links back to PlantMatch", async () => { render( diff --git a/frontend/src/tests/PlantCard.test.tsx b/frontend/src/tests/PlantCard.test.tsx index d3255da3..994794cd 100644 --- a/frontend/src/tests/PlantCard.test.tsx +++ b/frontend/src/tests/PlantCard.test.tsx @@ -106,7 +106,9 @@ describe("PlantCard", () => { expect(screen.queryByRole("img")).not.toBeInTheDocument(); expect(container.querySelector(".plant-card-image-missing")).not.toBeNull(); expect(screen.getAllByText("plantCard.unknown")).toHaveLength(3); - expect(screen.queryByRole("group")).not.toBeInTheDocument(); + expect( + screen.queryByRole("list", { name: "plantCard.preferences" }), + ).not.toBeInTheDocument(); }); it.each([ diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index b209cc30..9a65292a 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -1,4 +1,10 @@ -import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { + fireEvent, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; import { beforeEach, describe, it, expect, vi } from "vitest"; import PlantMatchPage from "../pages/plantMatch/PlantMatchPage"; import { @@ -82,6 +88,25 @@ beforeEach(() => { }); describe("PlantMatchPage", () => { + it("links the info button to the instructions and hides them with Escape", async () => { + render(); + const infoButton = screen.getByRole("button", { + name: "plantMatchPage.howToMatch", + }); + expect(infoButton).toHaveAccessibleDescription( + /plantMatchPage.instruction1/, + ); + + const wrapper = infoButton.parentElement!; + infoButton.focus(); + fireEvent.keyDown(infoButton, { key: "Escape" }); + expect(wrapper).toHaveClass("is-dismissed"); + + // Shown again the next time focus comes back + fireEvent.blur(infoButton); + expect(wrapper).not.toHaveClass("is-dismissed"); + }); + it("shows instructions and the first plant", async () => { render(); expect( @@ -143,12 +168,18 @@ describe("PlantMatchPage", () => { "is-match", ); expect(screen.getByText("preferences.fullSun")).not.toHaveClass("is-match"); - expect( - screen.getByRole("group", { name: "preferences.averageWater" }), - ).toHaveAccessibleDescription("plantCard.matchesPreferences"); - expect( - screen.getByRole("group", { name: "preferences.fullSun" }), - ).not.toHaveAttribute("aria-description"); + // Screen readers are told which chips match, not only shown it with colour + const items = within( + screen.getByRole("list", { name: "plantCard.preferences" }), + ).getAllByRole("listitem"); + const item = (name: string) => + items.find((li) => li.textContent?.includes(name)); + expect(item("preferences.averageWater")).toHaveTextContent( + "plantCard.matchesPreferences", + ); + expect(item("preferences.fullSun")).not.toHaveTextContent( + "plantCard.matchesPreferences", + ); }); it("loads plants in batches and fetches the next batch near the end", async () => { @@ -315,6 +346,24 @@ describe("PlantMatchPage", () => { ]); }); + it("restarts the deck when the user's preferences change", async () => { + const { rerender } = render(); + await screen.findAllByText("Hydrangea"); + skip(); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + + mockUser(["averageWater"]); + rerender(); + + await waitFor(() => expect(query).toHaveBeenCalledTimes(2)); + expect(query.mock.calls[1][0].variables).toEqual({ + limit: PLANT_BATCH_SIZE, + excludeIds: [], + preferences: ["averageWater"], + }); + expect(await screen.findAllByText("Hydrangea")).not.toHaveLength(0); + }); + it("waits for the user before fetching the first batch", () => { useUser.mockReturnValue({ userId: "user-1", user: null, loading: true }); render(); diff --git a/frontend/src/tests/PlantOwnerTest.test.tsx b/frontend/src/tests/PlantOwnerTestPage.test.tsx similarity index 92% rename from frontend/src/tests/PlantOwnerTest.test.tsx rename to frontend/src/tests/PlantOwnerTestPage.test.tsx index 1b11bc50..2dac5d84 100644 --- a/frontend/src/tests/PlantOwnerTest.test.tsx +++ b/frontend/src/tests/PlantOwnerTestPage.test.tsx @@ -1,10 +1,8 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; -// The extension is needed: without it, plantownertest.ts is found first on -// file systems that ignore upper and lower case (like macOS) -import PlantOwnerTest from "../pages/plantOwnerTest/PlantOwnerTest.tsx"; -import { getPlantOwnerResult } from "../pages/plantOwnerTest/plantownertest.ts"; +import PlantOwnerTestPage from "../pages/plantOwnerTest/PlantOwnerTestPage.tsx"; +import { getPlantOwnerResult } from "../pages/plantOwnerTest/plantOwnerTest.ts"; const { updateProfile, useUser } = vi.hoisted(() => ({ updateProfile: vi.fn(), @@ -39,7 +37,7 @@ async function takeTest(location: string, watering: string) { const pick = (name: string) => user.click(screen.getByRole("button", { name })); - render(); + render(); await pick("plantQuiz.questions.time.oneDay"); await pick("plantQuiz.next"); await pick("plantQuiz.questions.light.fullSun"); @@ -80,7 +78,7 @@ describe("getPlantOwnerResult", () => { }); }); -describe("PlantOwnerTest", () => { +describe("PlantOwnerTestPage", () => { beforeEach(() => { updateProfile.mockReset(); updateProfile.mockResolvedValue({}); @@ -89,7 +87,7 @@ describe("PlantOwnerTest", () => { it("only allows going on when an answer is chosen", async () => { const user = userEvent.setup(); - render(); + render(); expect( screen.getByRole("heading", { name: "plantQuiz.questions.time.title" }), @@ -113,7 +111,7 @@ describe("PlantOwnerTest", () => { it("shows the earlier answer when going back", async () => { const user = userEvent.setup(); - render(); + render(); await user.click( screen.getByRole("button", { name: "plantQuiz.questions.time.oneDay" }), @@ -135,7 +133,7 @@ describe("PlantOwnerTest", () => { ).toBeInTheDocument(); expect( screen.getByRole("img", { name: "plantQuiz.results.gardenExpert.name" }), - ).toHaveAttribute("src", expect.stringContaining("garden_expert")); + ).toHaveAttribute("src", expect.stringContaining("gardenExpert")); expect( screen.getByText("plantQuiz.results.gardenExpert.description"), ).toBeInTheDocument(); diff --git a/frontend/src/tests/PlantPreferences.test.tsx b/frontend/src/tests/PlantPreferences.test.tsx index 7e96ec91..a32fd412 100644 --- a/frontend/src/tests/PlantPreferences.test.tsx +++ b/frontend/src/tests/PlantPreferences.test.tsx @@ -39,6 +39,18 @@ describe("PlantPreferences", () => { updatePreferences.mockResolvedValue({}); }); + it("tells screen readers which preferences are selected", () => { + mockUser(["fullSun"]); + render(); + + expect( + screen.getByRole("button", { name: "preferences.fullSun" }), + ).toHaveAttribute("aria-pressed", "true"); + expect( + screen.getByRole("button", { name: "preferences.averageWater" }), + ).toHaveAttribute("aria-pressed", "false"); + }); + it("marks the preferences saved on the user", () => { mockUser(["fullSun"]); render(); diff --git a/frontend/src/tests/Profile.test.tsx b/frontend/src/tests/ProfilePage.test.tsx similarity index 93% rename from frontend/src/tests/Profile.test.tsx rename to frontend/src/tests/ProfilePage.test.tsx index f9973eb9..f2442457 100644 --- a/frontend/src/tests/Profile.test.tsx +++ b/frontend/src/tests/ProfilePage.test.tsx @@ -2,7 +2,7 @@ import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; -import Profile from "../pages/profile/Profile"; +import ProfilePage from "../pages/profile/ProfilePage"; const { updateProfile, useUser } = vi.hoisted(() => ({ updateProfile: vi.fn(), @@ -43,7 +43,7 @@ describe("Profile page", () => { } it("renders profile name", () => { - render(); + render(); expect( screen.getByRole("heading", { name: "profile.name" }), @@ -51,7 +51,7 @@ describe("Profile page", () => { }); it("renders profile image alt text", () => { - render(); + render(); expect( screen.getByRole("img", { name: "profile.imageAlt: profile.name" }), @@ -59,7 +59,7 @@ describe("Profile page", () => { }); it("includes a screen reader prefix in the profile description", () => { - render(); + render(); const label = screen.getByText("profile.descriptionLabel:"); expect(label).toHaveClass("profile-description-label"); @@ -69,7 +69,7 @@ describe("Profile page", () => { }); it("shows the preferences tab by default", () => { - render(); + render(); expect( screen.getByRole("button", { name: "profile.preferences" }), @@ -83,7 +83,7 @@ describe("Profile page", () => { it("opens Edit Profile and displays the labelled fields and avatar chooser", async () => { const user = userEvent.setup(); - render(); + render(); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), @@ -115,7 +115,7 @@ describe("Profile page", () => { for (const avatar of [ "monstera", "pothos", - "snake-plant", + "snakePlant", "anthurium", "succulent", "fern", @@ -136,7 +136,7 @@ describe("Profile page", () => { it("updates and saves the profile name, description and selected avatar", async () => { const user = userEvent.setup(); - render(); + render(); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), @@ -189,7 +189,7 @@ describe("Profile page", () => { it("saves the text at once when the field loses focus, and only once", async () => { const user = userEvent.setup(); - render(); + render(); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), ); @@ -215,7 +215,7 @@ describe("Profile page", () => { it("saves the text when the user leaves the profile page", async () => { const user = userEvent.setup(); - const { unmount } = render(); + const { unmount } = render(); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), ); @@ -235,7 +235,7 @@ describe("Profile page", () => { it("saves the text when the tab is reloaded or closed", async () => { const user = userEvent.setup(); - render(); + render(); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), ); @@ -255,7 +255,7 @@ describe("Profile page", () => { const user = userEvent.setup(); mockUser("monstera"); - render(); + render(); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), ); @@ -278,10 +278,10 @@ describe("Profile page", () => { const user = userEvent.setup(); mockUser("gardenExpert"); - render(); + render(); expect( screen.getByRole("img", { name: "profile.imageAlt: profile.name" }), - ).toHaveAttribute("src", expect.stringContaining("garden_expert")); + ).toHaveAttribute("src", expect.stringContaining("gardenExpert")); await user.click( screen.getByRole("button", { name: "profile.editProfile" }), @@ -289,7 +289,7 @@ describe("Profile page", () => { // Only the seven plant avatars can be chosen, and none of them is selected const choices = screen.getAllByRole("button", { - name: /^profile\.(monstera|pothos|snake-plant|anthurium|succulent|fern|orchid)$/, + name: /^profile\.(monstera|pothos|snakePlant|anthurium|succulent|fern|orchid)$/, }); expect(choices).toHaveLength(7); choices.forEach((choice) => @@ -298,7 +298,7 @@ describe("Profile page", () => { }); it("matches snapshot", () => { - const { container } = render(); + const { container } = render(); expect(container).toMatchSnapshot(); }); diff --git a/frontend/src/tests/Sidebar.test.tsx b/frontend/src/tests/Sidebar.test.tsx index 52d90d3a..02566067 100644 --- a/frontend/src/tests/Sidebar.test.tsx +++ b/frontend/src/tests/Sidebar.test.tsx @@ -42,6 +42,26 @@ function renderSidebar({ } describe("Sidebar", () => { + it("moves focus to the close button when it opens", () => { + renderSidebar({ isOpen: true }); + + expect( + screen.getByRole("button", { name: "sidebar.closeMenu" }), + ).toHaveFocus(); + }); + + it("closes with Escape while it is open", async () => { + const open = renderSidebar({ isOpen: true }); + await open.user.keyboard("{Escape}"); + expect(open.onCloseSidebar).toHaveBeenCalledTimes(1); + }); + + it("does not react to Escape while it is closed", async () => { + const { user, onCloseSidebar } = renderSidebar({ isOpen: false }); + await user.keyboard("{Escape}"); + expect(onCloseSidebar).not.toHaveBeenCalled(); + }); + // sidebar displays the title, links to all pages, language switcher, and theme toggle it("displays the title", () => { renderSidebar(); diff --git a/frontend/src/tests/SortMenu.test.tsx b/frontend/src/tests/SortMenu.test.tsx index 893d3313..9817f5c1 100644 --- a/frontend/src/tests/SortMenu.test.tsx +++ b/frontend/src/tests/SortMenu.test.tsx @@ -46,7 +46,7 @@ describe("SortMenu", () => { expect(option("Name (A-Z)")).toHaveAttribute("aria-pressed", "false"); }); - it("moves between the options with the arrow keys, Home, End and Tab", async () => { + it("moves between the options with the arrow keys, Home and End", async () => { const { user, sortButton, option } = setup(); await user.click(sortButton); expect(option("Name (A-Z)")).toHaveFocus(); @@ -67,12 +67,28 @@ describe("SortMenu", () => { await user.keyboard("{Home}"); expect(option("Name (A-Z)")).toHaveFocus(); + }); - // Tab and Shift+Tab stay inside the menu - await user.keyboard("{Tab}"); - expect(option("Name (Z-A)")).toHaveFocus(); + it("is linked to its list and closes when Tab moves focus out of it", async () => { + const { user, sortButton, option } = setup(); + expect(sortButton).not.toHaveAttribute("aria-haspopup"); + + await user.click(sortButton); + const list = screen.getByRole("list"); + expect(sortButton).toHaveAttribute("aria-controls", list.id); + + // Shift+Tab from the first option goes back to the sort button and + // stays inside the menu, so it is still open await user.keyboard("{Shift>}{Tab}{/Shift}"); - expect(option("Name (A-Z)")).toHaveFocus(); + expect(sortButton).toHaveFocus(); + expect(option("Name (Z-A)")).toBeInTheDocument(); + + // Tab past the last option leaves the menu, which closes + await user.click(sortButton); + await user.click(sortButton); + await user.keyboard("{End}{Tab}"); + expect(option("Name (Z-A)")).not.toBeInTheDocument(); + expect(sortButton).toHaveAttribute("aria-expanded", "false"); }); it("chooses an option, closes the menu and returns focus to the button", async () => { diff --git a/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap b/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap similarity index 73% rename from frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap rename to frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap index d31fa644..67e4adc6 100644 --- a/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/ExplorePlantsPage.test.tsx.snap @@ -1,15 +1,10 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`ExplorePlants > snapshots > matches the snapshot of the page with no results 1`] = ` +exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with no results 1`] = `
    -

    - explore.title -

    `; -exports[`ExplorePlants > snapshots > matches the snapshot of the page with results and page navigation 1`] = ` +exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with results and page navigation 1`] = `
    -

    - explore.title -

    snapshots > matches the snapshot of the page with resul - ExplorePlants.search + explorePlantsPage.search @@ -261,86 +282,86 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with resul - ExplorePlants.filters + explorePlantsPage.filters @@ -349,25 +370,32 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with resul > @@ -404,7 +432,7 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with resul class="reset-button" type="button" > - ExplorePlants.reset + explorePlantsPage.reset
    snapshots > matches the snapshot of the page with resul aria-live="polite" class="results-count" > - ExplorePlants.resultsCount 30 + explorePlantsPage.resultsCount 30

      snapshots > matches the snapshot of the page with resul class="add-match" >
    `; -exports[`ExplorePlants > snapshots > matches the snapshot of the page with the sort menu open 1`] = ` +exports[`ExplorePlantsPage > snapshots > matches the snapshot of the page with the sort menu open 1`] = `
    -

    - explore.title -

    snapshots > matches the snapshot of the page with the s - ExplorePlants.search + explorePlantsPage.search @@ -853,86 +888,86 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s - ExplorePlants.filters + explorePlantsPage.filters @@ -940,26 +975,34 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s class="sort-menu" >
    • @@ -1007,7 +1051,7 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s class="sort-option" type="button" > - ExplorePlants.name_desc + explorePlantsPage.name_desc
    • @@ -1016,7 +1060,7 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s class="sort-option" type="button" > - ExplorePlants.watering_asc + explorePlantsPage.watering_asc
    • @@ -1025,7 +1069,7 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s class="sort-option" type="button" > - ExplorePlants.careLevel_asc + explorePlantsPage.careLevel_asc
    @@ -1036,7 +1080,7 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with the s class="reset-button" type="button" > - ExplorePlants.reset + explorePlantsPage.reset
    snapshots > matches the snapshot of the page with the s aria-live="polite" class="results-count" > - ExplorePlants.resultsCount 3 + explorePlantsPage.resultsCount 3

      snapshots > matches the snapshot of the page with the s class="add-match" > @@ -80,47 +82,65 @@ exports[`Profile page > matches snapshot 1`] = ` class="plant-preferences" > diff --git a/frontend/src/tests/LanguageSettings.test.tsx b/frontend/src/tests/i18n.test.tsx similarity index 98% rename from frontend/src/tests/LanguageSettings.test.tsx rename to frontend/src/tests/i18n.test.tsx index 8094e653..2cfc05e7 100644 --- a/frontend/src/tests/LanguageSettings.test.tsx +++ b/frontend/src/tests/i18n.test.tsx @@ -9,7 +9,7 @@ function TranslatedContent() { return

      {t("sidebar.profile")}

      ; } -describe("language settings", () => { +describe("i18n language settings", () => { beforeEach(() => { vi.resetModules(); localStorage.clear(); diff --git a/frontend/src/tests/Translation.test.tsx b/frontend/src/tests/translationKeys.test.tsx similarity index 89% rename from frontend/src/tests/Translation.test.tsx rename to frontend/src/tests/translationKeys.test.tsx index a968a287..29cd9190 100644 --- a/frontend/src/tests/Translation.test.tsx +++ b/frontend/src/tests/translationKeys.test.tsx @@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest"; import no from "../i18n/locales/no/translation.json"; import en from "../i18n/locales/en/translation.json"; -// Turns nested translations into a flat list of keys, e.g. "ExplorePlants.watering" +// Turns nested translations into a flat list of keys, e.g. "explorePlantsPage.watering" function flatten(obj: Record, prefix = ""): string[] { return Object.entries(obj).flatMap(([key, value]) => typeof value === "object" && value !== null diff --git a/frontend/src/tests/useMatchedPlants.test.tsx b/frontend/src/tests/useMatchedPlants.test.tsx index ce55080d..162a371d 100644 --- a/frontend/src/tests/useMatchedPlants.test.tsx +++ b/frontend/src/tests/useMatchedPlants.test.tsx @@ -6,16 +6,22 @@ import { ErrorMessageProvider } from "../context/ErrorMessageContext"; import { ADD_USER_MATCH } from "../graphql/user/mutations"; import type { Plant } from "../types/Plant"; -const { addUserMatch, removeUserMatch, useUser } = vi.hoisted(() => ({ - addUserMatch: vi.fn(), - removeUserMatch: vi.fn(), - useUser: vi.fn(), -})); - -// Returns the right mutation function for each mutation +const { addUserMatch, removeUserMatch, useUser, mutationOptions } = vi.hoisted( + () => ({ + addUserMatch: vi.fn(), + removeUserMatch: vi.fn(), + useUser: vi.fn(), + mutationOptions: [] as unknown[], + }), +); + +// Returns the right mutation function for each mutation, and keeps the +// options the hook passed, so the tests can check the cache update vi.mock("@apollo/client/react", () => ({ - useMutation: (mutation: unknown) => - mutation === ADD_USER_MATCH ? [addUserMatch] : [removeUserMatch], + useMutation: (mutation: unknown, options: unknown) => { + mutationOptions.push(options); + return mutation === ADD_USER_MATCH ? [addUserMatch] : [removeUserMatch]; + }, })); vi.mock("../context/UserContext", () => ({ useUser })); vi.mock("react-i18next", () => ({ @@ -48,6 +54,7 @@ beforeEach(() => { addUserMatch.mockReset(); removeUserMatch.mockReset(); mockUser("user-1"); + mutationOptions.length = 0; }); describe("useMatchedPlants", () => { @@ -59,6 +66,20 @@ describe("useMatchedPlants", () => { expect(result.current.matchedPlantIds).toEqual(["plant-1", "plant-2"]); }); + it("removes My Matches from the cache when a match is added or removed", () => { + renderMatchedPlants(); + const cache = { evict: vi.fn(), gc: vi.fn() }; + + // Both mutations get the same update, which removes the saved pages + for (const options of mutationOptions) { + (options as { update: (cache: unknown) => void }).update(cache); + } + + expect(mutationOptions.length).toBeGreaterThan(0); + expect(cache.evict).toHaveBeenCalledWith({ fieldName: "myMatches" }); + expect(cache.gc).toHaveBeenCalled(); + }); + describe("adding a match", () => { it("saves the plant and shows no message when it works", async () => { addUserMatch.mockResolvedValue({ diff --git a/playwright.config.ts b/playwright.config.ts index 46bde4d5..93a712cf 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,5 +1,5 @@ import { defineConfig, devices } from "@playwright/test"; -import { E2E_DB_NAME, E2E_DB_PORT, E2E_MONGODB_URI } from "./e2e/test-db"; +import { E2E_DB_NAME, E2E_DB_PORT, E2E_MONGODB_URI } from "./e2e/testDb"; // The test backend runs on 3002, so it does not collide with the dev backend on 3001 const E2E_BACKEND_PORT = 3002; @@ -7,7 +7,7 @@ const E2E_BACKEND_PORT = 3002; export default defineConfig({ testDir: "./e2e", // Runs after the web servers are up: empties the test database and fills it with fixtures - globalSetup: "./e2e/global-setup.ts", + globalSetup: "./e2e/globalSetup.ts", // All tests share one database, so they run one at a time workers: 1, retries: process.env.CI ? 1 : 0, @@ -46,7 +46,7 @@ export default defineConfig({ webServer: [ { // In-memory MongoDB, no installation needed - command: "node e2e/start-test-db.mjs", + command: "node e2e/startTestDb.mjs", port: E2E_DB_PORT, env: { E2E_DB_PORT: String(E2E_DB_PORT) }, reuseExistingServer: !process.env.CI,