Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion frontend/src/i18n/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@
"oldest": "Oldest first",
"name_asc": "Name (A-Z)",
"name_desc": "Name (Z-A)",
"preferences": "Best match first"
"preferences": "Best match first",
"compatible-plant": "Your most compatible plant right now is:"
},
"matches": {
"addFailed": "Could not add the plant to My Matches. Please try again.",
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/i18n/locales/no/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@
"oldest": "Eldste først",
"name_asc": "Navn (A-Z)",
"name_desc": "Navn (Z-A)",
"preferences": "Best match først"
"preferences": "Best match først",
"compatible-plant": "Din mest kompatible plante akkurat nå er:"
},
"matches": {
"addFailed": "Kunne ikke legge planten til i Mine Matches. Prøv igjen.",
Expand Down
74 changes: 74 additions & 0 deletions frontend/src/pages/myMatches/MyMatchesPage.css
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@
background-color: var(--light-pink);
}

.matches-grid .my-matches-count {
grid-column: 1 / -1;
justify-self: center;
margin: 0 0 10px;
background-color: var(--light-pink);
border-color: var(--dark-pink);
color: var(--pink-text);
}

/* The previous matches are dimmed a little while new ones load, like on
Explore Plants */
.matches-grid.is-refreshing .plant-card-match {
Expand Down Expand Up @@ -87,6 +96,56 @@
font-size: 20px;
}

.compatible-plant-field {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
max-width: 100%;
min-height: 180px;
padding: 24px 36px;
box-sizing: border-box;
border-radius: 20px;
background: var(--light-green);
cursor: pointer;
transition:
transform 0.2s ease,
box-shadow 0.2s ease;
overflow: hidden;
}

.compatible-plant-field:hover {
transform: translateY(-3px);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.compatible-plant-field img {
width: 150px;
height: 180px;
object-fit: cover;
object-position: center;
border-radius: 14px;
}

.compatible-plant-field p {
margin: 0;
color: var(--text-dark);
}

.compatible-plant-field p:first-child {
font-size: 0.95rem;
font-weight: 600;
color: var(--pink-text);
text-transform: uppercase;
letter-spacing: 1px;
}

.compatible-plant-field p:last-child {
margin-top: 8px;
font-size: 1.6rem;
font-weight: 700;
}

.plant-card-match {
position: relative;
justify-self: center;
Expand Down Expand Up @@ -116,4 +175,19 @@
padding: 20px 12px;
border-radius: 12px;
}

.compatible-plant-field {
padding: 20px;
min-height: 140px;
gap: 12px;
}

.compatible-plant-field img {
width: 110px;
height: 100px;
}

.compatible-plant-field p:last-child {
font-size: 1.2rem;
}
}
98 changes: 85 additions & 13 deletions frontend/src/pages/myMatches/MyMatchesPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@apollo/client/react";
import MatchButton from "../../components/matchButton/MatchButton";
Expand Down Expand Up @@ -67,12 +67,51 @@ export default function MyMatchesPage() {
fetchPolicy: "cache-and-network",
});

const { data: bestMatchData } = useQuery<MyMatchesData>(MY_MATCHES, {
variables: {
userId,
search: null,
watering: null,
sunlight: null,
careLevel: null,
sort: PREFERENCES_SORT,
limit: 1,
offset: 0,
},
skip: !userId || !hasPreferences,
fetchPolicy: "cache-and-network",
});

const bestMatch = bestMatchData?.myMatches.plants[0];
const scrollToBestMatch = useRef(false);
const showBestMatch = () => {
reset();
setSort(PREFERENCES_SORT);
setPage(1);
scrollToBestMatch.current = true;
};

// While new results load, the previous ones stay on screen, like on
// Explore Plants, so the page does not flicker when the search, a filter
// or the page changes. If the matches could not be fetched, nothing is
// shown, so the page does not say that the user has no matches.
const data = error ? undefined : (currentData ?? previousData);
const plants = data?.myMatches.plants ?? [];
const plants = useMemo(() => data?.myMatches.plants ?? [], [data]);

useEffect(() => {
if (!scrollToBestMatch.current || !bestMatch) return;

const element = document.getElementById(`plant-${bestMatch.id}`);

if (element) {
element.scrollIntoView({
behavior: "smooth",
block: "center",
});

scrollToBestMatch.current = false;
}
}, [plants, bestMatch]);
const totalCount = data?.myMatches.totalCount ?? 0;
const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));
// Only show the loading text when there is nothing to show yet
Expand Down Expand Up @@ -124,17 +163,38 @@ export default function MyMatchesPage() {
one is removed, and that none fit when the search finds nothing.
While loading it says so, so "no matches" does not flash before the
matches are fetched. */}
<p
className={
!loading && totalCount > 0
? "my-matches-count"
: "my-matches-count my-matches-count--message"
}
aria-live="polite"
aria-busy={loading}
>
{status}
</p>

{(loading || (totalCount === 0 && !shownFiltered)) && (
<p
className="my-matches-count my-matches-count--message"
aria-live="polite"
aria-busy={loading}
>
{status}
</p>
)}

{bestMatch && (
<div
className="compatible-plant-field"
onClick={showBestMatch}
role="button"
tabIndex={0}
>
<div>
<p> {t("myMatchesPage.compatible-plant")}</p>
<p>{bestMatch.name}</p>
</div>

{bestMatch.imageURL && (
<img
src={bestMatch.imageURL}
alt={bestMatch.name ?? t("myMatchesPage.compatible-plant")}
/>
)}
</div>
)}
{/* Hidden when user has no preferences set in their profile.*/}

{/* Hidden only when the user has no matches at all, so the search and
filters stay on screen when they give no results and can be changed */}
Expand Down Expand Up @@ -165,6 +225,17 @@ export default function MyMatchesPage() {
<section
className={`matches-grid${refreshing ? " is-refreshing" : ""}`}
>
<p
className={
!loading && totalCount > 0
? "my-matches-count"
: "my-matches-count my-matches-count--message"
}
aria-live="polite"
aria-busy={loading}
>
{status}
</p>
{/* "None fit" is shown here, under the filters, like on Explore
Plants. The element is always in the box, with aria-live, so
screen readers hear it when the search or a filter removes the
Expand All @@ -175,6 +246,7 @@ export default function MyMatchesPage() {
{plants.map((plant) => (
<div
className="plant-card-match"
id={`plant-${plant.id}`}
key={plant.id}
data-testid="plant-item"
>
Expand Down
92 changes: 83 additions & 9 deletions frontend/src/tests/MyMatchesPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import userEvent from "@testing-library/user-event";
import { beforeEach, describe, it, expect, vi } from "vitest";
import MyMatchesPage from "../pages/myMatches/MyMatchesPage";
import type { Plant } from "../types/Plant";
import { PAGE_SIZE } from "../graphql/plants/queries";

const { removeUserMatch, useQuery, useUser } = vi.hoisted(() => ({
removeUserMatch: vi.fn(),
Expand Down Expand Up @@ -78,7 +77,12 @@ function mockMatches(
}

// The variables the page sent with its last myMatches query
const lastVariables = () => useQuery.mock.lastCall?.[1].variables;
const lastMatchesCall = () =>
useQuery.mock.calls
.filter(([, options]) => options.variables.limit === 12)
.at(-1);

const lastVariables = () => lastMatchesCall()?.[1].variables;

const nextPage = () => screen.getByRole("button", { name: "pagination.next" });

Expand Down Expand Up @@ -150,13 +154,8 @@ describe("myMatchesPage", () => {
mockMatches([]);
render(<MyMatchesPage />);

expect(useQuery.mock.lastCall?.[1]).toMatchObject({
variables: {
userId: "user-1",
sort: "newest",
limit: PAGE_SIZE,
offset: 0,
},
expect(lastMatchesCall()?.[1]).toMatchObject({
variables: { userId: "user-1", sort: "newest", limit: 12, offset: 0 },
skip: false,
fetchPolicy: "cache-and-network",
});
Expand Down Expand Up @@ -249,6 +248,24 @@ describe("myMatchesPage", () => {
expect(lastVariables()).toMatchObject({ offset: 12 }),
);
});

it("stays on the current page when it is still valid", async () => {
const user = userEvent.setup();

mockMatches([orchid], 30);

const { rerender } = render(<MyMatchesPage />);

await user.click(nextPage());

expect(lastVariables()).toMatchObject({ offset: 12 });

// 25 matches still give 3 pages
mockMatches([orchid], 25);
rerender(<MyMatchesPage />);

expect(lastVariables()).toMatchObject({ offset: 12 });
});
});

// The same search and filters as on Explore Plants, kept in sessionStorage
Expand Down Expand Up @@ -461,5 +478,62 @@ describe("myMatchesPage", () => {

expect(lastVariables()).toMatchObject({ sort: "newest" });
});

it("shows the best match when clicked", async () => {
const user = userEvent.setup();
mockUserWithPreferences();
mockMatches([orchid]);

render(<MyMatchesPage />);

await user.click(screen.getByRole("button", { name: /Orchid/ }));

expect(
screen.getByRole("button", { name: /preferences/ }),
).toBeInTheDocument();
});

it("scrolls to the best match when clicked", async () => {
mockUserWithPreferences();

const scrollIntoView = vi.fn();

Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
configurable: true,
value: scrollIntoView,
});

useQuery.mockImplementation((_query, options) => {
const plants = [orchid];

return {
data: {
myMatches: {
totalCount: 1,
plants: options.variables.limit === 1 ? [orchid] : plants,
filterCounts: makeFilterCounts(),
},
},
loading: false,
};
});

render(<MyMatchesPage />);

fireEvent.click(
screen
.getByText("myMatchesPage.compatible-plant")
.closest('[role="button"]')!,
);

await waitFor(() => {
expect(scrollIntoView).toHaveBeenCalledWith({
behavior: "smooth",
block: "center",
});
});

delete (HTMLElement.prototype as Partial<HTMLElement>).scrollIntoView;
});
});
});
Loading