From 1d7acde5573e8b3a624ab66a93fd9ffb6992cbe3 Mon Sep 17 00:00:00 2001 From: Helene Lotsberg Date: Fri, 6 Nov 2026 17:59:52 +0100 Subject: [PATCH] shorten search debounce and save profile text on blur and unmount, written/updated related tests and updated related documentation --- README.md | 4 +- docs/quality.md | 2 +- docs/tests.md | 12 ++-- e2e/uiExplorePlants.spec.ts | 2 +- frontend/src/hooks/useDebounce.ts | 2 +- frontend/src/hooks/useProfile.ts | 63 +++++++++++++--- .../src/pages/explorePlants/ExplorePlants.tsx | 2 +- frontend/src/pages/profile/Profile.tsx | 3 + frontend/src/tests/ExplorePage.test.tsx | 4 +- frontend/src/tests/Profile.test.tsx | 71 +++++++++++++++++++ frontend/src/tests/useDebounce.test.ts | 24 +++---- 11 files changed, 150 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 0e8e4ea7..61aeddaf 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/quality.md b/docs/quality.md index 09916052..860bacdb 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -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 diff --git a/docs/tests.md b/docs/tests.md index c83c81c4..4b3533f1 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -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. @@ -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:** diff --git a/e2e/uiExplorePlants.spec.ts b/e2e/uiExplorePlants.spec.ts index a6b40825..c39faa16 100644 --- a/e2e/uiExplorePlants.spec.ts +++ b/e2e/uiExplorePlants.spec.ts @@ -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"); diff --git a/frontend/src/hooks/useDebounce.ts b/frontend/src/hooks/useDebounce.ts index 24205b9e..a1d18709 100644 --- a/frontend/src/hooks/useDebounce.ts +++ b/frontend/src/hooks/useDebounce.ts @@ -1,6 +1,6 @@ import { useEffect, useState } from "react"; -export function useDebounce(value: T, delay = 800): T { +export function useDebounce(value: T, delay = 300): T { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { diff --git a/frontend/src/hooks/useProfile.ts b/frontend/src/hooks/useProfile.ts index 72e908c0..532a3415 100644 --- a/frontend/src/hooks/useProfile.ts +++ b/frontend/src/hooks/useProfile.ts @@ -1,5 +1,5 @@ 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, @@ -7,23 +7,65 @@ import { } 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(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({}); 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({}); + 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) => { @@ -57,5 +99,6 @@ export function useProfile() { setDescription: (description: string) => setDraft((d) => ({ ...d, description })), setProfilePicture, + saveNow, }; } diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index 830d76d7..4cef8d32 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -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") ?? ""; diff --git a/frontend/src/pages/profile/Profile.tsx b/frontend/src/pages/profile/Profile.tsx index 9e428c35..860c8034 100644 --- a/frontend/src/pages/profile/Profile.tsx +++ b/frontend/src/pages/profile/Profile.tsx @@ -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"); @@ -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")} /> @@ -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")} /> diff --git a/frontend/src/tests/ExplorePage.test.tsx b/frontend/src/tests/ExplorePage.test.tsx index 64bd50c8..1acac3c8 100644 --- a/frontend/src/tests/ExplorePage.test.tsx +++ b/frontend/src/tests/ExplorePage.test.tsx @@ -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); }); } diff --git a/frontend/src/tests/Profile.test.tsx b/frontend/src/tests/Profile.test.tsx index f9646a2d..b07f0e59 100644 --- a/frontend/src/tests/Profile.test.tsx +++ b/frontend/src/tests/Profile.test.tsx @@ -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(); + 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(); + 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(); + 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"); diff --git a/frontend/src/tests/useDebounce.test.ts b/frontend/src/tests/useDebounce.test.ts index 1692a7e6..03c3503c 100644 --- a/frontend/src/tests/useDebounce.test.ts +++ b/frontend/src/tests/useDebounce.test.ts @@ -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"); }); @@ -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" } }, ); @@ -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"); }); @@ -41,29 +41,29 @@ 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" }, }); @@ -71,7 +71,7 @@ describe("useDebounce", () => { rerender({ value: "b" }); act(() => { - vi.advanceTimersByTime(799); + vi.advanceTimersByTime(299); }); expect(result.current).toBe("a"); // 1 ms too early