Skip to content

Build your personal knowledge base with Trilium Notes

fix(collections): clamp an out-of-range page during render, not after it

Elian Doran944d6730ac18
diff --git a/apps/client/src/widgets/collections/Pagination.spec.tsx b/apps/client/src/widgets/collections/Pagination.spec.tsx
index 984a8b9b3e..044629409f 100644
--- a/apps/client/src/widgets/collections/Pagination.spec.tsx
+++ b/apps/client/src/widgets/collections/Pagination.spec.tsx
@@ -1,7 +1,8 @@
/**
- * Tests for the additive `defaultPageSize` parameter added to {@link usePagination} for C7:
- * the caller-provided default (e.g. the synced `searchResultsPageSize` option) drives the page size
- * when the note has no explicit `#pageSize` label, but an explicit label always keeps winning.
+ * Tests for {@link usePagination}: the additive `defaultPageSize` parameter, where the
+ * caller-provided default (e.g. the synced `searchResultsPageSize` option) drives the page size
+ * only while the note carries no explicit `#pageSize` label; and the page clamping that keeps a
+ * shrinking result set or a growing page size from rendering a page past the end.
*/
import { render } from "preact";
import { act } from "preact/test-utils";
@@ -15,6 +16,8 @@ import { ParentComponent } from "../react/react_utils";
import { usePagination } from "./Pagination";
let observed: { pageSize: number; pageCount: number; page: number; pageNotes?: FNote[]; setPage?: (page: number) => void } | undefined;
+/** Every committed render, so a test can assert on the frames between a change and its settled state. */
+let renders: Array<{ page: number; pageCount: number }> = [];
// 25 real froca notes so usePagination's froca.getNotes() slice never round-trips to the server.
const NOTE_IDS = buildNotes(Array.from({ length: 25 }, (_, i) => ({ id: `pag-${i}`, title: `N${i}` })));
@@ -22,14 +25,17 @@ const NOTE_IDS = buildNotes(Array.from({ length: 25 }, (_, i) => ({ id: `pag-${i
function Harness({ note, noteIds = NOTE_IDS, defaultPageSize }: { note: FNote; noteIds?: string[]; defaultPageSize?: number }) {
const { page, setPage, pageNotes, pageSize, pageCount } = usePagination(note, noteIds, { defaultPageSize });
observed = { pageSize, pageCount, page, pageNotes, setPage };
+ renders.push({ page, pageCount });
return null;
}
-describe("usePagination default page size", () => {
+describe("usePagination", () => {
let container: HTMLElement | undefined;
+ let parent: Component | undefined;
beforeEach(() => {
observed = undefined;
+ renders = [];
});
afterEach(() => {
@@ -40,16 +46,32 @@ describe("usePagination default page size", () => {
}
});
- async function mount(note: FNote, defaultPageSize?: number) {
- const parent = new Component();
- // Capture in a local const so the type stays narrowed to HTMLElement inside the act() closure.
- const el = document.createElement("div");
- container = el;
- document.body.appendChild(el);
+ async function mount(note: FNote, defaultPageSize?: number, noteIds?: string[]) {
+ parent = new Component();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ await rerender(note, defaultPageSize, noteIds);
+ }
+
+ /** Lets the pending `froca.getNotes()` promise resolve and its state update commit. */
+ async function settle() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ }
+
+ /** Renders into the same container, so the hook keeps its state the way a prop change would. */
+ async function rerender(note: FNote, defaultPageSize?: number, noteIds?: string[]) {
+ // Capture in local consts so the types stay narrowed inside the act() closure.
+ const el = container;
+ const parentComponent = parent;
+ if (!el || !parentComponent) {
+ throw new Error("mount() has to run first");
+ }
await act(async () => {
render(
- <ParentComponent.Provider value={parent}>
- <Harness note={note} defaultPageSize={defaultPageSize} />
+ <ParentComponent.Provider value={parentComponent}>
+ <Harness note={note} noteIds={noteIds} defaultPageSize={defaultPageSize} />
</ParentComponent.Provider>,
el
);
@@ -76,6 +98,44 @@ describe("usePagination default page size", () => {
expect(observed?.pageSize).toBe(20);
});
+ it("never renders past the last page when the result set shrinks under it", async () => {
+ const note = buildNote({ title: "Search", type: "search" });
+ await mount(note, 10);
+ await act(async () => observed?.setPage?.(3));
+ await settle();
+ expect(observed?.page).toBe(3);
+ expect(observed?.pageNotes?.map((n) => n.noteId)).toEqual(NOTE_IDS.slice(20, 25));
+
+ renders = [];
+ await rerender(note, 10, NOTE_IDS.slice(0, 12));
+ await settle();
+
+ // Callers slice with (page - 1) * pageSize, so a page past the end shows the previous
+ // result set's notes in the list and grid views and nothing in the search cards. No
+ // committed frame may carry one, not just the settled state.
+ expect(renders.length).toBeGreaterThan(0);
+ expect(renders.every(({ page, pageCount }) => page <= pageCount)).toBe(true);
+ expect(observed?.page).toBe(2);
+ expect(observed?.pageNotes?.map((n) => n.noteId)).toEqual(NOTE_IDS.slice(10, 12));
+ });
+
+ it("never renders past the last page when the page size grows past it", async () => {
+ const note = buildNote({ title: "Search", type: "search" });
+ await mount(note, 10);
+ await act(async () => observed?.setPage?.(3));
+ await settle();
+
+ // What the "Per page" selector does: 25 notes at 25 per page collapse to a single page.
+ renders = [];
+ await rerender(note, 25);
+ await settle();
+
+ expect(renders.length).toBeGreaterThan(0);
+ expect(renders.every(({ page, pageCount }) => page <= pageCount)).toBe(true);
+ expect(observed?.page).toBe(1);
+ expect(observed?.pageNotes).toHaveLength(25);
+ });
+
it("discards a stale note load that resolves after a newer page's load", async () => {
// Take over froca.getNotes with manually-resolved deferreds so resolution order can be
// inverted: rapid page flips issue overlapping loads, and the older one must not win.
diff --git a/apps/client/src/widgets/collections/Pagination.tsx b/apps/client/src/widgets/collections/Pagination.tsx
index 62e0d26491..42a8edd813 100644
--- a/apps/client/src/widgets/collections/Pagination.tsx
+++ b/apps/client/src/widgets/collections/Pagination.tsx
@@ -150,13 +150,16 @@ export function usePagination(
const normalizedPageSize = (pageSize && pageSize > 0 ? pageSize : 20);
// Calculate start/end index.
- const startIdx = (page - 1) * normalizedPageSize;
- const endIdx = startIdx + normalizedPageSize;
const pageCount = Math.ceil(noteIds.length / normalizedPageSize);
+ // A growing page size, or a shrinking result set, can leave `page` past the last page. Clamp
+ // here rather than waiting for the effect below: callers slice with the page this returns, so
+ // an out-of-range value renders the previous result set's notes in the list and grid views,
+ // and nothing at all in the search cards, which re-derive their own slice from it.
+ const effectivePage = pageCount > 0 ? Math.min(page, pageCount) : page;
+ const startIdx = (effectivePage - 1) * normalizedPageSize;
+ const endIdx = startIdx + normalizedPageSize;
- // If the page size grows (or the result set shrinks) enough that the current page no longer
- // exists, step back onto the last valid page so the slice below can't silently yield an empty
- // page. A no-op in steady state, so existing list/grid callers are unaffected.
+ // Catch the state up to what is being rendered, so the pager and `setPage` callers agree.
useEffect(() => {
if (pageCount > 0 && page > pageCount) {
setPage(pageCount);
@@ -167,12 +170,6 @@ export function usePagination(
const pageNoteIds = noteIds.slice(startIdx, Math.min(endIdx, noteIds.length));
useEffect(() => {
- // While the clamp effect above is stepping an out-of-range page back onto the last valid
- // one, the slice is empty; loading it would only flash the list blank for a frame.
- if (pageCount > 0 && page > pageCount) {
- return;
- }
-
// Overlapping loads (rapid page flips, a shrinking result set) can resolve out of order;
// the cleanup flag makes sure a superseded load can no longer overwrite the current page.
let cancelled = false;
@@ -184,10 +181,10 @@ export function usePagination(
return () => {
cancelled = true;
};
- }, [ note, noteIds, page, normalizedPageSize ]);
+ }, [ note, noteIds, effectivePage, normalizedPageSize ]);
return {
- page, setPage, pageNotes, pageCount,
+ page: effectivePage, setPage, pageNotes, pageCount,
pageSize: normalizedPageSize,
totalNotes: noteIds.length
};