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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
230 changes: 230 additions & 0 deletions src/__tests__/audits-route.test.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof vi.fn>;
disconnect: ReturnType<typeof vi.fn>;
}>,
}));

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<typeof page>;

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(<RouterProvider router={router} />);
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<Page>();
const currentPage = deferred<Page>();
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(<RouterProvider router={router} />);
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(<RouterProvider router={auditRouter(target)} />);
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(<RouterProvider router={auditRouter()} />);
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();
});
44 changes: 44 additions & 0 deletions src/__tests__/official-pagination.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<RouterProvider router={router} />);
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) =>
Expand Down
32 changes: 31 additions & 1 deletion src/lib/useLoadMoreObserver.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,46 @@ 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(<Target enabled={false} loadMore={next} />);
expect(observers[1].disconnect).toHaveBeenCalledTimes(2);
view.rerender(<Target enabled loadMore={next} />);
expect(observers[2].observe).toHaveBeenCalledWith(target);
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(<Target enabled loadMore={first} />);
const notify = (index: number) =>
act(() =>
observers[index].callback(
[{ isIntersecting: true } as IntersectionObserverEntry],
{} as IntersectionObserver,
),
);

view.rerender(<Target enabled loadMore={next} />);
notify(0);
expect(first).not.toHaveBeenCalled();
view.rerender(<Target enabled={false} loadMore={next} />);
notify(1);
expect(next).not.toHaveBeenCalled();
view.rerender(<Target enabled loadMore={next} />);
view.unmount();
notify(2);
expect(next).not.toHaveBeenCalled();
});
9 changes: 7 additions & 2 deletions src/lib/useLoadMoreObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,22 @@ 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();
}
},
{ rootMargin: "200px" },
);
observer.observe(target);
return () => observer.disconnect();
return () => {
active = false;
observer.disconnect();
};
}, [enabled, loadMore]);

return targetRef;
Expand Down
Loading
Loading