From 71f29a61bb13bf2d55bc8b7974763ad776d54591 Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Mon, 30 Nov 2026 18:31:30 +0800 Subject: [PATCH] fix: prevent stale pages after switching lists --- CHANGELOG.md | 2 + src/__tests__/audits-route.test.tsx | 230 +++++++++++++++++++++ src/__tests__/official-pagination.test.tsx | 44 ++++ src/lib/useLoadMoreObserver.test.tsx | 32 ++- src/lib/useLoadMoreObserver.ts | 9 +- src/routes/audits.tsx | 20 +- 6 files changed, 330 insertions(+), 7 deletions(-) create mode 100644 src/__tests__/audits-route.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 1560918a3c..bc55ab1e7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Pagination: ignore callbacks and requests from previous audit tabs or catalog searches so stale pages cannot mix into the current results. + - Navigation: restore keyboard focus and selection in publisher member menus and the header's More menu. - Plugin validation: hide native package-entry warnings on bundle plugins, including retained findings from older scans. Applicable findings and scan history remain available. diff --git a/src/__tests__/audits-route.test.tsx b/src/__tests__/audits-route.test.tsx new file mode 100644 index 0000000000..7bf8bbee15 --- /dev/null +++ b/src/__tests__/audits-route.test.tsx @@ -0,0 +1,230 @@ +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { getFunctionName } from "convex/server"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { Route } from "../routes/audits"; +import { deferred } from "./helpers/deferred"; + +const { queryMock, observers } = vi.hoisted(() => ({ + queryMock: vi.fn(), + observers: [] as Array<{ + callback: IntersectionObserverCallback; + options?: IntersectionObserverInit; + observe: ReturnType; + disconnect: ReturnType; + }>, +})); + +vi.mock("../convex/client", () => ({ + convexHttp: { query: (...args: unknown[]) => queryMock(...args) }, +})); + +type Target = "skills" | "plugins"; + +function page(target: Target, name: string, cursor: string | null) { + const item = { + displayName: name, + summary: `${name} summary`, + stats: { downloads: 12, installs: 0, stars: 0, versions: 1 }, + updatedAt: 1, + }; + const rows = [ + target === "skills" + ? { kind: "skill", skill: { ...item, slug: name }, ownerHandle: "owner", latestVersion: null } + : { + kind: "plugin", + package: { + ...item, + name, + family: "code-plugin", + channel: "community", + isOfficial: false, + ownerHandle: "owner", + latestVersion: null, + }, + latestRelease: null, + }, + ]; + return target === "skills" + ? { page: rows, hasMore: cursor !== null, nextCursor: cursor } + : { page: rows, continueCursor: cursor ?? "", isDone: cursor === null }; +} + +type Page = ReturnType; + +function auditRouter(target: Target = "skills") { + const root = createRootRoute(); + const route = Route.update({ + id: "/audits", + path: "/audits", + getParentRoute: () => root, + } as never); + return createRouter({ + routeTree: root.addChildren([route]), + history: createMemoryHistory({ initialEntries: [`/audits?type=${target}`] }), + }); +} + +function intersect(observer: (typeof observers)[number]) { + observer.callback( + [{ isIntersecting: true } as IntersectionObserverEntry], + {} as IntersectionObserver, + ); +} + +function rowNames() { + return within(screen.getByRole("table")) + .getAllByRole("link") + .map((link) => link.textContent); +} + +beforeEach(() => { + queryMock.mockReset(); + observers.length = 0; + vi.stubGlobal("scrollTo", vi.fn()); + vi.stubGlobal( + "IntersectionObserver", + class { + observe = vi.fn(); + disconnect = vi.fn(); + constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { + observers.push({ callback, options, observe: this.observe, disconnect: this.disconnect }); + } + }, + ); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +it("ignores a queued observer callback from the previous audit target", async () => { + queryMock.mockImplementation((reference) => { + const target = getFunctionName(reference).startsWith("skills:") ? "skills" : "plugins"; + return Promise.resolve(page(target, `${target}-first`, `${target}:1`)); + }); + const router = auditRouter(); + render(); + await screen.findByText("skills-first"); + const oldObserver = observers.at(-1)!; + + await act(async () => router.navigate({ to: "/audits", search: { type: "plugins" } })); + await screen.findByText("plugins-first"); + expect(oldObserver.disconnect).toHaveBeenCalled(); + const calls = queryMock.mock.calls.length; + await act(async () => intersect(oldObserver)); + + expect(queryMock).toHaveBeenCalledTimes(calls); + expect(rowNames()).toEqual(["@owner / plugins-first"]); +}); + +it.each(["resolve", "reject"] as const)( + "keeps the current page request fenced when an old request %ss", + async (settlement) => { + const oldPage = deferred(); + const currentPage = deferred(); + queryMock.mockImplementation((reference, { paginationOpts }) => { + const target = getFunctionName(reference).startsWith("skills:") ? "skills" : "plugins"; + return paginationOpts.cursor + ? target === "skills" + ? oldPage.promise + : currentPage.promise + : Promise.resolve(page(target, `${target}-first`, `${target}:1`)); + }); + const router = auditRouter(); + render(); + await screen.findByText("skills-first"); + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + await act(async () => router.navigate({ to: "/audits", search: { type: "plugins" } })); + await screen.findByText("plugins-first"); + const currentObserver = observers.at(-1)!; + + await act(async () => { + intersect(currentObserver); + if (settlement === "resolve") oldPage.resolve(page("skills", "stale-skill", null)); + else oldPage.reject(new Error("stale page failed")); + await oldPage.promise.catch(() => undefined); + intersect(currentObserver); + }); + + expect( + queryMock.mock.calls.filter( + ([reference, args]) => + getFunctionName(reference) === "packages:listAuditPage" && + args.paginationOpts.cursor === "plugins:1", + ), + ).toHaveLength(1); + expect(screen.queryByText(/could not load/)).toBeNull(); + await act(async () => currentPage.resolve(page("plugins", "plugins-second", null))); + expect(rowNames()).toEqual(["@owner / plugins-first", "@owner / plugins-second"]); + expect(screen.queryByRole("button", { name: "Load more" })).toBeNull(); + }, +); + +it.each(["skills", "plugins"] as const)( + "appends %s pages in order and stops at the final cursor", + async (target) => { + queryMock.mockImplementation((_reference, { paginationOpts }) => + Promise.resolve( + page( + target, + paginationOpts.cursor ? "second" : "first", + paginationOpts.cursor ? null : "next", + ), + ), + ); + render(); + await screen.findByText("first"); + expect(observers.at(-1)?.options).toEqual({ rootMargin: "420px 0px" }); + const calls = queryMock.mock.calls.length; + await act(async () => + observers + .at(-1)! + .callback( + [ + { isIntersecting: false } as IntersectionObserverEntry, + { isIntersecting: true } as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ), + ); + expect(queryMock).toHaveBeenCalledTimes(calls); + await act(async () => intersect(observers.at(-1)!)); + await screen.findByText("second"); + + expect(queryMock).toHaveBeenLastCalledWith(expect.anything(), { + paginationOpts: { cursor: "next", numItems: 50 }, + }); + expect(rowNames()).toEqual(["@owner / first", "@owner / second"]); + expect(screen.queryByRole("button", { name: "Load more" })).toBeNull(); + }, +); + +it("retains the current page after an error and retries the same cursor manually", async () => { + vi.spyOn(console, "error").mockImplementation(() => undefined); + queryMock + .mockResolvedValueOnce(page("skills", "first", "next")) + .mockRejectedValueOnce(new Error("page failed")) + .mockResolvedValueOnce(page("skills", "second", null)); + render(); + await screen.findByText("first"); + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + await screen.findByText("Some audit rows could not load. Try again in a moment."); + expect(rowNames()).toEqual(["@owner / first"]); + fireEvent.click(screen.getByRole("button", { name: "Load more" })); + await screen.findByText("second"); + + expect(queryMock.mock.calls.slice(1).map(([, args]) => args.paginationOpts)).toEqual([ + { cursor: "next", numItems: 50 }, + { cursor: "next", numItems: 50 }, + ]); + expect(rowNames()).toEqual(["@owner / first", "@owner / second"]); + expect(screen.queryByText(/could not load/)).toBeNull(); +}); diff --git a/src/__tests__/official-pagination.test.tsx b/src/__tests__/official-pagination.test.tsx index 2a7069f3c6..e0b87d0215 100644 --- a/src/__tests__/official-pagination.test.tsx +++ b/src/__tests__/official-pagination.test.tsx @@ -135,6 +135,50 @@ it("keeps the same official route input when search loads a new first page", asy expect((input as HTMLInputElement).value).toBe("new"); }); +it("ignores an old search observer callback and paginates the current search", async () => { + queryMock.mockImplementation((_reference, args) => + Promise.resolve( + page( + `${args.query}-${args.paginationOpts.cursor ? "second" : "first"}`, + args.paginationOpts.cursor ? null : `${args.query}:1`, + ), + ), + ); + const router = officialRouter(); + render(); + await screen.findByText("old-first"); + const oldObserver = observers.at(-1)!; + + await act(async () => router.navigate({ to: "/official", search: { q: "new" } })); + await screen.findByText("new-first"); + const calls = queryMock.mock.calls.length; + await act(async () => + oldObserver.callback( + [{ isIntersecting: true } as IntersectionObserverEntry], + {} as IntersectionObserver, + ), + ); + expect(queryMock).toHaveBeenCalledTimes(calls); + expect(screen.queryByText("old-second")).toBeNull(); + + await act(async () => + observers + .at(-1)! + .callback( + [{ isIntersecting: true } as IntersectionObserverEntry], + {} as IntersectionObserver, + ), + ); + await screen.findByText("new-second"); + expect( + Array.from( + document.querySelectorAll(".publisher-directory-list > div"), + (row) => row.textContent, + ), + ).toEqual(["new-first", "new-second"]); + expect(screen.queryByRole("button", { name: "Load more" })).toBeNull(); +}); + it("rejects an old pagination response after the router publishes a new query", async () => { const oldPage = pendingPage(); queryMock.mockImplementation((_reference, args) => diff --git a/src/lib/useLoadMoreObserver.test.tsx b/src/lib/useLoadMoreObserver.test.tsx index ce30712110..075d5c0da1 100644 --- a/src/lib/useLoadMoreObserver.test.tsx +++ b/src/lib/useLoadMoreObserver.test.tsx @@ -68,12 +68,18 @@ it("retains its target and rearms for callback or enabled changes with cleanup", expect(observers[1].observe).toHaveBeenCalledWith(target); act(() => observers[1].callback( - [{ isIntersecting: true } as IntersectionObserverEntry], + [ + { isIntersecting: false } as IntersectionObserverEntry, + { isIntersecting: true } as IntersectionObserverEntry, + ], {} as IntersectionObserver, ), ); expect(first).not.toHaveBeenCalled(); expect(next).toHaveBeenCalledOnce(); + expect(observers[1].disconnect.mock.invocationCallOrder[0]).toBeLessThan( + next.mock.invocationCallOrder[0], + ); view.rerender(); expect(observers[1].disconnect).toHaveBeenCalledTimes(2); view.rerender(); @@ -81,3 +87,27 @@ it("retains its target and rearms for callback or enabled changes with cleanup", view.unmount(); expect(observers[2].disconnect).toHaveBeenCalledOnce(); }); + +it("ignores queued callbacks after replacement, disabling, or unmounting", () => { + const first = vi.fn(); + const next = vi.fn(); + const view = render(); + const notify = (index: number) => + act(() => + observers[index].callback( + [{ isIntersecting: true } as IntersectionObserverEntry], + {} as IntersectionObserver, + ), + ); + + view.rerender(); + notify(0); + expect(first).not.toHaveBeenCalled(); + view.rerender(); + notify(1); + expect(next).not.toHaveBeenCalled(); + view.rerender(); + view.unmount(); + notify(2); + expect(next).not.toHaveBeenCalled(); +}); diff --git a/src/lib/useLoadMoreObserver.ts b/src/lib/useLoadMoreObserver.ts index 75029bd50e..16c8a96c4f 100644 --- a/src/lib/useLoadMoreObserver.ts +++ b/src/lib/useLoadMoreObserver.ts @@ -7,9 +7,11 @@ export function useLoadMoreObserver(enabled: boolean, loadMore: () => void | Pro if (!enabled || typeof IntersectionObserver === "undefined") return undefined; const target = targetRef.current; if (!target) return undefined; + // Disconnecting does not discard intersection entries already queued for delivery. + let active = true; const observer = new IntersectionObserver( (entries) => { - if (entries.some((entry) => entry.isIntersecting)) { + if (active && entries.some((entry) => entry.isIntersecting)) { observer.disconnect(); void loadMore(); } @@ -17,7 +19,10 @@ export function useLoadMoreObserver(enabled: boolean, loadMore: () => void | Pro { rootMargin: "200px" }, ); observer.observe(target); - return () => observer.disconnect(); + return () => { + active = false; + observer.disconnect(); + }; }, [enabled, loadMore]); return targetRef; diff --git a/src/routes/audits.tsx b/src/routes/audits.tsx index 27fb69b4c7..93e154c847 100644 --- a/src/routes/audits.tsx +++ b/src/routes/audits.tsx @@ -124,7 +124,7 @@ function useAuditFeed(type: AuditTarget) { setError(true); setStatus(nextCursor ? "idle" : "done"); } finally { - loadingMoreRef.current = false; + if (generation === generationRef.current) loadingMoreRef.current = false; } }, [type], @@ -133,6 +133,7 @@ function useAuditFeed(type: AuditTarget) { useEffect(() => { generationRef.current += 1; const generation = generationRef.current; + loadingMoreRef.current = false; setRows([]); setCursor(null); setError(false); @@ -146,18 +147,29 @@ function useAuditFeed(type: AuditTarget) { useEffect(() => { const node = sentinelRef.current; if (!node || !cursor || status !== "idle") return () => {}; + const generation = generationRef.current; + let active = true; const observer = new IntersectionObserver( (entries) => { const [entry] = entries; - if (!entry?.isIntersecting || loadingMoreRef.current) return; + if ( + !active || + generation !== generationRef.current || + !entry?.isIntersecting || + loadingMoreRef.current + ) + return; loadingMoreRef.current = true; setStatus("loadingMore"); - void fetchPage(cursor, generationRef.current); + void fetchPage(cursor, generation); }, { rootMargin: "420px 0px" }, ); observer.observe(node); - return () => observer.disconnect(); + return () => { + active = false; + observer.disconnect(); + }; }, [cursor, fetchPage, status]); return {