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
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,4 @@ See [quality.md](docs/quality.md) for Lighthouse results, testing, accessibility

## Known issues

If you type and switch pages within half a second after updating your profile, the last few letters are not saved, because the debounce didn't have time to send.

Information on plant card does not translate to Norwegian.
- Information on plant card does not translate to Norwegian.
2 changes: 1 addition & 1 deletion docs/quality.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ 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.

- **Debounced search:** The search functionality uses debouncing to avoid updating search results on every keystroke, reducing unnecessary search operations.
- **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.

## Design Choices

Expand Down
12 changes: 4 additions & 8 deletions docs/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,24 +138,20 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p
- `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`

- Tests the profile page, including the name and image, that the preferences tab is shown by default, and that the user can switch to the saved plants tab and see the saved plants. Also includes a snapshot test.

- 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.
- `LanguageSwitcher.test.tsx`
- Tests the language switcher button in both Norwegian and English, and verifies that it shows the correct label and accessible name, and that clicking it switches to the other language.

- 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.
- `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.
- `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`
- 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.
- `useDebounce.test.ts`
- The initial value is returned at once, updates only come after the delay, the delay restarts on quick changes, and the default delay is 800 ms.
- The initial value is returned at once, updates only come after the delay, the delay restarts on quick changes, and the default delay is 300 ms.
- `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.

Expand Down Expand Up @@ -226,7 +222,7 @@ The test user has no preferences, so PlantMatch shows the plants in random order

**Profile (`uiUserProfile`):** changing name, description and avatar is shown at once and is still there after a reload, so the changes are stored in the database.

Saving the profile is debounced by 800 ms. The test waits until the save request has reached the backend before reloading, instead of waiting a fixed time, so it does not depend on the length of the debounce.
Saving the profile is debounced by 500 ms, and the text is also saved at once when a field loses focus. The test waits until the save request has reached the backend before reloading, instead of waiting a fixed time, so it does not depend on the length of the debounce.

**API tests:**

Expand Down
2 changes: 1 addition & 1 deletion e2e/uiExplorePlants.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ test("user pages, filters, searches, opens a plant, sorts and resets", async ({
await careLevelSelect.selectOption("");
await expect(cards).toHaveCount(12);
await searchField.fill("plant");
// expect waits automatically, so the 800 ms debounce is not a problem
// expect waits automatically, so the 300 ms debounce is not a problem
await expect(cards).toHaveCount(2);
await expect(cards.nth(0)).toContainText("Jade Plant");
await expect(cards.nth(1)).toContainText("Snake Plant");
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";

export function useDebounce<T>(value: T, delay = 800): T {
export function useDebounce<T>(value: T, delay = 300): T {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
Expand Down
63 changes: 53 additions & 10 deletions frontend/src/hooks/useProfile.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,71 @@
import { useMutation } from "@apollo/client/react";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useUser } from "../context/UserContext";
import {
UPDATE_USER_PROFILE,
type UpdateUserProfileData,
} from "../context/userQueries";
import { useDebounce } from "./useDebounce";

type ProfileDraft = { name?: string; description?: string };

const sameDraft = (a: ProfileDraft, b: ProfileDraft) =>
a.name === b.name && a.description === b.description;

export function useProfile() {
const { userId, user } = useUser();
const [updateProfile] =
useMutation<UpdateUserProfileData>(UPDATE_USER_PROFILE);

// What the user has typed, shown right away but saved only after they stop typing
const [draft, setDraft] = useState<{ name?: string; description?: string }>(
{},
);
// What the user has typed, shown right away and saved after they stop typing
const [draft, setDraft] = useState<ProfileDraft>({});
const savedDraft = useDebounce(draft, 500);

// The latest draft and the last draft sent, kept in refs so saveNow can
// read them from cleanup functions and event listeners
const draftRef = useRef(draft);
const lastSentRef = useRef<ProfileDraft>({});
useEffect(() => {
draftRef.current = draft;
}, [draft]);

// Sends the draft, unless it is empty or was already sent
const save = useCallback(
(next: ProfileDraft) => {
if (!userId || Object.keys(next).length === 0) return;
if (sameDraft(next, lastSentRef.current)) return;
lastSentRef.current = next;
updateProfile({ variables: { userId, ...next } }).catch(() => {
// Backend unreachable. The text stays on screen, it just isn't saved.
// Forget the failed draft so the next blur or edit tries again.
lastSentRef.current = {};
});
},
[userId, updateProfile],
);

// Save when the user stops typing
useEffect(() => {
save(savedDraft);
}, [savedDraft, save]);

// Save right away, without waiting for the debounce
const saveNow = useCallback(() => save(draftRef.current), [save]);

// Save when the user leaves the profile page (unmount) or reloads/closes
// the tab (pagehide), so the last letters are not lost
const saveNowRef = useRef(saveNow);
useEffect(() => {
saveNowRef.current = saveNow;
}, [saveNow]);
useEffect(() => {
if (!userId || Object.keys(savedDraft).length === 0) return;
updateProfile({ variables: { userId, ...savedDraft } }).catch(() => {
// Backend unreachable. The text stays on screen, it just isn't saved.
});
}, [userId, savedDraft, updateProfile]);
const handlePageHide = () => saveNowRef.current();
window.addEventListener("pagehide", handlePageHide);
return () => {
window.removeEventListener("pagehide", handlePageHide);
saveNowRef.current();
};
}, []);

// Resolves to true when the picture was saved in the database
const setProfilePicture = async (profilePicture: string) => {
Expand Down Expand Up @@ -57,5 +99,6 @@ export function useProfile() {
setDescription: (description: string) =>
setDraft((d) => ({ ...d, description })),
setProfilePicture,
saveNow,
};
}
2 changes: 1 addition & 1 deletion frontend/src/pages/explorePlants/ExplorePlants.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default function ExplorePlants() {
const { matches, addMatch } = useMatchedPlants();

const search = searchParams.get("search") ?? "";
const debouncedSearch = useDebounce(search, 800);
const debouncedSearch = useDebounce(search, 300);
const watering = searchParams.get("watering") ?? "";
const sunlight = searchParams.get("sunlight") ?? "";
const careLevel = searchParams.get("careLevel") ?? "";
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/pages/profile/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default function Profile() {
setName,
setDescription,
setProfilePicture,
saveNow,
} = useProfile();
const shownName = name ?? t("profile.name");
const shownDescription = description ?? t("profile.description");
Expand Down Expand Up @@ -118,6 +119,7 @@ export default function Profile() {
type="text"
value={name ?? ""}
onChange={(event) => setName(event.target.value)}
onBlur={saveNow}
maxLength={40}
placeholder={t("profile.placeholderName")}
/>
Expand All @@ -128,6 +130,7 @@ export default function Profile() {
type="text"
value={description ?? ""}
onChange={(event) => setDescription(event.target.value)}
onBlur={saveNow}
maxLength={100}
placeholder={t("profile.placeholderAbout")}
/>
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/tests/ExplorePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ function setup(
const cards = () => screen.queryAllByTestId("plant-card");
const cardNames = () => cards().map((card) => card.textContent);

// Move past the 800 ms search debounce
// Move past the 300 ms search debounce
async function advanceDebounce() {
await act(async () => {
vi.advanceTimersByTime(800);
vi.advanceTimersByTime(300);
});
}

Expand Down
71 changes: 71 additions & 0 deletions frontend/src/tests/Profile.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,77 @@ describe("Profile page", () => {
);
});

// Calls to updateProfile that saved the given name
const savesOfName = (name: string) =>
updateProfile.mock.calls.filter(
([options]) => options.variables.name === name,
);

it("saves the text at once when the field loses focus, and only once", async () => {
const user = userEvent.setup();

render(<Profile />);
await user.click(
screen.getByRole("button", { name: "profile.editProfile" }),
);
await user.type(
screen.getByRole("textbox", { name: "profile.enterName" }),
"Nina",
);

// Typing takes far less than the 500 ms debounce, so nothing is saved yet
expect(savesOfName("Nina")).toHaveLength(0);

// Leaving the field saves right away, without waiting for the debounce
await user.tab();
expect(updateProfile).toHaveBeenCalledWith({
variables: { userId: "user-1", name: "Nina" },
});

// When the debounce runs later, the same text is not sent again
await new Promise((resolve) => setTimeout(resolve, 600));
expect(savesOfName("Nina")).toHaveLength(1);
});

it("saves the text when the user leaves the profile page", async () => {
const user = userEvent.setup();

const { unmount } = render(<Profile />);
await user.click(
screen.getByRole("button", { name: "profile.editProfile" }),
);
await user.type(
screen.getByRole("textbox", { name: "profile.enterName" }),
"Nina",
);

// Navigating to another page removes the profile page
unmount();

expect(updateProfile).toHaveBeenCalledWith({
variables: { userId: "user-1", name: "Nina" },
});
});

it("saves the text when the tab is reloaded or closed", async () => {
const user = userEvent.setup();

render(<Profile />);
await user.click(
screen.getByRole("button", { name: "profile.editProfile" }),
);
await user.type(
screen.getByRole("textbox", { name: "profile.enterName" }),
"Nina",
);

window.dispatchEvent(new Event("pagehide"));

expect(updateProfile).toHaveBeenCalledWith({
variables: { userId: "user-1", name: "Nina" },
});
});

it("shows the avatar saved on the user", async () => {
const user = userEvent.setup();
mockUser("monstera");
Expand Down
24 changes: 12 additions & 12 deletions frontend/src/tests/useDebounce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe("useDebounce", () => {

// the hook starts with the value it is given, with no delay
it("returns the initial value immediately", () => {
const { result } = renderHook(() => useDebounce("a", 800));
const { result } = renderHook(() => useDebounce("a", 300));

expect(result.current).toBe("a");
});
Expand All @@ -23,7 +23,7 @@ describe("useDebounce", () => {
it("updates the value only after the delay", () => {
// initialProps lets us change the value later with rerender()
const { result, rerender } = renderHook(
({ value }) => useDebounce(value, 800),
({ value }) => useDebounce(value, 300),
{ initialProps: { value: "a" } },
);

Expand All @@ -32,7 +32,7 @@ describe("useDebounce", () => {

// act() is needed because the timer updates React state
act(() => {
vi.advanceTimersByTime(800);
vi.advanceTimersByTime(300);
});
expect(result.current).toBe("ab");
});
Expand All @@ -41,37 +41,37 @@ describe("useDebounce", () => {
// so the value only updates when the user has stopped typing
it("restarts the delay when the value changes quickly", () => {
const { result, rerender } = renderHook(
({ value }) => useDebounce(value, 800),
({ value }) => useDebounce(value, 300),
{ initialProps: { value: "a" } },
);

rerender({ value: "ab" });
act(() => {
vi.advanceTimersByTime(500);
vi.advanceTimersByTime(200);
});

rerender({ value: "abc" }); // new change, timer starts over
act(() => {
vi.advanceTimersByTime(500);
vi.advanceTimersByTime(200);
});
expect(result.current).toBe("a"); // only 500 ms since the last change
expect(result.current).toBe("a"); // only 200 ms since the last change

act(() => {
vi.advanceTimersByTime(300);
vi.advanceTimersByTime(100);
});
expect(result.current).toBe("abc"); // 800 ms since the last change
expect(result.current).toBe("abc"); // 300 ms since the last change
});

// the hook has a default delay of 800 ms when none is given
it("uses 800 ms as the default delay", () => {
// the hook has a default delay of 300 ms when none is given
it("uses 300 ms as the default delay", () => {
const { result, rerender } = renderHook(({ value }) => useDebounce(value), {
initialProps: { value: "a" },
});

rerender({ value: "b" });

act(() => {
vi.advanceTimersByTime(799);
vi.advanceTimersByTime(299);
});
expect(result.current).toBe("a"); // 1 ms too early

Expand Down
Loading