Skip to content

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

Fix preview on crop/rotate (#7266)

Reece Brownea8b2957b7469
diff --git a/frontend/editor/src/core/components/tools/crop/CropSettings.tsx b/frontend/editor/src/core/components/tools/crop/CropSettings.tsx
index 710391dd6c..82516059b0 100644
--- a/frontend/editor/src/core/components/tools/crop/CropSettings.tsx
+++ b/frontend/editor/src/core/components/tools/crop/CropSettings.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState, useEffect } from "react";
+import { useState, useEffect } from "react";
import {
Stack,
Text,
@@ -12,7 +12,10 @@ import { ActionIcon } from "@app/ui/ActionIcon";
import { useTranslation } from "react-i18next";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import { CropParametersHook } from "@app/hooks/tools/crop/useCropParameters";
-import { useAllFiles } from "@app/contexts/FileContext";
+import {
+ useViewScopedFiles,
+ useViewScopedFileStubs,
+} from "@app/hooks/tools/shared/useViewScopedFiles";
import CropAreaSelector from "@app/components/tools/crop/CropAreaSelector";
import CropCoordinateInputs from "@app/components/tools/crop/CropCoordinateInputs";
import { DEFAULT_CROP_AREA } from "@app/constants/cropConstants";
@@ -34,32 +37,20 @@ const CONTAINER_SIZE = 250; // Fit within actual pane width
const CropSettings = ({ parameters, disabled = false }: CropSettingsProps) => {
const { t } = useTranslation();
- const { files, fileStubs } = useAllFiles();
-
- // Get the first file for preview
- const selectedStub = useMemo(() => {
- return fileStubs.length > 0 ? fileStubs[0] : null;
- }, [fileStubs]);
+ // Preview and measure the document the crop will actually apply to, so both
+ // follow the viewer when the user switches files with the tool open.
+ const [selectedStub = null] = useViewScopedFileStubs();
+ const [selectedFile = null] = useViewScopedFiles();
- // Get the first file for PDF processing
- const selectedFile = useMemo(() => {
- return files.length > 0 ? files[0] : null;
- }, [files]);
-
- // Get thumbnail for the selected file
- const [thumbnail, setThumbnail] = useState<string | null>(null);
const [pdfBounds, setPdfBounds] = useState<PDFBounds | null>(null);
useEffect(() => {
const loadPDFDimensions = async () => {
if (!selectedStub || !selectedFile) {
setPdfBounds(null);
- setThumbnail(null);
return;
}
- setThumbnail(selectedStub.thumbnailUrl || null);
-
try {
// Get PDF dimensions from the actual file
const arrayBuffer = await selectedFile.arrayBuffer();
@@ -223,7 +214,7 @@ const CropSettings = ({ parameters, disabled = false }: CropSettingsProps) => {
>
<DocumentThumbnail
file={selectedStub}
- thumbnail={thumbnail}
+ thumbnail={selectedStub?.thumbnailUrl ?? null}
style={{
width: pdfBounds.thumbnailWidth,
height: pdfBounds.thumbnailHeight,
diff --git a/frontend/editor/src/core/components/tools/rotate/RotateSettings.test.tsx b/frontend/editor/src/core/components/tools/rotate/RotateSettings.test.tsx
new file mode 100644
index 0000000000..0730521b8e
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/rotate/RotateSettings.test.tsx
@@ -0,0 +1,66 @@
+import { describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+
+const viewer = { activeFileIndex: 0 };
+const files = {
+ files: [
+ { fileId: "a", name: "alpha.pdf" },
+ { fileId: "b", name: "beta.pdf" },
+ ],
+ fileStubs: [
+ { id: "a", name: "alpha.pdf", thumbnailUrl: "alpha.png" },
+ { id: "b", name: "beta.pdf", thumbnailUrl: "beta.png" },
+ ],
+};
+
+vi.mock("@app/contexts/ViewerContext", () => ({ useViewer: () => viewer }));
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationState: () => ({ workbench: "viewer" }),
+}));
+vi.mock("@app/contexts/FileContext", () => ({ useAllFiles: () => files }));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback?: string) => fallback ?? _key,
+ }),
+}));
+
+import RotateSettings from "@app/components/tools/rotate/RotateSettings";
+
+const parameters = {
+ parameters: { angle: 0 },
+ rotateClockwise: vi.fn(),
+ rotateAnticlockwise: vi.fn(),
+} as never;
+
+const renderAt = (activeFileIndex: number) => {
+ viewer.activeFileIndex = activeFileIndex;
+ return render(
+ <MantineProvider>
+ <RotateSettings parameters={parameters} />
+ </MantineProvider>,
+ );
+};
+
+describe("RotateSettings preview", () => {
+ it("previews the viewer's active file, not the first loaded one", () => {
+ renderAt(1);
+
+ expect(screen.getByAltText("Preview of beta.pdf")).toBeInTheDocument();
+ expect(screen.queryByAltText("Preview of alpha.pdf")).toBeNull();
+ });
+
+ it("follows the viewer when the active file changes", () => {
+ const { rerender } = renderAt(0);
+ expect(screen.getByAltText("Preview of alpha.pdf")).toBeInTheDocument();
+
+ viewer.activeFileIndex = 1;
+ rerender(
+ <MantineProvider>
+ <RotateSettings parameters={parameters} />
+ </MantineProvider>,
+ );
+
+ expect(screen.getByAltText("Preview of beta.pdf")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/core/components/tools/rotate/RotateSettings.tsx b/frontend/editor/src/core/components/tools/rotate/RotateSettings.tsx
index ba66790298..950c78ea99 100644
--- a/frontend/editor/src/core/components/tools/rotate/RotateSettings.tsx
+++ b/frontend/editor/src/core/components/tools/rotate/RotateSettings.tsx
@@ -1,11 +1,11 @@
-import { useMemo, useState, useEffect } from "react";
+import { useEffect } from "react";
import { Stack, Text, Box, Group, Center } from "@mantine/core";
import { ActionIcon } from "@app/ui/ActionIcon";
import { useTranslation } from "react-i18next";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";
import { RotateParametersHook } from "@app/hooks/tools/rotate/useRotateParameters";
-import { useAllFiles } from "@app/contexts/FileContext";
+import { useViewScopedFileStubs } from "@app/hooks/tools/shared/useViewScopedFiles";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
interface RotateSettingsProps {
@@ -18,19 +18,9 @@ const RotateSettings = ({
disabled = false,
}: RotateSettingsProps) => {
const { t } = useTranslation();
- const { fileStubs } = useAllFiles();
-
- // Get the first file for preview
- const selectedStub = useMemo(() => {
- return fileStubs.length > 0 ? fileStubs[0] : null;
- }, [fileStubs]);
-
- // Get thumbnail for the selected file
- const [thumbnail, setThumbnail] = useState<string | null>(null);
-
- useEffect(() => {
- setThumbnail(selectedStub?.thumbnailUrl || null);
- }, [selectedStub]);
+ // Preview the document the rotation will actually apply to, so it follows
+ // the viewer when the user switches files with the tool open.
+ const [previewStub = null] = useViewScopedFileStubs();
// Calculate current angle display
const currentAngle = parameters.parameters.angle;
@@ -86,7 +76,10 @@ const RotateSettings = ({
justifyContent: "center",
}}
>
- <DocumentThumbnail file={selectedStub} thumbnail={thumbnail} />
+ <DocumentThumbnail
+ file={previewStub}
+ thumbnail={previewStub?.thumbnailUrl ?? null}
+ />
</Box>
</Box>
</Center>
diff --git a/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.test.ts b/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.test.ts
new file mode 100644
index 0000000000..974782c09e
--- /dev/null
+++ b/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+const mockViewer = { activeFileIndex: 0 };
+const mockNavigation = { workbench: "viewer" };
+const mockFiles: { files: unknown[]; fileStubs: unknown[] } = {
+ files: [],
+ fileStubs: [],
+};
+
+vi.mock("@app/contexts/ViewerContext", () => ({
+ useViewer: () => mockViewer,
+}));
+
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationState: () => mockNavigation,
+}));
+
+vi.mock("@app/contexts/FileContext", () => ({
+ useAllFiles: () => mockFiles,
+}));
+
+import {
+ useViewScopedFiles,
+ useViewScopedFileStubs,
+} from "@app/hooks/tools/shared/useViewScopedFiles";
+
+const file = (id: string) => ({ fileId: id, name: `${id}.pdf` });
+const stub = (id: string) => ({
+ id,
+ name: `${id}.pdf`,
+ thumbnailUrl: `${id}.png`,
+});
+
+function setState(opts: {
+ workbench?: string;
+ activeFileIndex?: number;
+ files?: unknown[];
+ fileStubs?: unknown[];
+}) {
+ mockNavigation.workbench = opts.workbench ?? "viewer";
+ mockViewer.activeFileIndex = opts.activeFileIndex ?? 0;
+ mockFiles.files = opts.files ?? [];
+ mockFiles.fileStubs = opts.fileStubs ?? [];
+}
+
+describe("useViewScopedFileStubs", () => {
+ it("follows the viewer's active file rather than the first loaded one", () => {
+ setState({
+ files: [file("a"), file("b"), file("c")],
+ fileStubs: [stub("a"), stub("b"), stub("c")],
+ activeFileIndex: 2,
+ });
+
+ const { result } = renderHook(() => useViewScopedFileStubs());
+
+ expect(result.current.map((s) => s.id)).toEqual(["c"]);
+ });
+
+ it("re-resolves when the viewer switches files", () => {
+ setState({
+ files: [file("a"), file("b")],
+ fileStubs: [stub("a"), stub("b")],
+ activeFileIndex: 0,
+ });
+
+ const { result, rerender } = renderHook(() => useViewScopedFileStubs());
+ expect(result.current.map((s) => s.id)).toEqual(["a"]);
+
+ setState({
+ files: [file("a"), file("b")],
+ fileStubs: [stub("a"), stub("b")],
+ activeFileIndex: 1,
+ });
+ rerender();
+
+ expect(result.current.map((s) => s.id)).toEqual(["b"]);
+ });
+
+ it("matches by id, not position, when the two lists are out of step", () => {
+ // A stub exists before its bytes load, so the stub list can be longer than
+ // (and offset from) the file list.
+ setState({
+ files: [file("b")],
+ fileStubs: [stub("a"), stub("b")],
+ activeFileIndex: 0,
+ });
+
+ const { result } = renderHook(() => useViewScopedFileStubs());
+
+ expect(result.current.map((s) => s.id)).toEqual(["b"]);
+ });
+
+ it("returns every stub outside the viewer, mirroring useViewScopedFiles", () => {
+ setState({
+ workbench: "fileEditor",
+ files: [file("a"), file("b")],
+ fileStubs: [stub("a"), stub("b")],
+ });
+
+ const stubs = renderHook(() => useViewScopedFileStubs()).result.current;
+ const files = renderHook(() => useViewScopedFiles()).result.current;
+
+ expect(stubs.map((s) => s.id)).toEqual(["a", "b"]);
+ expect(stubs).toHaveLength(files.length);
+ });
+
+ it("drops stubs with no loaded file instead of returning undefined holes", () => {
+ setState({
+ workbench: "fileEditor",
+ files: [file("a")],
+ fileStubs: [stub("a"), stub("orphan")],
+ });
+
+ const { result } = renderHook(() => useViewScopedFileStubs());
+
+ expect(result.current.map((s) => s.id)).toEqual(["a"]);
+ });
+});
diff --git a/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.ts b/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.ts
index 070e854700..cec039481f 100644
--- a/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.ts
+++ b/frontend/editor/src/core/hooks/tools/shared/useViewScopedFiles.ts
@@ -2,7 +2,7 @@ import { useMemo } from "react";
import { useAllFiles } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useNavigationState } from "@app/contexts/NavigationContext";
-import { StirlingFile } from "@app/types/fileContext";
+import { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
export function useViewScopedFiles(ignoreViewerScope = false): StirlingFile[] {
const { activeFileIndex } = useViewer();
@@ -18,3 +18,28 @@ export function useViewScopedFiles(ignoreViewerScope = false): StirlingFile[] {
return allFiles;
}, [workbench, allFiles, activeFileIndex, ignoreViewerScope]);
}
+
+/**
+ * The stubs for {@link useViewScopedFiles} — the same scoping rule, for UI that
+ * needs stub-only metadata (thumbnails, page counts) rather than file bytes.
+ * A tool's preview must read from here, not from the raw file list: indexing
+ * that list pins the preview to whichever file was added first, so it keeps
+ * showing the original document after the viewer switches files.
+ *
+ * Resolved by id rather than by position, because the file and stub lists are
+ * filtered independently — a stub exists before its bytes finish loading, so
+ * the two arrays can hold different indices for the same document.
+ */
+export function useViewScopedFileStubs(
+ ignoreViewerScope = false,
+): StirlingFileStub[] {
+ const scopedFiles = useViewScopedFiles(ignoreViewerScope);
+ const { fileStubs } = useAllFiles();
+
+ return useMemo(() => {
+ const stubsById = new Map(fileStubs.map((stub) => [stub.id, stub]));
+ return scopedFiles
+ .map((file) => stubsById.get(file.fileId))
+ .filter((stub): stub is StirlingFileStub => stub != null);
+ }, [scopedFiles, fileStubs]);
+}