Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

perf(sidebar): defer file thumbnail generation until a row nears the viewport (#8034)

briosd552c4cd9f04
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
index 99291f7ce0..8fd4baf8f3 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
@@ -12,6 +12,7 @@ import {
} from "@app/components/shared/PolicyBadges";
import { getFileDocVariant } from "@app/components/shared/filePreview/getFileTypeIcon";
import { useLazyThumbnail } from "@app/hooks/useLazyThumbnail";
+import { useInViewport } from "@app/hooks/useInViewport";
import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
import { formatFileSize, IMAGE_EXTENSIONS } from "@app/utils/fileUtils";
@@ -270,13 +271,15 @@ export const FileItem = React.memo(function FileItem({
// Only use raster thumbnails for PDFs and images — everything else uses scalable SVG icons
const useRasterThumb = ext === "pdf" || IMAGE_EXTENSIONS.has(ext);
+ const itemRef = useRef<HTMLDivElement>(null);
+ const isNearViewport = useInViewport(itemRef);
const resolvedThumbnail = useLazyThumbnail(
fileId,
size ?? 0,
useRasterThumb ? thumbnailUrl : undefined,
+ isNearViewport,
);
- const itemRef = useRef<HTMLDivElement>(null);
const [hoverRect, setHoverRect] = useState<DOMRect | null>(null);
const [menuOpened, setMenuOpened] = useState(false);
diff --git a/frontend/editor/src/core/hooks/useInViewport.test.tsx b/frontend/editor/src/core/hooks/useInViewport.test.tsx
new file mode 100644
index 0000000000..adfc2f35b3
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useInViewport.test.tsx
@@ -0,0 +1,101 @@
+import { useRef } from "react";
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useInViewport } from "@app/hooks/useInViewport";
+
+function entry(
+ target: Element,
+ isIntersecting: boolean,
+): IntersectionObserverEntry {
+ const rect = target.getBoundingClientRect();
+ return {
+ boundingClientRect: rect,
+ intersectionRatio: isIntersecting ? 1 : 0,
+ intersectionRect: rect,
+ isIntersecting,
+ rootBounds: null,
+ target,
+ time: performance.now(),
+ };
+}
+
+class FakeIntersectionObserver implements IntersectionObserver {
+ static instances: FakeIntersectionObserver[] = [];
+ readonly root: Element | Document | null;
+ readonly rootMargin: string;
+ readonly scrollMargin = "0px";
+ readonly thresholds: readonly number[] = [];
+ observe = vi.fn();
+ unobserve = vi.fn();
+ disconnect = vi.fn();
+ takeRecords = vi.fn(() => []);
+
+ constructor(
+ private readonly callback: IntersectionObserverCallback,
+ options?: IntersectionObserverInit,
+ ) {
+ this.root = options?.root ?? null;
+ this.rootMargin = options?.rootMargin ?? "0px";
+ FakeIntersectionObserver.instances.push(this);
+ }
+
+ emit(target: Element, isIntersecting: boolean) {
+ this.callback([entry(target, isIntersecting)], this);
+ }
+}
+
+function Probe({ rootMargin }: { rootMargin?: string }) {
+ const ref = useRef<HTMLDivElement>(null);
+ const inViewport = useInViewport(ref, rootMargin);
+ return <div ref={ref} data-testid="target" data-in-view={inViewport} />;
+}
+
+describe("useInViewport", () => {
+ afterEach(() => {
+ FakeIntersectionObserver.instances = [];
+ vi.unstubAllGlobals();
+ });
+
+ it("flips true once the element intersects, then stops observing", () => {
+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
+ render(<Probe />);
+
+ expect(screen.getByTestId("target").dataset.inView).toBe("false");
+ const observer = FakeIntersectionObserver.instances[0];
+ expect(observer.observe).toHaveBeenCalledTimes(1);
+
+ act(() => observer.emit(screen.getByTestId("target"), false));
+ expect(screen.getByTestId("target").dataset.inView).toBe("false");
+
+ act(() => observer.emit(screen.getByTestId("target"), true));
+ expect(screen.getByTestId("target").dataset.inView).toBe("true");
+ expect(observer.disconnect).toHaveBeenCalled();
+ });
+
+ it("passes the caller's rootMargin to the observer", () => {
+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
+ const { unmount } = render(<Probe rootMargin="120px" />);
+ const observer = FakeIntersectionObserver.instances[0];
+ expect(observer.rootMargin).toBe("120px");
+ expect(observer.observe).toHaveBeenCalledWith(screen.getByTestId("target"));
+ unmount();
+ });
+
+ it("observes through the nearest scroll container", () => {
+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
+ render(
+ <div data-testid="scroller" style={{ overflowY: "auto" }}>
+ <Probe />
+ </div>,
+ );
+
+ const observer = FakeIntersectionObserver.instances[0];
+ expect(observer.root).toBe(screen.getByTestId("scroller"));
+ });
+
+ it("fails open when IntersectionObserver is unavailable", () => {
+ vi.stubGlobal("IntersectionObserver", undefined);
+ render(<Probe />);
+ expect(screen.getByTestId("target").dataset.inView).toBe("true");
+ });
+});
diff --git a/frontend/editor/src/core/hooks/useInViewport.ts b/frontend/editor/src/core/hooks/useInViewport.ts
new file mode 100644
index 0000000000..f293a615db
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useInViewport.ts
@@ -0,0 +1,62 @@
+import { useEffect, useState, type RefObject } from "react";
+
+const DEFAULT_ROOT_MARGIN = "400px";
+
+// A row scrolled out of the sidebar list is clipped by that list before it ever
+// reaches the viewport, so `root: null` sees it as non-intersecting no matter
+// what rootMargin says (MDN, "Clipping and the intersection rectangle") and the
+// warm-up never happens. The closest scroll container is the root MDN
+// recommends for exactly this case.
+function nearestScrollableAncestor(element: Element): Element | null {
+ let parent = element.parentElement;
+ while (parent) {
+ const { overflowY } = window.getComputedStyle(parent);
+ if (
+ overflowY === "auto" ||
+ overflowY === "scroll" ||
+ overflowY === "overlay"
+ ) {
+ return parent;
+ }
+ parent = parent.parentElement;
+ }
+ return null;
+}
+
+/**
+ * True once the referenced element has come within `rootMargin` of its scroll
+ * container (or the viewport when nothing scrolls), and stays true after. The
+ * margin warms rows just before they scroll into view.
+ *
+ * Fails open where IntersectionObserver is unavailable, so callers never stall.
+ */
+export function useInViewport(
+ ref: RefObject<Element | null>,
+ rootMargin: string = DEFAULT_ROOT_MARGIN,
+): boolean {
+ const [inViewport, setInViewport] = useState(false);
+
+ useEffect(() => {
+ if (inViewport) return;
+ const element = ref.current;
+ if (!element) return;
+ if (typeof IntersectionObserver === "undefined") {
+ setInViewport(true);
+ return;
+ }
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ setInViewport(true);
+ observer.disconnect();
+ }
+ },
+ { root: nearestScrollableAncestor(element), rootMargin },
+ );
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [ref, rootMargin, inViewport]);
+
+ return inViewport;
+}
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx b/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
new file mode 100644
index 0000000000..542e1f7c78
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.test.tsx
@@ -0,0 +1,109 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { FileId } from "@app/types/file";
+import { useLazyThumbnail } from "@app/hooks/useLazyThumbnail";
+
+const mocks = vi.hoisted(() => ({
+ loadFile: vi.fn(),
+ updateThumbnail: vi.fn(),
+ updateStirlingFileStub: vi.fn(),
+ generateThumbnailForFile: vi.fn(),
+}));
+
+vi.mock("@app/contexts/IndexedDBContext", () => ({
+ useIndexedDB: () => ({
+ loadFile: mocks.loadFile,
+ updateThumbnail: mocks.updateThumbnail,
+ }),
+}));
+
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileManagement: () => ({
+ updateStirlingFileStub: mocks.updateStirlingFileStub,
+ }),
+}));
+
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailForFile: (...args: unknown[]) =>
+ mocks.generateThumbnailForFile(...args),
+}));
+
+vi.mock("@app/services/localFolderContents", () => ({
+ readDiskFile: vi.fn(),
+}));
+
+const FILE_ID = "file-abc" as FileId;
+
+function storeFile(): File {
+ return new File([new Uint8Array(8)], "picture.png", { type: "image/png" });
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useLazyThumbnail gating", () => {
+ it("queues no generation while the row is disabled", async () => {
+ const { result } = renderHook(() =>
+ useLazyThumbnail(FILE_ID, 2048, undefined, false),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(mocks.loadFile).not.toHaveBeenCalled();
+ expect(mocks.generateThumbnailForFile).not.toHaveBeenCalled();
+ expect(result.current).toBeUndefined();
+ });
+
+ it("generates once when a disabled row becomes enabled", async () => {
+ mocks.loadFile.mockResolvedValue(storeFile());
+ mocks.generateThumbnailForFile.mockResolvedValue(
+ "data:image/png;base64,thumb",
+ );
+
+ const { result, rerender } = renderHook(
+ ({ enabled }: { enabled: boolean }) =>
+ useLazyThumbnail(FILE_ID, 2048, undefined, enabled),
+ { initialProps: { enabled: false } },
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(mocks.loadFile).not.toHaveBeenCalled();
+
+ rerender({ enabled: true });
+
+ await waitFor(() => {
+ expect(result.current).toBe("data:image/png;base64,thumb");
+ });
+ expect(mocks.loadFile).toHaveBeenCalledTimes(1);
+ expect(mocks.generateThumbnailForFile).toHaveBeenCalledTimes(1);
+ expect(mocks.updateThumbnail).toHaveBeenCalledWith(
+ FILE_ID,
+ "data:image/png;base64,thumb",
+ );
+ });
+
+ it("does not regenerate after re-enabling a row that already ran", async () => {
+ mocks.loadFile.mockResolvedValue(storeFile());
+ mocks.generateThumbnailForFile.mockResolvedValue(
+ "data:image/png;base64,thumb",
+ );
+
+ const { result, rerender } = renderHook(
+ ({ enabled }: { enabled: boolean }) =>
+ useLazyThumbnail(FILE_ID, 2048, undefined, enabled),
+ { initialProps: { enabled: true } },
+ );
+
+ await waitFor(() => {
+ expect(result.current).toBe("data:image/png;base64,thumb");
+ });
+
+ rerender({ enabled: false });
+ rerender({ enabled: true });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(mocks.loadFile).toHaveBeenCalledTimes(1);
+ expect(mocks.generateThumbnailForFile).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.ts b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
index 82e15ceca2..2a8971dc67 100644
--- a/frontend/editor/src/core/hooks/useLazyThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
@@ -62,11 +62,15 @@ function queueStubThumbUpdate(
* Show the stub's thumbnail if present; otherwise pull bytes from IndexedDB,
* generate one, persist it, and update the stub. Server-only files with no
* cached bytes silently stay placeholder-only.
+ *
+ * Generation waits for `enabled` — callers pass the row's in-viewport state so
+ * a long list only queues work for rows the user can actually reach.
*/
export function useLazyThumbnail(
fileId: FileId,
size: number,
thumbnailUrl?: string,
+ enabled = true,
): string | undefined {
const [thumb, setThumb] = useState<string | undefined>(thumbnailUrl);
const attempted = useRef(false);
@@ -80,6 +84,7 @@ export function useLazyThumbnail(
useEffect(() => {
if (thumbnailUrl || attempted.current || size >= THUMBNAIL_SIZE_LIMIT)
return;
+ if (!enabled) return;
attempted.current = true;
let cancelled = false;
@@ -105,7 +110,7 @@ export function useLazyThumbnail(
return () => {
cancelled = true;
};
- }, [fileId, size, thumbnailUrl, indexedDB, updateStirlingFileStub]);
+ }, [fileId, size, thumbnailUrl, indexedDB, updateStirlingFileStub, enabled]);
return thumb;
}