Skip to content

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

perf(viewer): stabilize actions bundle and context value (#8149)

briosfc6c7ad949c4
diff --git a/frontend/editor/src/core/contexts/ViewerContext.test.tsx b/frontend/editor/src/core/contexts/ViewerContext.test.tsx
new file mode 100644
index 0000000000..23381c7825
--- /dev/null
+++ b/frontend/editor/src/core/contexts/ViewerContext.test.tsx
@@ -0,0 +1,171 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, act } from "@testing-library/react";
+import React, { useState } from "react";
+import {
+ ViewerProvider,
+ useViewer,
+ type ViewerContextType,
+} from "@app/contexts/ViewerContext";
+
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigation: () => ({ currentRoute: "/" }),
+}));
+
+const mockFile = Object.assign(new File(["%PDF"], "sample.pdf"), {
+ fileId: "file-1",
+ quickKey: "quick-1",
+});
+const mockSelectors = { getFiles: () => [mockFile] };
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileSelectors: () => mockSelectors,
+ // The workbench id list the provider watches when pruning activeFileId.
+ useFileSelector: () => [mockFile.fileId],
+ useFileIndex: () => -1,
+}));
+
+vi.mock("@app/services/policyExport", () => ({
+ enforceExportPolicies: vi.fn(),
+}));
+
+const MemoizedProbe = React.memo(function ContextProbe({
+ onRead,
+}: {
+ onRead: (ctx: ViewerContextType) => void;
+}) {
+ const ctx = useViewer();
+ onRead(ctx);
+ return (
+ <>
+ <button
+ onClick={() => ctx.toggleThumbnailSidebar()}
+ data-testid="toggle-sidebar"
+ >
+ Toggle
+ </button>
+ <button
+ onClick={() => ctx.setActiveFileIndex(0)}
+ data-testid="set-active-file"
+ >
+ Set active file
+ </button>
+ </>
+ );
+});
+
+function ParentHarness({
+ onRead,
+}: {
+ onRead: (ctx: ViewerContextType) => void;
+}) {
+ const [, setTick] = useState(0);
+ return (
+ <div>
+ <button
+ onClick={() => setTick((t) => t + 1)}
+ data-testid="rerender-parent"
+ >
+ Rerender Parent
+ </button>
+ <ViewerProvider>
+ <MemoizedProbe onRead={onRead} />
+ </ViewerProvider>
+ </div>
+ );
+}
+
+describe("ViewerContext stability", () => {
+ it("skips consumer re-renders when parent re-renders due to context value memoization", () => {
+ let renderCount = 0;
+ let latestCtx: ViewerContextType | null = null;
+
+ const { getByTestId } = render(
+ <ParentHarness
+ onRead={(ctx) => {
+ renderCount++;
+ latestCtx = ctx;
+ }}
+ />,
+ );
+
+ expect(renderCount).toBe(1);
+ const firstCtx = latestCtx;
+
+ act(() => {
+ getByTestId("rerender-parent").click();
+ });
+
+ expect(renderCount).toBe(1);
+ expect(latestCtx).toBe(firstCtx);
+ });
+
+ it("preserves identity of actions, getters, and toggle callbacks across internal state transitions", () => {
+ let renderCount = 0;
+ const recordedContexts: ViewerContextType[] = [];
+
+ const { getByTestId } = render(
+ <ViewerProvider>
+ <MemoizedProbe
+ onRead={(ctx) => {
+ renderCount++;
+ recordedContexts.push(ctx);
+ }}
+ />
+ </ViewerProvider>,
+ );
+
+ expect(renderCount).toBe(1);
+ const first = recordedContexts[0];
+
+ act(() => {
+ getByTestId("toggle-sidebar").click();
+ });
+
+ expect(renderCount).toBe(2);
+ const second = recordedContexts[1];
+
+ expect(first.isThumbnailSidebarVisible).toBe(false);
+ expect(second.isThumbnailSidebarVisible).toBe(true);
+
+ expect(second.scrollActions).toBe(first.scrollActions);
+ expect(second.zoomActions).toBe(first.zoomActions);
+ expect(second.panActions).toBe(first.panActions);
+ expect(second.selectionActions).toBe(first.selectionActions);
+ expect(second.spreadActions).toBe(first.spreadActions);
+ expect(second.rotationActions).toBe(first.rotationActions);
+ expect(second.searchActions).toBe(first.searchActions);
+ expect(second.exportActions).toBe(first.exportActions);
+ expect(second.bookmarkActions).toBe(first.bookmarkActions);
+ expect(second.attachmentActions).toBe(first.attachmentActions);
+ expect(second.printActions).toBe(first.printActions);
+ expect(second.searchInterfaceActions).toBe(first.searchInterfaceActions);
+
+ expect(second.getScrollState).toBe(first.getScrollState);
+ expect(second.getZoomState).toBe(first.getZoomState);
+ expect(second.getBookmarkState).toBe(first.getBookmarkState);
+ expect(second.toggleThumbnailSidebar).toBe(first.toggleThumbnailSidebar);
+ expect(second.toggleBookmarkSidebar).toBe(first.toggleBookmarkSidebar);
+ expect(second.toggleAttachmentSidebar).toBe(first.toggleAttachmentSidebar);
+ expect(second.toggleLayerSidebar).toBe(first.toggleLayerSidebar);
+ });
+
+ it("keeps print actions identical when the active file changes", () => {
+ const recordedContexts: ViewerContextType[] = [];
+
+ const { getByTestId } = render(
+ <ViewerProvider>
+ <MemoizedProbe onRead={(ctx) => recordedContexts.push(ctx)} />
+ </ViewerProvider>,
+ );
+
+ const first = recordedContexts[0];
+ expect(first.activeFileId).toBeNull();
+
+ act(() => {
+ getByTestId("set-active-file").click();
+ });
+
+ const latest = recordedContexts[recordedContexts.length - 1];
+ expect(latest.activeFileId).toBe("file-1");
+ expect(latest.printActions).toBe(first.printActions);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/ViewerContext.tsx b/frontend/editor/src/core/contexts/ViewerContext.tsx
index 3bb8d01320..b4c16f4aca 100644
--- a/frontend/editor/src/core/contexts/ViewerContext.tsx
+++ b/frontend/editor/src/core/contexts/ViewerContext.tsx
@@ -4,6 +4,7 @@ import React, {
useState,
useMemo,
useEffect,
+ useLayoutEffect,
ReactNode,
useRef,
useCallback,
@@ -261,6 +262,16 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
// activeFileIndex is derived from activeFileId so they can never desync.
// ViewerProvider sits inside FileContextProvider so these hooks are valid here.
const selectors = useFileSelectors();
+ const selectorsRef = useRef(selectors);
+ const tRef = useRef(t);
+ const activeFileIdRef = useRef(activeFileId);
+ // Updated after commit, not during render: a concurrent render React abandons
+ // would otherwise leave the callbacks reading values that were never shown.
+ useLayoutEffect(() => {
+ selectorsRef.current = selectors;
+ tRef.current = t;
+ activeFileIdRef.current = activeFileId;
+ }, [selectors, t, activeFileId]);
const fileIds = useFileSelector((s) => s.files.ids);
// Clear activeFileId when its file is removed from the workbench.
@@ -274,14 +285,11 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
}, [activeFileId, fileIds]);
const activeFileIndex = useFileIndex(activeFileId);
- const setActiveFileIndex = useCallback(
- (index: number) => {
- const files = selectors.getFiles();
- const file = files[index];
- if (file && isStirlingFile(file)) setActiveFileId(file.fileId);
- },
- [selectors],
- );
+ const setActiveFileIndex = useCallback((index: number) => {
+ const files = selectorsRef.current.getFiles();
+ const file = files[index];
+ if (file && isStirlingFile(file)) setActiveFileId(file.fileId);
+ }, []);
const [pdfRenderMode, setPdfRenderModeState] = useState<PdfRenderMode>(() =>
preferencesService.getPreference("pdfRenderMode"),
);
@@ -371,29 +379,29 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
[],
);
- const toggleThumbnailSidebar = () => {
+ const toggleThumbnailSidebar = useCallback(() => {
setIsThumbnailSidebarVisible((prev) => !prev);
- };
+ }, []);
- const toggleBookmarkSidebar = () => {
+ const toggleBookmarkSidebar = useCallback(() => {
setIsBookmarkSidebarVisible((prev) => !prev);
- };
+ }, []);
- const toggleAttachmentSidebar = () => {
+ const toggleAttachmentSidebar = useCallback(() => {
setIsAttachmentSidebarVisible((prev) => !prev);
- };
+ }, []);
- const toggleLayerSidebar = () => {
+ const toggleLayerSidebar = useCallback(() => {
setIsLayerSidebarVisible((prev) => !prev);
- };
+ }, []);
- const setCommentsSidebarVisible = (visible: boolean) => {
+ const setCommentsSidebarVisible = useCallback((visible: boolean) => {
setIsCommentsSidebarVisible(visible);
- };
+ }, []);
- const toggleCommentsSidebar = () => {
+ const toggleCommentsSidebar = useCallback(() => {
setIsCommentsSidebarVisible((prev) => !prev);
- };
+ }, []);
const requestCommentFocus = useCallback(
(
@@ -417,19 +425,22 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
setHighlightCommentRequest(null);
}, []);
- const searchInterfaceActions = {
- open: () => setSearchInterfaceVisible(true),
- close: () => setSearchInterfaceVisible(false),
- toggle: () => setSearchInterfaceVisible((prev) => !prev),
- };
+ const searchInterfaceActions = useMemo(
+ () => ({
+ open: () => setSearchInterfaceVisible(true),
+ close: () => setSearchInterfaceVisible(false),
+ toggle: () => setSearchInterfaceVisible((prev) => !prev),
+ }),
+ [],
+ );
- const toggleAnnotationsVisibility = () => {
+ const toggleAnnotationsVisibility = useCallback(() => {
setIsAnnotationsVisible((prev) => !prev);
- };
+ }, []);
- const setAnnotationMode = (enabled: boolean) => {
+ const setAnnotationMode = useCallback((enabled: boolean) => {
setIsAnnotationModeState(enabled);
- };
+ }, []);
const cyclePdfRenderMode = useCallback(() => {
setPdfRenderModeState((prev) => {
@@ -441,54 +452,54 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
}, []);
// State getters - read from bridge refs
- const getScrollState = (): ScrollState => {
+ const getScrollState = useCallback((): ScrollState => {
return (
bridgeRefs.current.scroll?.state || { currentPage: 1, totalPages: 0 }
);
- };
+ }, []);
- const getZoomState = (): ZoomState => {
+ const getZoomState = useCallback((): ZoomState => {
return (
bridgeRefs.current.zoom?.state || { currentZoom: 1.4, zoomPercent: 140 }
);
- };
+ }, []);
- const getPanState = (): PanState => {
+ const getPanState = useCallback((): PanState => {
return bridgeRefs.current.pan?.state || { isPanning: false };
- };
+ }, []);
- const getSelectionState = (): SelectionState => {
+ const getSelectionState = useCallback((): SelectionState => {
return bridgeRefs.current.selection?.state || { hasSelection: false };
- };
+ }, []);
- const getSpreadState = (): SpreadState => {
+ const getSpreadState = useCallback((): SpreadState => {
return (
bridgeRefs.current.spread?.state || {
spreadMode: SpreadMode.None,
isDualPage: false,
}
);
- };
+ }, []);
- const getRotationState = (): RotationState => {
+ const getRotationState = useCallback((): RotationState => {
return bridgeRefs.current.rotation?.state || { rotation: 0 };
- };
+ }, []);
- const getSearchState = (): SearchState => {
+ const getSearchState = useCallback((): SearchState => {
return (
bridgeRefs.current.search?.state || { results: null, activeIndex: 0 }
);
- };
+ }, []);
- const getThumbnailAPI = () => {
+ const getThumbnailAPI = useCallback(() => {
return bridgeRefs.current.thumbnail?.api || null;
- };
+ }, []);
- const getExportState = (): ExportState => {
+ const getExportState = useCallback((): ExportState => {
return bridgeRefs.current.export?.state || { canExport: false };
- };
+ }, []);
- const getBookmarkState = (): BookmarkState => {
+ const getBookmarkState = useCallback((): BookmarkState => {
return (
bridgeRefs.current.bookmark?.state || {
bookmarks: null,
@@ -496,11 +507,14 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
error: null,
}
);
- };
+ }, []);
- const hasBookmarkSupport = () => Boolean(bridgeRefs.current.bookmark);
+ const hasBookmarkSupport = useCallback(
+ () => Boolean(bridgeRefs.current.bookmark),
+ [],
+ );
- const getAttachmentState = (): AttachmentState => {
+ const getAttachmentState = useCallback((): AttachmentState => {
return (
bridgeRefs.current.attachment?.state || {
attachments: null,
@@ -508,11 +522,14 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
error: null,
}
);
- };
+ }, []);
- const hasAttachmentSupport = () => Boolean(bridgeRefs.current.attachment);
+ const hasAttachmentSupport = useCallback(
+ () => Boolean(bridgeRefs.current.attachment),
+ [],
+ );
- const getDocumentPermissions = (): DocumentPermissionsState => {
+ const getDocumentPermissions = useCallback((): DocumentPermissionsState => {
return (
bridgeRefs.current.permissions?.state || {
isEncrypted: false,
@@ -528,9 +545,9 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
canPrintHighQuality: true,
}
);
- };
+ }, []);
- const hasPermission = (flag: PdfPermissionFlag): boolean => {
+ const hasPermission = useCallback((flag: PdfPermissionFlag): boolean => {
const api = bridgeRefs.current.permissions?.api;
if (api?.hasPermission) {
return api.hasPermission(flag);
@@ -542,27 +559,19 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
);
}
return true;
- };
+ }, []);
// Action handlers - call APIs directly
- const {
- scrollActions,
- zoomActions,
- panActions,
- selectionActions,
- spreadActions,
- rotationActions,
- searchActions,
- exportActions,
- bookmarkActions,
- attachmentActions,
- printActions,
- } = createViewerActions({
- registry: bridgeRefs,
- getScrollState,
- getZoomState,
- triggerImmediateZoomUpdate,
- });
+ const actionsBundle = useMemo(
+ () =>
+ createViewerActions({
+ registry: bridgeRefs,
+ getScrollState,
+ getZoomState,
+ triggerImmediateZoomUpdate,
+ }),
+ [getScrollState, getZoomState, triggerImmediateZoomUpdate],
+ );
// Printing is an exit path, so a "run on export" policy must enforce here too.
// Enforce the current file through the same path export uses: when a policy
@@ -573,30 +582,33 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
// they haven't seen. With no active export policy this is a no-op and print
// runs straight away.
const printWithPolicy = useCallback(async () => {
- const file = activeFileId
- ? selectors.getFiles([activeFileId as FileId])[0]
+ // Through a ref: switching the active file must not rebuild this callback,
+ // or the memoised actions bundle and every effect depending on it churn.
+ const currentActiveFileId = activeFileIdRef.current;
+ const file = currentActiveFileId
+ ? selectorsRef.current.getFiles([currentActiveFileId as FileId])[0]
: undefined;
- if (!activeFileId || !file) {
- printActions.print();
+ if (!currentActiveFileId || !file) {
+ actionsBundle.printActions.print();
return;
}
const [enforced] = await enforceExportPolicies(
[file],
- [activeFileId],
+ [currentActiveFileId],
"print",
);
// Original file back means no policy rewrote it (no active policy, already
// enforced, or graceful failure fallback) — nothing new to review, print it.
if (!enforced || enforced === file) {
- printActions.print();
+ actionsBundle.printActions.print();
return;
}
alert({
alertType: "warning",
- title: t("policies.enforcement.printPolicyAppliedTitle"),
- body: t("policies.enforcement.printPolicyAppliedBody"),
+ title: tRef.current("policies.enforcement.printPolicyAppliedTitle"),
+ body: tRef.current("policies.enforcement.printPolicyAppliedBody"),
});
- }, [activeFileId, selectors, printActions]);
+ }, [actionsBundle.printActions]);
const enforcedPrintActions = useMemo<PrintActions>(
() => ({ print: printWithPolicy }),
@@ -609,97 +621,159 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
setZoomRestoreSettledTick((tick) => tick + 1);
}, []);
- const value: ViewerContextType = {
- // UI state
- isThumbnailSidebarVisible,
- toggleThumbnailSidebar,
- isBookmarkSidebarVisible,
- toggleBookmarkSidebar,
- isAttachmentSidebarVisible,
- toggleAttachmentSidebar,
- isLayerSidebarVisible,
- toggleLayerSidebar,
- hasLayers,
- setHasLayers,
- isCommentsSidebarVisible,
- setCommentsSidebarVisible,
- toggleCommentsSidebar,
- highlightCommentRequest,
- requestCommentFocus,
- clearHighlightCommentRequest,
-
- // Search interface
- isSearchInterfaceVisible,
- searchInterfaceActions,
-
- // Annotation controls
- isAnnotationsVisible,
- toggleAnnotationsVisibility,
- isAnnotationMode,
- setAnnotationMode,
-
- // Active file tracking
- activeFileId,
- setActiveFileId,
- activeFileIndex,
- setActiveFileIndex,
-
- // State getters
- getScrollState,
- getZoomState,
- getPanState,
- getSelectionState,
- getSpreadState,
- getRotationState,
- getSearchState,
- getThumbnailAPI,
- getExportState,
- getBookmarkState,
- hasBookmarkSupport,
- getAttachmentState,
- hasAttachmentSupport,
- getDocumentPermissions,
- hasPermission,
-
- // Immediate updates
- registerImmediateZoomUpdate,
- registerImmediateScrollUpdate,
- registerImmediateSpreadUpdate,
- registerImmediatePanUpdate,
- registerImmediateRotationUpdate,
- triggerImmediateScrollUpdate,
- triggerImmediateZoomUpdate,
- triggerImmediateSpreadUpdate,
- zoomRestorePendingRef,
- zoomRestoreSettledTick,
- notifyZoomRestoreSettled,
- triggerImmediatePanUpdate,
- triggerImmediateRotationUpdate,
-
- // Actions
- scrollActions,
- zoomActions,
- panActions,
- selectionActions,
- spreadActions,
- rotationActions,
- searchActions,
- exportActions,
- bookmarkActions,
- attachmentActions,
- printActions: enforcedPrintActions,
-
- // Bridge registration
- registerBridge,
-
- // Apply changes
- applyChanges,
- setApplyChanges,
-
- // PDF page rendering mode
- pdfRenderMode,
- cyclePdfRenderMode,
- };
+ const value = useMemo<ViewerContextType>(
+ () => ({
+ // UI state
+ isThumbnailSidebarVisible,
+ toggleThumbnailSidebar,
+ isBookmarkSidebarVisible,
+ toggleBookmarkSidebar,
+ isAttachmentSidebarVisible,
+ toggleAttachmentSidebar,
+ isLayerSidebarVisible,
+ toggleLayerSidebar,
+ hasLayers,
+ setHasLayers,
+ isCommentsSidebarVisible,
+ setCommentsSidebarVisible,
+ toggleCommentsSidebar,
+ highlightCommentRequest,
+ requestCommentFocus,
+ clearHighlightCommentRequest,
+
+ // Search interface
+ isSearchInterfaceVisible,
+ searchInterfaceActions,
+
+ // Annotation controls
+ isAnnotationsVisible,
+ toggleAnnotationsVisibility,
+ isAnnotationMode,
+ setAnnotationMode,
+
+ // Active file tracking
+ activeFileId,
+ setActiveFileId,
+ activeFileIndex,
+ setActiveFileIndex,
+
+ // State getters
+ getScrollState,
+ getZoomState,
+ getPanState,
+ getSelectionState,
+ getSpreadState,
+ getRotationState,
+ getSearchState,
+ getThumbnailAPI,
+ getExportState,
+ getBookmarkState,
+ hasBookmarkSupport,
+ getAttachmentState,
+ hasAttachmentSupport,
+ getDocumentPermissions,
+ hasPermission,
+
+ // Immediate updates
+ registerImmediateZoomUpdate,
+ registerImmediateScrollUpdate,
+ registerImmediateSpreadUpdate,
+ registerImmediatePanUpdate,
+ registerImmediateRotationUpdate,
+ triggerImmediateScrollUpdate,
+ triggerImmediateZoomUpdate,
+ triggerImmediateSpreadUpdate,
+ zoomRestorePendingRef,
+ zoomRestoreSettledTick,
+ notifyZoomRestoreSettled,
+ triggerImmediatePanUpdate,
+ triggerImmediateRotationUpdate,
+
+ // Actions
+ scrollActions: actionsBundle.scrollActions,
+ zoomActions: actionsBundle.zoomActions,
+ panActions: actionsBundle.panActions,
+ selectionActions: actionsBundle.selectionActions,
+ spreadActions: actionsBundle.spreadActions,
+ rotationActions: actionsBundle.rotationActions,
+ searchActions: actionsBundle.searchActions,
+ exportActions: actionsBundle.exportActions,
+ bookmarkActions: actionsBundle.bookmarkActions,
+ attachmentActions: actionsBundle.attachmentActions,
+ printActions: enforcedPrintActions,
+
+ // Bridge registration
+ registerBridge,
+
+ // Apply changes
+ applyChanges,
+ setApplyChanges,
+
+ // PDF page rendering mode
+ pdfRenderMode,
+ cyclePdfRenderMode,
+ }),
+ [
+ isThumbnailSidebarVisible,
+ toggleThumbnailSidebar,
+ isBookmarkSidebarVisible,
+ toggleBookmarkSidebar,
+ isAttachmentSidebarVisible,
+ toggleAttachmentSidebar,
+ isLayerSidebarVisible,
+ toggleLayerSidebar,
+ hasLayers,
+ isCommentsSidebarVisible,
+ setCommentsSidebarVisible,
+ toggleCommentsSidebar,
+ highlightCommentRequest,
+ requestCommentFocus,
+ clearHighlightCommentRequest,
+ isSearchInterfaceVisible,
+ searchInterfaceActions,
+ isAnnotationsVisible,
+ toggleAnnotationsVisibility,
+ isAnnotationMode,
+ setAnnotationMode,
+ activeFileId,
+ activeFileIndex,
+ setActiveFileIndex,
+ getScrollState,
+ getZoomState,
+ getPanState,
+ getSelectionState,
+ getSpreadState,
+ getRotationState,
+ getSearchState,
+ getThumbnailAPI,
+ getExportState,
+ getBookmarkState,
+ hasBookmarkSupport,
+ getAttachmentState,
+ hasAttachmentSupport,
+ getDocumentPermissions,
+ hasPermission,
+ registerImmediateZoomUpdate,
+ registerImmediateScrollUpdate,
+ registerImmediateSpreadUpdate,
+ registerImmediatePanUpdate,
+ registerImmediateRotationUpdate,
+ triggerImmediateScrollUpdate,
+ triggerImmediateZoomUpdate,
+ triggerImmediateSpreadUpdate,
+ zoomRestoreSettledTick,
+ notifyZoomRestoreSettled,
+ triggerImmediatePanUpdate,
+ triggerImmediateRotationUpdate,
+ actionsBundle,
+ enforcedPrintActions,
+ registerBridge,
+ applyChanges,
+ setApplyChanges,
+ pdfRenderMode,
+ cyclePdfRenderMode,
+ ],
+ );
return (
<ViewerContext.Provider value={value}>{children}</ViewerContext.Provider>