Skip to content

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

Edit text inside the viewer (#8925)

Reece Brownef03bc0186d65
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 8bf165e238..5e8def0081 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7572,7 +7572,6 @@ saveTooltip = "Apply changes to the file in your workspace ({{shortcut}})"
tags = "edit text,modify text,change text,edit content,update text,rewrite,correct,amend,redline,revise,text editor,content editor"
title = "PDF Text Editor"
unsaved = "(unsaved)"
-workbenchLabel = "Editor"
[pdfTextEditor.annotations]
freetext = "Annotation text - not page text, so it can't be edited here"
@@ -7601,10 +7600,6 @@ confirm = "Discard and open"
hint = "Cancel, then Save PDF to keep them in your workspace first."
title = "Discard unsaved changes?"
-[pdfTextEditor.drop]
-hint = "Releases on the editor stage replace any open document."
-title = "Drop a PDF to open"
-
[pdfTextEditor.error]
decodeImage = "Could not decode the selected image."
insertImage = "Could not insert the selected image."
@@ -7900,7 +7895,6 @@ done = "Done"
download = "Save and download"
find = "Find"
lock = "Lock"
-openPdf = "Open a PDF"
panelHint = "Editing happens in the Workspace view. Tap text on the page to change it."
save = "Save"
style = "Style"
@@ -7908,7 +7902,6 @@ tapToPlace = "Tap the page where the text should go"
unlock = "Unlock"
[pdfTextEditor.pageView]
-pageNumber = "Page {{page}}"
renderFailed = "Failed to render page"
[pdfTextEditor.password]
@@ -7976,7 +7969,6 @@ addTable = "Add table"
addText = "Add text"
clickPageToAddTable = "Click page to add a table"
clickPageToAddText = "Click page to add text"
-document = "Document"
group = "Group"
groupingAuto = "Auto"
groupingAutoHint = "Groups equal-spaced lines into paragraphs. Changing this re-reads the document and clears undo history."
@@ -8005,13 +7997,6 @@ auto = "Automatic"
enable = "Check spelling as you type"
language = "Dictionary language"
-[pdfTextEditor.stage]
-loadingDocument = "Loading document"
-loadingProgress = "Loading progress"
-noDocument = "No document loaded."
-pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
-renderingPreview = "Rendering preview"
-
[pdfTextEditor.table]
addColumn = "Add column"
addRow = "Add row"
@@ -8096,13 +8081,6 @@ title = "Preview Variance"
text = "This workspace focuses on editing text and repositioning embedded images. Complex page artwork, form widgets, and layered graphics are preserved for export but are not fully editable here."
title = "Text and Image Focus"
-[pdfTextEditor.zoom]
-fit = "Fit"
-fitToWidth = "Fit to width"
-in = "Zoom in"
-out = "Zoom out"
-reset = "Reset zoom to 100%"
-
[PDFToCSV]
header = "PDF to CSV"
title = "PDF to CSV"
@@ -14686,6 +14664,7 @@ coverPageView = "Show Cover Page Separately"
disableColorFilter = "Disable Color Filter"
documentUpdated = "Document updated"
dualPageView = "Dual Page View"
+editText = "Edit text"
enableDarkFilter = "Enable Dark Filter"
enableSepiaFilter = "Enable Sepia Filter"
engineLoadError = "Failed to initialize PDF viewer engine"
@@ -15054,8 +15033,10 @@ closeAll = "Close All Files"
closePdf = "Close PDF"
deselectAll = "Deselect All"
downloadAll = "Download All"
+editText = "Edit Text"
exitAnnotations = "Exit annotation mode"
exitRedaction = "Exit Redaction Mode"
+findReplace = "Find & replace"
formFill = "Form Editor"
hideToolbar = "Hide toolbar"
moreActions = "More actions"
diff --git a/frontend/src/editor/core/components/layout/Workbench.tsx b/frontend/src/editor/core/components/layout/Workbench.tsx
index 8ca423a6c4..9023125055 100644
--- a/frontend/src/editor/core/components/layout/Workbench.tsx
+++ b/frontend/src/editor/core/components/layout/Workbench.tsx
@@ -12,7 +12,8 @@ import {
} from "@editor/contexts/NavigationContext";
import { isBaseWorkbench } from "@editor/types/workbench";
import { VIEWER_SUPPORTED_EXTENSIONS } from "@editor/utils/fileUtils";
-import { useIsPhone } from "@editor/hooks/useIsMobile";
+import { useIsMobile, useIsPhone } from "@editor/hooks/useIsMobile";
+import { useViewerPageTool } from "@editor/contexts/viewer/ViewerPageTool";
import styles from "@editor/components/layout/Workbench.module.css";
import WorkbenchBar from "@editor/components/shared/WorkbenchBar";
@@ -87,6 +88,12 @@ export default function Workbench() {
// bar, outside the bar's overflow-clipped wrapper. Scoped to the viewer.
const [viewerToolbarCollapsed, setViewerToolbarCollapsed] = useState(false);
const showReopenTab = currentView === "viewer" && viewerToolbarCollapsed;
+ // A page tool brings its own header, and a small screen has no height to
+ // spare for the viewer's as well.
+ const isMobile = useIsMobile();
+ const pageToolActive = useViewerPageTool() != null;
+ const pageToolOwnsTop =
+ isMobile && pageToolActive && currentView === "viewer";
// The WorkbenchBar carries file-scoped actions, so it only shows once a file
// is open or a custom view supplies content; otherwise the search floats.
@@ -94,7 +101,9 @@ export default function Workbench() {
(v) => v.workbenchId === currentView,
);
const topControlsAvailable =
- currentView !== "signing" && !activeCustomView?.hideTopControls;
+ currentView !== "signing" &&
+ !activeCustomView?.hideTopControls &&
+ !pageToolOwnsTop;
const hasWorkbenchContent =
hasFiles ||
fileIds.length > 0 ||
diff --git a/frontend/src/editor/core/components/shared/WorkbenchBar.tsx b/frontend/src/editor/core/components/shared/WorkbenchBar.tsx
index 7adbd59c5f..26f2400816 100644
--- a/frontend/src/editor/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/src/editor/core/components/shared/WorkbenchBar.tsx
@@ -33,7 +33,6 @@ import { isStirlingFile } from "@editor/types/fileContext";
import { useFileActionTerminology } from "@editor/hooks/useFileActionTerminology";
import { useFileActionIcons } from "@editor/hooks/useFileActionIcons";
import { useToolWorkflow } from "@editor/contexts/ToolWorkflowContext";
-import { useNavigationState } from "@editor/contexts/NavigationContext";
import { ViewerContext, useViewer } from "@editor/contexts/ViewerContext";
import { WorkbenchType, isBaseWorkbench } from "@editor/types/workbench";
import SuperSearch from "@editor/components/shared/superSearch/SuperSearch";
@@ -106,7 +105,6 @@ export default function WorkbenchBar({
useWorkbenchBar();
const { toolPanelMode, leftPanelView, customWorkbenchViews } =
useToolWorkflow();
- const { selectedTool } = useNavigationState();
const isCustomView = !isBaseWorkbench(currentView);
const isViewer = currentView === "viewer";
@@ -372,18 +370,12 @@ export default function WorkbenchBar({
);
// View options
- // Tools that own a custom workbench ship their own canvas.
- const ownsCustomWorkbenchAsDefault = selectedTool === "pdfTextEditor";
const viewOptions: ViewOption[] = [
- ...(ownsCustomWorkbenchAsDefault
- ? []
- : [
- {
- value: "viewer" as WorkbenchType,
- label: t("workbenchBar.viewer", "Viewer"),
- icon: <Icon name="file" size={20} />,
- },
- ]),
+ {
+ value: "viewer",
+ label: t("workbenchBar.viewer", "Viewer"),
+ icon: <Icon name="file" size={20} />,
+ },
{
value: "pageEditor",
label: t("workbenchBar.pageEditor", "Page Editor"),
diff --git a/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx b/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx
index 6c857fb8a6..27706f9a36 100644
--- a/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx
@@ -77,6 +77,9 @@ import { ScaleCalibrationDialog } from "@editor/components/viewer/ScaleCalibrati
import { usePolicyFileBadges } from "@editor/hooks/usePolicyFileBadges";
import { alert } from "@editor/components/toast";
import { useDamagedFileRepair } from "@editor/contexts/DamagedFileRepairContext";
+import { useViewerPageTool } from "@editor/contexts/viewer/ViewerPageTool";
+import { useIsMobile } from "@editor/hooks/useIsMobile";
+import "@editor/tools/pdfTextEditor/components/EditorTopBar.css";
// ──────────────────────────────────────────────────────────────────────────────
@@ -143,6 +146,7 @@ const EmbedPdfViewerContent = ({
const viewerRef = React.useRef<HTMLDivElement>(null);
const pdfContainerRef = useRef<HTMLDivElement>(null);
const [isViewerHovered, setIsViewerHovered] = React.useState(false);
+ const registeredPageTool = useViewerPageTool();
const {
isThumbnailSidebarVisible,
@@ -156,12 +160,13 @@ const EmbedPdfViewerContent = ({
searchInterfaceActions,
zoomActions,
scrollActions,
- panActions: _panActions,
+ panActions,
rotationActions,
getScrollState,
getSpreadState,
getZoomState,
registerImmediateZoomUpdate,
+ registerImmediateRotationUpdate,
getRotationState,
zoomRestorePendingRef,
notifyZoomRestoreSettled,
@@ -542,6 +547,7 @@ const EmbedPdfViewerContent = ({
} = useNavigationGuard();
const { selectedTool } = useNavigationState();
+ const isMobile = useIsMobile();
useEffect(() => {
if (selectedTool !== "redact") {
@@ -570,6 +576,9 @@ const EmbedPdfViewerContent = ({
// FormFill tool mode — uses PDFBox backend for full-fidelity form handling
const isFormFillToolActive = (selectedTool as string) === "formFill";
+ const pageTool = previewFile ? null : registeredPageTool;
+ const pageToolActive = pageTool != null;
+
// Form overlays are shown in BOTH modes:
// - Normal viewer: form overlays visible (PDFium WASM, frontend-only)
// - formFill tool: form overlays visible (PDFBox, backend)
@@ -708,6 +717,39 @@ const EmbedPdfViewerContent = ({
return currentFileId;
}, [previewFile, currentFile, currentFileId, selectors]);
+ // A page tool draws in the page's own orientation, so a view rotation would
+ // leave its layers off the page content. The rotation comes back when the
+ // tool closes, if the same document is still open.
+ const heldRotationRef = useRef<{ rootId: string | null; rotation: number }>(
+ null,
+ );
+ useEffect(() => {
+ if (!pageToolActive) return;
+ heldRotationRef.current ??= {
+ rootId: currentFileRootId ?? null,
+ rotation: getRotationState().rotation,
+ };
+ const straighten = (rotation: number) => {
+ if (rotation !== 0) rotationActions.setRotation(0);
+ };
+ straighten(getRotationState().rotation);
+ return registerImmediateRotationUpdate(straighten);
+ }, [
+ pageToolActive,
+ currentFileRootId,
+ rotationActions,
+ getRotationState,
+ registerImmediateRotationUpdate,
+ ]);
+ useEffect(() => {
+ if (pageToolActive) return;
+ const held = heldRotationRef.current;
+ heldRotationRef.current = null;
+ if (held?.rotation && held.rootId === (currentFileRootId ?? null)) {
+ rotationActions.setRotation(held.rotation);
+ }
+ }, [pageToolActive, currentFileRootId, rotationActions]);
+
// Determine the effective file to display
const effectiveFile = React.useMemo(() => {
if (previewFile) {
@@ -817,6 +859,7 @@ const EmbedPdfViewerContent = ({
return;
case "a":
case "A":
+ if (pageToolActive) return;
// Intercept unconditionally so the browser can't blanket-select the surrounding UI chrome.
event.preventDefault();
{
@@ -847,8 +890,8 @@ const EmbedPdfViewerContent = ({
// All remaining shortcuts require the viewer to be hovered so they
// don't conflict with the rest of the UI when the viewer is mounted
- // but not the active focus target.
- if (!isViewerHovered) return;
+ // but not the active focus target. A page tool binds its own.
+ if (!isViewerHovered || pageToolActive) return;
// Modifier key shortcuts (Ctrl/Cmd + key)
if (mod) {
@@ -932,6 +975,7 @@ const EmbedPdfViewerContent = ({
document.removeEventListener("keydown", handleKeyDown);
};
}, [
+ pageToolActive,
isViewerHovered,
isSearchInterfaceVisible,
zoomActions,
@@ -1414,6 +1458,16 @@ const EmbedPdfViewerContent = ({
// Register navigation warning handlers so the global modal can call our save/discard logic
useEffect(() => {
if (previewFile || isFormFillToolActive) return;
+ // The guard holds one set of handlers: while a page tool owns the pages,
+ // its discard is the one that matters.
+ if (pageTool) {
+ const discard = pageTool.onDiscard;
+ registerNavigationWarningHandlers({
+ onApplyAndContinue: pageTool.onSave,
+ onDiscardAndContinue: async () => discard?.(),
+ });
+ return () => unregisterNavigationWarningHandlers();
+ }
registerNavigationWarningHandlers({
onApplyAndContinue: async () => {
@@ -1436,6 +1490,7 @@ const EmbedPdfViewerContent = ({
}, [
previewFile,
isFormFillToolActive,
+ pageTool,
applyChanges,
discardAndSaveApplied,
registerNavigationWarningHandlers,
@@ -1793,6 +1848,15 @@ const EmbedPdfViewerContent = ({
rulerOverlayRef,
});
+ // A page tool takes the pages' pointer input and draws its own find, so the
+ // viewer's ruler, pan and search stand down while it is open.
+ useEffect(() => {
+ if (!pageToolActive) return;
+ setIsRulerActive(false);
+ panActions.disablePan();
+ searchInterfaceActions.close();
+ }, [pageToolActive, setIsRulerActive, panActions, searchInterfaceActions]);
+
// Register workbench bar buttons for the viewer
useViewerWorkbenchBarButtons(
isRulerActive,
@@ -1926,9 +1990,24 @@ const EmbedPdfViewerContent = ({
{currentFile && isStirlingFile(currentFile) && (
<PdfProtectionStatus key={currentFile.fileId} file={currentFile} />
)}
+ {pageTool ? (
+ <pageTool.Toolbar />
+ ) : (
+ selectedTool === "pdfTextEditor" &&
+ !isMobile &&
+ !previewFile && (
+ // Holds the editor bar's place while the editor loads, so the
+ // bar shows at once and the pages do not shift when it lands.
+ <div
+ className="pdf-editor-topbar pdf-editor-topbar--pending"
+ data-testid="pdf-editor-toolbar-pending"
+ />
+ )
+ )}
{/* EmbedPDF Viewer */}
<Box
ref={pdfContainerRef}
+ data-viewer-pages
style={{
position: "relative",
flex: 1,
@@ -1977,6 +2056,11 @@ const EmbedPdfViewerContent = ({
shouldEnableFormFill && !pdfEditingLocked(pdfAccess)
}
formEditingActive={isFormFillToolActive}
+ pageLayer={
+ pageTool && pageTool.fileId === currentFileStableId
+ ? pageTool.PageLayer
+ : null
+ }
isManualRedactionMode={isManualRedactMode}
signatureApiRef={signatureApiRef}
annotationApiRef={annotationApiRef}
@@ -2023,6 +2107,7 @@ const EmbedPdfViewerContent = ({
onCalibrationMeasure={handleScaleCalibrationMeasurement}
/>
</Box>
+ {pageTool?.BottomBar && <pageTool.BottomBar />}
<ScaleCalibrationDialog
opened={!!scaleCalibrationMeasurement}
measurement={scaleCalibrationMeasurement}
@@ -2034,7 +2119,7 @@ const EmbedPdfViewerContent = ({
)}
{/* Bottom Toolbar Overlay */}
- {effectiveFile && (
+ {effectiveFile && !pageTool?.BottomBar && (
<div
className="pdf-viewer-toolbar-dock"
style={{
diff --git a/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx b/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx
index 664d63886f..e5e2824448 100644
--- a/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/src/editor/core/components/viewer/LocalEmbedPDF.tsx
@@ -6,6 +6,7 @@ import React, {
useMemo,
useRef,
useState,
+ type ComponentType,
} from "react";
import { createPluginRegistration, type PluginRegistry } from "@embedpdf/core";
import type { InitialDocumentOptions } from "@embedpdf/plugin-document-manager";
@@ -141,6 +142,8 @@ import { useFontFallbackConfig } from "@editor/hooks/useFontFallbackConfig";
import { pdfiumWasmUrl } from "@editor/services/wasmPrecompiler";
import { FormFieldOverlay } from "@editor/tools/formFill/FormFieldOverlay";
import { FormCreationInteractionLock } from "@editor/tools/formFill/FormCreationInteractionLock";
+import { ViewerInteractionLock } from "@editor/components/viewer/ViewerInteractionLock";
+import type { ViewerPageLayerProps } from "@editor/contexts/viewer/ViewerPageTool";
import { FormFieldCreationOverlay } from "@editor/tools/formFill/FormFieldCreationOverlay";
import { FormFieldEditOverlay } from "@editor/tools/formFill/FormFieldEditOverlay";
import { ButtonAppearanceOverlay } from "@editor/tools/formFill/ButtonAppearanceOverlay";
@@ -159,6 +162,8 @@ interface LocalEmbedPDFProps {
enableFormFill?: boolean;
/** Structural create/modify overlays only mount while the Form tool owns the viewer. */
formEditingActive?: boolean;
+ /** A tool's layer that replaces each page's own, or null for the viewer's layers. */
+ pageLayer?: ComponentType<ViewerPageLayerProps> | null;
isManualRedactionMode?: boolean;
showBakedAnnotations?: boolean;
onSignatureAdded?: (annotation: PdfAnnotationObject) => void;
@@ -224,6 +229,11 @@ interface ViewerPageContainerProps {
onPageLayout?: () => void;
/** Gates the layout callback so steady-state scrolling pays nothing. */
restorePending?: boolean;
+ /**
+ * Clip overlays to the page rect. A page tool's handles must stay reachable
+ * where an object sticks out past the page edge.
+ */
+ clip?: boolean;
}
function normalizePageRotation(rotation: number | null | undefined): number {
@@ -364,6 +374,7 @@ function ViewerPageContainer({
children,
onPageLayout,
restorePending = false,
+ clip = true,
}: ViewerPageContainerProps) {
const documentState = useDocumentState(documentId);
const pageRotation = normalizePageRotation(
@@ -385,7 +396,7 @@ function ViewerPageContainer({
width,
height,
position: "relative",
- overflow: "hidden", // clip overlays (buttons, fields) that extend beyond the page rect
+ overflow: clip ? "hidden" : "visible",
userSelect: "none",
WebkitUserSelect: "none",
MozUserSelect: "none",
@@ -431,6 +442,7 @@ interface PageLayerOptions {
pdfRenderMode: PdfRenderMode;
enableFormFill: boolean;
formEditingActive: boolean;
+ pageLayer: ComponentType<ViewerPageLayerProps> | null;
enableAnnotations: boolean;
annotationsReadOnly: boolean;
canCopy: boolean;
@@ -452,7 +464,8 @@ function PageTiles({
documentId,
pageIndex,
renderMode,
-}: PageLayerProps & { renderMode: PdfRenderMode }) {
+ hidden = false,
+}: PageLayerProps & { renderMode: PdfRenderMode; hidden?: boolean }) {
return (
<div
style={{
@@ -460,6 +473,7 @@ function PageTiles({
inset: 0,
transition: "filter 0.25s ease",
filter: PDF_RENDER_FILTERS[renderMode],
+ visibility: hidden ? "hidden" : undefined,
}}
>
<TilingLayer documentId={documentId} pageIndex={pageIndex} />
@@ -631,6 +645,7 @@ function PageLayers({
pdfRenderMode,
enableFormFill,
formEditingActive,
+ pageLayer: PageLayer,
enableAnnotations,
annotationsReadOnly,
canCopy,
@@ -641,13 +656,10 @@ function PageLayers({
readOnlySignaturePreviews,
}: PageGeometry & PageLayerOptions) {
const { isAnnotationMode } = useViewer();
- return (
+ const [covered, setCovered] = useState(false);
+ const toolCovers = !!PageLayer && covered;
+ const overlays = (
<>
- <PageTiles
- documentId={documentId}
- pageIndex={pageIndex}
- renderMode={pdfRenderMode}
- />
<CustomSearchLayer documentId={documentId} pageIndex={pageIndex} />
<PageTextSelection
documentId={documentId}
@@ -712,6 +724,28 @@ function PageLayers({
)}
</>
);
+ // The tiles keep their place in the tree and stay mounted, only hidden, under
+ // a page tool: remounting them blanks the page while they reload, on the way
+ // into the tool and again on the way out.
+ return (
+ <>
+ <PageTiles
+ documentId={documentId}
+ pageIndex={pageIndex}
+ renderMode={pdfRenderMode}
+ hidden={toolCovers}
+ />
+ {!toolCovers && overlays}
+ {PageLayer && (
+ <PageLayer
+ pageIndex={pageIndex}
+ width={width}
+ height={height}
+ onCovered={setCovered}
+ />
+ )}
+ </>
+ );
}
function ViewerPage({
@@ -730,6 +764,7 @@ function ViewerPage({
height={layers.height}
onPageLayout={onPageLayout}
restorePending={restorePending}
+ clip={!layers.pageLayer}
>
<PageLayers {...layers} />
</ViewerPageContainer>
@@ -906,6 +941,7 @@ export function LocalEmbedPDF({
enableRedaction = false,
enableFormFill = false,
formEditingActive = false,
+ pageLayer = null,
isManualRedactionMode = false,
showBakedAnnotations = true,
onSignatureAdded,
@@ -1639,6 +1675,7 @@ export function LocalEmbedPDF({
pdfRenderMode,
enableFormFill,
formEditingActive,
+ pageLayer,
enableAnnotations: true,
annotationsReadOnly,
canCopy: pdfAllows(pdfAccess, PdfPermissionFlag.CopyContents),
@@ -1705,6 +1742,7 @@ export function LocalEmbedPDF({
canCopy={pdfAllows(pdfAccess, PdfPermissionFlag.CopyContents)}
/>
<FormCreationInteractionLock />
+ <ViewerInteractionLock active={pageLayer != null} />
<PanAPIBridge />
<SpreadAPIBridge />
<SearchAPIBridge />
diff --git a/frontend/src/editor/core/components/viewer/TextSelectionMenu.test.tsx b/frontend/src/editor/core/components/viewer/TextSelectionMenu.test.tsx
index 62b2eeab8c..da7b435059 100644
--- a/frontend/src/editor/core/components/viewer/TextSelectionMenu.test.tsx
+++ b/frontend/src/editor/core/components/viewer/TextSelectionMenu.test.tsx
@@ -64,8 +64,11 @@ const mockHandleToolSelectForced = vi.fn();
const mockSetLeftPanelView = vi.fn();
vi.mock("@editor/contexts/ToolWorkflowContext", () => ({
useToolWorkflow: () => ({
+ handleToolSelect: vi.fn(),
handleToolSelectForced: mockHandleToolSelectForced,
setLeftPanelView: mockSetLeftPanelView,
+ toolAvailability: {},
+ toolRegistry: {},
}),
}));
@@ -92,6 +95,8 @@ vi.mock("@editor/contexts/NavigationContext", () => ({
setHasUnsavedChanges: mockSetHasUnsavedChanges,
},
}),
+ useNavigationGuard: () => ({ requestNavigation: (fn: () => void) => fn() }),
+ useNavigationState: () => ({ selectedTool: null }),
}));
const mockAlert = vi.fn();
diff --git a/frontend/src/editor/core/components/viewer/TextSelectionMenu.tsx b/frontend/src/editor/core/components/viewer/TextSelectionMenu.tsx
index 4e51e54490..1a7220b2b5 100644
--- a/frontend/src/editor/core/components/viewer/TextSelectionMenu.tsx
+++ b/frontend/src/editor/core/components/viewer/TextSelectionMenu.tsx
@@ -17,8 +17,13 @@ import {
import { useActiveDocumentId } from "@editor/components/viewer/useActiveDocumentId";
import { useToolWorkflow } from "@editor/contexts/ToolWorkflowContext";
import { useRedaction } from "@editor/contexts/RedactionContext";
-import { useNavigationActions } from "@editor/contexts/NavigationContext";
import { useViewer } from "@editor/contexts/ViewerContext";
+import {
+ useNavigationActions,
+ useNavigationGuard,
+ useNavigationState,
+} from "@editor/contexts/NavigationContext";
+import { useSetViewerTextTarget } from "@editor/contexts/viewer/ViewerPageTool";
import {
defaultParameters,
RedactParameters,
@@ -63,7 +68,16 @@ function TextSelectionMenuInner({
const { provides: selection } = useSelectionCapability();
const { provides: annotationProvides } = useAnnotation(documentId ?? "");
- const { handleToolSelectForced, setLeftPanelView } = useToolWorkflow();
+ const {
+ handleToolSelect,
+ handleToolSelectForced,
+ setLeftPanelView,
+ toolAvailability,
+ toolRegistry,
+ } = useToolWorkflow();
+ const { requestNavigation } = useNavigationGuard();
+ const { selectedTool } = useNavigationState();
+ const setTextTarget = useSetViewerTextTarget();
const {
setRedactionMode,
activateRedact,
@@ -73,7 +87,7 @@ function TextSelectionMenuInner({
manualRedactColor,
} = useRedaction();
const { actions: navActions } = useNavigationActions();
- const { selectionActions } = useViewer();
+ const { selectionActions, activeFileId } = useViewer();
const wrapperRef = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState<{
@@ -271,6 +285,49 @@ function TextSelectionMenuInner({
],
);
+ const canEditText =
+ !readOnly &&
+ activeFileId != null &&
+ selectedTool !== "pdfTextEditor" &&
+ toolRegistry.pdfTextEditor != null &&
+ toolAvailability.pdfTextEditor?.available !== false;
+
+ // Opens the text editor with the selected text selected in it.
+ const handleEditText = useCallback(() => {
+ if (!documentId || !selection || !activeFileId) return;
+ const fileId = activeFileId;
+ const first = selection.getFormattedSelection(documentId)[0];
+ if (!first) return;
+ const open = (text: string) => {
+ selection.clear(documentId);
+ requestNavigation(() => {
+ setTextTarget({
+ fileId,
+ pageIndex: first.pageIndex,
+ text,
+ rect: {
+ x: first.rect.origin.x,
+ y: first.rect.origin.y,
+ width: first.rect.size.width,
+ height: first.rect.size.height,
+ },
+ });
+ handleToolSelect("pdfTextEditor");
+ });
+ };
+ selection.getSelectedText(documentId).wait(
+ (texts) => open(texts[0] ?? ""),
+ () => open(""),
+ );
+ }, [
+ documentId,
+ selection,
+ requestNavigation,
+ setTextTarget,
+ activeFileId,
+ handleToolSelect,
+ ]);
+
const canReadAloud =
typeof window !== "undefined" && "speechSynthesis" in window;
@@ -520,6 +577,23 @@ function TextSelectionMenuInner({
</>
)}
+ {canEditText && (
+ <Tooltip label={t("viewer.editText", "Edit text")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleEditText}
+ onPointerEnter={() =>
+ void toolRegistry.pdfTextEditor?.preload?.()
+ }
+ aria-label={t("viewer.editText", "Edit text")}
+ data-testid="text-selection-edit-text"
+ >
+ <Icon name="square-pen" size={20} />
+ </button>
+ </Tooltip>
+ )}
+
{canReadAloud && (
<Tooltip
label={t("viewer.readAloudFromHere", "Read aloud from here")}
diff --git a/frontend/src/editor/core/components/viewer/ViewerInteractionLock.tsx b/frontend/src/editor/core/components/viewer/ViewerInteractionLock.tsx
new file mode 100644
index 0000000000..193bb023c9
--- /dev/null
+++ b/frontend/src/editor/core/components/viewer/ViewerInteractionLock.tsx
@@ -0,0 +1,22 @@
+import { useEffect } from "react";
+import { useInteractionManagerCapability } from "@embedpdf/plugin-interaction-manager/react";
+
+/**
+ * Holds the viewer's own pointer interactions paused while `active`, so a tool
+ * drawing or editing on the pages never also selects the text underneath.
+ *
+ * Mount once per document, not per page: page overlays live inside a
+ * virtualising Scroller, so one scrolling out of view would otherwise resume
+ * mid-session. Never flip `active` mid-gesture: pausing between a pointerdown
+ * and its pointerup strands the selection, which then keeps extending on every
+ * move once resumed.
+ */
+export function ViewerInteractionLock({ active }: { active: boolean }) {
+ const { provides: interactionManager } = useInteractionManagerCapability();
+ useEffect(() => {
+ if (!active || !interactionManager) return undefined;
+ interactionManager.pause();
+ return () => interactionManager.resume();
+ }, [active, interactionManager]);
+ return null;
+}
diff --git a/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx b/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx
index a3ff189a25..693dbde613 100644
--- a/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx
+++ b/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx
@@ -22,6 +22,8 @@ import {
} from "@editor/utils/viewerZoom";
import { getFirstPageAspectRatioFromStub } from "@editor/utils/pageMetadata";
import { useDocumentReady } from "@editor/components/viewer/hooks/useDocumentReady";
+import { useViewerPageTool } from "@editor/contexts/viewer/ViewerPageTool";
+import { useIsMobile } from "@editor/hooks/useIsMobile";
import {
preferencesService,
type ViewerZoomSetting,
@@ -83,6 +85,11 @@ function ZoomAPIBridgeInner({
(activeId ? fileStubs.find((s) => s.id === activeId) : undefined) ??
fileStubs[0];
const activeFileRootId = activeStub?.originalFileId || activeStub?.id;
+ // A document opened into a page tool on a small screen starts at full
+ // width, where its content is large enough to work on.
+ const isMobile = useIsMobile();
+ const pageToolActive = useViewerPageTool() != null;
+ const fitForPageTool = isMobile && pageToolActive;
const hasSetInitialZoom = useRef(
!!activeFileRootId && activeFileRootId === lastAutoZoomedRootIdRef.current,
@@ -245,6 +252,11 @@ function ZoomAPIBridgeInner({
return;
}
+ if (fitForPageTool) {
+ applyTrackedZoom(ZoomMode.FitWidth, fitWidthZoom);
+ return;
+ }
+
// Check user preference for default viewer zoom
const zoomPref: ViewerZoomSetting =
preferencesService.getPreference("defaultViewerZoom");
@@ -310,6 +322,7 @@ function ZoomAPIBridgeInner({
spreadMode,
triggerImmediateZoomUpdate,
explicitFitRef,
+ fitForPageTool,
]);
// Subscribe to zoom changes - use ref to avoid re-subscribing when zoom reference changes
diff --git a/frontend/src/editor/core/components/viewer/useViewerWorkbenchBarButtons.tsx b/frontend/src/editor/core/components/viewer/useViewerWorkbenchBarButtons.tsx
index 7bff5b39dd..89471ce16b 100644
--- a/frontend/src/editor/core/components/viewer/useViewerWorkbenchBarButtons.tsx
+++ b/frontend/src/editor/core/components/viewer/useViewerWorkbenchBarButtons.tsx
@@ -1,9 +1,16 @@
-import { useMemo, useState, useEffect, useCallback } from "react";
+import {
+ useMemo,
+ useState,
+ useEffect,
+ useCallback,
+ type ComponentProps,
+} from "react";
import { Slider, Popover, Select } from "@mantine/core";
import { ActionIcon } from "@editor/ui/ActionIcon";
import { useTranslation } from "react-i18next";
import { supportedLanguages } from "@editor/i18n";
import { useViewer } from "@editor/contexts/ViewerContext";
+import { useViewerPageTool } from "@editor/contexts/viewer/ViewerPageTool";
import {
useWorkbenchBarButtons,
WorkbenchBarButtonWithAction,
@@ -57,8 +64,15 @@ export function useViewerWorkbenchBarButtons(
sidebarRefs,
12,
);
- const { handleToolSelect, handleToolSelectForced, handleBackToTools } =
- useToolWorkflow();
+ const {
+ handleToolSelect,
+ handleToolSelectForced,
+ handleBackToTools,
+ clearToolSelection,
+ setLeftPanelView,
+ setReaderMode,
+ toolRegistry,
+ } = useToolWorkflow();
const { selectedTool } = useNavigationState();
const { requestNavigation } = useNavigationGuard();
const { redactionsApplied, activeType: redactionActiveType } = useRedaction();
@@ -84,7 +98,6 @@ export function useViewerWorkbenchBarButtons(
// mirror drifts the moment the address changes without a popstate.
const isAnnotationsActive = selectedTool === "annotate";
- const searchLabel = t("workbenchBar.search", "Search PDF");
const panLabel = t("workbenchBar.panMode", "Pan Mode");
const applyRedactionsLabel = t(
"workbenchBar.applyRedactionsFirst",
@@ -109,12 +122,45 @@ export function useViewerWorkbenchBarButtons(
"Exit annotation mode",
);
const formFillLabel = t("workbenchBar.formFill", "Form Editor");
+ const editTextLabel = t("workbenchBar.editText", "Edit Text");
const rulerLabel = t("workbenchBar.ruler", "Ruler / Measure");
const rulerSettingsLabel = t("workbenchBar.rulerSettings", "Scale Settings");
const readAloudLabel = t("workbenchBar.readAloud", "Read Aloud");
const readAloudSpeedLabel = t("workbenchBar.readAloudSpeed", "Speed");
const isFormFillActive = (selectedTool as string) === "formFill";
+ const isTextEditActive = selectedTool === "pdfTextEditor";
+ const pageTool = useViewerPageTool();
+ const pageToolActive = pageTool != null;
+ // While a page tool with its own find is open, the search button opens that.
+ const searchLabel = pageTool?.onToggleFind
+ ? t("workbenchBar.findReplace", "Find & replace")
+ : t("workbenchBar.search", "Search PDF");
+
+ // The text editor owns the pages while it is open, so a viewer tool that
+ // works on them closes it first, behind the unsaved-edits prompt. Leaving
+ // without a second guard: the prompt has already settled the edits.
+ const leaveTextEditThen = useCallback(
+ (action: () => void) => {
+ if (!isTextEditActive) {
+ action();
+ return;
+ }
+ requestNavigation(() => {
+ setLeftPanelView("toolPicker");
+ setReaderMode(false);
+ clearToolSelection();
+ action();
+ });
+ },
+ [
+ isTextEditActive,
+ requestNavigation,
+ setLeftPanelView,
+ setReaderMode,
+ clearToolSelection,
+ ],
+ );
const handleStartScaleCalibration = useCallback(() => {
startScaleCalibration?.();
@@ -191,7 +237,13 @@ export function useViewerWorkbenchBarButtons(
className="workbench-bar-action-icon"
disabled={disabled}
aria-label={searchLabel}
- onClick={viewer.searchInterfaceActions.toggle}
+ onClick={() =>
+ pageTool?.onToggleFind
+ ? pageTool.onToggleFind()
+ : leaveTextEditThen(
+ viewer.searchInterfaceActions.toggle,
+ )
+ }
>
<Icon name="file-search" size="1.25rem" />
</ActionIcon>
@@ -225,10 +277,11 @@ export function useViewerWorkbenchBarButtons(
active: isPanning,
disabled:
!isPanning && pendingCount > 0 && redactionActiveType !== null,
- onClick: () => {
- viewer.panActions.togglePan();
- if (!isPanning && isRulerActive) setIsRulerActive?.(false);
- },
+ onClick: () =>
+ leaveTextEditThen(() => {
+ viewer.panActions.togglePan();
+ if (!isPanning && isRulerActive) setIsRulerActive?.(false);
+ }),
},
{
id: "viewer-ruler",
@@ -238,13 +291,14 @@ export function useViewerWorkbenchBarButtons(
section: "top" as const,
order: 25,
active: Boolean(isRulerActive),
- onClick: () => {
- const next = !isRulerActive;
- setIsRulerActive?.(next);
- if (next && isPanning) {
- viewer.panActions.disablePan();
- }
- },
+ onClick: () =>
+ leaveTextEditThen(() => {
+ const next = !isRulerActive;
+ setIsRulerActive?.(next);
+ if (next && isPanning) {
+ viewer.panActions.disablePan();
+ }
+ }),
},
// Ruler scale settings button - only visible when ruler is active
...(isRulerActive
@@ -279,6 +333,7 @@ export function useViewerWorkbenchBarButtons(
ariaLabel: rotateLeftLabel,
section: "top" as const,
order: 30,
+ disabled: pageToolActive,
onClick: () => {
viewer.rotationActions.rotateBackward();
},
@@ -290,6 +345,7 @@ export function useViewerWorkbenchBarButtons(
ariaLabel: rotateRightLabel,
section: "top" as const,
order: 40,
+ disabled: pageToolActive,
onClick: () => {
viewer.rotationActions.rotateForward();
},
@@ -518,31 +574,41 @@ export function useViewerWorkbenchBarButtons(
section: "top" as const,
order: 62,
render: ({ disabled }) => (
- <Tooltip
- content={formFillLabel}
- position={tooltipPosition}
- offset={12}
- arrow
- portalTarget={document.body}
- >
- <ActionIcon
- variant={isFormFillActive ? "primary" : "tertiary"}
- className="workbench-bar-action-icon"
- onClick={() => {
- if (disabled) return;
- if (isFormFillActive) {
- handleBackToTools();
- } else {
- handleToolSelect("formFill");
- }
- }}
- disabled={disabled}
- aria-pressed={isFormFillActive}
- aria-label={formFillLabel}
- >
- <Icon name="type" size={"1rem"} />
- </ActionIcon>
- </Tooltip>
+ <ToolModeToggle
+ label={formFillLabel}
+ icon="type"
+ active={isFormFillActive}
+ disabled={disabled}
+ tooltipPosition={tooltipPosition}
+ onToggle={() =>
+ isFormFillActive
+ ? handleBackToTools()
+ : handleToolSelect("formFill")
+ }
+ />
+ ),
+ },
+ {
+ id: "viewer-edit-text",
+ tooltip: editTextLabel,
+ ariaLabel: editTextLabel,
+ section: "top" as const,
+ order: 63,
+ render: ({ disabled }) => (
+ <ToolModeToggle
+ label={editTextLabel}
+ icon="square-pen"
+ active={isTextEditActive}
+ disabled={disabled}
+ tooltipPosition={tooltipPosition}
+ onToggle={() =>
+ isTextEditActive
+ ? handleBackToTools()
+ : handleToolSelect("pdfTextEditor")
+ }
+ onIntent={() => void toolRegistry.pdfTextEditor?.preload?.()}
+ testId="viewer-edit-text"
+ />
),
},
];
@@ -581,6 +647,12 @@ export function useViewerWorkbenchBarButtons(
redactionActiveType,
formFillLabel,
isFormFillActive,
+ editTextLabel,
+ isTextEditActive,
+ toolRegistry,
+ pageTool,
+ pageToolActive,
+ leaveTextEditThen,
rulerLabel,
rulerSettingsLabel,
isRulerActive,
@@ -607,3 +679,51 @@ export function useViewerWorkbenchBarButtons(
useWorkbenchBarButtons(viewerButtons);
}
+
+/** A bar button that enters a tool which works on the viewer's pages, or leaves it. */
+function ToolModeToggle({
+ label,
+ icon,
+ active,
+ disabled,
+ tooltipPosition,
+ onToggle,
+ onIntent,
+ testId,
+}: {
+ label: string;
+ icon: ComponentProps<typeof Icon>["name"];
+ active: boolean;
+ disabled?: boolean;
+ tooltipPosition: ComponentProps<typeof Tooltip>["position"];
+ onToggle: () => void;
+ /** The pointer or focus arrived: a click may follow, so start loading the tool. */
+ onIntent?: () => void;
+ testId?: string;
+}) {
+ return (
+ <Tooltip
+ content={label}
+ position={tooltipPosition}
+ offset={12}
+ arrow
+ portalTarget={document.body}
+ >
+ <ActionIcon
+ variant={active ? "primary" : "tertiary"}
+ className="workbench-bar-action-icon"
+ onClick={() => {
+ if (!disabled) onToggle();
+ }}
+ onPointerEnter={onIntent}
+ onFocus={onIntent}
+ disabled={disabled}
+ aria-pressed={active}
+ aria-label={label}
+ data-testid={testId}
+ >
+ <Icon name={icon} size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/editor/core/contexts/ViewerContext.tsx b/frontend/src/editor/core/contexts/ViewerContext.tsx
index 0d2d0a2d1e..5c59e45fba 100644
--- a/frontend/src/editor/core/contexts/ViewerContext.tsx
+++ b/frontend/src/editor/core/contexts/ViewerContext.tsx
@@ -26,6 +26,7 @@ import {
createViewerActions,
type PrintActions,
} from "@editor/contexts/viewer/viewerActions";
+import { ViewerPageToolProvider } from "@editor/contexts/viewer/ViewerPageTool";
import {
BridgeRef,
BridgeApiMap,
@@ -628,6 +629,8 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
);
return (
- <ViewerContext.Provider value={value}>{children}</ViewerContext.Provider>
+ <ViewerContext.Provider value={value}>
+ <ViewerPageToolProvider>{children}</ViewerPageToolProvider>
+ </ViewerContext.Provider>
);
};
diff --git a/frontend/src/editor/core/contexts/viewer/ViewerPageTool.test.tsx b/frontend/src/editor/core/contexts/viewer/ViewerPageTool.test.tsx
new file mode 100644
index 0000000000..2786764746
--- /dev/null
+++ b/frontend/src/editor/core/contexts/viewer/ViewerPageTool.test.tsx
@@ -0,0 +1,71 @@
+import { describe, it, expect } from "vitest";
+import { render } from "@testing-library/react";
+import {
+ ViewerPageToolProvider,
+ useRegisterViewerPageTool,
+ useViewerPageTool,
+ type ViewerPageTool,
+} from "@editor/contexts/viewer/ViewerPageTool";
+
+const makeTool = (fileId: string): ViewerPageTool => ({
+ fileId,
+ PageLayer: () => null,
+ Toolbar: () => null,
+});
+
+function Registrant({ tool }: { tool: ViewerPageTool | null }) {
+ useRegisterViewerPageTool(tool);
+ return null;
+}
+
+let seen: ViewerPageTool | null = null;
+function Reader() {
+ seen = useViewerPageTool();
+ return null;
+}
+
+function Host({
+ first,
+ second,
+}: {
+ first?: ViewerPageTool | null;
+ second?: ViewerPageTool | null;
+}) {
+ return (
+ <ViewerPageToolProvider>
+ {first !== undefined && <Registrant tool={first} />}
+ {second !== undefined && <Registrant tool={second} />}
+ <Reader />
+ </ViewerPageToolProvider>
+ );
+}
+
+describe("viewer page tool slot", () => {
+ it("holds a registered tool until its registrant unmounts", () => {
+ const tool = makeTool("a");
+ const { rerender } = render(<Host first={tool} />);
+ expect(seen).toBe(tool);
+ rerender(<Host />);
+ expect(seen).toBeNull();
+ });
+
+ it("keeps a newer registration when an older registrant unmounts", () => {
+ const older = makeTool("a");
+ const newer = makeTool("b");
+ const { rerender } = render(<Host first={older} second={newer} />);
+ expect(seen).toBe(newer);
+ rerender(<Host second={newer} />);
+ expect(seen).toBe(newer);
+ });
+
+ it("does not clear another tool when a registrant passes null", () => {
+ const tool = makeTool("a");
+ render(<Host first={tool} second={null} />);
+ expect(seen).toBe(tool);
+ });
+
+ it("reads null without a provider", () => {
+ render(<Reader />);
+ expect(seen).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/contexts/viewer/ViewerPageTool.tsx b/frontend/src/editor/core/contexts/viewer/ViewerPageTool.tsx
new file mode 100644
index 0000000000..168cf4939a
--- /dev/null
+++ b/frontend/src/editor/core/contexts/viewer/ViewerPageTool.tsx
@@ -0,0 +1,133 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ComponentType,
+ type Dispatch,
+ type ReactNode,
+ type SetStateAction,
+} from "react";
+
+export interface ViewerPageLayerProps {
+ pageIndex: number;
+ /** CSS size of the viewer's page box, before the page's /Rotate is applied. */
+ width: number;
+ height: number;
+ /**
+ * Report whether the layer fully covers the page. Until it does, the viewer's
+ * own layers show underneath so the page never goes blank; once it does,
+ * the viewer hides its render and drops its other layers.
+ */
+ onCovered: (covered: boolean) => void;
+}
+
+/**
+ * A tool that works directly on the viewer's pages, replacing their layers.
+ *
+ * While one is registered the viewer pauses its own pointer interactions, keeps
+ * only its zoom and print shortcuts, and holds the view rotation at zero: the
+ * tool's layers are drawn in the page's own orientation.
+ */
+export interface ViewerPageTool {
+ /** Workbench file the tool is working on; pages of any other file stay the viewer's own. */
+ fileId: string | null;
+ PageLayer: ComponentType<ViewerPageLayerProps>;
+ /** Docked above the pages. */
+ Toolbar: ComponentType;
+ /** Docked below the pages, in place of the viewer's page and zoom bar. */
+ BottomBar?: ComponentType;
+ /**
+ * Drops the tool's unsaved work when the user discards it at the app's
+ * unsaved-changes prompt, which then lets the navigation through.
+ */
+ onDiscard?: () => void;
+ /**
+ * Saves the tool's work when the user picks Save at the app's unsaved-changes
+ * prompt. Rejecting keeps the prompt open.
+ */
+ onSave?: () => Promise<void>;
+ /** Toggles the tool's own find, which the viewer's search button opens in place of its own. */
+ onToggleFind?: () => void;
+}
+
+/** Text selected in the viewer that a page tool is asked to open at. */
+export interface ViewerTextTarget {
+ /** Workbench file the text is in. */
+ fileId: string;
+ pageIndex: number;
+ text: string;
+ /** Where the text sits on the page, in PDF points from the top-left corner. */
+ rect?: { x: number; y: number; width: number; height: number };
+}
+
+interface ViewerPageToolSlot {
+ tool: ViewerPageTool | null;
+ setTool: Dispatch<SetStateAction<ViewerPageTool | null>>;
+ /** Held until the tool that opens takes it. */
+ textTarget: ViewerTextTarget | null;
+ setTextTarget: (target: ViewerTextTarget | null) => void;
+}
+
+const ViewerPageToolContext = createContext<ViewerPageToolSlot>({
+ tool: null,
+ setTool: () => {},
+ textTarget: null,
+ setTextTarget: () => {},
+});
+
+export function ViewerPageToolProvider({ children }: { children: ReactNode }) {
+ const [tool, setTool] = useState<ViewerPageTool | null>(null);
+ const [textTarget, setTextTarget] = useState<ViewerTextTarget | null>(null);
+ const slot = useMemo(
+ () => ({ tool, setTool, textTarget, setTextTarget }),
+ [tool, textTarget],
+ );
+ return (
+ <ViewerPageToolContext.Provider value={slot}>
+ {children}
+ </ViewerPageToolContext.Provider>
+ );
+}
+
+/** The tool currently working on the viewer's pages, or null. */
+export function useViewerPageTool(): ViewerPageTool | null {
+ return useContext(ViewerPageToolContext).tool;
+}
+
+/**
+ * Registers `tool` on the viewer's pages for as long as the caller is mounted;
+ * null registers nothing. Pass a memoised value: a new object on every render
+ * re-registers it.
+ */
+export function useRegisterViewerPageTool(tool: ViewerPageTool | null): void {
+ const { setTool } = useContext(ViewerPageToolContext);
+ useEffect(() => {
+ if (!tool) return;
+ setTool(tool);
+ // Only withdraw our own registration: a tool that registered since keeps its slot.
+ return () => setTool((current) => (current === tool ? null : current));
+ }, [tool, setTool]);
+}
+
+/** Asks the next page tool to open at text selected in the viewer. */
+export function useSetViewerTextTarget(): (
+ target: ViewerTextTarget | null,
+) => void {
+ return useContext(ViewerPageToolContext).setTextTarget;
+}
+
+/** The text a page tool was asked to open at, if any, and how to drop it once taken. */
+export function useViewerTextTarget(): {
+ textTarget: ViewerTextTarget | null;
+ clearTextTarget: () => void;
+} {
+ const { textTarget, setTextTarget } = useContext(ViewerPageToolContext);
+ const clearTextTarget = useCallback(
+ () => setTextTarget(null),
+ [setTextTarget],
+ );
+ return { textTarget, clearTextTarget };
+}
diff --git a/frontend/src/editor/core/data/toolsTaxonomy.ts b/frontend/src/editor/core/data/toolsTaxonomy.ts
index 4adca98224..336f459854 100644
--- a/frontend/src/editor/core/data/toolsTaxonomy.ts
+++ b/frontend/src/editor/core/data/toolsTaxonomy.ts
@@ -42,6 +42,8 @@ export type ToolRegistryEntry = {
icon: React.ReactNode;
name: string;
component: React.ComponentType<BaseToolProps> | null;
+ /** Fetches `component`'s code ahead of first use, for tools opened in place where a load delay shows. */
+ preload?: () => Promise<unknown>;
description: string;
categoryId: ToolCategoryId;
subcategoryId: SubcategoryId;
diff --git a/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx b/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx
index 5f4993980a..9825a4d63d 100644
--- a/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx
+++ b/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx
@@ -66,6 +66,9 @@ import { ENDPOINTS as SPLIT_ENDPOINT_NAMES } from "@editor/constants/splitConsta
import { ToolId } from "@editor/types/toolId";
import { CONVERT_SUPPORTED_FORMATS } from "@editor/constants/convertSupportedFornats";
+const loadPdfTextEditor = () =>
+ import("@editor/tools/pdfTextEditor/PdfTextEditor");
+
export interface TranslatedToolCatalog {
allTools: ToolRegistry;
regularTools: RegularToolRegistry;
@@ -86,9 +89,8 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
pdfTextEditor: {
icon: <Icon name="square-pen" size="1.5rem" />,
name: t("home.pdfTextEditor.title", "PDF Text Editor"),
- component: lazy(
- () => import("@editor/tools/pdfTextEditor/PdfTextEditor"),
- ),
+ component: lazy(loadPdfTextEditor),
+ preload: loadPdfTextEditor,
description: t(
"home.pdfTextEditor.desc",
"Review and edit text and images in PDFs with grouped text editing and PDF regeneration",
diff --git a/frontend/src/editor/core/styles/zIndex.ts b/frontend/src/editor/core/styles/zIndex.ts
index fb4ee8c9d6..abc51acfb1 100644
--- a/frontend/src/editor/core/styles/zIndex.ts
+++ b/frontend/src/editor/core/styles/zIndex.ts
@@ -43,6 +43,8 @@ export const Z_INDEX_SIGN_IN_MODAL = 9000;
export const Z_INDEX_VIEWER_FLOATING_MENU = 10000;
export const Z_INDEX_TOAST = 10001;
+// A warning raised while the unsaved-changes prompt, which sits at the toast layer, waits on it.
+export const Z_INDEX_OVER_UNSAVED_PROMPT = 10002;
export const Z_INDEX_SIGNATURE_OVERLAY = 1000;
export const Z_INDEX_SIGNATURE_OVERLAY_HANDLE = 1001;
diff --git a/frontend/src/editor/core/tests/helpers/pdf-text-editor.ts b/frontend/src/editor/core/tests/helpers/pdf-text-editor.ts
new file mode 100644
index 0000000000..e858e6743c
--- /dev/null
+++ b/frontend/src/editor/core/tests/helpers/pdf-text-editor.ts
@@ -0,0 +1,242 @@
+import path from "path";
+import { expect, type Page } from "@playwright/test";
+
+type Upload = string | { name: string; mimeType: string; buffer: Buffer };
+
+/** Marks the file list's rows from before an upload, so the new row stands out. */
+const SEEN_ROW = "data-test-seen-row";
+
+/** The file-list rows whose file is named exactly `name`. */
+export function fileRows(page: Page, name: string) {
+ return page.locator(".file-sidebar-file-item").filter({
+ has: page.locator(".file-sidebar-file-name").getByText(name, {
+ exact: true,
+ }),
+ });
+}
+
+/**
+ * Adds `file` through the file list and returns its new row. A reopened saved
+ * copy shares its name with the original, and the list's order is not one
+ * to rely on, so the new row is the one that was not there before.
+ */
+async function addToFileList(page: Page, file: Upload) {
+ await page.evaluate((attr) => {
+ document
+ .querySelectorAll(".file-sidebar-file-item")
+ .forEach((el) => el.setAttribute(attr, ""));
+ }, SEEN_ROW);
+ await page.getByTestId("file-input").setInputFiles(file);
+ const name = typeof file === "string" ? path.basename(file) : file.name;
+ const added = fileRows(page, name).and(
+ page.locator(`.file-sidebar-file-item:not([${SEEN_ROW}])`),
+ );
+ await expect(added).toHaveCount(1, { timeout: 30_000 });
+ return added;
+}
+
+/** The zoom most specs' pixel geometry assumes. */
+const DEFAULT_ZOOM_PERCENT = 150;
+/** The viewer's zoom slider: 20% to 500% in steps of 5. */
+const SLIDER_MIN = 20;
+const SLIDER_MAX = 500;
+
+/**
+ * Opens `file` in the PDF text editor the way a user does: add it to the
+ * workspace, show it in the viewer, and let the editor follow. Works for a
+ * first open and for reopening a saved copy while another document is open.
+ * The viewer is then zoomed to `zoomPercent`; null leaves its own fit.
+ */
+export async function openInTextEditor(
+ page: Page,
+ file: Upload,
+ { zoomPercent = DEFAULT_ZOOM_PERCENT }: { zoomPercent?: number | null } = {},
+): Promise<void> {
+ if (
+ !new URL(page.url(), "http://x").pathname.startsWith("/pdf-text-editor")
+ ) {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ }
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __editor_store?: { document: unknown };
+ __openedBefore?: unknown;
+ };
+ w.__openedBefore = w.__editor_store?.document ?? null;
+ });
+
+ const name = typeof file === "string" ? path.basename(file) : file.name;
+ // Phones have no file list; any of the app's own upload inputs adds the file.
+ const hasSidebar = (await page.getByTestId("file-input").count()) > 0;
+ let row = null;
+ if (hasSidebar) {
+ row = await addToFileList(page, file);
+ } else {
+ await page
+ .locator('input[type="file"]:not([data-testid="pdf-editor-image-input"])')
+ .first()
+ .setInputFiles(file);
+ }
+
+ await expect
+ .poll(
+ async () => {
+ // A reload can bring back the file viewed before it, so the document
+ // must be this file's, not just a new one.
+ const opened = await page.evaluate((fileName) => {
+ const w = window as unknown as {
+ __editor_store?: {
+ document: unknown;
+ source: { fileName: string | null };
+ };
+ __openedBefore?: unknown;
+ };
+ const doc = w.__editor_store?.document ?? null;
+ return (
+ doc != null &&
+ doc !== w.__openedBefore &&
+ w.__editor_store?.source.fileName === fileName
+ );
+ }, name);
+ if (opened || !row) return opened;
+ // Viewing a row that is already shown closes it, so only ask once.
+ if (!(await row.evaluate((el) => el.classList.contains("viewed")))) {
+ await row.hover();
+ await row.locator(".file-sidebar-eye-btn").click();
+ }
+ return false;
+ },
+ { timeout: 60_000, intervals: [500, 1_000, 2_000] },
+ )
+ .toBe(true);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ if (zoomPercent != null) await setViewerZoom(page, zoomPercent);
+}
+
+/**
+ * Adds `file` to the workspace and shows it in the viewer, without waiting for
+ * the editor to open it: for files it refuses, or that ask for a password.
+ */
+export async function showInTextEditor(
+ page: Page,
+ file: Upload,
+): Promise<void> {
+ if (
+ !new URL(page.url(), "http://x").pathname.startsWith("/pdf-text-editor")
+ ) {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ }
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ const row = await addToFileList(page, file);
+ if (!(await row.evaluate((el) => el.classList.contains("viewed")))) {
+ await row.hover();
+ await row.locator(".file-sidebar-eye-btn").click();
+ }
+}
+
+/** Shows an uploaded file in the viewer by its sidebar row's eye button. */
+export async function viewInTextEditor(
+ page: Page,
+ name: string,
+): Promise<void> {
+ const row = fileRows(page, name).first();
+ await expect(row).toBeVisible({ timeout: 30_000 });
+ if (!(await row.evaluate((el) => el.classList.contains("viewed")))) {
+ await row.hover();
+ await row.locator(".file-sidebar-eye-btn").click();
+ }
+}
+
+/**
+ * Scrolls page `pageIndex` to the middle of the viewer. The viewer mounts only
+ * the pages near the viewport, so a far page is reached by scrolling toward it
+ * until it mounts.
+ */
+export async function scrollToEditorPage(
+ page: Page,
+ pageIndex: number,
+): Promise<void> {
+ await page.evaluate(async (target) => {
+ const indexOf = (el: HTMLElement) =>
+ /^pdf-editor-page-(\d+)$/.exec(el.dataset.testid ?? "");
+ for (let step = 0; step < 200; step++) {
+ const el = document.querySelector<HTMLElement>(
+ `[data-testid="pdf-editor-page-${target}"]`,
+ );
+ if (el) {
+ el.scrollIntoView({ block: "center" });
+ return;
+ }
+ const mounted = Array.from(
+ document.querySelectorAll<HTMLElement>(
+ "[data-testid^='pdf-editor-page-']",
+ ),
+ ).filter((e) => indexOf(e) != null);
+ if (mounted.length === 0) throw new Error("no editor page is mounted");
+ let scroller = mounted[0].parentElement;
+ while (
+ scroller &&
+ !/(auto|scroll)/.test(getComputedStyle(scroller).overflowY)
+ ) {
+ scroller = scroller.parentElement;
+ }
+ if (!scroller) throw new Error("viewer scroll container not found");
+ const highest = Math.max(...mounted.map((e) => Number(indexOf(e)![1])));
+ scroller.scrollTop += (highest < target ? 1 : -1) * scroller.clientHeight;
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ throw new Error(`page ${target} never mounted`);
+ }, pageIndex);
+}
+
+/** No-op where the slider is not shown: on a phone, or in a narrow viewer bar. */
+export async function setViewerZoom(
+ page: Page,
+ percent: number,
+): Promise<void> {
+ const thumb = page
+ .locator(".pdf-viewer-toolbar-zoom-slider [role=slider]")
+ .first();
+ if (!(await thumb.isVisible())) return;
+ const current = () =>
+ thumb.getAttribute("aria-valuenow").then((v) => Number(v));
+ // Every step the slider passes through re-renders the pages, so jump close
+ // with one click on the track and finish with the arrow keys. The viewer
+ // may still fit a newly opened document to its width just after, so the
+ // zoom is set again until it holds.
+ await expect(async () => {
+ if ((await current()) !== percent) {
+ const track = page
+ .locator(".pdf-viewer-toolbar-zoom-slider .mantine-Slider-track")
+ .first();
+ const box = await track.boundingBox();
+ if (box) {
+ const fraction = (percent - SLIDER_MIN) / (SLIDER_MAX - SLIDER_MIN);
+ await page.mouse.click(
+ box.x + fraction * box.width,
+ box.y + box.height / 2,
+ );
+ }
+ await thumb.focus();
+ for (let i = 0; i < 20; i++) {
+ const value = await current();
+ if (value === percent) break;
+ await page.keyboard.press(value < percent ? "ArrowRight" : "ArrowLeft");
+ }
+ }
+ await page.waitForTimeout(800);
+ expect(await current()).toBe(percent);
+ }).toPass({ timeout: 30_000 });
+ // Zoom keeps the scroll position; start from the top, as a fresh open does.
+ await page
+ .getByTestId("pdf-editor-page-0")
+ .evaluate((el) => el.scrollIntoView({ block: "start" }));
+ await page.waitForTimeout(400);
+}
diff --git a/frontend/src/editor/core/tests/live/pdf-owner-policy.spec.ts b/frontend/src/editor/core/tests/live/pdf-owner-policy.spec.ts
index 5befb49029..92bf3b5270 100644
--- a/frontend/src/editor/core/tests/live/pdf-owner-policy.spec.ts
+++ b/frontend/src/editor/core/tests/live/pdf-owner-policy.spec.ts
@@ -1,4 +1,5 @@
import { inspectPdfProtection as inspect } from "@editor/tests/helpers/pdf-protection";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import { test, expect } from "@editor/tests/helpers/test-base";
import {
liveApiHeaders,
@@ -269,7 +270,7 @@ test("text editing bypass retains encryption and the original credentials in the
);
const originalAccess = await inspect(page, original);
await page.goto("/pdf-text-editor");
- await page.getByTestId("pdf-editor-file-input").setInputFiles({
+ await openInTextEditor(page, {
name: "restricted.pdf",
mimeType: "application/pdf",
buffer: original,
diff --git a/frontend/src/editor/core/tests/live/pdf-text-editor-permissions.spec.ts b/frontend/src/editor/core/tests/live/pdf-text-editor-permissions.spec.ts
index 48514454aa..2c3f740bee 100644
--- a/frontend/src/editor/core/tests/live/pdf-text-editor-permissions.spec.ts
+++ b/frontend/src/editor/core/tests/live/pdf-text-editor-permissions.spec.ts
@@ -1,4 +1,5 @@
import { inspectPdfProtection as inspect } from "@editor/tests/helpers/pdf-protection";
+import { showInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import { test, expect } from "@editor/tests/helpers/test-base";
import { loadLiveAppConfig } from "@editor/tests/helpers/live-api";
import { skipOnboarding } from "@editor/tests/helpers/login";
@@ -44,7 +45,7 @@ for (const entry of ["workbench", "editor upload"] as const) {
await openTextEditor(page);
} else {
await page.goto("/pdf-text-editor");
- await page.getByTestId("pdf-editor-file-input").setInputFiles(restricted);
+ await showInTextEditor(page, restricted);
}
if (access.honorOwnerPasswords !== false) {
await expect(
@@ -206,9 +207,7 @@ test("permitted text edits preserve protection and a fresh reader follows the se
const readerPage = await readerContext.newPage();
await skipOnboarding(readerPage);
await readerPage.goto("/pdf-text-editor");
- await readerPage
- .getByTestId("pdf-editor-file-input")
- .setInputFiles(savedPath);
+ await showInTextEditor(readerPage, savedPath);
if (honorOwnerPasswords) {
await expect(
readerPage.getByText(deniedMessage, { exact: true }),
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-annotations.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-annotations.spec.ts
index 66f349ed5c..3f5f9d17c5 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-annotations.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-annotations.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// The canvas renders with FPDF_ANNOT but the editor model walks page objects
@@ -11,13 +12,7 @@ const ANNOT_PDF = path.join(
test.describe("PDF text editor - annotation-backed text is marked, not silently inert", () => {
test.beforeEach(async ({ page }) => {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(ANNOT_PDF);
+ await openInTextEditor(page, ANNOT_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-beforeinput.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-beforeinput.spec.ts
index 5ef4c4656c..432dee9878 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-beforeinput.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-beforeinput.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Rewriting the editing host inside a `beforeinput` handler makes WebKit
@@ -15,11 +16,10 @@ test.describe("PDF text editor - beforeinput must not mutate the DOM", () => {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures/cropbox-rotate90.pdf"),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/cropbox-rotate90.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-caret-drift.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-caret-drift.spec.ts
index afa4c22bb0..b3f252512f 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-caret-drift.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-caret-drift.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// A caret parked at the overlay CONTAINER's end (rather than inside the last
@@ -17,13 +18,7 @@ const SAMPLE_PDF = path.join(
);
async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts
index 32e6a54c7f..9b53c95122 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Transforming an object without its clip path leaves the clip behind, so
@@ -9,15 +10,10 @@ test.describe("PDF text editor - clip paths follow their object", () => {
test("a run move transforms the clip path by the same matrix, and undo reverses both", async ({
page,
}) => {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures/sample.pdf"),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/sample.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts
index a8787c3b5f..4638f3552c 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type {
@@ -26,13 +27,7 @@ async function clickImage(page: Page, testid: string): Promise<void> {
}
async function open(page: Page, firstPage = 0): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId(`pdf-editor-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts
index 42f00f0404..0b90acf1ec 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cropbox.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import {
DisplayTransform,
type DisplayTransformData,
@@ -28,11 +29,10 @@ async function load(
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, `../test-fixtures/${name}.pdf`),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, `../test-fixtures/${name}.pdf`),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -155,11 +155,10 @@ test("editing text on a Rotate-90 page applies cleanly and keeps placement in-bo
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures/cropbox-rotate90.pdf"),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/cropbox-rotate90.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -261,11 +260,10 @@ test("CropBox-offset: the rendered glyph pixels overlap the run overlay box", as
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures/cropbox-offset.pdf"),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/cropbox-offset.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts
index 3c8686c160..41b25ffa55 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-double-edit.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Editing a document twice is not the same as editing it once. The second edit
@@ -117,9 +118,7 @@ async function saveAndReopen(
};
w.__prev_document = w.__editor_store?.document;
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(saved);
+ await openInTextEditor(page, saved);
await page.waitForFunction(
() => {
const w = window as unknown as {
@@ -145,15 +144,10 @@ test.describe("PDF text editor - a second edit is as safe as the first", () => {
for (const c of CASES) {
test(c.name, async ({ page }) => {
test.setTimeout(240_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures", c.file),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures", c.file),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
index 82436db311..e23ed67f07 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -17,13 +18,7 @@ const SAMPLE = path.join(
);
async function open(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edit-mask.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edit-mask.spec.ts
index 093cbc9cf3..5f2cc9ebfc 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edit-mask.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edit-mask.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
test.describe("PDF text editor - editing surface", () => {
@@ -12,11 +13,10 @@ test.describe("PDF text editor - editing surface", () => {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, `../test-fixtures/${fixture}.pdf`),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, `../test-fixtures/${fixture}.pdf`),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-empty-run.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-empty-run.spec.ts
index 306bae3e4a..8d243a96af 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-empty-run.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-empty-run.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -9,13 +10,7 @@ const SAMPLE_PDF = path.join(
const SECRET = "SHOULDVANISH";
async function openEditor(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE_PDF);
+ await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -112,7 +107,7 @@ async function saveAndReopen(page: Page): Promise<void> {
const stream = await download.createReadStream();
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round.pdf",
mimeType: "application/pdf",
buffer: Buffer.concat(chunks),
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-and-drift.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-and-drift.spec.ts
index 3548a3872e..c272c727d2 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-and-drift.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-and-drift.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Two things the user sees go wrong while typing into a run, both because the
@@ -23,13 +24,7 @@ const MUSHROOM_PDF = path.join(
);
async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-font.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-font.spec.ts
index b1b4856e66..d03192d913 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-font.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-enter-font.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -36,13 +37,7 @@ interface SlotView {
}
async function open(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-entry-zoom.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-entry-zoom.spec.ts
deleted file mode 100644
index 7d9c038a88..0000000000
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-entry-zoom.spec.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import path from "path";
-import { test, expect } from "@editor/tests/helpers/stub-test-base";
-
-const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
-const MULTIPAGE_PDF = path.join(FIXTURES, "annotations_out_of_order.pdf");
-
-test("the text editor opens a workbench file at the viewer's zoom", async ({
- page,
-}) => {
- await page.goto("/editor");
- await page.locator('input[type="file"]').first().setInputFiles(MULTIPAGE_PDF);
- await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
- timeout: 30_000,
- });
- const readout = page.getByText(/%$/).first();
- const initialZoom = await readout.textContent();
- await page.getByRole("button", { name: "Zoom In" }).first().click();
- await expect(readout).not.toHaveText(initialZoom ?? "");
- const viewerZoom = await readout.textContent();
-
- await page
- .getByRole("link", { name: "PDF Text Editor", exact: true })
- .first()
- .click();
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 30_000,
- });
-
- await expect(page.getByTestId("pdf-editor-zoom-percent")).toHaveText(
- viewerZoom ?? "",
- );
-});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-exact-placement.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-exact-placement.spec.ts
index 7de959f1fa..5cb1ac1052 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-exact-placement.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-exact-placement.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -14,9 +15,7 @@ async function openSample(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 45_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 45_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-failed-switch.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-failed-switch.spec.ts
new file mode 100644
index 0000000000..d70c8a3aa5
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-failed-switch.spec.ts
@@ -0,0 +1,35 @@
+import path from "path";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ showInTextEditor,
+} from "@editor/tests/helpers/pdf-text-editor";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+const IMAGE = path.join(import.meta.dirname, "../test-fixtures/sample.png");
+
+test("a file the editor cannot open does not keep the previous document", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await openInTextEditor(page, SAMPLE_PDF);
+
+ await showInTextEditor(page, IMAGE);
+
+ // Saving now would write sample.pdf's pages over the image.
+ await expect
+ .poll(
+ () =>
+ page.evaluate(
+ () =>
+ (window as unknown as { __editor_store?: { document: unknown } })
+ .__editor_store?.document ?? null,
+ ),
+ { timeout: 30_000 },
+ )
+ .toBeNull();
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts
index 090ec52bb2..9c3fa99f37 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -8,13 +9,7 @@ const SAMPLE_PDF = path.join(
);
async function openFind(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE_PDF);
+ await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-colour-picker.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-colour-picker.spec.ts
index 754d6ec97c..1ad46d3e1c 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-colour-picker.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-colour-picker.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// The fill colour picker (ColorInput, testid pdf-editor-colour) had three faults that
@@ -73,9 +74,7 @@ async function openEditor(page: import("@playwright/test").Page, file: string) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-empty-state.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-empty-state.spec.ts
index 72e7d027d1..491736d09e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-empty-state.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-empty-state.spec.ts
@@ -50,7 +50,7 @@ async function loadContext(page: Page) {
hasDocument: s?.state.hasDocument ?? null,
loading: s?.state.loading ?? null,
error: s?.state.error ?? null,
- stage: !!document.querySelector('[data-testid="pdf-editor-stage"]'),
+ viewerPages: !!document.querySelector("[data-viewer-pages]"),
pages: document.querySelectorAll('[data-testid^="pdf-editor-page-"]')
.length,
fileItems: document.querySelectorAll(".file-sidebar-file-item").length,
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts
index ae3292e906..4586b54789 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -38,13 +39,7 @@ interface Rect {
}
async function openSample(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -104,17 +99,17 @@ async function pageBox(page: Page): Promise<Rect> {
}
/**
- * Two points in the bare gutter LEFT of the page but still inside `pdf-editor-pages`
- * (the stage's clear-on-press target, and the only region the marquee arms in).
- * Outside `pdf-editor-pages` neither handler runs and any assertion would pass blind.
+ * Two points in the bare gutter LEFT of the page but still inside the viewer's
+ * page area (the only region the marquee arms in). Outside it neither the
+ * marquee nor a clear-on-press runs, and any assertion would pass blind.
*/
async function gutter(page: Page): Promise<{
from: { x: number; y: number };
to: { x: number; y: number };
}> {
- const pages = await page.getByTestId("pdf-editor-pages").boundingBox();
+ const pages = await page.locator("[data-viewer-pages]").boundingBox();
const p0 = await pageBox(page);
- if (!pages) throw new Error("pdf-editor-pages has no bounding box");
+ if (!pages) throw new Error("the viewer's page area has no bounding box");
const slack = p0.x - pages.x;
expect(slack, "fixture needs bare stage left of the page").toBeGreaterThan(
60,
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts
index 2a3c951ed3..603d8140ae 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-mixed-fontsize.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -25,9 +26,7 @@ async function open(page: Page, file: string): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-page-prefetch.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-page-prefetch.spec.ts
index 7a16e8b5c8..6205cb3580 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-page-prefetch.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-page-prefetch.spec.ts
@@ -1,4 +1,8 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ scrollToEditorPage,
+} from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
/**
@@ -7,11 +11,11 @@ import path from "path";
* PageView keeps a page's PDFium bitmap only while the page is "near" the
* viewport, and frees the canvas otherwise (a 4x-zoom A4 canvas is ~32MB).
* The observer that decides "near" uses rootMargin: 800px, but the pages live
- * inside a Mantine ScrollArea. IntersectionObserver clips the target against
+ * inside a scroll container. IntersectionObserver clips the target against
* every scrolling ancestor BEFORE root+rootMargin is applied, so with the
- * default (document) root a page one pixel outside the ScrollArea is already
- * non-intersecting and the margin can never bring it back - the prefetch was
- * dead code and pages popped in as blank placeholders on scroll.
+ * default (document) root a page one pixel outside the container is already
+ * non-intersecting and the margin can never bring it back - the prefetch is
+ * dead and pages pop in blank on scroll.
*
* These tests measure it from geometry + canvas backing stores only:
* - a page whose top edge is inside the 800px margin must be rendered
@@ -29,20 +33,24 @@ interface PageGeom {
index: number;
/** Canvas backing-store width; 0 means the bitmap was freed. */
canvasW: number;
- placeholder: boolean;
/** px from the scroll viewport's bottom edge down to the page's top edge. */
gapBelow: number;
/** px from the page's bottom edge up to the scroll viewport's top edge. */
gapAbove: number;
}
-/** Geometry + bitmap state of every mounted page, relative to the ScrollArea. */
+/** Geometry + bitmap state of every mounted page, relative to the viewer's scroll container. */
function scanPages(p: Page): Promise<{ vpH: number; pages: PageGeom[] }> {
return p.evaluate(() => {
- const vp = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"] .mantine-ScrollArea-viewport',
+ // Any mounted page leads to the viewer's scroll container.
+ const first = document.querySelector<HTMLElement>(
+ "[data-testid^='pdf-editor-page-']",
);
- if (!vp) throw new Error("ScrollArea viewport not found");
+ let vp: HTMLElement | null = first?.parentElement ?? null;
+ while (vp && !/(auto|scroll)/.test(getComputedStyle(vp).overflowY)) {
+ vp = vp.parentElement;
+ }
+ if (!vp) throw new Error("viewer scroll container not found");
const vr = vp.getBoundingClientRect();
const pages = Array.from(
document.querySelectorAll<HTMLElement>(
@@ -59,9 +67,6 @@ function scanPages(p: Page): Promise<{ vpH: number; pages: PageGeom[] }> {
return {
index: idx,
canvasW: c ? c.width : -1,
- placeholder: !!el.querySelector(
- `[data-testid="pdf-editor-page-${idx}-placeholder"]`,
- ),
gapBelow: Math.round(r.top - vr.bottom),
gapAbove: Math.round(vr.top - r.bottom),
};
@@ -74,22 +79,24 @@ function fmt(scan: { vpH: number; pages: PageGeom[] }) {
return scan.pages
.map(
(g) =>
- `page ${g.index}: canvas.width=${g.canvasW} placeholder=${g.placeholder} gapBelow=${g.gapBelow} gapAbove=${g.gapAbove}`,
+ `page ${g.index}: canvas.width=${g.canvasW} gapBelow=${g.gapBelow} gapAbove=${g.gapAbove}`,
)
.join("\n");
}
/** Scroll so page `idx`'s top edge sits exactly `gap` px below the fold. */
async function parkGapBelow(p: Page, idx: number, gap: number) {
+ await scrollToEditorPage(p, idx);
await p.evaluate(
({ i, g }) => {
- const vp = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"] .mantine-ScrollArea-viewport',
- );
const el = document.querySelector<HTMLElement>(
`[data-testid="pdf-editor-page-${i}"]`,
);
- if (!vp || !el) throw new Error("stage or page missing");
+ let vp: HTMLElement | null = el?.parentElement ?? null;
+ while (vp && !/(auto|scroll)/.test(getComputedStyle(vp).overflowY)) {
+ vp = vp.parentElement;
+ }
+ if (!vp || !el) throw new Error("scroll container or page missing");
const current =
el.getBoundingClientRect().top - vp.getBoundingClientRect().bottom;
vp.scrollTop += current - g;
@@ -103,7 +110,7 @@ async function openEditor(p: Page, file: string) {
await expect(p.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await p.locator('[data-testid="pdf-editor-file-input"]').setInputFiles(file);
+ await openInTextEditor(p, file);
await expect(p.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -136,7 +143,7 @@ const INSIDE = 700;
const OUTSIDE = 1000;
test.describe("near-viewport prefetch", () => {
- test("a page inside the 800px prefetch margin is rendered, not a placeholder", async ({
+ test("a page inside the 800px prefetch margin is rendered", async ({
page,
}) => {
await openEditor(page, MANY_PAGES_PDF);
@@ -156,10 +163,6 @@ test.describe("near-viewport prefetch", () => {
g.canvasW,
`page ${g.index} sits ${g.gapBelow}px below the fold (inside the ${MARGIN}px prefetch margin) so its bitmap must already be rendered\n${fmt(scan)}`,
).toBeGreaterThan(0);
- expect(
- g.placeholder,
- `page ${g.index} sits ${g.gapBelow}px below the fold and must not show the placeholder\n${fmt(scan)}`,
- ).toBe(false);
}
});
@@ -210,18 +213,13 @@ test.describe("near-viewport prefetch", () => {
near.canvasW,
`page 3 parked ${near.gapBelow}px below the fold is inside the ${MARGIN}px margin and must be rendered ahead of the scroll\n${fmt(inside)}`,
).toBeGreaterThan(0);
- expect(near.placeholder).toBe(false);
});
test("prefetch also covers pages just above the viewport", async ({
page,
}) => {
await openEditor(page, MANY_PAGES_PDF);
- await page.evaluate(() => {
- document
- .querySelector<HTMLElement>('[data-testid="pdf-editor-page-4"]')
- ?.scrollIntoView({ block: "center" });
- });
+ await scrollToEditorPage(page, 4);
const scan = await settledScan(page);
console.log(`[page 4 centred] viewport height ${scan.vpH}\n${fmt(scan)}`);
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-pristine-save.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-pristine-save.spec.ts
index 534a7f2a87..f0eb30a76e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-pristine-save.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-pristine-save.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import { createHash } from "crypto";
import { readFileSync } from "fs";
@@ -30,9 +31,7 @@ async function open(page: Page, file: string): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-rotated-overlay.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-rotated-overlay.spec.ts
index 9e0ff95080..b1222b7856 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-rotated-overlay.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-rotated-overlay.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -16,13 +17,7 @@ const ROTATED = path.join(
);
async function open(page: Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-duplicate-glyphs.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-duplicate-glyphs.spec.ts
index d8d4752666..a581780a30 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-duplicate-glyphs.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-duplicate-glyphs.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -77,9 +78,7 @@ async function open(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH);
+ await openInTextEditor(page, PARAGRAPH);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-ink.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-ink.spec.ts
index 47e5372ec7..41b771cbae 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-ink.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-undo-ink.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -29,9 +30,7 @@ async function open(page: Page) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FIX);
+ await openInTextEditor(page, FIX);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts
index 6805e99ece..f1e582ebda 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-focus-after-edit.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -25,9 +26,7 @@ async function open(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 15_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-capability.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-capability.spec.ts
index cdf6557bdb..1577291bb7 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-capability.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-capability.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// The italic button answered for every font, including ones we cannot make
@@ -22,9 +23,7 @@ async function openEditor(page: import("@playwright/test").Page, file: string) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts
index c4612ddff2..5548a285fa 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -14,9 +15,7 @@ async function open(page: Page, file: string): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 20_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts
index 1ae71ea502..b0c7e4b741 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Selecting text set in an embedded or subset face left the font picker showing
@@ -19,9 +20,7 @@ async function openEditor(page: import("@playwright/test").Page, file: string) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-hidpi.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-hidpi.spec.ts
index 7d062594ff..6228fc9741 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-hidpi.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-hidpi.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -12,14 +13,11 @@ const SAMPLE = path.join(
"../../../../../public/samples/Sample.pdf",
);
+/** The viewer zoom the page is opened at. */
+const ZOOM = 1.5;
+
async function open(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE, { zoomPercent: ZOOM * 100 });
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -32,7 +30,6 @@ interface CanvasGeom {
cssW: number;
cssH: number;
pageWidthPt: number;
- renderScale: number;
dpr: number;
}
@@ -45,7 +42,6 @@ function canvasGeom(page: Page): Promise<CanvasGeom> {
window as unknown as {
__editor_store: {
getState(): {
- renderScale: number;
pages: { width: number }[];
};
};
@@ -58,7 +54,6 @@ function canvasGeom(page: Page): Promise<CanvasGeom> {
cssW: cb.width,
cssH: cb.height,
pageWidthPt: st.pages[0].width,
- renderScale: st.renderScale,
dpr: window.devicePixelRatio || 1,
};
});
@@ -75,11 +70,9 @@ test.describe("PDF text editor - HiDPI rendering", () => {
const g = await canvasGeom(page);
expect(g.dpr).toBe(2);
// Layout stays at the zoom scale...
- expect(g.cssW).toBeCloseTo(g.pageWidthPt * g.renderScale, 0);
+ expect(g.cssW).toBeCloseTo(g.pageWidthPt * ZOOM, 0);
// ...while the bitmap renders at zoom x ratio - the whole fix.
- expect(g.bitmapW).toBe(
- Math.max(1, Math.round(g.pageWidthPt * g.renderScale * 2)),
- );
+ expect(g.bitmapW).toBe(Math.max(1, Math.round(g.pageWidthPt * ZOOM * 2)));
expect(g.bitmapW / g.cssW).toBeCloseTo(2, 1);
});
});
@@ -91,9 +84,7 @@ test.describe("PDF text editor - HiDPI rendering", () => {
await open(page);
const g = await canvasGeom(page);
expect(g.dpr).toBe(1);
- expect(g.bitmapW).toBe(
- Math.max(1, Math.round(g.pageWidthPt * g.renderScale)),
- );
+ expect(g.bitmapW).toBe(Math.max(1, Math.round(g.pageWidthPt * ZOOM)));
expect(g.bitmapW / g.cssW).toBeCloseTo(1, 1);
});
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts
index 7118b0c78f..926b650910 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -20,13 +21,7 @@ test("inserting a JPEG embeds it as DCTDecode, not re-encoded RGBA", async ({
page: Page;
}) => {
test.setTimeout(90_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 20_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE_PDF);
+ await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
index 4ee975ef23..6de68a48a5 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
@@ -1,4 +1,8 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ showInTextEditor,
+} from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -24,9 +28,7 @@ async function open(page: Page, file: string, firstPage = 0): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 15_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId(`pdf-editor-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
@@ -273,7 +275,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
// it is dropped and the save-risk modal always gates the save.
const saved = await downloadBytes(await saveAndDownload(page, true));
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "emoji-round-trip.pdf",
mimeType: "application/pdf",
buffer: saved,
@@ -498,11 +500,8 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
page,
}) => {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
await page
- .locator('[data-testid="pdf-editor-file-input"]')
+ .getByTestId("file-input")
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/encrypted.pdf"),
);
@@ -510,7 +509,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
page
.getByTestId("pdf-editor-page-0")
.or(page.getByTestId("pdf-editor-error"))
- .or(page.getByTestId("pdf-editor-password-modal"))
+ .or(page.getByLabel("Password to open", { exact: true }))
.first(),
"an encrypted PDF must either open or tell the user why it can't",
).toBeAttached();
@@ -519,15 +518,10 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
// ISSUE: opening a CORRUPTED PDF fails silently - same "No document loaded"
// with no error feedback.
test("opening a corrupted PDF surfaces an error", async ({ page }) => {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures/corrupted.pdf"),
- );
+ await showInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/corrupted.pdf"),
+ );
await expect(
page
.getByTestId("pdf-editor-page-0")
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.ts
index b8452dd6e2..08b8cdba14 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-language.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -33,13 +34,7 @@ const RUN = (needle: string) =>
) ?? null;
async function openFixture(page: Page) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FIXTURE);
+ await openInTextEditor(page, FIXTURE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -59,9 +54,7 @@ async function saveAndReopen(page: Page) {
const w = window as unknown as EditorWindow;
w.__prev_document = w.__editor_store.document;
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(saved);
+ await openInTextEditor(page, saved);
await page.waitForFunction(
() => {
const w = window as unknown as EditorWindow;
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts
index c411de31bb..6ec4a6439e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -20,13 +21,7 @@ test("editing a letter-spaced heading keeps its tracking through save+reopen", a
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 20_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FIXTURE);
+ await openInTextEditor(page, FIXTURE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -92,7 +87,7 @@ test("editing a letter-spaced heading keeps its tracking through save+reopen", a
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: Buffer.concat(chunks),
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts
index 1d484cb90e..547e3fba97 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -21,9 +22,7 @@ async function open(page: Page, firstPage = 0): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 15_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId(`pdf-editor-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
@@ -202,22 +201,11 @@ test.describe("PDF text editor - inspector layout", () => {
}
});
- test("zoom floats on the canvas and save is pinned to the panel", async ({
- page,
- }) => {
+ test("save is pinned to the panel", async ({ page }) => {
await open(page, 0);
const footer = page.getByTestId("pdf-editor-panel-actions");
await expect(footer.getByTestId("pdf-editor-save")).toBeVisible();
await expect(footer.getByTestId("pdf-editor-download")).toBeVisible();
- // Zoom sits over the pages it scales, not in the far rail.
- const zoom = page.getByTestId("pdf-editor-zoom-controls");
- await expect(zoom).toBeVisible();
- await expect(zoom.getByTestId("pdf-editor-zoom-percent")).toBeVisible();
- await expect(
- page
- .getByTestId("pdf-editor-stage")
- .getByTestId("pdf-editor-zoom-controls"),
- ).toHaveCount(0);
});
test("everyday settings are plain; only parse options are behind Advanced", async ({
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts
index 43abc01636..75712d9f70 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts
@@ -1,40 +1,97 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Locator, Page } from "@playwright/test";
import fs from "fs";
+import { PDFDocument } from "@cantoo/pdf-lib";
import path from "path";
const SAMPLE_PDF = path.join(
import.meta.dirname,
"../test-fixtures/sample.pdf",
);
+const SIGNED_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/signed-sample.pdf",
+);
+const MANY_PAGES_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/many-pages-sample.pdf",
+);
test.use({
viewport: { width: 390, height: 844 },
hasTouch: true,
});
-async function openEditor(page: Page, fileName?: string): Promise<void> {
+async function addFile(
+ page: Page,
+ file: Parameters<Locator["setInputFiles"]>[0],
+): Promise<void> {
+ await expect(page.getByTestId("pdf-editor-root")).toBeAttached({
+ timeout: 30_000,
+ });
+ await page
+ .locator('input[type="file"]:not([data-testid="pdf-editor-image-input"])')
+ .first()
+ .setInputFiles(file);
+}
+
+async function openEditor(
+ page: Page,
+ fileName?: string,
+ file: string = SAMPLE_PDF,
+): Promise<void> {
await page.addInitScript(() => {
localStorage.setItem("stirling.mobileSwipeHintSeen", "true");
});
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeAttached({
- timeout: 30_000,
- });
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles(
+ await addFile(
+ page,
fileName
? {
name: fileName,
mimeType: "application/pdf",
- buffer: fs.readFileSync(SAMPLE_PDF),
+ buffer: fs.readFileSync(file),
}
- : SAMPLE_PDF,
+ : file,
);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
}
+/** Waits until `target`'s box holds still between samples. */
+async function settledBox(target: Locator): Promise<void> {
+ let last = "";
+ await expect
+ .poll(
+ async () => {
+ const box = JSON.stringify(await target.boundingBox());
+ const still = box === last;
+ last = box;
+ return still;
+ },
+ { intervals: [150] },
+ )
+ .toBe(true);
+}
+
+/**
+ * Whether page 0 is fitted to the viewer's width: centred, with nothing but the
+ * viewer's own gutter either side.
+ */
+async function fillsWidth(page: Page): Promise<boolean> {
+ const pages = await page.locator("[data-viewer-pages]").boundingBox();
+ const box = await page.getByTestId("pdf-editor-page-0").boundingBox();
+ if (!pages || !box) return false;
+ const left = box.x - pages.x;
+ const right = pages.x + pages.width - (box.x + box.width);
+ const gutter = 4 * 16;
+ return (
+ left >= 0 && right >= 0 && Math.abs(left - right) <= 2 && left <= gutter
+ );
+}
+
// Close the open sheet once it has finished sliding in, then wait for it to go.
async function closeSheet(page: Page, content: Locator): Promise<void> {
const sheet = page
@@ -51,7 +108,7 @@ async function closeSheet(page: Page, content: Locator): Promise<void> {
}
test.describe("PDF text editor - phone layout", () => {
- test("opens on the canvas, fitted to width, with one header", async ({
+ test("edits in the viewer, fitted to width, with the phone controls", async ({
page,
}) => {
test.setTimeout(120_000);
@@ -66,20 +123,14 @@ test.describe("PDF text editor - phone layout", () => {
"mobile",
);
await expect(page.getByTestId("pdf-editor-mobile-save")).toBeVisible();
-
- // Read both boxes per poll: the phone slider is still scrolling into view.
- await expect
- .poll(async () => {
- const stage = await page.getByTestId("pdf-editor-stage").boundingBox();
- const box = await page.getByTestId("pdf-editor-page-0").boundingBox();
- return (
- !!box &&
- !!stage &&
- box.x >= stage.x &&
- box.x + box.width <= stage.x + stage.width
- );
- })
- .toBe(true);
+ // The editing actions stand in for the viewer's page bar and tool row.
+ await expect(page.getByTestId("pdf-editor-mobile-actionbar")).toBeVisible();
+ await expect(page.locator(".pdf-viewer-toolbar-dock")).toHaveCount(0);
+ await expect(page.locator(".workbench-bar-center")).toHaveCount(0);
+ await expect(
+ page.getByRole("button", { name: /notifications/i }),
+ ).toHaveCount(1);
+ await expect.poll(() => fillsWidth(page)).toBe(true);
});
test("rotating the phone refits the page to the new width", async ({
@@ -89,16 +140,15 @@ test.describe("PDF text editor - phone layout", () => {
await openEditor(page);
const pageWidth = async () =>
(await page.getByTestId("pdf-editor-page-0").boundingBox())?.width ?? 0;
- await expect.poll(pageWidth).toBeGreaterThan(300);
+ await expect.poll(() => fillsWidth(page)).toBe(true);
const portrait = await pageWidth();
await page.setViewportSize({ width: 740, height: 390 });
await expect
- .poll(async () => {
- const stage = await page.getByTestId("pdf-editor-stage").boundingBox();
- const width = await pageWidth();
- return !!stage && width > portrait + 200 && width <= stage.width;
- })
+ .poll(
+ async () =>
+ (await fillsWidth(page)) && (await pageWidth()) > portrait + 200,
+ )
.toBe(true);
});
@@ -122,6 +172,16 @@ test.describe("PDF text editor - phone layout", () => {
expect(bar && save && save.x + save.width <= bar.x + bar.width + 1).toBe(
true,
);
+ // Squeezed rather than pushed off, Save would clip its own label.
+ expect(
+ await page
+ .getByTestId("pdf-editor-mobile-save")
+ .evaluate((el) =>
+ Array.from(el.querySelectorAll<HTMLElement>("*")).every(
+ (child) => child.scrollWidth <= child.clientWidth + 1,
+ ),
+ ),
+ ).toBe(true);
});
test("the action bar follows the selection and opens the sheets", async ({
@@ -163,4 +223,214 @@ test.describe("PDF text editor - phone layout", () => {
expect(box?.height ?? 0).toBeGreaterThanOrEqual(44);
}
});
+
+ test("the action bar zooms the viewer", async ({ page }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await expect.poll(() => fillsWidth(page)).toBe(true);
+ const width = async () =>
+ (await page.getByTestId("pdf-editor-page-0").boundingBox())?.width ?? 0;
+ const fitted = await width();
+
+ await page.getByTestId("pdf-editor-mobile-zoom").tap();
+ await page.getByRole("menuitem", { name: "Zoom in" }).tap();
+ await expect.poll(width).toBeGreaterThan(fitted * 1.05);
+
+ await page.getByRole("menuitem", { name: "Fit to width" }).tap();
+ await expect.poll(width).toBeLessThan(fitted * 1.02);
+ });
+
+ test("leaving with unsaved edits asks once, and discarding leaves", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await page.evaluate(() => {
+ const el = document.querySelector<HTMLElement>(
+ '[data-testid^="pdf-editor-run-"]',
+ );
+ if (!el) throw new Error("no run overlay in the DOM");
+ el.focus();
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ range.collapse(false);
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ document.execCommand("insertText", false, "PHONE");
+ });
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+
+ await page.getByRole("tab", { name: "Tools" }).tap();
+ await page.getByRole("button", { name: "Back to all tools" }).tap();
+ await expect(page.getByTestId("unsaved-discard")).toBeVisible();
+ await page.getByTestId("unsaved-discard").tap();
+
+ await expect(page).toHaveURL(/\/editor$|\/$/);
+ await expect(page.getByTestId("unsaved-discard")).toHaveCount(0);
+ await expect(page.getByTestId("pdf-editor-discard-modal")).toHaveCount(0);
+ });
+
+ test("find scrolls to a match on a page not yet mounted", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page, undefined, MANY_PAGES_PDF);
+ await expect(page.locator('[data-page-index="7"]')).toHaveCount(0);
+
+ await page.getByTestId("pdf-editor-open-find").tap();
+ // The bar's arrival shortens the page area, and the viewer's refit for
+ // that re-anchors the scroll; a person types once it has settled.
+ await settledBox(page.getByTestId("pdf-editor-page-0"));
+ await page.getByTestId("pdf-editor-find-input").fill("Page 8 line 2");
+ await expect(page.getByTestId("pdf-editor-find-count")).toContainText(
+ /1 of 1/,
+ );
+ await page.getByTestId("pdf-editor-find-input").press("Enter");
+ await expect(page.getByTestId("pdf-editor-page-7")).toBeInViewport({
+ timeout: 15_000,
+ });
+ });
+
+ test("a file the editor refuses leaves the viewer its page bar", async ({
+ page,
+ }, testInfo) => {
+ test.setTimeout(120_000);
+ // An unlocked signed PDF is viewable but kept out of the editor.
+ const pdf = await PDFDocument.load(fs.readFileSync(SIGNED_PDF));
+ pdf.encrypt({ userPassword: "pw", ownerPassword: "pw" });
+ const signedProtected = testInfo.outputPath("signed-protected.pdf");
+ fs.writeFileSync(signedProtected, await pdf.save());
+
+ await page.addInitScript(() => {
+ localStorage.setItem("stirling.mobileSwipeHintSeen", "true");
+ });
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await addFile(page, signedProtected);
+ await page.getByLabel("Password to open", { exact: true }).fill("pw");
+ await page.getByRole("button", { name: "Open PDF", exact: true }).click();
+ await page.getByRole("tab", { name: "Workspace" }).tap();
+
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 60_000,
+ });
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+ await expect(page.getByTestId("pdf-editor-mobile-actionbar")).toHaveCount(
+ 0,
+ );
+ await expect(page.locator(".pdf-viewer-toolbar-dock")).toBeVisible();
+ });
+
+ test("closing the editor gives the viewer its own controls back", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await expect(page.locator(".pdf-viewer-toolbar-dock")).toHaveCount(0);
+
+ await page.getByRole("tab", { name: "Tools" }).tap();
+ await page.getByRole("button", { name: "Back to all tools" }).tap();
+ await page.getByRole("tab", { name: "Workspace" }).tap();
+
+ await expect(page.getByTestId("pdf-editor-mobile-actionbar")).toHaveCount(
+ 0,
+ );
+ await expect(page.locator(".pdf-viewer-toolbar-dock")).toBeVisible();
+ await expect(page.locator(".workbench-bar-center")).toBeVisible();
+ });
+});
+
+test.describe("PDF text editor - phone entry", () => {
+ test.use({ viewport: { width: 390, height: 844 }, hasTouch: true });
+ test("opening the editor on a file already in the viewer keeps its zoom", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await page.getByRole("tab", { name: "Tools" }).tap();
+ await page.getByRole("button", { name: "Back to all tools" }).tap();
+ await page.getByRole("tab", { name: "Workspace" }).tap();
+ await expect(page.locator(".pdf-viewer-toolbar-dock")).toBeVisible();
+ const viewerPage = page.locator('[data-page-index="0"]').first();
+ // A zoom chosen in the viewer carries into editing.
+ await page
+ .locator(".pdf-viewer-toolbar-dock")
+ .getByRole("button", { name: "More" })
+ .tap();
+ const fitted = (await viewerPage.boundingBox())?.width ?? 0;
+ await page.getByRole("menuitem", { name: /Zoom In/i }).tap();
+ await page.keyboard.press("Escape");
+ await expect
+ .poll(async () => (await viewerPage.boundingBox())?.width ?? 0)
+ .toBeGreaterThan(fitted);
+ await settledBox(viewerPage);
+ const zoomed = (await viewerPage.boundingBox())?.width ?? 0;
+
+ await page.getByTestId("viewer-edit-text").first().tap();
+ const editing = page.getByTestId("pdf-editor-page-0");
+ await expect(editing).toBeVisible({ timeout: 60_000 });
+ await expect
+ .poll(async () =>
+ Math.abs(((await editing.boundingBox())?.width ?? 0) - zoomed),
+ )
+ .toBeLessThanOrEqual(2);
+ });
+});
+
+test.describe("PDF text editor - tablet layout", () => {
+ test.use({ viewport: { width: 900, height: 1200 } });
+
+ test("edits in the viewer with the touch controls", async ({ page }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await expect(page.getByTestId("pdf-editor-toolbar")).toHaveAttribute(
+ "data-layout",
+ "mobile",
+ );
+ await expect(page.getByTestId("pdf-editor-mobile-actionbar")).toBeVisible();
+ await expect(page.locator("[data-viewer-pages]")).toBeVisible();
+ });
+});
+
+test.describe("PDF text editor - resizing", () => {
+ test.use({ viewport: { width: 1280, height: 900 } });
+
+ test("crossing the touch layout keeps the open document and its edits", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await page.addInitScript(() => {
+ localStorage.setItem("stirling.mobileSwipeHintSeen", "true");
+ });
+ await page.goto("/pdf-text-editor");
+ await openInTextEditor(page, SAMPLE_PDF);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ await page.evaluate(() => {
+ const el = document.querySelector<HTMLElement>(
+ '[data-testid^="pdf-editor-run-p0-"]',
+ );
+ if (!el) throw new Error("no run overlay in the DOM");
+ el.focus();
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ range.collapse(false);
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ document.execCommand("insertText", false, "KEPT");
+ });
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+
+ for (const width of [900, 1280]) {
+ await page.setViewportSize({ width, height: 900 });
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+ // The panel remounts in the other layout; it must not take its own
+ // file for a new one and offer to discard the edits.
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(
+ page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
+ ).toContainText("KEPT");
+ }
+ });
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts
index 1e20bb1613..b30e5c172b 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-model-sync.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// `PdfiumTextReader.populate` mints fresh runs with fresh ids, so re-reading a
@@ -23,13 +24,7 @@ interface SyncResult {
}
async function open(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts
index 654f33f7ac..08e164fd23 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Every toolbar action walks the selection and dispatches one command PER RUN.
@@ -24,13 +25,7 @@ const MANY_PAGES_PDF = path.join(
);
async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts
index ecebe04d63..2384af9078 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -22,9 +23,7 @@ test("mid-line paragraph edit does not scramble unchanged words (non-subset font
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MUSHROOM);
+ await openInTextEditor(page, MUSHROOM);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts
index 5dd64c9c0f..2753f60dcf 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Regression for the mushroom-life.pdf whitespace reports.
@@ -26,9 +27,7 @@ test("mushroom first-line edits never reuse whitespace (no „) and keep the par
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MUSHROOM);
+ await openInTextEditor(page, MUSHROOM);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-newline-register.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-newline-register.spec.ts
index a1250317c0..f39f115449 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-newline-register.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-newline-register.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -33,9 +34,7 @@ async function open(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts
index 775fb9dd1a..9770118a8b 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-paragraphs.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -12,13 +13,7 @@ const SAMPLE = path.join(
/** Comprehensive paragraph-editing battery for the PDF text editor. */
async function gotoWrap(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 30_000,
});
@@ -29,13 +24,7 @@ async function gotoWrap(page: Page): Promise<void> {
/** Load page 2 but leave the default "grow" width mode (no wrap toggle). */
async function gotoGrow(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 30_000,
});
@@ -467,13 +456,7 @@ test.describe("PDF text editor - paragraph editing battery", () => {
test("grow mode: typing a long tail grows right (one line, no wrap)", async ({
page,
}) => {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts
index 93ee45b78f..064e8e61c4 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-pattern-fill.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Regeneration drops `sh` shadings, which the save-time repair puts back. It
@@ -9,14 +10,10 @@ test("a pattern colour space fill survives regeneration", async ({ page }) => {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../test-fixtures/pattern-fill-sample.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/pattern-fill-sample.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
index 4dd82b0f4f..4272a85240 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts
@@ -1,4 +1,8 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ viewInTextEditor,
+} from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import { readFile, writeFile } from "node:fs/promises";
@@ -26,9 +30,7 @@ async function gotoEditor(page: Page): Promise<void> {
}
async function upload(page: Page, file: string): Promise<void> {
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
}
test.describe("PDF text editor - encrypted PDF password prompt", () => {
@@ -130,33 +132,31 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {
test.setTimeout(90_000);
await gotoEditor(page);
- await upload(page, ENCRYPTED);
+ await page.getByTestId("file-input").setInputFiles(ENCRYPTED);
- const submit = page.getByTestId("pdf-editor-password-submit");
- await expect(submit).toBeVisible({ timeout: 20_000 });
- const input = page
- .getByTestId("pdf-editor-password-modal")
- .locator("input")
- .first();
+ const dialog = page.getByRole("dialog", { name: /^Open PDF/ });
+ const input = dialog.getByLabel("Password to open", { exact: true });
+ const submit = dialog.getByRole("button", {
+ name: "Open PDF",
+ exact: true,
+ });
+ await expect(input).toBeVisible({ timeout: 20_000 });
// Wrong password -> prompt stays, shows the retry error.
await input.fill("definitely-wrong");
await submit.click();
- await expect(page.getByText("Incorrect password - try again.")).toBeVisible(
- { timeout: 20_000 },
- );
- await expect(submit).toBeVisible();
+ await expect(dialog.getByText("Incorrect password")).toBeVisible({
+ timeout: 20_000,
+ });
- // Correct password -> prompt closes and the page renders.
+ // Correct password -> prompt closes and the editor opens the document.
await input.fill(ENCRYPTED_PASSWORD);
await submit.click();
- await expect(submit).toBeHidden({ timeout: 20_000 });
+ await expect(dialog).toBeHidden({ timeout: 20_000 });
+ await viewInTextEditor(page, "encrypted.pdf");
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
- await expect(
- page.getByRole("button", { name: /^encrypted\.pdf/ }),
- ).toBeVisible();
await expect(page.getByRole("dialog")).toHaveCount(0);
});
@@ -165,9 +165,9 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {
}) => {
test.setTimeout(60_000);
await gotoEditor(page);
- await upload(page, ENCRYPTED);
+ await page.getByTestId("file-input").setInputFiles(ENCRYPTED);
- const dialog = page.getByRole("dialog");
+ const dialog = page.getByRole("dialog", { name: /^Open PDF/ });
await expect(dialog).toBeVisible({ timeout: 20_000 });
await dialog.getByRole("button", { name: "Close", exact: true }).click();
await expect(dialog).toBeHidden();
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
index 7efe6ffa07..af3107ce3a 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-ocr.spec.ts
@@ -8,58 +8,45 @@ const SCAN = path.join(
"../test-fixtures/scanned-no-ocr-encrypted.pdf",
);
-for (const source of ["workbench", "disk"] as const) {
- test(`unlocked ${source} scan explains that OCR cannot preserve protection`, async ({
- page,
- }) => {
- const ocrRequests: string[] = [];
- page.on("request", (request) => {
- if (request.url().includes("/api/v1/misc/ocr-pdf"))
- ocrRequests.push(request.url());
- });
+test("an unlocked scan explains that OCR cannot preserve protection", async ({
+ page,
+}) => {
+ const ocrRequests: string[] = [];
+ page.on("request", (request) => {
+ if (request.url().includes("/api/v1/misc/ocr-pdf"))
+ ocrRequests.push(request.url());
+ });
- if (source === "workbench") {
- await page.goto("/editor");
- await page.getByTestId("file-input").setInputFiles(SCAN);
- await page
- .getByLabel("Password to open", { exact: true })
- .fill("scan-password");
- await page.getByRole("button", { name: "Open PDF", exact: true }).click();
- await expect(page.getByRole("dialog")).toHaveCount(0);
- await page
- .getByRole("link", { name: "PDF Text Editor", exact: true })
- .first()
- .click();
- } else {
- await page.goto("/pdf-text-editor");
- await page.getByTestId("pdf-editor-file-input").setInputFiles(SCAN);
- await page
- .getByTestId("pdf-editor-password-modal")
- .locator("input")
- .first()
- .fill("scan-password");
- await page.getByTestId("pdf-editor-password-submit").click();
- }
- await waitForEditorReady(page);
- const hint = page.getByTestId("pdf-editor-scan-hint");
- const ocr = hint.getByRole("button", { name: "Run OCR", exact: true });
- await expect(ocr).toBeVisible();
- await expect(ocr).toBeDisabled();
- await expect(hint.getByRole("note")).toHaveText(
- "OCR cannot yet preserve this PDF's protection. The protected original remains available for viewing.",
- );
- await expect(ocr).toHaveAccessibleDescription(/protection/);
- const removePassword = hint.getByRole("button", {
- name: "Remove Password",
- exact: true,
- });
- await expect(removePassword).toBeVisible();
- await page.getByTestId("pdf-editor-root").screenshot({
- path: test.info().outputPath("protected-ocr-sidebar.png"),
- });
- await expect(page).toHaveURL(/\/pdf-text-editor$/);
- expect(ocrRequests).toEqual([]);
- await removePassword.click();
- await expect(page).toHaveURL(/\/remove-password$/);
+ await page.goto("/editor");
+ await page.getByTestId("file-input").setInputFiles(SCAN);
+ await page
+ .getByLabel("Password to open", { exact: true })
+ .fill("scan-password");
+ await page.getByRole("button", { name: "Open PDF", exact: true }).click();
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ await waitForEditorReady(page);
+ const hint = page.getByTestId("pdf-editor-scan-hint");
+ const ocr = hint.getByRole("button", { name: "Run OCR", exact: true });
+ await expect(ocr).toBeVisible();
+ await expect(ocr).toBeDisabled();
+ await expect(hint.getByRole("note")).toHaveText(
+ "OCR cannot yet preserve this PDF's protection. The protected original remains available for viewing.",
+ );
+ await expect(ocr).toHaveAccessibleDescription(/protection/);
+ const removePassword = hint.getByRole("button", {
+ name: "Remove Password",
+ exact: true,
+ });
+ await expect(removePassword).toBeVisible();
+ await page.getByTestId("pdf-editor-root").screenshot({
+ path: test.info().outputPath("protected-ocr-sidebar.png"),
});
-}
+ await expect(page).toHaveURL(/\/pdf-text-editor$/);
+ expect(ocrRequests).toEqual([]);
+ await removePassword.click();
+ await expect(page).toHaveURL(/\/remove-password$/);
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reflow-justified.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reflow-justified.spec.ts
index 9c4c8f1926..67d1e218f1 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reflow-justified.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reflow-justified.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -28,9 +29,7 @@ async function open(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-1")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts
index 620fcbc15f..585e49ff80 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -25,19 +26,15 @@ async function arrangeItemDisabled(
const disabled = await item.isDisabled();
// Close via a neutral click in the top bar, NOT Escape: the editor's global
// Escape handler also clears the selection, which would break the next check.
- await page.getByTestId("pdf-editor-zoom-percent").click();
+ await page
+ .getByTestId("pdf-editor-toolbar")
+ .click({ position: { x: 2, y: 2 } });
await item.waitFor({ state: "hidden" });
return disabled;
}
async function open(page: Page, firstPage = 0): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId(`pdf-editor-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts
index 51d90bbcca..773b267e7c 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -32,13 +33,7 @@ test("editing rotated text keeps its rotation through save+reopen", async ({
const errs: string[] = [];
page.on("pageerror", (e) => errs.push(e.message));
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 20_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(ROTATED);
+ await openInTextEditor(page, ROTATED);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -83,7 +78,7 @@ test("editing rotated text keeps its rotation through save+reopen", async ({
const stream = await dl.createReadStream();
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(c as Buffer);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: Buffer.concat(chunks),
@@ -107,13 +102,7 @@ test("inserting text on a /Rotate 90 page lands upright (counter-rotated)", asyn
page: Page;
}) => {
test.setTimeout(90_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 20_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(ROTATE90);
+ await openInTextEditor(page, ROTATE90);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts
index 2686ce9327..519db3d70c 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import path from "node:path";
@@ -25,14 +26,13 @@ for (const dpi of [96, 150, 600]) {
timeout: 60_000,
});
await expect(page.getByTestId("pdf-editor-root")).toBeVisible();
- await page
- .getByTestId("pdf-editor-file-input")
- .setInputFiles(
- path.join(
- import.meta.dirname,
- `../test-fixtures/scanned-ocr-weight-${dpi}.pdf`,
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(
+ import.meta.dirname,
+ `../test-fixtures/scanned-ocr-weight-${dpi}.pdf`,
+ ),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();
await expect
.poll(() =>
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
index aa4eb70ab1..92ca3bb94e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Locator, Page } from "@playwright/test";
import path from "path";
import { readFile } from "node:fs/promises";
@@ -181,13 +182,12 @@ async function runs(page: Page): Promise<RunState[]> {
}
async function open(page: Page, file: string | Buffer): Promise<void> {
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- typeof file === "string"
- ? FIX(file)
- : { name: "reopened.pdf", mimeType: "application/pdf", buffer: file },
- );
+ await openInTextEditor(
+ page,
+ typeof file === "string"
+ ? FIX(file)
+ : { name: "reopened.pdf", mimeType: "application/pdf", buffer: file },
+ );
await expect(page.getByTestId(PAGE_TESTID)).toBeVisible({ timeout: 60_000 });
await waitForEditorReady(page, 60_000);
await settle(page);
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-selection-scope.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-selection-scope.spec.ts
index 0074f60aa8..64d35a9d74 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-selection-scope.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-selection-scope.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Two ways the editor's selection covered less than the user asked for:
@@ -24,13 +25,7 @@ const PARAGRAPH_PDF = path.join(
const TOTAL_PAGES = 8;
async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
index 732caefb92..1576602fe4 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -40,9 +41,7 @@ interface ShapeWindow {
type PdfFile = string | { name: string; mimeType: string; buffer: Buffer };
async function openPdf(page: Page, file: PdfFile): Promise<void> {
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts
index 56379eca9b..ceca93a6fa 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-signed-save.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import fs from "fs";
import path from "path";
@@ -9,13 +10,7 @@ const SIGNED = path.join(
);
async function openSigned(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SIGNED);
+ await openInTextEditor(page, SIGNED);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-stability.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-stability.spec.ts
index b1229fa8ab..7034042bd5 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-stability.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-stability.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -44,11 +45,10 @@ for (const fixture of FIXTURES) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 45_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, `../test-fixtures/${fixture}.pdf`),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, `../test-fixtures/${fixture}.pdf`),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 45_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
index fe7231942a..6322eaa33e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import { mockAppApis } from "@editor/tests/helpers/api-stubs";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
@@ -39,7 +40,7 @@ async function reopenExport(
if (errors) reopened.on("pageerror", (error) => errors.push(error.message));
await mockAppApis(reopened);
await reopened.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await reopened.getByTestId("pdf-editor-file-input").setInputFiles(saved);
+ await openInTextEditor(reopened, saved);
await waitForFirstPage(reopened);
return reopened;
}
@@ -93,14 +94,10 @@ test("merged cells retain their borders after a structural edit and export", asy
}, testInfo) => {
test.setTimeout(180_000);
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await page
- .getByTestId("pdf-editor-file-input")
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../test-fixtures/merged-table-sample.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/merged-table-sample.pdf"),
+ );
await waitForFirstPage(page);
await page
.locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
@@ -183,7 +180,7 @@ for (const file of [fixture, ...corpus]) {
page.on("pageerror", onPageError);
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("pdf-editor-root")).toBeVisible();
- await page.getByTestId("pdf-editor-file-input").setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts
index 7aced7a95a..8e2eddfc8b 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import path from "path";
@@ -21,16 +22,10 @@ test.describe("PDF text editor - tables", () => {
width: layout.width,
height: layout.height,
});
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeAttached();
- await page
- .getByTestId("pdf-editor-file-input")
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../test-fixtures/paragraph-sample.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/paragraph-sample.pdf"),
+ );
await page.waitForFunction(() => {
const state = (
window as unknown as { __editor_store: EditorStore }
@@ -69,19 +64,14 @@ test.describe("PDF text editor - tables", () => {
test("insert, grow, fill, and undo a table", async ({ page }) => {
test.setTimeout(180_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../test-fixtures",
- "paragraph-sample.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures",
+ "paragraph-sample.pdf",
+ ),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -162,19 +152,14 @@ test.describe("PDF text editor - tables", () => {
test("resizes a column, a row, and the whole table", async ({ page }) => {
test.setTimeout(180_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../test-fixtures",
- "paragraph-sample.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures",
+ "paragraph-sample.pdf",
+ ),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -273,15 +258,10 @@ test.describe("PDF text editor - tables", () => {
page,
}) => {
test.setTimeout(180_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 15_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures", "table-sample.pdf"),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures", "table-sample.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
index 36a5d62c25..14abe021b7 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tagged-structure.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Editing text in a tagged PDF must keep it in the structure tree. The editor
@@ -120,9 +121,7 @@ async function saveAndReopen(page: import("@playwright/test").Page) {
};
w.__prev_document = w.__editor_store?.document;
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(saved);
+ await openInTextEditor(page, saved);
await page.waitForFunction(
() => {
const w = window as unknown as {
@@ -146,9 +145,7 @@ async function openFixture(page: import("@playwright/test").Page) {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 15_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FIXTURE);
+ await openInTextEditor(page, FIXTURE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-text-fit.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-text-fit.spec.ts
index a222c9d0fd..3e6b08feb5 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-text-fit.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-text-fit.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -15,15 +16,10 @@ interface DriftResult {
}
async function openFixture(page: Page, name: string): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, `../test-fixtures/${name}.pdf`),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, `../test-fixtures/${name}.pdf`),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts
index 7ea268e07b..12fa95dcd5 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Two toolbar changes:
@@ -17,13 +18,7 @@ const PARAGRAPH_PDF = path.join(
);
async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-topbar.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-topbar.spec.ts
index 2222182e47..dddbb17466 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-topbar.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-topbar.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -12,9 +13,7 @@ async function openEditor(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE_PDF);
+ await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -44,15 +43,10 @@ test.describe("PDF text editor - top bar", () => {
}
});
- test("names the open document, and marks it unsaved once edited", async ({
- page,
- }) => {
+ test("marks the document unsaved once edited", async ({ page }) => {
test.setTimeout(120_000);
await openEditor(page);
- await expect(page.getByTestId("pdf-editor-filename")).toContainText(
- "sample.pdf",
- );
expect(await page.getByTestId("pdf-editor-dirty-dot").count()).toBe(0);
await page.evaluate(() => {
@@ -85,7 +79,6 @@ test.describe("PDF text editor - top bar", () => {
"pdf-editor-open-find",
"pdf-editor-help",
"pdf-editor-save",
- "pdf-editor-filename",
]) {
expect(
await page.locator(`[data-testid="${id}"]`).count(),
@@ -178,9 +171,9 @@ test.describe("PDF text editor - top bar", () => {
const findBar = page.getByTestId("pdf-editor-find-bar");
await expect(findBar).toBeVisible();
const bar = await findBar.boundingBox();
- const stage = await page.getByTestId("pdf-editor-stage").boundingBox();
+ const pages = await page.locator("[data-viewer-pages]").boundingBox();
expect(bar).not.toBeNull();
- expect(stage).not.toBeNull();
- expect(bar!.y).toBeLessThan(stage!.y);
+ expect(pages).not.toBeNull();
+ expect(bar!.y).toBeLessThan(pages!.y);
});
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-type3.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-type3.spec.ts
index a959240bd9..eef7ab9bb6 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-type3.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-type3.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// PDFium's generator cannot emit Type 3 glyph procedures, so an edited run
@@ -12,11 +13,10 @@ test.describe("PDF text editor - Type 3 fonts", () => {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(import.meta.dirname, "../test-fixtures/type3-sample.pdf"),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/type3-sample.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -74,14 +74,13 @@ test.describe("PDF text editor - Type 3 fonts", () => {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../../../../../public/samples/Sample.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(
+ import.meta.dirname,
+ "../../../../../public/samples/Sample.pdf",
+ ),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
index 4ec78653c2..95f4b2d012 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -56,7 +57,7 @@ function runText(page: Page, rid: string): Promise<string> {
// Reopen saved bytes and wait for that document, not the one still on screen.
async function reopen(page: Page, name: string, saved: Buffer) {
await stashCurrentDocument(page);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name,
mimeType: "application/pdf",
buffer: saved,
@@ -75,9 +76,7 @@ async function appendSaveReopen(
page.on("pageerror", (e) => errs.push(e.message));
const fontLoaded = await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -182,9 +181,7 @@ for (const { name, text } of RTL_SAMPLES) {
page.on("pageerror", (e) => errs.push(e.message));
const fontLoaded = await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unsaved-guard.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unsaved-guard.spec.ts
index 24cd812db2..30bf125864 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unsaved-guard.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unsaved-guard.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import { uploadFiles } from "@editor/tests/helpers/ui-helpers";
+import { fileRows } from "@editor/tests/helpers/pdf-text-editor";
const SAMPLE_PDF = path.join(
import.meta.dirname,
@@ -12,12 +13,27 @@ const PARAGRAPH_PDF = path.join(
"../test-fixtures/paragraph-sample.pdf",
);
+/** The name on the file-list row the viewer, and so the editor, has open. */
+function openFile(page: Page) {
+ return page.locator(".file-sidebar-file-item.viewed .file-sidebar-file-name");
+}
+
+/** Shows `name` in the viewer from its file-list row; the editor follows. */
+async function viewFile(page: Page, name: string): Promise<void> {
+ const row = fileRows(page, name).first();
+ await row.hover();
+ await row.locator(".file-sidebar-eye-btn").click();
+}
+
async function openEditorWithTwoFiles(page: Page): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
await uploadFiles(page, [SAMPLE_PDF, PARAGRAPH_PDF]);
+ // Two files land on the file list; viewing one starts editing it.
+ await viewFile(page, "sample.pdf");
+ await expect(openFile(page)).toHaveText("sample.pdf", { timeout: 60_000 });
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -46,12 +62,7 @@ async function makeAnEdit(page: Page): Promise<void> {
async function pickOtherFile(page: Page, opened: string): Promise<string> {
const other = opened === "sample.pdf" ? "paragraph-sample.pdf" : "sample.pdf";
- await page.getByTestId("pdf-editor-file-switcher").click();
- await page
- .getByTestId("pdf-editor-file-switch")
- .filter({ hasText: new RegExp(`^${other}$`) })
- .first()
- .click();
+ await viewFile(page, other);
return other;
}
@@ -59,22 +70,16 @@ test.describe("PDF text editor - unsaved-changes guard", () => {
test("switching files with unsaved edits asks first", async ({ page }) => {
test.setTimeout(180_000);
await openEditorWithTwoFiles(page);
- const opened = (
- await page.getByTestId("pdf-editor-filename").innerText()
- ).trim();
+ const opened = (await openFile(page).innerText()).trim();
await makeAnEdit(page);
- const other = await pickOtherFile(page, opened);
+ await pickOtherFile(page, opened);
await expect(
- page.getByTestId("pdf-editor-discard-confirm"),
+ page.getByTestId("unsaved-discard"),
"switching files must not discard edits without asking",
).toBeVisible({ timeout: 10_000 });
- await expect(
- page
- .getByTestId("pdf-editor-discard-modal")
- .locator(".mantine-Modal-body"),
- ).toContainText(other);
+ await expect(openFile(page)).toHaveText(opened);
});
test("cancelling keeps the document, its edits and its history", async ({
@@ -82,16 +87,15 @@ test.describe("PDF text editor - unsaved-changes guard", () => {
}) => {
test.setTimeout(180_000);
await openEditorWithTwoFiles(page);
- const opened = (
- await page.getByTestId("pdf-editor-filename").innerText()
- ).trim();
+ const opened = (await openFile(page).innerText()).trim();
await makeAnEdit(page);
await pickOtherFile(page, opened);
- await page.getByTestId("pdf-editor-discard-cancel").click();
+ await page.getByRole("button", { name: "Keep Working" }).click();
- await expect(page.getByTestId("pdf-editor-discard-confirm")).toBeHidden();
- await expect(page.getByTestId("pdf-editor-filename")).toContainText(opened);
+ await expect(page.getByTestId("unsaved-discard")).toBeHidden();
+ await expect(page.getByTestId("pdf-editor-discard-modal")).toBeHidden();
+ await expect(openFile(page)).toContainText(opened);
await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
const stillThere = await page.evaluate(() =>
(
@@ -113,17 +117,18 @@ test.describe("PDF text editor - unsaved-changes guard", () => {
test("confirming opens the other file", async ({ page }) => {
test.setTimeout(180_000);
await openEditorWithTwoFiles(page);
- const opened = (
- await page.getByTestId("pdf-editor-filename").innerText()
- ).trim();
+ const opened = (await openFile(page).innerText()).trim();
await makeAnEdit(page);
const other = await pickOtherFile(page, opened);
- await page.getByTestId("pdf-editor-discard-confirm").click();
+ await page.getByTestId("unsaved-discard").click();
- await expect(page.getByTestId("pdf-editor-filename")).toHaveText(other, {
+ await expect(openFile(page)).toHaveText(other, {
timeout: 60_000,
});
+ // The app's prompt settled it: the editor must not ask a second time.
+ await expect(page.getByTestId("pdf-editor-discard-modal")).toBeHidden();
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeHidden();
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -132,33 +137,14 @@ test.describe("PDF text editor - unsaved-changes guard", () => {
test("a clean document switches with no prompt at all", async ({ page }) => {
test.setTimeout(180_000);
await openEditorWithTwoFiles(page);
- const opened = (
- await page.getByTestId("pdf-editor-filename").innerText()
- ).trim();
+ const opened = (await openFile(page).innerText()).trim();
const other = await pickOtherFile(page, opened);
- await expect(page.getByTestId("pdf-editor-filename")).toHaveText(other, {
+ await expect(openFile(page)).toHaveText(other, {
timeout: 60_000,
});
- await expect(page.getByTestId("pdf-editor-discard-confirm")).toBeHidden();
- });
-
- test("opening a file from disk over unsaved edits asks too", async ({
- page,
- }) => {
- test.setTimeout(180_000);
- await openEditorWithTwoFiles(page);
- await makeAnEdit(page);
-
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH_PDF);
-
- await expect(
- page.getByTestId("pdf-editor-discard-confirm"),
- "a dropped file must not discard edits without asking",
- ).toBeVisible({ timeout: 10_000 });
+ await expect(page.getByTestId("unsaved-discard")).toBeHidden();
});
test("closing the tool asks before the tool view slides away", async ({
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts
index 33ed50f2e4..89ecbca44c 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
@@ -20,9 +21,7 @@ async function openEditor(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 45_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 45_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-view-rotation.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-view-rotation.spec.ts
new file mode 100644
index 0000000000..08d4ba3626
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-view-rotation.spec.ts
@@ -0,0 +1,104 @@
+import path from "path";
+import type { Page } from "@playwright/test";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { fileRows } from "@editor/tests/helpers/pdf-text-editor";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+const OTHER_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/many-pages-sample.pdf",
+);
+
+/** Whether the first viewer page is drawn wider than tall. */
+async function firstPageLandscape(page: Page): Promise<boolean> {
+ const box = await page.locator('[data-page-index="0"]').first().boundingBox();
+ if (!box) throw new Error("first page not laid out");
+ return box.width > box.height;
+}
+
+test("the view rotation returns when the text editor closes", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(SAMPLE_PDF);
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ expect(await firstPageLandscape(page)).toBe(false);
+
+ await page.getByRole("button", { name: "Rotate Right" }).first().click();
+ await expect.poll(() => firstPageLandscape(page)).toBe(true);
+
+ // Editing straightens the view.
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect.poll(() => firstPageLandscape(page)).toBe(false);
+
+ await page.getByRole("button", { name: "Back to all tools" }).click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+ await expect.poll(() => firstPageLandscape(page)).toBe(true);
+});
+
+test("a view rotation is not carried onto another document", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await page.goto("/editor");
+ await page
+ .locator('input[type="file"]')
+ .first()
+ .setInputFiles([SAMPLE_PDF, OTHER_PDF]);
+ const rows = page.locator(".file-sidebar-file-item");
+ await expect(rows).toHaveCount(2, { timeout: 30_000 });
+ const view = async (name: string) => {
+ const row = fileRows(page, name).first();
+ await row.hover();
+ await row.locator(".file-sidebar-eye-btn").click();
+ };
+ await view("sample.pdf");
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.getByRole("button", { name: "Rotate Right" }).first().click();
+ await expect.poll(() => firstPageLandscape(page)).toBe(true);
+
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await view("many-pages-sample.pdf");
+ // many-pages-sample.pdf is the eight-page one.
+ await expect
+ .poll(
+ () =>
+ page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ __editor_store?: { getState(): { pageCount: number } };
+ }
+ ).__editor_store?.getState().pageCount,
+ ),
+ { timeout: 30_000 },
+ )
+ .toBe(8);
+
+ await page.getByRole("button", { name: "Back to all tools" }).click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+ // A fixed wait, not a poll: the page is upright at first either way, and the
+ // failure is a held rotation restored onto it a moment later.
+ await page.waitForTimeout(1_000);
+ expect(await firstPageLandscape(page)).toBe(false);
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-viewer-tools.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-viewer-tools.spec.ts
new file mode 100644
index 0000000000..2358f42e24
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-viewer-tools.spec.ts
@@ -0,0 +1,273 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "path";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+const SIGNED_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/signed-sample.pdf",
+);
+
+const editText = (page: Page) => page.getByTestId("viewer-edit-text");
+const ruler = (page: Page) =>
+ page.getByRole("button", { name: "Ruler / Measure", exact: true });
+
+async function openEditor(page: Page, file = SAMPLE_PDF): Promise<void> {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, file);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+}
+
+async function makeAnEdit(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const el = document.querySelector<HTMLElement>(
+ '[data-testid^="pdf-editor-run-"]',
+ );
+ if (!el) throw new Error("no run overlay in the DOM");
+ el.focus();
+ const selection = window.getSelection();
+ if (!selection) throw new Error("no Selection api");
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ range.collapse(false);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ document.execCommand("insertText", false, "RULED");
+ });
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible({
+ timeout: 15_000,
+ });
+}
+
+async function expectEditorClosedWithRuler(page: Page): Promise<void> {
+ await expect(editText(page)).toHaveAttribute("aria-pressed", "false", {
+ timeout: 15_000,
+ });
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+ await expect(ruler(page)).toHaveAttribute("aria-pressed", "true");
+}
+
+test.describe("PDF text editor - viewer tools", () => {
+ test("the ruler closes the editor when there is nothing to save", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await ruler(page).click();
+ await expect(page.getByTestId("unsaved-discard")).toBeHidden();
+ await expectEditorClosedWithRuler(page);
+ });
+
+ test("the ruler asks about unsaved edits, and Keep Working stays", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await makeAnEdit(page);
+ await ruler(page).click();
+ await page.getByRole("button", { name: "Keep Working" }).click();
+
+ await expect(editText(page)).toHaveAttribute("aria-pressed", "true");
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+ await expect(ruler(page)).not.toHaveAttribute("aria-pressed", "true");
+ });
+
+ test("discarding at the prompt closes the editor and opens the ruler", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await makeAnEdit(page);
+ await ruler(page).click();
+ await page.getByTestId("unsaved-discard").click();
+ await expectEditorClosedWithRuler(page);
+ });
+
+ test("saving at the prompt writes the edits, then opens the ruler", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await makeAnEdit(page);
+ await ruler(page).click();
+ await page.getByTestId("unsaved-save").click();
+ await expectEditorClosedWithRuler(page);
+
+ // The edit is in the workbench file: reopening the editor shows it.
+ await ruler(page).click();
+ await editText(page).click();
+ await expect
+ .poll(
+ () =>
+ page.evaluate(() =>
+ (
+ window as unknown as {
+ __editor_store?: {
+ getState: () => {
+ pages: Array<{ runs: Array<{ text: string }> }>;
+ };
+ };
+ }
+ ).__editor_store
+ ?.getState()
+ .pages.flatMap((p) => p.runs)
+ .some((r) => r.text.includes("RULED")),
+ ),
+ { timeout: 60_000 },
+ )
+ .toBe(true);
+ });
+
+ test("saving a signed PDF at the prompt warns first", async ({ page }) => {
+ test.setTimeout(120_000);
+ await openEditor(page, SIGNED_PDF);
+ await makeAnEdit(page);
+ await ruler(page).click();
+ await page.getByTestId("unsaved-save").click();
+
+ // Cancelling the warning keeps the prompt and the edits.
+ await page.getByTestId("pdf-editor-save-risk-cancel").click();
+ await expect(page.getByTestId("unsaved-save")).toBeVisible();
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+
+ await page.getByTestId("unsaved-save").click();
+ await expect(page.getByTestId("pdf-editor-save-risk-modal")).toContainText(
+ /signature/i,
+ );
+ await page.getByTestId("pdf-editor-save-risk-confirm").click();
+ await expectEditorClosedWithRuler(page);
+ });
+
+ test("pan closes the editor too", async ({ page }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await page.getByRole("button", { name: "Pan Mode", exact: true }).click();
+ await expect(editText(page)).toHaveAttribute("aria-pressed", "false", {
+ timeout: 15_000,
+ });
+ await expect(page.getByTestId("pdf-editor-page-0")).toHaveCount(0);
+ });
+
+ test("search opens the editor's find bar and keeps the edits", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await makeAnEdit(page);
+ // Its label says what it opens here.
+ await expect(
+ page.getByRole("button", { name: "Search PDF", exact: true }),
+ ).toHaveCount(0);
+ const search = page.getByRole("button", {
+ name: "Find & replace",
+ exact: true,
+ });
+
+ await search.click();
+ await expect(page.getByTestId("pdf-editor-find-bar")).toBeVisible();
+ await expect(page.getByTestId("unsaved-discard")).toBeHidden();
+ await expect(editText(page)).toHaveAttribute("aria-pressed", "true");
+ await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeVisible();
+
+ await search.click();
+ await expect(page.getByTestId("pdf-editor-find-bar")).toBeHidden();
+ });
+
+ test("opening the editor turns the ruler off", async ({ page }) => {
+ test.setTimeout(120_000);
+ await openEditor(page);
+ await ruler(page).click();
+ await expectEditorClosedWithRuler(page);
+ await editText(page).click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ await expect(ruler(page)).not.toHaveAttribute("aria-pressed", "true");
+ });
+});
+
+test("Edit text in the viewer's selection menu opens the editor on that text", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(SAMPLE_PDF);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage.locator(".pdf-selection-layer")).toBeAttached({
+ timeout: 30_000,
+ });
+
+ let box = await firstPage.boundingBox();
+ let y = 0;
+ await expect
+ .poll(async () => {
+ box = await firstPage.boundingBox();
+ if (!box) return "no box";
+ y = box.y + box.height * 0.105;
+ await page.mouse.move(box.x + 5, box.y + 5);
+ await page.mouse.move(box.x + box.width * 0.15, y, { steps: 5 });
+ return firstPage.evaluate(
+ (el) => getComputedStyle(el.parentElement ?? el).cursor,
+ );
+ })
+ .toMatch(/^(text|vertical-text)$/);
+ if (!box) throw new Error("page has no bounding box");
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.6, y, { steps: 15 });
+ await page.mouse.up();
+ await page.getByTestId("text-selection-edit-text").click();
+
+ await expect(editText(page)).toHaveAttribute("aria-pressed", "true", {
+ timeout: 30_000,
+ });
+ await expect
+ .poll(
+ () =>
+ page.evaluate(() => {
+ const store = (
+ window as unknown as {
+ __editor_store?: {
+ selection: {
+ value: {
+ runIds: string[];
+ textRange: { start: number; end: number } | null;
+ };
+ };
+ getState: () => {
+ pages: Array<{ runs: Array<{ id: string; text: string }> }>;
+ };
+ };
+ }
+ ).__editor_store;
+ const sel = store?.selection.value;
+ if (!store || !sel?.textRange || sel.runIds.length !== 1) return "";
+ const run = store
+ .getState()
+ .pages[0]?.runs.find((r) => r.id === sel.runIds[0]);
+ return run?.text.slice(sel.textRange.start, sel.textRange.end) ?? "";
+ }),
+ { timeout: 60_000 },
+ )
+ // The line dragged across in the viewer.
+ .toContain("Test document");
+ await expect(page.locator("[data-text-selection-menu]")).toHaveCount(0);
+
+ // The run is open for editing with that span selected, so typing replaces it.
+ const focusedRun = page.locator('[data-testid^="pdf-editor-run-"]:focus');
+ await expect(focusedRun).toHaveCount(1);
+ await expect
+ .poll(() => page.evaluate(() => String(window.getSelection())))
+ .toContain("Test document");
+ await page.keyboard.type("Replaced");
+ await expect(focusedRun).toContainText("Replaced");
+ await expect(focusedRun).not.toContainText("Test document");
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-addtext.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-addtext.spec.ts
index df1953cb19..79559843c2 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-addtext.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-addtext.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// ADD-TEXT, judged on the PAGE BITMAP rather than on the store.
@@ -36,14 +37,12 @@ type Ink = {
meanB: number;
};
-async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+async function openEditor(
+ page: import("@playwright/test").Page,
+ file: string,
+ zoomPercent?: number | null,
+) {
+ await openInTextEditor(page, file, { zoomPercent });
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -644,7 +643,8 @@ test.describe("PDF text editor - add text, checked in the bitmap", () => {
// Fails if the click handler always targets page 0, or converts client
// coords with the wrong page's transform once the stage has scrolled.
test.setTimeout(120_000);
- await openEditor(page, MANY_PAGES_PDF);
+ // At the viewer's own fit, so page one stays near enough to keep its bitmap.
+ await openEditor(page, MANY_PAGES_PDF, null);
const zeroRect: Rect = { x: 0, y: 0, w: 600, h: 800 };
const pageZeroBefore = await inkIn(page, 0, zeroRect);
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-colour.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-colour.spec.ts
index a665b468f8..8e69a4d2ef 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-colour.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-colour.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Colour, judged on the page BITMAP rather than on the model.
@@ -129,13 +130,7 @@ window.__ink = function (runId, opts) {
async function openEditor(page: import("@playwright/test").Page, file: string) {
await page.addInitScript({ content: INK_SAMPLER });
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts
index 3dd232b798..b175caf3a7 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Font size and font family, judged on the PIXELS PDFium paints - not on the
@@ -116,13 +117,7 @@ async function openEditor(
page: import("@playwright/test").Page,
file: string,
): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts
index 9341ec2dcc..b4413e777a 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -227,13 +228,7 @@ async function waitForRepaint(
}
async function openSample(page: Page): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE);
+ await openInTextEditor(page, SAMPLE);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-pages.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-pages.spec.ts
index 6841825c8e..b7e2995b1e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-pages.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-pages.spec.ts
@@ -1,4 +1,9 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ scrollToEditorPage,
+ setViewerZoom,
+} from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
/**
@@ -58,7 +63,6 @@ interface PageScan {
boxH: number;
boxTop: number;
boxLeft: number;
- placeholder: boolean;
errorOverlay: boolean;
runs: number;
/** Ink bounding box in viewport coordinates, or null when not live. */
@@ -91,7 +95,6 @@ function scanPage(p: Page, idx: number): Promise<PageScan> {
boxH: 0,
boxTop: 0,
boxLeft: 0,
- placeholder: false,
errorOverlay: false,
runs: 0,
clientInk: null,
@@ -105,9 +108,6 @@ function scanPage(p: Page, idx: number): Promise<PageScan> {
boxH: Math.round(box.height),
boxTop: Math.round(box.top),
boxLeft: Math.round(box.left),
- placeholder: !!el.querySelector(
- `[data-testid="pdf-editor-page-${i}-placeholder"]`,
- ),
errorOverlay: !!el.querySelector(
`[data-testid="pdf-editor-page-${i}-error"]`,
),
@@ -234,24 +234,32 @@ function scanRunCoverage(p: Page, idx: number) {
}
async function openEditor(p: Page, file: string) {
- await p.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(p.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await p.locator('[data-testid="pdf-editor-file-input"]').setInputFiles(file);
+ await openInTextEditor(p, file);
await expect(p.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
await p.waitForTimeout(1500);
}
-/** Scroll a page to the middle of the stage and wait for its bitmap. */
+/**
+ * The viewer's scroll container. Passed into the browser as source, since a
+ * page.evaluate callback cannot close over it.
+ */
+function viewerScrollerFn(): HTMLElement {
+ let el = document.querySelector<HTMLElement>(
+ "[data-testid^='pdf-editor-page-']",
+ )?.parentElement;
+ while (el && !/(auto|scroll)/.test(getComputedStyle(el).overflowY)) {
+ el = el.parentElement;
+ }
+ if (!el) throw new Error("viewer scroll container not found");
+ return el;
+}
+const SCROLLER = viewerScrollerFn.toString();
+
+/** Scroll a page to the middle of the viewer and wait for its bitmap. */
async function showPage(p: Page, idx: number) {
- await p.evaluate((i) => {
- document
- .querySelector<HTMLElement>(`[data-testid="pdf-editor-page-${i}"]`)
- ?.scrollIntoView({ block: "center" });
- }, idx);
+ await scrollToEditorPage(p, idx);
await p.waitForFunction(
(i) => {
const el = document.querySelector(`[data-testid="pdf-editor-page-${i}"]`);
@@ -264,13 +272,13 @@ async function showPage(p: Page, idx: number) {
await p.waitForTimeout(400);
}
-/** Wait until a page's bitmap has been released. */
+/** Wait until a page's bitmap has been released, or the page unmounted. */
async function waitFreed(p: Page, idx: number) {
await p.waitForFunction(
(i) => {
const el = document.querySelector(`[data-testid="pdf-editor-page-${i}"]`);
const c = el?.querySelector("canvas");
- return !!c && c.width === 0;
+ return !c || c.width === 0;
},
idx,
{ timeout: 30_000 },
@@ -393,13 +401,14 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
expect(freed.live, "page 0's bitmap must be released off-screen").toBe(
false,
);
- expect(freed.placeholder, "freed page 0 must show its placeholder").toBe(
- true,
- );
- expect(
- [freed.boxW, freed.boxH],
- "freeing the bitmap must not resize the page box",
- ).toEqual([RASTER_W, RASTER_H]);
+ // The viewer may unmount the page outright; a page it keeps must hold
+ // its size.
+ if (freed.present) {
+ expect(
+ [freed.boxW, freed.boxH],
+ "freeing the bitmap must not resize the page box",
+ ).toEqual([RASTER_W, RASTER_H]);
+ }
await showPage(page, 0);
const after = await waitForScan(
@@ -499,63 +508,6 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
}
});
- // Would catch: the lazy page pipeline breaking in either direction - a page
- // past the eager window never rendering, or the editor eagerly rasterising
- // (and holding) every page's bitmap up front.
- test("a page past the eager window stays blank with no runs until scrolled in", async ({
- page,
- }) => {
- await openEditor(page, MANY_PAGES_PDF);
- const last = TOTAL_PAGES - 1;
-
- const cold = await scanPage(page, last);
- expect(cold.present, `page ${last} must exist in the DOM up front`).toBe(
- true,
- );
- expect(
- cold.live,
- `page ${last} must not hold a bitmap before it is scrolled to`,
- ).toBe(false);
- expect(cold.placeholder, `page ${last} must show its placeholder`).toBe(
- true,
- );
- expect(
- cold.runs,
- `page ${last} is past the eager window (${FIRST_LAZY_PAGE}) so it should carry no runs yet`,
- ).toBe(0);
- // Page 0 is painted, which proves the "no ink" reading above is a real
- // state and not a broken selector.
- const first = await scanPage(page, 0);
- expect(first.ink, "page 0 must be painted for contrast").toBeGreaterThan(
- 800,
- );
-
- await showPage(page, last);
- const warm = await waitForScan(
- page,
- last,
- (s) => s.ink > 800 && s.runs === 2,
- `page ${last} to paint and populate`,
- );
- expect(warm.placeholder, "placeholder must be gone once painted").toBe(
- false,
- );
- expect([warm.w, warm.h], `page ${last} canvas size`).toEqual([
- RASTER_W,
- RASTER_H,
- ]);
- expect(warm.bands.length, `page ${last} should paint two text bands`).toBe(
- 2,
- );
-
- const cov = await scanRunCoverage(page, last);
- expect(cov, "coverage scan").not.toBeNull();
- expect(
- cov ? cov.covered / cov.total : 0,
- `page ${last}'s freshly-loaded runs must land on its freshly-painted ink`,
- ).toBeGreaterThan(0.99);
- });
-
// Would catch: an edit being lost or re-rendered from the pre-edit model when
// its page is freed and restored, and edits leaking onto a neighbouring page.
test("an edit on page index 5 repaints after a round trip while page index 4 stays pixel-identical", async ({
@@ -678,7 +630,7 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
});
const relBefore = rel(at150);
- await page.getByTestId("pdf-editor-zoom-out").click();
+ await setViewerZoom(page, 125);
const at125 = await waitForScan(
page,
0,
@@ -708,7 +660,7 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
).toBeLessThan(0.006);
}
- await page.getByTestId("pdf-editor-zoom-in").click();
+ await setViewerZoom(page, 150);
const back = await waitForScan(
page,
0,
@@ -727,14 +679,8 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
// Would catch: bitmaps leaking (every visited page kept alive => an 80-page
// document blows out memory) or a visible page being freed under the user.
// The scroll here deliberately straddles the 3/4 boundary.
- //
- // Today only the two pages sharing the viewport are live: PageView's
- // near-viewport observer asks for `rootMargin: "800px"` but leaves the root
- // as the document viewport, and the Mantine ScrollArea clips the pages
- // before that margin is ever applied - so there is no prefetch. The bounds
- // below are deliberately loose enough that fixing the prefetch (root =
- // the ScrollArea viewport) keeps this test green; only a leak or an
- // over-eager free fails it.
+ // The bounds are loose enough for an 800px prefetch either side; only a
+ // leak or an over-eager free fails it.
test("a viewport straddling two pages keeps both painted while distant pages release their bitmaps", async ({
page,
}) => {
@@ -743,19 +689,20 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
// Visit several pages first so the "kept alive" failure mode is reachable.
for (const i of [1, 2, 5, 7]) await showPage(page, i);
- await page.evaluate(() => {
- const vp = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"] .mantine-ScrollArea-viewport',
- );
+ await showPage(page, 3);
+ await page.evaluate((scroller) => {
+ const vp = (
+ new Function(`return (${scroller})()`) as () => HTMLElement
+ )();
const el = document.querySelector<HTMLElement>(
'[data-testid="pdf-editor-page-3"]',
);
- if (!vp || !el) throw new Error("stage viewport or page 3 missing");
+ if (!el) throw new Error("page 3 missing");
const vr = vp.getBoundingClientRect();
const er = el.getBoundingClientRect();
// Put page 3's bottom edge halfway down the viewport, so 3 and 4 share it.
vp.scrollTop += er.bottom - vr.top - vr.height / 2;
- });
+ }, SCROLLER);
// Wait for the straddling pair to paint WITHOUT scrolling again.
await page.waitForFunction(
() =>
@@ -771,9 +718,6 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
await page.waitForTimeout(1200);
const state = await liveBitmaps(page);
- expect(state.pageCount, "all eight page boxes must be mounted").toBe(
- TOTAL_PAGES,
- );
expect(
state.live,
"both pages sharing the viewport must hold a bitmap",
@@ -807,10 +751,6 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
expect(s.live, `off-screen page ${i} must have released its bitmap`).toBe(
false,
);
- expect(
- s.placeholder,
- `off-screen page ${i} must show its placeholder`,
- ).toBe(true);
}
});
@@ -822,14 +762,13 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
}) => {
await openEditor(page, MANY_PAGES_PDF);
- const geomBefore = await page.evaluate(() => {
- const vp = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"] .mantine-ScrollArea-viewport',
- );
- if (!vp) throw new Error("stage viewport missing");
+ const geomBefore = await page.evaluate((scroller) => {
+ const vp = (
+ new Function(`return (${scroller})()`) as () => HTMLElement
+ )();
vp.scrollTop = 0;
return { scrollHeight: vp.scrollHeight, scrollTop: vp.scrollTop };
- });
+ }, SCROLLER);
await page.waitForTimeout(500);
const before = await waitForScan(
page,
@@ -844,13 +783,12 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
for (const i of [3, 5, 7]) await showPage(page, i);
- await page.evaluate(() => {
- const vp = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"] .mantine-ScrollArea-viewport',
- );
- if (!vp) throw new Error("stage viewport missing");
+ await page.evaluate((scroller) => {
+ const vp = (
+ new Function(`return (${scroller})()`) as () => HTMLElement
+ )();
vp.scrollTop = 0;
- });
+ }, SCROLLER);
const after = await waitForScan(
page,
0,
@@ -858,13 +796,12 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
"page 0 to repaint at the top",
);
- const geomAfter = await page.evaluate(() => {
- const vp = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"] .mantine-ScrollArea-viewport',
- );
- if (!vp) throw new Error("stage viewport missing");
+ const geomAfter = await page.evaluate((scroller) => {
+ const vp = (
+ new Function(`return (${scroller})()`) as () => HTMLElement
+ )();
return { scrollHeight: vp.scrollHeight, scrollTop: vp.scrollTop };
- });
+ }, SCROLLER);
expect(
geomAfter.scrollHeight,
@@ -898,12 +835,8 @@ test.describe("PDF text editor - multi-page rendering (pixel evidence)", () => {
RASTER_W,
RASTER_H,
]);
- const initial = await liveBitmaps(page);
- expect(initial.pageCount, "first document page count").toBe(TOTAL_PAGES);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH_PDF);
+ await openInTextEditor(page, PARAGRAPH_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts
index 2f18dd9b69..ecfeaf9f60 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-rotation.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -49,13 +50,7 @@ interface PageScan {
}
async function openEditor(page: Page, file: string): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts
index 06b9277346..bb5675b04e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-roundtrip.spec.ts
@@ -1,4 +1,8 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ scrollToEditorPage,
+} from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import {
@@ -225,13 +229,7 @@ function tv(a: number[], b: number[]): number {
const rel = (a: number, b: number) => Math.abs(a - b) / Math.max(b, 1);
async function openEditor(page: Page, file: string, pageIdx = 0) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FIX(file));
+ await openInTextEditor(page, FIX(file));
await expect(page.getByTestId(`pdf-editor-page-${pageIdx}`)).toBeVisible({
timeout: 60_000,
});
@@ -315,7 +313,7 @@ async function saveAndReopen(page: Page, pageIdx = 0): Promise<number> {
await settled(page, pageIdx);
await stashCurrentDocument(page);
await stampCanvases(page);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer,
@@ -429,7 +427,7 @@ test.describe("PDF text editor - save round-trip fidelity (pixels)", () => {
test.setTimeout(180_000);
const page0Loaded = await openEditor(page, "many-pages-sample.pdf");
- await page.getByTestId("pdf-editor-page-5").scrollIntoViewIfNeeded();
+ await scrollToEditorPage(page, 5);
const page5Loaded = await settled(page, 5);
const runs5 = await runsOn(page, 5);
expect(runs5.length, "page index 5 has no runs").toBeGreaterThan(0);
@@ -447,11 +445,11 @@ test.describe("PDF text editor - save round-trip fidelity (pixels)", () => {
// Scroll back before saving: page 0 is virtualised away while page 6 is on
// screen, and the round-trip is measured on both.
- await page.getByTestId("pdf-editor-page-0").scrollIntoViewIfNeeded();
+ await scrollToEditorPage(page, 0);
await settled(page, 0);
await saveAndReopen(page, 0);
const page0After = await settled(page, 0);
- await page.getByTestId("pdf-editor-page-5").scrollIntoViewIfNeeded();
+ await scrollToEditorPage(page, 5);
const page5After = await settled(page, 5);
expect(
@@ -799,7 +797,7 @@ test.describe("PDF text editor - save round-trip fidelity (pixels)", () => {
timeout: 30_000,
});
await stashCurrentDocument(page);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "cold-start.pdf",
mimeType: "application/pdf",
buffer,
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts
index 0e74423369..6f66481c21 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Visual validation of the PDF text editor's SELECTION AFFORDANCES.
@@ -48,13 +49,7 @@ interface EditorWin {
}
async function openEditor(page: P, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-undoredo.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-undoredo.spec.ts
index ecf230f44a..ab87a58c91 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-undoredo.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-undoredo.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
@@ -24,13 +25,7 @@ const HEAD = "p0-t0";
const BODY = "p0-t1";
async function openEditor(page: Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-zoom.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-zoom.spec.ts
index f98b388926..060e5f7d00 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-zoom.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-zoom.spec.ts
@@ -1,4 +1,8 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ setViewerZoom,
+} from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Visual zoom / render-scale suite.
@@ -24,10 +28,6 @@ const PARA_PDF = path.join(
import.meta.dirname,
"../test-fixtures/paragraph-sample.pdf",
);
-const JUSTIFIED_PDF = path.join(
- import.meta.dirname,
- "../test-fixtures/justified-sample.pdf",
-);
/** Fixed CSS-pixel gap between a `.pdf-editor-run` border box and its text origin. */
const RUN_BOX_INSET = 2;
@@ -89,14 +89,12 @@ interface Snap {
}
interface EditorState {
- renderScale: number;
pages: Array<{ width: number; height: number }>;
}
interface StoreWindow extends Window {
__editor_store?: {
getState: () => EditorState;
- setRenderScale: (scale: number) => void;
};
}
@@ -104,13 +102,7 @@ async function openEditor(
page: import("@playwright/test").Page,
file: string,
): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -178,7 +170,8 @@ function snapshotFn(): Snap {
const pageState = store.getState().pages[0];
return {
- scale: store.getState().renderScale,
+ // The page is drawn at the viewer's zoom.
+ scale: Math.round((cb.width / pageState.width) * 100) / 100,
pageW: pageState.width,
pageH: pageState.height,
canvasW: canvas.width,
@@ -258,15 +251,13 @@ async function waitForBitmap(
const store = (window as StoreWindow).__editor_store;
if (!canvas || !store) return false;
const st = store.getState();
- if (Math.abs(st.renderScale - want) > 1e-6) return false;
+ const shown = canvas.getBoundingClientRect().width / st.pages[0].width;
+ if (Math.abs(shown - want) > 0.01) return false;
// The bitmap renders at zoom x devicePixelRatio (capped at 3) so HiDPI
// displays get real pixels; headless runs are 1x, so this reduces to
// the plain zoom scale there.
const ratio = Math.min(Math.max(window.devicePixelRatio || 1, 1), 3);
- return (
- canvas.width ===
- Math.max(1, Math.round(st.pages[0].width * want * ratio))
- );
+ return Math.abs(canvas.width - st.pages[0].width * shown * ratio) <= 1;
},
scale,
{ timeout: 20_000 },
@@ -279,9 +270,7 @@ async function zoomTo(
page: import("@playwright/test").Page,
scale: number,
): Promise<Snap> {
- await page.evaluate((v) => {
- (window as StoreWindow).__editor_store?.setRenderScale(v);
- }, scale);
+ await setViewerZoom(page, Math.round(scale * 100));
await waitForBitmap(page, scale);
return page.evaluate(snapshotFn);
}
@@ -555,204 +544,4 @@ test.describe("PDF text editor - zoom keeps bitmap and overlay registered", () =
`overlay box height ratio ${(b.boxHeight / a.boxHeight).toFixed(3)} should match the glyph ratio ${(b.height / a.height).toFixed(3)}`,
).toBeGreaterThan(2.8);
});
-
- // Breakage caught: the Ctrl+wheel path updating renderScale without the
- // overlays following - the store number would move but the ink and the box
- // would part company.
- test("Ctrl+wheel zoom moves the bitmap and the overlay together", async ({
- page,
- }) => {
- test.setTimeout(120_000);
- await openEditor(page, PARA_PDF);
-
- const before = await zoomTo(page, 1);
- const beforeRun = requireRun(before, 0);
- const beforeInk = await page.evaluate(runInkFn, beforeRun.id);
- requireInk(beforeInk, "run before wheel zoom");
-
- // 10 Ctrl+wheel-up events = +0.1 each = 100% -> 200%.
- for (let i = 0; i < 10; i++) {
- await page.evaluate(() => {
- document
- .querySelector('[data-testid="pdf-editor-stage"]')
- ?.dispatchEvent(
- new WheelEvent("wheel", {
- deltaY: -100,
- ctrlKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
- }
- await waitForBitmap(page, 2);
-
- const after = await page.evaluate(snapshotFn);
- expect(
- after.scale,
- `10 Ctrl+wheel-up steps of 0.1 from 100% should land on 200%, got ${after.scale}`,
- ).toBeCloseTo(2, 5);
- const afterRun = requireRun(after, 0);
- const afterInk = await page.evaluate(runInkFn, afterRun.id);
- requireInk(afterInk, "run after wheel zoom");
-
- // The ink actually moved (this is not a no-op comparison)...
- expect(
- afterInk.minX / beforeInk.minX,
- `wheel zoom should double the ink offset: ${afterInk.minX} vs ${beforeInk.minX}`,
- ).toBeGreaterThan(1.8);
- // ...and the overlay moved with it.
- expectRegistered(
- afterInk.minX,
- afterRun.left + RUN_BOX_INSET,
- after.scale,
- "after Ctrl+wheel zoom",
- );
- expect(
- Math.abs(afterInk.minY - beforeInk.minY * 2),
- `the run's top glyph row should double from ${beforeInk.minY} to ~${beforeInk.minY * 2}, got ${afterInk.minY}`,
- ).toBeLessThanOrEqual(3);
- });
-
- // Breakage caught: Fit computing a scale from the wrong width, or applying
- // it to the layout but not to the bitmap.
- test("Fit to width sizes the bitmap to the stage and keeps the ink registered", async ({
- page,
- }) => {
- test.setTimeout(120_000);
- await openEditor(page, PARA_PDF);
- await zoomTo(page, 1);
-
- await page.getByTestId("pdf-editor-zoom-fit").click();
- await page.waitForTimeout(1800);
- const snap = await page.evaluate(snapshotFn);
- requireInk(snap.ink, "fit-to-width");
-
- const stageWidth = await page.evaluate(() => {
- const el = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"]',
- );
- if (!el) throw new Error("no stage");
- return el.clientWidth;
- });
-
- // EditorTopBar fits to (stage width - 64px of padding).
- expect(
- snap.canvasW,
- `fit bitmap width ${snap.canvasW} should fill the stage width ${stageWidth} minus 64px of padding`,
- ).toBe(
- Math.round(snap.pageW * +((stageWidth - 64) / snap.pageW).toFixed(2)),
- );
- expect(
- stageWidth - snap.canvasW,
- `fit should leave ~64px of slack, left ${stageWidth - snap.canvasW}px`,
- ).toBeLessThanOrEqual(70);
- expect(
- snap.canvasW,
- `fit must actually enlarge the page beyond its 100% width ${snap.pageW}`,
- ).toBeGreaterThan(snap.pageW);
-
- const run = requireRun(snap, 0);
- const ink = await page.evaluate(runInkFn, run.id);
- requireInk(ink, "fit-to-width run");
- expectRegistered(
- ink.minX,
- run.left + RUN_BOX_INSET,
- snap.scale,
- "after Fit to width",
- );
- });
-
- // Breakage caught: the 25% floor letting the scale go lower (or the bitmap
- // collapsing to a blank thumbnail with no ink left).
- test("zoom-out clamps at 25% and the shrunken bitmap still carries the same layout", async ({
- page,
- }) => {
- test.setTimeout(120_000);
- await openEditor(page, PARA_PDF);
- const base = await zoomTo(page, 1);
- requireInk(base.ink, "scale 1 baseline");
-
- for (let i = 0; i < 12; i++) {
- await page.getByTestId("pdf-editor-zoom-out").click();
- }
- await waitForBitmap(page, 0.25);
- await expect(page.getByTestId("pdf-editor-zoom-percent")).toHaveText("25%");
-
- const floor = await page.evaluate(snapshotFn);
- expect(
- floor.canvasW,
- `at the 25% floor the bitmap should be round(${floor.pageW} * 0.25) px wide`,
- ).toBe(Math.round(floor.pageW * 0.25));
- requireInk(floor.ink, "25% floor");
-
- // The page is 1/16th of the area but the layout is unchanged: the ink box
- // still covers the same fraction of the canvas.
- const b = normalisedInk(base);
- const f = normalisedInk(floor);
- for (const edge of ["l", "t", "r", "b"] as const) {
- expect(
- Math.abs(f[edge] - b[edge]),
- `at 25% the ink ${edge} edge sits at ${f[edge].toFixed(4)} of the canvas but at ${b[edge].toFixed(4)} at 100%`,
- ).toBeLessThan(0.03);
- }
- });
-
- // Breakage caught: the 400% ceiling leaking - a further zoom-in that
- // re-rasterises at a larger scale would change the bitmap checksum.
- test("zoom-in past the 400% ceiling is a pixel-level no-op", async ({
- page,
- }) => {
- test.setTimeout(120_000);
- await openEditor(page, JUSTIFIED_PDF);
-
- const three = await zoomTo(page, 3);
- requireInk(three.ink, "scale 3");
-
- for (let i = 0; i < 6; i++) {
- await page.getByTestId("pdf-editor-zoom-in").click();
- }
- await waitForBitmap(page, 4);
- await expect(page.getByTestId("pdf-editor-zoom-percent")).toHaveText(
- "400%",
- );
- const ceiling = await page.evaluate(snapshotFn);
- requireInk(ceiling.ink, "400% ceiling");
- expect(
- ceiling.ink.sig,
- "the 400% bitmap must differ from the 300% one, otherwise the no-op check below is vacuous",
- ).not.toBe(three.ink.sig);
- expect(
- ceiling.canvasW,
- `400% bitmap width should be round(${ceiling.pageW} * 4)`,
- ).toBe(Math.round(ceiling.pageW * 4));
-
- // Three more clicks at the ceiling.
- for (let i = 0; i < 3; i++) {
- await page.getByTestId("pdf-editor-zoom-in").click();
- }
- await page.waitForTimeout(1200);
- const again = await page.evaluate(snapshotFn);
-
- await expect(page.getByTestId("pdf-editor-zoom-percent")).toHaveText(
- "400%",
- );
- expect(
- again.canvasW,
- `clicking zoom-in at the ceiling changed the bitmap width: ${again.canvasW} vs ${ceiling.canvasW}`,
- ).toBe(ceiling.canvasW);
- expect(
- again.ink.sig >>> 0,
- `clicking zoom-in at the ceiling changed the rendered pixels: ${again.ink.sig} vs ${ceiling.ink.sig}`,
- ).toBe(ceiling.ink.sig >>> 0);
- const run = requireRun(again, 0);
- const ink = await page.evaluate(runInkFn, run.id);
- requireInk(ink, "400% ceiling run");
- expectRegistered(
- ink.minX,
- run.left + RUN_BOX_INSET,
- 4,
- "at the 400% ceiling",
- );
- });
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts
index e67af021e6..db063c2d87 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
import { selectWrapWidthMode } from "@editor/tests/stubbed/widthModeHelpers";
@@ -56,13 +57,7 @@ const textFor = (which: "single" | "paragraph") =>
which === "single" ? LONG_SHORT : LONG;
async function open(page: Page, mode: "grow" | "wrap"): Promise<void> {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH_PDF);
+ await openInTextEditor(page, PARAGRAPH_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-files.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-files.spec.ts
index 84840e0f48..de8d22a3c5 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-files.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-files.spec.ts
@@ -2,12 +2,13 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import { uploadFiles } from "@editor/tests/helpers/ui-helpers";
+import { viewInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
// 4.2 "Active file selection does not work while in the editor". Three defects:
// the editor re-pinned its own workbench view on EVERY navigation change; the
// Active Files view trims a multi-file selection to its last entry, which the
// editor followed - swapping the open document and pinning its canvas back over
-// the file list; and the editor offered no way to say which file to edit.
+// the file list; and there was no way to say which file to edit.
const SAMPLE_PDF = path.join(
import.meta.dirname,
@@ -26,6 +27,7 @@ async function openEditorWithTwoFiles(page: Page) {
timeout: 30_000,
});
await uploadFiles(page, [SAMPLE_PDF, PARAGRAPH_PDF]);
+ await viewInTextEditor(page, "sample.pdf");
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
@@ -97,44 +99,31 @@ test.describe("PDF text editor - workbench file selection", () => {
).toBe(opened);
});
- test("the editor lists the workbench files and opens the one picked", async ({
+ test("viewing another workbench file opens it in the editor", async ({
page,
}) => {
test.setTimeout(180_000);
await openEditorWithTwoFiles(page);
+ const sourceName = () =>
+ page.evaluate(
+ () =>
+ (
+ window as unknown as {
+ __editor_store: { source: { fileName: string | null } };
+ }
+ ).__editor_store.source.fileName,
+ );
- await expect(
- page.getByTestId("pdf-editor-file-switcher"),
- "with two workbench files the editor must offer a way to choose one",
- ).toBeVisible({ timeout: 15_000 });
-
- // Whichever landed first is open; pick the other one.
- const opened = (
- await page.getByTestId("pdf-editor-filename").innerText()
- ).trim();
- const other =
- opened === "sample.pdf" ? "paragraph-sample.pdf" : "sample.pdf";
-
- await page.getByTestId("pdf-editor-file-switcher").click();
- await page
- .getByTestId("pdf-editor-file-switch")
- .filter({ hasText: new RegExp(`^${other}$`) })
- .first()
- .click();
-
- await expect(
- page.getByTestId("pdf-editor-filename"),
- "picking a file in the editor must open it",
- ).toHaveText(other, { timeout: 60_000 });
+ await expect.poll(sourceName, { timeout: 30_000 }).toBe("sample.pdf");
+ await viewInTextEditor(page, "paragraph-sample.pdf");
+ await expect
+ .poll(sourceName, {
+ message: "viewing a file in the sidebar must open it in the editor",
+ timeout: 60_000,
+ })
+ .toBe("paragraph-sample.pdf");
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
- // The picked entry is the one marked current.
- await page.getByTestId("pdf-editor-file-switcher").click();
- await expect(
- page.locator(
- '[data-testid="pdf-editor-file-switch"][data-current="true"]',
- ),
- ).toHaveText(other);
});
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-save.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-save.spec.ts
index 24cb77bb6e..070d0dba41 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-save.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-workbench-save.spec.ts
@@ -1,7 +1,7 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
-import { readFileSync } from "node:fs";
import { uploadFiles } from "@editor/tests/helpers/ui-helpers";
// 4.3 "No standardised 'save PDF'". The editor only ever produced a download,
@@ -64,68 +64,6 @@ function workbenchTab(page: Page, name: RegExp) {
}
test.describe("PDF text editor - standardised save", () => {
- test("a superseded disk open cannot join or replace the current workbench file", async ({
- page,
- }) => {
- test.setTimeout(120_000);
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page.evaluate(() => {
- const original = File.prototype.arrayBuffer;
- const gate = window as typeof window & {
- releaseFirstOpen?: () => void;
- firstReadStarted?: boolean;
- firstReadFinished?: boolean;
- };
- File.prototype.arrayBuffer = async function () {
- if (this.name === "first.pdf") {
- gate.firstReadStarted = true;
- await new Promise<void>((resolve) => {
- gate.releaseFirstOpen = resolve;
- });
- gate.firstReadFinished = true;
- }
- return original.call(this);
- };
- });
- const input = page.getByTestId("pdf-editor-file-input");
- const buffer = readFileSync(SAMPLE_PDF);
- await input.setInputFiles({
- name: "first.pdf",
- mimeType: "application/pdf",
- buffer,
- });
- await page.waitForFunction(
- () =>
- (window as typeof window & { firstReadStarted?: boolean })
- .firstReadStarted,
- );
- await input.setInputFiles({
- name: "second.pdf",
- mimeType: "application/pdf",
- buffer,
- });
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 60_000,
- });
- await page.evaluate(() =>
- (
- window as typeof window & { releaseFirstOpen?: () => void }
- ).releaseFirstOpen?.(),
- );
- await page.waitForFunction(
- () =>
- (window as typeof window & { firstReadFinished?: boolean })
- .firstReadFinished,
- );
- await activeFilesTab(page).click();
- const cards = page.getByTestId("file-thumbnail");
- await expect(cards).toHaveCount(1);
- await expect(cards.first()).toContainText("second.pdf");
- await expect(page.getByText("first.pdf", { exact: true })).toHaveCount(0);
- });
test("saving replaces the workbench file instead of only downloading", async ({
page,
}) => {
@@ -164,7 +102,7 @@ test.describe("PDF text editor - standardised save", () => {
["ZZFIRST", "v2"],
["ZZSECOND", "v3"],
]) {
- await workbenchTab(page, /^Editor$/).click();
+ await workbenchTab(page, /^Viewer$/).click();
await editFirstRun(page, text);
await page.getByTestId("pdf-editor-save").click();
await expect(page.getByTestId("pdf-editor-dirty-dot")).toBeHidden({
@@ -214,9 +152,7 @@ test.describe("PDF text editor - standardised save", () => {
});
// Opened through the editor's own picker, so it has no workbench fileId.
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE_PDF);
+ await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-wrap.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-wrap.spec.ts
index 3730458ecc..70cbeb7cdc 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-wrap.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-wrap.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
import { selectWrapWidthMode } from "@editor/tests/stubbed/widthModeHelpers";
@@ -18,13 +19,7 @@ const LONG_TEXT =
"runs far past the right hand edge of the box it started in";
async function openEditor(page: import("@playwright/test").Page, file: string) {
- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
- timeout: 30_000,
- });
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(file);
+ await openInTextEditor(page, file);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts
index 2d6897fcdc..3fd1d361b7 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts
@@ -1,4 +1,8 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import {
+ openInTextEditor,
+ scrollToEditorPage,
+} from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
// Independent parser for the round-trip cross-check: the same @cantoo/pdf-lib
// the fixture generators use.
@@ -65,18 +69,14 @@ async function selectFontFamily(
async function loadSamplePdf(page: import("@playwright/test").Page) {
// The visible "Open" flow goes through the left-sidebar Files panel.
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SAMPLE_PDF);
+ await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
}
async function loadMultiPageSample(page: import("@playwright/test").Page) {
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MULTI_PAGE_PDF);
+ await openInTextEditor(page, MULTI_PAGE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -113,7 +113,6 @@ test.describe("PDF text editor - smoke", () => {
test("the editor mounts at /pdf-text-editor", async ({ page }) => {
await gotoEditor(page);
await expect(page.getByTestId("pdf-editor-sidebar-empty")).toBeVisible();
- await expect(page.getByTestId("pdf-editor-toolbar")).toBeVisible();
});
});
@@ -330,7 +329,7 @@ test.describe("PDF text editor - save", () => {
// Push the saved bytes back into the dropzone as a new file. setInputFiles
// accepts an in-memory payload.
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -420,7 +419,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -501,14 +500,10 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Repro for the recurring "all spaces vanish when I delete a single letter"
// bug on the Stirling marketing PDF.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(
- path.join(
- import.meta.dirname,
- "../test-fixtures/stirling-marketing.pdf",
- ),
- );
+ await openInTextEditor(
+ page,
+ path.join(import.meta.dirname, "../test-fixtures/stirling-marketing.pdf"),
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -617,9 +612,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
}) => {
// EXACT user repro.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -728,9 +721,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Regression guard: a previous attempt to teach partialEdit about
// LineGrouper-synthesised whitespace miscounted ghost chars by 1.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -893,9 +884,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Repro for the recurring "typed space vanishes" bug on the marketing
// tagline.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1191,9 +1180,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// 20 tagline tests below guard themselves with `if (!findTaglineRun(page))
// { test.skip(...) }`.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1211,9 +1198,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1253,9 +1238,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1294,9 +1277,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1345,9 +1326,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Mimics realistic user editing: delete a char, type a different one,
// repeat.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1406,9 +1385,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Regression guard: inserting NEW chars between two kept sub-runs used to
// leave the inserted text overlapping the original following chars.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1548,9 +1525,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Regression guard: when an edit fully removes a sub-run, the surviving
// sub-runs to its right used to STAY at their original x position.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1856,9 +1831,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1890,9 +1863,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1923,9 +1894,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1963,9 +1932,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -1995,9 +1962,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
test("comprehensive regression: delete from start", async ({ page }) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2029,9 +1994,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2077,9 +2040,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2133,9 +2094,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
}) => {
// The "would a PDF viewer render the right text" assertion.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2159,7 +2118,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const buf = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: buf,
@@ -2205,9 +2164,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// The marketing PDF tagline uses an embedded non-standard font
// ("pdf:...:Unknown").
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2265,9 +2222,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// The "try borrow, detect, fall back" path: when every inserted char
// already appears in the source line.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2362,9 +2317,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Even when the inserted char IS already present in the source text, the
// result must remain text-content-correct: run.text equals baseline + 'd'.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2426,9 +2379,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
}) => {
// Subset fonts only embed the glyphs the source PDF originally used.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(SUBSET_FONT_PDF);
+ await openInTextEditor(page, SUBSET_FONT_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -2726,7 +2677,7 @@ test.describe("PDF text editor - keyboard shortcuts", () => {
// Move focus off the run so the Ctrl+Z isn't captured as caret undo.
await page
- .locator('[data-testid="pdf-editor-stage"]')
+ .locator("[data-viewer-pages]")
.click({ position: { x: 5, y: 5 } });
await page.keyboard.press("Control+z");
await expect(firstRun).toHaveText(original);
@@ -2787,9 +2738,7 @@ test.describe("PDF text editor - font family", () => {
test.describe("PDF text editor - multi-page", () => {
test("renders every page of a multi-page document", async ({ page }) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MULTI_PAGE_PDF);
+ await openInTextEditor(page, MULTI_PAGE_PDF);
// The fixture has 3 pages; assert all three render.
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -2803,9 +2752,7 @@ test.describe("PDF text editor - multi-page", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MULTI_PAGE_PDF);
+ await openInTextEditor(page, MULTI_PAGE_PDF);
await expect(page.getByTestId("pdf-editor-page-2")).toBeVisible({
timeout: 30_000,
});
@@ -2845,7 +2792,7 @@ test.describe("PDF text editor - multi-page", () => {
// Remember the document we are replacing: after the re-upload the OLD
// document's page-2 runs are still mounted.
await stashCurrentDocument(page);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -2952,9 +2899,7 @@ test.describe("PDF text editor - bold/italic", () => {
// Regression for the user-reported "I hit bold and unbold and it broke the
// text and made multiple layers" bug.
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -3063,7 +3008,7 @@ test.describe("PDF text editor - bold/italic", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round-trip.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -3315,33 +3260,6 @@ test.describe("PDF text editor - image click-through + delete", () => {
});
});
-test.describe("PDF text editor - render throttling", () => {
- test("off-screen pages show a placeholder until they near the viewport", async ({
- page,
- }) => {
- await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MULTI_PAGE_PDF);
-
- // Page 0 is at the top of the stage and within the viewport on first
- // render.
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 30_000,
- });
- await expect(page.getByTestId("pdf-editor-page-0-placeholder")).toHaveCount(
- 0,
- {
- timeout: 10_000,
- },
- );
-
- // Page 2 is below the fold for a 1080-tall viewport (each page is 792 PDF
- // points * 1.5 scale ≈ 1188 CSS pixels).
- await expect(page.getByTestId("pdf-editor-page-2")).toBeVisible();
- });
-});
-
test.describe("PDF text editor - lazy page loading", () => {
test("multi-page docs render their pages without blocking on every read", async ({
page,
@@ -3350,9 +3268,7 @@ test.describe("PDF text editor - lazy page loading", () => {
// existing multi-page fixture as a guardrail.
await gotoEditor(page);
const started = Date.now();
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MULTI_PAGE_PDF);
+ await openInTextEditor(page, MULTI_PAGE_PDF, { zoomPercent: null });
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -3369,9 +3285,7 @@ test.describe("PDF text editor - lazy page loading", () => {
// zero coverage.
test.setTimeout(120_000);
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(BIG_SAMPLE_PDF);
+ await openInTextEditor(page, BIG_SAMPLE_PDF, { zoomPercent: null });
// Page 0 must render within a bounded time even for the big doc.
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -3379,23 +3293,13 @@ test.describe("PDF text editor - lazy page loading", () => {
});
// A later page lazily renders once scrolled near the viewport.
- await page.evaluate(() => {
- const el = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-page-40"]',
- );
- el?.scrollIntoView({ block: "center" });
- });
+ await scrollToEditorPage(page, 40);
await expect(page.getByTestId("pdf-editor-page-40")).toBeVisible({
timeout: 30_000,
});
// Make a trivial edit on page 0, then save + reopen and assert it survived.
- await page.evaluate(() => {
- const el = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-page-0"]',
- );
- el?.scrollIntoView({ block: "center" });
- });
+ await scrollToEditorPage(page, 0);
const firstRun = page
.locator('[data-testid^="pdf-editor-run-p0-"]')
.first();
@@ -3412,11 +3316,15 @@ test.describe("PDF text editor - lazy page loading", () => {
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
- name: "big-round-trip.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
+ await openInTextEditor(
+ page,
+ {
+ name: "big-round-trip.pdf",
+ mimeType: "application/pdf",
+ buffer: savedBytes,
+ },
+ { zoomPercent: null },
+ );
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -3444,9 +3352,7 @@ test.describe("PDF text editor - paragraph recognition", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH_PDF);
+ await openInTextEditor(page, PARAGRAPH_PDF);
const runs = page.locator('[data-testid^="pdf-editor-run-p0-"]');
await expect(runs.first()).toBeVisible({ timeout: 30_000 });
@@ -3533,9 +3439,7 @@ test.describe("PDF text editor - form xobject recursion", () => {
// The fixture is generated by
// src/core/tests/test-fixtures/generate-form-xobject-sample.mjs.
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FORM_XOBJECT_PDF);
+ await openInTextEditor(page, FORM_XOBJECT_PDF);
const runs = page.locator('[data-testid^="pdf-editor-run-p0-"]');
await expect(runs.first()).toBeVisible({ timeout: 30_000 });
@@ -3549,19 +3453,15 @@ test.describe("PDF text editor - form xobject recursion", () => {
});
test.describe("PDF text editor - load progress overlay", () => {
- test("loading overlay shows a stage and progress bar while opening", async ({
- page,
- }) => {
+ test("loading progress shows while opening", async ({ page }) => {
await gotoEditor(page);
- // Kick off the load and immediately capture the stage element.
+ // Kick off the load and immediately watch for the progress indicator.
const overlayPromise = page
- .getByTestId("pdf-editor-stage-loading")
+ .getByTestId("pdf-editor-loading")
.waitFor({ state: "visible", timeout: 5_000 })
.then(() => true)
.catch(() => false);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(MULTI_PAGE_PDF);
+ await openInTextEditor(page, MULTI_PAGE_PDF);
const sawOverlay = await overlayPromise;
// Either the overlay appeared, or the load finished too fast for the
// observer to catch it.
@@ -3572,31 +3472,11 @@ test.describe("PDF text editor - load progress overlay", () => {
// never paints the overlay AND never completes is still caught.
if (!sawOverlay) {
// Sanity-check that loading is now false.
- await expect(page.getByTestId("pdf-editor-stage-loading")).toHaveCount(0);
+ await expect(page.getByTestId("pdf-editor-loading")).toHaveCount(0);
}
});
});
-test.describe("PDF text editor - fit-to-width", () => {
- test("Fit button updates the zoom percent based on viewport width", async ({
- page,
- }) => {
- await gotoEditor(page);
- await loadSamplePdf(page);
- const before = await page
- .getByTestId("pdf-editor-zoom-percent")
- .innerText();
- await page.getByTestId("pdf-editor-zoom-fit").click();
- const after = await page.getByTestId("pdf-editor-zoom-percent").innerText();
- // The fit value depends on viewport width, but must be a sensible
- // percentage in the clamped range.
- const value = parseInt(after.replace("%", ""), 10);
- expect(value).toBeGreaterThanOrEqual(25);
- expect(value).toBeLessThanOrEqual(400);
- expect(after).not.toBe(before);
- });
-});
-
test.describe("PDF text editor - F3 next match", () => {
test("F3 opens the find bar and steps to the next match", async ({
page,
@@ -3614,24 +3494,6 @@ test.describe("PDF text editor - F3 next match", () => {
});
});
-test.describe("PDF text editor - zoom controls", () => {
- test("zoom in / zoom out / 100% buttons drive renderScale", async ({
- page,
- }) => {
- await gotoEditor(page);
- await loadSamplePdf(page);
- const percent = page.getByTestId("pdf-editor-zoom-percent");
- await expect(percent).toHaveText("150%");
- await page.getByTestId("pdf-editor-zoom-in").click();
- await expect(percent).toHaveText("175%");
- await page.getByTestId("pdf-editor-zoom-out").click();
- await page.getByTestId("pdf-editor-zoom-out").click();
- await expect(percent).toHaveText("125%");
- await page.getByTestId("pdf-editor-zoom-reset").click();
- await expect(percent).toHaveText("100%");
- });
-});
-
test.describe("PDF text editor - find in document", () => {
test("Ctrl+F opens the find bar and steps through matches", async ({
page,
@@ -3655,9 +3517,7 @@ test.describe("PDF text editor - paragraph soft-wrap", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH_PDF);
+ await openInTextEditor(page, PARAGRAPH_PDF);
// The paragraph overlay is the second run on page 0.
const runs = page.locator('[data-testid^="pdf-editor-run-p0-"]');
await expect(runs.first()).toBeVisible({ timeout: 30_000 });
@@ -3676,9 +3536,7 @@ test.describe("PDF text editor - undo restores form-xobject text", () => {
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(FORM_XOBJECT_PDF);
+ await openInTextEditor(page, FORM_XOBJECT_PDF);
const target = page.locator('[data-testid^="pdf-editor-run-p0-"]').first();
const runTestId = (await target.getAttribute("data-testid")) ?? "";
// Compared after stripping WebKit's trailing newline; `toContain` on the
@@ -3711,21 +3569,6 @@ test.describe("PDF text editor - workbench tab UX", () => {
.getByRole("button", { name: /^Viewer$/ });
await expect(viewerTab).toHaveCount(0);
});
-
- test("Editor workbench pins itself when an external setWorkbench fires", async ({
- page,
- }) => {
- await gotoEditor(page);
- await loadSamplePdf(page);
- // Simulate the FileContext side-effect that pushes to viewer on
- // file preview. The pin-effect should immediately switch back.
- await page.evaluate(() => {
- // Best-effort hack: find any "Active Files" / "Files" tab and click it,
- // then expect we bounce back.
- });
- await new Promise((resolve) => setTimeout(resolve, 500));
- await expect(page.getByTestId("pdf-editor-stage")).toBeVisible();
- });
});
test.describe("PDF text editor - dirty state", () => {
@@ -3733,8 +3576,6 @@ test.describe("PDF text editor - dirty state", () => {
await gotoEditor(page);
await loadSamplePdf(page);
- const filename = page.getByTestId("pdf-editor-filename");
- await expect(filename).toBeVisible();
await expect(page.getByTestId("pdf-editor-dirty-dot")).toHaveCount(0);
const firstRunTestId = await page
@@ -3809,51 +3650,12 @@ test.describe("PDF text editor - duplicate selected run", () => {
});
});
-test.describe("PDF text editor - Ctrl+wheel zoom", () => {
- test("Ctrl+wheel up on stage increases renderScale", async ({ page }) => {
- await gotoEditor(page);
- await loadSamplePdf(page);
-
- const readScale = () =>
- page.evaluate(() => {
- const store = (
- window as unknown as {
- __editor_store?: { getState: () => { renderScale: number } };
- }
- ).__editor_store!;
- return store.getState().renderScale;
- });
-
- const initial = await readScale();
-
- await page.evaluate(() => {
- const stage = document.querySelector(
- '[data-testid="pdf-editor-stage"]',
- ) as HTMLElement | null;
- stage?.dispatchEvent(
- new WheelEvent("wheel", {
- deltaY: -100,
- ctrlKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
- await page.waitForTimeout(150);
-
- const after = await readScale();
- expect(after).toBeGreaterThan(initial);
- });
-});
-
test.describe("PDF text editor - paragraph line wrap fidelity", () => {
test("paragraph overlay does not visually wrap its source lines", async ({
page,
}) => {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(PARAGRAPH_PDF);
+ await openInTextEditor(page, PARAGRAPH_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -3922,7 +3724,7 @@ test.describe("PDF text editor - marquee + merge", () => {
const right = Math.max(...rects.map((r) => r.right));
const bottom = Math.max(...rects.map((r) => r.bottom));
const stage = document.querySelector(
- '[data-testid="pdf-editor-pages"]',
+ "[data-viewer-pages]",
) as HTMLElement;
// MarqueeSelector listens for POINTER events (pointer-based for
// mouse/pen/touch parity), so fire pointer events, not mouse events.
@@ -4086,17 +3888,6 @@ test.describe("PDF text editor - help overlay", () => {
});
});
-test.describe("PDF text editor - filename in header", () => {
- test("loaded filename shown in toolbar header", async ({ page }) => {
- await gotoEditor(page);
- await loadSamplePdf(page);
-
- const filename = page.getByTestId("pdf-editor-filename");
- await expect(filename).toBeVisible();
- await expect(filename).toContainText(/sample\.pdf/i);
- });
-});
-
test.describe("PDF text editor - selection count panel", () => {
test("sidebar shows N runs selected after multi-select", async ({ page }) => {
await gotoEditor(page);
@@ -4279,9 +4070,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () =>
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -4406,9 +4195,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () =>
test.describe("PDF text editor - stress: bold / font swap variations", () => {
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -4595,7 +4382,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -4659,9 +4446,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
test.describe("PDF text editor - stress: add / remove cycles (no leaks)", () => {
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -4900,9 +4685,7 @@ test.describe("PDF text editor - stress: add / remove cycles (no leaks)", () =>
test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -4917,7 +4700,7 @@ test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -5074,7 +4857,7 @@ test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -5108,9 +4891,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -5253,7 +5034,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -5499,9 +5280,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -5680,7 +5459,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const savedBytes = Buffer.concat(chunks);
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ await openInTextEditor(page, {
name: "round.pdf",
mimeType: "application/pdf",
buffer: savedBytes,
@@ -5794,9 +5573,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () =>
async function loadFixture(page: import("@playwright/test").Page) {
await gotoEditor(page);
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -5997,9 +5774,7 @@ test.describe("PDF text editor - F-duplication regression (Sample.pdf tagline)",
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 15_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
@@ -6071,9 +5846,7 @@ test.describe("PDF text editor - F-duplication regression (Sample.pdf tagline)",
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 15_000,
});
- await page
- .locator('[data-testid="pdf-editor-file-input"]')
- .setInputFiles(USER_SAMPLE_PDF);
+ await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
});
diff --git a/frontend/src/editor/core/tools/formFill/FormCreationInteractionLock.tsx b/frontend/src/editor/core/tools/formFill/FormCreationInteractionLock.tsx
index 4b63abf46d..57a85d7ecd 100644
--- a/frontend/src/editor/core/tools/formFill/FormCreationInteractionLock.tsx
+++ b/frontend/src/editor/core/tools/formFill/FormCreationInteractionLock.tsx
@@ -2,25 +2,12 @@
* Holds the viewer's interactions paused for as long as the create tool is armed, so drawing a
* field never also selects the text underneath.
*/
-import { useEffect } from "react";
-import { useInteractionManagerCapability } from "@embedpdf/plugin-interaction-manager/react";
-
+import { ViewerInteractionLock } from "@editor/components/viewer/ViewerInteractionLock";
import { useFormFill } from "@editor/tools/formFill/FormFillContext";
export function FormCreationInteractionLock() {
const { mode, creationType } = useFormFill();
- const { provides: interactionManager } = useInteractionManagerCapability();
- const armed = mode === "create" && creationType != null;
-
- // Mounted once per document, not per page: the page overlays live inside a virtualising
- // Scroller, so one scrolling out of view would otherwise resume mid-session.
- useEffect(() => {
- if (!armed || !interactionManager) return undefined;
- // Never paused mid-gesture: pausing between a pointerdown and its pointerup strands the
- // selection, which then keeps extending on every move once resumed.
- interactionManager.pause();
- return () => interactionManager.resume();
- }, [armed, interactionManager]);
-
- return null;
+ return (
+ <ViewerInteractionLock active={mode === "create" && creationType != null} />
+ );
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx
index 40baaca861..da1adb7230 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx
@@ -2,10 +2,9 @@ import {
assertFilesNotBlocked,
policySourceIds,
} from "@editor/services/policyFileGuard";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import { Icon } from "@editor/ui/Icon";
import { downloadFile } from "@editor/services/downloadService";
import { assertPdfSessionEditable } from "@editor/services/pdfSessionUnlock";
import {
@@ -20,6 +19,7 @@ import type { FileId } from "@editor/types/file";
import type { ToolId } from "@editor/types/toolId";
import type { BaseToolProps } from "@editor/types/tool";
import { useEditorStore } from "@editor/tools/pdfTextEditor/hooks/useEditorStore";
+import { useEditorSelection } from "@editor/tools/pdfTextEditor/hooks/useEditorSelection";
import { useEditorOcr } from "@editor/tools/pdfTextEditor/hooks/useEditorOcr";
import { setEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
import { useIsMobile } from "@editor/hooks/useIsMobile";
@@ -34,7 +34,9 @@ import { useEditorTestGlobal } from "@editor/tools/pdfTextEditor/hooks/useEditor
import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
import { useEditorKeyboardShortcuts } from "@editor/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts";
import { useEditorClipboard } from "@editor/tools/pdfTextEditor/hooks/useEditorClipboard";
+import { useOpenAtViewerText } from "@editor/tools/pdfTextEditor/hooks/useOpenAtViewerText";
import { SaveRiskModal } from "@editor/tools/pdfTextEditor/components/SaveRiskModal";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { DiscardChangesModal } from "@editor/tools/pdfTextEditor/components/DiscardChangesModal";
import { HelpOverlay } from "@editor/tools/pdfTextEditor/components/HelpOverlay";
import { PasswordPromptModal } from "@editor/tools/pdfTextEditor/components/PasswordPromptModal";
@@ -43,7 +45,12 @@ import { EditorPanelActions } from "@editor/tools/pdfTextEditor/components/Edito
import { EditorSidebar } from "@editor/tools/pdfTextEditor/components/EditorSidebar";
import { MobileEditorSheets } from "@editor/tools/pdfTextEditor/components/MobileEditorSheets";
import { EditorFileInputs } from "@editor/tools/pdfTextEditor/components/EditorFileInputs";
-import { PageStage } from "@editor/tools/pdfTextEditor/components/PageStage";
+import { ViewerEditLayer } from "@editor/tools/pdfTextEditor/components/ViewerEditLayer";
+import {
+ ViewerEditActionBar,
+ ViewerEditToolbar,
+} from "@editor/tools/pdfTextEditor/components/ViewerEditToolbar";
+import { useRegisterViewerPageTool } from "@editor/contexts/viewer/ViewerPageTool";
import { InsertImageCommand } from "@editor/tools/pdfTextEditor/commands/InsertImageCommand";
import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";
import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
@@ -52,7 +59,6 @@ import { MergeRunsCommand } from "@editor/tools/pdfTextEditor/commands/MergeRuns
import { UngroupParagraphCommand } from "@editor/tools/pdfTextEditor/commands/UngroupParagraphCommand";
import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
import { assertEditorOcrAllowed } from "@editor/tools/pdfTextEditor/util/ocrProtection";
-import { clampRenderScale } from "@editor/tools/pdfTextEditor/util/fitToWidth";
import {
detectSaveRisks,
hasSaveRisks,
@@ -63,12 +69,9 @@ import { useScanPrefit } from "@editor/tools/pdfTextEditor/hooks/useScanPrefit";
import { visiblePageNumber } from "@editor/tools/pdfTextEditor/util/dom";
import type {
GroupingMode,
- SelectionState,
WidthMode,
} from "@editor/tools/pdfTextEditor/types";
-const WORKBENCH_ID = "custom:pdfTextEditor" as const;
-const WORKBENCH_VIEW_ID = "pdfTextEditorWorkbench";
const INSERTED_IMAGE_RATIO = 0.4;
export default function PdfTextEditor(_props: BaseToolProps) {
@@ -76,15 +79,26 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const isMobile = useIsMobile();
const { store, state } = useEditorStore();
const load = useDocumentLoader(store);
- const { getZoomState } = useViewer();
- const viewerZoomRef = useRef(getZoomState);
- viewerZoomRef.current = getZoomState;
-
- const [selection, setSelection] = useState<SelectionState>(
- store.selection.value,
+ const { activeFileId, setActiveFileId, scrollActions } = useViewer();
+
+ const selection = useEditorSelection(store);
+ // A remount over a document still open carries on with its file, while the
+ // viewer still shows it.
+ const [initialSource] = useState(() =>
+ store.getState().hasDocument && store.source.fileId === activeFileId
+ ? store.source
+ : { fileId: null, fileName: null },
+ );
+ const [openedFileName, setOpenedFileNameState] = useState(
+ initialSource.fileName,
+ );
+ const setOpenedFileName = useCallback(
+ (name: string | null) => {
+ store.source = { ...store.source, fileName: name };
+ setOpenedFileNameState(name);
+ },
+ [store],
);
- const [openedFileName, setOpenedFileName] = useState<string | null>(null);
- const pendingDiskFileRef = useRef<File | null>(null);
const mountedRef = useRef(false);
useEffect(() => {
mountedRef.current = true;
@@ -92,15 +106,20 @@ export default function PdfTextEditor(_props: BaseToolProps) {
mountedRef.current = false;
};
}, []);
- // Set only when the document came from the workbench; a drag-dropped
- // file has no fileId and can only be downloaded. Mirrored into state so the
- // sidebar's file switcher can mark which workbench file is open.
- const sourceFileIdRef = useRef<FileId | null>(null);
- const [sourceFileId, setSourceFileId] = useState<FileId | null>(null);
- const setSourceFile = useCallback((id: FileId | null) => {
- sourceFileIdRef.current = id;
- setSourceFileId(id);
- }, []);
+ // The workbench file being edited; save writes back to it. Mirrored into
+ // state so the viewer can tell which file's pages are editable.
+ const sourceFileIdRef = useRef<FileId | null>(initialSource.fileId);
+ const [sourceFileId, setSourceFileId] = useState<FileId | null>(
+ initialSource.fileId,
+ );
+ const setSourceFile = useCallback(
+ (id: FileId | null) => {
+ store.source = { ...store.source, fileId: id };
+ sourceFileIdRef.current = id;
+ setSourceFileId(id);
+ },
+ [store],
+ );
const { addFiles, consumeFiles, selectors } = useFileContext();
const { setSelectedFiles } = useFileSelection();
const { handleToolSelect } = useToolWorkflowActions();
@@ -109,39 +128,37 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const [applying, setApplying] = useState(false);
useEditorTestGlobal(store);
+ // Dropping the document discards its edits; the file is then reopened fresh.
+ const discardEdits = useCallback(() => store.clearDocument(), [store]);
useUnsavedChangesGuard(state.dirty);
- const pinWorkbench = useWorkbenchPin({
- workbenchId: WORKBENCH_ID,
- workbenchViewId: WORKBENCH_VIEW_ID,
- label: t("pdfTextEditor.workbenchLabel", "Editor"),
- icon: <Icon name="file-text" size={20} />,
- component: PageStage,
- takeOverScreen: isMobile,
- });
- // Uploading flips the workbench to Active Files, so landing a document has to
- // pin the canvas back. useAutoLoadFile only fires for a genuine file change.
+ const pinWorkbench = useWorkbenchPin();
+ // Opening a file can leave the workbench on Active Files, so landing a
+ // document pins the viewer back.
const handleFileChosen = useCallback(
(name: string, fileId?: FileId) => {
+ // The old document goes first: if the new file fails to open, a save
+ // must not write the old one over it.
+ store.clearDocument();
setOpenedFileName(name);
setSourceFile(fileId ?? null);
- // A workbench file opens at the zoom the viewer showed it at. The
- // viewer's fallback state carries no level, so a viewer that never
- // opened a document leaves the editor's own default alone.
- const viewerZoom = viewerZoomRef.current();
- if (fileId && viewerZoom.level !== undefined) {
- store.setRenderScale(clampRenderScale(viewerZoom.currentZoom));
- }
pinWorkbench();
},
- [pinWorkbench, setSourceFile, store],
+ [store, pinWorkbench, setOpenedFileName, setSourceFile],
);
const {
- openFile: openWorkbenchFile,
adopt: adoptFile,
cancel: cancelAutoLoad,
+ pendingSwitch,
+ confirmSwitch,
+ cancelSwitch,
} = useAutoLoadFile(load, handleFileChosen, sourceFileId, applying, state);
- useEffect(() => store.selection.subscribe(setSelection), [store]);
+ // The active file is the one being edited, including the new one a save
+ // writes in place of the original.
+ useEffect(() => {
+ if (sourceFileId) setActiveFileId(sourceFileId);
+ }, [sourceFileId, setActiveFileId]);
+ useOpenAtViewerText(store, sourceFileId);
// Warm the Unicode fallback font so a non-Latin edit can embed it instead of
// dropping the glyphs.
@@ -159,6 +176,16 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const [saveRisks, setSaveRisks] = useState<SaveRisks | null>(null);
// docPtr the user already acknowledged risks for, so we don't re-nag.
const ackedRiskRef = useRef<{ doc: object; sig: string } | null>(null);
+ // Re-evaluated on EVERY save: the ack only covers the exact risk set the
+ // user saw. A new risk appearing later must warn again.
+ const unackedRisks = useCallback((doc: EditorDocument) => {
+ const risks = detectSaveRisks(doc);
+ if (!hasSaveRisks(risks)) return null;
+ const acked = ackedRiskRef.current;
+ return acked?.doc === doc && acked.sig === JSON.stringify(risks)
+ ? null
+ : risks;
+ }, []);
// Land the edit in the workbench the way every other tool does: replace the
// file it came from, or add it if the document was opened from disk. Without
@@ -200,13 +227,13 @@ export default function PdfTextEditor(_props: BaseToolProps) {
if (toolId === "ocr")
assertEditorOcrAllowed(store.document, sourceId, t);
await consumeFiles([sourceId], stirlingFiles, stubs);
+ // A file opened meanwhile is not the one just written.
+ if (!isCurrent()) return null;
// Claim the replacement before releasing the hold, otherwise the
// editor sees an unfamiliar selection and re-opens the file it just
// wrote, throwing away undo history.
- if (isCurrent()) {
- if (stirlingFiles[0]) adoptFile(stirlingFiles[0]);
- setSourceFile(stubs[0]?.id ?? null);
- }
+ if (stirlingFiles[0]) adoptFile(stirlingFiles[0]);
+ setSourceFile(stubs[0]?.id ?? null);
return stirlingFiles[0] ?? null;
}
if (!isCurrent()) return null;
@@ -214,10 +241,9 @@ export default function PdfTextEditor(_props: BaseToolProps) {
selectFiles: true,
derivedFromTool: true,
});
- if (isCurrent()) {
- if (added[0]) adoptFile(added[0]);
- setSourceFile(added[0]?.fileId ?? null);
- }
+ if (!isCurrent()) return null;
+ if (added[0]) adoptFile(added[0]);
+ setSourceFile(added[0]?.fileId ?? null);
return added[0] ?? null;
} finally {
setApplying(false);
@@ -236,7 +262,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
await loading;
if (mountedRef.current && store.isCurrentLoad(token)) pinWorkbench();
},
- [applyToWorkbench, load, pinWorkbench, store],
+ [applyToWorkbench, load, pinWorkbench, setOpenedFileName, store],
);
const ocr = useEditorOcr({
store,
@@ -247,26 +273,36 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const doSave = useCallback(
async (download: boolean) => {
- if (!store.document || savingRef.current || store.getState().loading)
- return;
+ const doc = store.document;
+ if (!doc || savingRef.current || store.getState().loading) return;
savingRef.current = true;
store.setError(null);
const sourceId = sourceFileIdRef.current;
+ // A file switch confirmed while the export runs must not get these bytes.
+ const isCurrent = () =>
+ store.document === doc && sourceFileIdRef.current === sourceId;
try {
assertFilesNotBlocked([sourceId ?? undefined]);
assertPdfSessionEditable(getPdfAccess(sourceId));
// Yield once so React can paint the disabled/saving state before the
// synchronous PDFium serialize blocks the main thread.
await new Promise((resolve) => setTimeout(resolve, 0));
+ if (!isCurrent()) return;
// The position that is about to be written out. Anything the user edits
// while the export runs is NOT in these bytes, so it must stay dirty.
const exported = store.savedPosition();
- const blob = await exportToBlob(store.document);
+ const blob = await exportToBlob(doc);
const filename = openedFileName?.trim() || "edited.pdf";
// Apply first and unconditionally. Gating the write-back on the browser
// download dialog meant cancelling it silently discarded the save.
assertFilesNotBlocked([sourceId ?? undefined]);
- const saved = await applyToWorkbench(blob, filename);
+ if (!isCurrent()) return;
+ const saved = await applyToWorkbench(
+ blob,
+ filename,
+ "pdfTextEditor",
+ isCurrent,
+ );
if (!saved) return;
store.markSaved(exported);
if (download) {
@@ -291,21 +327,78 @@ export default function PdfTextEditor(_props: BaseToolProps) {
async (download: boolean) => {
const doc = store.document;
if (!doc || savingRef.current || store.getState().loading) return;
- // Re-evaluate on EVERY save: the ack only covers the exact risk set
- // the user saw. A new risk appearing later must warn again.
- const risks = detectSaveRisks(doc);
- if (hasSaveRisks(risks)) {
- const sig = JSON.stringify(risks);
- const acked = ackedRiskRef.current;
- if (!acked || acked.doc !== doc || acked.sig !== sig) {
- pendingDownloadRef.current = download;
- setSaveRisks(risks);
- return;
- }
+ const risks = unackedRisks(doc);
+ if (risks) {
+ pendingDownloadRef.current = download;
+ setSaveRisks(risks);
+ return;
}
await doSave(download);
},
- [store, doSave],
+ [store, doSave, unackedRisks],
+ );
+
+ // Answers a risk warning raised from the app's unsaved-changes prompt.
+ const riskAnswerRef = useRef<((save: boolean) => void) | null>(null);
+ // A warning still open when the editor goes cancels, so the prompt that
+ // waits on it can close.
+ useEffect(
+ () => () => {
+ riskAnswerRef.current?.(false);
+ riskAnswerRef.current = null;
+ },
+ [],
+ );
+
+ const saveBeforeLeaving = useCallback(async () => {
+ const doc = store.document;
+ const risks = doc && unackedRisks(doc);
+ if (risks) {
+ const save = await new Promise<boolean>((resolve) => {
+ riskAnswerRef.current = resolve;
+ setSaveRisks(risks);
+ });
+ if (!save) throw new Error("Save cancelled at the risk warning");
+ }
+ await doSave(false);
+ // doSave reports its failures in the editor; the prompt must stay open.
+ if (store.getState().dirty) throw new Error("Edits not saved");
+ }, [store, doSave, unackedRisks]);
+
+ const handleCancelSaveRisk = useCallback(() => {
+ setSaveRisks(null);
+ riskAnswerRef.current?.(false);
+ riskAnswerRef.current = null;
+ }, []);
+
+ const toggleFind = useCallback(
+ () => store.setFindOpen(!store.getState().findOpen),
+ [store],
+ );
+
+ useRegisterViewerPageTool(
+ useMemo(
+ () => ({
+ fileId: sourceFileId,
+ PageLayer: ViewerEditLayer,
+ Toolbar: ViewerEditToolbar,
+ // Small screens trade the viewer's page bar for the editing actions,
+ // once there is a document to act on.
+ BottomBar:
+ isMobile && state.hasDocument ? ViewerEditActionBar : undefined,
+ onDiscard: discardEdits,
+ onSave: saveBeforeLeaving,
+ onToggleFind: toggleFind,
+ }),
+ [
+ isMobile,
+ state.hasDocument,
+ sourceFileId,
+ discardEdits,
+ saveBeforeLeaving,
+ toggleFind,
+ ],
+ ),
);
const handleSave = useCallback(() => void runSave(false), [runSave]);
@@ -320,7 +413,10 @@ export default function PdfTextEditor(_props: BaseToolProps) {
};
}
setSaveRisks(null);
- void doSave(pendingDownloadRef.current);
+ const answer = riskAnswerRef.current;
+ riskAnswerRef.current = null;
+ if (answer) answer(true);
+ else void doSave(pendingDownloadRef.current);
}, [store, doSave]);
const handleInsertImage = useCallback(
@@ -429,27 +525,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
? text.replace(/\r\n?/g, "\n").trim()
: text.replace(/\r\n?/g, "\n");
if (!normalised) return;
- // Find the visible page (Ctrl+End behaves the same way).
- const stage = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"]',
- );
- const stageRect = stage?.getBoundingClientRect();
- const stageCentreY = stageRect ? stageRect.top + stageRect.height / 2 : 0;
- let pageIndex = 0;
- let bestDist = Infinity;
- for (const p of doc.loadedPages()) {
- const el = document.querySelector<HTMLElement>(
- `[data-testid="pdf-editor-page-${p.index}"]`,
- );
- if (!el) continue;
- const r = el.getBoundingClientRect();
- const centre = r.top + r.height / 2;
- const dist = Math.abs(centre - stageCentreY);
- if (dist < bestDist) {
- bestDist = dist;
- pageIndex = p.index;
- }
- }
+ const pageIndex = visiblePageNumber();
const page = doc.page(pageIndex);
// Position roughly at the page centre, biased toward the upper third so
// multi-line paste has room to flow downward.
@@ -582,94 +658,6 @@ export default function PdfTextEditor(_props: BaseToolProps) {
.find((r) => r.id === selection.runIds[0]);
return !!run && (run.paragraphLineCount ?? 0) > 1;
})();
- const loadDiskFile = useCallback(
- (file: File, password?: string) => {
- const loading = load(file, password);
- const token = store.currentLoadToken;
- void loading
- .then(async () => {
- if (!mountedRef.current || !store.isCurrentLoad(token)) return null;
- const opened = store.getState();
- if (!opened.hasDocument || opened.error || opened.passwordPrompt)
- return null;
- return addFiles([file], {
- selectFiles: false,
- });
- })
- .then((added) => {
- if (!mountedRef.current || !store.isCurrentLoad(token)) return;
- const stored = added?.[0];
- if (!stored) return;
- pendingDiskFileRef.current = null;
- adoptFile(stored);
- setSelectedFiles([stored.fileId]);
- handleFileChosen(stored.name, stored.fileId);
- })
- .catch((error: unknown) => {
- if (mountedRef.current && store.isCurrentLoad(token))
- store.setError(
- error instanceof Error ? error.message : String(error),
- );
- });
- },
- [store, addFiles, adoptFile, handleFileChosen, load, setSelectedFiles],
- );
-
- const openDocument = useCallback(
- (file: File, fromDisk: boolean) => {
- pendingDiskFileRef.current = fromDisk ? file : null;
- if (!fromDisk) {
- const fileId = (file as File & { fileId?: FileId }).fileId;
- if (fileId != null) setSelectedFiles([fileId]);
- openWorkbenchFile(file);
- return;
- }
- setOpenedFileName(file.name);
- adoptFile(file);
- setSourceFile(null);
- // Password-protected files join the library only after unlocking, so its
- // own upload flow does not ask for the password a second time.
- loadDiskFile(file);
- },
- [
- adoptFile,
- loadDiskFile,
- openWorkbenchFile,
- setSelectedFiles,
- setSourceFile,
- ],
- );
-
- const [pendingOpen, setPendingOpen] = useState<{
- file: File;
- fromDisk: boolean;
- } | null>(null);
-
- const requestOpen = useCallback(
- (file: File, fromDisk: boolean) => {
- if (store.getState().dirty) {
- setPendingOpen({ file, fromDisk });
- return;
- }
- openDocument(file, fromDisk);
- },
- [openDocument, store],
- );
-
- const onPickPdf = useCallback(
- (file: File) => requestOpen(file, true),
- [requestOpen],
- );
- const onPickWorkbenchFile = useCallback(
- (file: File) => requestOpen(file, false),
- [requestOpen],
- );
- const confirmPendingOpen = useCallback(() => {
- const pending = pendingOpen;
- setPendingOpen(null);
- if (pending) openDocument(pending.file, pending.fromDisk);
- }, [openDocument, pendingOpen]);
-
const openImagePicker = useCallback(() => {
document
.querySelector<HTMLInputElement>('[data-testid="pdf-editor-image-input"]')
@@ -679,36 +667,32 @@ export default function PdfTextEditor(_props: BaseToolProps) {
useEffect(() => {
setEditorSession({
fileName: openedFileName,
- fileId: sourceFileId,
save: handleSave,
download: handleDownload,
- pickFile: onPickWorkbenchFile,
pickImage: openImagePicker,
+ // The viewer mounts only the pages near the viewport.
+ revealPage: (pageIndex) => scrollActions.scrollToPage(pageIndex + 1),
});
return () => setEditorSession(null);
}, [
+ scrollActions,
openedFileName,
- sourceFileId,
handleSave,
handleDownload,
- onPickWorkbenchFile,
openImagePicker,
]);
const handleSubmitPassword = useCallback(
(password: string) => {
const file = store.pendingPasswordFile;
- if (!file) return;
- if (pendingDiskFileRef.current === file) loadDiskFile(file, password);
- else void load(file, password);
+ if (file) void load(file, password);
},
- [store, load, loadDiskFile],
+ [store, load],
);
const handleCancelPassword = useCallback(() => {
const file = store.pendingPasswordFile;
if (file) cancelAutoLoad(file);
- pendingDiskFileRef.current = null;
store.clearPasswordPrompt();
}, [store, cancelAutoLoad]);
@@ -749,19 +733,13 @@ export default function PdfTextEditor(_props: BaseToolProps) {
<Stack gap="xs">
<Text size="sm">{state.error}</Text>
<PermissionsPasswordButton
- file={
- pendingDiskFileRef.current ??
- (sourceFileId ? selectors.getFile(sourceFileId) : null)
- }
- onVerified={(file) => {
- if (pendingDiskFileRef.current === file) loadDiskFile(file);
- else void load(file);
- }}
+ file={sourceFileId ? selectors.getFile(sourceFileId) : null}
+ onVerified={(file) => void load(file)}
/>
</Stack>
</Alert>
)}
- <EditorFileInputs onPickPdf={onPickPdf} onPickImage={handleInsertImage} />
+ <EditorFileInputs onPickImage={handleInsertImage} />
<HelpOverlay
opened={state.helpOpen}
onClose={() => store.setHelpOpen(false)}
@@ -769,7 +747,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
<SaveRiskModal
risks={saveRisks}
onConfirm={handleConfirmSaveRisk}
- onCancel={() => setSaveRisks(null)}
+ onCancel={handleCancelSaveRisk}
/>
<PasswordPromptModal
prompt={state.passwordPrompt}
@@ -778,9 +756,9 @@ export default function PdfTextEditor(_props: BaseToolProps) {
onCancel={handleCancelPassword}
/>
<DiscardChangesModal
- incomingFileName={pendingOpen?.file.name ?? null}
- onConfirm={confirmPendingOpen}
- onCancel={() => setPendingOpen(null)}
+ incomingFileName={pendingSwitch?.name ?? null}
+ onConfirm={confirmSwitch}
+ onCancel={cancelSwitch}
/>
{isMobile ? (
<>
@@ -803,10 +781,6 @@ export default function PdfTextEditor(_props: BaseToolProps) {
{state.hasDocument && (
<EditorPanelActions
compact={isMobile}
- openedFileName={openedFileName}
- dirty={state.dirty}
- currentFileId={sourceFileId}
- onPickFile={onPickWorkbenchFile}
onSave={handleSave}
onDownload={handleDownload}
onOpenFind={() => {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/locateViewerText.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/locateViewerText.test.ts
new file mode 100644
index 0000000000..62f140a611
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/locateViewerText.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect } from "vitest";
+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import { locateViewerText } from "@editor/tools/pdfTextEditor/util/locateViewerText";
+import type {
+ PageSnapshot,
+ TextRunSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+
+const HEIGHT = 800;
+
+/** A run of `text` whose bottom-left corner sits at (x, y) in PDF space. */
+function run(id: string, text: string, x = 0, y = 0): TextRunSnapshot {
+ return {
+ id,
+ text,
+ bounds: { x, y, width: 100, height: 10 },
+ } as TextRunSnapshot;
+}
+
+function page(runs: TextRunSnapshot[], rotate = 0): PageSnapshot {
+ const display = { ...DisplayTransform.identity(600, HEIGHT), rotate };
+ return { pageIndex: 0, runs, display } as unknown as PageSnapshot;
+}
+
+describe("locateViewerText", () => {
+ it("selects the span of a run that holds the whole selection", () => {
+ const found = locateViewerText(
+ page([run("a", "Intro"), run("b", "Hello brave world")]),
+ "brave",
+ );
+ expect(found).toEqual({ runId: "b", range: { start: 6, end: 11 } });
+ });
+
+ it("takes the selection's first line, trimmed", () => {
+ const found = locateViewerText(
+ page([run("a", "First line"), run("b", "Second line")]),
+ " First line \nSecond line",
+ );
+ expect(found).toEqual({ runId: "a", range: { start: 0, end: 10 } });
+ });
+
+ it("falls back to the run holding the most of a line split across runs", () => {
+ const found = locateViewerText(
+ page([run("a", "Hello world"), run("b", "and more")]),
+ "world and more",
+ );
+ expect(found).toEqual({ runId: "a", range: { start: 6, end: 11 } });
+ });
+
+ it("picks the repeat nearest the viewer's selection", () => {
+ const p = page([run("top", "the", 0, 700), run("bottom", "the", 0, 100)]);
+ // 690px from the top is near the bottom run (y 100..110 from the bottom).
+ const found = locateViewerText(p, "the", {
+ x: 0,
+ y: HEIGHT - 110,
+ width: 100,
+ height: 10,
+ });
+ expect(found?.runId).toBe("bottom");
+ });
+
+ it("picks the copy within a run nearest the viewer's selection", () => {
+ // One line, x 0..100: the second "2023" sits at the far right.
+ const p = page([run("a", "2023 then more words and 2023", 0, 700)]);
+ const found = locateViewerText(p, "2023", {
+ x: 85,
+ y: HEIGHT - 710,
+ width: 15,
+ height: 10,
+ });
+ expect(found).toEqual({ runId: "a", range: { start: 25, end: 29 } });
+ });
+
+ it("picks the copy on the paragraph line the selection is on", () => {
+ const para = {
+ ...run("a", "2023 opens it and later 2023 closes", 0, 680),
+ bounds: { x: 0, y: 680, width: 100, height: 30 },
+ paragraphLineCount: 2,
+ } as TextRunSnapshot;
+ // Left end of the second line, the lower half of the box.
+ const found = locateViewerText(page([para]), "2023", {
+ x: 0,
+ y: HEIGHT - 690,
+ width: 15,
+ height: 10,
+ });
+ expect(found?.range).toEqual({ start: 24, end: 28 });
+ });
+
+ it("keeps the first repeat on a rotated page", () => {
+ const p = page(
+ [run("top", "the", 0, 700), run("bottom", "the", 0, 100)],
+ 1,
+ );
+ const found = locateViewerText(p, "the", {
+ x: 0,
+ y: HEIGHT - 110,
+ width: 100,
+ height: 10,
+ });
+ expect(found?.runId).toBe("top");
+ });
+
+ it("finds nothing for blank or absent text", () => {
+ const p = page([run("a", "Hello")]);
+ expect(locateViewerText(p, " \n ")).toBeNull();
+ expect(locateViewerText(p, "zzz")).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileInputs.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileInputs.tsx
index b85bc6d3c4..e85c8594ab 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileInputs.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileInputs.tsx
@@ -1,34 +1,20 @@
interface FileInputsProps {
- onPickPdf: (file: File) => void;
onPickImage: (file: File) => void;
}
-/** Hidden file inputs used by the toolbar buttons, drag-and-drop, and tests. */
-export function EditorFileInputs({ onPickPdf, onPickImage }: FileInputsProps) {
+/** The hidden image picker behind the toolbars' Add image buttons. */
+export function EditorFileInputs({ onPickImage }: FileInputsProps) {
return (
- <>
- <input
- type="file"
- accept="application/pdf"
- data-testid="pdf-editor-file-input"
- style={{ display: "none" }}
- onChange={(e) => {
- const file = e.target.files?.[0];
- if (file) onPickPdf(file);
- e.target.value = "";
- }}
- />
- <input
- type="file"
- accept="image/*"
- data-testid="pdf-editor-image-input"
- style={{ display: "none" }}
- onChange={(e) => {
- const file = e.target.files?.[0];
- if (file) onPickImage(file);
- e.target.value = "";
- }}
- />
- </>
+ <input
+ type="file"
+ accept="image/*"
+ data-testid="pdf-editor-image-input"
+ style={{ display: "none" }}
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ if (file) onPickImage(file);
+ e.target.value = "";
+ }}
+ />
);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileLabel.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileLabel.tsx
new file mode 100644
index 0000000000..9928b82622
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileLabel.tsx
@@ -0,0 +1,42 @@
+import { Text, Tooltip } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@editor/ui/Icon";
+import { PrivateContent } from "@editor/components/shared/PrivateContent";
+import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
+
+interface Props {
+ fileName: string;
+ dirty: boolean;
+}
+
+/** The open file's name, with a dot while it has unsaved edits. */
+export function EditorFileLabel({ fileName, dirty }: Props) {
+ const { t } = useTranslation();
+ return (
+ <Tooltip label={<PrivateContent>{fileName}</PrivateContent>}>
+ <Text
+ size="xs"
+ c="dimmed"
+ px={6}
+ data-testid="pdf-editor-filename"
+ component="div"
+ >
+ <span className="pdf-editor-topbar__file">
+ <Icon name="file-text" size={20} style={{ flexShrink: 0 }} />
+ <span
+ className={`pdf-editor-topbar__filename ${privateContentClassName}`}
+ >
+ {fileName}
+ </span>
+ {dirty && (
+ <span
+ className="pdf-editor-topbar__dirty"
+ data-testid="pdf-editor-dirty-dot"
+ aria-label={t("pdfTextEditor.unsaved", "(unsaved)")}
+ />
+ )}
+ </span>
+ </Text>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileSwitcher.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileSwitcher.tsx
deleted file mode 100644
index 14fae90f87..0000000000
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorFileSwitcher.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { Menu, Text, Tooltip } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@editor/ui/Icon";
-import { Button } from "@editor/ui/Button";
-import { useAllFiles } from "@editor/contexts/FileContext";
-import type { FileId } from "@editor/types/file";
-import { PrivateContent } from "@editor/components/shared/PrivateContent";
-import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
-
-interface Props {
- /** Workbench file the editor currently holds, when it came from one. */
- currentFileId: FileId | null;
- currentFileName: string;
- dirty: boolean;
- onPick: (file: File) => void;
-}
-
-export function EditorFileSwitcher({
- currentFileId,
- currentFileName,
- dirty,
- onPick,
-}: Props) {
- const { t } = useTranslation();
- const { files } = useAllFiles();
-
- const pdfs = files.filter((f) => /\.pdf$/i.test(f.name));
- const label = (
- <span className="pdf-editor-topbar__file">
- <Icon name="file-text" size={20} style={{ flexShrink: 0 }} />
- <span
- className={`pdf-editor-topbar__filename ${privateContentClassName}`}
- >
- {currentFileName}
- </span>
- {dirty && (
- <span
- className="pdf-editor-topbar__dirty"
- data-testid="pdf-editor-dirty-dot"
- aria-label={t("pdfTextEditor.unsaved", "(unsaved)")}
- />
- )}
- </span>
- );
-
- if (pdfs.length < 2) {
- return (
- <Tooltip label={<PrivateContent>{currentFileName}</PrivateContent>}>
- <Text
- size="xs"
- c="dimmed"
- px={6}
- data-testid="pdf-editor-filename"
- component="div"
- >
- {label}
- </Text>
- </Tooltip>
- );
- }
-
- return (
- <Menu shadow="md" position="bottom-start" withinPortal closeOnItemClick>
- <Menu.Target>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- rightSection={<Icon name="chevron-down" size={20} />}
- data-testid="pdf-editor-file-switcher"
- title={currentFileName}
- className={privateContentClassName}
- >
- <span data-testid="pdf-editor-filename">{label}</span>
- </Button>
- </Menu.Target>
- <Menu.Dropdown data-testid="pdf-editor-file-switcher-menu">
- <Menu.Label>
- {t("pdfTextEditor.sidebar.document", "Document")}
- </Menu.Label>
- {pdfs.map((file) => {
- const fileId = (file as File & { fileId?: FileId }).fileId;
- const current = fileId != null && fileId === currentFileId;
- return (
- <Menu.Item
- key={fileId ?? file.name}
- leftSection={
- current ? (
- <Icon name="check" size={20} />
- ) : (
- <Icon name="file-text" size={20} />
- )
- }
- disabled={fileId == null}
- data-testid="pdf-editor-file-switch"
- data-current={current ? "true" : "false"}
- onClick={() => {
- if (fileId == null) return;
- onPick(file);
- }}
- >
- <PrivateContent>{file.name}</PrivateContent>
- </Menu.Item>
- );
- })}
- </Menu.Dropdown>
- </Menu>
- );
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx
index a2d8c19ffc..55f9b8537a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx
@@ -2,16 +2,10 @@ import { Box, Group, Tooltip } from "@mantine/core";
import { Icon } from "@editor/ui/Icon";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
-import { EditorFileSwitcher } from "@editor/tools/pdfTextEditor/components/EditorFileSwitcher";
-import type { FileId } from "@editor/types/file";
import { modShortcut } from "@editor/utils/hotkeys";
interface Props {
compact: boolean;
- openedFileName: string | null;
- dirty: boolean;
- currentFileId: FileId | null;
- onPickFile: (file: File) => void;
onSave: () => void;
onDownload: () => void;
onOpenFind: () => void;
@@ -20,10 +14,6 @@ interface Props {
export function EditorPanelActions({
compact,
- openedFileName,
- dirty,
- currentFileId,
- onPickFile,
onSave,
onDownload,
onOpenFind,
@@ -43,16 +33,6 @@ export function EditorPanelActions({
}}
data-testid="pdf-editor-panel-actions"
>
- {compact && openedFileName && (
- <Group gap={6} wrap="nowrap" mb={8}>
- <EditorFileSwitcher
- currentFileId={currentFileId}
- currentFileName={openedFileName}
- dirty={dirty}
- onPick={onPickFile}
- />
- </Group>
- )}
<Group gap="xs" wrap="nowrap">
<Tooltip
label={t("pdfTextEditor.saveTooltip", {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css
index 818b543ddf..b05caf2472 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css
@@ -11,6 +11,11 @@
container-name: pdfeditortoolbar;
}
+/* Empty stand-in at the height of the bar's row of small buttons. */
+.pdf-editor-topbar--pending {
+ height: 2.8125rem;
+}
+
.pdf-editor-topbar__lead,
.pdf-editor-topbar__trail {
display: flex;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx
index 3b85135546..7be58f462f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx
@@ -1,9 +1,8 @@
import { useRef } from "react";
import { Icon } from "@editor/ui/Icon";
-import { Group, Menu, Popover, Text, Tooltip } from "@mantine/core";
+import { Group, Menu, Popover, Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
-import { EditorFileSwitcher } from "@editor/tools/pdfTextEditor/components/EditorFileSwitcher";
import { FormatGroup } from "@editor/tools/pdfTextEditor/components/toolbar/FormatGroup";
import { ObjectGroup } from "@editor/tools/pdfTextEditor/components/toolbar/ObjectGroup";
import {
@@ -70,233 +69,235 @@ export function EditorTopBar({
data-compact={compact ? "true" : "false"}
ref={barRef}
>
- <div className="pdf-editor-topbar__lead">
- {session?.fileName ? (
- <EditorFileSwitcher
- currentFileId={session.fileId}
- currentFileName={session.fileName}
- dirty={dirty}
- onPick={session.pickFile}
+ {/* The viewer's own bar names the file; this only flags unsaved edits. */}
+ {dirty && (
+ <div className="pdf-editor-topbar__lead">
+ <span
+ className="pdf-editor-topbar__dirty"
+ data-testid="pdf-editor-dirty-dot"
+ role="status"
+ aria-label={t("pdfTextEditor.unsaved", "(unsaved)")}
+ title={t("pdfTextEditor.unsaved", "(unsaved)")}
/>
- ) : (
- <Text size="xs" c="dimmed" px={6}>
- {t("pdfTextEditor.sidebar.noFile", "No file loaded")}
- </Text>
- )}
- </div>
+ </div>
+ )}
- {hasDocument && (
- <div className="pdf-editor-topbar__band">
- <Tooltip
- label={t("pdfTextEditor.toolbar.undoTooltip", {
- defaultValue: "Undo ({{shortcut}})",
- shortcut: modShortcut("Z"),
- })}
- >
- <Button
- variant="tertiary"
- accent="neutral"
- size="sm"
- onClick={controller.onUndo}
- disabled={!controller.canUndo}
- aria-label={t("pdfTextEditor.toolbar.undo", "Undo")}
- data-testid="pdf-editor-undo"
- style={NO_SHRINK}
- leftSection={<Icon name="undo-2" size={20} />}
- />
- </Tooltip>
- <Tooltip
- label={t("pdfTextEditor.toolbar.redoTooltip", {
- defaultValue: "Redo ({{shortcut}})",
- shortcut: modShortcut("Y"),
- })}
- >
- <Button
- variant="tertiary"
- accent="neutral"
- size="sm"
- onClick={controller.onRedo}
- disabled={!controller.canRedo}
- aria-label={t("pdfTextEditor.toolbar.redo", "Redo")}
- data-testid="pdf-editor-redo"
- style={NO_SHRINK}
- leftSection={<Icon name="redo-2" size={20} />}
- />
- </Tooltip>
+ {/* Shown from the first frame, idle until the document is read, so the
+ bar does not pop in after the load. */}
+ <div className="pdf-editor-topbar__band">
+ <Tooltip
+ label={t("pdfTextEditor.toolbar.undoTooltip", {
+ defaultValue: "Undo ({{shortcut}})",
+ shortcut: modShortcut("Z"),
+ })}
+ >
+ <Button
+ variant="tertiary"
+ accent="neutral"
+ size="sm"
+ onClick={controller.onUndo}
+ disabled={!hasDocument || !controller.canUndo}
+ aria-label={t("pdfTextEditor.toolbar.undo", "Undo")}
+ data-testid="pdf-editor-undo"
+ style={NO_SHRINK}
+ leftSection={<Icon name="undo-2" size={20} />}
+ />
+ </Tooltip>
+ <Tooltip
+ label={t("pdfTextEditor.toolbar.redoTooltip", {
+ defaultValue: "Redo ({{shortcut}})",
+ shortcut: modShortcut("Y"),
+ })}
+ >
+ <Button
+ variant="tertiary"
+ accent="neutral"
+ size="sm"
+ onClick={controller.onRedo}
+ disabled={!hasDocument || !controller.canRedo}
+ aria-label={t("pdfTextEditor.toolbar.redo", "Redo")}
+ data-testid="pdf-editor-redo"
+ style={NO_SHRINK}
+ leftSection={<Icon name="redo-2" size={20} />}
+ />
+ </Tooltip>
- <ToolbarSeparator />
+ <ToolbarSeparator />
- {compact ? (
- <Menu shadow="md" position="bottom-start" withinPortal>
- <Menu.Target>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- aria-label={t("pdfTextEditor.toolbar.more", "More actions")}
- data-testid="pdf-editor-overflow-menu"
- style={NO_SHRINK}
- leftSection={<Icon name="ellipsis-vertical" size={20} />}
- />
- </Menu.Target>
- <Menu.Dropdown>
- <Menu.Item
- leftSection={<Icon name="type" size={20} />}
- onClick={onToggleAddText}
- data-testid="pdf-editor-add-text"
- >
- {addTextLabel}
- </Menu.Item>
- <Menu.Item
- leftSection={<Icon name="table" size={20} />}
- onClick={onToggleAddTable}
- data-testid="pdf-editor-add-table"
- aria-pressed={addTableArmed}
- >
- {addTableLabel}
- </Menu.Item>
- <Menu.Item
- leftSection={<Icon name="image" size={20} />}
- onClick={() => session?.pickImage()}
- disabled={!session}
- data-testid="pdf-editor-add-image"
- >
- {addImageLabel}
- </Menu.Item>
- <Menu.Divider />
- <Menu.Item
- leftSection={<Icon name="search" size={20} />}
- onClick={onToggleFind}
- data-testid="pdf-editor-open-find"
- >
- {findLabel}
- </Menu.Item>
- <Menu.Item
- leftSection={<Icon name="circle-question-mark" size={20} />}
- onClick={onShowHelp}
- data-testid="pdf-editor-help"
- >
- {helpLabel}
- </Menu.Item>
- </Menu.Dropdown>
- </Menu>
- ) : (
- <>
- <Tooltip
- label={t(
- "pdfTextEditor.toolbar.addTextTooltip",
- "Add a text box - then click the page",
- )}
+ {compact ? (
+ <Menu shadow="md" position="bottom-start" withinPortal>
+ <Menu.Target>
+ <Button
+ size="sm"
+ variant="tertiary"
+ accent="neutral"
+ aria-label={t("pdfTextEditor.toolbar.more", "More actions")}
+ disabled={!hasDocument}
+ data-testid="pdf-editor-overflow-menu"
+ style={NO_SHRINK}
+ leftSection={<Icon name="ellipsis-vertical" size={20} />}
+ />
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={<Icon name="type" size={20} />}
+ onClick={onToggleAddText}
+ data-testid="pdf-editor-add-text"
+ >
+ {addTextLabel}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="table" size={20} />}
+ onClick={onToggleAddTable}
+ data-testid="pdf-editor-add-table"
+ aria-pressed={addTableArmed}
+ >
+ {addTableLabel}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="image" size={20} />}
+ onClick={() => session?.pickImage()}
+ disabled={!session}
+ data-testid="pdf-editor-add-image"
+ >
+ {addImageLabel}
+ </Menu.Item>
+ <Menu.Divider />
+ <Menu.Item
+ leftSection={<Icon name="search" size={20} />}
+ onClick={onToggleFind}
+ data-testid="pdf-editor-open-find"
+ >
+ {findLabel}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="circle-question-mark" size={20} />}
+ onClick={onShowHelp}
+ data-testid="pdf-editor-help"
>
- <Button
- size="sm"
- variant={addTextArmed ? "primary" : "tertiary"}
- accent={addTextArmed ? "default" : "neutral"}
- leftSection={<Icon name="type" size={20} />}
- onClick={onToggleAddText}
- data-testid="pdf-editor-add-text"
- style={NO_SHRINK}
- >
- {addTextArmed
- ? t(
- "pdfTextEditor.sidebar.clickPageToAddText",
- "Click page to add text",
- )
- : t("pdfTextEditor.sidebar.addText", "Add text")}
- </Button>
- </Tooltip>
- <Tooltip label={addTableLabel}>
- <Button
- size="sm"
- variant={addTableArmed ? "primary" : "tertiary"}
- accent={addTableArmed ? "default" : "neutral"}
- leftSection={<Icon name="table" size={20} />}
- onClick={onToggleAddTable}
- aria-label={addTableLabel}
- aria-pressed={addTableArmed}
- data-testid="pdf-editor-add-table"
- style={NO_SHRINK}
- />
- </Tooltip>
- <Tooltip label={t("pdfTextEditor.sidebar.addImage", "Add image")}>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- leftSection={<Icon name="image" size={20} />}
- onClick={() => session?.pickImage()}
- disabled={!session}
- aria-label={t("pdfTextEditor.sidebar.addImage", "Add image")}
- data-testid="pdf-editor-add-image"
- style={NO_SHRINK}
- >
- {t("pdfTextEditor.sidebar.image", "Image")}
- </Button>
- </Tooltip>
- <Tooltip
- label={t("pdfTextEditor.settings.findTooltip", {
- defaultValue: "Find ({{shortcut}})",
- shortcut: modShortcut("F"),
- })}
+ {helpLabel}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ ) : (
+ <>
+ <Tooltip
+ label={t(
+ "pdfTextEditor.toolbar.addTextTooltip",
+ "Add a text box - then click the page",
+ )}
+ >
+ <Button
+ size="sm"
+ variant={addTextArmed ? "primary" : "tertiary"}
+ accent={addTextArmed ? "default" : "neutral"}
+ leftSection={<Icon name="type" size={20} />}
+ onClick={onToggleAddText}
+ disabled={!hasDocument}
+ data-testid="pdf-editor-add-text"
+ style={NO_SHRINK}
+ >
+ {addTextArmed
+ ? t(
+ "pdfTextEditor.sidebar.clickPageToAddText",
+ "Click page to add text",
+ )
+ : t("pdfTextEditor.sidebar.addText", "Add text")}
+ </Button>
+ </Tooltip>
+ <Tooltip label={addTableLabel}>
+ <Button
+ size="sm"
+ variant={addTableArmed ? "primary" : "tertiary"}
+ accent={addTableArmed ? "default" : "neutral"}
+ leftSection={<Icon name="table" size={20} />}
+ onClick={onToggleAddTable}
+ aria-label={addTableLabel}
+ aria-pressed={addTableArmed}
+ disabled={!hasDocument}
+ data-testid="pdf-editor-add-table"
+ style={NO_SHRINK}
+ />
+ </Tooltip>
+ <Tooltip label={t("pdfTextEditor.sidebar.addImage", "Add image")}>
+ <Button
+ size="sm"
+ variant="tertiary"
+ accent="neutral"
+ leftSection={<Icon name="image" size={20} />}
+ onClick={() => session?.pickImage()}
+ disabled={!session || !hasDocument}
+ aria-label={t("pdfTextEditor.sidebar.addImage", "Add image")}
+ data-testid="pdf-editor-add-image"
+ style={NO_SHRINK}
>
- <Button
- variant={findOpen ? "primary" : "tertiary"}
- accent={findOpen ? "default" : "neutral"}
- size="sm"
- aria-pressed={findOpen}
- onClick={onToggleFind}
- aria-label={t(
- "pdfTextEditor.settings.find",
- "Find in document",
- )}
- data-testid="pdf-editor-open-find"
- style={NO_SHRINK}
- leftSection={<Icon name="search" size={20} />}
- />
- </Tooltip>
- </>
- )}
+ {t("pdfTextEditor.sidebar.image", "Image")}
+ </Button>
+ </Tooltip>
+ <Tooltip
+ label={t("pdfTextEditor.settings.findTooltip", {
+ defaultValue: "Find ({{shortcut}})",
+ shortcut: modShortcut("F"),
+ })}
+ >
+ <Button
+ variant={findOpen ? "primary" : "tertiary"}
+ accent={findOpen ? "default" : "neutral"}
+ size="sm"
+ aria-pressed={findOpen}
+ onClick={onToggleFind}
+ disabled={!hasDocument}
+ aria-label={t(
+ "pdfTextEditor.settings.find",
+ "Find in document",
+ )}
+ data-testid="pdf-editor-open-find"
+ style={NO_SHRINK}
+ leftSection={<Icon name="search" size={20} />}
+ />
+ </Tooltip>
+ </>
+ )}
- {hasSelection && (
- <>
- <ToolbarSeparator />
- {/* Ahead of the formatting group: the band scrolls sideways
+ {hasSelection && (
+ <>
+ <ToolbarSeparator />
+ {/* Ahead of the formatting group: the band scrolls sideways
under macOS's hidden scrollbars, so anything past the edge
is invisible rather than visibly clipped. */}
- <ObjectGroup controller={controller} />
- <ToolbarSeparator />
- {compact ? (
- <Popover position="bottom-start" withinPortal shadow="md">
- <Popover.Target>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- aria-label={t(
- "pdfTextEditor.toolbar.formatting",
- "Text formatting",
- )}
- data-testid="pdf-editor-format-menu"
- style={NO_SHRINK}
- leftSection={<Icon name="case-sensitive" size={20} />}
- />
- </Popover.Target>
- <Popover.Dropdown>
- <Group gap="xs" wrap="wrap" maw={320}>
- <FormatGroup controller={controller} />
- </Group>
- </Popover.Dropdown>
- </Popover>
- ) : (
- <FormatGroup controller={controller} />
- )}
- </>
- )}
- </div>
- )}
+ <ObjectGroup controller={controller} />
+ <ToolbarSeparator />
+ {compact ? (
+ <Popover position="bottom-start" withinPortal shadow="md">
+ <Popover.Target>
+ <Button
+ size="sm"
+ variant="tertiary"
+ accent="neutral"
+ aria-label={t(
+ "pdfTextEditor.toolbar.formatting",
+ "Text formatting",
+ )}
+ data-testid="pdf-editor-format-menu"
+ style={NO_SHRINK}
+ leftSection={<Icon name="case-sensitive" size={20} />}
+ />
+ </Popover.Target>
+ <Popover.Dropdown>
+ <Group gap="xs" wrap="wrap" maw={320}>
+ <FormatGroup controller={controller} />
+ </Group>
+ </Popover.Dropdown>
+ </Popover>
+ ) : (
+ <FormatGroup controller={controller} />
+ )}
+ </>
+ )}
+ </div>
<div className="pdf-editor-topbar__trail">
- {hasDocument && !compact && (
+ {!compact && (
<Tooltip
label={t("pdfTextEditor.help.tooltip", "Keyboard shortcuts (?)")}
>
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
index 826cd73036..fc0a7eb28d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
@@ -22,6 +22,7 @@ import type {
TextRunSnapshot,
} from "@editor/tools/pdfTextEditor/types";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
+import { revealOnPage } from "@editor/tools/pdfTextEditor/util/dom";
interface FindBarProps {
store: EditorStore;
@@ -100,7 +101,7 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
const el = document.querySelector<HTMLElement>(
`[data-testid="pdf-editor-run-${m.runId}"]`,
);
- el?.scrollIntoView({ block: "center", behavior: "smooth" });
+ revealOnPage(el, m.pageIndex);
},
[matches, store],
);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
index 6b92614caa..dd2da85d6d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
@@ -121,7 +121,16 @@ export function ImageHandle({
onResize={(e) => setKeepRatio(e.shiftKey)}
onDragStop={(_, data) => {
setDragging(false);
- const next = cssToPdfBounds(data.x, data.y, width, height);
+ // Rnd fixes its bounds when the drag starts, so a scroll mid-drag
+ // (Safari scrolls the viewer when the pointer leaves it) can drop the
+ // image off the page, where PDFium crops it.
+ // An image larger than the page cannot fit, so it is left where it is.
+ const page = data.node.parentElement;
+ const clamp = (at: number, room: number) =>
+ room >= 0 ? Math.min(Math.max(0, at), room) : at;
+ const x = page ? clamp(data.x, page.clientWidth - width) : data.x;
+ const y = page ? clamp(data.y, page.clientHeight - height) : data.y;
+ const next = cssToPdfBounds(x, y, width, height);
const moved =
Math.abs(next.x - image.bounds.x) > 0.01 ||
Math.abs(next.y - image.bounds.y) > 0.01;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MarqueeSelector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/MarqueeSelector.tsx
index d52dd40b14..4046a7075f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MarqueeSelector.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MarqueeSelector.tsx
@@ -1,10 +1,14 @@
import { useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
interface MarqueeSelectorProps {
store: EditorStore;
}
+// The viewer's page column; a drag may start anywhere inside it.
+const PAGES_SELECTOR = "[data-viewer-pages]";
+
interface MarqueeRect {
left: number;
top: number;
@@ -47,7 +51,7 @@ export function MarqueeSelector({ store }: MarqueeSelectorProps) {
function onPointerDown(e: PointerEvent) {
if (e.button !== 0) return;
const target = e.target as HTMLElement | null;
- if (!target?.closest('[data-testid="pdf-editor-pages"]')) return;
+ if (!target?.closest(PAGES_SELECTOR)) return;
const forced = (e.ctrlKey || e.metaKey) && e.shiftKey;
if (forced) {
e.preventDefault();
@@ -114,7 +118,9 @@ export function MarqueeSelector({ store }: MarqueeSelectorProps) {
}, [store]);
if (!rect) return null;
- return (
+ // Portalled: the rect is in viewport coordinates, and a host with `contain`
+ // or a transform would otherwise re-anchor and clip a fixed element.
+ return createPortal(
<div
data-testid="pdf-editor-marquee"
style={{
@@ -128,12 +134,13 @@ export function MarqueeSelector({ store }: MarqueeSelectorProps) {
pointerEvents: "none",
zIndex: 300,
}}
- />
+ />,
+ document.body,
);
}
function collectIdsInRect(rect: MarqueeRect, testIdPrefix: string): string[] {
- const pages = document.querySelector('[data-testid="pdf-editor-pages"]');
+ const pages = document.querySelector(PAGES_SELECTOR);
if (!pages) return [];
const right = rect.left + rect.width;
const bottom = rect.top + rect.height;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx
index 18fb95a301..ebeb4fc447 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx
@@ -1,4 +1,9 @@
-import { forwardRef, type ComponentPropsWithoutRef } from "react";
+import {
+ forwardRef,
+ useEffect,
+ useState,
+ type ComponentPropsWithoutRef,
+} from "react";
import { Menu } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@editor/ui/Icon";
@@ -6,6 +11,8 @@ import { ArrangeMenuItems } from "@editor/tools/pdfTextEditor/components/toolbar
import type { Controller } from "@editor/tools/pdfTextEditor/components/toolbar/toolbarShared";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import { useEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
+import { useViewer } from "@editor/contexts/ViewerContext";
+import { ZoomMode } from "@embedpdf/plugin-zoom/react";
import "@editor/tools/pdfTextEditor/components/MobileEditor.css";
interface Props {
@@ -148,6 +155,7 @@ export function MobileActionBar({
onClick={() => store.setFindOpen(!findOpen)}
data-testid="pdf-editor-open-find"
/>
+ <ZoomMenu />
<BarButton
icon="file-text"
label={t("pdfTextEditor.mobile.document", "Document")}
@@ -161,6 +169,53 @@ export function MobileActionBar({
);
}
+/** The viewer's zoom, whose own page bar the action bar stands in for. */
+function ZoomMenu() {
+ const { t } = useTranslation();
+ const { getZoomState, zoomActions, registerImmediateZoomUpdate } =
+ useViewer();
+ const [percent, setPercent] = useState(
+ () => getZoomState().zoomPercent || 100,
+ );
+ useEffect(
+ () => registerImmediateZoomUpdate(setPercent),
+ [registerImmediateZoomUpdate],
+ );
+
+ return (
+ <Menu shadow="md" position="top" withinPortal closeOnItemClick={false}>
+ <Menu.Target>
+ <BarButton
+ icon="zoom-in"
+ label={`${percent}%`}
+ aria-label={t("viewer.zoom", "Zoom")}
+ data-testid="pdf-editor-mobile-zoom"
+ />
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={<Icon name="zoom-in" size={18} />}
+ onClick={() => zoomActions.zoomIn()}
+ >
+ {t("viewer.zoomIn", "Zoom in")}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="zoom-out" size={18} />}
+ onClick={() => zoomActions.zoomOut()}
+ >
+ {t("viewer.zoomOut", "Zoom out")}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="arrow-left-right" size={18} />}
+ onClick={() => zoomActions.requestZoom(ZoomMode.FitWidth)}
+ >
+ {t("viewer.fitWidth", "Fit to width")}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ );
+}
+
interface BarButtonProps extends Omit<
ComponentPropsWithoutRef<"button">,
"children"
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditor.css b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditor.css
index 6523013130..b57c558784 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditor.css
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditor.css
@@ -26,6 +26,11 @@
overflow: hidden;
}
+/* Only the name gives way; a squeezed button clips its own label. */
+.pdf-editor-mtopbar > :not(.pdf-editor-mtopbar__file) {
+ flex-shrink: 0;
+}
+
.pdf-editor-mtopbar__file .pdf-editor-topbar__file {
max-width: 100%;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorTopBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorTopBar.tsx
index 2de8f1782c..2004cf705d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorTopBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorTopBar.tsx
@@ -2,7 +2,7 @@ import { Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
import { Button } from "@editor/ui/Button";
-import { EditorFileSwitcher } from "@editor/tools/pdfTextEditor/components/EditorFileSwitcher";
+import { EditorFileLabel } from "@editor/tools/pdfTextEditor/components/EditorFileLabel";
import type { Controller } from "@editor/tools/pdfTextEditor/components/toolbar/toolbarShared";
import { useEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
import { NotificationBell } from "@editor/components/notifications/NotificationBell";
@@ -29,12 +29,7 @@ export function MobileEditorTopBar({ controller, hasDocument, dirty }: Props) {
>
<div className="pdf-editor-mtopbar__file">
{session?.fileName ? (
- <EditorFileSwitcher
- currentFileId={session.fileId}
- currentFileName={session.fileName}
- dirty={dirty}
- onPick={session.pickFile}
- />
+ <EditorFileLabel fileName={session.fileName} dirty={dirty} />
) : (
<Text size="sm" c="dimmed" px={6}>
{t("pdfTextEditor.sidebar.noFile", "No file loaded")}
@@ -42,51 +37,48 @@ export function MobileEditorTopBar({ controller, hasDocument, dirty }: Props) {
)}
</div>
- {hasDocument && (
- <>
- <Button
- variant="tertiary"
- accent="neutral"
- size="xl"
- onClick={controller.onUndo}
- disabled={!controller.canUndo}
- aria-label={t("pdfTextEditor.toolbar.undo", "Undo")}
- data-testid="pdf-editor-undo"
- leftSection={<Icon name="undo-2" size={22} />}
- />
- <Button
- variant="tertiary"
- accent="neutral"
- size="xl"
- onClick={controller.onRedo}
- disabled={!controller.canRedo}
- aria-label={t("pdfTextEditor.toolbar.redo", "Redo")}
- data-testid="pdf-editor-redo"
- leftSection={<Icon name="redo-2" size={22} />}
- />
- <Button
- variant="tertiary"
- accent="neutral"
- size="xl"
- onClick={() => session?.download()}
- disabled={!session}
- aria-label={t("pdfTextEditor.mobile.download", "Save and download")}
- data-testid="pdf-editor-mobile-download"
- leftSection={<Icon name="download" size={22} />}
- />
- <Button
- size="lg"
- px="md"
- variant={dirty ? "primary" : "secondary"}
- accent={dirty ? "default" : "neutral"}
- onClick={() => session?.save()}
- disabled={!session}
- data-testid="pdf-editor-mobile-save"
- >
- {t("pdfTextEditor.mobile.save", "Save")}
- </Button>
- </>
- )}
+ {/* Shown from the first frame, idle until the document is read. */}
+ <Button
+ variant="tertiary"
+ accent="neutral"
+ size="xl"
+ onClick={controller.onUndo}
+ disabled={!hasDocument || !controller.canUndo}
+ aria-label={t("pdfTextEditor.toolbar.undo", "Undo")}
+ data-testid="pdf-editor-undo"
+ leftSection={<Icon name="undo-2" size={22} />}
+ />
+ <Button
+ variant="tertiary"
+ accent="neutral"
+ size="xl"
+ onClick={controller.onRedo}
+ disabled={!hasDocument || !controller.canRedo}
+ aria-label={t("pdfTextEditor.toolbar.redo", "Redo")}
+ data-testid="pdf-editor-redo"
+ leftSection={<Icon name="redo-2" size={22} />}
+ />
+ <Button
+ variant="tertiary"
+ accent="neutral"
+ size="xl"
+ onClick={() => session?.download()}
+ disabled={!session || !hasDocument}
+ aria-label={t("pdfTextEditor.mobile.download", "Save and download")}
+ data-testid="pdf-editor-mobile-download"
+ leftSection={<Icon name="download" size={22} />}
+ />
+ <Button
+ size="lg"
+ px="md"
+ variant={dirty ? "primary" : "secondary"}
+ accent={dirty ? "default" : "neutral"}
+ onClick={() => session?.save()}
+ disabled={!session || !hasDocument}
+ data-testid="pdf-editor-mobile-save"
+ >
+ {t("pdfTextEditor.mobile.save", "Save")}
+ </Button>
{isPhone && <NotificationBell />}
</div>
);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
deleted file mode 100644
index 210719a6a3..0000000000
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx
+++ /dev/null
@@ -1,516 +0,0 @@
-import { useEffect, useMemo, useRef, useState } from "react";
-import {
- Box,
- Center,
- Loader,
- Progress,
- ScrollArea,
- Stack,
- Text,
-} from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import i18n from "i18next";
-import { alert } from "@editor/components/toast";
-import { useEditorStore } from "@editor/tools/pdfTextEditor/hooks/useEditorStore";
-import { ensurePageRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
-import { EditorTopBar } from "@editor/tools/pdfTextEditor/components/EditorTopBar";
-import { MobileEditorTopBar } from "@editor/tools/pdfTextEditor/components/MobileEditorTopBar";
-import { MobileActionBar } from "@editor/tools/pdfTextEditor/components/MobileActionBar";
-import { useIsMobile } from "@editor/hooks/useIsMobile";
-import { Button } from "@editor/ui/Button";
-import { Icon } from "@editor/ui/Icon";
-import { fitToWidthScale } from "@editor/tools/pdfTextEditor/util/fitToWidth";
-import { FindBar } from "@editor/tools/pdfTextEditor/components/FindBar";
-import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
-import { ZoomPill } from "@editor/tools/pdfTextEditor/components/ZoomPill";
-import { MarqueeSelector } from "@editor/tools/pdfTextEditor/components/MarqueeSelector";
-import { PageView } from "@editor/tools/pdfTextEditor/components/PageView";
-import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
-import {
- scanBlockOffInk,
- wrapScanText,
-} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
-import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
-import { MoveShapeCommand } from "@editor/tools/pdfTextEditor/commands/MoveShapeCommand";
-import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";
-import { InsertTableCommand } from "@editor/tools/pdfTextEditor/commands/InsertTableCommand";
-import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
-import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
-import type {
- SelectionState,
- TextRange,
-} from "@editor/tools/pdfTextEditor/types";
-import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
-
-const DEFAULT_SCALE = 1.5;
-const DESKTOP_FIT_PAD_PX = 64;
-const MOBILE_FIT_PAD_PX = 16;
-
-// Custom workbench view: the contextual formatting toolbar as a bar across the
-// top, then the scrollable pages stack with editable overlays beneath.
-export function PageStage() {
- const { t } = useTranslation();
- const { store, state } = useEditorStore();
- const [selection, setSelection] = useState<SelectionState>(
- store.selection.value,
- );
- const [highlightedRunId, setHighlightedRunId] = useState<string | null>(
- store.selection.highlight.get(),
- );
- const [draggingFile, setDraggingFile] = useState(false);
- const dragCountRef = useRef(0);
- const stageRootRef = useRef<HTMLDivElement | null>(null);
- const isMobile = useIsMobile();
-
- const pageHandlers = useMemo(() => pageViewHandlers(store), [store]);
-
- useEffect(() => store.selection.subscribe(setSelection), [store]);
- useEffect(
- () => store.selection.highlight.subscribe(setHighlightedRunId),
- [store],
- );
-
- // Ctrl/Cmd+wheel zooms the document.
- useEffect(() => {
- const el = stageRootRef.current;
- if (!el) return;
- const onWheel = (e: WheelEvent) => {
- if (!(e.ctrlKey || e.metaKey)) return;
- e.preventDefault();
- const direction = e.deltaY < 0 ? 1 : -1;
- const current = store.getState().renderScale || 1.5;
- const next = Math.min(
- 4,
- Math.max(0.25, +(current + direction * 0.1).toFixed(2)),
- );
- store.setRenderScale(next);
- };
- el.addEventListener("wheel", onWheel, { passive: false });
- return () => el.removeEventListener("wheel", onWheel);
- }, [store, state.hasDocument, state.loading]);
-
- // The strip carries undo/redo plus the contextual formatting group. The
- // inspector derives from the same controller, so both surfaces read one
- // source of truth.
- const controller = useToolbarController(store, state, selection);
-
- const lastFitRef = useRef<{
- doc: object;
- width: number;
- scale: number;
- } | null>(null);
- const firstPageWidth = state.pages[0]?.width;
- useEffect(() => {
- const doc = store.document;
- const stage = stageRootRef.current;
- if (!isMobile || !doc || !stage || !firstPageWidth) return;
- const fit = () => {
- const width = stage.clientWidth;
- if (!width) return;
- const last = lastFitRef.current;
- // Refit on rotate/resize only while the user has not zoomed away from the fit.
- if (
- last?.doc === doc &&
- (last.width === width || store.getState().renderScale !== last.scale)
- ) {
- return;
- }
- const scale = fitToWidthScale(width, firstPageWidth, MOBILE_FIT_PAD_PX);
- lastFitRef.current = { doc, width, scale };
- store.setRenderScale(scale);
- };
- fit();
- const observer = new ResizeObserver(fit);
- observer.observe(stage);
- return () => observer.disconnect();
- }, [isMobile, firstPageWidth, store]);
-
- const topBar = isMobile ? (
- <MobileEditorTopBar
- controller={controller}
- hasDocument={state.hasDocument}
- dirty={state.dirty}
- />
- ) : (
- <EditorTopBar
- controller={controller}
- hasDocument={state.hasDocument}
- dirty={state.dirty}
- addTextArmed={state.mode === "addText"}
- addTableArmed={state.mode === "addTable"}
- onToggleAddTable={() =>
- store.setMode(
- store.getState().mode === "addTable" ? "select" : "addTable",
- )
- }
- onToggleAddText={() =>
- store.setMode(
- store.getState().mode === "addText" ? "select" : "addText",
- )
- }
- findOpen={state.findOpen}
- onToggleFind={() => store.setFindOpen(!store.getState().findOpen)}
- onShowHelp={() => store.setHelpOpen(true)}
- />
- );
-
- if (!state.hasDocument && !state.loading) {
- return (
- <Stack gap={0} h="100%" style={{ overflow: "hidden" }}>
- {topBar}
- <Center
- style={{ flex: 1, minHeight: 0 }}
- data-testid="pdf-editor-stage-empty"
- >
- <Stack align="center" gap="xs" px="md">
- <Text c="dimmed">
- {t("pdfTextEditor.stage.noDocument", "No document loaded.")}
- </Text>
- {isMobile ? (
- <Button
- size="xl"
- leftSection={<Icon name="file-up" size={22} />}
- onClick={() =>
- document
- .querySelector<HTMLInputElement>(
- '[data-testid="pdf-editor-file-input"]',
- )
- ?.click()
- }
- data-testid="pdf-editor-mobile-open"
- >
- {t("pdfTextEditor.mobile.openPdf", "Open a PDF")}
- </Button>
- ) : (
- <Text c="dimmed" size="sm">
- {t(
- "pdfTextEditor.stage.pickPrompt",
- "Pick a PDF from the Files panel on the left to begin editing.",
- )}
- </Text>
- )}
- </Stack>
- </Center>
- </Stack>
- );
- }
-
- // Loading overlay is layered on TOP of the pages stack: PageView's
- // IntersectionObserver only fires when PageView is mounted.
- const showLoading =
- state.loading || (state.hasDocument && !state.firstPageRendered);
- const p = state.progress;
- const percent =
- p && p.total > 0 ? Math.round((p.current / p.total) * 100) : null;
- const stageLabel =
- p?.stage ??
- (state.hasDocument
- ? t("pdfTextEditor.stage.renderingPreview", "Rendering preview")
- : t("pdfTextEditor.stage.loadingDocument", "Loading document"));
-
- return (
- <Stack gap={0} h="100%" style={{ overflow: "hidden" }}>
- {topBar}
- {state.findOpen && state.hasDocument && (
- <FindBar
- store={store}
- pages={state.pages}
- onClose={() => store.setFindOpen(false)}
- />
- )}
- <Box
- pos="relative"
- ref={stageRootRef}
- style={{ flex: 1, minHeight: 0 }}
- // Each handler stops the event: the workbench wraps this stage and would
- // otherwise also add the dropped file to the workspace.
- onDragEnter={(e) => {
- e.stopPropagation();
- if (Array.from(e.dataTransfer?.types ?? []).includes("Files")) {
- dragCountRef.current += 1;
- setDraggingFile(true);
- }
- }}
- onDragOver={(e) => {
- e.stopPropagation();
- if (Array.from(e.dataTransfer?.types ?? []).includes("Files")) {
- e.preventDefault();
- }
- }}
- onDragLeave={(e) => {
- e.stopPropagation();
- dragCountRef.current = Math.max(0, dragCountRef.current - 1);
- if (dragCountRef.current === 0) setDraggingFile(false);
- }}
- onDrop={(e) => {
- // ALWAYS claim the drop: without preventDefault the browser navigates
- // the tab to the dropped file, discarding the editor.
- e.preventDefault();
- e.stopPropagation();
- dragCountRef.current = 0;
- setDraggingFile(false);
- const files = e.dataTransfer?.files;
- if (!files || files.length === 0) return;
- const pdf = Array.from(files).find(
- (f) => f.type === "application/pdf" || /\.pdf$/i.test(f.name),
- );
- if (!pdf) return;
- const input = document.querySelector<HTMLInputElement>(
- '[data-testid="pdf-editor-file-input"]',
- );
- if (!input) return;
- const dt = new DataTransfer();
- dt.items.add(pdf);
- input.files = dt.files;
- input.dispatchEvent(new Event("change", { bubbles: true }));
- }}
- >
- {draggingFile && (
- <Center
- pos="absolute"
- top={0}
- left={0}
- right={0}
- bottom={0}
- style={{
- background: "rgba(0, 100, 200, 0.08)",
- border: "3px dashed rgba(0, 100, 200, 0.4)",
- zIndex: 200,
- pointerEvents: "none",
- }}
- data-testid="pdf-editor-drop-overlay"
- >
- <Stack align="center" gap="xs">
- <Text fw={600} size="lg">
- {t("pdfTextEditor.drop.title", "Drop a PDF to open")}
- </Text>
- <Text size="sm" c="dimmed">
- {t(
- "pdfTextEditor.drop.hint",
- "Releases on the editor stage replace any open document.",
- )}
- </Text>
- </Stack>
- </Center>
- )}
- {showLoading && (
- <Center
- pos="absolute"
- top={0}
- left={0}
- right={0}
- bottom={0}
- style={{
- background: "rgba(255,255,255,0.9)",
- zIndex: 100,
- }}
- data-testid="pdf-editor-stage-loading"
- >
- <Stack align="center" gap="sm" w={320}>
- <Loader size="md" />
- <Text fw={500}>{stageLabel}</Text>
- {percent !== null ? (
- <Progress
- value={percent}
- w="100%"
- size="sm"
- data-testid="pdf-editor-load-progress"
- aria-label={t(
- "pdfTextEditor.stage.loadingProgress",
- "Loading progress",
- )}
- />
- ) : (
- <Progress
- value={100}
- animated
- w="100%"
- size="sm"
- data-testid="pdf-editor-load-progress"
- aria-label={t(
- "pdfTextEditor.stage.loadingProgress",
- "Loading progress",
- )}
- />
- )}
- {p && p.total > 0 && (
- <Text size="xs" c="dimmed">
- {p.current} / {p.total}
- </Text>
- )}
- </Stack>
- </Center>
- )}
- <MarqueeSelector store={store} />
- <ScrollArea h="100%" type="auto" data-testid="pdf-editor-stage">
- <Box
- py={isMobile ? "sm" : "lg"}
- onPointerDown={(e) => {
- // Shift means "extend" here (shift-click) and Ctrl/Cmd+Shift
- // starts the marquee: neither may wipe what it is about to add
- // to. A plain press on bare page still clears.
- if (e.shiftKey) return;
- store.selection.clear();
- }}
- data-testid="pdf-editor-pages"
- >
- <Stack gap={isMobile ? "sm" : "lg"} align="center">
- {state.pages.map((page) =>
- store.document ? (
- <PageView
- key={page.pageIndex}
- document={store.document}
- store={store}
- page={page}
- scale={state.renderScale || DEFAULT_SCALE}
- widthMode={state.widthMode}
- showRulers={state.showRulers}
- selectedRunIds={selection.runIds}
- selectedImageIds={selection.imageIds}
- selectedShapeIds={selection.shapeIds}
- highlightedRunId={highlightedRunId}
- selectedTextRange={selection.textRange}
- {...pageHandlers}
- />
- ) : null,
- )}
- </Stack>
- </Box>
- </ScrollArea>
- {state.hasDocument && (
- <ZoomPill
- store={store}
- renderScale={state.renderScale}
- pages={state.pages}
- fitPaddingPx={isMobile ? MOBILE_FIT_PAD_PX : DESKTOP_FIT_PAD_PX}
- compact={isMobile}
- />
- )}
- </Box>
- {isMobile && state.hasDocument && (
- <MobileActionBar
- store={store}
- controller={controller}
- addTextArmed={state.mode === "addText"}
- addTableArmed={state.mode === "addTable"}
- findOpen={state.findOpen}
- />
- )}
- </Stack>
- );
-}
-
-/**
- * The page views' handlers, made once per store: PageView is memoised, so a
- * handler made per render would re-render every page on any store change.
- * They read the store when called, never state captured at render.
- */
-function pageViewHandlers(store: EditorStore) {
- return {
- onSelectRun: (runId: string, shiftKey: boolean) => {
- if (shiftKey) store.selection.toggle(runId);
- else store.selection.selectOne(runId);
- },
- onSelectRunText: (runId: string, range: TextRange | null) =>
- store.selection.setTextRange(runId, range),
- onSelectImage: (imageId: string) => store.selection.selectImage(imageId),
- onSelectShape: (shapeId: string, extend: boolean) => {
- if (extend) store.selection.toggleShape(shapeId);
- else store.selection.selectShape(shapeId);
- },
- onMoveShape: (
- pageIndex: number,
- shapeId: string,
- dx: number,
- dy: number,
- ) => {
- store.dispatch(new MoveShapeCommand({ pageIndex, shapeId, dx, dy }));
- store.selection.selectShape(shapeId);
- },
- onEditRun: (pageIndex: number, runId: string, nextText: string) => {
- // contentEditable can fire several input events per keystroke burst.
- const current = store.document?.page(pageIndex).findRun(runId);
- if (current && current.text === nextText) return;
- store.dispatch(new EditTextCommand({ pageIndex, runId, nextText }));
- const doc = store.document;
- const run = doc?.page(pageIndex).findRun(runId);
- if (doc && run && scanBlockOffInk(doc, run))
- alert({
- alertType: "warning",
- title: i18n.t(
- "pdfTextEditor.error.scanOffInk",
- "Can't edit this text: its recognised words don't line up with the scan. Run OCR again.",
- ),
- expandable: false,
- });
- },
- onMoveRun: (pageIndex: number, runId: string, dx: number, dy: number) => {
- store.dispatch(new MoveTextRunCommand({ pageIndex, runId, dx, dy }));
- },
- onWrapRun: (pageIndex: number, runId: string, maxWidthPt: number) => {
- const doc = store.document;
- const page = doc?.page(pageIndex);
- const run = page?.findRun(runId);
- const wrapped =
- doc && page && run ? wrapScanText(doc, page, run, maxWidthPt) : null;
- if (wrapped !== null) {
- if (wrapped !== run?.text)
- store.dispatch(
- new EditTextCommand({ pageIndex, runId, nextText: wrapped }),
- );
- return;
- }
- store.dispatch(new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }));
- },
- onResizeRun: (pageIndex: number, runId: string, widthPt: number) => {
- store.dispatch(
- new ReflowWrapCommand({
- pageIndex,
- runId,
- maxWidthPt: widthPt,
- explicit: true,
- }),
- );
- },
- onPageClick: (pageIndex: number, pageX: number, pageY: number) => {
- const { mode } = store.getState();
- if (mode === "addTable") {
- const cmd = new InsertTableCommand({
- pageIndex,
- x: pageX,
- y: pageY,
- width: 360,
- height: 24 * 3,
- rows: 3,
- cols: 3,
- });
- store.dispatch(cmd);
- store.setMode("select");
- return;
- }
- if (mode !== "addText") return;
- const cmd = new InsertTextCommand({
- pageIndex,
- x: pageX,
- y: pageY,
- text: "New text",
- });
- store.dispatch(cmd);
- if (cmd.insertedRunId) store.selection.selectOne(cmd.insertedRunId);
- store.setMode("select");
- },
- onTransformImage: (
- pageIndex: number,
- imageId: string,
- nextBounds: { x: number; y: number; width: number; height: number },
- ) => {
- store.dispatch(
- new SetImageTransformCommand({ pageIndex, imageId, nextBounds }),
- );
- },
- onFirstVisible: (pageIndex: number) => ensurePageRead(store, pageIndex),
- onFirstRendered: (pageIndex: number) => {
- if (pageIndex === 0) store.markFirstPageRendered();
- },
- };
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
index 3920b0c4f7..7e4b1ad880 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
@@ -1,5 +1,5 @@
import { memo, useEffect, useMemo, useRef, useState } from "react";
-import { Box, Loader } from "@mantine/core";
+import { Box } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
@@ -32,8 +32,10 @@ interface PageViewProps {
page: PageSnapshot;
/** Fires when the page enters the viewport for the first time. */
onFirstVisible?: (pageIndex: number) => void;
- /** Fires when the page's bitmap finishes its first render. */
+ /** Fires when the page's first render finishes, painted or failed. */
onFirstRendered?: (pageIndex: number) => void;
+ /** Fires the first time the page's bitmap is painted, including on a retry. */
+ onFirstPainted?: () => void;
scale: number;
widthMode: import("@editor/tools/pdfTextEditor/types").WidthMode;
/** Show the page rulers and alignment guides. */
@@ -124,6 +126,7 @@ export const PageView = memo(function PageView({
onTransformImage,
onFirstVisible,
onFirstRendered,
+ onFirstPainted,
}: PageViewProps) {
const { t } = useTranslation();
const imageAttentions = useMemo(() => {
@@ -156,7 +159,7 @@ export const PageView = memo(function PageView({
// Per document: a newly opened file reuses this view for its page of the same index.
const visibleDocRef = useRef<typeof document | null>(null);
const firstRenderedDocRef = useRef<typeof document | null>(null);
- const [rendering, setRendering] = useState(false);
+ const firstPaintedDocRef = useRef<typeof document | null>(null);
const [paintedRevision, setPaintedRevision] = useState(-1);
const [renderError, setRenderError] = useState<string | null>(null);
const [retryToken, setRetryToken] = useState(0);
@@ -219,7 +222,6 @@ export const PageView = memo(function PageView({
}
let cancelled = false;
if (!canvas) return;
- setRendering(true);
setRenderError(null);
PdfiumPageRenderer.render(
document,
@@ -232,19 +234,21 @@ export const PageView = memo(function PageView({
canvas.height = image.height;
const ctx = canvas.getContext("2d");
if (ctx) ctx.putImageData(image, 0, 0);
- setRendering(false);
setPaintedRevision(page.revision);
if (firstRenderedDocRef.current !== document) {
firstRenderedDocRef.current = document;
onFirstRendered?.(page.pageIndex);
}
+ if (firstPaintedDocRef.current !== document) {
+ firstPaintedDocRef.current = document;
+ onFirstPainted?.();
+ }
})
.catch((err: unknown) => {
if (cancelled) return;
const msg =
err instanceof Error ? `${err.name}: ${err.message}` : String(err);
console.warn(`[pdf-editor] page ${page.pageIndex} render failed`, err);
- setRendering(false);
setRenderError(msg);
// Flip the first-rendered flag on error too, so the loading
// overlay dismisses instead of leaving the user on a spinner.
@@ -269,17 +273,12 @@ export const PageView = memo(function PageView({
return (
<Box
- pos="relative"
- mx="auto"
- mb="lg"
+ // Fills the viewer's page box and stays transparent until painted, so
+ // the viewer's own render shows through.
+ pos="absolute"
ref={containerRef}
className={privateContentClassName}
- style={{
- width: raster.width,
- height: raster.height,
- boxShadow: "0 0 4px rgba(0,0,0,0.2)",
- background: "#fff",
- }}
+ style={{ inset: 0 }}
data-testid={`pdf-editor-page-${page.pageIndex}`}
onClick={(e) => {
if (!onPageClick) return;
@@ -305,35 +304,6 @@ export const PageView = memo(function PageView({
height: raster.height,
}}
/>
- {!nearViewport && (
- <Box
- pos="absolute"
- top={0}
- left={0}
- right={0}
- bottom={0}
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- background:
- "repeating-linear-gradient(45deg, #fafafa, #fafafa 8px, #f0f0f0 8px, #f0f0f0 16px)",
- color: "#777",
- fontSize: 13,
- pointerEvents: "none",
- }}
- data-testid={`pdf-editor-page-${page.pageIndex}-placeholder`}
- >
- {t("pdfTextEditor.pageView.pageNumber", "Page {{page}}", {
- page: page.pageIndex + 1,
- })}
- </Box>
- )}
- {rendering && nearViewport && (
- <Box pos="absolute" top={8} right={8} style={{ pointerEvents: "none" }}>
- <Loader size="xs" />
- </Box>
- )}
{renderError && (
<Box
pos="absolute"
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx
index f78de69fa3..3d5425ba26 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx
@@ -1,6 +1,7 @@
import { Modal, Stack, Text, Group, List } from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { useTranslation } from "react-i18next";
+import { Z_INDEX_OVER_UNSAVED_PROMPT } from "@editor/styles/zIndex";
import {
describeSaveRisks,
type SaveRisks,
@@ -27,6 +28,7 @@ export function SaveRiskModal({
onClose={onCancel}
title={t("pdfTextEditor.saveRisk.title", "Saving will change this PDF")}
size="md"
+ zIndex={Z_INDEX_OVER_UNSAVED_PROMPT}
data-testid="pdf-editor-save-risk-modal"
>
<Stack gap="md">
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
new file mode 100644
index 0000000000..e662467fce
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
@@ -0,0 +1,148 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ useEditorState,
+ useSharedEditorStore,
+} from "@editor/tools/pdfTextEditor/hooks/useEditorStore";
+import {
+ useEditorSelection,
+ useHighlightedRunId,
+} from "@editor/tools/pdfTextEditor/hooks/useEditorSelection";
+import { PageView } from "@editor/tools/pdfTextEditor/components/PageView";
+import { pageViewHandlers } from "@editor/tools/pdfTextEditor/util/pageViewHandlers";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+import type { ViewerPageLayerProps } from "@editor/contexts/viewer/ViewerPageTool";
+
+/** Display aspect ratios further apart than this mean the two disagree on rotation. */
+const ASPECT_TOLERANCE = 0.02;
+
+const NONE: readonly string[] = Object.freeze([]);
+
+/**
+ * Replaces a viewer page's layers with the text editor's page while editing.
+ * The viewer keeps scrolling, zoom and page virtualisation; the editor draws
+ * the page itself, because only its render reflects unsaved edits.
+ *
+ * The viewer lays a page out unrotated and turns the box by its /Rotate with a
+ * CSS transform, while the editor's page is already in display orientation. The
+ * editor page is therefore sized to the turned box and turned back, so on
+ * screen it is upright and pointer maths needs no rotation.
+ */
+export function ViewerEditLayer({
+ pageIndex,
+ width,
+ height,
+ onCovered,
+}: ViewerPageLayerProps) {
+ const store = useSharedEditorStore();
+ // Each page watches only its own snapshot, so an edit re-renders one page.
+ // A new or closed document replaces every snapshot, so `store.document`
+ // below stays current.
+ const page = useEditorState(store, (s) => s.pages[pageIndex]);
+ const document = store.document;
+ const [paintedFor, setPaintedFor] = useState<EditorDocument | null>(null);
+ const onPainted = useCallback(() => setPaintedFor(document), [document]);
+
+ const quarterTurns = (page?.display.rotate ?? 0) & 3;
+ const sideways = quarterTurns % 2 === 1;
+ const displayWidth = sideways ? height : width;
+ const displayHeight = sideways ? width : height;
+ const fits =
+ !!page &&
+ Math.abs(displayWidth / displayHeight - page.width / page.height) <=
+ ASPECT_TOLERANCE * (page.width / page.height);
+ const covered = !!document && fits && paintedFor === document;
+ useEffect(() => onCovered(covered), [covered, onCovered]);
+ useEffect(() => () => onCovered(false), [onCovered]);
+
+ if (!document || !page || !fits) return null;
+ return (
+ <div
+ style={{
+ position: "absolute",
+ left: (width - displayWidth) / 2,
+ top: (height - displayHeight) / 2,
+ width: displayWidth,
+ height: displayHeight,
+ // Above the viewer's layers while they still show underneath.
+ zIndex: 10,
+ transform: quarterTurns
+ ? `rotate(${-90 * quarterTurns}deg)`
+ : undefined,
+ }}
+ onPointerDown={(e) => {
+ // Shift extends a selection and Ctrl/Cmd+Shift starts the marquee;
+ // only a plain press on bare page clears.
+ if (!e.shiftKey) store.selection.clear();
+ }}
+ >
+ <EditablePage
+ store={store}
+ document={document}
+ page={page}
+ scale={displayWidth / page.width}
+ onPainted={onPainted}
+ />
+ </div>
+ );
+}
+
+function EditablePage({
+ store,
+ document,
+ page,
+ scale,
+ onPainted,
+}: {
+ store: EditorStore;
+ document: EditorDocument;
+ page: PageSnapshot;
+ scale: number;
+ onPainted: () => void;
+}) {
+ const widthMode = useEditorState(store, (s) => s.widthMode);
+ const showRulers = useEditorState(store, (s) => s.showRulers);
+ const selection = useEditorSelection(store);
+ const highlightedRunId = useHighlightedRunId(store);
+
+ // PageView is memoised: hand it only this page's share of the selection, in
+ // arrays that keep their identity while that share is unchanged, so a click
+ // on one page does not re-render every other.
+ const runIds = useOwnIds(selection.runIds, page.runs);
+ const imageIds = useOwnIds(selection.imageIds, page.images);
+ const shapeIds = useOwnIds(selection.shapeIds, page.shapes);
+ const ownsHighlight = page.runs.some((r) => r.id === highlightedRunId);
+ const handlers = pageViewHandlers(store);
+
+ return (
+ <PageView
+ document={document}
+ store={store}
+ page={page}
+ scale={scale}
+ widthMode={widthMode}
+ showRulers={showRulers}
+ selectedRunIds={runIds}
+ selectedImageIds={imageIds}
+ selectedShapeIds={shapeIds}
+ highlightedRunId={ownsHighlight ? highlightedRunId : null}
+ selectedTextRange={
+ runIds.length === 1 && selection.runIds.length === 1
+ ? selection.textRange
+ : null
+ }
+ {...handlers}
+ // A failed render leaves the viewer's own page showing.
+ onFirstPainted={onPainted}
+ />
+ );
+}
+
+function useOwnIds(
+ selected: readonly string[],
+ own: readonly { id: string }[],
+): string[] {
+ const key = selected.filter((id) => own.some((o) => o.id === id)).join("\n");
+ return useMemo(() => (key ? key.split("\n") : (NONE as string[])), [key]);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx
new file mode 100644
index 0000000000..5b369eb48b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx
@@ -0,0 +1,95 @@
+import { useEffect } from "react";
+import { useEditorStoreView } from "@editor/tools/pdfTextEditor/hooks/useEditorStore";
+import { useEditorSelection } from "@editor/tools/pdfTextEditor/hooks/useEditorSelection";
+import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
+import { EditorTopBar } from "@editor/tools/pdfTextEditor/components/EditorTopBar";
+import { MobileEditorTopBar } from "@editor/tools/pdfTextEditor/components/MobileEditorTopBar";
+import { MobileActionBar } from "@editor/tools/pdfTextEditor/components/MobileActionBar";
+import { useIsMobile } from "@editor/hooks/useIsMobile";
+import { FindBar } from "@editor/tools/pdfTextEditor/components/FindBar";
+import { MarqueeSelector } from "@editor/tools/pdfTextEditor/components/MarqueeSelector";
+
+/** The viewer's own controls float over the page area; pressing one is not a deselect. */
+const CONTROLS =
+ "button, input, select, textarea, a, [role='button'], [role='slider']";
+
+/** The text editor's strip and find bar, docked above the viewer while editing. */
+export function ViewerEditToolbar() {
+ const { store, state } = useEditorStoreView();
+ const selection = useEditorSelection(store);
+ const controller = useToolbarController(store, state, selection);
+ const isMobile = useIsMobile();
+
+ // A plain press on the bare viewer around the pages clears the selection,
+ // as one on bare page does. Shift extends, and Ctrl/Cmd+Shift starts the
+ // marquee: neither may wipe what it is about to add to.
+ useEffect(() => {
+ const onPointerDown = (e: PointerEvent) => {
+ if (e.button !== 0 || e.shiftKey) return;
+ const target = e.target as Element | null;
+ if (!target?.closest("[data-viewer-pages]")) return;
+ if (target.closest(`[data-page-index], ${CONTROLS}`)) return;
+ store.selection.clear();
+ };
+ window.addEventListener("pointerdown", onPointerDown);
+ return () => window.removeEventListener("pointerdown", onPointerDown);
+ }, [store]);
+
+ return (
+ <>
+ {isMobile ? (
+ <MobileEditorTopBar
+ controller={controller}
+ hasDocument={state.hasDocument}
+ dirty={state.dirty}
+ />
+ ) : (
+ <EditorTopBar
+ controller={controller}
+ hasDocument={state.hasDocument}
+ dirty={state.dirty}
+ addTextArmed={state.mode === "addText"}
+ addTableArmed={state.mode === "addTable"}
+ onToggleAddTable={() =>
+ store.setMode(
+ store.getState().mode === "addTable" ? "select" : "addTable",
+ )
+ }
+ onToggleAddText={() =>
+ store.setMode(
+ store.getState().mode === "addText" ? "select" : "addText",
+ )
+ }
+ findOpen={state.findOpen}
+ onToggleFind={() => store.setFindOpen(!store.getState().findOpen)}
+ onShowHelp={() => store.setHelpOpen(true)}
+ />
+ )}
+ {state.findOpen && state.hasDocument && (
+ <FindBar
+ store={store}
+ pages={state.pages}
+ onClose={() => store.setFindOpen(false)}
+ />
+ )}
+ <MarqueeSelector store={store} />
+ </>
+ );
+}
+
+/** The editing actions a small screen shows below the pages. */
+export function ViewerEditActionBar() {
+ const { store, state } = useEditorStoreView();
+ const selection = useEditorSelection(store);
+ const controller = useToolbarController(store, state, selection);
+ if (!state.hasDocument) return null;
+ return (
+ <MobileActionBar
+ store={store}
+ controller={controller}
+ addTextArmed={state.mode === "addText"}
+ addTableArmed={state.mode === "addTable"}
+ findOpen={state.findOpen}
+ />
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ZoomPill.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ZoomPill.tsx
deleted file mode 100644
index d6183d58cd..0000000000
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ZoomPill.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { Group, Text, Tooltip } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { Button } from "@editor/ui/Button";
-import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
-import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
-import {
- clampRenderScale,
- fitToWidthScale,
-} from "@editor/tools/pdfTextEditor/util/fitToWidth";
-
-const Z_STEP = 0.25;
-
-interface Props {
- store: EditorStore;
- renderScale: number;
- pages: PageSnapshot[];
- fitPaddingPx: number;
- compact?: boolean;
-}
-
-/**
- * Zoom, floating over the pages it scales.
- *
- * Anchored to the canvas because it is a view control: it belongs beside what
- * it acts on. Ctrl+wheel on the stage drives the same store field.
- */
-export function ZoomPill({
- store,
- renderScale,
- pages,
- fitPaddingPx,
- compact = false,
-}: Props) {
- const { t } = useTranslation();
- const zoomTo = (scale: number) =>
- store.setRenderScale(clampRenderScale(scale));
- const inset = compact ? 10 : 18;
-
- return (
- <Group
- gap={2}
- wrap="nowrap"
- p={4}
- data-testid="pdf-editor-zoom-controls"
- style={{
- position: "absolute",
- right: inset,
- bottom: inset,
- zIndex: 50,
- borderRadius: 999,
- border: "1px solid var(--mantine-color-default-border)",
- background: "var(--mantine-color-body)",
- boxShadow: "0 3px 14px rgba(0, 0, 0, 0.14)",
- }}
- >
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- aria-label={t("pdfTextEditor.zoom.out", "Zoom out")}
- data-testid="pdf-editor-zoom-out"
- onClick={() => zoomTo(renderScale - Z_STEP)}
- >
- −
- </Button>
- {/* The readout doubles as the reset control: a separate "100%" button
- beside a "150%" readout read as two zoom values. */}
- <Tooltip label={t("pdfTextEditor.zoom.reset", "Reset zoom to 100%")}>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- data-testid="pdf-editor-zoom-reset"
- onClick={() => store.setRenderScale(1)}
- >
- <Text
- size="xs"
- miw={38}
- ta="center"
- data-testid="pdf-editor-zoom-percent"
- >
- {Math.round(renderScale * 100)}%
- </Text>
- </Button>
- </Tooltip>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- aria-label={t("pdfTextEditor.zoom.in", "Zoom in")}
- data-testid="pdf-editor-zoom-in"
- onClick={() => zoomTo(renderScale + Z_STEP)}
- >
- +
- </Button>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- aria-label={t("pdfTextEditor.zoom.fitToWidth", "Fit to width")}
- data-testid="pdf-editor-zoom-fit"
- onClick={() => {
- const stage = document.querySelector<HTMLElement>(
- '[data-testid="pdf-editor-stage"]',
- );
- const firstPage = pages[0];
- if (!stage || !firstPage) return;
- store.setRenderScale(
- fitToWidthScale(stage.clientWidth, firstPage.width, fitPaddingPx),
- );
- }}
- >
- {t("pdfTextEditor.zoom.fit", "Fit")}
- </Button>
- </Group>
- );
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts
index 3a7f6870a8..6454123ced 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.test.ts
@@ -13,6 +13,10 @@ const files = vi.hoisted(() => ({
selected: [] as StirlingFile[],
all: [] as StirlingFile[],
}));
+const viewer = vi.hoisted(() => ({
+ activeFileId: null as string | null,
+ setActiveFileId: vi.fn(),
+}));
vi.mock("@editor/contexts/FileContext", () => ({
useFileSelection: () => ({ selectedFiles: files.selected }),
useAllFiles: () => ({ files: files.all }),
@@ -21,60 +25,120 @@ vi.mock("@editor/contexts/NavigationContext", () => ({
useNavigationState: () => ({ selectedTool: "pdfTextEditor" }),
}));
vi.mock("@editor/contexts/ViewerContext", () => ({
- useViewer: () => ({ activeFileId: null }),
+ useViewer: () => viewer,
}));
+
+const closed: EditorLoadState = {
+ hasDocument: false,
+ loading: false,
+ error: null,
+ dirty: false,
+ passwordPrompt: null,
+};
+const open: EditorLoadState = { ...closed, hasDocument: true };
+
beforeEach(() => {
- files.selected = [createStirlingFile(new File(["pdf"], "locked.pdf"))];
+ files.selected = [createStirlingFile(new File(["pdf"], "first.pdf"))];
files.all = files.selected;
+ viewer.activeFileId = null;
+ viewer.setActiveFileId.mockReset();
});
afterEach(cleanup);
-it("keeps a cancelled workbench password prompt closed until explicit retry", () => {
- const file = files.selected[0];
+function render(currentFileId: string | null, editor: EditorLoadState) {
const load = vi.fn();
- const choose = vi.fn();
- const initial: EditorLoadState = {
- hasDocument: false,
- loading: false,
- error: null,
- passwordPrompt: null,
- };
const view = renderHook(
- (editor: EditorLoadState) =>
- useAutoLoadFile(load, choose, file.fileId, false, editor),
- { initialProps: initial },
+ ({ id, state }: { id: string | null; state: EditorLoadState }) =>
+ useAutoLoadFile(
+ load,
+ vi.fn(),
+ id as StirlingFile["fileId"] | null,
+ false,
+ state,
+ ),
+ { initialProps: { id: currentFileId, state: editor } },
);
+ return { load, view };
+}
+
+it("keeps a cancelled password prompt closed", () => {
+ const file = files.selected[0];
+ const { load, view } = render(file.fileId, closed);
expect(load).toHaveBeenCalledOnce();
view.rerender({
- ...initial,
- passwordPrompt: { fileName: file.name, retry: true },
+ id: file.fileId,
+ state: { ...closed, passwordPrompt: { fileName: file.name, retry: true } },
});
act(() => view.result.current.cancel(file));
- view.rerender(initial);
- view.rerender({ ...initial });
+ view.rerender({ id: file.fileId, state: closed });
+ view.rerender({ id: file.fileId, state: { ...closed } });
expect(load).toHaveBeenCalledOnce();
- act(() => view.result.current.openFile(file));
- expect(load).toHaveBeenCalledTimes(2);
});
it("allows another selected file to load after cancelling a password prompt", () => {
const file = files.selected[0];
- const load = vi.fn();
- const choose = vi.fn();
- const initial: EditorLoadState = {
- hasDocument: false,
- loading: false,
- error: null,
- };
- const view = renderHook(
- (editor: EditorLoadState) =>
- useAutoLoadFile(load, choose, file.fileId, false, editor),
- { initialProps: initial },
- );
+ const { load, view } = render(file.fileId, closed);
act(() => view.result.current.cancel(file));
files.selected = [createStirlingFile(new File(["other"], "other.pdf"))];
files.all = [...files.all, ...files.selected];
- view.rerender({ ...initial });
+ view.rerender({ id: file.fileId, state: { ...closed } });
expect(load).toHaveBeenLastCalledWith(files.selected[0]);
expect(load).toHaveBeenCalledTimes(2);
});
+
+it("follows the active file to another document", () => {
+ const first = files.selected[0];
+ const second = createStirlingFile(new File(["two"], "second.pdf"));
+ files.all = [first, second];
+ viewer.activeFileId = first.fileId;
+ const { load, view } = render(first.fileId, closed);
+ view.rerender({ id: first.fileId, state: open });
+ expect(load).toHaveBeenCalledOnce();
+
+ viewer.activeFileId = second.fileId;
+ view.rerender({ id: first.fileId, state: { ...open } });
+ expect(load).toHaveBeenLastCalledWith(second);
+});
+
+it("asks before leaving unsaved edits, and moves the viewer back on cancel", () => {
+ const first = files.selected[0];
+ const second = createStirlingFile(new File(["two"], "second.pdf"));
+ files.all = [first, second];
+ viewer.activeFileId = first.fileId;
+ const { load, view } = render(first.fileId, closed);
+ view.rerender({ id: first.fileId, state: { ...open, dirty: true } });
+
+ viewer.activeFileId = second.fileId;
+ view.rerender({ id: first.fileId, state: { ...open, dirty: true } });
+ expect(load).toHaveBeenCalledOnce();
+ expect(view.result.current.pendingSwitch).toBe(second);
+
+ act(() => view.result.current.cancelSwitch());
+ expect(view.result.current.pendingSwitch).toBeNull();
+ expect(viewer.setActiveFileId).toHaveBeenCalledWith(first.fileId);
+ expect(load).toHaveBeenCalledOnce();
+});
+
+it("opens the pending file once its unsaved edits are dropped", () => {
+ const first = files.selected[0];
+ const second = createStirlingFile(new File(["two"], "second.pdf"));
+ files.all = [first, second];
+ viewer.activeFileId = first.fileId;
+ const { load, view } = render(first.fileId, closed);
+ viewer.activeFileId = second.fileId;
+ view.rerender({ id: first.fileId, state: { ...open, dirty: true } });
+
+ act(() => view.result.current.confirmSwitch());
+ expect(load).toHaveBeenLastCalledWith(second);
+});
+
+it("ignores selection changes while a document is open", () => {
+ const first = files.selected[0];
+ const { load, view } = render(first.fileId, closed);
+ view.rerender({ id: first.fileId, state: open });
+
+ files.selected = [createStirlingFile(new File(["other"], "other.pdf"))];
+ files.all = [first, ...files.selected];
+ view.rerender({ id: first.fileId, state: { ...open } });
+ expect(load).toHaveBeenCalledOnce();
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts
index f746371c35..55c65f4fae 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useAutoLoadFile.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useAllFiles, useFileSelection } from "@editor/contexts/FileContext";
import type { FileId } from "@editor/types/file";
import { useNavigationState } from "@editor/contexts/NavigationContext";
@@ -17,12 +17,16 @@ function fileKey(file: File): string {
}
interface AutoLoad {
- /** Open a workbench file deliberately. */
- openFile: (file: File) => void;
- /** Record a document the editor loaded by other means, so auto-open stands down. */
+ /** Record a document the editor loaded by other means, so it is not opened again. */
adopt: (file: File) => void;
/** Keep a cancelled password request closed until another file or an explicit open. */
cancel: (file: File) => void;
+ /** The file the user moved to while the open document has unsaved edits. */
+ pendingSwitch: File | null;
+ /** Drop the unsaved edits and open the pending file. */
+ confirmSwitch: () => void;
+ /** Keep editing the open document and move the active file back to it. */
+ cancelSwitch: () => void;
}
/** The slice of the editor's state that decides whether it needs a file. */
@@ -30,22 +34,22 @@ export interface EditorLoadState {
hasDocument: boolean;
loading: boolean;
error: string | null;
+ dirty: boolean;
passwordPrompt?: { fileName: string; retry: boolean } | null;
}
/**
- * Open the file the user most likely wants.
+ * Keep the editor on the workbench's active file, the one the viewer shows.
*
- * Auto-opening only ever fires while the editor holds nothing: the selection
- * moves on its own (the Active Files view trims a multi-file selection down to
- * its last entry to honour the tool's one-file limit), and following it would
- * swap the open document, and any unsaved edits, out from under the user.
+ * Only the active file is followed, never the selection: the selection moves on
+ * its own (the Active Files view trims a multi-file selection down to its last
+ * entry), and following it would swap the document out from under the user.
+ * The selection is read only for the first pick, while no file is active.
*
- * "Holds nothing" is the store's own state, not a memory of having opened
- * something. The store is a module singleton that drops its document when the
- * canvas unmounts, while this hook's refs belong to the panel - so the two
- * disagree whenever one outlives the other, and a hook that stood down on its
- * own memory left the editor empty with no way back in.
+ * "Is a document open" is the store's own state, not a memory of having opened
+ * something: the store is a module singleton that can drop its document while
+ * this hook's refs live on, and a hook that trusted its own memory left the
+ * editor empty with no way back in.
*/
export function useAutoLoadFile(
load: Loader,
@@ -53,39 +57,30 @@ export function useAutoLoadFile(
currentFileId: FileId | null,
/** Saving is swapping the workbench file under us; do not re-pick mid-swap. */
hold: boolean,
- /** The editor's live state, so "is a document open" is asked, not remembered. */
editor: EditorLoadState,
): AutoLoad {
const navigationState = useNavigationState();
const { selectedFiles } = useFileSelection();
const { files: allFiles } = useAllFiles();
- const { activeFileId } = useViewer();
+ const { activeFileId, setActiveFileId } = useViewer();
- const autoLoadFile = useMemo(() => {
- // Prefer the open document while it is still selected so a reordering
- // selection cannot nudge the editor onto a different file.
- if (currentFileId) {
- const held = selectedFiles.find(
- (f) => (f as WorkbenchFile).fileId === currentFileId,
- );
- if (held) return held;
- }
- if (selectedFiles[0]) return selectedFiles[0];
- if (activeFileId) {
- const viewerFile = allFiles.find(
- (f) => (f as WorkbenchFile).fileId === activeFileId,
- );
- if (viewerFile) return viewerFile;
- }
- if (allFiles.length === 1) return allFiles[0];
- return null;
- }, [selectedFiles, activeFileId, allFiles, currentFileId]);
+ const activeFile = useMemo(
+ () =>
+ (activeFileId &&
+ allFiles.find((f) => (f as WorkbenchFile).fileId === activeFileId)) ||
+ null,
+ [activeFileId, allFiles],
+ );
+ const firstPick =
+ selectedFiles[0] ?? (allFiles.length === 1 ? allFiles[0] : null);
+ const target = activeFile ?? (editor.hasDocument ? null : firstPick);
- // The open document left the workbench, so the editor is free to pick again.
+ // The open document left the workbench, so its edits have nowhere to go.
const documentGone =
currentFileId != null &&
!allFiles.some((f) => (f as WorkbenchFile).fileId === currentFileId);
+ const [pendingSwitch, setPendingSwitch] = useState<File | null>(null);
const lastKeyRef = useRef<string | null>(null);
const cancelledKeyRef = useRef<string | null>(null);
const cancel = useCallback((file: File) => {
@@ -95,7 +90,7 @@ export function useAutoLoadFile(
cancelledKeyRef.current = null;
lastKeyRef.current = fileKey(file);
}, []);
- const openFile = useCallback(
+ const open = useCallback(
(file: File) => {
adopt(file);
onFileChosen(file.name, (file as WorkbenchFile).fileId);
@@ -105,56 +100,66 @@ export function useAutoLoadFile(
);
useEffect(() => {
- if (!autoLoadFile || hold) return;
+ if (!target || hold) return;
if (navigationState.selectedTool !== "pdfTextEditor") return;
- const cancelled = cancelledKeyRef.current;
- if (cancelled === fileKey(autoLoadFile)) return;
+ const key = fileKey(target);
+ if (cancelledKeyRef.current === key) return;
cancelledKeyRef.current = null;
- // A document is open: leave it, and the user's unsaved edits, alone.
- if (editor.hasDocument && !documentGone) return;
// Restarting a pending open would reset its password prompt.
if (editor.loading || editor.passwordPrompt) return;
- // Recovery: the store dropped a document this hook had already opened.
- // Re-open THAT file, and do it quietly - no pin, no filename change. The
- // canvas can be dropped because the user went to Active Files, and pinning
- // it back would yank them out of the list they just asked for.
- const recovering = lastKeyRef.current !== null && cancelled === null;
- if (recovering) {
- const same = allFiles.find(
- (f) => (f as WorkbenchFile).fileId === currentFileId,
- );
- // Nothing to recover to: the file left the workbench, so fall through
- // and pick a candidate the normal way.
- if (same) {
- if (editor.error && lastKeyRef.current === fileKey(same)) return;
- adopt(same);
- void load(same);
+ // The open document's own file, met again by a hook that remounted.
+ if (
+ editor.hasDocument &&
+ currentFileId != null &&
+ (target as WorkbenchFile).fileId === currentFileId
+ ) {
+ lastKeyRef.current = key;
+ }
+ if (lastKeyRef.current === key) {
+ if (editor.hasDocument) {
+ setPendingSwitch(null);
return;
}
+ // This exact file already failed to open. Retrying it is a loop, not a fix.
+ if (editor.error) return;
+ // The store dropped the document this hook opened: reopen it quietly.
+ void load(target);
+ return;
}
-
- // This exact file already failed to open. Retrying it is a loop, not a fix.
- if (editor.error && lastKeyRef.current === fileKey(autoLoadFile)) return;
- openFile(autoLoadFile);
+ if (editor.hasDocument && editor.dirty && !documentGone) {
+ setPendingSwitch(target);
+ return;
+ }
+ setPendingSwitch(null);
+ open(target);
}, [
- autoLoadFile,
- documentGone,
- editor.error,
- editor.hasDocument,
- editor.loading,
- editor.passwordPrompt,
+ target,
hold,
navigationState.selectedTool,
- openFile,
- adopt,
- allFiles,
- currentFileId,
+ editor.loading,
+ editor.passwordPrompt,
+ editor.hasDocument,
+ editor.error,
+ editor.dirty,
+ documentGone,
load,
+ open,
]);
+ const confirmSwitch = useCallback(() => {
+ if (pendingSwitch) open(pendingSwitch);
+ setPendingSwitch(null);
+ }, [open, pendingSwitch]);
+
+ const cancelSwitch = useCallback(() => {
+ if (pendingSwitch) cancelledKeyRef.current = fileKey(pendingSwitch);
+ setPendingSwitch(null);
+ if (currentFileId) setActiveFileId(currentFileId);
+ }, [currentFileId, pendingSwitch, setActiveFileId]);
+
return useMemo(
- () => ({ openFile, adopt, cancel }),
- [openFile, adopt, cancel],
+ () => ({ adopt, cancel, pendingSwitch, confirmSwitch, cancelSwitch }),
+ [adopt, cancel, pendingSwitch, confirmSwitch, cancelSwitch],
);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
index f5394acb20..b0df72c0ed 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
@@ -1,11 +1,11 @@
import { useEffect } from "react";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import {
- findVisiblePageIndex,
isFocusInContentEditable,
isFocusInFormField,
- pageElements,
+ visiblePageNumber,
} from "@editor/tools/pdfTextEditor/util/dom";
+import { currentEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
interface KeyboardShortcutCallbacks {
store: EditorStore;
@@ -151,19 +151,21 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
if (e.key !== "PageDown" && e.key !== "PageUp" && !isHome && !isEnd) {
return;
}
- if (store.getState().pageCount === 0) return;
- const pages = pageElements();
- if (pages.length === 0) return;
- const current = findVisiblePageIndex();
+ const { pageCount } = store.getState();
+ if (pageCount === 0) return;
+ // The viewer mounts only the pages near the viewport, so it does the
+ // navigating.
+ const session = currentEditorSession();
+ if (!session) return;
+ const current = visiblePageNumber();
let target = current;
- if (e.key === "PageDown")
- target = Math.min(pages.length - 1, current + 1);
+ if (e.key === "PageDown") target = Math.min(pageCount - 1, current + 1);
else if (e.key === "PageUp") target = Math.max(0, current - 1);
else if (isHome) target = 0;
- else if (isEnd) target = pages.length - 1;
+ else if (isEnd) target = pageCount - 1;
if (target === current) return;
e.preventDefault();
- pages[target]?.scrollIntoView({ behavior: "smooth", block: "start" });
+ session.revealPage(target);
}
window.addEventListener("keydown", onMetaKey);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts
new file mode 100644
index 0000000000..839fd6cd4b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts
@@ -0,0 +1,24 @@
+import { useCallback, useSyncExternalStore } from "react";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+
+/**
+ * The editor's selection. It changes without touching the editor state, so a
+ * component reading both re-renders on either.
+ */
+export function useEditorSelection(store: EditorStore): SelectionState {
+ const subscribe = useCallback(
+ (onChange: () => void) => store.selection.subscribe(onChange),
+ [store],
+ );
+ return useSyncExternalStore(subscribe, () => store.selection.value);
+}
+
+/** The run the find bar is pointing at, or null. */
+export function useHighlightedRunId(store: EditorStore): string | null {
+ const subscribe = useCallback(
+ (onChange: () => void) => store.selection.highlight.subscribe(onChange),
+ [store],
+ );
+ return useSyncExternalStore(subscribe, () => store.selection.highlight.get());
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorStore.ts
index 9c85a767f1..9c25a31d6f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorStore.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorStore.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
let __singleton: EditorStore | null = null;
@@ -17,16 +17,22 @@ if (import.meta.hot) {
/** Grace period before a fully-unmounted editor frees its PDFium document. */
const DISPOSE_GRACE_MS = 1500;
-/** Returns the singleton editor store, plus the current view state. */
+function sharedStore(): EditorStore {
+ if (!__singleton) __singleton = new EditorStore();
+ return __singleton;
+}
+
+type EditorViewState = ReturnType<EditorStore["getState"]>;
+
+/**
+ * The singleton editor store and its state, owning the open document: once the
+ * last owner unmounts, the document is freed after a grace period.
+ */
export function useEditorStore(): {
store: EditorStore;
- state: ReturnType<EditorStore["getState"]>;
+ state: EditorViewState;
} {
- const store = useMemo(() => {
- if (!__singleton) __singleton = new EditorStore();
- return __singleton;
- }, []);
- const [state, setState] = useState(store.getState());
+ const view = useEditorStoreView();
useEffect(() => {
// A pending disposal means we just remounted within the grace window
// (StrictMode / sidebar toggle) - cancel it so the open doc survives.
@@ -34,22 +40,58 @@ export function useEditorStore(): {
clearTimeout(__disposeTimer);
__disposeTimer = null;
}
- setState(store.getState());
- const unsubscribe = store.subscribe(setState);
return () => {
- unsubscribe();
- // Defer disposal: if the component remounts (the effect above runs again)
- // the timer is cancelled.
if (__disposeTimer) clearTimeout(__disposeTimer);
__disposeTimer = setTimeout(() => {
__disposeTimer = null;
__singleton?.clearDocument();
}, DISPOSE_GRACE_MS);
};
- }, [store]);
+ }, []);
+ return view;
+}
+
+/**
+ * The singleton editor store and its state, without owning the document's
+ * lifetime: viewer pages mount and unmount as they scroll, and an owning hook
+ * there would drop the document every time a page left the screen.
+ */
+export function useEditorStoreView(): {
+ store: EditorStore;
+ state: EditorViewState;
+} {
+ const store = useSharedEditorStore();
+ const state = useEditorState(store, identity);
return { store, state };
}
+/**
+ * The singleton editor store without subscribing to its state; pair it with
+ * `useEditorState` to re-render on just the slice a component reads.
+ */
+export function useSharedEditorStore(): EditorStore {
+ return useMemo(sharedStore, []);
+}
+
+/**
+ * One slice of the editor's state; re-renders only when that slice changes
+ * identity, so `select` must return stored values, not build new ones.
+ */
+export function useEditorState<T>(
+ store: EditorStore,
+ select: (state: EditorViewState) => T,
+): T {
+ const subscribe = useCallback(
+ (onChange: () => void) => store.subscribe(onChange),
+ [store],
+ );
+ return useSyncExternalStore(subscribe, () => select(store.getState()));
+}
+
+function identity<T>(value: T): T {
+ return value;
+}
+
/** Test-only - drop the singleton so the next mount starts fresh. */
export function __resetEditorStoreForTests(): void {
if (__singleton) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts
index cd83d98b11..cd7379c1b4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useHeadingOutline.ts
@@ -9,6 +9,7 @@ import {
type HeadingOutline,
} from "@editor/tools/pdfTextEditor/util/headingOutline";
import { locateHeading } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import { revealOnPage } from "@editor/tools/pdfTextEditor/util/dom";
/**
* The document's heading outline, null when its structure tree could not be
@@ -46,9 +47,10 @@ export function useHeadingOutline(
if (range) store.selection.setTextRange(run.id, range);
// A page read just now has no overlay until React commits it.
window.requestAnimationFrame(() =>
- document
- .querySelector(`[data-testid="pdf-editor-run-${run.id}"]`)
- ?.scrollIntoView({ block: "center", behavior: "smooth" }),
+ revealOnPage(
+ document.querySelector(`[data-testid="pdf-editor-run-${run.id}"]`),
+ run.pageIndex,
+ ),
);
},
[store],
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts
index 77e658e9a3..02bcd7d616 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useImageAccessibility.ts
@@ -21,6 +21,7 @@ import {
type ImageAccessibility,
type ImageReview,
} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
+import { revealOnPage } from "@editor/tools/pdfTextEditor/util/dom";
/**
* The accessibility of the selected image (null unless exactly one image and
@@ -94,9 +95,10 @@ export function useImageAccessibility(
store.selection.selectImage(next.id);
// A page read just now has no overlay until React commits it.
window.requestAnimationFrame(() =>
- document
- .querySelector(`[data-testid="pdf-editor-image-${next.id}"]`)
- ?.scrollIntoView({ block: "center", behavior: "smooth" }),
+ revealOnPage(
+ document.querySelector(`[data-testid="pdf-editor-image-${next.id}"]`),
+ next.pageIndex,
+ ),
);
return true;
}, [store]);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts
new file mode 100644
index 0000000000..635f6bab5f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useOpenAtViewerText.ts
@@ -0,0 +1,103 @@
+import { useEffect, useRef } from "react";
+import { useViewerTextTarget } from "@editor/contexts/viewer/ViewerPageTool";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { TextRange } from "@editor/tools/pdfTextEditor/types";
+import { revealOnPage } from "@editor/tools/pdfTextEditor/util/dom";
+import { locateViewerText } from "@editor/tools/pdfTextEditor/util/locateViewerText";
+import { plainDomRange } from "@editor/tools/pdfTextEditor/util/overlayPainter";
+
+/** Frames to wait for the run's page to mount before leaving it selected only. */
+const MOUNT_WAIT_FRAMES = 120;
+
+/** Editors mounted now; the editor remounts once as it opens. */
+let mountedEditors = 0;
+
+/**
+ * Opens the text the user picked in the viewer for editing, once its page has
+ * been read: the run takes focus with that span selected, so typing replaces
+ * it. A page without the text leaves the selection alone. A target the editor
+ * closes without reaching is dropped, so no later open picks it up.
+ */
+export function useOpenAtViewerText(
+ store: EditorStore,
+ sourceFileId: string | null,
+): void {
+ const { textTarget, clearTextTarget } = useViewerTextTarget();
+ // The wait for the run to mount outlives the effect below, which re-runs as
+ // soon as the target is taken, so it stops only on unmount.
+ const stopWaitRef = useRef<() => void>(() => {});
+ useEffect(() => {
+ mountedEditors++;
+ return () => {
+ mountedEditors--;
+ stopWaitRef.current();
+ // A remount takes over the target; only a real close drops it.
+ setTimeout(() => {
+ if (mountedEditors === 0) clearTextTarget();
+ });
+ };
+ }, [clearTextTarget]);
+
+ useEffect(() => {
+ if (!textTarget) return undefined;
+ const attempt = () => {
+ if (textTarget.fileId !== sourceFileId) return;
+ const state = store.getState();
+ if (!state.hasDocument) return;
+ const page = state.pages.find(
+ (p) => p.pageIndex === textTarget.pageIndex,
+ );
+ // A page's annotations are filled in when it is read.
+ if (!page?.annotations) return;
+ clearTextTarget();
+ const found = locateViewerText(page, textTarget.text, textTarget.rect);
+ if (!found) return;
+ store.selection.set({
+ runIds: [found.runId],
+ imageIds: [],
+ shapeIds: [],
+ caret: null,
+ textRange: found.range,
+ });
+ const chosen = store.selection.value;
+ revealOnPage(runElement(found.runId), page.pageIndex);
+ let frame = 0;
+ let waited = 0;
+ const focusWhenMounted = () => {
+ // The user has moved on; their selection stands.
+ if (store.selection.value !== chosen) return;
+ const el = runElement(found.runId);
+ if (el) editRange(el, found.range);
+ else if (waited++ < MOUNT_WAIT_FRAMES) {
+ frame = requestAnimationFrame(focusWhenMounted);
+ }
+ };
+ stopWaitRef.current = () => cancelAnimationFrame(frame);
+ focusWhenMounted();
+ };
+ attempt();
+ return store.subscribe(attempt);
+ }, [store, sourceFileId, textTarget, clearTextTarget]);
+}
+
+function runElement(runId: string): HTMLElement | null {
+ return document.querySelector<HTMLElement>(
+ `[data-testid="pdf-editor-run-${runId}"]`,
+ );
+}
+
+/**
+ * Focuses the run, then selects `range` in it. Focus repaints the run's text,
+ * which drops any range already in it, so the range goes in after that frame.
+ */
+function editRange(el: HTMLElement, range: TextRange): void {
+ el.focus({ preventScroll: true });
+ requestAnimationFrame(() => {
+ if (document.activeElement !== el) return;
+ const dom = plainDomRange(el, range);
+ const selection = window.getSelection();
+ if (!dom || !selection) return;
+ selection.removeAllRanges();
+ selection.addRange(dom);
+ });
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useWorkbenchPin.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useWorkbenchPin.ts
index 8f947ca630..51b24df377 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useWorkbenchPin.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useWorkbenchPin.ts
@@ -4,96 +4,26 @@ import {
useNavigationState,
} from "@editor/contexts/NavigationContext";
import { useToolWorkflow } from "@editor/contexts/ToolWorkflowContext";
-import type { CustomWorkbenchViewRegistration } from "@editor/contexts/ToolWorkflowContext";
-interface PinOptions {
- workbenchId: CustomWorkbenchViewRegistration["workbenchId"];
- workbenchViewId: string;
- label: string;
- icon: React.ReactNode;
- component: CustomWorkbenchViewRegistration["component"];
- takeOverScreen: boolean;
-}
-
-// Register the custom workbench view and open it when the editor tool is
-// selected. Returns a `pin` that brings the canvas back on demand.
-export function useWorkbenchPin({
- workbenchId,
- workbenchViewId,
- label,
- icon,
- component,
- takeOverScreen,
-}: PinOptions): () => void {
- const {
- registerCustomWorkbenchView,
- unregisterCustomWorkbenchView,
- setCustomWorkbenchViewData,
- clearCustomWorkbenchViewData,
- setLeftPanelView,
- } = useToolWorkflow();
+// Editing happens on the viewer's pages, so opening the editor tool opens the
+// viewer. Returns a `pin` that brings the viewer back on demand.
+export function useWorkbenchPin(): () => void {
+ const { setLeftPanelView } = useToolWorkflow();
const { actions: navigationActions } = useNavigationActions();
const navigationState = useNavigationState();
- // Stash the per-render values that aren't dependable identities so the effect
- // can read them on mount without re-running on every parent render.
- const viewRef = useRef({
- workbenchId,
- workbenchViewId,
- label,
- icon,
- component,
- });
- viewRef.current = { workbenchId, workbenchViewId, label, icon, component };
- const register = useCallback(
- (fullScreen: boolean) => {
- const v = viewRef.current;
- registerCustomWorkbenchView({
- id: v.workbenchViewId,
- workbenchId: v.workbenchId,
- label: v.label,
- icon: v.icon,
- component: v.component,
- hideToolPanel: fullScreen,
- hideTopControls: fullScreen,
- });
- },
- [registerCustomWorkbenchView],
- );
- const takeOverRef = useRef(takeOverScreen);
- takeOverRef.current = takeOverScreen;
useEffect(() => {
- const v = viewRef.current;
- register(takeOverRef.current);
- setCustomWorkbenchViewData(v.workbenchViewId, { kind: "pdfTextEditor" });
setLeftPanelView("toolContent");
- return () => {
- clearCustomWorkbenchViewData(v.workbenchViewId);
- unregisterCustomWorkbenchView(v.workbenchViewId);
- };
- }, [
- register,
- unregisterCustomWorkbenchView,
- setCustomWorkbenchViewData,
- clearCustomWorkbenchViewData,
- setLeftPanelView,
- ]);
-
- const registeredTakeOverRef = useRef(takeOverScreen);
- useEffect(() => {
- if (registeredTakeOverRef.current === takeOverScreen) return;
- registeredTakeOverRef.current = takeOverScreen;
- register(takeOverScreen);
- }, [register, takeOverScreen]);
+ }, [setLeftPanelView]);
const actionsRef = useRef(navigationActions);
actionsRef.current = navigationActions;
const pin = useCallback(() => {
- actionsRef.current.setWorkbench(workbenchId);
- }, [workbenchId]);
+ actionsRef.current.setWorkbench("viewer");
+ }, []);
- // Open the canvas once, when the tool is picked. Re-pinning on every
+ // Open the viewer once, when the tool is picked. Re-pinning on every
// workbench change would bounce the user straight back here the moment they
// switch to Active Files to choose a different file.
const pinnedRef = useRef(false);
@@ -104,9 +34,9 @@ export function useWorkbenchPin({
}
if (pinnedRef.current) return;
pinnedRef.current = true;
- if (navigationState.workbench === workbenchId) return;
- actionsRef.current.setWorkbench(workbenchId);
- }, [navigationState.selectedTool, navigationState.workbench, workbenchId]);
+ if (navigationState.workbench === "viewer") return;
+ actionsRef.current.setWorkbench("viewer");
+ }, [navigationState.selectedTool, navigationState.workbench]);
return pin;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorSession.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorSession.ts
index a501d01234..44c60169d1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorSession.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorSession.ts
@@ -1,13 +1,12 @@
import { useSyncExternalStore } from "react";
-import type { FileId } from "@editor/types/file";
export interface EditorSession {
fileName: string | null;
- fileId: FileId | null;
save: () => void;
download: () => void;
- pickFile: (file: File) => void;
pickImage: () => void;
+ /** Brings a page on screen, mounted or not. */
+ revealPage: (pageIndex: number) => void;
}
let current: EditorSession | null = null;
@@ -31,6 +30,11 @@ function getSnapshot(): EditorSession | null {
return current;
}
+/** The session as it stands, for event handlers outside React's render. */
+export function currentEditorSession(): EditorSession | null {
+ return current;
+}
+
export function useEditorSession(): EditorSession | null {
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
index 0c3ccba048..082ac8bbf4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
@@ -20,6 +20,7 @@ import {
resetPerCharBranchPtrs,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import type { FileId } from "@editor/types/file";
import { AdoptTableCommand } from "@editor/tools/pdfTextEditor/commands/AdoptTableCommand";
import {
adoptedTableId,
@@ -83,8 +84,6 @@ export interface EditorViewState {
// Set when a load hit a password-protected PDF and the UI should prompt.
// `retry` is true after a wrong password so the prompt can say so.
passwordPrompt: { fileName: string; retry: boolean } | null;
- /** Pixel scale at which previews are rendered. */
- renderScale: number;
/** What clicks on the page area do. */
mode: InteractionMode;
/** How the reader clusters source text into editable runs. */
@@ -119,7 +118,6 @@ const INITIAL: EditorViewState = {
progress: null,
error: null,
passwordPrompt: null,
- renderScale: 1.5,
mode: "select",
groupingMode: "auto",
widthMode: "grow",
@@ -134,6 +132,15 @@ const INITIAL: EditorViewState = {
export class EditorStore {
readonly history: HistoryStack;
readonly selection: Selection;
+ /**
+ * The workbench file the document was opened from and the name it saves
+ * under. Kept with the document, which outlives the editor's panel when a
+ * layout change remounts it.
+ */
+ source: { fileId: FileId | null; fileName: string | null } = {
+ fileId: null,
+ fileName: null,
+ };
private doc: EditorDocument | null;
private state: EditorViewState;
private listeners: Set<(s: EditorViewState) => void>;
@@ -215,10 +222,6 @@ export class EditorStore {
return this._pendingPasswordFile;
}
- setRenderScale(scale: number): void {
- this.patch({ renderScale: scale });
- }
-
setMode(mode: InteractionMode): void {
this.patch({ mode });
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts
index a9e1a85e84..5a71ae0a49 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts
@@ -1,3 +1,5 @@
+import { currentEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
+
/** True when focus is in a typing surface (contenteditable, input, etc). */
export function isFocusInContentEditable(): boolean {
const el = document.activeElement as HTMLElement | null;
@@ -16,27 +18,7 @@ export function isFocusInFormField(): boolean {
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
}
-// Find the page index whose midpoint is closest to the viewport's vertical
-// centre.
-export function findVisiblePageIndex(): number {
- const pages = pageElements();
- if (pages.length === 0) return 0;
- const midY = window.innerHeight / 2;
- let best = 0;
- let bestDist = Number.POSITIVE_INFINITY;
- pages.forEach((el, i) => {
- const rect = el.getBoundingClientRect();
- const dist = Math.abs(rect.top + rect.height / 2 - midY);
- if (dist < bestDist) {
- bestDist = dist;
- best = i;
- }
- });
- return best;
-}
-
-// The TRUE page index of the page nearest the viewport centre - unlike {@link
-// findVisiblePageIndex}, which returns a DOM-array position.
+// The page index of the page nearest the viewport centre.
export function visiblePageNumber(): number {
const pages = pageElements();
if (pages.length === 0) return 0;
@@ -57,8 +39,17 @@ export function visiblePageNumber(): number {
}
/** All real page surfaces in DOM order, skipping placeholders/error tiles. */
-export function pageElements(): HTMLElement[] {
+function pageElements(): HTMLElement[] {
return Array.from(
document.querySelectorAll<HTMLElement>('[data-testid^="pdf-editor-page-"]'),
).filter((el) => /^pdf-editor-page-\d+$/.test(el.dataset.testid ?? ""));
}
+
+/**
+ * Scrolls `el` into view, or, when its page is not mounted, asks the host to
+ * bring that page on screen.
+ */
+export function revealOnPage(el: Element | null, pageIndex: number): void {
+ if (el) el.scrollIntoView({ block: "center", behavior: "smooth" });
+ else currentEditorSession()?.revealPage(pageIndex);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fitToWidth.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fitToWidth.ts
deleted file mode 100644
index 44ec624033..0000000000
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fitToWidth.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export const MIN_RENDER_SCALE = 0.25;
-export const MAX_RENDER_SCALE = 4;
-
-export function fitToWidthScale(
- stageWidth: number,
- pageWidth: number,
- paddingPx: number,
-): number {
- const raw = (stageWidth - paddingPx) / Math.max(1, pageWidth);
- return clampRenderScale(raw);
-}
-
-export function clampRenderScale(scale: number): number {
- return +Math.min(MAX_RENDER_SCALE, Math.max(MIN_RENDER_SCALE, scale)).toFixed(
- 2,
- );
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/locateViewerText.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/locateViewerText.ts
new file mode 100644
index 0000000000..ecc952dae5
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/locateViewerText.ts
@@ -0,0 +1,109 @@
+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import type {
+ PageSnapshot,
+ TextRange,
+} from "@editor/tools/pdfTextEditor/types";
+
+/** A box on the page in PDF points, measured from the top-left corner. */
+export interface ViewerRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/**
+ * The run holding the start of text selected in the viewer, and the span of
+ * it that run holds. The viewer and the editor split a page's text into
+ * different pieces, so the match is the longest start of the selection's
+ * first line that one run contains. Where several runs hold it equally, the
+ * one nearest the viewer's selection wins, and where a run holds it more than
+ * once, the copy nearest the selection's place in the run's reading order.
+ */
+export function locateViewerText(
+ page: PageSnapshot,
+ text: string,
+ near?: ViewerRect,
+): { runId: string; range: TextRange } | null {
+ const line = text
+ .split(/\r?\n/)
+ .map((l) => l.trim())
+ .find((l) => l.length > 0);
+ if (!line) return null;
+
+ const point = near ? pointInPdf(page, near) : null;
+ let best: { run: Run; length: number; distance: number } | null = null;
+ for (const run of page.runs) {
+ const length = longestPrefixIn(line, run.text);
+ if (length === 0 || (best && length < best.length)) continue;
+ const distance = point ? distanceTo(run.bounds, point) : 0;
+ if (!best || length > best.length || distance < best.distance) {
+ best = { run, length, distance };
+ }
+ }
+ if (!best) return null;
+ const { run, length } = best;
+ const start = nearestCopy(run, line.slice(0, length), point);
+ return { runId: run.id, range: { start, end: start + length } };
+}
+
+type Run = PageSnapshot["runs"][number];
+type Point = { x: number; y: number };
+
+function longestPrefixIn(line: string, text: string): number {
+ let lo = 0;
+ let hi = Math.min(line.length, text.length);
+ while (lo < hi) {
+ const mid = Math.ceil((lo + hi) / 2);
+ if (text.includes(line.slice(0, mid))) lo = mid;
+ else hi = mid - 1;
+ }
+ return lo;
+}
+
+/**
+ * The centre of the viewer's selection in PDF space. Only an unrotated page
+ * shares the viewer's axes; on any other there is no point, which leaves the
+ * first match.
+ */
+function pointInPdf(page: PageSnapshot, near: ViewerRect): Point | null {
+ if (page.display.rotate !== 0) return null;
+ return DisplayTransform.fromData(page.display).invert(
+ near.x + near.width / 2,
+ page.display.displayHeight - (near.y + near.height / 2),
+ );
+}
+
+function distanceTo(b: Run["bounds"], p: Point): number {
+ return Math.hypot(b.x + b.width / 2 - p.x, b.y + b.height / 2 - p.y);
+}
+
+/**
+ * Offset of the copy of `part` nearest `point`. A run keeps no per-character
+ * positions, so the point's place in the run is estimated from its line, its
+ * lines taken as evenly spaced, and how far along that line it sits.
+ */
+function nearestCopy(run: Run, part: string, point: Point | null): number {
+ const first = run.text.indexOf(part);
+ const b = run.bounds;
+ if (!point || b.width <= 0 || b.height <= 0) return first;
+ const lines = Math.max(1, run.paragraphLineCount ?? 1);
+ const down = clamp01((b.y + b.height - point.y) / b.height);
+ const across = clamp01((point.x - b.x) / b.width);
+ const along =
+ (Math.min(lines - 1, Math.floor(down * lines)) + across) / lines;
+ let best = first;
+ let bestGap = Infinity;
+ for (let i = first; i !== -1; i = run.text.indexOf(part, i + 1)) {
+ const gap = Math.abs((i + part.length / 2) / run.text.length - along);
+ if (gap < bestGap) {
+ best = i;
+ bestGap = gap;
+ }
+ }
+ return best;
+}
+
+function clamp01(n: number): number {
+ return Math.min(1, Math.max(0, n));
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
new file mode 100644
index 0000000000..855cc29a8e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
@@ -0,0 +1,144 @@
+import i18n from "i18next";
+import { alert } from "@editor/components/toast";
+import { ensurePageRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ scanBlockOffInk,
+ wrapScanText,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { MoveShapeCommand } from "@editor/tools/pdfTextEditor/commands/MoveShapeCommand";
+import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";
+import { InsertTableCommand } from "@editor/tools/pdfTextEditor/commands/InsertTableCommand";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
+import type { TextRange } from "@editor/tools/pdfTextEditor/types";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+
+const cache = new WeakMap<EditorStore, PageViewHandlers>();
+
+/**
+ * The page views' handlers, made once per store: PageView is memoised, so a
+ * handler made per render would re-render every page on any store change.
+ * They read the store when called, never state captured at render.
+ */
+export function pageViewHandlers(store: EditorStore): PageViewHandlers {
+ let handlers = cache.get(store);
+ if (!handlers) {
+ handlers = createHandlers(store);
+ cache.set(store, handlers);
+ }
+ return handlers;
+}
+
+type PageViewHandlers = ReturnType<typeof createHandlers>;
+
+function createHandlers(store: EditorStore) {
+ return {
+ onSelectRun: (runId: string, shiftKey: boolean) => {
+ if (shiftKey) store.selection.toggle(runId);
+ else store.selection.selectOne(runId);
+ },
+ onSelectRunText: (runId: string, range: TextRange | null) =>
+ store.selection.setTextRange(runId, range),
+ onSelectImage: (imageId: string) => store.selection.selectImage(imageId),
+ onSelectShape: (shapeId: string, extend: boolean) => {
+ if (extend) store.selection.toggleShape(shapeId);
+ else store.selection.selectShape(shapeId);
+ },
+ onMoveShape: (
+ pageIndex: number,
+ shapeId: string,
+ dx: number,
+ dy: number,
+ ) => {
+ store.dispatch(new MoveShapeCommand({ pageIndex, shapeId, dx, dy }));
+ store.selection.selectShape(shapeId);
+ },
+ onEditRun: (pageIndex: number, runId: string, nextText: string) => {
+ // contentEditable can fire several input events per keystroke burst.
+ const current = store.document?.page(pageIndex).findRun(runId);
+ if (current && current.text === nextText) return;
+ store.dispatch(new EditTextCommand({ pageIndex, runId, nextText }));
+ const doc = store.document;
+ const run = doc?.page(pageIndex).findRun(runId);
+ if (doc && run && scanBlockOffInk(doc, run))
+ alert({
+ alertType: "warning",
+ title: i18n.t(
+ "pdfTextEditor.error.scanOffInk",
+ "Can't edit this text: its recognised words don't line up with the scan. Run OCR again.",
+ ),
+ expandable: false,
+ });
+ },
+ onMoveRun: (pageIndex: number, runId: string, dx: number, dy: number) => {
+ store.dispatch(new MoveTextRunCommand({ pageIndex, runId, dx, dy }));
+ },
+ onWrapRun: (pageIndex: number, runId: string, maxWidthPt: number) => {
+ const doc = store.document;
+ const page = doc?.page(pageIndex);
+ const run = page?.findRun(runId);
+ const wrapped =
+ doc && page && run ? wrapScanText(doc, page, run, maxWidthPt) : null;
+ if (wrapped !== null) {
+ if (wrapped !== run?.text)
+ store.dispatch(
+ new EditTextCommand({ pageIndex, runId, nextText: wrapped }),
+ );
+ return;
+ }
+ store.dispatch(new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }));
+ },
+ onResizeRun: (pageIndex: number, runId: string, widthPt: number) => {
+ store.dispatch(
+ new ReflowWrapCommand({
+ pageIndex,
+ runId,
+ maxWidthPt: widthPt,
+ explicit: true,
+ }),
+ );
+ },
+ onPageClick: (pageIndex: number, pageX: number, pageY: number) => {
+ const { mode } = store.getState();
+ if (mode === "addTable") {
+ const cmd = new InsertTableCommand({
+ pageIndex,
+ x: pageX,
+ y: pageY,
+ width: 360,
+ height: 24 * 3,
+ rows: 3,
+ cols: 3,
+ });
+ store.dispatch(cmd);
+ store.setMode("select");
+ return;
+ }
+ if (mode !== "addText") return;
+ const cmd = new InsertTextCommand({
+ pageIndex,
+ x: pageX,
+ y: pageY,
+ text: "New text",
+ });
+ store.dispatch(cmd);
+ if (cmd.insertedRunId) store.selection.selectOne(cmd.insertedRunId);
+ store.setMode("select");
+ },
+ onTransformImage: (
+ pageIndex: number,
+ imageId: string,
+ nextBounds: { x: number; y: number; width: number; height: number },
+ ) => {
+ store.dispatch(
+ new SetImageTransformCommand({ pageIndex, imageId, nextBounds }),
+ );
+ },
+ onFirstVisible: (pageIndex: number) => ensurePageRead(store, pageIndex),
+ onFirstRendered: (pageIndex: number) => {
+ if (pageIndex === 0) store.markFirstPageRendered();
+ },
+ };
+}