Skip to content

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

Replace multi-tool with redesigned Page Editor (#7618)

James Brunton05cc2b66ba80
diff --git a/AGENTS.md b/AGENTS.md
index 462c9ab58f..91ab0c08e9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -426,7 +426,7 @@ The frontend is organized with a clear separation of concerns:
- **`core/components/`**: React components organized by feature
- `core/components/tools/`: Individual PDF tool implementations
- `core/components/viewer/`: PDF viewer components
- - `core/components/pageEditor/`: Page manipulation UI
+ - `core/components/pageTracks/`: Page editor (every open PDF as a track of pages)
- `core/components/tooltips/`: Help tooltips for tools
- `core/components/shared/`: Reusable UI components
- **`core/contexts/`**: React Context providers
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 977e46189c..622ea08e4d 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6595,63 +6595,6 @@ yourCloudAccess = "You'll become a team member and lose owner access."
deselectAll = "None"
selectAll = "Check All"
-[pageEditor]
-dragPreviewAlt = "Dragging"
-filePosition = "Position {{position}}"
-pageLabel = "Page {{page}}"
-title = "Page Editor"
-
-[pageEditor.actions]
-deletePage = "Delete Page"
-insertFileAfter = "Insert File After"
-moveLeft = "Move Left"
-moveRight = "Move Right"
-rotateLeft = "Rotate Left"
-rotateRight = "Rotate Right"
-splitAfter = "Split After"
-
-[pageEditor.commands]
-addSplitAt = "Add split at position {{position}}"
-addSplits_one = "Add {{count}} split"
-addSplits_other = "Add {{count}} splits"
-deletePages_one = "Delete {{count}} page"
-deletePages_other = "Delete {{count}} pages"
-insertFiles_one = "Insert {{count}} file after page {{page}}"
-insertFiles_other = "Insert {{count}} files after page {{page}}"
-insertPageBreaks_one = "Insert {{count}} page break"
-insertPageBreaks_other = "Insert {{count}} page breaks"
-insertPageBreaksAll = "Insert page breaks after all pages"
-removeAllSplits = "Remove all splits"
-removeSplitAt = "Remove split at position {{position}}"
-removeSplits_one = "Remove {{count}} split"
-removeSplits_other = "Remove {{count}} splits"
-reorderPages = "Reorder pages"
-rotatePageLeft = "Rotate page left"
-rotatePageRight = "Rotate page right"
-rotatePagesLeft_one = "Rotate {{count}} page left"
-rotatePagesLeft_other = "Rotate {{count}} pages left"
-rotatePagesRight_one = "Rotate {{count}} page right"
-rotatePagesRight_other = "Rotate {{count}} pages right"
-splitAllPages = "Split all pages"
-toggleSplits_one = "Toggle {{count}} split position"
-toggleSplits_other = "Toggle {{count}} split positions"
-
-[pageEditor.emptyState]
-body = "Add files to start editing pages"
-title = "No PDF files loaded"
-
-[pageEditor.fileDropdown]
-addFile = "Add File"
-selectedCount = "{{selected}}/{{total}} files selected"
-untitled = "Untitled"
-
-[pageEditor.toolbar]
-delete = "Delete Selected"
-redo = "Redo"
-rotateLeft = "Rotate Selected Left"
-rotateRight = "Rotate Selected Right"
-undo = "Undo"
-
[pageExtracter]
title = "Extract Pages"
@@ -6816,6 +6759,68 @@ title = "Page Ranges"
bullet1 = "<strong>all</strong> → selects all pages"
title = "Special Keywords"
+[pageTracks]
+blankPage = "Blank page"
+deleteSelected = "Delete selected pages"
+dragging_one = "{{count}} page"
+dragging_other = "{{count}} pages"
+edited = "edited"
+emptyTrack = "No pages left. Drag pages here, or save to close this file."
+insertBlank = "Insert blank page"
+insertBlankAfterSelected = "Insert blank pages after selected pages"
+moveLeft = "Move left"
+moveRight = "Move right"
+nextPage = "Next page"
+page = "Page {{number}}"
+pageCount_one = "{{count}} page"
+pageCount_other = "{{count}} pages"
+pagePosition = "Page {{number}} of {{total}}"
+prevPage = "Previous page"
+readingPages = "Reading pages..."
+redo = "Redo"
+rotateLeft = "Rotate left"
+rotateRight = "Rotate right"
+rotateSelectedLeft = "Rotate selected pages left"
+rotateSelectedRight = "Rotate selected pages right"
+saveChanges = "Save changes to all files"
+saving = "Saving..."
+savingProgress = "Saving {{done}} of {{total}}"
+selectPage = "Select page {{number}}"
+splitAfterSelected = "Split after selected pages"
+splitHere = "Split here"
+undo = "Undo"
+viewError = "Couldn't render this page"
+viewPage = "View page"
+zoomIn = "Zoom in"
+zoomOut = "Zoom out"
+
+[pageTracks.close]
+message = "Are you sure you want to close all files?"
+unsaved = "These files have unsaved changes."
+
+[pageTracks.delete]
+page = "Delete page"
+
+[pageTracks.empty]
+body = "Add PDFs to expand them into editable page tracks"
+title = "No PDF files loaded"
+
+[pageTracks.exportFailed]
+body = "The edited files couldn't be prepared. Try again."
+title = "Couldn't download"
+
+[pageTracks.saveFailed]
+body = "Your edits haven't been lost. Try saving again."
+title = "Couldn't save changes"
+
+[pageTracks.track]
+close = "Close file"
+collapse = "Collapse"
+expand = "Expand"
+
+[pageTracks.wrap]
+label = "Wrap pages"
+
[payg.activity]
docs = "docs"
empty = "No billable activity yet this period."
@@ -13927,16 +13932,13 @@ annotations = "Annotations"
applyRedactionsFirst = "Apply redactions first"
closeAll = "Close All Files"
closePdf = "Close PDF"
-deleteSelected = "Delete Selected Pages"
deselectAll = "Deselect All"
downloadAll = "Download All"
exitRedaction = "Exit Redaction Mode"
-exportAll = "Export PDF"
-exportSelected = "Export Selected Pages"
formFill = "Form Editor"
hideToolbar = "Hide toolbar"
moreActions = "More actions"
-multiTool = "Multi-Tool"
+pageEditor = "Page Editor"
panMode = "Pan Mode"
print = "Print PDF"
readAloud = "Read Aloud"
@@ -13950,7 +13952,6 @@ rulerSettings = "Scale Settings"
save = "Save"
saveAll = "Save All"
saveAs = "Save As"
-saveChanges = "Save Changes"
search = "Search PDF"
selectAll = "Select All"
selectByNumber = "Select by Page Numbers"
diff --git a/frontend/editor/src/core/components/AppProviders.tsx b/frontend/editor/src/core/components/AppProviders.tsx
index 6d9db23cd2..1242cc0039 100644
--- a/frontend/editor/src/core/components/AppProviders.tsx
+++ b/frontend/editor/src/core/components/AppProviders.tsx
@@ -26,7 +26,6 @@ import { SigningOverlayProvider } from "@app/contexts/SigningOverlayContext";
import { AnnotationProvider } from "@app/contexts/AnnotationContext";
import { TourOrchestrationProvider } from "@app/contexts/TourOrchestrationContext";
import { AdminTourOrchestrationProvider } from "@app/contexts/AdminTourOrchestrationContext";
-import { PageEditorProvider } from "@app/contexts/PageEditorContext";
import { BannerProvider } from "@app/contexts/BannerContext";
import ErrorBoundary from "@app/components/shared/ErrorBoundary";
import { useAppInitialization } from "@app/hooks/useAppInitialization";
@@ -142,26 +141,24 @@ export function AppProviders({
<HotkeyProvider>
<SidebarProvider>
<ViewerProvider>
- <PageEditorProvider>
- <SignatureProvider>
- <SigningOverlayProvider>
- <RedactionProvider>
- <FormFillProvider>
- <AnnotationProvider>
- <WorkbenchBarProvider>
- <TourOrchestrationProvider>
- <AdminTourOrchestrationProvider>
- <WorkbenchSessionPersistence />
- {children}
- </AdminTourOrchestrationProvider>
- </TourOrchestrationProvider>
- </WorkbenchBarProvider>
- </AnnotationProvider>
- </FormFillProvider>
- </RedactionProvider>
- </SigningOverlayProvider>
- </SignatureProvider>
- </PageEditorProvider>
+ <SignatureProvider>
+ <SigningOverlayProvider>
+ <RedactionProvider>
+ <FormFillProvider>
+ <AnnotationProvider>
+ <WorkbenchBarProvider>
+ <TourOrchestrationProvider>
+ <AdminTourOrchestrationProvider>
+ <WorkbenchSessionPersistence />
+ {children}
+ </AdminTourOrchestrationProvider>
+ </TourOrchestrationProvider>
+ </WorkbenchBarProvider>
+ </AnnotationProvider>
+ </FormFillProvider>
+ </RedactionProvider>
+ </SigningOverlayProvider>
+ </SignatureProvider>
</ViewerProvider>
</SidebarProvider>
</HotkeyProvider>
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
index b60619601d..925f90a364 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -34,6 +34,7 @@ import HoverActionMenu, {
} from "@app/components/shared/HoverActionMenu";
import { downloadFileWithPolicy as downloadFile } from "@app/services/exportWithPolicy";
import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { CloseFilesConfirmModal } from "@app/components/shared/CloseFilesConfirmModal";
import UploadToServerModal from "@app/components/shared/UploadToServerModal";
import ShareFileModal from "@app/components/shared/ShareFileModal";
import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryModal";
@@ -685,58 +686,28 @@ const FileEditorThumbnail = ({
<p className={styles.fileMeta}>{metaLine}</p>
</div>
- {/* Close Confirmation Modal */}
- <Modal
+ <CloseFilesConfirmModal
opened={showCloseModal}
- onClose={handleCancelClose}
- title={t("confirmClose", "Confirm Close")}
- centered
- size="auto"
- >
- <Stack gap="md">
- {file.isDirty && file.localFilePath ? (
- <>
- <Text size="md">
- {t("confirmCloseUnsaved", "This file has unsaved changes.")}
- </Text>
- <Text size="sm" c="dimmed" fw={500}>
- <PrivateContent>{file.name}</PrivateContent>
- </Text>
- <Group justify="flex-end" gap="sm">
- <Button variant="secondary" onClick={handleCancelClose}>
- {t("confirmCloseCancel", "Cancel")}
- </Button>
- <Button accent="danger" onClick={handleConfirmClose}>
- {t("confirmCloseDiscard", "Discard changes and close")}
- </Button>
- <Button onClick={handleSaveAndClose}>
- {t("confirmCloseSave", "Save and close")}
- </Button>
- </Group>
- </>
- ) : (
- <>
- <Text size="md">
- {t(
- "confirmCloseMessage",
- "Are you sure you want to close this file?",
- )}
- </Text>
- <Text size="sm" c="dimmed" fw={500}>
- <PrivateContent>{file.name}</PrivateContent>
- </Text>
- <Group justify="flex-end" gap="sm">
- <Button variant="secondary" onClick={handleCancelClose}>
- {t("confirmCloseCancel", "Cancel")}
- </Button>
- <Button accent="danger" onClick={handleConfirmClose}>
- {t("confirmCloseConfirm", "Close File")}
- </Button>
- </Group>
- </>
- )}
- </Stack>
- </Modal>
+ message={
+ file.isDirty && file.localFilePath
+ ? t("confirmCloseUnsaved", "This file has unsaved changes.")
+ : t(
+ "confirmCloseMessage",
+ "Are you sure you want to close this file?",
+ )
+ }
+ files={[{ id: file.id, name: file.name }]}
+ closeLabel={
+ file.isDirty && file.localFilePath
+ ? t("confirmCloseDiscard", "Discard changes and close")
+ : t("confirmCloseConfirm", "Close File")
+ }
+ onClose={handleConfirmClose}
+ onCancel={handleCancelClose}
+ onSave={
+ file.isDirty && file.localFilePath ? handleSaveAndClose : undefined
+ }
+ />
{/* Shared edit notice modal */}
<Modal
diff --git a/frontend/editor/src/core/components/layout/Workbench.tsx b/frontend/editor/src/core/components/layout/Workbench.tsx
index 8c98c7c781..66ede9761d 100644
--- a/frontend/editor/src/core/components/layout/Workbench.tsx
+++ b/frontend/editor/src/core/components/layout/Workbench.tsx
@@ -25,16 +25,13 @@ import { ChatFAB } from "@app/components/chat/ChatFAB";
import { NotificationBell } from "@app/components/notifications/NotificationBell";
// Workbench panels are loaded on demand. Viewer pulls in pdfjs-dist and the
-// full @embedpdf plugin set; FileEditor/PageEditor are only needed once a file
+// full @embedpdf plugin set; FileEditor/PageTracks are only needed once a file
// is open. Lazy-loading keeps all of that out of the initial bundle.
const SigningWorkspace = lazy(
() => import("@app/components/shared/signing/SigningWorkspace"),
);
const FileEditor = lazy(() => import("@app/components/fileEditor/FileEditor"));
-const PageEditor = lazy(() => import("@app/components/pageEditor/PageEditor"));
-const PageEditorControls = lazy(
- () => import("@app/components/pageEditor/PageEditorControls"),
-);
+const PageTracks = lazy(() => import("@app/components/pageTracks/PageTracks"));
const Viewer = lazy(() => import("@app/components/viewer/Viewer"));
const FileManagerView = lazy(
() => import("@app/components/filesPage/FileManagerView"),
@@ -52,14 +49,8 @@ export default function Workbench() {
const { workbench: currentView } = useNavigationState();
const { actions: navActions } = useNavigationActions();
const setCurrentView = navActions.setWorkbench;
- const {
- previewFile,
- pageEditorFunctions,
- setPreviewFile,
- setPageEditorFunctions,
- customWorkbenchViews,
- readerMode,
- } = useToolWorkflow();
+ const { previewFile, setPreviewFile, customWorkbenchViews, readerMode } =
+ useToolWorkflow();
const { handleToolSelect } = useToolWorkflow();
// Below this width the rail, and the bell it carries, is gone.
@@ -202,43 +193,7 @@ export default function Workbench() {
);
case "pageEditor":
- return (
- <div style={{ position: "relative", flex: "1 1 0", height: 0 }}>
- <PageEditor onFunctionsReady={setPageEditorFunctions} />
- {pageEditorFunctions && (
- <div
- style={{
- position: "absolute",
- bottom: 0,
- left: 0,
- right: 0,
- zIndex: 100,
- }}
- >
- <PageEditorControls
- onClosePdf={pageEditorFunctions.closePdf}
- onUndo={pageEditorFunctions.handleUndo}
- onRedo={pageEditorFunctions.handleRedo}
- canUndo={pageEditorFunctions.canUndo}
- canRedo={pageEditorFunctions.canRedo}
- onRotate={pageEditorFunctions.handleRotate}
- onDelete={pageEditorFunctions.handleDelete}
- onSplit={pageEditorFunctions.handleSplit}
- onSplitAll={pageEditorFunctions.handleSplitAll}
- onPageBreak={pageEditorFunctions.handlePageBreak}
- onPageBreakAll={pageEditorFunctions.handlePageBreakAll}
- onExportAll={pageEditorFunctions.onExportAll}
- exportLoading={pageEditorFunctions.exportLoading}
- selectionMode={pageEditorFunctions.selectionMode}
- selectedPageIds={pageEditorFunctions.selectedPageIds}
- displayDocument={pageEditorFunctions.displayDocument}
- splitPositions={pageEditorFunctions.splitPositions}
- totalPages={pageEditorFunctions.totalPages}
- />
- </div>
- )}
- </div>
- );
+ return <PageTracks />;
default:
return null;
diff --git a/frontend/editor/src/core/components/pageEditor/DragDropGrid.module.css b/frontend/editor/src/core/components/pageEditor/DragDropGrid.module.css
deleted file mode 100644
index 519ec608e0..0000000000
--- a/frontend/editor/src/core/components/pageEditor/DragDropGrid.module.css
+++ /dev/null
@@ -1,72 +0,0 @@
-.gridContainer {
- width: 100%;
- height: 100%;
- position: relative;
- overflow: hidden;
-}
-
-.virtualRows {
- width: 100%;
- position: relative;
- margin: 0 auto;
-}
-
-.virtualRow {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
-}
-
-.rowContent {
- display: flex;
- justify-content: flex-start;
- height: 100%;
- align-items: center;
- position: relative;
-}
-
-.selectionBox {
- position: absolute;
- border: 2px dashed var(--c-primary);
- background-color: color-mix(in srgb, var(--c-primary) 10%, transparent);
- pointer-events: none;
-}
-
-.dropIndicator {
- position: absolute;
- width: 4px;
- background-color: color-mix(in srgb, var(--c-primary) 80%, transparent);
- border-radius: 2px;
- pointer-events: none;
-}
-
-.dragOverlay {
- position: relative;
- cursor: grabbing;
-}
-
-.dragOverlayBadge {
- position: absolute;
- top: -8px;
- right: -8px;
- background-color: var(--c-primary);
- color: var(--c-text-on-primary);
- border-radius: 50%;
- width: 32px;
- height: 32px;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 14px;
- font-weight: bold;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
-}
-
-.dragOverlayPreview {
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 48px;
- opacity: 0.5;
-}
diff --git a/frontend/editor/src/core/components/pageEditor/DragDropGrid.stories.tsx b/frontend/editor/src/core/components/pageEditor/DragDropGrid.stories.tsx
deleted file mode 100644
index a437402985..0000000000
--- a/frontend/editor/src/core/components/pageEditor/DragDropGrid.stories.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import DragDropGrid, {
- type DragHandleProps,
-} from "@app/components/pageEditor/DragDropGrid";
-
-interface MockGridItem {
- id: string;
- pageNumber?: number;
- originalFileId?: string;
-}
-
-const buildItems = (count: number): MockGridItem[] =>
- Array.from({ length: count }, (_, index) => ({
- id: `page-${index + 1}`,
- pageNumber: index + 1,
- originalFileId: "file-1",
- }));
-
-const renderItem = (
- item: MockGridItem,
- index: number,
- refs: React.MutableRefObject<Map<string, HTMLDivElement>>,
- boxSelectedIds: string[],
- clearBoxSelection: () => void,
- activeDragIds: string[],
- justMoved: boolean,
- dragHandleProps?: DragHandleProps,
- zoomLevel?: number,
-) => {
- const { ref: dndRef, ...restDragProps } = dragHandleProps ?? {};
- const isBoxSelected = boxSelectedIds.includes(item.id);
- const isDragging = activeDragIds.includes(item.id);
-
- return (
- <div
- ref={(element: HTMLDivElement | null) => {
- if (element) {
- refs.current.set(item.id, element);
- } else {
- refs.current.delete(item.id);
- }
- dndRef?.(element);
- }}
- {...restDragProps}
- onClick={clearBoxSelection}
- style={{
- width: `calc(10rem * ${zoomLevel ?? 1})`,
- height: `calc(13rem * ${zoomLevel ?? 1})`,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- borderRadius: "0.5rem",
- border: isBoxSelected
- ? "2px solid var(--mantine-color-blue-6)"
- : "1px solid var(--mantine-color-gray-4)",
- background: isDragging
- ? "var(--mantine-color-gray-1)"
- : "var(--mantine-color-body)",
- opacity: justMoved ? 0.7 : 1,
- cursor: "grab",
- }}
- >
- Page {item.pageNumber ?? index + 1}
- </div>
- );
-};
-
-const noopReorder = () => {};
-
-const meta = {
- title: "PageEditor/DragDropGrid",
- component: DragDropGrid,
- parameters: { layout: "fullscreen" },
-} satisfies Meta<typeof DragDropGrid>;
-export default meta;
-
-type Story = StoryObj<typeof meta>;
-
-const ScrollDecorator = (StoryComponent: React.ComponentType) => (
- <div
- data-scrolling-container="true"
- style={{ height: "40rem", overflow: "auto" }}
- >
- <StoryComponent />
- </div>
-);
-
-export const Default: Story = {
- args: {
- items: buildItems(8),
- onReorderPages: noopReorder,
- renderItem,
- },
- decorators: [ScrollDecorator],
-};
-
-export const Empty: Story = {
- args: {
- items: [],
- onReorderPages: noopReorder,
- renderItem,
- },
- decorators: [ScrollDecorator],
-};
-
-export const Zoomed: Story = {
- args: {
- items: buildItems(6),
- onReorderPages: noopReorder,
- renderItem,
- zoomLevel: 1.5,
- },
- decorators: [ScrollDecorator],
-};
diff --git a/frontend/editor/src/core/components/pageEditor/DragDropGrid.tsx b/frontend/editor/src/core/components/pageEditor/DragDropGrid.tsx
deleted file mode 100644
index ecb70967fd..0000000000
--- a/frontend/editor/src/core/components/pageEditor/DragDropGrid.tsx
+++ /dev/null
@@ -1,1037 +0,0 @@
-import React, {
- useRef,
- useEffect,
- useState,
- useCallback,
- useMemo,
-} from "react";
-import { Box } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { useVirtualizer } from "@tanstack/react-virtual";
-import { GRID_CONSTANTS } from "@app/components/pageEditor/constants";
-import styles from "@app/components/pageEditor/DragDropGrid.module.css";
-import {
- Z_INDEX_SELECTION_BOX,
- Z_INDEX_DROP_INDICATOR,
- Z_INDEX_DRAG_BADGE,
-} from "@app/styles/zIndex";
-import { Icon } from "@app/ui/Icon";
-import {
- DndContext,
- DragEndEvent,
- DragStartEvent,
- DragOverlay,
- DraggableAttributes,
- useSensor,
- useSensors,
- PointerSensor,
- closestCenter,
- useDraggable,
- useDroppable,
-} from "@dnd-kit/core";
-
-export type DragHandleProps = DraggableAttributes & {
- ref: React.RefCallback<HTMLElement>;
-} & Record<string, unknown>;
-
-interface DragDropItem {
- id: string;
- splitAfter?: boolean;
- isPlaceholder?: boolean;
- originalFileId?: string;
- pageNumber?: number;
-}
-
-interface DragDropGridProps<T extends DragDropItem> {
- items: T[];
- onReorderPages: (
- sourcePageNumber: number,
- targetIndex: number,
- selectedPageIds?: string[],
- ) => void;
- renderItem: (
- item: T,
- index: number,
- refs: React.MutableRefObject<Map<string, HTMLDivElement>>,
- boxSelectedIds: string[],
- clearBoxSelection: () => void,
- activeDragIds: string[],
- justMoved: boolean,
- dragHandleProps?: DragHandleProps,
- zoomLevel?: number,
- isOverTarget?: boolean,
- ) => React.ReactNode;
- getThumbnailData?: (
- itemId: string,
- ) => { src: string; rotation: number } | null;
- zoomLevel?: number;
- selectedFileIds?: string[];
- selectedPageIds?: string[];
- onVisibleItemsChange?: (items: T[]) => void;
-}
-
-type DropSide = "left" | "right" | null;
-
-type ItemRect = { id: string; rect: DOMRect };
-
-interface DropHint {
- hoveredId: string | null;
- dropSide: DropSide;
-}
-
-function resolveDropHint(
- activeId: string | null,
- itemRefs: React.MutableRefObject<Map<string, HTMLDivElement>>,
- cursorX: number,
- cursorY: number,
-): DropHint {
- if (!activeId) {
- return { hoveredId: null, dropSide: null };
- }
-
- const items: ItemRect[] = Array.from(itemRefs.current.entries())
- .filter(
- (entry): entry is [string, HTMLDivElement] =>
- !!entry[1] && entry[0] !== activeId,
- )
- .map(([itemId, element]) => ({
- id: itemId,
- rect: element.getBoundingClientRect(),
- }))
- .filter(({ rect }) => rect.width > 0 && rect.height > 0);
-
- if (items.length === 0) {
- return { hoveredId: null, dropSide: null };
- }
-
- items.sort((a, b) => a.rect.top - b.rect.top);
-
- const rows: ItemRect[][] = [];
- const rowTolerance = items[0].rect.height / 2;
-
- items.forEach((item) => {
- const currentRow = rows[rows.length - 1];
- if (!currentRow) {
- rows.push([item]);
- return;
- }
-
- const isSameRow =
- Math.abs(item.rect.top - currentRow[0].rect.top) <= rowTolerance;
- if (isSameRow) {
- currentRow.push(item);
- } else {
- rows.push([item]);
- }
- });
-
- let targetRow: ItemRect[] | undefined;
- let smallestRowDistance = Infinity;
-
- rows.forEach((row) => {
- if (row.length === 0) {
- return;
- }
- const top = row[0].rect.top;
- const bottom = row[0].rect.bottom;
- const centerY = top + (bottom - top) / 2;
- const distance = Math.abs(cursorY - centerY);
- if (distance < smallestRowDistance) {
- smallestRowDistance = distance;
- targetRow = row;
- }
- });
-
- if (!targetRow || targetRow.length === 0) {
- return { hoveredId: null, dropSide: null };
- }
-
- let hoveredItem = targetRow[0];
- let smallestHorizontalDistance = Infinity;
-
- targetRow.forEach((item) => {
- const midpoint = item.rect.left + item.rect.width / 2;
- const distance = Math.abs(cursorX - midpoint);
- if (distance < smallestHorizontalDistance) {
- smallestHorizontalDistance = distance;
- hoveredItem = item;
- }
- });
-
- const firstItem = targetRow[0];
- const lastItem = targetRow[targetRow.length - 1];
-
- let dropSide: DropSide;
- if (cursorX < firstItem.rect.left) {
- hoveredItem = firstItem;
- dropSide = "left";
- } else if (cursorX > lastItem.rect.right) {
- hoveredItem = lastItem;
- dropSide = "right";
- } else {
- const midpoint = hoveredItem.rect.left + hoveredItem.rect.width / 2;
- dropSide = cursorX >= midpoint ? "right" : "left";
- }
-
- return { hoveredId: hoveredItem.id, dropSide };
-}
-
-function resolveTargetIndex<T extends DragDropItem>(
- hoveredId: string | null,
- dropSide: DropSide,
- filteredItems: T[],
- filteredToOriginalIndex: number[],
- originalItemsLength: number,
- fallbackIndex: number | null,
-): number | null {
- const convertFilteredIndexToOriginal = (filteredIndex: number): number => {
- if (filteredToOriginalIndex.length === 0) {
- return 0;
- }
-
- if (filteredIndex <= 0) {
- return filteredToOriginalIndex[0];
- }
-
- if (filteredIndex >= filteredToOriginalIndex.length) {
- return originalItemsLength;
- }
-
- return filteredToOriginalIndex[filteredIndex];
- };
-
- if (hoveredId) {
- const filteredIndex = filteredItems.findIndex(
- (item) => item.id === hoveredId,
- );
- if (filteredIndex !== -1) {
- const adjustedIndex = filteredIndex + (dropSide === "right" ? 1 : 0);
- return convertFilteredIndexToOriginal(adjustedIndex);
- }
- }
-
- if (fallbackIndex !== null && fallbackIndex !== undefined) {
- const adjustedIndex = fallbackIndex + (dropSide === "right" ? 1 : 0);
- return convertFilteredIndexToOriginal(adjustedIndex);
- }
-
- return null;
-}
-
-// Lightweight wrapper that handles dnd-kit hooks for each visible item
-interface DraggableItemProps<T extends DragDropItem> {
- item: T;
- index: number;
- itemRefs: React.MutableRefObject<Map<string, HTMLDivElement>>;
- boxSelectedPageIds: string[];
- clearBoxSelection: () => void;
- activeDragIds: string[];
- justMoved: boolean;
- getThumbnailData?: (
- itemId: string,
- ) => { src: string; rotation: number } | null;
- onUpdateDropTarget: (itemId: string | null) => void;
- renderItem: (
- item: T,
- index: number,
- refs: React.MutableRefObject<Map<string, HTMLDivElement>>,
- boxSelectedIds: string[],
- clearBoxSelection: () => void,
- activeDragIds: string[],
- justMoved: boolean,
- dragHandleProps?: DragHandleProps,
- zoomLevel?: number,
- isOverTarget?: boolean,
- ) => React.ReactNode;
- zoomLevel: number;
- selectedPageIds?: string[];
- isOverTarget: boolean;
-}
-
-const DraggableItemInner = <T extends DragDropItem>({
- item,
- index,
- itemRefs,
- boxSelectedPageIds,
- clearBoxSelection,
- activeDragIds,
- justMoved,
- getThumbnailData,
- renderItem,
- onUpdateDropTarget,
- zoomLevel,
- isOverTarget,
-}: DraggableItemProps<T>) => {
- const isPlaceholder = Boolean(item.isPlaceholder);
- const pageNumber = item.pageNumber ?? index + 1;
- const {
- attributes,
- listeners,
- setNodeRef: setDraggableRef,
- } = useDraggable({
- id: item.id,
- disabled: isPlaceholder,
- data: {
- index,
- pageNumber,
- getThumbnail: () => {
- if (getThumbnailData) {
- const data = getThumbnailData(item.id);
- if (data?.src) return data;
- }
-
- const element = itemRefs.current.get(item.id);
- const imgElement = element?.querySelector(
- "img.ph-no-capture",
- ) as HTMLImageElement;
- if (imgElement?.src) {
- return {
- src: imgElement.src,
- rotation: imgElement.dataset.originalRotation
- ? parseInt(imgElement.dataset.originalRotation)
- : 0,
- };
- }
- return null;
- },
- },
- });
-
- const { setNodeRef: setDroppableRef, isOver } = useDroppable({
- id: item.id,
- data: { index, pageNumber: index + 1 },
- });
-
- // Notify parent when hover state changes
- useEffect(() => {
- if (isOver) {
- onUpdateDropTarget(item.id);
- } else {
- onUpdateDropTarget(null);
- }
- }, [isOver, item.id, onUpdateDropTarget]);
-
- const setNodeRef = useCallback(
- (element: HTMLDivElement | null) => {
- setDraggableRef(element);
- setDroppableRef(element);
- },
- [setDraggableRef, setDroppableRef],
- );
-
- return (
- <>
- {renderItem(
- item,
- index,
- itemRefs,
- boxSelectedPageIds,
- clearBoxSelection,
- activeDragIds,
- justMoved,
- { ref: setNodeRef, ...attributes, ...listeners },
- zoomLevel,
- isOverTarget,
- )}
- </>
- );
-};
-
-// Memoize to prevent unnecessary re-renders and hook thrashing
-const DraggableItem = React.memo(DraggableItemInner, (prevProps, nextProps) => {
- // Return true to SKIP re-render (props are equal)
- // Return false to RE-RENDER (props changed)
-
- // Check if item reference or content changed (including thumbnail)
- const itemChanged = prevProps.item !== nextProps.item;
-
- // If item object reference changed, we need to re-render
- if (itemChanged) {
- return false; // Props changed, re-render needed
- }
-
- // Check if page selection changed (for checkbox selection, not box selection)
- const prevSelectedSet = prevProps.selectedPageIds
- ? new Set(prevProps.selectedPageIds)
- : null;
- const nextSelectedSet = nextProps.selectedPageIds
- ? new Set(nextProps.selectedPageIds)
- : null;
-
- if (prevSelectedSet && nextSelectedSet) {
- const prevSelected = prevSelectedSet.has(prevProps.item.id);
- const nextSelected = nextSelectedSet.has(nextProps.item.id);
- if (prevSelected !== nextSelected) {
- return false; // Selection state changed for this item, re-render needed
- }
- }
-
- // Item reference is same, check other props
- return (
- prevProps.item.id === nextProps.item.id &&
- prevProps.index === nextProps.index &&
- prevProps.justMoved === nextProps.justMoved &&
- prevProps.zoomLevel === nextProps.zoomLevel &&
- prevProps.isOverTarget === nextProps.isOverTarget &&
- prevProps.activeDragIds.length === nextProps.activeDragIds.length &&
- prevProps.boxSelectedPageIds.length === nextProps.boxSelectedPageIds.length
- );
-}) as typeof DraggableItemInner;
-
-const DragDropGrid = <T extends DragDropItem>({
- items,
- renderItem,
- onReorderPages,
- getThumbnailData,
- zoomLevel = 1.0,
- selectedFileIds,
- selectedPageIds,
- onVisibleItemsChange,
-}: DragDropGridProps<T>) => {
- const { t } = useTranslation();
- const itemRefs = useRef<Map<string, HTMLDivElement>>(new Map());
- const containerRef = useRef<HTMLDivElement>(null);
-
- const getScrollElement = useCallback(() => {
- return containerRef.current?.closest(
- "[data-scrolling-container]",
- ) as HTMLElement | null;
- }, []);
-
- // Create stable signature for items to ensure useMemo detects changes
- const itemsSignature = useMemo(
- () => items.map((item) => item.id).join(","),
- [items],
- );
- const selectedFileIdsSignature = useMemo(
- () => selectedFileIds?.join(",") || "",
- [selectedFileIds],
- );
-
- const { filteredItems: visibleItems, filteredToOriginalIndex } =
- useMemo(() => {
- const filtered: T[] = [];
- const indexMap: number[] = [];
- const selectedIds =
- selectedFileIds && selectedFileIds.length > 0
- ? new Set(selectedFileIds)
- : null;
-
- items.forEach((item, index) => {
- const isPlaceholder = Boolean(item.isPlaceholder);
- if (isPlaceholder) {
- return;
- }
-
- const belongsToVisibleFile =
- !selectedIds ||
- !item.originalFileId ||
- selectedIds.has(item.originalFileId);
-
- if (!belongsToVisibleFile) {
- return;
- }
-
- filtered.push(item);
- indexMap.push(index);
- });
-
- return { filteredItems: filtered, filteredToOriginalIndex: indexMap };
- }, [items, selectedFileIds, itemsSignature, selectedFileIdsSignature]);
-
- useEffect(() => {
- const visibleIdSet = new Set(visibleItems.map((item) => item.id));
- itemRefs.current.forEach((_, pageId) => {
- if (!visibleIdSet.has(pageId)) {
- itemRefs.current.delete(pageId);
- }
- });
- }, [visibleItems]);
-
- // Box selection state
- const [boxSelectStart, setBoxSelectStart] = useState<{
- x: number;
- y: number;
- } | null>(null);
- const [boxSelectEnd, setBoxSelectEnd] = useState<{
- x: number;
- y: number;
- } | null>(null);
- const [isBoxSelecting, setIsBoxSelecting] = useState(false);
- const [boxSelectedPageIds, setBoxSelectedPageIds] = useState<string[]>([]);
- const [justMovedIds, setJustMovedIds] = useState<string[]>([]);
- const highlightTimeoutRef = useRef<number | null>(null);
-
- // Drag state
- const [activeId, setActiveId] = useState<string | null>(null);
- const [dragPreview, setDragPreview] = useState<{
- src: string;
- rotation: number;
- } | null>(null);
- const [hoveredItemId, setHoveredItemId] = useState<string | null>(null);
- const [dropSide, setDropSide] = useState<DropSide>(null);
-
- // Configure sensors for dnd-kit with activation constraint
- // Require 10px movement before drag starts to allow clicks for selection
- const sensors = useSensors(
- useSensor(PointerSensor, {
- activationConstraint: {
- distance: 10,
- },
- }),
- );
-
- // Throttled pointer move handler for drop indicator
- // Calculate drop position based on cursor location relative to ALL items, not just hovered item
- useEffect(() => {
- if (!activeId) {
- setDropSide(null);
- setHoveredItemId(null);
- return;
- }
-
- let rafId: number | null = null;
-
- const handlePointerMove = (e: PointerEvent) => {
- // Use the actual cursor position (pointer coordinates)
- const cursorX = e.clientX;
- const cursorY = e.clientY;
-
- if (rafId === null) {
- rafId = requestAnimationFrame(() => {
- const hint = resolveDropHint(activeId, itemRefs, cursorX, cursorY);
- setHoveredItemId(hint.hoveredId);
- setDropSide(hint.dropSide);
- rafId = null;
- });
- }
- };
-
- window.addEventListener("pointermove", handlePointerMove, {
- passive: true,
- });
- return () => {
- window.removeEventListener("pointermove", handlePointerMove);
- if (rafId !== null) {
- cancelAnimationFrame(rafId);
- }
- };
- }, [activeId]);
-
- // Responsive grid configuration
- const [itemsPerRow, setItemsPerRow] = useState(4);
- const OVERSCAN =
- visibleItems.length > 1000
- ? GRID_CONSTANTS.OVERSCAN_LARGE
- : GRID_CONSTANTS.OVERSCAN_SMALL;
-
- // Calculate items per row based on container width
- const calculateItemsPerRow = useCallback(() => {
- if (!containerRef.current) return 4; // Default fallback
-
- const containerWidth = containerRef.current.offsetWidth;
- if (containerWidth === 0) return 4; // Container not measured yet
-
- // Convert rem to pixels for calculation
- const remToPx = parseFloat(
- getComputedStyle(document.documentElement).fontSize,
- );
- const ITEM_WIDTH =
- parseFloat(GRID_CONSTANTS.ITEM_WIDTH) * remToPx * zoomLevel;
- const ITEM_GAP = parseFloat(GRID_CONSTANTS.ITEM_GAP) * remToPx * zoomLevel;
-
- // Calculate how many items fit: (width - gap) / (itemWidth + gap)
- const availableWidth = containerWidth - ITEM_GAP; // Account for first gap
- const itemWithGap = ITEM_WIDTH + ITEM_GAP;
- const calculated = Math.floor(availableWidth / itemWithGap);
-
- return Math.max(1, calculated); // At least 1 item per row
- }, [zoomLevel]);
-
- // Update items per row when container resizes or zoom changes
- useEffect(() => {
- const updateLayout = () => {
- const newItemsPerRow = calculateItemsPerRow();
- setItemsPerRow(newItemsPerRow);
- };
-
- // Initial calculation
- updateLayout();
-
- // Listen for window resize
- window.addEventListener("resize", updateLayout);
-
- // Use ResizeObserver for container size changes
- const resizeObserver = new ResizeObserver(updateLayout);
- if (containerRef.current) {
- resizeObserver.observe(containerRef.current);
- }
-
- return () => {
- window.removeEventListener("resize", updateLayout);
- resizeObserver.disconnect();
- };
- }, [calculateItemsPerRow, zoomLevel]);
-
- // Virtualization with react-virtual library
- const rowVirtualizer = useVirtualizer({
- count: Math.ceil(visibleItems.length / itemsPerRow),
- getScrollElement,
- estimateSize: () => {
- const remToPx = parseFloat(
- getComputedStyle(document.documentElement).fontSize,
- );
- return parseFloat(GRID_CONSTANTS.ITEM_HEIGHT) * remToPx * zoomLevel;
- },
- overscan: OVERSCAN,
- });
-
- const virtualRows = rowVirtualizer.getVirtualItems();
-
- useEffect(() => {
- if (!onVisibleItemsChange) return;
-
- const visibleItemsForCallback: T[] = [];
- virtualRows.forEach((row) => {
- const startIndex = row.index * itemsPerRow;
- const endIndex = Math.min(startIndex + itemsPerRow, visibleItems.length);
- visibleItemsForCallback.push(...visibleItems.slice(startIndex, endIndex));
- });
-
- onVisibleItemsChange(visibleItemsForCallback);
- }, [virtualRows, visibleItems, itemsPerRow, onVisibleItemsChange]);
-
- // Re-measure virtualizer when zoom or items per row changes
- // Also remeasure when items change (not just length) to handle item additions/removals
- const visibleItemsSignature = useMemo(
- () => visibleItems.map((item) => item.id).join(","),
- [visibleItems],
- );
- useEffect(() => {
- rowVirtualizer.measure();
- }, [
- zoomLevel,
- itemsPerRow,
- visibleItems.length,
- visibleItemsSignature,
- rowVirtualizer,
- ]);
-
- // Cleanup highlight timeout on unmount
- useEffect(() => {
- return () => {
- if (highlightTimeoutRef.current) {
- window.clearTimeout(highlightTimeoutRef.current);
- highlightTimeoutRef.current = null;
- }
- };
- }, []);
-
- // Box selection handlers
- const handleMouseDown = useCallback(
- (e: React.MouseEvent) => {
- if (e.button !== 0) return; // Only respond to primary button
-
- const container = containerRef.current;
- if (!container) return;
-
- const clickTarget = e.target as Node;
- let clickedPageId: string | null = null;
-
- itemRefs.current.forEach((element, pageId) => {
- if (element.contains(clickTarget)) {
- clickedPageId = pageId;
- }
- });
-
- if (clickedPageId) {
- // Clicking directly on a page shouldn't initiate box selection
- // but clear previous box selection if clicking outside current group
- if (
- boxSelectedPageIds.length > 0 &&
- !boxSelectedPageIds.includes(clickedPageId)
- ) {
- setBoxSelectedPageIds([]);
- }
- return;
- }
-
- e.preventDefault();
-
- const rect = container.getBoundingClientRect();
- setIsBoxSelecting(true);
- setBoxSelectStart({ x: e.clientX - rect.left, y: e.clientY - rect.top });
- setBoxSelectEnd({ x: e.clientX - rect.left, y: e.clientY - rect.top });
- setBoxSelectedPageIds([]);
- },
- [boxSelectedPageIds],
- );
-
- const handleMouseMove = useCallback(
- (e: React.MouseEvent) => {
- if (!isBoxSelecting || !boxSelectStart) return;
-
- const rect = containerRef.current?.getBoundingClientRect();
- if (!rect) return;
-
- setBoxSelectEnd({ x: e.clientX - rect.left, y: e.clientY - rect.top });
-
- // Calculate which pages intersect with selection box
- const boxLeft = Math.min(boxSelectStart.x, e.clientX - rect.left);
- const boxRight = Math.max(boxSelectStart.x, e.clientX - rect.left);
- const boxTop = Math.min(boxSelectStart.y, e.clientY - rect.top);
- const boxBottom = Math.max(boxSelectStart.y, e.clientY - rect.top);
-
- const selectedIds: string[] = [];
- itemRefs.current.forEach((pageEl, pageId) => {
- const pageRect = pageEl.getBoundingClientRect();
- const pageLeft = pageRect.left - rect.left;
- const pageRight = pageRect.right - rect.left;
- const pageTop = pageRect.top - rect.top;
- const pageBottom = pageRect.bottom - rect.top;
-
- // Check if page intersects with selection box
- const intersects = !(
- pageRight < boxLeft ||
- pageLeft > boxRight ||
- pageBottom < boxTop ||
- pageTop > boxBottom
- );
-
- if (intersects) {
- selectedIds.push(pageId);
- }
- });
-
- setBoxSelectedPageIds(selectedIds);
- },
- [isBoxSelecting, boxSelectStart],
- );
-
- const handleMouseUp = useCallback(() => {
- if (isBoxSelecting) {
- // Keep box-selected pages highlighted (don't clear boxSelectedPageIds yet)
- // They will remain highlighted until next interaction
- setIsBoxSelecting(false);
- setBoxSelectStart(null);
- setBoxSelectEnd(null);
- }
- }, [isBoxSelecting]);
-
- // Function to clear box selection (exposed to child components)
- const clearBoxSelection = useCallback(() => {
- setBoxSelectedPageIds([]);
- }, []);
-
- // Handle drag start
- const handleDragStart = useCallback((event: DragStartEvent) => {
- const activeId = event.active.id as string;
- setActiveId(activeId);
-
- // Call the getter function to get fresh thumbnail data
- const getThumbnail = event.active.data.current?.getThumbnail;
- if (getThumbnail) {
- const thumbnailData = getThumbnail();
- if (thumbnailData?.src) {
- setDragPreview({
- src: thumbnailData.src,
- rotation: thumbnailData.rotation,
- });
- return;
- }
- }
-
- setDragPreview(null);
- }, []);
-
- // Handle drag cancel
- const handleDragCancel = useCallback(() => {
- setActiveId(null);
- setDragPreview(null);
- setHoveredItemId(null);
- setDropSide(null);
- }, []);
-
- // Handle drag end
- const handleDragEnd = useCallback(
- (event: DragEndEvent) => {
- const { active, over } = event;
- const finalDropSide = dropSide;
- setActiveId(null);
- setDragPreview(null);
- setHoveredItemId(null);
- setDropSide(null);
-
- if (!over || active.id === over.id) {
- return;
- }
-
- const activeData = active.data.current;
- if (!activeData) {
- return;
- }
-
- const sourcePageNumber = activeData.pageNumber;
-
- const overData = over?.data.current;
- let targetIndex = resolveTargetIndex(
- hoveredItemId,
- finalDropSide,
- visibleItems,
- filteredToOriginalIndex,
- items.length,
- overData ? overData.index : null,
- );
-
- if (targetIndex === null) {
- return;
- }
- if (targetIndex < 0) targetIndex = 0;
- if (targetIndex > items.length) targetIndex = items.length;
-
- // Check if this page is box-selected
- const isBoxSelected = boxSelectedPageIds.includes(active.id as string);
- const pagesToDrag =
- isBoxSelected && boxSelectedPageIds.length > 0
- ? boxSelectedPageIds
- : undefined;
-
- // Call reorder with page number and target index
- onReorderPages(sourcePageNumber, targetIndex, pagesToDrag);
-
- // Highlight moved pages briefly
- const movedIds = pagesToDrag ?? [active.id as string];
- setJustMovedIds(movedIds);
- if (highlightTimeoutRef.current) {
- window.clearTimeout(highlightTimeoutRef.current);
- }
- highlightTimeoutRef.current = window.setTimeout(() => {
- setJustMovedIds([]);
- highlightTimeoutRef.current = null;
- }, 1200);
-
- // Clear box selection after drag
- if (pagesToDrag) {
- clearBoxSelection();
- }
- },
- [
- boxSelectedPageIds,
- dropSide,
- hoveredItemId,
- visibleItems,
- filteredToOriginalIndex,
- items,
- onReorderPages,
- clearBoxSelection,
- ],
- );
-
- // Calculate optimal width for centering
- const remToPx = parseFloat(
- getComputedStyle(document.documentElement).fontSize,
- );
- const itemWidth = parseFloat(GRID_CONSTANTS.ITEM_WIDTH) * remToPx * zoomLevel;
- const itemGap = parseFloat(GRID_CONSTANTS.ITEM_GAP) * remToPx * zoomLevel;
- const gridWidth = itemsPerRow * itemWidth + (itemsPerRow - 1) * itemGap;
-
- // Calculate selection box dimensions
- const selectionBoxStyle =
- isBoxSelecting && boxSelectStart && boxSelectEnd
- ? {
- left: Math.min(boxSelectStart.x, boxSelectEnd.x),
- top: Math.min(boxSelectStart.y, boxSelectEnd.y),
- width: Math.abs(boxSelectEnd.x - boxSelectStart.x),
- height: Math.abs(boxSelectEnd.y - boxSelectStart.y),
- zIndex: Z_INDEX_SELECTION_BOX,
- }
- : null;
-
- // Calculate drop indicator position
- const dropIndicatorStyle = useMemo(() => {
- if (!hoveredItemId || !dropSide || !activeId) return null;
-
- const element = itemRefs.current.get(hoveredItemId);
- const container = containerRef.current;
- if (!element || !container) return null;
-
- const itemRect = element.getBoundingClientRect();
- const containerRect = container.getBoundingClientRect();
-
- const top = itemRect.top - containerRect.top;
- const height = itemRect.height;
- const left =
- dropSide === "left"
- ? itemRect.left - containerRect.left - itemGap / 2
- : itemRect.right - containerRect.left + itemGap / 2;
-
- return {
- left: `${left}px`,
- top: `${top}px`,
- height: `${height}px`,
- zIndex: Z_INDEX_DROP_INDICATOR,
- };
- }, [hoveredItemId, dropSide, activeId, itemGap, zoomLevel]);
-
- const activeDragIds = useMemo(() => {
- if (!activeId) return [];
- if (boxSelectedPageIds.includes(activeId)) {
- return boxSelectedPageIds;
- }
- return [activeId];
- }, [activeId, boxSelectedPageIds]);
-
- const handleWheelWhileDragging = useCallback(
- (event: React.WheelEvent<HTMLDivElement>) => {
- if (!activeId) {
- return;
- }
-
- const scrollElement = getScrollElement();
- if (!scrollElement) {
- return;
- }
-
- scrollElement.scrollBy({
- top: event.deltaY,
- left: event.deltaX,
- });
-
- event.preventDefault();
- },
- [activeId, getScrollElement],
- );
-
- return (
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragStart={handleDragStart}
- onDragEnd={handleDragEnd}
- onDragCancel={handleDragCancel}
- >
- <Box
- ref={containerRef}
- className={styles.gridContainer}
- onMouseDown={handleMouseDown}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onWheel={handleWheelWhileDragging}
- >
- {selectionBoxStyle && (
- <div className={styles.selectionBox} style={selectionBoxStyle} />
- )}
-
- {dropIndicatorStyle && (
- <div className={styles.dropIndicator} style={dropIndicatorStyle} />
- )}
-
- <div
- className={styles.virtualRows}
- style={{
- height: `${rowVirtualizer.getTotalSize()}px`,
- maxWidth: `${gridWidth}px`,
- margin: "0 auto",
- }}
- >
- {virtualRows.map((virtualRow) => {
- const startIndex = virtualRow.index * itemsPerRow;
- const endIndex = Math.min(
- startIndex + itemsPerRow,
- visibleItems.length,
- );
- const rowItems = visibleItems.slice(startIndex, endIndex);
-
- return (
- <div
- key={virtualRow.index}
- className={styles.virtualRow}
- style={{
- height: `${virtualRow.size}px`,
- transform: `translateY(${virtualRow.start}px)`,
- }}
- >
- <div
- className={styles.rowContent}
- style={{
- gap: `calc(${GRID_CONSTANTS.ITEM_GAP} * ${zoomLevel})`,
- }}
- >
- {rowItems.map((item, itemIndex) => {
- const actualIndex = startIndex + itemIndex;
- return (
- <DraggableItem
- key={item.id}
- item={item}
- index={actualIndex}
- itemRefs={itemRefs}
- boxSelectedPageIds={boxSelectedPageIds}
- clearBoxSelection={clearBoxSelection}
- activeDragIds={activeDragIds}
- justMoved={justMovedIds.includes(item.id)}
- getThumbnailData={getThumbnailData}
- onUpdateDropTarget={setHoveredItemId}
- renderItem={renderItem}
- zoomLevel={zoomLevel}
- selectedPageIds={selectedPageIds}
- isOverTarget={hoveredItemId === item.id}
- />
- );
- })}
- </div>
- </div>
- );
- })}
- </div>
- </Box>
-
- {/* Drag Overlay */}
- <DragOverlay>
- {activeId && (
- <div className={styles.dragOverlay}>
- {boxSelectedPageIds.includes(activeId) &&
- boxSelectedPageIds.length > 1 && (
- <div
- className={styles.dragOverlayBadge}
- style={{ zIndex: Z_INDEX_DRAG_BADGE }}
- >
- {boxSelectedPageIds.length}
- </div>
- )}
- {dragPreview ? (
- <img
- src={dragPreview.src}
- alt={t("pageEditor.dragPreviewAlt", "Dragging")}
- style={{
- width: `calc(20rem * ${zoomLevel})`,
- height: `calc(20rem * ${zoomLevel})`,
- objectFit: "contain",
- transform: `rotate(${dragPreview.rotation}deg)`,
- pointerEvents: "none",
- opacity: 0.5,
- }}
- />
- ) : (
- <div
- className={styles.dragOverlayPreview}
- style={{
- width: `calc(20rem * ${zoomLevel})`,
- height: `calc(20rem * ${zoomLevel})`,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- fontSize: "2rem",
- color: "var(--mantine-color-dimmed)",
- }}
- >
- <Icon name="file-text" size="3rem" />
- </div>
- )}
- </div>
- )}
- </DragOverlay>
- </DndContext>
- );
-};
-
-export default DragDropGrid;
diff --git a/frontend/editor/src/core/components/pageEditor/FileThumbnail.tsx b/frontend/editor/src/core/components/pageEditor/FileThumbnail.tsx
deleted file mode 100644
index 9a450b03fc..0000000000
--- a/frontend/editor/src/core/components/pageEditor/FileThumbnail.tsx
+++ /dev/null
@@ -1,393 +0,0 @@
-import React, {
- useState,
- useCallback,
- useRef,
- useMemo,
- useEffect,
-} from "react";
-import { CheckboxIndicator } from "@mantine/core";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Button } from "@app/ui/Button";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@app/ui/Icon";
-import {
- draggable,
- dropTargetForElements,
-} from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
-
-import styles from "@app/components/pageEditor/PageEditor.module.css";
-import { useFileContext } from "@app/contexts/FileContext";
-import { FileId } from "@app/types/file";
-import { PrivateContent } from "@app/components/shared/PrivateContent";
-import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
-import { downloadFileWithPolicy as downloadFile } from "@app/services/exportWithPolicy";
-
-interface FileItem {
- id: FileId;
- name: string;
- pageCount: number;
- thumbnail: string | null;
- size: number;
- modifiedAt?: number | string | Date;
-}
-
-interface FileThumbnailProps {
- file: FileItem;
- index: number;
- totalFiles: number;
- selectedFiles: string[];
- selectionMode: boolean;
- onToggleFile: (fileId: FileId) => void;
- onDeleteFile: (fileId: FileId) => void;
- onViewFile: (fileId: FileId) => void;
- onSetStatus: (status: string) => void;
- onReorderFiles?: (
- sourceFileId: FileId,
- targetFileId: FileId,
- selectedFileIds: FileId[],
- ) => void;
- onDownloadFile?: (fileId: FileId) => void;
- toolMode?: boolean;
- isSupported?: boolean;
-}
-
-const FileThumbnail = ({
- file,
- index,
- selectedFiles,
- onToggleFile,
- onDeleteFile,
- onSetStatus,
- onReorderFiles,
- onDownloadFile,
- isSupported = true,
-}: FileThumbnailProps) => {
- const { t } = useTranslation();
- const terminology = useFileActionTerminology();
- const icons = useFileActionIcons();
- const { pinFile, unpinFile, isFilePinned, activeFiles } = useFileContext();
-
- // ---- Drag state ----
- const [isDragging, setIsDragging] = useState(false);
- const dragElementRef = useRef<HTMLDivElement | null>(null);
- const [actionsWidth, setActionsWidth] = useState<number | undefined>(
- undefined,
- );
- const [showActions, setShowActions] = useState(false);
-
- // Resolve the actual File object for pin/unpin operations
- const actualFile = useMemo(() => {
- return activeFiles.find((f) => f.fileId === file.id);
- }, [activeFiles, file.id]);
- const isPinned = actualFile ? isFilePinned(actualFile) : false;
-
- const downloadSelectedFile = useCallback(() => {
- // Prefer parent-provided handler if available
- if (typeof onDownloadFile === "function") {
- onDownloadFile(file.id);
- return;
- }
-
- // Fallback: attempt to download using the File object if provided
- const maybeFile = (file as unknown as { file?: File }).file;
- if (maybeFile instanceof File) {
- void downloadFile({
- data: maybeFile,
- filename: maybeFile.name || file.name || "download",
- fileId: file.id,
- });
- return;
- }
-
- // If we can't find a way to download, surface a status message
- onSetStatus?.(terminology.downloadUnavailable);
- }, [file, onDownloadFile, onSetStatus, t]);
- const handleRef = useRef<HTMLSpanElement | null>(null);
-
- // ---- Selection ----
- const isSelected = selectedFiles.includes(file.id);
-
- // ---- Drag & drop wiring ----
- const fileElementRef = useCallback(
- (element: HTMLDivElement | null) => {
- if (!element) return;
-
- dragElementRef.current = element;
-
- const dragCleanup = draggable({
- element,
- getInitialData: () => ({
- type: "file",
- fileId: file.id,
- fileName: file.name,
- selectedFiles: [file.id], // Always drag only this file, ignore selection state
- }),
- onDragStart: () => {
- setIsDragging(true);
- },
- onDrop: () => {
- setIsDragging(false);
- },
- });
-
- const dropCleanup = dropTargetForElements({
- element,
- getData: () => ({
- type: "file",
- fileId: file.id,
- }),
- canDrop: ({ source }) => {
- const sourceData = source.data;
- return sourceData.type === "file" && sourceData.fileId !== file.id;
- },
- onDrop: ({ source }) => {
- const sourceData = source.data;
- if (sourceData.type === "file" && onReorderFiles) {
- const sourceFileId = sourceData.fileId as FileId;
- const selectedFileIds = sourceData.selectedFiles as FileId[];
- onReorderFiles(sourceFileId, file.id, selectedFileIds);
- }
- },
- });
-
- return () => {
- dragCleanup();
- dropCleanup();
- };
- },
- [file.id, file.name, selectedFiles, onReorderFiles],
- );
-
- // Update dropdown width on resize
- useEffect(() => {
- const update = () => {
- if (dragElementRef.current)
- setActionsWidth(dragElementRef.current.offsetWidth);
- };
- update();
- window.addEventListener("resize", update);
- return () => window.removeEventListener("resize", update);
- }, []);
-
- // Close the actions dropdown when hovering outside this file card (and its dropdown)
- useEffect(() => {
- if (!showActions) return;
-
- const isInsideCard = (target: EventTarget | null) => {
- const container = dragElementRef.current;
- if (!container) return false;
- return target instanceof Node && container.contains(target);
- };
-
- const handleMouseMove = (e: MouseEvent) => {
- if (!isInsideCard(e.target)) {
- setShowActions(false);
- }
- };
-
- const handleTouchStart = (e: TouchEvent) => {
- // On touch devices, close if the touch target is outside the card
- if (!isInsideCard(e.target)) {
- setShowActions(false);
- }
- };
-
- document.addEventListener("mousemove", handleMouseMove);
- document.addEventListener("touchstart", handleTouchStart, {
- passive: true,
- });
- return () => {
- document.removeEventListener("mousemove", handleMouseMove);
- document.removeEventListener("touchstart", handleTouchStart);
- };
- }, [showActions]);
-
- // ---- Card interactions ----
- const handleCardClick = () => {
- if (!isSupported) return;
- onToggleFile(file.id);
- };
-
- return (
- <div
- ref={fileElementRef}
- data-file-id={file.id}
- data-testid="file-thumbnail"
- data-selected={isSelected}
- data-supported={isSupported}
- className={`${styles.card} w-[18rem] h-[22rem] select-none flex flex-col shadow-sm transition-all relative`}
- style={{
- opacity: isSupported ? (isDragging ? 0.9 : 1) : 0.5,
- filter: isSupported ? "none" : "grayscale(50%)",
- }}
- tabIndex={0}
- role="listitem"
- aria-selected={isSelected}
- onClick={handleCardClick}
- >
- {/* Header bar */}
- <div
- className={`${styles.header} ${isSelected ? styles.headerSelected : styles.headerResting}`}
- >
- {/* Logo/checkbox area */}
- <div className={styles.logoMark}>
- {isSupported ? (
- <CheckboxIndicator
- checked={isSelected}
- onChange={() => onToggleFile(file.id)}
- color="var(--c-primary)"
- />
- ) : (
- <div className={styles.unsupportedPill}>
- <span>{t("unsupported", "Unsupported")}</span>
- </div>
- )}
- </div>
-
- {/* Centered index */}
- <div
- className={styles.headerIndex}
- aria-label={t("pageEditor.filePosition", "Position {{position}}", {
- position: index + 1,
- })}
- >
- {index + 1}
- </div>
-
- {/* Kebab menu */}
- <ActionIcon
- aria-label={t("moreOptions", "More options")}
- variant="tertiary"
- className={styles.kebab}
- onClick={(e) => {
- e.stopPropagation();
- setShowActions((v) => !v);
- }}
- >
- <Icon name="ellipsis-vertical" size={20} />
- </ActionIcon>
- </div>
-
- {/* Actions overlay */}
- {showActions && (
- <div
- className={styles.actionsOverlay}
- style={{ width: actionsWidth }}
- onClick={(e) => e.stopPropagation()}
- >
- <Button
- variant="tertiary"
- justify="start"
- fullWidth
- className={styles.actionRow}
- leftSection={<Icon name="pin" size={20} filled={isPinned} />}
- onClick={() => {
- if (actualFile) {
- if (isPinned) {
- unpinFile(actualFile);
- onSetStatus?.(`Unpinned ${file.name}`);
- } else {
- pinFile(actualFile);
- onSetStatus?.(`Pinned ${file.name}`);
- }
- }
- setShowActions(false);
- }}
- >
- {isPinned ? t("unpin", "Unpin") : t("pin", "Pin")}
- </Button>
- <Button
- variant="tertiary"
- justify="start"
- fullWidth
- className={styles.actionRow}
- leftSection={<Icon name={icons.download} size={20} />}
- onClick={() => {
- downloadSelectedFile();
- setShowActions(false);
- }}
- >
- {terminology.download}
- </Button>
- <div className={styles.actionsDivider} />
- <Button
- variant="tertiary"
- justify="start"
- fullWidth
- className={`${styles.actionRow} ${styles.actionDanger}`}
- leftSection={<Icon name="trash" size={20} />}
- onClick={() => {
- onDeleteFile(file.id);
- onSetStatus(`Deleted ${file.name}`);
- setShowActions(false);
- }}
- >
- {t("delete", "Delete")}
- </Button>
- </div>
- )}
-
- {/* File content area */}
- <div className="file-container w-[90%] h-[80%] relative">
- {/* Stacked file effect - multiple shadows to simulate pages */}
- <div
- style={{
- width: "100%",
- height: "100%",
- backgroundColor: "var(--mantine-color-gray-1)",
- borderRadius: 6,
- border: "1px solid var(--mantine-color-gray-3)",
- padding: 4,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- position: "relative",
- boxShadow: "2px 2px 0 rgba(0,0,0,0.1), 4px 4px 0 rgba(0,0,0,0.05)",
- }}
- >
- {file.thumbnail && (
- <PrivateContent>
- <img
- src={file.thumbnail}
- alt={file.name}
- draggable={false}
- onError={(e) => {
- // Hide broken image if blob URL was revoked
- const img = e.target as HTMLImageElement;
- img.style.display = "none";
- }}
- style={{
- maxWidth: "80%",
- maxHeight: "80%",
- objectFit: "contain",
- borderRadius: 0,
- background: "#ffffff",
- border: "1px solid var(--c-border)",
- display: "block",
- marginLeft: "auto",
- marginRight: "auto",
- alignSelf: "start",
- }}
- />
- </PrivateContent>
- )}
- </div>
-
- {/* Pin indicator (bottom-left) */}
- {isPinned && (
- <span className={styles.pinIndicator} aria-hidden>
- <Icon name="pin" size={20} filled />
- </span>
- )}
-
- {/* Drag handle (span wrapper so we can attach a ref reliably) */}
- <span ref={handleRef} className={styles.dragHandle} aria-hidden>
- <Icon name="grip-vertical" size={20} />
- </span>
- </div>
- </div>
- );
-};
-
-export default React.memo(FileThumbnail);
diff --git a/frontend/editor/src/core/components/pageEditor/PageEditor.module.css b/frontend/editor/src/core/components/pageEditor/PageEditor.module.css
deleted file mode 100644
index fe8660a04a..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageEditor.module.css
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Page container hover effects - optimized for smooth scrolling */
-.pageContainer {
- transition: transform 0.2s ease-in-out;
- /* Enable hardware acceleration for smoother scrolling */
- will-change: transform;
- transform: translateZ(0);
- backface-visibility: hidden;
-}
-
-.pageContainer:hover {
- transform: scale(1.02) translateZ(0);
-}
-
-.pageSurface {
- transition: background-color 0.4s ease;
-}
-
-.pageJustMoved {
- animation: pageMovedHighlight 1.2s ease-out;
-}
-
-@keyframes pageMovedHighlight {
- 0% {
- background-color: color-mix(in srgb, var(--c-primary) 32%, transparent);
- }
- 60% {
- background-color: color-mix(in srgb, var(--c-primary) 12%, transparent);
- }
- 100% {
- background-color: color-mix(in srgb, var(--c-primary) 0%, transparent);
- }
-}
-
-.pageContainer:hover .pageNumber {
- opacity: 1 !important;
-}
-
-.pageContainer:hover .pageHoverControls {
- opacity: 0.95 !important;
-}
-
-/* Checkbox container - prevent transform inheritance */
-.checkboxContainer {
- transform: none !important;
- transition: none !important;
-}
-
-/* Page movement animations */
-.pageMoveAnimation {
- transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
-}
-
-/* Animations */
-@keyframes pulse {
- 0%,
- 100% {
- opacity: 1;
- }
- 50% {
- opacity: 0.5;
- }
-}
-
-/* Action styles */
-.actionRow:hover {
- background: var(--c-hover);
-}
-
-.actionDanger {
- color: var(--text-brand-accent);
-}
-
-.actionsDivider {
- height: 1px;
- background: var(--c-border);
- margin: 4px 0;
-}
-
-.pinIndicator {
- position: absolute;
- bottom: 4px;
- left: 4px;
- z-index: 1;
- color: rgba(0, 0, 0, 0.35); /* match drag handle color */
-}
-
-.unsupportedPill {
- margin-left: 1.75rem;
- background: var(--c-text-subtle);
- color: white;
- padding: 4px 8px;
- border-radius: 12px;
- font-size: 10px;
- font-weight: 500;
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: 80px;
- height: 20px;
-}
diff --git a/frontend/editor/src/core/components/pageEditor/PageEditor.tsx b/frontend/editor/src/core/components/pageEditor/PageEditor.tsx
deleted file mode 100644
index 03c7be2fbf..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageEditor.tsx
+++ /dev/null
@@ -1,843 +0,0 @@
-import { useState, useCallback, useRef, useEffect, useMemo } from "react";
-import { Text, Center, Box, LoadingOverlay, Stack } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { useFileState, useFileActions } from "@app/contexts/FileContext";
-import {
- useNavigationGuard,
- useNavigationState,
-} from "@app/contexts/NavigationContext";
-import { usePageEditor } from "@app/contexts/PageEditorContext";
-import { PageEditorFunctions, PDFPage } from "@app/types/pageEditor";
-// Thumbnail generation is now handled by individual PageThumbnail components
-import "@app/components/pageEditor/PageEditor.module.css";
-import PageThumbnail from "@app/components/pageEditor/PageThumbnail";
-import DragDropGrid, {
- type DragHandleProps,
-} from "@app/components/pageEditor/DragDropGrid";
-import SkeletonLoader from "@app/components/shared/SkeletonLoader";
-import { FileId } from "@app/types/file";
-import { GRID_CONSTANTS } from "@app/components/pageEditor/constants";
-import { useInitialPageDocument } from "@app/components/pageEditor/hooks/useInitialPageDocument";
-import { usePageDocument } from "@app/components/pageEditor/hooks/usePageDocument";
-import { usePageEditorState } from "@app/components/pageEditor/hooks/usePageEditorState";
-import { usePageEditorWorkbenchBarButtons } from "@app/components/pageEditor/pageEditorWorkbenchBarButtons";
-import { useFileColorMap } from "@app/components/pageEditor/hooks/useFileColorMap";
-import { useWheelZoom } from "@app/hooks/useWheelZoom";
-import { useEditedDocumentState } from "@app/components/pageEditor/hooks/useEditedDocumentState";
-import { useUndoManagerState } from "@app/components/pageEditor/hooks/useUndoManagerState";
-import { usePageSelectionManager } from "@app/components/pageEditor/hooks/usePageSelectionManager";
-import { usePageEditorCommands } from "@app/components/pageEditor/hooks/useEditorCommands";
-import { usePageEditorExport } from "@app/components/pageEditor/hooks/usePageEditorExport";
-import { useThumbnailGeneration } from "@app/hooks/useThumbnailGeneration";
-import { convertSplitPageIdsToIndexes } from "@app/components/pageEditor/utils/splitPositions";
-
-export interface PageEditorProps {
- onFunctionsReady?: (functions: PageEditorFunctions) => void;
-}
-
-interface PageEditorFileEntry {
- fileId: FileId;
- name: string;
- versionNumber: number | undefined;
- isSelected: boolean;
-}
-
-const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
- const { t } = useTranslation();
- // Use split contexts to prevent re-renders
- const { state, selectors } = useFileState();
- const { actions } = useFileActions();
-
- // Navigation guard for unsaved changes
- const {
- setHasUnsavedChanges,
- registerNavigationWarningHandlers,
- unregisterNavigationWarningHandlers,
- } = useNavigationGuard();
- const navigationState = useNavigationState();
-
- // Get PageEditor coordination functions
- const {
- updateFileOrderFromPages,
- fileOrder,
- reorderedPages,
- clearReorderedPages,
- updateCurrentPages,
- savePersistedDocument,
- clearPersistedDocument,
- contentRevision,
- } = usePageEditor();
-
- const [visiblePageIds, setVisiblePageIds] = useState<string[]>([]);
- const thumbnailRequestsRef = useRef<Set<string>>(new Set());
- const { requestThumbnail, getThumbnailFromCache } = useThumbnailGeneration();
- const handleVisibleItemsChange = useCallback((items: PDFPage[]) => {
- setVisiblePageIds((prev) => {
- const ids = items.map((item) => item.id);
- if (
- prev.length === ids.length &&
- prev.every((id, index) => id === ids[index])
- ) {
- return prev;
- }
- return ids;
- });
- }, []);
-
- // Zoom state management
- const [zoomLevel, setZoomLevel] = useState(1.0);
- const containerRef = useRef<HTMLDivElement>(null);
- const rootFontSize = useMemo(() => {
- if (typeof window === "undefined") {
- return 16;
- }
- const computed = getComputedStyle(document.documentElement).fontSize;
- const parsed = parseFloat(computed);
- return Number.isNaN(parsed) ? 16 : parsed;
- }, []);
- const itemGapPx = useMemo(() => {
- return parseFloat(GRID_CONSTANTS.ITEM_GAP) * rootFontSize * zoomLevel;
- }, [rootFontSize, zoomLevel]);
-
- // Zoom actions
- const zoomIn = useCallback(() => {
- setZoomLevel((prev) => Math.min(prev + 0.1, 3.0));
- }, []);
-
- const zoomOut = useCallback(() => {
- setZoomLevel((prev) => Math.max(prev - 0.1, 0.5));
- }, []);
-
- // Derive page editor files from PageEditorContext's fileOrder (page editor workspace order)
- // Filter to only show PDF files (PageEditor only supports PDFs)
- // Use stable string keys to prevent infinite loops
- // Cache file objects to prevent infinite re-renders from new object references
- const fileOrderKey = fileOrder.join(",");
- const selectedIdsKey = [...state.ui.selectedFileIds].sort().join(",");
- const filesSignature = selectors.getFilesSignature();
-
- const fileObjectsRef = useRef(new Map<FileId, PageEditorFileEntry>());
- const gridItemRefsRef = useRef<React.MutableRefObject<
- Map<string, HTMLDivElement>
- > | null>(null);
-
- const pageEditorFiles = useMemo(() => {
- const cache = fileObjectsRef.current;
- const newFiles: PageEditorFileEntry[] = [];
-
- fileOrder.forEach((fileId) => {
- const stub = selectors.getStirlingFileStub(fileId);
- const isSelected = state.ui.selectedFileIds.includes(fileId);
- const isPdf = stub?.name?.toLowerCase().endsWith(".pdf") ?? false;
-
- if (!isPdf) return; // Skip non-PDFs
-
- const cached = cache.get(fileId);
-
- // Check if data actually changed (compare by fileId, not position)
- if (
- cached &&
- cached.fileId === fileId &&
- cached.name === (stub?.name || "") &&
- cached.versionNumber === stub?.versionNumber &&
- cached.isSelected === isSelected
- ) {
- // Reuse existing object reference
- newFiles.push(cached);
- } else {
- // Create new object only if data changed
- const newFile = {
- fileId,
- name: stub?.name || "",
- versionNumber: stub?.versionNumber,
- isSelected,
- };
- cache.set(fileId, newFile);
- newFiles.push(newFile);
- }
- });
-
- // Clean up removed files from cache
- const activeIds = new Set(newFiles.map((f) => f.fileId));
- for (const cachedId of cache.keys()) {
- if (!activeIds.has(cachedId)) {
- cache.delete(cachedId);
- }
- }
-
- return newFiles;
- }, [fileOrderKey, selectedIdsKey, filesSignature]);
-
- // Get ALL file IDs in order (not filtered by selection)
- const orderedFileIds = useMemo(() => {
- return pageEditorFiles.map((f) => f.fileId);
- }, [pageEditorFiles]);
-
- // Get selected file IDs for filtering
- const selectedFileIds = useMemo(() => {
- return pageEditorFiles.filter((f) => f.isSelected).map((f) => f.fileId);
- }, [pageEditorFiles]);
- const activeFilesSignature = selectors.getFilesSignature();
-
- // Check if there are any PDF files in FileContext (bypasses fileOrder, which is
- // populated asynchronously via effect). Used to avoid a one-render flash of
- // "No PDF files loaded" when PageEditor first mounts after files are added.
- const hasPdfFiles = useMemo(() => {
- return state.files.ids.some((id) => {
- const stub = selectors.getStirlingFileStub(id);
- return stub?.name?.toLowerCase().endsWith(".pdf") ?? false;
- });
- }, [state.files.ids, selectors]);
-
- // UI state
- const globalProcessing = state.ui.isProcessing;
-
- const initialDocument = useInitialPageDocument();
- const { document: mergedPdfDocument } = usePageDocument();
-
- // The undo manager is created below this hook, so the reset is forwarded
- // through a ref rather than reordering the two.
- const clearUndoHistoryRef = useRef<() => void>(() => {});
- const handleDocumentReplaced = useCallback(() => {
- clearUndoHistoryRef.current();
- }, []);
-
- const { setEditedDocument, displayDocument, getEditedDocument } =
- useEditedDocumentState({
- initialDocument,
- mergedPdfDocument,
- reorderedPages,
- clearReorderedPages,
- fileOrder,
- updateCurrentPages,
- contentRevision,
- onDocumentReplaced: handleDocumentReplaced,
- });
-
- const displayDocumentRef = useRef(displayDocument);
- useEffect(() => {
- displayDocumentRef.current = displayDocument;
- }, [displayDocument]);
-
- const queueThumbnailRequestsForPages = useCallback(
- (pageIds: string[]) => {
- const doc = displayDocumentRef.current;
- if (!doc || pageIds.length === 0) return;
-
- const loadedCount = doc.pages.filter((p) => p.thumbnail).length;
- const pending = thumbnailRequestsRef.current.size;
- const MAX_CONCURRENT_THUMBNAILS =
- loadedCount < 8
- ? 1
- : doc.totalPages < 20
- ? 3
- : doc.totalPages < 50
- ? 5
- : 8;
- const available = Math.max(0, MAX_CONCURRENT_THUMBNAILS - pending);
- if (available === 0) return;
-
- const toLoad: string[] = [];
- for (const pageId of pageIds) {
- if (toLoad.length >= available) break;
- if (thumbnailRequestsRef.current.has(pageId)) continue;
- const page = doc.pages.find((p) => p.id === pageId);
- if (!page || page.thumbnail) continue;
- toLoad.push(pageId);
- }
-
- if (toLoad.length === 0) return;
-
- toLoad.forEach((pageId) => {
- const page = doc.pages.find((p) => p.id === pageId);
- if (!page) return;
-
- const cached = getThumbnailFromCache(pageId);
- if (cached) {
- thumbnailRequestsRef.current.add(pageId);
- Promise.resolve(cached)
- .then((cache) => {
- setEditedDocument((prev) => {
- if (!prev) return prev;
- const pageIndex = prev.pages.findIndex((p) => p.id === pageId);
- if (pageIndex === -1) return prev;
-
- const updated = [...prev.pages];
- updated[pageIndex] = {
- ...prev.pages[pageIndex],
- thumbnail: cache,
- };
- return { ...prev, pages: updated };
- });
- })
- .finally(() => {
- thumbnailRequestsRef.current.delete(pageId);
- });
- return;
- }
-
- const fileId = page.originalFileId;
- if (!fileId) return;
- const file = selectors.getFile(fileId);
- if (!file) return;
-
- thumbnailRequestsRef.current.add(pageId);
- requestThumbnail(
- pageId,
- file,
- page.originalPageNumber || page.pageNumber,
- )
- .then((thumbnail) => {
- if (thumbnail) {
- setEditedDocument((prev) => {
- if (!prev) return prev;
- const pageIndex = prev.pages.findIndex((p) => p.id === pageId);
- if (pageIndex === -1) return prev;
-
- const updated = [...prev.pages];
- updated[pageIndex] = { ...prev.pages[pageIndex], thumbnail };
- return { ...prev, pages: updated };
- });
- }
- })
- .catch((error) => {
- console.error("[Thumbnail Loading] Error:", error);
- })
- .finally(() => {
- thumbnailRequestsRef.current.delete(pageId);
- });
- });
- },
- [getThumbnailFromCache, requestThumbnail, selectors, setEditedDocument],
- );
-
- useEffect(() => {
- if (!displayDocument) {
- return;
- }
- queueThumbnailRequestsForPages(visiblePageIds);
- }, [displayDocument, visiblePageIds, queueThumbnailRequestsForPages]);
-
- const lastInitialDocumentSignatureRef = useRef<string | null>(null);
- const displayDocumentId = displayDocument?.id ?? null;
- const displayDocumentLength = displayDocument?.pages.length ?? 0;
- useEffect(() => {
- if (!displayDocument || displayDocument.pages.length === 0) {
- lastInitialDocumentSignatureRef.current = null;
- return;
- }
-
- const signature = `${displayDocumentId}:${displayDocumentLength}`;
- if (lastInitialDocumentSignatureRef.current === signature) {
- return;
- }
-
- const INITIAL_VISIBLE_PAGE_COUNT = 8;
- const initialIds = displayDocument.pages
- .slice(0, INITIAL_VISIBLE_PAGE_COUNT)
- .map((page) => page.id);
-
- queueThumbnailRequestsForPages(initialIds);
- lastInitialDocumentSignatureRef.current = signature;
- }, [
- displayDocumentId,
- displayDocumentLength,
- queueThumbnailRequestsForPages,
- ]);
-
- useEffect(() => {
- setVisiblePageIds([]);
- }, [displayDocumentId]);
-
- useEffect(() => {
- return () => {
- if (navigationState.workbench !== "pageEditor") {
- return;
- }
-
- const doc = displayDocumentRef.current;
- if (doc && doc.pages.length > 0) {
- const signature = doc.pages.map((page) => page.id).join(",");
- savePersistedDocument(doc, signature);
- }
- };
- }, [savePersistedDocument, navigationState.workbench]);
-
- // UI state management
- const {
- selectionMode,
- selectedPageIds,
- movingPage,
- isAnimating,
- splitPositions,
- exportLoading,
- setSelectionMode,
- setSelectedPageIds,
- setMovingPage,
- setSplitPositions,
- setExportLoading,
- togglePage,
- toggleSelectAll,
- animateReorder,
- } = usePageEditorState();
-
- const {
- csvInput,
- setCsvInput,
- totalPages,
- getPageNumbersFromIds,
- handleSelectAll,
- handleDeselectAll,
- handleSetSelectedPages,
- updatePagesFromCSV,
- } = usePageSelectionManager({
- displayDocument,
- selectedPageIds,
- setSelectedPageIds,
- setSelectionMode,
- toggleSelectAll,
- activeFilesSignature,
- });
-
- // Grid container ref for positioning split indicators
- const gridContainerRef = useRef<HTMLDivElement>(null);
-
- const {
- canUndo,
- canRedo,
- executeCommandWithTracking,
- handleUndo,
- handleRedo,
- clearUndoHistory,
- } = useUndoManagerState({
- setHasUnsavedChanges,
- });
- clearUndoHistoryRef.current = clearUndoHistory;
-
- const {
- createRotateCommand,
- createDeleteCommand,
- createSplitCommand,
- executeCommand,
- handleRotate,
- handleDelete,
- handleDeletePage,
- handleSplit,
- handleSplitAll,
- handlePageBreak,
- handlePageBreakAll,
- handleInsertFiles,
- handleReorderPages,
- closePdf,
- } = usePageEditorCommands({
- displayDocument,
- getEditedDocument,
- setEditedDocument,
- splitPositions,
- setSplitPositions,
- selectedPageIds,
- setSelectedPageIds,
- getPageNumbersFromIds,
- executeCommandWithTracking,
- updateFileOrderFromPages,
- actions,
- selectors,
- setSelectionMode,
- clearUndoHistory,
- });
-
- const { onExportSelected, onExportAll, applyChanges } = usePageEditorExport({
- displayDocument,
- selectedPageIds,
- splitPositions,
- selectedFileIds,
- selectors,
- actions,
- setHasUnsavedChanges,
- exportLoading,
- setExportLoading,
- setSplitPositions,
- clearPersistedDocument,
- updateCurrentPages,
- });
-
- // Register navigation warning handlers for the global modal
- useEffect(() => {
- registerNavigationWarningHandlers({
- onApplyAndContinue: async () => {
- await applyChanges();
- },
- onExportAndContinue: async () => {
- await onExportAll();
- },
- });
- return () => unregisterNavigationWarningHandlers();
- }, [
- applyChanges,
- onExportAll,
- registerNavigationWarningHandlers,
- unregisterNavigationWarningHandlers,
- ]);
-
- // Derived values for usePageEditorWorkbenchBarButtons (must be after displayDocument)
- const selectedPageCount = selectedPageIds.length;
-
- usePageEditorWorkbenchBarButtons({
- totalPages,
- selectedPageCount,
- csvInput,
- setCsvInput,
- selectedPageIds,
- displayDocument: displayDocument || undefined,
- updatePagesFromCSV,
- handleSelectAll,
- handleDeselectAll,
- handleDelete,
- onExportSelected,
- onSaveChanges: applyChanges,
- exportLoading,
- });
-
- // Export preview function - defined after export functions to avoid circular dependency
- const handleExportPreview = useCallback(
- (selectedOnly: boolean = false) => {
- if (!displayDocument) return;
-
- // For now, trigger the actual export directly
- // In the original, this would show a preview modal first
- if (selectedOnly) {
- onExportSelected();
- } else {
- onExportAll();
- }
- },
- [displayDocument, onExportSelected, onExportAll],
- );
-
- // Expose functions to parent component
- useEffect(() => {
- if (onFunctionsReady) {
- onFunctionsReady({
- handleUndo,
- handleRedo,
- canUndo,
- canRedo,
- handleRotate,
- handleDelete,
- handleSplit,
- handleSplitAll,
- handlePageBreak,
- handlePageBreakAll,
- handleSelectAll,
- handleDeselectAll,
- handleSetSelectedPages,
- showExportPreview: handleExportPreview,
- onExportSelected,
- onExportAll,
- applyChanges,
- exportLoading,
- selectionMode,
- selectedPageIds,
- displayDocument: displayDocument || undefined,
- splitPositions,
- totalPages: displayDocument?.pages.length || 0,
- closePdf,
- });
- }
- }, [
- onFunctionsReady,
- handleUndo,
- handleRedo,
- canUndo,
- canRedo,
- handleRotate,
- handleDelete,
- handleSplit,
- handleSplitAll,
- handlePageBreak,
- handlePageBreakAll,
- handleSelectAll,
- handleDeselectAll,
- handleSetSelectedPages,
- handleExportPreview,
- onExportSelected,
- onExportAll,
- applyChanges,
- exportLoading,
- selectionMode,
- selectedPageIds,
- splitPositions,
- displayDocument?.pages.length,
- closePdf,
- ]);
-
- useWheelZoom({
- ref: containerRef,
- onZoomIn: zoomIn,
- onZoomOut: zoomOut,
- enabled: !!displayDocument,
- });
-
- // Handle keyboard zoom shortcuts
- useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- if (!(event.ctrlKey || event.metaKey)) return;
-
- const target = event.target as Element | null;
- const isInTextInput =
- target?.tagName === "INPUT" ||
- target?.tagName === "TEXTAREA" ||
- (target as HTMLElement | null)?.isContentEditable === true;
- if (isInTextInput) return;
-
- if (event.key === "=" || event.key === "+") {
- event.preventDefault();
- zoomIn();
- } else if (event.key === "-" || event.key === "_") {
- event.preventDefault();
- zoomOut();
- } else if (event.key === "0") {
- event.preventDefault();
- setZoomLevel(1.0);
- }
- };
-
- document.addEventListener("keydown", handleKeyDown);
- return () => {
- document.removeEventListener("keydown", handleKeyDown);
- };
- }, [zoomIn, zoomOut, setZoomLevel]);
-
- // Display all pages - use edited or original document
- const displayedPages = displayDocument?.pages || [];
-
- // Track color assignments by insertion order (files keep their color)
- const fileColorIndexMap = useFileColorMap(orderedFileIds);
-
- // Memoize renderItem to prevent DragDropGrid's React.memo from blocking updates
- // when selectedPageIds changes
- const renderItemCallback = useCallback(
- (
- page: PDFPage,
- index: number,
- refs: React.MutableRefObject<Map<string, HTMLDivElement>>,
- boxSelectedIds: string[],
- clearBoxSelection: () => void,
- activeDragIds: string[],
- justMoved: boolean,
- dragHandleProps?: DragHandleProps,
- zoomLevelParam?: number,
- isOverTarget?: boolean,
- ) => {
- gridItemRefsRef.current = refs;
- const fileColorIndex = page.originalFileId
- ? (fileColorIndexMap.get(page.originalFileId) ?? 0)
- : 0;
- const isBoxSelected = boxSelectedIds.includes(page.id);
- return (
- <PageThumbnail
- key={page.id}
- page={page}
- index={index}
- totalPages={displayDocument?.pages.length || 0}
- fileColorIndex={fileColorIndex}
- selectedPageIds={selectedPageIds}
- selectionMode={selectionMode}
- movingPage={movingPage}
- isAnimating={isAnimating}
- isBoxSelected={isBoxSelected}
- clearBoxSelection={clearBoxSelection}
- activeDragIds={activeDragIds}
- justMoved={justMoved}
- pageRefs={refs}
- dragHandleProps={dragHandleProps}
- isOverTarget={isOverTarget}
- onReorderPages={handleReorderPages}
- onTogglePage={togglePage}
- onAnimateReorder={animateReorder}
- onExecuteCommand={executeCommand}
- onSetStatus={() => {}}
- onSetMovingPage={setMovingPage}
- onDeletePage={handleDeletePage}
- createRotateCommand={createRotateCommand}
- createDeleteCommand={createDeleteCommand}
- createSplitCommand={createSplitCommand}
- pdfDocument={displayDocument!}
- setPdfDocument={setEditedDocument}
- splitPositions={splitPositions}
- onInsertFiles={handleInsertFiles}
- zoomLevel={zoomLevelParam || zoomLevel}
- />
- );
- },
- [
- selectedPageIds,
- selectionMode,
- movingPage,
- isAnimating,
- displayDocument,
- fileColorIndexMap,
- handleReorderPages,
- togglePage,
- animateReorder,
- executeCommand,
- setMovingPage,
- handleDeletePage,
- createRotateCommand,
- createDeleteCommand,
- createSplitCommand,
- setEditedDocument,
- splitPositions,
- handleInsertFiles,
- zoomLevel,
- ],
- );
-
- return (
- <div
- ref={containerRef}
- data-scrolling-container="true"
- style={{
- height: "100%",
- overflow: "auto",
- position: "relative",
- width: "100%",
- }}
- >
- <LoadingOverlay visible={globalProcessing && !initialDocument} />
-
- {!initialDocument && !globalProcessing && !hasPdfFiles && (
- <Center h="100%">
- <Stack align="center" gap="md">
- <Text size="lg" c="dimmed">
- 📄
- </Text>
- <Text c="dimmed">
- {t("pageEditor.emptyState.title", "No PDF files loaded")}
- </Text>
- <Text size="sm" c="dimmed">
- {t(
- "pageEditor.emptyState.body",
- "Add files to start editing pages",
- )}
- </Text>
- </Stack>
- </Center>
- )}
-
- {!initialDocument && (globalProcessing || hasPdfFiles) && (
- <Box p={0}>
- <SkeletonLoader type="controls" />
- <SkeletonLoader type="pageGrid" count={8} />
- </Box>
- )}
-
- {displayDocument && (
- <Box
- ref={gridContainerRef}
- p={0}
- pt="2rem"
- pb="4rem"
- style={{ position: "relative" }}
- >
- {/* Split Lines Overlay */}
- <div
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- pointerEvents: "none",
- zIndex: 10,
- }}
- >
- {(() => {
- const refsMap = gridItemRefsRef.current?.current;
- const containerEl = gridContainerRef.current;
- if (!refsMap || !containerEl) {
- return null;
- }
-
- const containerRect = containerEl.getBoundingClientRect();
- const splitIndexes = convertSplitPageIdsToIndexes(
- displayDocument,
- splitPositions,
- );
-
- return Array.from(splitIndexes).map((position) => {
- const currentPage = displayedPages[position];
- if (!currentPage) {
- return null;
- }
-
- const currentEl = refsMap.get(currentPage.id);
- if (!currentEl) {
- return null;
- }
-
- const currentRect = currentEl.getBoundingClientRect();
- const nextPage = displayedPages[position + 1];
- let lineLeft;
-
- if (nextPage) {
- const nextEl = refsMap.get(nextPage.id);
- if (nextEl) {
- const nextRect = nextEl.getBoundingClientRect();
- const sameRow =
- Math.abs(nextRect.top - currentRect.top) <
- currentRect.height / 2;
- if (sameRow) {
- lineLeft = (currentRect.right + nextRect.left) / 2;
- } else {
- lineLeft = currentRect.right + itemGapPx / 2;
- }
- } else {
- lineLeft = currentRect.right + itemGapPx / 2;
- }
- } else {
- lineLeft = currentRect.right + itemGapPx / 2;
- }
-
- return (
- <div
- key={`split-${position}`}
- style={{
- position: "absolute",
- left: `${lineLeft - containerRect.left}px`,
- top: `${currentRect.top - containerRect.top}px`,
- width: "1px",
- height: `${currentRect.height}px`,
- borderLeft: "1px dashed #3b82f6",
- }}
- />
- );
- });
- })()}
- </div>
-
- {/* Pages Grid */}
- <DragDropGrid
- items={displayedPages}
- onReorderPages={handleReorderPages}
- zoomLevel={zoomLevel}
- selectedFileIds={selectedFileIds}
- selectedPageIds={selectedPageIds}
- onVisibleItemsChange={handleVisibleItemsChange}
- getThumbnailData={(pageId) => {
- const page = displayDocument.pages.find((p) => p.id === pageId);
- if (!page?.thumbnail) return null;
- return {
- src: page.thumbnail,
- rotation: page.rotation || 0,
- };
- }}
- renderItem={renderItemCallback}
- />
- </Box>
- )}
- </div>
- );
-};
-
-export default PageEditor;
diff --git a/frontend/editor/src/core/components/pageEditor/PageEditorControls.module.css b/frontend/editor/src/core/components/pageEditor/PageEditorControls.module.css
deleted file mode 100644
index 71930cfc79..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageEditorControls.module.css
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Sized against this element, not the viewport - the page editor panel narrows
- when a tool panel is open, so viewport media queries measure the wrong box. */
-.dock {
- position: sticky;
- left: 0;
- right: 0;
- bottom: 0;
- z-index: 50;
- display: flex;
- justify-content: center;
- pointer-events: none;
- background: transparent;
- container-type: inline-size;
-}
-
-.bar {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- justify-content: center;
- /* Fluid spacing keeps the seven controls on one row down to ~300px without a
- breakpoint; below that the row wraps rather than clipping any control. */
- gap: clamp(0.25rem, 1.5cqi, 0.75rem);
- padding: clamp(0.5rem, 1.5cqi, 1rem);
- min-width: 0;
- max-width: min(700px, 100%);
- border: 1px solid var(--c-border);
- border-radius: 16px 16px 0 0;
- background-color: var(--c-bg-raised);
- box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);
- pointer-events: auto;
-}
-
-.divider {
- flex: none;
- width: 1px;
- height: 28px;
- background-color: var(--mantine-color-gray-3);
-}
diff --git a/frontend/editor/src/core/components/pageEditor/PageEditorControls.stories.tsx b/frontend/editor/src/core/components/pageEditor/PageEditorControls.stories.tsx
deleted file mode 100644
index 5838a6c7d4..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageEditorControls.stories.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import PageEditorControls from "@app/components/pageEditor/PageEditorControls";
-
-const meta = {
- title: "PageEditor/PageEditorControls",
- component: PageEditorControls,
- parameters: { layout: "padded" },
-} satisfies Meta<typeof PageEditorControls>;
-export default meta;
-type Story = StoryObj<typeof meta>;
-
-const baseArgs = {
- onClosePdf: () => {},
- onUndo: () => {},
- onRedo: () => {},
- canUndo: true,
- canRedo: true,
- onRotate: () => {},
- onDelete: () => {},
- onSplit: () => {},
- onSplitAll: () => {},
- onPageBreak: () => {},
- onPageBreakAll: () => {},
- onExportAll: () => {},
- exportLoading: false,
- selectionMode: true,
- selectedPageIds: ["page-1", "page-2"],
- displayDocument: {
- pages: [
- { id: "page-1", pageNumber: 1 },
- { id: "page-2", pageNumber: 2 },
- { id: "page-3", pageNumber: 3 },
- ],
- },
- splitPositions: new Set<string>(),
- totalPages: 3,
-};
-
-export const Default: Story = {
- args: baseArgs,
-};
-
-export const NoSelection: Story = {
- args: {
- ...baseArgs,
- selectedPageIds: [],
- canUndo: false,
- canRedo: false,
- },
-};
-
-export const WithExistingSplits: Story = {
- args: {
- ...baseArgs,
- splitPositions: new Set<string>(["page-1", "page-2"]),
- },
-};
diff --git a/frontend/editor/src/core/components/pageEditor/PageEditorControls.tsx b/frontend/editor/src/core/components/pageEditor/PageEditorControls.tsx
deleted file mode 100644
index c14bb62691..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageEditorControls.tsx
+++ /dev/null
@@ -1,195 +0,0 @@
-import { Tooltip } from "@mantine/core";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Icon } from "@app/ui/Icon";
-import { useTranslation } from "react-i18next";
-import styles from "@app/components/pageEditor/PageEditorControls.module.css";
-
-interface PageEditorControlsProps {
- // Close/Reset functions
- onClosePdf: () => void;
-
- // Undo/Redo
- onUndo: () => void;
- onRedo: () => void;
- canUndo: boolean;
- canRedo: boolean;
-
- // Page operations
- onRotate: (direction: "left" | "right") => void;
- onDelete: () => void;
- onSplit: () => void;
- onSplitAll: () => void;
- onPageBreak: () => void;
- onPageBreakAll: () => void;
-
- onExportAll: () => void;
- exportLoading: boolean;
-
- // Selection state
- selectionMode: boolean;
- selectedPageIds: string[];
- displayDocument?: { pages: { id: string; pageNumber: number }[] };
-
- // Split state (for tooltip logic)
- splitPositions?: Set<string>;
- totalPages?: number;
-}
-
-const PageEditorControls = ({
- onUndo,
- onRedo,
- canUndo,
- canRedo,
- onRotate,
- onDelete,
- onSplit,
- onPageBreak,
- selectedPageIds,
- displayDocument,
- splitPositions,
-}: PageEditorControlsProps) => {
- const { t } = useTranslation();
- // Calculate split tooltip text using smart toggle logic
- const getSplitTooltip = () => {
- if (!splitPositions || !displayDocument || selectedPageIds.length === 0) {
- return "Split Selected";
- }
-
- const totalPages = displayDocument.pages.length;
- const selectedValidPageIds = displayDocument.pages
- .filter(
- (page, index) =>
- selectedPageIds.includes(page.id) && index < totalPages - 1,
- )
- .map((page) => page.id);
-
- if (selectedValidPageIds.length === 0) {
- return "Split Selected";
- }
-
- const existingSplitsCount = selectedValidPageIds.filter((id) =>
- splitPositions.has(id),
- ).length;
- const noSplitsCount = selectedValidPageIds.length - existingSplitsCount;
-
- const willRemoveSplits = existingSplitsCount > noSplitsCount;
-
- if (willRemoveSplits) {
- return existingSplitsCount === selectedValidPageIds.length
- ? "Remove All Selected Splits"
- : "Remove Selected Splits";
- } else {
- return existingSplitsCount === 0
- ? "Split Selected"
- : "Complete Selected Splits";
- }
- };
-
- // Calculate page break tooltip text
- const getPageBreakTooltip = () => {
- return selectedPageIds.length > 0
- ? `Insert ${selectedPageIds.length} Page Break${selectedPageIds.length > 1 ? "s" : ""}`
- : "Insert Page Breaks";
- };
-
- return (
- <div className={styles.dock}>
- <div className={styles.bar}>
- {/* Undo/Redo */}
- <Tooltip label={t("pageEditor.toolbar.undo", "Undo")}>
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={onUndo}
- disabled={!canUndo}
- aria-label={t("pageEditor.toolbar.undo", "Undo")}
- >
- <Icon name="undo-2" />
- </ActionIcon>
- </Tooltip>
- <Tooltip label={t("pageEditor.toolbar.redo", "Redo")}>
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={onRedo}
- disabled={!canRedo}
- aria-label={t("pageEditor.toolbar.redo", "Redo")}
- >
- <Icon name="redo-2" />
- </ActionIcon>
- </Tooltip>
-
- <div className={styles.divider} />
-
- {/* Page Operations */}
- <Tooltip
- label={t("pageEditor.toolbar.rotateLeft", "Rotate Selected Left")}
- >
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={() => onRotate("left")}
- disabled={selectedPageIds.length === 0}
- aria-label={t(
- "pageEditor.toolbar.rotateLeft",
- "Rotate Selected Left",
- )}
- >
- <Icon name="rotate-ccw" />
- </ActionIcon>
- </Tooltip>
- <Tooltip
- label={t("pageEditor.toolbar.rotateRight", "Rotate Selected Right")}
- >
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={() => onRotate("right")}
- disabled={selectedPageIds.length === 0}
- aria-label={t(
- "pageEditor.toolbar.rotateRight",
- "Rotate Selected Right",
- )}
- >
- <Icon name="rotate-cw" />
- </ActionIcon>
- </Tooltip>
- <Tooltip label={t("pageEditor.toolbar.delete", "Delete Selected")}>
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={onDelete}
- disabled={selectedPageIds.length === 0}
- aria-label={t("pageEditor.toolbar.delete", "Delete Selected")}
- >
- <Icon name="trash" />
- </ActionIcon>
- </Tooltip>
- <Tooltip label={getSplitTooltip()}>
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={onSplit}
- disabled={selectedPageIds.length === 0}
- aria-label={getSplitTooltip()}
- >
- <Icon name="scissors" />
- </ActionIcon>
- </Tooltip>
- <Tooltip label={getPageBreakTooltip()}>
- <ActionIcon
- variant="tertiary"
- size="md"
- onClick={onPageBreak}
- disabled={selectedPageIds.length === 0}
- aria-label={getPageBreakTooltip()}
- >
- <Icon name="square-split-vertical" />
- </ActionIcon>
- </Tooltip>
- </div>
- </div>
- );
-};
-
-export default PageEditorControls;
diff --git a/frontend/editor/src/core/components/pageEditor/PageSelectByNumberButton.tsx b/frontend/editor/src/core/components/pageEditor/PageSelectByNumberButton.tsx
deleted file mode 100644
index c987c91c6f..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageSelectByNumberButton.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { Popover } from "@mantine/core";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Icon } from "@app/ui/Icon";
-import { Tooltip } from "@app/components/shared/Tooltip";
-import BulkSelectionPanel from "@app/components/pageEditor/BulkSelectionPanel";
-
-interface PageSelectByNumberButtonProps {
- disabled: boolean;
- totalPages: number;
- label: string;
- csvInput: string;
- setCsvInput: (value: string) => void;
- selectedPageIds: string[];
- displayDocument?: { pages: { id: string; pageNumber: number }[] };
- updatePagesFromCSV: (override?: string) => void;
-}
-
-export default function PageSelectByNumberButton({
- disabled,
- totalPages,
- label,
- csvInput,
- setCsvInput,
- selectedPageIds,
- displayDocument,
- updatePagesFromCSV,
-}: PageSelectByNumberButtonProps) {
- return (
- <Tooltip
- content={label}
- position="bottom"
- offset={12}
- arrow
- portalTarget={document.body}
- >
- <div>
- <Popover position="left" withArrow shadow="md" offset={8}>
- <Popover.Target>
- <div style={{ display: "inline-flex" }}>
- <ActionIcon
- variant="tertiary"
- disabled={disabled || totalPages === 0}
- aria-label={label}
- >
- <Icon name="picture-in-picture" size="1.5rem" />
- </ActionIcon>
- </div>
- </Popover.Target>
- <Popover.Dropdown>
- <div style={{ minWidth: "24rem", maxWidth: "32rem" }}>
- <BulkSelectionPanel
- csvInput={csvInput}
- setCsvInput={setCsvInput}
- selectedPageIds={selectedPageIds}
- displayDocument={displayDocument}
- onUpdatePagesFromCSV={updatePagesFromCSV}
- />
- </div>
- </Popover.Dropdown>
- </Popover>
- </div>
- </Tooltip>
- );
-}
diff --git a/frontend/editor/src/core/components/pageEditor/PageThumbnail.tsx b/frontend/editor/src/core/components/pageEditor/PageThumbnail.tsx
deleted file mode 100644
index 68ffd2e65c..0000000000
--- a/frontend/editor/src/core/components/pageEditor/PageThumbnail.tsx
+++ /dev/null
@@ -1,571 +0,0 @@
-import React, {
- useCallback,
- useState,
- useEffect,
- useRef,
- useMemo,
-} from "react";
-import { Text, Checkbox } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { useIsMobile } from "@app/hooks/useIsMobile";
-import { Icon } from "@app/ui/Icon";
-import { PDFPage, PDFDocument } from "@app/types/pageEditor";
-import { useFilesModalContext } from "@app/contexts/FilesModalContext";
-import { getFileColorWithOpacity } from "@app/components/pageEditor/fileColors";
-import { type DragHandleProps } from "@app/components/pageEditor/DragDropGrid";
-import styles from "@app/components/pageEditor/PageEditor.module.css";
-import HoverActionMenu, {
- HoverAction,
-} from "@app/components/shared/HoverActionMenu";
-import { StirlingFileStub } from "@app/types/fileContext";
-import { PrivateContent } from "@app/components/shared/PrivateContent";
-
-interface PageThumbnailProps {
- page: PDFPage;
- index: number;
- totalPages: number;
- fileColorIndex: number;
- selectedPageIds: string[];
- selectionMode: boolean;
- movingPage: number | null;
- isAnimating: boolean;
- isOverTarget?: boolean;
- isBoxSelected?: boolean;
- clearBoxSelection?: () => void;
- activeDragIds: string[];
- justMoved?: boolean;
- pageRefs: React.MutableRefObject<Map<string, HTMLDivElement>>;
- dragHandleProps?: DragHandleProps;
- onReorderPages: (
- sourcePageNumber: number,
- targetIndex: number,
- selectedPageIds?: string[],
- ) => void;
- onTogglePage: (pageId: string) => void;
- onAnimateReorder: () => void;
- onExecuteCommand: (command: { execute: () => void }) => void;
- onSetStatus: (status: string) => void;
- onSetMovingPage: (page: number | null) => void;
- onDeletePage: (pageNumber: number) => void;
- createRotateCommand: (
- pageIds: string[],
- rotation: number,
- ) => { execute: () => void };
- createDeleteCommand: (pageIds: string[]) => { execute: () => void };
- createSplitCommand: (
- pageId: string,
- pageNumber: number,
- ) => { execute: () => void };
- pdfDocument: PDFDocument;
- setPdfDocument: (doc: PDFDocument) => void;
- splitPositions: Set<string>;
- onInsertFiles?: (
- files: File[] | StirlingFileStub[],
- insertAfterPage: number,
- isFromStorage?: boolean,
- ) => void;
- zoomLevel?: number;
-}
-
-const PageThumbnail: React.FC<PageThumbnailProps> = ({
- page,
- index: _index,
- totalPages,
- fileColorIndex,
- selectedPageIds,
- selectionMode,
- movingPage,
- isAnimating,
- isOverTarget = false,
- isBoxSelected = false,
- clearBoxSelection,
- activeDragIds,
- pageRefs,
- dragHandleProps,
- onReorderPages,
- onTogglePage,
- onExecuteCommand,
- onSetStatus,
- onDeletePage,
- createRotateCommand,
- createSplitCommand,
- pdfDocument,
- splitPositions,
- onInsertFiles,
- zoomLevel = 1.0,
- justMoved = false,
-}: PageThumbnailProps) => {
- const { t } = useTranslation();
- const pageIndex = page.pageNumber - 1;
- const isSelected = Array.isArray(selectedPageIds)
- ? selectedPageIds.includes(page.id)
- : false;
-
- const [isMouseDown, setIsMouseDown] = useState(false);
- const [mouseStartPos, setMouseStartPos] = useState<{
- x: number;
- y: number;
- } | null>(null);
- const [isHovered, setIsHovered] = useState(false);
- const isMobile = useIsMobile();
- const lastClickTimeRef = useRef<number>(0);
-
- const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(
- page.thumbnail,
- );
- const elementRef = useRef<HTMLDivElement | null>(null);
- const { openFilesModal } = useFilesModalContext();
-
- // Check if this page is currently being dragged
- const isDragging = activeDragIds.includes(page.id);
-
- // Calculate document aspect ratio from first non-blank page
- const getDocumentAspectRatio = useCallback(() => {
- // Find first non-blank page with a thumbnail to get aspect ratio
- const firstRealPage = pdfDocument.pages.find(
- (p) => !p.isBlankPage && p.thumbnail,
- );
- if (firstRealPage?.thumbnail) {
- // Try to get aspect ratio from an actual thumbnail image
- // For now, default to A4 but could be enhanced to measure image dimensions
- return "1 / 1.414"; // A4 ratio as fallback
- }
- return "1 / 1.414"; // Default A4 ratio
- }, [pdfDocument.pages]);
-
- // Update thumbnail URL when page prop changes
- useEffect(() => {
- if (page.thumbnail && page.thumbnail !== thumbnailUrl) {
- setThumbnailUrl(page.thumbnail);
- }
- }, [page.thumbnail, thumbnailUrl]);
-
- // Merge refs - combine our ref tracking with dnd-kit's ref
- const mergedRef = useCallback(
- (element: HTMLDivElement | null) => {
- // Track in our refs map
- elementRef.current = element;
- if (element) {
- pageRefs.current.set(page.id, element);
- } else {
- pageRefs.current.delete(page.id);
- }
-
- // Call dnd-kit's ref if provided
- if (dragHandleProps?.ref) {
- dragHandleProps.ref(element);
- }
- },
- [page.id, pageRefs, dragHandleProps],
- );
-
- // DOM command handlers
- const handleRotateLeft = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
- // Use the command system for undo/redo support
- const command = createRotateCommand([page.id], -90);
- onExecuteCommand(command);
- onSetStatus(`Rotated page ${page.pageNumber} left`);
- },
- [
- page.id,
- page.pageNumber,
- onExecuteCommand,
- onSetStatus,
- createRotateCommand,
- ],
- );
-
- const handleRotateRight = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
- // Use the command system for undo/redo support
- const command = createRotateCommand([page.id], 90);
- onExecuteCommand(command);
- onSetStatus(`Rotated page ${page.pageNumber} right`);
- },
- [
- page.id,
- page.pageNumber,
- onExecuteCommand,
- onSetStatus,
- createRotateCommand,
- ],
- );
-
- const handleDelete = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
- onDeletePage(page.pageNumber);
- onSetStatus(`Deleted page ${page.pageNumber}`);
- },
- [page.pageNumber, onDeletePage, onSetStatus],
- );
-
- const handleSplit = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
-
- // Create a command to toggle split at this position
- const command = createSplitCommand(page.id, page.pageNumber);
- onExecuteCommand(command);
-
- const hasSplit = splitPositions.has(page.id);
- const action = hasSplit ? "removed" : "added";
- onSetStatus(`Split marker ${action} after position ${pageIndex + 1}`);
- },
- [
- pageIndex,
- splitPositions,
- onExecuteCommand,
- onSetStatus,
- createSplitCommand,
- ],
- );
-
- const handleInsertFileAfter = useCallback(
- (e: React.MouseEvent) => {
- e.stopPropagation();
-
- if (onInsertFiles) {
- // Open file manager modal with custom handler for page insertion
- openFilesModal({
- insertAfterPage: page.pageNumber,
- customHandler: (
- files: File[] | StirlingFileStub[],
- insertAfterPage?: number,
- isFromStorage?: boolean,
- ) => {
- if (insertAfterPage !== undefined) {
- onInsertFiles(files, insertAfterPage, isFromStorage);
- }
- },
- });
- onSetStatus(`Select files to insert after page ${page.pageNumber}`);
- } else {
- // Fallback to normal file handling
- openFilesModal({ insertAfterPage: page.pageNumber });
- onSetStatus(`Select files to insert after page ${page.pageNumber}`);
- }
- },
- [openFilesModal, page.pageNumber, onSetStatus, onInsertFiles],
- );
-
- // Handle click vs drag differentiation
- const handleMouseDown = useCallback((e: React.MouseEvent) => {
- setIsMouseDown(true);
- setMouseStartPos({ x: e.clientX, y: e.clientY });
- }, []);
-
- const handleMouseUp = useCallback(
- (e: React.MouseEvent) => {
- if (!isMouseDown || !mouseStartPos) {
- setIsMouseDown(false);
- setMouseStartPos(null);
- return;
- }
-
- // Calculate distance moved
- const deltaX = Math.abs(e.clientX - mouseStartPos.x);
- const deltaY = Math.abs(e.clientY - mouseStartPos.y);
- const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
-
- // If mouse moved less than 2 pixels, consider it a click (not a drag)
- if (distance < 2 && !isDragging) {
- // Prevent rapid double-clicks from causing issues (debounce with 100ms threshold)
- const now = Date.now();
- if (now - lastClickTimeRef.current > 100) {
- lastClickTimeRef.current = now;
-
- // Clear box selection when clicking on a non-selected page
- if (!isBoxSelected && clearBoxSelection) {
- clearBoxSelection();
- }
-
- // Don't toggle page selection if it's box-selected (just keep the box selection)
- if (!isBoxSelected) {
- onTogglePage(page.id);
- }
- }
- }
-
- setIsMouseDown(false);
- setMouseStartPos(null);
- },
- [
- isMouseDown,
- mouseStartPos,
- isDragging,
- page.id,
- isBoxSelected,
- clearBoxSelection,
- onTogglePage,
- ],
- );
-
- const handleMouseLeave = useCallback(() => {
- setIsMouseDown(false);
- setMouseStartPos(null);
- setIsHovered(false);
- }, []);
-
- const fileColorBorder = page.isBlankPage
- ? "transparent"
- : getFileColorWithOpacity(fileColorIndex, 0.3);
-
- // Spread dragHandleProps but use our merged ref
- const { ref: _, ...restDragProps } = dragHandleProps || {};
-
- // Build hover menu actions
- const hoverActions = useMemo<HoverAction[]>(
- () => [
- {
- id: "move-left",
- icon: <Icon name="arrow-left" size={20} />,
- label: t("pageEditor.actions.moveLeft", "Move Left"),
- onClick: (e) => {
- e.stopPropagation();
- if (pageIndex > 0 && !isAnimating) {
- onReorderPages(page.pageNumber, pageIndex - 1);
- onSetStatus(`Moved page ${page.pageNumber} left`);
- }
- },
- disabled: pageIndex === 0,
- },
- {
- id: "move-right",
- icon: <Icon name="arrow-right" size={20} />,
- label: t("pageEditor.actions.moveRight", "Move Right"),
- onClick: (e) => {
- e.stopPropagation();
- if (pageIndex < totalPages - 1 && !isAnimating) {
- // +2 compensates for ReorderPagesCommand's internal targetIndex - 1 adjustment.
- onReorderPages(page.pageNumber, pageIndex + 2);
- onSetStatus(`Moved page ${page.pageNumber} right`);
- }
- },
- disabled: pageIndex === totalPages - 1,
- },
- {
- id: "rotate-left",
- icon: <Icon name="rotate-ccw" size={20} />,
- label: t("pageEditor.actions.rotateLeft", "Rotate Left"),
- onClick: handleRotateLeft,
- },
- {
- id: "rotate-right",
- icon: <Icon name="rotate-cw" size={20} />,
- label: t("pageEditor.actions.rotateRight", "Rotate Right"),
- onClick: handleRotateRight,
- },
- {
- id: "delete",
- icon: <Icon name="trash" size={20} />,
- label: t("pageEditor.actions.deletePage", "Delete Page"),
- onClick: handleDelete,
- color: "red",
- },
- {
- id: "split",
- icon: <Icon name="scissors" size={20} />,
- label: t("pageEditor.actions.splitAfter", "Split After"),
- onClick: handleSplit,
- hidden: pageIndex >= totalPages - 1,
- },
- {
- id: "insert",
- icon: <Icon name="plus" size={20} />,
- label: t("pageEditor.actions.insertFileAfter", "Insert File After"),
- onClick: handleInsertFileAfter,
- },
- ],
- [
- pageIndex,
- totalPages,
- isAnimating,
- page.pageNumber,
- handleRotateLeft,
- handleRotateRight,
- handleDelete,
- handleSplit,
- handleInsertFileAfter,
- onReorderPages,
- onSetStatus,
- t,
- ],
- );
-
- return (
- <div
- ref={mergedRef}
- {...restDragProps}
- data-page-id={page.id}
- data-page-number={page.pageNumber}
- className={`
- ${styles.pageContainer}
- !rounded-lg
- ${selectionMode ? "cursor-pointer" : "cursor-grab"}
- select-none
- flex items-center justify-center
- flex-shrink-0
- shadow-sm
- hover:shadow-md
- transition-all
- relative
- ${isDragging ? "opacity-50 scale-95" : ""}
- ${movingPage === page.pageNumber ? "page-moving" : ""}
- ${isBoxSelected ? "ring-4 ring-blue-400 ring-offset-2" : ""}
- `}
- style={{
- width: `calc(20rem * ${zoomLevel})`,
- height: `calc(20rem * ${zoomLevel})`,
- transition: isAnimating ? "none" : "transform 0.2s ease-in-out",
- zIndex: isHovered ? 50 : 1,
- ...(isBoxSelected && {
- boxShadow: "0 0 0 4px rgba(59, 130, 246, 0.5)",
- }),
- }}
- onMouseDown={handleMouseDown}
- onMouseUp={handleMouseUp}
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={handleMouseLeave}
- >
- {
- <div
- className={styles.checkboxContainer}
- style={{
- position: "absolute",
- top: 8,
- right: 8,
- zIndex: 10,
- backgroundColor: "white",
- borderRadius: "4px",
- padding: "2px",
- boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
- pointerEvents: "auto",
- }}
- onMouseDown={(e) => {
- e.stopPropagation();
- onTogglePage(page.id);
- }}
- onMouseUp={(e) => e.stopPropagation()}
- onDragStart={(e) => {
- e.preventDefault();
- e.stopPropagation();
- }}
- >
- <Checkbox
- checked={isSelected}
- onChange={() => {
- // Selection is handled by container mouseDown
- }}
- size="sm"
- style={{ pointerEvents: "none" }}
- />
- </div>
- }
-
- <div className="page-container w-[90%] h-[90%]" draggable={false}>
- <div
- className={`${styles.pageSurface} ${justMoved ? styles.pageJustMoved : ""}`}
- style={{
- width: "100%",
- height: "100%",
- backgroundColor: "var(--mantine-color-gray-1)",
- borderRadius: 6,
- boxShadow: page.isBlankPage
- ? "none"
- : `0 0 ${4 + 4 * zoomLevel}px 3px ${fileColorBorder}`,
- padding: 4,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- {page.isBlankPage ? (
- <div
- style={{
- width: "100%",
- height: "100%",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <div
- style={{
- width: "70%",
- aspectRatio: getDocumentAspectRatio(),
- backgroundColor: "white",
- border: "1px solid #e9ecef",
- borderRadius: 2,
- }}
- />
- </div>
- ) : thumbnailUrl ? (
- <PrivateContent>
- <img
- className="ph-no-capture"
- src={thumbnailUrl}
- alt={t("pageEditor.pageLabel", "Page {{page}}", {
- page: page.pageNumber,
- })}
- draggable={false}
- data-original-rotation={page.rotation}
- style={{
- width: "100%",
- height: "100%",
- objectFit: "contain",
- borderRadius: 2,
- transform: `rotate(${page.rotation}deg)`,
- transition: "transform 0.3s ease-in-out",
- }}
- />
- </PrivateContent>
- ) : (
- <div style={{ textAlign: "center" }}>
- <Text size="lg" c="dimmed">
- 📄
- </Text>
- <Text size="xs" c="dimmed" mt={4}>
- {t("pageEditor.pageLabel", "Page {{page}}", {
- page: page.pageNumber,
- })}
- </Text>
- </div>
- )}
- </div>
-
- <Text
- className={styles.pageNumber}
- size="sm"
- fw={500}
- style={{
- color: "var(--mantine-color-white)", // Use theme token for consistency
- position: "absolute",
- top: 5,
- left: 5,
- background: "rgba(162, 201, 255, 0.8)",
- padding: "6px 8px",
- borderRadius: 8,
- zIndex: 20,
- opacity: isHovered || (isOverTarget && !isDragging) ? 0.6 : 0,
- transition: "opacity 0.2s ease-in-out",
- }}
- >
- {page.pageNumber}
- </Text>
-
- <HoverActionMenu
- show={isHovered || isMobile}
- actions={hoverActions}
- position="inside"
- className={styles.pageHoverControls}
- />
- </div>
- </div>
- );
-};
-
-export default PageThumbnail;
diff --git a/frontend/editor/src/core/components/pageEditor/commands/pageCommands.ts b/frontend/editor/src/core/components/pageEditor/commands/pageCommands.ts
deleted file mode 100644
index 69f1f83c3d..0000000000
--- a/frontend/editor/src/core/components/pageEditor/commands/pageCommands.ts
+++ /dev/null
@@ -1,1111 +0,0 @@
-import i18n from "i18next";
-import { FileId } from "@app/types/file";
-import { PDFDocument, PDFPage, PageBreakSettings } from "@app/types/pageEditor";
-
-// V1-style DOM-first command system (replaces the old React state commands)
-export abstract class DOMCommand {
- abstract execute(): void;
- abstract undo(): void;
- abstract description: string;
-}
-
-export class RotatePageCommand extends DOMCommand {
- private originalRotation: number | null = null;
-
- constructor(
- private pageId: string,
- private degrees: number,
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- ) {
- super();
- }
-
- execute(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc) return;
-
- const page = currentDoc.pages.find((p) => p.id === this.pageId);
- if (!page) return;
-
- if (this.originalRotation === null) {
- this.originalRotation = page.rotation;
- }
-
- const newRotation = (((page.rotation + this.degrees) % 360) + 360) % 360;
-
- this.setDocument({
- ...currentDoc,
- pages: currentDoc.pages.map((p) =>
- p.id === this.pageId ? { ...p, rotation: newRotation } : p,
- ),
- });
-
- // Also update DOM immediately for CSS animation on currently-mounted pages
- const pageElement = document.querySelector(
- `[data-page-id="${this.pageId}"]`,
- );
- if (pageElement) {
- const img = pageElement.querySelector("img");
- if (img) img.style.transform = `rotate(${newRotation}deg)`;
- }
- }
-
- undo(): void {
- if (this.originalRotation === null) return;
-
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc) return;
-
- this.setDocument({
- ...currentDoc,
- pages: currentDoc.pages.map((p) =>
- p.id === this.pageId ? { ...p, rotation: this.originalRotation! } : p,
- ),
- });
-
- const pageElement = document.querySelector(
- `[data-page-id="${this.pageId}"]`,
- );
- if (pageElement) {
- const img = pageElement.querySelector("img");
- if (img) img.style.transform = `rotate(${this.originalRotation}deg)`;
- }
- }
-
- get description(): string {
- if (this.degrees > 0) {
- return i18n.t("pageEditor.commands.rotatePageRight", "Rotate page right");
- }
- return i18n.t("pageEditor.commands.rotatePageLeft", "Rotate page left");
- }
-}
-
-export class DeletePagesCommand extends DOMCommand {
- private originalDocument: PDFDocument | null = null;
- private originalSplitPositions: Set<string> = new Set();
- private originalSelectedPages: number[] = [];
- private hasExecuted: boolean = false;
- private pageIdsToDelete: string[] = [];
- private onAllPagesDeleted?: () => void;
-
- constructor(
- private pagesToDelete: number[],
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- private setSelectedPageIds: (pageIds: string[]) => void,
- private getSplitPositions: () => Set<string>,
- private setSplitPositions: (positions: Set<string>) => void,
- private getSelectedPages: () => number[],
- onAllPagesDeleted?: () => void,
- ) {
- super();
- this.onAllPagesDeleted = onAllPagesDeleted;
- }
-
- execute(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc || this.pagesToDelete.length === 0) return;
-
- // Store complete original state for undo (only on first execution)
- if (!this.hasExecuted) {
- this.originalDocument = {
- ...currentDoc,
- pages: currentDoc.pages.map((page) => ({ ...page })), // Deep copy pages
- };
- this.originalSplitPositions = new Set(this.getSplitPositions());
- this.originalSelectedPages = [...this.getSelectedPages()];
-
- // Convert page numbers to page IDs for stable identification
- this.pageIdsToDelete = this.pagesToDelete
- .map((pageNum) => {
- const page = currentDoc.pages.find((p) => p.pageNumber === pageNum);
- return page?.id || "";
- })
- .filter((id) => id);
-
- this.hasExecuted = true;
- }
-
- const selectedPageNumbersBefore = this.getSelectedPages();
- const selectedIdSet = new Set(
- selectedPageNumbersBefore
- .map(
- (pageNum) =>
- currentDoc.pages.find((p) => p.pageNumber === pageNum)?.id,
- )
- .filter((id): id is string => Boolean(id)),
- );
-
- // Filter out deleted pages by ID (stable across undo/redo)
- const remainingPages = currentDoc.pages.filter(
- (page) => !this.pageIdsToDelete.includes(page.id),
- );
-
- if (remainingPages.length === 0) {
- // If all pages would be deleted, clear selection/splits and close PDF
- this.setSelectedPageIds([]);
- this.setSplitPositions(new Set());
- this.onAllPagesDeleted?.();
- return;
- }
-
- // Renumber remaining pages
- remainingPages.forEach((page, index) => {
- page.pageNumber = index + 1;
- });
-
- // Update document
- const updatedDocument: PDFDocument = {
- ...currentDoc,
- pages: remainingPages,
- totalPages: remainingPages.length,
- };
-
- // Adjust split positions
- const currentSplitPositions = this.getSplitPositions();
- const remainingIndexMap = new Map<string, number>();
- remainingPages.forEach((page, index) => {
- remainingIndexMap.set(page.id, index);
- });
- const newPositions = new Set<string>();
- currentSplitPositions.forEach((pageId) => {
- const splitIndex = remainingIndexMap.get(pageId);
- if (splitIndex !== undefined && splitIndex < remainingPages.length - 1) {
- newPositions.add(pageId);
- }
- });
-
- // Apply changes
- this.setDocument(updatedDocument);
-
- const remainingSelectedPageIds = remainingPages
- .filter((page) => selectedIdSet.has(page.id))
- .map((page) => page.id);
- this.setSelectedPageIds(remainingSelectedPageIds);
-
- this.setSplitPositions(newPositions);
- }
-
- undo(): void {
- if (!this.originalDocument) return;
-
- // Simply restore the complete original document state
- this.setDocument(this.originalDocument);
- this.setSplitPositions(this.originalSplitPositions);
- const restoredIds = this.originalSelectedPages
- .map(
- (pageNum) =>
- this.originalDocument!.pages.find(
- (page) => page.pageNumber === pageNum,
- )?.id || "",
- )
- .filter((id) => id !== "");
- this.setSelectedPageIds(restoredIds);
- }
-
- get description(): string {
- return i18n.t("pageEditor.commands.deletePages", "Delete {{count}} pages", {
- count: this.pagesToDelete.length,
- });
- }
-}
-
-export class ReorderPagesCommand extends DOMCommand {
- private originalPages: PDFPage[] = [];
-
- constructor(
- private sourcePageNumber: number,
- private targetIndex: number,
- private selectedPages: number[] | undefined,
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- private onReorderComplete?: (newPages: PDFPage[]) => void,
- ) {
- super();
- }
-
- execute(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc) return;
-
- // Store original state for undo
- this.originalPages = currentDoc.pages.map((page) => ({ ...page }));
-
- // Perform the reorder
- const sourceIndex = currentDoc.pages.findIndex(
- (p) => p.pageNumber === this.sourcePageNumber,
- );
- if (sourceIndex === -1) return;
-
- let reorderedPages: PDFPage[];
-
- if (
- this.selectedPages &&
- this.selectedPages.length > 1 &&
- this.selectedPages.includes(this.sourcePageNumber)
- ) {
- // Multi-page reorder
- const selectedPageObjects = this.selectedPages
- .map((pageNum) =>
- currentDoc.pages.find((p) => p.pageNumber === pageNum),
- )
- .filter((page) => page !== undefined);
-
- const remainingPages = currentDoc.pages.filter(
- (page) => !this.selectedPages!.includes(page.pageNumber),
- );
- remainingPages.splice(this.targetIndex, 0, ...selectedPageObjects);
- reorderedPages = remainingPages;
- } else {
- // Single page reorder
- const working = [...currentDoc.pages];
- const [movedPage] = working.splice(sourceIndex, 1);
-
- // Adjust target index if moving forward (after removal, indices shift)
- const adjustedTargetIndex =
- sourceIndex < this.targetIndex
- ? this.targetIndex - 1
- : this.targetIndex;
-
- working.splice(adjustedTargetIndex, 0, movedPage);
- reorderedPages = working;
- }
-
- const newPages = reorderedPages.map((page, index) => ({
- ...page,
- pageNumber: index + 1,
- }));
-
- const reorderedDocument: PDFDocument = {
- ...currentDoc,
- pages: newPages,
- totalPages: newPages.length,
- };
-
- this.setDocument(reorderedDocument);
-
- // Notify that reordering is complete
- if (this.onReorderComplete) {
- this.onReorderComplete(newPages);
- }
- }
-
- undo(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc || this.originalPages.length === 0) return;
-
- // Restore original page order
- const restoredDocument: PDFDocument = {
- ...currentDoc,
- pages: this.originalPages,
- totalPages: this.originalPages.length,
- };
-
- this.setDocument(restoredDocument);
- }
-
- get description(): string {
- return i18n.t("pageEditor.commands.reorderPages", "Reorder pages");
- }
-}
-
-export class SplitCommand extends DOMCommand {
- private originalSplitPositions: Set<string> = new Set();
-
- constructor(
- private pageId: string,
- private pageNumber: number,
- private getSplitPositions: () => Set<string>,
- private setSplitPositions: (positions: Set<string>) => void,
- ) {
- super();
- }
-
- execute(): void {
- // Store original state for undo
- this.originalSplitPositions = new Set(this.getSplitPositions());
-
- // Toggle the split position
- const currentPositions = this.getSplitPositions();
- const newPositions = new Set(currentPositions);
-
- if (newPositions.has(this.pageId)) {
- newPositions.delete(this.pageId);
- } else {
- newPositions.add(this.pageId);
- }
-
- this.setSplitPositions(newPositions);
- }
-
- undo(): void {
- // Restore original split positions
- this.setSplitPositions(this.originalSplitPositions);
- }
-
- get description(): string {
- const currentPositions = this.getSplitPositions();
- const willAdd = !currentPositions.has(this.pageId);
- if (willAdd) {
- return i18n.t(
- "pageEditor.commands.addSplitAt",
- "Add split at position {{position}}",
- { position: this.pageNumber },
- );
- }
- return i18n.t(
- "pageEditor.commands.removeSplitAt",
- "Remove split at position {{position}}",
- { position: this.pageNumber },
- );
- }
-}
-
-export class BulkRotateCommand extends DOMCommand {
- private originalRotations: Map<string, number> = new Map();
-
- constructor(
- private pageIds: string[],
- private degrees: number,
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- ) {
- super();
- }
-
- execute(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc) return;
-
- const pageIdSet = new Set(this.pageIds);
-
- // Store original rotations from state for reliable undo (only on first execution)
- if (this.originalRotations.size === 0) {
- for (const page of currentDoc.pages) {
- if (pageIdSet.has(page.id)) {
- this.originalRotations.set(page.id, page.rotation);
- }
- }
- }
-
- // Update state so rotation survives virtualizer unmount/remount
- // Build a map of id → new rotation for O(1) DOM lookups below
- const newRotationById = new Map<string, number>();
- const updatedPages = currentDoc.pages.map((page) => {
- if (pageIdSet.has(page.id)) {
- const newRotation =
- (((page.rotation + this.degrees) % 360) + 360) % 360;
- newRotationById.set(page.id, newRotation);
- return { ...page, rotation: newRotation };
- }
- return page;
- });
-
- this.setDocument({ ...currentDoc, pages: updatedPages });
-
- // Mirror to DOM immediately for CSS animation on currently-mounted pages
- for (const pageId of this.pageIds) {
- const pageElement = document.querySelector(`[data-page-id="${pageId}"]`);
- if (pageElement) {
- const img = pageElement.querySelector("img");
- if (img)
- img.style.transform = `rotate(${newRotationById.get(pageId)}deg)`;
- }
- }
- }
-
- undo(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc) return;
-
- // Restore original rotations in state
- const updatedPages = currentDoc.pages.map((page) =>
- this.originalRotations.has(page.id)
- ? { ...page, rotation: this.originalRotations.get(page.id)! }
- : page,
- );
-
- this.setDocument({ ...currentDoc, pages: updatedPages });
-
- // Mirror to DOM immediately for CSS animation on currently-mounted pages
- for (const pageId of this.pageIds) {
- const pageElement = document.querySelector(`[data-page-id="${pageId}"]`);
- if (pageElement) {
- const img = pageElement.querySelector("img");
- if (img && this.originalRotations.has(pageId)) {
- img.style.transform = `rotate(${this.originalRotations.get(pageId)}deg)`;
- }
- }
- }
- }
-
- get description(): string {
- const count = this.pageIds.length;
- if (this.degrees > 0) {
- return i18n.t(
- "pageEditor.commands.rotatePagesRight",
- "Rotate {{count}} pages right",
- { count },
- );
- }
- return i18n.t(
- "pageEditor.commands.rotatePagesLeft",
- "Rotate {{count}} pages left",
- { count },
- );
- }
-}
-
-export class BulkSplitCommand extends DOMCommand {
- private originalSplitPositions: Set<number> = new Set();
-
- constructor(
- private positions: number[],
- private getSplitPositions: () => Set<number>,
- private setSplitPositions: (positions: Set<number>) => void,
- ) {
- super();
- }
-
- execute(): void {
- // Store original state for undo (only on first execution)
- if (this.originalSplitPositions.size === 0) {
- this.originalSplitPositions = new Set(this.getSplitPositions());
- }
-
- // Toggle each position
- const currentPositions = new Set(this.getSplitPositions());
- this.positions.forEach((position) => {
- if (currentPositions.has(position)) {
- currentPositions.delete(position);
- } else {
- currentPositions.add(position);
- }
- });
-
- this.setSplitPositions(currentPositions);
- }
-
- undo(): void {
- // Restore original split positions
- this.setSplitPositions(this.originalSplitPositions);
- }
-
- get description(): string {
- return i18n.t(
- "pageEditor.commands.toggleSplits",
- "Toggle {{count}} split positions",
- { count: this.positions.length },
- );
- }
-}
-
-export class SplitAllCommand extends DOMCommand {
- private originalSplitPositions: Set<number> = new Set();
- private allPossibleSplits: Set<number> = new Set();
-
- constructor(
- private totalPages: number,
- private getSplitPositions: () => Set<number>,
- private setSplitPositions: (positions: Set<number>) => void,
- ) {
- super();
- // Calculate all possible split positions (between pages, not after last page)
- for (let i = 0; i < this.totalPages - 1; i++) {
- this.allPossibleSplits.add(i);
- }
- }
-
- execute(): void {
- // Store original state for undo
- this.originalSplitPositions = new Set(this.getSplitPositions());
-
- // Check if all splits are already active
- const currentSplits = this.getSplitPositions();
- const hasAllSplits = Array.from(this.allPossibleSplits).every((pos) =>
- currentSplits.has(pos),
- );
-
- if (hasAllSplits) {
- // Remove all splits
- this.setSplitPositions(new Set());
- } else {
- // Add all splits
- this.setSplitPositions(this.allPossibleSplits);
- }
- }
-
- undo(): void {
- // Restore original split positions
- this.setSplitPositions(this.originalSplitPositions);
- }
-
- get description(): string {
- const currentSplits = this.getSplitPositions();
- const hasAllSplits = Array.from(this.allPossibleSplits).every((pos) =>
- currentSplits.has(pos),
- );
- if (hasAllSplits) {
- return i18n.t("pageEditor.commands.removeAllSplits", "Remove all splits");
- }
- return i18n.t("pageEditor.commands.splitAllPages", "Split all pages");
- }
-}
-
-// PageBreakSettings, PageSize, and PageOrientation are now imported from pageEditor.ts
-
-export class PageBreakCommand extends DOMCommand {
- private insertedPages: PDFPage[] = [];
- private originalDocument: PDFDocument | null = null;
-
- constructor(
- private selectedPageNumbers: number[],
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- private settings?: PageBreakSettings,
- ) {
- super();
- }
-
- execute(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc || this.selectedPageNumbers.length === 0) return;
-
- // Store original state for undo
- this.originalDocument = {
- ...currentDoc,
- pages: currentDoc.pages.map((page) => ({ ...page })),
- };
-
- // Create new pages array with blank pages inserted
- const newPages: PDFPage[] = [];
- this.insertedPages = [];
- let pageNumberCounter = 1;
-
- currentDoc.pages.forEach((page, index) => {
- // Add the current page
- const updatedPage = { ...page, pageNumber: pageNumberCounter++ };
- newPages.push(updatedPage);
-
- // If this page is selected for page break insertion, add a blank page after it
- if (this.selectedPageNumbers.includes(page.pageNumber)) {
- const blankPage: PDFPage = {
- id: `blank-${Date.now()}-${index}`,
- pageNumber: pageNumberCounter++,
- originalPageNumber: -1, // Mark as blank page
- thumbnail: null,
- rotation: 0,
- selected: false,
- splitAfter: false,
- isBlankPage: true, // Custom flag for blank pages
- pageBreakSettings: this.settings, // Store settings for export
- };
- newPages.push(blankPage);
- this.insertedPages.push(blankPage);
- }
- });
-
- // Update document
- const updatedDocument: PDFDocument = {
- ...currentDoc,
- pages: newPages,
- totalPages: newPages.length,
- };
-
- this.setDocument(updatedDocument);
-
- // No need to maintain selection - page IDs remain stable, so selection persists automatically
- }
-
- undo(): void {
- if (!this.originalDocument) return;
- this.setDocument(this.originalDocument);
- }
-
- get description(): string {
- return i18n.t(
- "pageEditor.commands.insertPageBreaks",
- "Insert {{count}} page breaks",
- { count: this.selectedPageNumbers.length },
- );
- }
-}
-
-export class BulkPageBreakCommand extends DOMCommand {
- private insertedPages: PDFPage[] = [];
- private originalDocument: PDFDocument | null = null;
- private originalSelectedPages: number[] = [];
-
- constructor(
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- private setSelectedPages: (pages: number[]) => void,
- private getSelectedPages: () => number[],
- ) {
- super();
- }
-
- execute(): void {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc) return;
-
- // Store original selection to restore later
- this.originalSelectedPages = this.getSelectedPages();
-
- // Store original state for undo
- this.originalDocument = {
- ...currentDoc,
- pages: currentDoc.pages.map((page) => ({ ...page })),
- };
-
- // Create new pages array with blank pages inserted after each page (except the last)
- const newPages: PDFPage[] = [];
- this.insertedPages = [];
- let pageNumberCounter = 1;
-
- currentDoc.pages.forEach((page, index) => {
- // Add the current page
- const updatedPage = { ...page, pageNumber: pageNumberCounter++ };
- newPages.push(updatedPage);
-
- // Add blank page after each page except the last one
- if (index < currentDoc.pages.length - 1) {
- const blankPage: PDFPage = {
- id: `blank-${Date.now()}-${index}`,
- pageNumber: pageNumberCounter++,
- originalPageNumber: -1,
- thumbnail: null,
- rotation: 0,
- selected: false,
- splitAfter: false,
- isBlankPage: true,
- };
- newPages.push(blankPage);
- this.insertedPages.push(blankPage);
- }
- });
-
- // Update document
- const updatedDocument: PDFDocument = {
- ...currentDoc,
- pages: newPages,
- totalPages: newPages.length,
- };
-
- this.setDocument(updatedDocument);
-
- // Maintain existing selection by mapping original selected pages to their new positions
- const updatedSelection: number[] = [];
- this.originalSelectedPages.forEach((originalPageNum) => {
- // Find the original page by matching the page ID from the original document
- const originalPage = this.originalDocument?.pages[originalPageNum - 1];
- if (originalPage) {
- const foundPage = newPages.find(
- (page) => page.id === originalPage.id && !page.isBlankPage,
- );
- if (foundPage) {
- updatedSelection.push(foundPage.pageNumber);
- }
- }
- });
- this.setSelectedPages(updatedSelection);
- }
-
- undo(): void {
- if (!this.originalDocument) return;
- this.setDocument(this.originalDocument);
- }
-
- get description(): string {
- return i18n.t(
- "pageEditor.commands.insertPageBreaksAll",
- "Insert page breaks after all pages",
- );
- }
-}
-
-export class InsertFilesCommand extends DOMCommand {
- private insertedPages: PDFPage[] = [];
- private originalDocument: PDFDocument | null = null;
- private fileDataMap = new Map<FileId, ArrayBuffer>(); // Store file data for thumbnail generation
- private insertedFileMap = new Map<FileId, File>(); // Store inserted files for export
-
- constructor(
- private files: File[],
- private insertAfterPageNumber: number,
- private getCurrentDocument: () => PDFDocument | null,
- private setDocument: (doc: PDFDocument) => void,
- private setSelectedPages: (pages: number[]) => void,
- private getSelectedPages: () => number[],
- private updateFileContext?: (
- updatedDocument: PDFDocument,
- insertedFiles?: Map<FileId, File>,
- ) => void,
- ) {
- super();
- }
-
- async execute(): Promise<void> {
- const currentDoc = this.getCurrentDocument();
- if (!currentDoc || this.files.length === 0) return;
-
- // Store original state for undo
- this.originalDocument = {
- ...currentDoc,
- pages: currentDoc.pages.map((page) => ({ ...page })),
- };
-
- try {
- // Process each file to extract pages and wait for all to complete
- const allNewPages: PDFPage[] = [];
-
- // Process all files and wait for their completion
- const baseTimestamp = Date.now();
- const extractionPromises = this.files.map(async (file, index) => {
- const fileId =
- `inserted-${file.name}-${baseTimestamp + index}` as FileId;
- // Store inserted file for export
- this.insertedFileMap.set(fileId, file);
- // Use base timestamp + index to ensure unique but predictable file IDs
- return await this.extractPagesFromFile(file, baseTimestamp + index);
- });
-
- const extractedPageArrays = await Promise.all(extractionPromises);
-
- // Flatten all extracted pages
- for (const pages of extractedPageArrays) {
- allNewPages.push(...pages);
- }
-
- if (allNewPages.length === 0) return;
-
- // Find insertion point (after the specified page)
- const insertIndex = this.insertAfterPageNumber; // Insert after page N means insert at index N
-
- // Create new pages array with inserted pages
- const newPages: PDFPage[] = [];
- let pageNumberCounter = 1;
-
- // Add pages before insertion point
- for (let i = 0; i < insertIndex && i < currentDoc.pages.length; i++) {
- const page = {
- ...currentDoc.pages[i],
- pageNumber: pageNumberCounter++,
- };
- newPages.push(page);
- }
-
- // Add inserted pages
- for (const newPage of allNewPages) {
- const insertedPage: PDFPage = {
- ...newPage,
- pageNumber: pageNumberCounter++,
- selected: false,
- splitAfter: false,
- };
- newPages.push(insertedPage);
- this.insertedPages.push(insertedPage);
- }
-
- // Add remaining pages after insertion point
- for (let i = insertIndex; i < currentDoc.pages.length; i++) {
- const page = {
- ...currentDoc.pages[i],
- pageNumber: pageNumberCounter++,
- };
- newPages.push(page);
- }
-
- // Update document
- const updatedDocument: PDFDocument = {
- ...currentDoc,
- pages: newPages,
- totalPages: newPages.length,
- };
-
- this.setDocument(updatedDocument);
-
- // Update FileContext with the new document structure and inserted files
- if (this.updateFileContext) {
- this.updateFileContext(updatedDocument, this.insertedFileMap);
- }
-
- // Generate thumbnails for inserted pages (all files should be read by now)
- this.generateThumbnailsForInsertedPages(updatedDocument);
-
- // Maintain existing selection by mapping original selected pages to their new positions
- const originalSelection = this.getSelectedPages();
- const updatedSelection: number[] = [];
-
- originalSelection.forEach((originalPageNum) => {
- if (originalPageNum <= this.insertAfterPageNumber) {
- // Pages before insertion point keep same number
- updatedSelection.push(originalPageNum);
- } else {
- // Pages after insertion point are shifted by number of inserted pages
- updatedSelection.push(originalPageNum + allNewPages.length);
- }
- });
-
- this.setSelectedPages(updatedSelection);
- } catch (error) {
- console.error("Failed to insert files:", error);
- // Revert to original state if error occurs
- if (this.originalDocument) {
- this.setDocument(this.originalDocument);
- }
- }
- }
-
- private async generateThumbnailsForInsertedPages(
- updatedDocument: PDFDocument,
- ): Promise<void> {
- try {
- const { thumbnailGenerationService } =
- await import("@app/services/thumbnailGenerationService");
-
- // Group pages by file ID to generate thumbnails efficiently
- const pagesByFileId = new Map<FileId, PDFPage[]>();
-
- for (const page of this.insertedPages) {
- const fileId = page.id.substring(
- 0,
- page.id.lastIndexOf("-page-"),
- ) as FileId; /* FIX ME: This looks wrong - like we've thrown away info too early and need to recreate it */
- if (!pagesByFileId.has(fileId)) {
- pagesByFileId.set(fileId, []);
- }
- pagesByFileId.get(fileId)!.push(page);
- }
-
- // Generate thumbnails for each file
- for (const [fileId, pages] of pagesByFileId) {
- const arrayBuffer = this.fileDataMap.get(fileId);
-
- console.log("Generating thumbnails for file:", fileId);
- console.log("Pages:", pages.length);
- console.log(
- "ArrayBuffer size:",
- arrayBuffer?.byteLength || "undefined",
- );
-
- try {
- if (arrayBuffer && arrayBuffer.byteLength > 0) {
- // Extract page numbers for all pages from this file
- const pageNumbers = pages.map((page) => {
- const pageNumMatch = page.id.match(/-page-(\d+)$/);
- return pageNumMatch ? parseInt(pageNumMatch[1]) : 1;
- });
-
- console.log("Generating thumbnails for page numbers:", pageNumbers);
-
- // Generate thumbnails for all pages from this file at once
- const results = await thumbnailGenerationService.generateThumbnails(
- fileId,
- arrayBuffer,
- pageNumbers,
- {
- scale: 0.2,
- quality: 0.8,
- },
- );
-
- console.log(
- "Thumbnail generation results:",
- results.length,
- "thumbnails generated",
- );
-
- // Update pages with generated thumbnails
- for (let i = 0; i < results.length && i < pages.length; i++) {
- const result = results[i];
- const page = pages[i];
-
- if (result.success) {
- const pageIndex = updatedDocument.pages.findIndex(
- (p) => p.id === page.id,
- );
- if (pageIndex >= 0) {
- updatedDocument.pages[pageIndex].thumbnail = result.thumbnail;
- console.log("Updated thumbnail for page:", page.id);
- }
- }
- }
-
- // Trigger re-render by updating the document
- this.setDocument({ ...updatedDocument });
- } else {
- console.error("No valid ArrayBuffer found for file ID:", fileId);
- }
- } catch (error) {
- console.error(
- "Failed to generate thumbnails for file:",
- fileId,
- error,
- );
- } finally {
- this.fileDataMap.delete(fileId);
- }
- }
- } catch (error) {
- console.error("Failed to generate thumbnails for inserted pages:", error);
- }
- }
-
- private async extractPagesFromFile(
- file: File,
- baseTimestamp: number,
- ): Promise<PDFPage[]> {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = async (event) => {
- try {
- const arrayBuffer = event.target?.result as ArrayBuffer;
- console.log(
- "File reader onload - arrayBuffer size:",
- arrayBuffer?.byteLength || "undefined",
- );
-
- if (!arrayBuffer) {
- reject(new Error("Failed to read file"));
- return;
- }
-
- // Clone the ArrayBuffer before passing to PDF.js (it might consume it)
- const clonedArrayBuffer = arrayBuffer.slice(0);
-
- // Use PDF.js via the worker manager to extract pages
- const { pdfWorkerManager } =
- await import("@app/services/pdfWorkerManager");
- const pdf = await pdfWorkerManager.createDocument(clonedArrayBuffer);
-
- const pageCount = pdf.numPages;
- const pages: PDFPage[] = [];
- const fileId = `inserted-${file.name}-${baseTimestamp}` as FileId;
-
- console.log("Original ArrayBuffer size:", arrayBuffer.byteLength);
- console.log(
- "Storing ArrayBuffer for fileId:",
- fileId,
- "size:",
- arrayBuffer.byteLength,
- );
-
- // Store the original ArrayBuffer for thumbnail generation
- this.fileDataMap.set(fileId, arrayBuffer);
-
- console.log(
- "After storing - fileDataMap size:",
- this.fileDataMap.size,
- );
- console.log(
- "Stored value size:",
- this.fileDataMap.get(fileId)?.byteLength || "undefined",
- );
-
- for (let i = 1; i <= pageCount; i++) {
- const pageId = `${fileId}-page-${i}`;
- pages.push({
- id: pageId,
- pageNumber: i, // Will be renumbered in execute()
- originalPageNumber: i,
- thumbnail: null, // Will be generated after insertion
- rotation: 0,
- selected: false,
- splitAfter: false,
- isBlankPage: false,
- });
- }
-
- // Clean up PDF document
- pdfWorkerManager.destroyDocument(pdf);
-
- resolve(pages);
- } catch (error) {
- reject(error);
- }
- };
- reader.onerror = () => reject(new Error("Failed to read file"));
- reader.readAsArrayBuffer(file);
- });
- }
-
- undo(): void {
- if (!this.originalDocument) return;
- this.setDocument(this.originalDocument);
- }
-
- get description(): string {
- return i18n.t(
- "pageEditor.commands.insertFiles",
- "Insert {{count}} files after page {{page}}",
- { count: this.files.length, page: this.insertAfterPageNumber },
- );
- }
-}
-
-// Simple undo manager for DOM commands
-export class UndoManager {
- private undoStack: DOMCommand[] = [];
- private redoStack: DOMCommand[] = [];
- private onStateChange?: () => void;
-
- setStateChangeCallback(callback: () => void): void {
- this.onStateChange = callback;
- }
-
- executeCommand(command: DOMCommand): void {
- command.execute();
- this.undoStack.push(command);
- this.redoStack = [];
- this.onStateChange?.();
- }
-
- // For async commands that need to be executed manually
- addToUndoStack(command: DOMCommand): void {
- this.undoStack.push(command);
- this.redoStack = [];
- this.onStateChange?.();
- }
-
- undo(): boolean {
- const command = this.undoStack.pop();
- if (command) {
- command.undo();
- this.redoStack.push(command);
- this.onStateChange?.();
- return true;
- }
- return false;
- }
-
- redo(): boolean {
- const command = this.redoStack.pop();
- if (command) {
- command.execute();
- this.undoStack.push(command);
- this.onStateChange?.();
- return true;
- }
- return false;
- }
-
- canUndo(): boolean {
- return this.undoStack.length > 0;
- }
-
- canRedo(): boolean {
- return this.redoStack.length > 0;
- }
-
- hasHistory(): boolean {
- return this.undoStack.length > 0;
- }
-
- clear(): void {
- this.undoStack = [];
- this.redoStack = [];
- this.onStateChange?.();
- }
-}
diff --git a/frontend/editor/src/core/components/pageEditor/constants.ts b/frontend/editor/src/core/components/pageEditor/constants.ts
deleted file mode 100644
index 9d50620ab8..0000000000
--- a/frontend/editor/src/core/components/pageEditor/constants.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-// Shared constants for PageEditor grid layout
-export const GRID_CONSTANTS = {
- ITEM_WIDTH: "20rem", // page width
- ITEM_HEIGHT: "21.5rem", // 20rem + 1.5rem gap
- ITEM_GAP: "1.5rem", // gap between items
- OVERSCAN_SMALL: 8, // Overscan for normal documents
- OVERSCAN_LARGE: 12, // Overscan for large documents (12 rows = ~96 pages pre-rendered)
-} as const;
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts b/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts
deleted file mode 100644
index 3fdb2f89dc..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts
+++ /dev/null
@@ -1,292 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-
-import { FileId } from "@app/types/file";
-import { PDFDocument, PDFPage } from "@app/types/pageEditor";
-
-interface UseEditedDocumentStateParams {
- initialDocument: PDFDocument | null;
- mergedPdfDocument: PDFDocument | null;
- reorderedPages: PDFPage[] | null;
- clearReorderedPages: () => void;
- fileOrder: FileId[];
- updateCurrentPages: (pages: PDFPage[] | null) => void;
- /** Bumps when the bytes behind the open files are replaced. */
- contentRevision: number;
- /** Runs when that discards the working document, so the caller can drop the
- * undo history and the unsaved-changes flag that described it. */
- onDocumentReplaced: () => void;
-}
-
-export const useEditedDocumentState = ({
- initialDocument,
- mergedPdfDocument,
- reorderedPages,
- clearReorderedPages,
- fileOrder,
- updateCurrentPages,
- contentRevision,
- onDocumentReplaced,
-}: UseEditedDocumentStateParams) => {
- const [editedDocument, setEditedDocument] = useState<PDFDocument | null>(
- null,
- );
- const editedDocumentRef = useRef<PDFDocument | null>(null);
- const pagePositionCacheRef = useRef<Map<string, number>>(new Map());
- const pageNeighborCacheRef = useRef<Map<string, string | null>>(new Map());
- const lastSyncedSignatureRef = useRef<string | null>(null);
-
- // Clone the initial document once so we can safely mutate working state
- useEffect(() => {
- if (!initialDocument || editedDocument) return;
-
- setEditedDocument({
- ...initialDocument,
- pages: initialDocument.pages.map((page) => ({ ...page })),
- });
- }, [initialDocument, editedDocument]);
-
- // Apply reorders triggered elsewhere in the editor
- useEffect(() => {
- if (!reorderedPages || !editedDocument) return;
-
- setEditedDocument({
- ...editedDocument,
- pages: reorderedPages,
- });
- clearReorderedPages();
- }, [reorderedPages, editedDocument, clearReorderedPages]);
-
- // Keep ref synced so effects can read latest without re-running
- useEffect(() => {
- editedDocumentRef.current = editedDocument;
- }, [editedDocument]);
-
- // Cache page positions to help future insertions preserve intent
- useEffect(() => {
- if (!editedDocument) return;
-
- const positionCache = pagePositionCacheRef.current;
- const neighborCache = pageNeighborCacheRef.current;
- const pages = editedDocument.pages;
-
- pages.forEach((page, index) => {
- positionCache.set(page.id, index);
- neighborCache.set(page.id, index > 0 ? pages[index - 1].id : null);
- });
- }, [editedDocument]);
-
- // A disk reload swaps the bytes under an unchanged file id, so the merge
- // below - which is built to fold in additions and removals while preserving
- // the user's edits - would carry edits belonging to a document that no longer
- // exists. The next rebuild is taken whole instead.
- const replaceOnNextRebuild = useRef(false);
- const seenContentRevision = useRef(contentRevision);
- useEffect(() => {
- if (seenContentRevision.current === contentRevision) return;
- seenContentRevision.current = contentRevision;
- replaceOnNextRebuild.current = true;
- onDocumentReplaced();
- }, [contentRevision, onDocumentReplaced]);
-
- const fileOrderKey = useMemo(() => fileOrder.join(","), [fileOrder]);
- const mergedDocSignature = useMemo(() => {
- if (!mergedPdfDocument?.pages) return "";
- return mergedPdfDocument.pages.map((page) => page.id).join(",");
- }, [mergedPdfDocument]);
-
- useEffect(() => {
- if (!mergedPdfDocument) {
- lastSyncedSignatureRef.current = null;
- }
- }, [mergedPdfDocument]);
-
- useEffect(() => {
- if (!mergedPdfDocument) {
- setEditedDocument(null);
- }
- }, [mergedPdfDocument, setEditedDocument]);
-
- // Keep editedDocument in sync with out-of-band insert/remove events (e.g. uploads finishing)
- useEffect(() => {
- const currentEditedDocument = editedDocumentRef.current;
- if (!mergedPdfDocument || !currentEditedDocument) return;
-
- const signatureChanged =
- mergedDocSignature !== lastSyncedSignatureRef.current;
- const metadataChanged =
- currentEditedDocument.id !== mergedPdfDocument.id ||
- currentEditedDocument.file !== mergedPdfDocument.file ||
- currentEditedDocument.name !== mergedPdfDocument.name;
- // Replacing the bytes can leave the page ids identical - same file, same
- // page count, different content - so a pending replace is its own reason to
- // rebuild, not just a modifier on one.
- const replacing = replaceOnNextRebuild.current;
-
- if (!signatureChanged && !metadataChanged && !replacing) return;
- replaceOnNextRebuild.current = false;
-
- setEditedDocument((prev) => {
- if (!prev) return prev;
-
- let pages = prev.pages;
-
- if (signatureChanged || replacing) {
- const sourcePages = mergedPdfDocument.pages;
- const sourceIds = new Set(sourcePages.map((p) => p.id));
- const prevIds = new Set(prev.pages.map((p) => p.id));
- const hasOverlap = sourcePages.some((page) => prevIds.has(page.id));
- const shouldResetToMerged = replacing || !hasOverlap;
-
- const newPages: PDFPage[] = [];
- for (const page of sourcePages) {
- if (!prevIds.has(page.id)) {
- newPages.push(page);
- }
- }
-
- const hasAdditions = newPages.length > 0;
- const isEphemeralPage = (page: PDFPage) =>
- Boolean(page.isBlankPage || page.isPlaceholder);
-
- let hasRemovals = false;
- for (const page of prev.pages) {
- if (!sourceIds.has(page.id) && !isEphemeralPage(page)) {
- hasRemovals = true;
- break;
- }
- }
-
- if (shouldResetToMerged) {
- pages = sourcePages.map((page) => ({ ...page }));
- } else if (hasAdditions || hasRemovals) {
- pages = [...prev.pages];
-
- const placeholderPositions = new Map<FileId, number>();
- pages.forEach((page, index) => {
- if (page.isPlaceholder && page.originalFileId) {
- placeholderPositions.set(page.originalFileId, index);
- }
- });
-
- const nextInsertIndexByFile = new Map(placeholderPositions);
-
- if (hasRemovals) {
- pages = pages.filter(
- (page) => sourceIds.has(page.id) || isEphemeralPage(page),
- );
- }
-
- if (hasAdditions) {
- const mergedIndexMap = new Map<string, number>();
- sourcePages.forEach((page, index) =>
- mergedIndexMap.set(page.id, index),
- );
-
- const additions = newPages
- .map((page) => ({
- page,
- cachedIndex: pagePositionCacheRef.current.get(page.id),
- mergedIndex: mergedIndexMap.get(page.id) ?? sourcePages.length,
- neighborId: pageNeighborCacheRef.current.get(page.id),
- }))
- .sort((a, b) => {
- const aIndex = a.cachedIndex ?? a.mergedIndex;
- const bIndex = b.cachedIndex ?? b.mergedIndex;
- if (aIndex !== bIndex) return aIndex - bIndex;
- return a.mergedIndex - b.mergedIndex;
- });
-
- additions.forEach(
- ({ page, neighborId, cachedIndex, mergedIndex }) => {
- if (pages.some((existing) => existing.id === page.id)) {
- return;
- }
-
- let insertIndex: number;
- const originalFileId = page.originalFileId;
- const placeholderIndex =
- originalFileId !== undefined
- ? nextInsertIndexByFile.get(originalFileId)
- : undefined;
-
- if (originalFileId && placeholderIndex !== undefined) {
- insertIndex = Math.min(placeholderIndex, pages.length);
- nextInsertIndexByFile.set(originalFileId, insertIndex + 1);
- } else if (neighborId === null) {
- insertIndex = 0;
- } else if (neighborId) {
- const neighborIndex = pages.findIndex(
- (p) => p.id === neighborId,
- );
- if (neighborIndex !== -1) {
- insertIndex = neighborIndex + 1;
- } else {
- const fallbackIndex =
- cachedIndex ?? mergedIndex ?? pages.length;
- insertIndex = Math.min(fallbackIndex, pages.length);
- }
- } else {
- const fallbackIndex =
- cachedIndex ?? mergedIndex ?? pages.length;
- insertIndex = Math.min(fallbackIndex, pages.length);
- }
-
- const clonedPage = { ...page };
- pages.splice(insertIndex, 0, clonedPage);
- },
- );
- }
- }
-
- if (shouldResetToMerged || hasAdditions || hasRemovals) {
- pages = pages.map((page, index) => ({
- ...page,
- pageNumber: index + 1,
- }));
- }
- }
-
- const shouldReplaceBase =
- metadataChanged || signatureChanged || replacing;
- const baseDocument = shouldReplaceBase
- ? {
- ...mergedPdfDocument,
- destroy: prev.destroy,
- }
- : prev;
-
- if (baseDocument === prev && pages === prev.pages) {
- return prev;
- }
-
- return {
- ...baseDocument,
- pages,
- totalPages: pages.length,
- };
- });
-
- if (signatureChanged || replacing) {
- lastSyncedSignatureRef.current = mergedDocSignature;
- }
- }, [mergedPdfDocument, fileOrderKey, mergedDocSignature, contentRevision]);
-
- const displayDocument = editedDocument || initialDocument;
-
- const getEditedDocument = useCallback(() => editedDocumentRef.current, []);
-
- useEffect(() => {
- updateCurrentPages(displayDocument?.pages ?? null);
- }, [displayDocument, updateCurrentPages]);
-
- return {
- editedDocument,
- setEditedDocument,
- displayDocument,
- getEditedDocument,
- };
-};
-
-export type UseEditedDocumentStateReturn = ReturnType<
- typeof useEditedDocumentState
->;
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/useEditorCommands.ts b/frontend/editor/src/core/components/pageEditor/hooks/useEditorCommands.ts
deleted file mode 100644
index 72ee6c689f..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/useEditorCommands.ts
+++ /dev/null
@@ -1,463 +0,0 @@
-import { useCallback, useEffect, useRef } from "react";
-import i18n from "i18next";
-
-import {
- BulkRotateCommand,
- DeletePagesCommand,
- DOMCommand,
- PageBreakCommand,
- ReorderPagesCommand,
- SplitCommand,
-} from "@app/components/pageEditor/commands/pageCommands";
-import type { useFileActions, useFileState } from "@app/contexts/FileContext";
-import { PDFDocument, PDFPage } from "@app/types/pageEditor";
-import { FileId } from "@app/types/file";
-import { StirlingFileStub } from "@app/types/fileContext";
-
-type FileActions = ReturnType<typeof useFileActions>["actions"];
-type FileSelectors = ReturnType<typeof useFileState>["selectors"];
-
-interface UsePageEditorCommandsParams {
- displayDocument: PDFDocument | null;
- getEditedDocument: () => PDFDocument | null;
- setEditedDocument: React.Dispatch<React.SetStateAction<PDFDocument | null>>;
- splitPositions: Set<string>;
- setSplitPositions: React.Dispatch<React.SetStateAction<Set<string>>>;
- selectedPageIds: string[];
- setSelectedPageIds: (ids: string[]) => void;
- getPageNumbersFromIds: (pageIds: string[]) => number[];
- executeCommandWithTracking: (command: DOMCommand) => void;
- updateFileOrderFromPages: (pages: PDFPage[]) => void;
- actions: FileActions;
- selectors: FileSelectors;
- setSelectionMode: (enabled: boolean) => void;
- clearUndoHistory: () => void;
-}
-
-export const usePageEditorCommands = ({
- displayDocument,
- getEditedDocument,
- setEditedDocument,
- splitPositions,
- setSplitPositions,
- selectedPageIds,
- setSelectedPageIds,
- getPageNumbersFromIds,
- executeCommandWithTracking,
- updateFileOrderFromPages,
- actions,
- selectors,
- setSelectionMode,
- clearUndoHistory,
-}: UsePageEditorCommandsParams) => {
- const splitPositionsRef = useRef(splitPositions);
-
- useEffect(() => {
- splitPositionsRef.current = splitPositions;
- }, [splitPositions]);
-
- const closePdf = useCallback(() => {
- actions.clearAllFiles();
- clearUndoHistory();
- setSelectedPageIds([]);
- setSelectionMode(false);
- }, [actions, clearUndoHistory, setSelectedPageIds, setSelectionMode]);
-
- const handleRotatePages = useCallback(
- (pageIds: string[], rotation: number) => {
- const bulkRotateCommand = new BulkRotateCommand(
- pageIds,
- rotation,
- getEditedDocument,
- setEditedDocument,
- );
- executeCommandWithTracking(bulkRotateCommand);
- },
- [executeCommandWithTracking, getEditedDocument, setEditedDocument],
- );
-
- const createRotateCommand = useCallback(
- (pageIds: string[], rotation: number) => ({
- execute: () => {
- const bulkRotateCommand = new BulkRotateCommand(
- pageIds,
- rotation,
- getEditedDocument,
- setEditedDocument,
- );
- executeCommandWithTracking(bulkRotateCommand);
- },
- }),
- [executeCommandWithTracking, getEditedDocument, setEditedDocument],
- );
-
- const createDeleteCommand = useCallback(
- (pageIds: string[]) => ({
- execute: () => {
- const currentDocument = getEditedDocument();
- if (!currentDocument) return;
-
- const pagesToDelete = pageIds
- .map((pageId) => {
- const page = currentDocument.pages.find((p) => p.id === pageId);
- return page?.pageNumber || 0;
- })
- .filter((num) => num > 0);
-
- if (pagesToDelete.length > 0) {
- const deleteCommand = new DeletePagesCommand(
- pagesToDelete,
- getEditedDocument,
- setEditedDocument,
- setSelectedPageIds,
- () => splitPositions,
- setSplitPositions,
- () => getPageNumbersFromIds(selectedPageIds),
- () => closePdf(),
- );
- executeCommandWithTracking(deleteCommand);
- }
- },
- }),
- [
- closePdf,
- executeCommandWithTracking,
- getEditedDocument,
- getPageNumbersFromIds,
- selectedPageIds,
- setEditedDocument,
- setSelectedPageIds,
- setSplitPositions,
- splitPositions,
- ],
- );
-
- const createSplitCommand = useCallback(
- (pageId: string, pageNumber: number) => ({
- execute: () => {
- const splitCommand = new SplitCommand(
- pageId,
- pageNumber,
- () => splitPositionsRef.current,
- setSplitPositions,
- );
- executeCommandWithTracking(splitCommand);
- },
- }),
- [executeCommandWithTracking, setSplitPositions],
- );
-
- const executeCommand = useCallback((command: { execute: () => void }) => {
- command.execute();
- }, []);
-
- const handleRotate = useCallback(
- (direction: "left" | "right") => {
- if (!displayDocument || selectedPageIds.length === 0) return;
- const rotation = direction === "left" ? -90 : 90;
-
- handleRotatePages(selectedPageIds, rotation);
- },
- [displayDocument, selectedPageIds, handleRotatePages],
- );
-
- const handleDelete = useCallback(() => {
- if (!displayDocument || selectedPageIds.length === 0) return;
-
- const selectedPageNumbers = getPageNumbersFromIds(selectedPageIds);
-
- const deleteCommand = new DeletePagesCommand(
- selectedPageNumbers,
- getEditedDocument,
- setEditedDocument,
- setSelectedPageIds,
- () => splitPositions,
- setSplitPositions,
- () => selectedPageNumbers,
- () => closePdf(),
- );
- executeCommandWithTracking(deleteCommand);
- }, [
- closePdf,
- displayDocument,
- executeCommandWithTracking,
- getEditedDocument,
- getPageNumbersFromIds,
- selectedPageIds,
- setEditedDocument,
- setSelectedPageIds,
- setSplitPositions,
- splitPositions,
- ]);
-
- const handleDeletePage = useCallback(
- (pageNumber: number) => {
- if (!displayDocument) return;
-
- const deleteCommand = new DeletePagesCommand(
- [pageNumber],
- getEditedDocument,
- setEditedDocument,
- setSelectedPageIds,
- () => splitPositions,
- setSplitPositions,
- () => getPageNumbersFromIds(selectedPageIds),
- () => closePdf(),
- );
- executeCommandWithTracking(deleteCommand);
- },
- [
- closePdf,
- getEditedDocument,
- executeCommandWithTracking,
- getPageNumbersFromIds,
- selectedPageIds,
- setEditedDocument,
- setSelectedPageIds,
- setSplitPositions,
- splitPositions,
- ],
- );
-
- const handleSplit = useCallback(() => {
- if (!displayDocument || selectedPageIds.length === 0) return;
-
- const selectedSplitPageIds = displayDocument.pages
- .filter(
- (page, index) =>
- selectedPageIds.includes(page.id) &&
- index < displayDocument.pages.length - 1,
- )
- .map((page) => page.id);
-
- if (selectedSplitPageIds.length === 0) return;
-
- const existingSplitsCount = selectedSplitPageIds.filter((id) =>
- splitPositions.has(id),
- ).length;
- const noSplitsCount = selectedSplitPageIds.length - existingSplitsCount;
- const shouldRemoveSplits = existingSplitsCount > noSplitsCount;
-
- const newSplitPositions = new Set(splitPositions);
-
- if (shouldRemoveSplits) {
- selectedSplitPageIds.forEach((id) => newSplitPositions.delete(id));
- } else {
- selectedSplitPageIds.forEach((id) => newSplitPositions.add(id));
- }
-
- const smartSplitCommand = {
- execute: () => setSplitPositions(newSplitPositions),
- undo: () => setSplitPositions(splitPositions),
- description: shouldRemoveSplits
- ? i18n.t(
- "pageEditor.commands.removeSplits",
- "Remove {{count}} splits",
- {
- count: selectedSplitPageIds.length,
- },
- )
- : i18n.t("pageEditor.commands.addSplits", "Add {{count}} splits", {
- count: noSplitsCount,
- }),
- };
-
- executeCommandWithTracking(smartSplitCommand);
- }, [
- selectedPageIds,
- displayDocument,
- splitPositions,
- setSplitPositions,
- getPageNumbersFromIds,
- executeCommandWithTracking,
- ]);
-
- const handleSplitAll = handleSplit;
-
- const handlePageBreak = useCallback(() => {
- if (!displayDocument || selectedPageIds.length === 0) return;
-
- const selectedPageNumbers = getPageNumbersFromIds(selectedPageIds);
-
- const pageBreakCommand = new PageBreakCommand(
- selectedPageNumbers,
- getEditedDocument,
- setEditedDocument,
- );
- executeCommandWithTracking(pageBreakCommand);
- }, [
- displayDocument,
- executeCommandWithTracking,
- getEditedDocument,
- getPageNumbersFromIds,
- selectedPageIds,
- setEditedDocument,
- ]);
-
- const handlePageBreakAll = handlePageBreak;
-
- const handleInsertFiles = useCallback(
- async (
- files: File[] | StirlingFileStub[],
- insertAfterPage: number,
- isFromStorage?: boolean,
- ) => {
- console.log("[PageEditor] handleInsertFiles called:", {
- fileCount: files.length,
- insertAfterPage,
- isFromStorage,
- });
-
- const workingDocument = getEditedDocument();
- if (!workingDocument || files.length === 0) {
- console.log("[PageEditor] handleInsertFiles early return:", {
- hasDocument: !!workingDocument,
- fileCount: files.length,
- });
- return;
- }
-
- try {
- const targetPage = workingDocument.pages.find(
- (p) => p.pageNumber === insertAfterPage,
- );
- if (!targetPage) {
- console.log("[PageEditor] Target page not found:", insertAfterPage);
- return;
- }
-
- const insertAfterPageId = targetPage.id;
- console.log("[PageEditor] Inserting files after page:", {
- pageNumber: insertAfterPage,
- pageId: insertAfterPageId,
- });
-
- let addedFileIds: FileId[] = [];
- if (isFromStorage) {
- const stubs = files as StirlingFileStub[];
- const result = await actions.addStirlingFileStubs(stubs, {
- selectFiles: true,
- insertAfterPageId,
- });
- addedFileIds = result.map((file) => file.fileId);
- } else {
- const result = await actions.addFiles(files as File[], {
- selectFiles: true,
- insertAfterPageId,
- });
- addedFileIds = result.map((file) => file.fileId);
- console.log("[PageEditor] Files added to context:", {
- addedCount: addedFileIds.length,
- fileIds: addedFileIds,
- });
- }
-
- await new Promise((resolve) => setTimeout(resolve, 100));
-
- const newPages: PDFPage[] = [];
- for (const fileId of addedFileIds) {
- const stub = selectors.getStirlingFileStub(fileId);
- if (stub?.processedFile?.pages) {
- const clonedPages = stub.processedFile.pages.map((page, idx) => ({
- ...page,
- id: `${fileId}-${page.pageNumber ?? idx + 1}`,
- pageNumber: page.pageNumber ?? idx + 1,
- originalFileId: fileId,
- originalPageNumber:
- page.originalPageNumber ?? page.pageNumber ?? idx + 1,
- rotation: page.rotation ?? 0,
- thumbnail: page.thumbnail ?? null,
- selected: false,
- splitAfter: page.splitAfter ?? false,
- }));
- newPages.push(...clonedPages);
- }
- }
-
- if (newPages.length > 0) {
- const targetIndex = workingDocument.pages.findIndex(
- (p) => p.id === targetPage.id,
- );
-
- if (targetIndex >= 0) {
- const updatedPages = [...workingDocument.pages];
- updatedPages.splice(targetIndex + 1, 0, ...newPages);
-
- updatedPages.forEach((page, index) => {
- page.pageNumber = index + 1;
- });
-
- setEditedDocument({
- ...workingDocument,
- pages: updatedPages,
- });
-
- updateFileOrderFromPages(updatedPages);
- }
- }
- } catch (error) {
- console.error("Failed to insert files:", error);
- }
- },
- [
- getEditedDocument,
- actions,
- selectors,
- updateFileOrderFromPages,
- setEditedDocument,
- ],
- );
-
- const handleReorderPages = useCallback(
- (
- sourcePageNumber: number,
- targetIndex: number,
- draggedPageIds?: string[],
- ) => {
- if (!displayDocument) return;
-
- const selectedPages = draggedPageIds
- ? getPageNumbersFromIds(draggedPageIds)
- : undefined;
-
- const reorderCommand = new ReorderPagesCommand(
- sourcePageNumber,
- targetIndex,
- selectedPages,
- getEditedDocument,
- setEditedDocument,
- (newPages) => updateFileOrderFromPages(newPages),
- );
- executeCommandWithTracking(reorderCommand);
- },
- [
- displayDocument,
- getEditedDocument,
- executeCommandWithTracking,
- getPageNumbersFromIds,
- setEditedDocument,
- updateFileOrderFromPages,
- ],
- );
-
- return {
- createRotateCommand,
- createDeleteCommand,
- createSplitCommand,
- executeCommand,
- handleRotate,
- handleDelete,
- handleDeletePage,
- handleSplit,
- handleSplitAll,
- handlePageBreak,
- handlePageBreakAll,
- handleInsertFiles,
- handleReorderPages,
- closePdf,
- };
-};
-
-export type UsePageEditorCommandsReturn = ReturnType<
- typeof usePageEditorCommands
->;
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/useFileColorMap.ts b/frontend/editor/src/core/components/pageEditor/hooks/useFileColorMap.ts
deleted file mode 100644
index f6e9a9c7ed..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/useFileColorMap.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { useMemo, useRef } from "react";
-import { FileId } from "@app/types/file";
-
-/**
- * Maintains stable color assignments for a collection of file IDs.
- * Colors are assigned by insertion order and preserved across reorders.
- */
-export function useFileColorMap(fileIds: FileId[]): Map<FileId, number> {
- const assignmentsRef = useRef(new Map<FileId, number>());
-
- const serializedIds = useMemo(() => fileIds.join(","), [fileIds]);
-
- return useMemo(() => {
- const assignments = assignmentsRef.current;
- const activeIds = new Set(fileIds);
-
- // Remove colors for files that no longer exist
- for (const id of Array.from(assignments.keys())) {
- if (!activeIds.has(id)) {
- assignments.delete(id);
- }
- }
-
- // Assign colors to any new files
- fileIds.forEach((id) => {
- if (!assignments.has(id)) {
- assignments.set(id, assignments.size);
- }
- });
-
- return assignments;
- }, [serializedIds, fileIds]);
-}
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/useInitialPageDocument.ts b/frontend/editor/src/core/components/pageEditor/hooks/useInitialPageDocument.ts
deleted file mode 100644
index 5fda7123eb..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/useInitialPageDocument.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { useState, useEffect, useRef } from "react";
-import { usePageDocument } from "@app/components/pageEditor/hooks/usePageDocument";
-import { PDFDocument } from "@app/types/pageEditor";
-
-/**
- * Hook that calls usePageDocument but only returns the FIRST non-null result
- * After initialization, it ignores all subsequent updates
- */
-export function useInitialPageDocument(): PDFDocument | null {
- const { document: liveDocument } = usePageDocument();
- const [initialDocument, setInitialDocument] = useState<PDFDocument | null>(
- null,
- );
- const lastDocumentIdRef = useRef<string | null>(null);
- const liveDocumentId = liveDocument?.id ?? null;
-
- useEffect(() => {
- if (!liveDocumentId) {
- lastDocumentIdRef.current = null;
- setInitialDocument(null);
- return;
- }
-
- if (liveDocumentId !== lastDocumentIdRef.current) {
- lastDocumentIdRef.current = liveDocumentId;
- setInitialDocument(null);
- }
- }, [liveDocumentId]);
-
- useEffect(() => {
- if (!liveDocument || initialDocument) {
- return;
- }
-
- console.log(
- "📄 useInitialPageDocument: Captured initial document with",
- liveDocument.pages.length,
- "pages",
- );
- setInitialDocument(liveDocument);
- }, [liveDocument, initialDocument]);
-
- return initialDocument;
-}
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageDocument.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageDocument.ts
deleted file mode 100644
index 001ffb2abb..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageDocument.ts
+++ /dev/null
@@ -1,465 +0,0 @@
-import { useMemo, useEffect, useRef, useState } from "react";
-import { useFileState } from "@app/contexts/FileContext";
-import { usePageEditor } from "@app/contexts/PageEditorContext";
-import { PDFDocument, PDFPage } from "@app/types/pageEditor";
-import { FileId } from "@app/types/file";
-import { FileAnalyzer } from "@app/services/fileAnalyzer";
-
-export interface PageDocumentHook {
- document: PDFDocument | null;
- isVeryLargeDocument: boolean;
- isLoading: boolean;
-}
-
-/**
- * Hook for managing PDF document state and metadata in PageEditor
- * Handles document merging, large document detection, and loading states
- */
-export function usePageDocument(): PageDocumentHook {
- const { state, selectors } = useFileState();
- const {
- fileOrder,
- currentPages,
- persistedDocument,
- persistedDocumentSignature,
- } = usePageEditor();
-
- // Use PageEditorContext's fileOrder instead of FileContext's global order
- // This ensures the page editor respects its own workspace ordering
- const allFileIds = fileOrder;
-
- // Derive selected file IDs directly from FileContext (single source of truth)
- // Filter to only include PDF files (PageEditor only supports PDFs)
- // Use stable string keys to prevent infinite loops
- const allFileIdsKey = allFileIds.join(",");
- const selectedFileIdsKey = [...state.ui.selectedFileIds].sort().join(",");
- const activeFilesSignature = selectors.getFilesSignature();
-
- // Get ALL PDF files (selected or not) for document building with placeholders
- const activeFileIds = useMemo(() => {
- return allFileIds.filter((id) => {
- const stub = selectors.getStirlingFileStub(id);
- return stub?.name?.toLowerCase().endsWith(".pdf") ?? false;
- });
- }, [allFileIdsKey, activeFilesSignature, selectors]);
-
- const selectedActiveFileIds = useMemo(() => {
- if (activeFileIds.length === 0) {
- return [];
- }
- const selectedSet = new Set(state.ui.selectedFileIds);
- if (selectedSet.size === 0) {
- return [];
- }
- return activeFileIds.filter((id) => selectedSet.has(id));
- }, [activeFileIds, selectedFileIdsKey]);
-
- const primaryFileId = selectedActiveFileIds[0] ?? activeFileIds[0] ?? null;
-
- // UI state
- const globalProcessing = state.ui.isProcessing;
-
- // Get primary file record outside useMemo to track processedFile changes
- const primaryStirlingFileStub = primaryFileId
- ? selectors.getStirlingFileStub(primaryFileId)
- : null;
- const processedFilePages = primaryStirlingFileStub?.processedFile?.pages;
- const processedFileTotalPages =
- primaryStirlingFileStub?.processedFile?.totalPages;
-
- const placeholderDocumentRef = useRef<PDFDocument | null>(null);
- const [placeholderVersion, setPlaceholderVersion] = useState(0);
-
- useEffect(() => {
- if (!primaryFileId) {
- placeholderDocumentRef.current = null;
- setPlaceholderVersion((v) => v + 1);
- return;
- }
-
- if (primaryStirlingFileStub?.processedFile) {
- placeholderDocumentRef.current = null;
- setPlaceholderVersion((v) => v + 1);
- return;
- }
-
- const file = selectors.getFile(primaryFileId);
- if (!file) {
- placeholderDocumentRef.current = null;
- setPlaceholderVersion((v) => v + 1);
- return;
- }
-
- let canceled = false;
-
- const loadPlaceholder = async () => {
- try {
- const analysis = await FileAnalyzer.quickPDFAnalysis(file);
- if (canceled) return;
- const totalPages = Math.max(1, analysis.pageCount || 1);
- const pages: PDFPage[] = Array.from(
- { length: totalPages },
- (_, index) => ({
- id: `placeholder-${primaryFileId}-page-${index + 1}`,
- pageNumber: index + 1,
- thumbnail: null,
- rotation: 0,
- selected: false,
- originalFileId: primaryFileId,
- originalPageNumber: index + 1,
- }),
- );
-
- if (!canceled) {
- placeholderDocumentRef.current = {
- id: `placeholder-${primaryFileId}`,
- name:
- selectors.getStirlingFileStub(primaryFileId)?.name ?? file.name,
- file,
- pages,
- totalPages,
- };
- setPlaceholderVersion((v) => v + 1);
- }
- } catch {
- if (!canceled) {
- placeholderDocumentRef.current = null;
- setPlaceholderVersion((v) => v + 1);
- }
- }
- };
-
- loadPlaceholder();
-
- return () => {
- canceled = true;
- };
- }, [primaryFileId, primaryStirlingFileStub?.processedFile, selectors]);
-
- // Compute merged document with stable signature (prevents infinite loops)
- const currentPagesSignature = useMemo(() => {
- return currentPages ? currentPages.map((page) => page.id).join(",") : "";
- }, [currentPages]);
-
- const mergedPdfDocument = useMemo((): PDFDocument | null => {
- console.log("[usePageDocument] Building document:", {
- activeFileIds: activeFileIds.length,
- selectedActiveFileIds: selectedActiveFileIds.length,
- hasPersistedDoc: !!persistedDocument,
- persistedDocPages: persistedDocument?.pages.length,
- persistedSig: persistedDocumentSignature?.substring(0, 50),
- currentSig: currentPagesSignature.substring(0, 50),
- });
-
- if (activeFileIds.length === 0) {
- console.log("[usePageDocument] No active files, returning null");
- return null;
- }
-
- // Check if persisted document is still valid
- // Must match signature AND have the same number of source files
- const persistedFileIds = persistedDocument
- ? Array.from(
- new Set(
- persistedDocument.pages
- .map((p) => p.originalFileId)
- .filter(Boolean),
- ),
- )
- : [];
- const persistedIsValid =
- persistedDocument &&
- persistedDocumentSignature &&
- persistedDocumentSignature === currentPagesSignature &&
- currentPagesSignature.length > 0 &&
- persistedFileIds.length === activeFileIds.length; // Ensure file count matches
-
- if (persistedIsValid) {
- console.log("[usePageDocument] Using persisted document");
- return persistedDocument;
- } else if (persistedDocument) {
- console.log(
- "[usePageDocument] Persisted document invalid - rebuilding:",
- {
- sigMatch: persistedDocumentSignature === currentPagesSignature,
- persistedFiles: persistedFileIds.length,
- activeFiles: activeFileIds.length,
- },
- );
- }
-
- if (
- !primaryStirlingFileStub?.processedFile &&
- placeholderDocumentRef.current
- ) {
- return placeholderDocumentRef.current;
- }
-
- const primaryFile = primaryFileId ? selectors.getFile(primaryFileId) : null;
-
- // If we have file IDs but no file record, something is wrong - return null to show loading
- if (!primaryStirlingFileStub) {
- console.log(
- "🎬 PageEditor: No primary file record found, showing loading",
- );
- return null;
- }
-
- const namingFileIds =
- selectedActiveFileIds.length > 0 ? selectedActiveFileIds : activeFileIds;
-
- const name =
- namingFileIds.length <= 1
- ? namingFileIds[0]
- ? (selectors.getStirlingFileStub(namingFileIds[0])?.name ??
- "document.pdf")
- : "document.pdf"
- : namingFileIds
- .map((id) =>
- (selectors.getStirlingFileStub(id)?.name ?? "file").replace(
- /\.pdf$/i,
- "",
- ),
- )
- .join(" + ");
-
- // Build page insertion map from files with insertion positions
- const insertionMap = new Map<string, FileId[]>(); // insertAfterPageId -> fileIds
- const originalFileIds: FileId[] = [];
-
- activeFileIds.forEach((fileId) => {
- const record = selectors.getStirlingFileStub(fileId);
- if (record?.insertAfterPageId !== undefined) {
- console.log("[usePageDocument] File has insertAfterPageId:", {
- fileId,
- insertAfterPageId: record.insertAfterPageId,
- });
- if (!insertionMap.has(record.insertAfterPageId)) {
- insertionMap.set(record.insertAfterPageId, []);
- }
- insertionMap.get(record.insertAfterPageId)!.push(fileId);
- } else {
- originalFileIds.push(fileId);
- }
- });
-
- console.log("[usePageDocument] File categorization:", {
- originalFiles: originalFileIds.length,
- filesToInsert: insertionMap.size,
- totalActive: activeFileIds.length,
- });
-
- // Build pages by interleaving original pages with insertions
- let pages: PDFPage[];
-
- // Helper function to create pages from a file (or placeholder if deselected)
- const createPagesFromFile = (
- fileId: FileId,
- startPageNumber: number,
- isSelected: boolean,
- ): PDFPage[] => {
- const stirlingFileStub = selectors.getStirlingFileStub(fileId);
- if (!stirlingFileStub) {
- return [];
- }
-
- // If file is deselected, create a single placeholder page
- if (!isSelected) {
- return [
- {
- id: `${fileId}-placeholder`,
- pageNumber: startPageNumber,
- originalPageNumber: 1,
- originalFileId: fileId,
- rotation: 0,
- thumbnail: null,
- selected: false,
- splitAfter: false,
- isPlaceholder: true,
- },
- ];
- }
-
- const processedFile = stirlingFileStub.processedFile;
-
- if (processedFile?.pages && processedFile.pages.length > 0) {
- // Use fully processed pages with thumbnails
- return processedFile.pages.map((page, pageIndex) => ({
- id: `${fileId}-${pageIndex + 1}`,
- pageNumber: startPageNumber + pageIndex,
- thumbnail: page.thumbnail || null,
- rotation: page.rotation || 0,
- selected: false,
- splitAfter: page.splitAfter || false,
- // Always use pageIndex + 1 for originalPageNumber to ensure correct numbering
- // This prevents stale or incorrect page numbers from being cached
- originalPageNumber: pageIndex + 1,
- originalFileId: fileId,
- isPlaceholder: false,
- }));
- }
-
- if (processedFile?.totalPages) {
- // Fallback: create pages without thumbnails but with correct count
- return Array.from(
- { length: processedFile.totalPages },
- (_, pageIndex) => ({
- id: `${fileId}-${pageIndex + 1}`,
- pageNumber: startPageNumber + pageIndex,
- originalPageNumber: pageIndex + 1,
- originalFileId: fileId,
- rotation: 0,
- thumbnail: null,
- selected: false,
- splitAfter: false,
- isPlaceholder: false,
- }),
- );
- }
-
- // No processedFile yet - create a single loading placeholder
- // This will be replaced when processing completes
- return [
- {
- id: `${fileId}-loading`,
- pageNumber: startPageNumber,
- originalPageNumber: 1,
- originalFileId: fileId,
- rotation: 0,
- thumbnail: null,
- selected: false,
- splitAfter: false,
- isPlaceholder: true,
- },
- ];
- };
-
- // Collect all pages from original files, respecting their previous positions
- const selectedFileIdsSet = new Set(state.ui.selectedFileIds);
-
- // Sort original files by their position in fileOrder (so placeholders stay in correct spot)
- // Use fileOrder as source of truth since it persists across page editor sessions
- const fileOrderMap = new Map(allFileIds.map((id, index) => [id, index]));
-
- const sortedOriginalFileIds = [...originalFileIds].sort((a, b) => {
- const posA = fileOrderMap.get(a) ?? Number.MAX_SAFE_INTEGER;
- const posB = fileOrderMap.get(b) ?? Number.MAX_SAFE_INTEGER;
- return posA - posB;
- });
-
- const originalFilePages: PDFPage[] = [];
- sortedOriginalFileIds.forEach((fileId) => {
- const isSelected = selectedFileIdsSet.has(fileId);
- const filePages = createPagesFromFile(fileId, 1, isSelected); // Temporary numbering
- originalFilePages.push(...filePages);
- });
-
- // Start with all original pages numbered sequentially
- pages = originalFilePages.map((page, index) => ({
- ...page,
- pageNumber: index + 1,
- }));
-
- // Process each insertion by finding the page ID and inserting after it
- for (const [insertAfterPageId, fileIds] of insertionMap.entries()) {
- const targetPageIndex = pages.findIndex(
- (p) => p.id === insertAfterPageId,
- );
-
- if (targetPageIndex === -1) continue;
-
- // Collect all pages to insert
- const allNewPages: PDFPage[] = [];
- fileIds.forEach((fileId) => {
- const isSelected = selectedFileIdsSet.has(fileId);
- const insertedPages = createPagesFromFile(fileId, 1, isSelected);
- allNewPages.push(...insertedPages);
- });
-
- // Insert all new pages after the target page
- pages.splice(targetPageIndex + 1, 0, ...allNewPages);
-
- // Renumber all pages after insertion
- pages.forEach((page, index) => {
- page.pageNumber = index + 1;
- });
- }
-
- if (pages.length === 0) {
- return null;
- }
-
- // Pages are already in the correct order from the sorted assembly above
- // Just ensure page numbers are sequential
- pages = pages.map((page, index) => ({
- ...page,
- pageNumber: index + 1,
- }));
-
- const currentPagesSet = currentPages
- ? new Set(currentPages.map((page) => page.id))
- : null;
- if (
- currentPagesSet &&
- currentPages &&
- currentPagesSet.size === pages.length
- ) {
- const sameIds = pages.every((page) => currentPagesSet.has(page.id));
- if (sameIds) {
- const mergedById = new Map(pages.map((page) => [page.id, page]));
- pages = currentPages.map((currentPage, index) => {
- const source = mergedById.get(currentPage.id);
- const mergedPage = source
- ? { ...source, ...currentPage }
- : currentPage;
- return {
- ...mergedPage,
- pageNumber: index + 1,
- };
- });
- }
- }
-
- const mergedDoc: PDFDocument = {
- id: activeFileIds.join("-"),
- name,
- file: primaryFile!,
- pages,
- totalPages: pages.length,
- };
-
- return mergedDoc;
- }, [
- activeFileIds,
- selectedActiveFileIds,
- primaryFileId,
- primaryStirlingFileStub,
- processedFilePages,
- processedFileTotalPages,
- selectors,
- activeFilesSignature,
- selectedFileIdsKey,
- state.ui.selectedFileIds,
- state.files.byId, // Force recompute when any file stub changes (including processedFile updates)
- allFileIds,
- currentPagesSignature,
- currentPages,
- persistedDocument,
- persistedDocumentSignature,
- placeholderVersion,
- ]);
-
- // Large document detection for smart loading
- const isVeryLargeDocument = useMemo(() => {
- return mergedPdfDocument ? mergedPdfDocument.totalPages > 2000 : false;
- }, [mergedPdfDocument?.totalPages]);
-
- // Loading state
- const isLoading = globalProcessing && !mergedPdfDocument;
-
- return {
- document: mergedPdfDocument,
- isVeryLargeDocument,
- isLoading,
- };
-}
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts
deleted file mode 100644
index 94ed6590ce..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { useMemo } from "react";
-import { usePageEditor } from "@app/contexts/PageEditorContext";
-import { shallowEqual, useFileSelector } from "@app/contexts/FileContext";
-import { FileId } from "@app/types/file";
-import { useFileColorMap } from "@app/components/pageEditor/hooks/useFileColorMap";
-
-export interface PageEditorDropdownFile {
- fileId: FileId;
- name: string;
- versionNumber?: number;
- isSelected: boolean;
-}
-
-export interface PageEditorDropdownState {
- files: PageEditorDropdownFile[];
- selectedCount: number;
- totalCount: number;
- onToggleSelection: (fileId: FileId) => void;
- onReorder: (fromIndex: number, toIndex: number) => void;
- fileColorMap: Map<FileId, number>;
-}
-
-const isPdf = (name?: string | null) =>
- typeof name === "string" && name.toLowerCase().endsWith(".pdf");
-
-export function usePageEditorDropdownState(): PageEditorDropdownState {
- const selectedFileIds = useFileSelector((s) => s.ui.selectedFileIds);
- const { toggleFileSelection, reorderFiles, fileOrder } = usePageEditor();
-
- // Subscribe to the stubs for the files in view so name/version changes
- // re-render the dropdown. Reading via useFileSelectors() during render would
- // not subscribe, so the displayed name/version could go stale.
- const orderedStubs = useFileSelector(
- (s) => fileOrder.map((fileId) => s.files.byId[fileId]),
- shallowEqual,
- );
-
- const pageEditorFiles = useMemo(() => {
- return fileOrder
- .map<PageEditorDropdownFile | null>((fileId, index) => {
- const stub = orderedStubs[index];
- if (!isPdf(stub?.name)) return null;
-
- return {
- fileId,
- name: stub?.name || "",
- versionNumber: stub?.versionNumber,
- isSelected: selectedFileIds.includes(fileId),
- };
- })
- .filter((file): file is PageEditorDropdownFile => file !== null);
- }, [fileOrder, orderedStubs, selectedFileIds]);
-
- const fileColorMap = useFileColorMap(
- pageEditorFiles.map((file) => file.fileId),
- );
-
- const selectedCount = useMemo(
- () => pageEditorFiles.filter((file) => file.isSelected).length,
- [pageEditorFiles],
- );
-
- return useMemo<PageEditorDropdownState>(
- () => ({
- files: pageEditorFiles,
- selectedCount,
- totalCount: pageEditorFiles.length,
- onToggleSelection: toggleFileSelection,
- onReorder: reorderFiles,
- fileColorMap,
- }),
- [
- pageEditorFiles,
- selectedCount,
- toggleFileSelection,
- reorderFiles,
- fileColorMap,
- ],
- );
-}
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
deleted file mode 100644
index 370cb32188..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
+++ /dev/null
@@ -1,393 +0,0 @@
-import { Dispatch, SetStateAction, useCallback } from "react";
-
-import type { useFileActions, useFileState } from "@app/contexts/FileContext";
-import { inheritedSourceLink } from "@app/contexts/file/storedFileReconciler";
-import { documentManipulationService } from "@app/services/documentManipulationService";
-import { pdfExportService } from "@app/services/pdfExportService";
-import { exportProcessedDocumentsToFiles } from "@app/services/pdfExportHelpers";
-import { FileId } from "@app/types/file";
-import { PDFDocument, PDFPage } from "@app/types/pageEditor";
-import {
- assertFilesNotBlocked,
- policySourceIds,
-} from "@app/services/policyFileGuard";
-
-type FileActions = ReturnType<typeof useFileActions>["actions"];
-type FileSelectors = ReturnType<typeof useFileState>["selectors"];
-
-interface UsePageEditorExportParams {
- displayDocument: PDFDocument | null;
- selectedPageIds: string[];
- splitPositions: Set<string>;
- selectedFileIds: FileId[];
- selectors: FileSelectors;
- actions: FileActions;
- setHasUnsavedChanges: (dirty: boolean) => void;
- exportLoading: boolean;
- setExportLoading: (loading: boolean) => void;
- setSplitPositions: Dispatch<SetStateAction<Set<string>>>;
- clearPersistedDocument: () => void;
- updateCurrentPages: (pages: PDFPage[] | null) => void;
-}
-
-const removePlaceholderPages = (document: PDFDocument): PDFDocument => {
- const filteredPages = document.pages.filter((page) => !page.isPlaceholder);
- if (filteredPages.length === document.pages.length) {
- return document;
- }
-
- const normalizedPages = filteredPages.map((page, index) => ({
- ...page,
- pageNumber: index + 1,
- }));
-
- return {
- ...document,
- pages: normalizedPages,
- totalPages: normalizedPages.length,
- };
-};
-
-const normalizeProcessedDocuments = (
- processed: PDFDocument | PDFDocument[],
-): PDFDocument | PDFDocument[] => {
- if (Array.isArray(processed)) {
- const normalized = processed
- .map(removePlaceholderPages)
- .filter((doc) => doc.pages.length > 0);
- return normalized;
- }
- return removePlaceholderPages(processed);
-};
-
-export const usePageEditorExport = ({
- displayDocument,
- selectedPageIds,
- splitPositions,
- selectedFileIds,
- selectors,
- actions,
- setHasUnsavedChanges,
- exportLoading,
- setExportLoading,
- setSplitPositions,
- clearPersistedDocument,
- updateCurrentPages,
-}: UsePageEditorExportParams) => {
- const getPolicyIds = useCallback(() => {
- const ids = new Set([
- ...selectedFileIds,
- ...(displayDocument?.pages.flatMap((page) =>
- page.originalFileId ? [page.originalFileId] : [],
- ) ?? []),
- ]);
- return [...ids].flatMap((id) => {
- const stub = selectors.getStirlingFileStub(id);
- return stub ? policySourceIds(stub) : [id];
- });
- }, [selectedFileIds, displayDocument, selectors]);
- const getSourceFiles = useCallback((): Map<FileId, File> | null => {
- const sourceFiles = new Map<FileId, File>();
-
- selectedFileIds.forEach((fileId) => {
- const file = selectors.getFile(fileId);
- if (file) {
- sourceFiles.set(fileId, file);
- }
- });
-
- const hasInsertedFiles = false;
- const hasMultipleOriginalFiles = selectedFileIds.length > 1;
-
- if (!hasInsertedFiles && !hasMultipleOriginalFiles) {
- return null;
- }
-
- return sourceFiles.size > 0 ? sourceFiles : null;
- }, [selectedFileIds, selectors]);
-
- const getExportFilename = useCallback((): string => {
- if (selectedFileIds.length <= 1) {
- return displayDocument?.name || "document.pdf";
- }
-
- const firstFile = selectors.getFile(selectedFileIds[0]);
- if (firstFile) {
- const baseName = firstFile.name.replace(/\.pdf$/i, "");
- return `${baseName} (merged).pdf`;
- }
-
- return "merged-document.pdf";
- }, [selectedFileIds, selectors, displayDocument]);
-
- const onExportSelected = useCallback(async () => {
- if (!displayDocument || selectedPageIds.length === 0) return;
-
- setExportLoading(true);
- const policyIds = getPolicyIds();
- try {
- assertFilesNotBlocked(policyIds);
- const processedDocuments =
- documentManipulationService.applyDOMChangesToDocument(
- displayDocument,
- displayDocument,
- splitPositions,
- );
-
- const normalizedDocuments =
- normalizeProcessedDocuments(processedDocuments);
- const documentWithDOMState = Array.isArray(normalizedDocuments)
- ? normalizedDocuments[0]
- : normalizedDocuments;
-
- if (!documentWithDOMState || documentWithDOMState.pages.length === 0) {
- console.warn(
- "Export skipped: no concrete pages available after filtering placeholders.",
- );
- setExportLoading(false);
- return;
- }
-
- const validSelectedPageIds = selectedPageIds.filter((pageId) =>
- documentWithDOMState.pages.some((page) => page.id === pageId),
- );
-
- const sourceFiles = getSourceFiles();
- const exportFilename = getExportFilename();
- const result = sourceFiles
- ? await pdfExportService.exportPDFMultiFile(
- documentWithDOMState,
- sourceFiles,
- validSelectedPageIds,
- {
- selectedOnly: true,
- filename: exportFilename,
- },
- )
- : await pdfExportService.exportPDF(
- documentWithDOMState,
- validSelectedPageIds,
- {
- selectedOnly: true,
- filename: exportFilename,
- },
- );
-
- assertFilesNotBlocked(policyIds);
- pdfExportService.downloadFile(result.blob, result.filename);
- setHasUnsavedChanges(false);
- setSplitPositions(new Set());
- setExportLoading(false);
- } catch (error) {
- console.error("Export failed:", error);
- setExportLoading(false);
- }
- }, [
- displayDocument,
- selectedPageIds,
- splitPositions,
- getSourceFiles,
- getExportFilename,
- selectedFileIds,
- getPolicyIds,
- setHasUnsavedChanges,
- setExportLoading,
- ]);
-
- const onExportAll = useCallback(async () => {
- if (!displayDocument) return;
-
- setExportLoading(true);
- const policyIds = getPolicyIds();
- try {
- assertFilesNotBlocked(policyIds);
- const processedDocuments =
- documentManipulationService.applyDOMChangesToDocument(
- displayDocument,
- displayDocument,
- splitPositions,
- );
-
- const normalizedDocuments =
- normalizeProcessedDocuments(processedDocuments);
-
- if (
- (Array.isArray(normalizedDocuments) &&
- normalizedDocuments.length === 0) ||
- (!Array.isArray(normalizedDocuments) &&
- normalizedDocuments.pages.length === 0)
- ) {
- console.warn(
- "Export skipped: no concrete pages available after filtering placeholders.",
- );
- setExportLoading(false);
- return;
- }
-
- const sourceFiles = getSourceFiles();
- const exportFilename = getExportFilename();
- const files = await exportProcessedDocumentsToFiles(
- normalizedDocuments,
- sourceFiles,
- exportFilename,
- );
-
- if (files.length > 1) {
- const JSZip = await import("jszip");
- const zip = new JSZip.default();
-
- files.forEach((file) => {
- zip.file(file.name, file);
- });
-
- const zipBlob = await zip.generateAsync({ type: "blob" });
- const zipFilename = exportFilename.replace(/\.pdf$/i, ".zip");
-
- assertFilesNotBlocked(policyIds);
- pdfExportService.downloadFile(zipBlob, zipFilename);
- } else {
- const file = files[0];
- assertFilesNotBlocked(policyIds);
- pdfExportService.downloadFile(file, file.name);
- }
-
- setHasUnsavedChanges(false);
- setSplitPositions(new Set());
- setExportLoading(false);
- } catch (error) {
- console.error("Export failed:", error);
- setExportLoading(false);
- }
- }, [
- displayDocument,
- splitPositions,
- getSourceFiles,
- getExportFilename,
- selectedFileIds,
- getPolicyIds,
- setHasUnsavedChanges,
- setExportLoading,
- ]);
-
- const applyChanges = useCallback(async () => {
- if (!displayDocument) return;
-
- setExportLoading(true);
- const policyIds = getPolicyIds();
- try {
- assertFilesNotBlocked(policyIds);
- const processedDocuments =
- documentManipulationService.applyDOMChangesToDocument(
- displayDocument,
- displayDocument,
- splitPositions,
- );
-
- const normalizedDocuments =
- normalizeProcessedDocuments(processedDocuments);
-
- if (
- (Array.isArray(normalizedDocuments) &&
- normalizedDocuments.length === 0) ||
- (!Array.isArray(normalizedDocuments) &&
- normalizedDocuments.pages.length === 0)
- ) {
- console.warn(
- "Apply changes skipped: no concrete pages available after filtering placeholders.",
- );
- setExportLoading(false);
- return;
- }
-
- const sourceFiles = getSourceFiles();
- const exportFilename = getExportFilename();
- const files = await exportProcessedDocumentsToFiles(
- normalizedDocuments,
- sourceFiles,
- exportFilename,
- );
-
- assertFilesNotBlocked(policyIds);
-
- // Add "_multitool" suffix to filenames
- const renamedFiles = files.map((file) => {
- const nameParts = file.name.match(/^(.+?)(\.pdf)$/i);
- if (nameParts) {
- const baseName = nameParts[1];
- const extension = nameParts[2];
- const newName = `${baseName}_multitool${extension}`;
- return new File([file], newName, { type: file.type });
- }
- return file;
- });
-
- // Store source file IDs before adding new files
- const sourceFileIds = [...selectedFileIds];
-
- // Read before the removal below, which takes the source out of the
- // workbench and out of storage: a read afterwards finds nothing, and the
- // file this produces silently loses its link to the one it came from.
- const sourceStub =
- sourceFileIds.length === 1
- ? selectors.getStirlingFileStub(sourceFileIds[0])
- : undefined;
- const inherited = sourceStub ? inheritedSourceLink(sourceStub) : {};
-
- // Clear all cached page state to prevent stale data from being merged
- clearPersistedDocument();
- updateCurrentPages(null);
-
- // Deselect old files immediately so the view can reset before we mutate the file list
- actions.setSelectedFiles([]);
-
- // Remove the original files before inserting the newly generated versions
- if (sourceFileIds.length > 0) {
- await actions.removeFiles(sourceFileIds, true);
- }
-
- assertFilesNotBlocked(policyIds);
- const newStirlingFiles = await actions.addFiles(renamedFiles, {
- selectFiles: true,
- skipUploadTracking: true,
- });
- if (newStirlingFiles.length > 0) {
- actions.setSelectedFiles(newStirlingFiles.map((file) => file.fileId));
- }
-
- if (newStirlingFiles.length === 1 && Object.keys(inherited).length > 0) {
- actions.updateStirlingFileStub(newStirlingFiles[0].fileId, {
- ...inherited,
- isDirty: true,
- });
- }
-
- setHasUnsavedChanges(false);
- setSplitPositions(new Set());
- setExportLoading(false);
- } catch (error) {
- console.error("Apply changes failed:", error);
- setExportLoading(false);
- }
- }, [
- displayDocument,
- splitPositions,
- getSourceFiles,
- getExportFilename,
- selectedFileIds,
- getPolicyIds,
- actions,
- setHasUnsavedChanges,
- setExportLoading,
- clearPersistedDocument,
- updateCurrentPages,
- ]);
-
- return {
- exportLoading,
- onExportSelected,
- onExportAll,
- applyChanges,
- };
-};
-
-export type UsePageEditorExportReturn = ReturnType<typeof usePageEditorExport>;
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorState.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorState.ts
deleted file mode 100644
index 13a96ec3ed..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorState.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { useState, useCallback } from "react";
-import React from "react";
-
-export interface PageEditorState {
- // Selection state
- selectionMode: boolean;
- selectedPageIds: string[];
-
- // Animation state
- movingPage: number | null;
- isAnimating: boolean;
-
- // Split state
- splitPositions: Set<string>;
-
- // Export state
- exportLoading: boolean;
-
- // Actions
- setSelectionMode: (mode: boolean) => void;
- setSelectedPageIds: (pages: string[]) => void;
- setMovingPage: (pageNumber: number | null) => void;
- setIsAnimating: (animating: boolean) => void;
- setSplitPositions: React.Dispatch<React.SetStateAction<Set<string>>>;
- setExportLoading: (loading: boolean) => void;
-
- // Helper functions
- togglePage: (pageId: string) => void;
- toggleSelectAll: (allPageIds: string[]) => void;
- animateReorder: () => void;
-}
-
-/**
- * Hook for managing PageEditor UI state
- * Handles selection, animation, splits, and export states
- */
-export function usePageEditorState(): PageEditorState {
- // Selection state
- const [selectionMode, setSelectionMode] = useState(false);
- const [selectedPageIds, setSelectedPageIds] = useState<string[]>([]);
-
- // Animation state
- const [movingPage, setMovingPage] = useState<number | null>(null);
- const [isAnimating, setIsAnimating] = useState(false);
-
- // Split state - position-based split tracking (replaces page-based splitAfter)
- const [splitPositions, setSplitPositions] = useState<Set<string>>(new Set());
-
- // Export state
- const [exportLoading, setExportLoading] = useState(false);
-
- // Helper functions
- const togglePage = useCallback((pageId: string) => {
- setSelectedPageIds((prev) => {
- const newSelection = prev.includes(pageId)
- ? prev.filter((id) => id !== pageId)
- : [...prev, pageId];
- return newSelection;
- });
- }, []); // Empty deps - uses updater function so always has latest state
-
- const toggleSelectAll = useCallback((allPageIds: string[]) => {
- if (!allPageIds.length) return;
-
- setSelectedPageIds((prev) =>
- prev.length === allPageIds.length ? [] : allPageIds,
- );
- }, []);
-
- const animateReorder = useCallback(() => {
- setIsAnimating(true);
- setTimeout(() => setIsAnimating(false), 500);
- }, []);
-
- return {
- // State
- selectionMode,
- selectedPageIds,
- movingPage,
- isAnimating,
- splitPositions,
- exportLoading,
-
- // Setters
- setSelectionMode,
- setSelectedPageIds,
- setMovingPage,
- setIsAnimating,
- setSplitPositions,
- setExportLoading,
-
- // Helpers
- togglePage,
- toggleSelectAll,
- animateReorder,
- };
-}
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageSelectionManager.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageSelectionManager.ts
deleted file mode 100644
index e19b64f0cd..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageSelectionManager.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-
-import { PDFDocument } from "@app/types/pageEditor";
-import { parseSelection } from "@app/utils/bulkselection/parseSelection";
-
-interface UsePageSelectionManagerParams {
- displayDocument: PDFDocument | null;
- selectedPageIds: string[];
- setSelectedPageIds: (ids: string[]) => void;
- setSelectionMode: (enabled: boolean) => void;
- toggleSelectAll: (ids: string[]) => void;
- activeFilesSignature: string;
-}
-
-export const usePageSelectionManager = ({
- displayDocument,
- selectedPageIds,
- setSelectedPageIds,
- setSelectionMode,
- toggleSelectAll,
- activeFilesSignature,
-}: UsePageSelectionManagerParams) => {
- const [csvInput, setCsvInput] = useState<string>("");
- const hasInitializedSelection = useRef(false);
- const previousPageIdsRef = useRef<Set<string>>(new Set());
-
- const totalPages = displayDocument?.pages.length ?? 0;
-
- const getPageNumbersFromIds = useCallback(
- (pageIds: string[]) => {
- if (!displayDocument) return [];
- return pageIds
- .map((id) => {
- const page = displayDocument.pages.find((p) => p.id === id);
- return page?.pageNumber || 0;
- })
- .filter((num) => num > 0);
- },
- [displayDocument],
- );
-
- const getPageIdsFromNumbers = useCallback(
- (pageNumbers: number[]) => {
- if (!displayDocument) return [];
- return pageNumbers
- .map((num) => {
- const page = displayDocument.pages.find((p) => p.pageNumber === num);
- return page?.id || "";
- })
- .filter((id) => id !== "");
- },
- [displayDocument],
- );
-
- useEffect(() => {
- if (
- displayDocument &&
- displayDocument.pages.length > 0 &&
- !hasInitializedSelection.current
- ) {
- const allPageIds = displayDocument.pages.map((page) => page.id);
- setSelectedPageIds(allPageIds);
- setSelectionMode(true);
- hasInitializedSelection.current = true;
- }
- }, [displayDocument, setSelectedPageIds, setSelectionMode]);
-
- useEffect(() => {
- if (!displayDocument || displayDocument.pages.length === 0) {
- previousPageIdsRef.current = new Set();
- return;
- }
-
- const currentIds = new Set(displayDocument.pages.map((page) => page.id));
- const newlyAddedPageIds: string[] = [];
- currentIds.forEach((id) => {
- if (!previousPageIdsRef.current.has(id)) {
- newlyAddedPageIds.push(id);
- }
- });
-
- if (newlyAddedPageIds.length > 0) {
- const next = new Set(selectedPageIds);
- newlyAddedPageIds.forEach((id) => next.add(id));
- setSelectedPageIds(Array.from(next));
- }
-
- previousPageIdsRef.current = currentIds;
- }, [displayDocument, selectedPageIds, setSelectedPageIds]);
-
- useEffect(() => {
- setCsvInput("");
- }, [activeFilesSignature]);
-
- const handleSelectAll = useCallback(() => {
- if (!displayDocument) return;
- const allPageIds = displayDocument.pages.map((page) => page.id);
- toggleSelectAll(allPageIds);
- }, [displayDocument, toggleSelectAll]);
-
- const handleDeselectAll = useCallback(() => {
- setSelectedPageIds([]);
- }, [setSelectedPageIds]);
-
- const handleSetSelectedPages = useCallback(
- (pageNumbers: number[]) => {
- const pageIds = getPageIdsFromNumbers(pageNumbers);
- setSelectedPageIds(pageIds);
- },
- [getPageIdsFromNumbers, setSelectedPageIds],
- );
-
- const updatePagesFromCSV = useCallback(
- (override?: string) => {
- if (totalPages === 0) return;
- const normalized = parseSelection(override ?? csvInput, totalPages);
- handleSetSelectedPages(normalized);
- },
- [csvInput, totalPages, handleSetSelectedPages],
- );
-
- return {
- csvInput,
- setCsvInput,
- totalPages,
- getPageNumbersFromIds,
- getPageIdsFromNumbers,
- handleSelectAll,
- handleDeselectAll,
- handleSetSelectedPages,
- updatePagesFromCSV,
- };
-};
-
-export type UsePageSelectionManagerReturn = ReturnType<
- typeof usePageSelectionManager
->;
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/useUndoManagerState.ts b/frontend/editor/src/core/components/pageEditor/hooks/useUndoManagerState.ts
deleted file mode 100644
index 0e11aa1e80..0000000000
--- a/frontend/editor/src/core/components/pageEditor/hooks/useUndoManagerState.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-
-import {
- DOMCommand,
- UndoManager,
-} from "@app/components/pageEditor/commands/pageCommands";
-
-interface UseUndoManagerStateParams {
- setHasUnsavedChanges: (dirty: boolean) => void;
-}
-
-export const useUndoManagerState = ({
- setHasUnsavedChanges,
-}: UseUndoManagerStateParams) => {
- const undoManagerRef = useRef(new UndoManager());
- const [canUndo, setCanUndo] = useState(false);
- const [canRedo, setCanRedo] = useState(false);
-
- const updateUndoRedoState = useCallback(() => {
- const undoManager = undoManagerRef.current;
- setCanUndo(undoManager.canUndo());
- setCanRedo(undoManager.canRedo());
-
- if (!undoManager.hasHistory()) {
- setHasUnsavedChanges(false);
- }
- }, [setHasUnsavedChanges]);
-
- useEffect(() => {
- undoManagerRef.current.setStateChangeCallback(updateUndoRedoState);
- updateUndoRedoState();
- }, [updateUndoRedoState]);
-
- const executeCommandWithTracking = useCallback(
- (command: DOMCommand) => {
- undoManagerRef.current.executeCommand(command);
- setHasUnsavedChanges(true);
- },
- [setHasUnsavedChanges],
- );
-
- const handleUndo = useCallback(() => {
- undoManagerRef.current.undo();
- }, []);
-
- const handleRedo = useCallback(() => {
- undoManagerRef.current.redo();
- }, []);
-
- const clearUndoHistory = useCallback(() => {
- undoManagerRef.current.clear();
- updateUndoRedoState();
- }, [updateUndoRedoState]);
-
- return {
- canUndo,
- canRedo,
- executeCommandWithTracking,
- handleUndo,
- handleRedo,
- clearUndoHistory,
- };
-};
-
-export type UseUndoManagerStateReturn = ReturnType<typeof useUndoManagerState>;
diff --git a/frontend/editor/src/core/components/pageEditor/pageEditorWorkbenchBarButtons.tsx b/frontend/editor/src/core/components/pageEditor/pageEditorWorkbenchBarButtons.tsx
deleted file mode 100644
index 2cfa257884..0000000000
--- a/frontend/editor/src/core/components/pageEditor/pageEditorWorkbenchBarButtons.tsx
+++ /dev/null
@@ -1,167 +0,0 @@
-import { useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import {
- useWorkbenchBarButtons,
- WorkbenchBarButtonWithAction,
-} from "@app/hooks/useWorkbenchBarButtons";
-import { Icon } from "@app/ui/Icon";
-import PageSelectByNumberButton from "@app/components/pageEditor/PageSelectByNumberButton";
-
-interface PageEditorWorkbenchBarButtonsParams {
- totalPages: number;
- selectedPageCount: number;
- csvInput: string;
- setCsvInput: (value: string) => void;
- selectedPageIds: string[];
- displayDocument?: { pages: { id: string; pageNumber: number }[] };
- updatePagesFromCSV: (override?: string) => void;
- handleSelectAll: () => void;
- handleDeselectAll: () => void;
- handleDelete: () => void;
- onExportSelected: () => void;
- onSaveChanges: () => void;
- exportLoading: boolean;
-}
-
-export function usePageEditorWorkbenchBarButtons(
- params: PageEditorWorkbenchBarButtonsParams,
-) {
- const {
- totalPages,
- selectedPageCount,
- csvInput,
- setCsvInput,
- selectedPageIds,
- displayDocument,
- updatePagesFromCSV,
- handleSelectAll,
- handleDeselectAll,
- handleDelete,
- onExportSelected,
- onSaveChanges,
- exportLoading,
- } = params;
-
- const { t, i18n } = useTranslation();
-
- // Lift i18n labels out of memo for clarity
- const selectAllLabel = t("workbenchBar.selectAll", "Select All");
- const deselectAllLabel = t("workbenchBar.deselectAll", "Deselect All");
- const selectByNumberLabel = t(
- "workbenchBar.selectByNumber",
- "Select by Page Numbers",
- );
- const deleteSelectedLabel = t(
- "workbenchBar.deleteSelected",
- "Delete Selected Pages",
- );
- const exportSelectedLabel = t(
- "workbenchBar.exportSelected",
- "Export Selected Pages",
- );
- const saveChangesLabel = t("workbenchBar.saveChanges", "Save Changes");
- const buttons = useMemo<WorkbenchBarButtonWithAction[]>(() => {
- return [
- {
- id: "page-select-all",
- icon: <Icon name="select-all" size="1.5rem" />,
- tooltip: selectAllLabel,
- ariaLabel: selectAllLabel,
- section: "top" as const,
- order: 10,
- disabled: totalPages === 0 || selectedPageCount === totalPages,
- visible: totalPages > 0,
- onClick: handleSelectAll,
- },
- {
- id: "page-deselect-all",
- icon: <Icon name="square" size="1.5rem" />,
- tooltip: deselectAllLabel,
- ariaLabel: deselectAllLabel,
- section: "top" as const,
- order: 20,
- disabled: selectedPageCount === 0,
- visible: totalPages > 0,
- onClick: handleDeselectAll,
- },
- {
- id: "page-select-by-number",
- tooltip: selectByNumberLabel,
- ariaLabel: selectByNumberLabel,
- section: "top" as const,
- order: 30,
- disabled: totalPages === 0,
- visible: totalPages > 0,
- render: ({ disabled }) => (
- <PageSelectByNumberButton
- disabled={disabled}
- totalPages={totalPages}
- label={selectByNumberLabel}
- csvInput={csvInput}
- setCsvInput={setCsvInput}
- selectedPageIds={selectedPageIds}
- displayDocument={displayDocument}
- updatePagesFromCSV={updatePagesFromCSV}
- />
- ),
- },
- {
- id: "page-delete-selected",
- icon: <Icon name="trash" size="1.5rem" />,
- tooltip: deleteSelectedLabel,
- ariaLabel: deleteSelectedLabel,
- section: "top" as const,
- order: 40,
- disabled: selectedPageCount === 0,
- visible: totalPages > 0,
- onClick: handleDelete,
- },
- {
- id: "page-export-selected",
- icon: <Icon name="download" size="1.5rem" />,
- tooltip: exportSelectedLabel,
- ariaLabel: exportSelectedLabel,
- section: "top" as const,
- order: 50,
- disabled: selectedPageCount === 0 || exportLoading,
- visible: totalPages > 0,
- onClick: onExportSelected,
- },
- {
- id: "page-save-changes",
- icon: <Icon name="save" size="1.5rem" />,
- tooltip: saveChangesLabel,
- ariaLabel: saveChangesLabel,
- section: "top" as const,
- order: 55,
- disabled: totalPages === 0 || exportLoading,
- visible: totalPages > 0,
- onClick: onSaveChanges,
- },
- ];
- }, [
- t,
- i18n.language,
- selectAllLabel,
- deselectAllLabel,
- selectByNumberLabel,
- deleteSelectedLabel,
- exportSelectedLabel,
- saveChangesLabel,
- totalPages,
- selectedPageCount,
- csvInput,
- setCsvInput,
- selectedPageIds,
- displayDocument,
- updatePagesFromCSV,
- handleSelectAll,
- handleDeselectAll,
- handleDelete,
- onExportSelected,
- onSaveChanges,
- exportLoading,
- ]);
-
- useWorkbenchBarButtons(buttons);
-}
diff --git a/frontend/editor/src/core/components/pageEditor/utils/splitPositions.ts b/frontend/editor/src/core/components/pageEditor/utils/splitPositions.ts
deleted file mode 100644
index ee8f03988c..0000000000
--- a/frontend/editor/src/core/components/pageEditor/utils/splitPositions.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { PDFDocument } from "@app/types/pageEditor";
-
-/**
- * Build a map from page ID to its index in the provided document.
- */
-export function buildPageIdIndexMap(
- document: PDFDocument | null,
-): Map<string, number> {
- const map = new Map<string, number>();
- if (!document) return map;
- document.pages.forEach((page, index) => {
- map.set(page.id, index);
- });
- return map;
-}
-
-/**
- * Convert a set of split page IDs (the page preceding each split) into
- * the current index positions inside the document.
- */
-export function convertSplitPageIdsToIndexes(
- document: PDFDocument | null,
- splitPageIds: Set<string>,
-): Set<number> {
- const indexes = new Set<number>();
- if (!document || !splitPageIds || splitPageIds.size === 0) {
- return indexes;
- }
-
- const totalPages = document.pages.length;
- document.pages.forEach((page, index) => {
- if (index >= totalPages - 1) {
- return; // Cannot split after the last page.
- }
- if (splitPageIds.has(page.id)) {
- indexes.add(index);
- }
- });
-
- return indexes;
-}
diff --git a/frontend/editor/src/core/components/pageTracks/BlankPagePreview.tsx b/frontend/editor/src/core/components/pageTracks/BlankPagePreview.tsx
new file mode 100644
index 0000000000..92b36a2bfa
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/BlankPagePreview.tsx
@@ -0,0 +1,37 @@
+import { CSSProperties } from "react";
+import { useTranslation } from "react-i18next";
+import { BlankTrackPage } from "@app/components/pageTracks/types";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+
+interface BlankPagePreviewProps {
+ page: BlankTrackPage;
+ /** Which box the page is fitted to: a lane tile, or the page-view modal. */
+ placement: "tile" | "view";
+}
+
+/** A blank page drawn at its own proportions and turned like a rendered one. */
+export function BlankPagePreview({ page, placement }: BlankPagePreviewProps) {
+ const { t } = useTranslation();
+ const quarterTurn = page.rotation === 90 || page.rotation === 270;
+ return (
+ <div
+ className={[
+ styles.blankPage,
+ placement === "tile" ? styles.blankInTile : styles.blankInView,
+ quarterTurn ? styles.blankQuarterTurn : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ style={
+ {
+ "--blank-ar": page.width / page.height,
+ transform: `rotate(${page.rotation}deg)`,
+ } as CSSProperties
+ }
+ data-blank-page
+ data-original-rotation={page.rotation}
+ >
+ {t("pageTracks.blankPage", "Blank page")}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/pageTracks/DisabledFileTrack.tsx b/frontend/editor/src/core/components/pageTracks/DisabledFileTrack.tsx
new file mode 100644
index 0000000000..f5621df4ef
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/DisabledFileTrack.tsx
@@ -0,0 +1,71 @@
+import { useDraggable, useDroppable } from "@dnd-kit/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { truncateCenter } from "@app/utils/textUtils";
+import { FileId } from "@app/types/file";
+import {
+ trackHandleId,
+ trackZoneId,
+} from "@app/components/pageTracks/TrackRow";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+
+interface DisabledFileTrackProps {
+ fileId: FileId;
+ name: string;
+ onClose: () => void;
+}
+
+/**
+ * An open file the page editor can't edit (not a PDF). Shown greyed as a
+ * header-only row, like a collapsed track with nothing to expand. It still
+ * joins the track order and can be dragged to reorder (and so reorders the
+ * open files), so every file type sits in one sequence.
+ */
+export function DisabledFileTrack({
+ fileId,
+ name,
+ onClose,
+}: DisabledFileTrackProps) {
+ const { t } = useTranslation();
+ const closeLabel = t("pageTracks.track.close", "Close file");
+ const { listeners, setNodeRef: setHandleRef } = useDraggable({
+ id: trackHandleId(fileId),
+ data: { type: "trackHandle", fileId },
+ });
+ const { setNodeRef: setZoneRef } = useDroppable({
+ id: trackZoneId(fileId),
+ data: { type: "zone", fileId },
+ });
+ return (
+ <section
+ ref={setZoneRef}
+ className={`${styles.track} ${styles.trackDisabled}`}
+ data-track-file-id={fileId}
+ data-unsupported
+ >
+ <header ref={setHandleRef} className={styles.trackHeader} {...listeners}>
+ <span className={styles.trackName}>
+ <PrivateContent>{truncateCenter(name, 40)}</PrivateContent>
+ </span>
+ <div className={styles.trackActions}>
+ <Tooltip position="bottom" content={closeLabel}>
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ accent="danger"
+ aria-label={closeLabel}
+ onClick={onClose}
+ >
+ <Icon name="x" size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ </header>
+ </section>
+ );
+}
+
+export default DisabledFileTrack;
diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.module.css b/frontend/editor/src/core/components/pageTracks/PageTracks.module.css
new file mode 100644
index 0000000000..103f5c68ee
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.module.css
@@ -0,0 +1,580 @@
+.root {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+ position: relative;
+}
+
+.scroller {
+ flex: 1 1 0;
+ min-height: 0;
+ overflow-y: auto;
+}
+
+/* Holds the stack of tracks. Separate from the scroll container so its height
+ tracks the content (the wrap-mode row virtualiser measures each lane's
+ offset within this scrolling content). min-height fills the viewport so a
+ click below the last track still lands here to clear the selection. */
+.scrollerContent {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ padding: var(--space-4);
+ min-height: 100%;
+}
+
+/* ── Track ───────────────────────────────────────────────────────────────── */
+
+.track {
+ position: relative;
+ /* --pt-tile-w / --pt-tile-h / --pt-tile-footer-h / --pt-gap come from
+ constants.ts, so the virtualiser and the CSS agree on tile geometry. */
+ /* The scroller is a flex column: without this, an overflowing stack of
+ tracks squeezes each lane below its tiles and clips them. */
+ flex: 0 0 auto;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--c-surface);
+ overflow: hidden;
+}
+
+.trackDropActive {
+ border-color: var(--c-primary);
+ box-shadow: inset 0 0 0 1px var(--c-primary);
+}
+
+/* An open file the page editor can't edit (not a PDF): greyed so it stays
+ visible but clearly out of scope, like a disabled file in Active Files. */
+.trackDisabled {
+ opacity: 0.55;
+}
+
+.trackDisabled .trackHeader {
+ cursor: default;
+}
+
+.trackHeader {
+ cursor: grab;
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: 0.5rem 0.75rem;
+ border-bottom: 1px solid var(--c-border-subtle);
+ background: var(--c-surface-sunken);
+ min-width: 0;
+}
+
+/* The disclosure chevron: leftmost in the header, never squeezed. */
+.trackCollapse {
+ flex: 0 0 auto;
+}
+
+/* Sits after the page count, so a long filename must not squeeze it. */
+.trackLeadAction {
+ flex: 0 0 auto;
+}
+
+.trackName {
+ font-size: 0.8125rem;
+ font-weight: 600;
+ color: var(--c-text);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ min-width: 0;
+}
+
+.trackMeta {
+ font-size: 0.75rem;
+ color: var(--c-text-muted);
+ white-space: nowrap;
+ flex: 0 0 auto;
+}
+
+.trackActions {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 0.125rem;
+ flex: 0 0 auto;
+}
+
+.lane {
+ position: relative;
+ padding: 0.75rem var(--pt-lane-pad-x);
+ overflow-x: auto;
+ overflow-y: hidden;
+}
+
+/* Wrap mode: pages flow onto as many rows as needed and the lane grows to fit,
+ so it neither scrolls horizontally nor clips. Row virtualisation runs against
+ the outer scroller instead of the lane. */
+.laneWrap {
+ overflow: visible;
+}
+
+/* Sized by the virtualiser; the tiles inside are absolutely placed, so the
+ height has to be stated rather than derived from content. */
+.laneInner {
+ position: relative;
+ height: calc(var(--pt-tile-h) + var(--pt-tile-footer-h));
+}
+
+.laneHint {
+ pointer-events: none;
+}
+
+.laneEmpty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: calc(var(--pt-tile-h) + 2.5rem);
+ color: var(--c-text-subtle);
+ font-size: 0.8125rem;
+}
+
+/* ── Tile ────────────────────────────────────────────────────────────────── */
+
+/* A transparent wrapper stacking the page over its number. The visible "card"
+ is the thumbnail box, matching Active Files: a page floats on a soft shadow
+ rather than sitting in a bordered container. */
+.tile {
+ position: absolute;
+ top: 0;
+ width: var(--pt-tile-w);
+ display: flex;
+ flex-direction: column;
+ cursor: grab;
+ user-select: none;
+ --pt-selection-ring:
+ 0 0 0 2px var(--c-primary),
+ 0 0 0 5px color-mix(in srgb, var(--c-primary) 22%, transparent);
+}
+
+.tileDragging {
+ opacity: 0.35;
+}
+
+/* A transparent, fixed-size centring area (so rows stay virtualisable). The
+ card look lives on the page itself, not this box, so the shadow hugs the
+ actual page and rotates with it instead of showing a fixed rectangle around
+ a turned page. Lifts the page on hover. */
+.thumbBox {
+ position: relative;
+ height: var(--pt-tile-h);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: transform 0.2s ease;
+}
+
+.thumbBox:hover {
+ transform: translateY(-1px);
+}
+
+.pageShadow {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ filter: drop-shadow(var(--shadow-md));
+ transition: filter 0.15s ease;
+ /* Decorative only: clicks fall through to the tile (selection, drag) and the
+ hover controls layered over the page, the way the bare image used to. */
+ pointer-events: none;
+}
+
+.thumbBox:hover .pageShadow {
+ filter: drop-shadow(var(--shadow-lg));
+}
+
+/* The page carries the floating-card look: rounded, no border. */
+.thumb {
+ width: auto;
+ height: auto;
+ max-width: 100%;
+ max-height: 100%;
+ border-radius: 0.375rem;
+ background: var(--c-surface);
+ transition: transform 0.2s ease-in-out;
+}
+
+/* Selection reads as a ring hugging the page, not an outlined tile. A uniform
+ ring looks the same turned or not, so it rides the rotating image to hug the
+ page tightly. The hover rule outranks a plain .tileSelected selector (its
+ :hover counts as a class), so the ring is re-asserted for the hovered case. */
+.tileSelected .thumb,
+.tileSelected .thumbPending {
+ box-shadow: var(--pt-selection-ring);
+}
+
+.tileSelected .thumbBox:hover .thumb,
+.tileSelected .thumbBox:hover .thumbPending {
+ box-shadow: var(--pt-selection-ring);
+}
+
+/*
+ * A quarter turn is applied after layout, so the pre-rotation box has to be
+ * constrained by the OPPOSITE axis or the rotated page overflows and clips.
+ */
+.thumbQuarterTurn {
+ max-width: var(--pt-tile-h);
+ max-height: var(--pt-tile-w);
+}
+
+.thumbPending {
+ width: 60%;
+ height: 78%;
+ border-radius: 0.375rem;
+ background: var(--c-hover);
+}
+
+/* Clicks land on the stable box around the page instead: the placeholder is
+ swapped for the image as the thumbnail arrives, and WebKit drops a click
+ whose pressed element has been replaced by the time the button comes up. */
+.thumb,
+.thumbPending {
+ pointer-events: none;
+}
+
+/*
+ * A blank page, fitted to its box at its own proportions: whichever of width
+ * or height binds first. A quarter turn is applied after layout, so it fits
+ * the pre-rotation box to the opposite axes, like .thumbQuarterTurn.
+ */
+.blankPage {
+ width: min(var(--blank-bw), calc(var(--blank-bh) * var(--blank-ar)));
+ height: min(var(--blank-bh), calc(var(--blank-bw) / var(--blank-ar)));
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 0.375rem;
+ background: var(--c-surface);
+ color: var(--c-text-subtle);
+ font-size: calc(0.75rem * var(--pt-zoom, 1));
+ transition: transform 0.2s ease-in-out;
+}
+
+.blankInTile {
+ --blank-bw: var(--pt-tile-w);
+ --blank-bh: var(--pt-tile-h);
+}
+
+.blankInTile.blankQuarterTurn {
+ --blank-bw: var(--pt-tile-h);
+ --blank-bh: var(--pt-tile-w);
+}
+
+.blankInView {
+ --blank-bw: 80vw;
+ --blank-bh: 82vh;
+}
+
+.blankInView.blankQuarterTurn {
+ --blank-bw: 82vh;
+ --blank-bh: 80vw;
+}
+
+.tileSelected .blankPage {
+ box-shadow: var(--pt-selection-ring);
+}
+
+.tileSelected .thumbBox:hover .blankPage {
+ box-shadow: var(--pt-selection-ring);
+}
+
+/* Just the page number as plain centred text below the page, scaled with zoom. */
+.pageNumber {
+ height: var(--pt-tile-footer-h);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: calc(0.75rem * var(--pt-zoom, 1));
+ color: var(--c-text-muted);
+ font-variant-numeric: tabular-nums;
+}
+
+/* Kept out of the way until the tile is hovered or already selected: a
+ permanent checkbox over every page reads as noise at this density. */
+.tileCheckbox {
+ position: absolute;
+ top: 0.25rem;
+ left: 0.25rem;
+ z-index: 2;
+ display: flex;
+ padding: 0.125rem;
+ border-radius: var(--radius-sm);
+ background: var(--c-surface);
+ box-shadow: 0 1px 3px rgb(0 0 0 / 25%);
+ opacity: 0;
+ transition: opacity 0.12s ease;
+}
+
+.tile:hover .tileCheckbox,
+.tile:focus-within .tileCheckbox,
+.tileSelected .tileCheckbox {
+ opacity: 1;
+}
+
+/* Move-one-place chips, halfway down each side and scaled with the page. */
+.shiftButton {
+ position: absolute;
+ top: 50%;
+ z-index: 2;
+ display: flex;
+ border-radius: 999px;
+ background: var(--c-surface);
+ box-shadow: var(--shadow-sm);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.12s ease;
+}
+
+.shiftLeft {
+ left: 0;
+ transform: translateY(-50%) scale(var(--pt-zoom, 1));
+ transform-origin: left center;
+}
+
+.shiftRight {
+ right: 0;
+ transform: translateY(-50%) scale(var(--pt-zoom, 1));
+ transform-origin: right center;
+}
+
+.tile:hover .shiftButton,
+.tile:focus-within .shiftButton,
+.shiftButton[data-force-visible="true"] {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+/* The controls in a gap between pages. A lane-level element (not attached to
+ a tile), placed by inline left/top/width so it covers the GAP: the same line
+ the drag insertion marker uses, with the gap's actions stacked on it.
+ Revealed by hovering or focusing the gap. */
+.gapHandle {
+ position: absolute;
+ z-index: 5;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: calc(0.375rem * var(--pt-zoom, 1));
+ opacity: 0;
+ transition: opacity 0.12s ease;
+}
+
+.gapHandle::before {
+ content: "";
+ position: absolute;
+ left: 50%;
+ transform: translateX(-50%);
+ top: 0;
+ bottom: 0;
+ width: 2px;
+ border-radius: 999px;
+ background: var(--c-primary);
+}
+
+.gapHandle:hover,
+.gapHandle:focus-within {
+ opacity: 1;
+}
+
+.gapAction {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: calc(1.5rem * var(--pt-zoom, 1));
+ height: calc(1.5rem * var(--pt-zoom, 1));
+ padding: 0;
+ border: 1px solid var(--c-primary);
+ border-radius: 999px;
+ background: var(--c-surface);
+ color: var(--c-primary);
+ box-shadow: var(--shadow-sm);
+ font-size: calc(0.875rem * var(--pt-zoom, 1));
+ cursor: pointer;
+}
+
+.gapAction:hover,
+.gapAction:focus-visible {
+ background: var(--c-primary);
+ color: var(--c-text-on-primary);
+}
+
+/*
+ * Compacted from the shared pill's defaults: the same component carries up to
+ * six actions on a 20rem file card, and three at that scale would overflow a
+ * page tile a third of the width.
+ *
+ * Scaled by --pt-zoom (the compound selector outranks the shared .hoverMenu's
+ * own transform, which centres it) so the controls keep their proportion to the
+ * tile at every zoom instead of swamping a shrunken page. Anchored bottom-centre
+ * so it stays put over the page while it scales.
+ */
+.tile .pagePill {
+ gap: 0.25rem;
+ padding: 0.25rem 0.5rem;
+ z-index: 2;
+ transform: translateX(-50%) scale(var(--pt-zoom, 1));
+ transform-origin: center bottom;
+}
+
+/* CSS-hover driven visibility, matching the file cards in Active Files. */
+.tile [data-hover-action-menu-mode="cssHover"][data-force-visible="false"] {
+ opacity: 0;
+ pointer-events: none;
+}
+
+.tile:hover
+ [data-hover-action-menu-mode="cssHover"][data-force-visible="false"],
+.tile:focus-within
+ [data-hover-action-menu-mode="cssHover"][data-force-visible="false"] {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+/* ── Page view modal ─────────────────────────────────────────────────────── */
+
+.pageViewBody {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+/* Previous/next buttons flanking the page; fixed so the page gets the space. */
+.pageViewNav {
+ flex: 0 0 auto;
+}
+
+.pageViewStage {
+ flex: 1 1 auto;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 12rem;
+ min-height: 12rem;
+}
+
+/* Fills most of the screen; the quarter-turn variant swaps the caps so a
+ rotated (landscape) page still fits within the viewport after the CSS turn. */
+.pageViewImage {
+ max-width: 80vw;
+ max-height: 82vh;
+ object-fit: contain;
+ border-radius: 0.375rem;
+ background: var(--c-surface);
+ box-shadow: var(--shadow-md);
+}
+
+.pageViewQuarter {
+ max-width: 82vh;
+ max-height: 80vw;
+}
+
+/* ── Unsaved-changes marker on the save button ───────────────────────────── */
+
+.saveButton {
+ position: relative;
+}
+
+.unsavedDot {
+ position: absolute;
+ top: 0.125rem;
+ right: 0.125rem;
+ width: 0.4375rem;
+ height: 0.4375rem;
+ border-radius: 999px;
+ background: var(--c-danger);
+ /* Ringed in the bar's own surface so it reads against the icon behind it. */
+ box-shadow: 0 0 0 1.5px var(--c-bg-raised);
+ pointer-events: none;
+}
+
+/* ── Track reorder ───────────────────────────────────────────────────────── */
+
+.trackDragging {
+ opacity: 0.4;
+}
+
+/* A non-clipping wrapper so the reorder marker can sit in the gap between
+ tracks: .track itself clips its overflow to round the lane's corners, which
+ would hide a marker drawn outside its edge. */
+.trackSlot {
+ position: relative;
+ flex: 0 0 auto;
+}
+
+/* The reorder marker, centred in the flex gap between tracks (half a gap above
+ for "before", below for "after the last"), like the page marker in its gap. */
+.trackDropBefore::before,
+.trackDropAfterLast::after {
+ content: "";
+ position: absolute;
+ left: 0;
+ right: 0;
+ height: 3px;
+ border-radius: 999px;
+ background: var(--c-primary);
+ pointer-events: none;
+ z-index: 3;
+}
+
+.trackDropBefore::before {
+ top: calc(var(--space-3) / -2);
+}
+
+.trackDropAfterLast::after {
+ bottom: calc(var(--space-3) / -2);
+}
+
+/* ── Drop indicator ──────────────────────────────────────────────────────── */
+
+/*
+ * Drawn on the tile it inserts against, not as a flex item of its own: a real
+ * element in the lane adds another `gap`, shifting every tile to its right by
+ * 8px — including the tile whose midpoint decides which side to drop on.
+ */
+.dropBefore::before,
+.dropAfterLast::after {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 2px;
+ border-radius: 999px;
+ background: var(--c-primary);
+ pointer-events: none;
+}
+
+/* Centred in the gap (half a gap outside the tile edge), so it lines up with
+ the insert/split controls that sit between the same two pages. --pt-col-gap
+ is the real inter-column gap, which widens in wrap mode; it falls back to the
+ plain gap before the lane has measured itself. */
+.dropBefore::before {
+ left: calc(var(--pt-col-gap, var(--pt-gap)) / -2);
+}
+
+.dropAfterLast::after {
+ right: calc(var(--pt-col-gap, var(--pt-gap)) / -2);
+}
+
+.dragBadge {
+ display: flex;
+ align-items: center;
+ gap: 0.375rem;
+ padding: 0.25rem 0.5rem;
+ border-radius: var(--radius-sm);
+ background: var(--c-primary);
+ color: var(--c-text-on-primary);
+ font-size: 0.75rem;
+ font-weight: 600;
+ box-shadow: 0 6px 16px rgb(0 0 0 / 25%);
+}
diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
new file mode 100644
index 0000000000..7ca7de5da7
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
@@ -0,0 +1,1119 @@
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { Center, Loader, LoadingOverlay, Stack, Text } from "@mantine/core";
+import {
+ CollisionDetection,
+ DndContext,
+ DragEndEvent,
+ DragMoveEvent,
+ DragOverlay,
+ DragStartEvent,
+ PointerSensor,
+ closestCenter,
+ pointerWithin,
+ rectIntersection,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { useFileActions, useFileState } from "@app/contexts/FileContext";
+import {
+ useNavigationActions,
+ useNavigationGuard,
+} from "@app/contexts/NavigationContext";
+import { useViewer } from "@app/contexts/ViewerContext";
+import { useWheelZoom } from "@app/hooks/useWheelZoom";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { truncateCenter } from "@app/utils/textUtils";
+import { FileId } from "@app/types/file";
+import { WorkbenchExportFile } from "@app/types/workbenchBar";
+import { useWorkbenchViewFileActions } from "@app/hooks/useWorkbenchViewFileActions";
+import { CloseFilesConfirmModal } from "@app/components/shared/CloseFilesConfirmModal";
+import { alert } from "@app/components/toast";
+import {
+ PolicyBlockedError,
+ assertFilesNotBlocked,
+} from "@app/services/policyFileGuard";
+import {
+ buildTrackFile,
+ policyIdsForTracks,
+} from "@app/components/pageTracks/buildTrackFile";
+import { tracksEntangledWith } from "@app/components/pageTracks/trackWorkspaceReducer";
+import { useTrackWorkspace } from "@app/components/pageTracks/hooks/useTrackWorkspace";
+import { useTrackSelection } from "@app/components/pageTracks/hooks/useTrackSelection";
+import { useTrackThumbnails } from "@app/components/pageTracks/hooks/useTrackThumbnails";
+import { useTrackSave } from "@app/components/pageTracks/hooks/useTrackSave";
+import { usePageTracksWorkbenchBarButtons } from "@app/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons";
+import { totalPageCount } from "@app/components/pageTracks/types";
+import TrackRow, { DropHint } from "@app/components/pageTracks/TrackRow";
+import { DisabledFileTrack } from "@app/components/pageTracks/DisabledFileTrack";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+
+const PAGE_PREFIX = "page:";
+const TRACK_PREFIX = "track:";
+const ZONE_PREFIX = "zone:";
+const HANDLE_PREFIX = "trackhandle:";
+
+const isPdfName = (name: string | undefined): boolean =>
+ name?.toLowerCase().endsWith(".pdf") ?? false;
+
+const ZOOM_MIN = 0.5;
+const ZOOM_MAX = 3.0;
+const ZOOM_STEP = 0.1;
+// Rounded each step so repeated +/- 0.1 doesn't drift off the bounds.
+const clampZoom = (value: number): number =>
+ Math.round(Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, value)) * 10) / 10;
+
+/**
+ * Droppables nest (zone > lane > page), so the hit has to be picked by what is
+ * being dragged: a track header only ever lands on a whole track, while a page
+ * prefers the tile under the pointer and falls back to the track around it.
+ */
+const collisionDetection: CollisionDetection = (args) => {
+ const within = pointerWithin(args);
+ const first = (prefix: string) =>
+ within.find((c) => String(c.id).startsWith(prefix));
+
+ if (args.active.data.current?.type === "trackHandle") {
+ const zone = first(ZONE_PREFIX);
+ if (zone) return [zone];
+ // In the gap between tracks (or past either end) no zone is under the
+ // pointer, so fall back to the nearest track by centre: resolveTrackHint
+ // then reads the pointer's side of it to insert before or after.
+ const zones = args.droppableContainers.filter((c) =>
+ String(c.id).startsWith(ZONE_PREFIX),
+ );
+ return closestCenter({ ...args, droppableContainers: zones });
+ }
+
+ const page = first(PAGE_PREFIX);
+ if (page) return [page];
+ const lane = first(TRACK_PREFIX);
+ if (lane) return [lane];
+ const zone = first(ZONE_PREFIX);
+ if (zone) return [zone];
+ return rectIntersection(args);
+};
+
+const sameHint = (a: DropHint | null, b: DropHint | null): boolean =>
+ a === b ||
+ (a != null &&
+ b != null &&
+ a.fileId === b.fileId &&
+ a.beforePageId === b.beforePageId);
+
+/**
+ * The pointer x dnd-kit is itself working from: the activator's position plus
+ * the drag delta. Using this rather than a live pointermove listener keeps the
+ * side-of-tile decision consistent with the reported collision.
+ */
+function pointerYOf(event: DragMoveEvent | DragEndEvent): number {
+ const activator = event.activatorEvent;
+ const originY =
+ activator instanceof MouseEvent
+ ? activator.clientY
+ : activator instanceof TouchEvent && activator.touches.length > 0
+ ? activator.touches[0].clientY
+ : 0;
+ return originY + event.delta.y;
+}
+
+function pointerXOf(event: DragMoveEvent | DragEndEvent): number {
+ const activator = event.activatorEvent;
+ const originX =
+ activator instanceof MouseEvent
+ ? activator.clientX
+ : activator instanceof TouchEvent && activator.touches.length > 0
+ ? activator.touches[0].clientX
+ : 0;
+ return originX + event.delta.x;
+}
+
+export default function PageTracks() {
+ const { t } = useTranslation();
+ const { state: fileState, selectors: fileSelectors } = useFileState();
+ const { actions: fileActions } = useFileActions();
+ const {
+ state,
+ dispatch,
+ pendingFileIds,
+ unsupportedFileIds,
+ hasPdfFiles,
+ changedFileIds,
+ isDirty,
+ canUndo,
+ canRedo,
+ } = useTrackWorkspace();
+ const workspace = state.present;
+
+ const selection = useTrackSelection(workspace);
+ const thumbnails = useTrackThumbnails();
+ const { actions: navActions } = useNavigationActions();
+ const { setActiveFileId } = useViewer();
+
+ // The file the user asked to view, held across a save: committing gives it a
+ // new id, and the viewer drops an active file that has left the workbench.
+ const viewTargetRef = useRef<FileId | null>(null);
+ const handleVersioned = useCallback(
+ (previousId: FileId, nextId: FileId) => {
+ if (viewTargetRef.current !== previousId) return;
+ viewTargetRef.current = nextId;
+ setActiveFileId(nextId);
+ },
+ [setActiveFileId],
+ );
+
+ // A saved split's new file is appended to the open-file list; this moves it
+ // back beside its source once it has landed in file state (see the effect).
+ const [pendingSplitPlacements, setPendingSplitPlacements] = useState<
+ { fileId: FileId; afterFileId: FileId | null }[]
+ >([]);
+
+ const { saving, progress, save } = useTrackSave(workspace, changedFileIds, {
+ onVersioned: handleVersioned,
+ onMaterialized: ({ dropTrackIds, order, placements }) => {
+ dispatch({ type: "reconcileAfterSave", dropTrackIds, order });
+ if (placements.length > 0) setPendingSplitPlacements(placements);
+ },
+ });
+
+ useEffect(() => {
+ if (pendingSplitPlacements.length === 0) return;
+ const byId = fileState.files.byId;
+ // Wait until every new split file is actually in the list before moving it.
+ if (!pendingSplitPlacements.every((p) => byId[p.fileId])) return;
+
+ let order = fileState.files.ids;
+ for (const { fileId, afterFileId } of pendingSplitPlacements) {
+ const without = order.filter((id) => id !== fileId);
+ const at = afterFileId == null ? -1 : without.indexOf(afterFileId);
+ order =
+ at === -1
+ ? [...without, fileId]
+ : [...without.slice(0, at + 1), fileId, ...without.slice(at + 1)];
+ }
+ setPendingSplitPlacements([]);
+ if (!order.every((id, i) => fileState.files.ids[i] === id))
+ fileActions.reorderFiles(order);
+ }, [pendingSplitPlacements, fileState.files, fileActions]);
+
+ /**
+ * Opens one track's file in the Viewer. Routed through setWorkbench so the
+ * unsaved-changes prompt still fires: viewing a file whose pending edits
+ * haven't been written would show stale pages.
+ */
+ const openInViewer = useCallback(
+ (fileId: FileId) => {
+ viewTargetRef.current = fileId;
+ setActiveFileId(fileId);
+ navActions.setWorkbench("viewer");
+ },
+ [navActions, setActiveFileId],
+ );
+
+ const [draggingIds, setDraggingIds] = useState<Set<string>>(
+ () => new Set<string>(),
+ );
+ const [dropHint, setDropHint] = useState<DropHint | null>(null);
+ const [draggingTrack, setDraggingTrack] = useState<FileId | null>(null);
+ // undefined = no target, null = append to the end.
+ const [trackDropTarget, setTrackDropTarget] = useState<
+ FileId | null | undefined
+ >(undefined);
+
+ // Off = one horizontally scrolling row per track (virtualised along its
+ // lane). On = pages wrap onto as many rows as fit and each track grows as
+ // tall as it needs, with the rows virtualised against the outer scroller.
+ const [wrap, setWrap] = useState<boolean>(
+ () =>
+ fileState.files.ids.filter((id) =>
+ isPdfName(fileState.files.byId[id]?.name),
+ ).length === 1,
+ );
+ const toggleWrap = useCallback(() => setWrap((prev) => !prev), []);
+
+ // Scales the page tiles only: the tracks, headers and bar keep their size.
+ const [zoom, setZoom] = useState(1);
+ const zoomIn = useCallback(
+ () => setZoom((z) => clampZoom(z + ZOOM_STEP)),
+ [],
+ );
+ const zoomOut = useCallback(
+ () => setZoom((z) => clampZoom(z - ZOOM_STEP)),
+ [],
+ );
+
+ // The scrolling container each wrap-mode lane virtualises its rows against.
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const contentRef = useRef<HTMLDivElement | null>(null);
+ // Bumped whenever the stacked height of the tracks changes, so every lane
+ // re-measures its offset within the scroller: one track growing shifts the
+ // ones below it, and their row positions depend on that offset.
+ const [layoutVersion, setLayoutVersion] = useState(0);
+
+ useEffect(() => {
+ const content = contentRef.current;
+ if (!content || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(() => {
+ setLayoutVersion((version) => version + 1);
+ });
+ observer.observe(content);
+ return () => observer.disconnect();
+ }, []);
+
+ // Ctrl/Cmd + wheel zooms, matching the Multi-Tool page editor.
+ useWheelZoom({ ref: scrollerRef, onZoomIn: zoomIn, onZoomOut: zoomOut });
+
+ // Ctrl/Cmd + '+' / '-' zoom, '0' resets. Matches the Multi-Tool shortcuts.
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (!(event.ctrlKey || event.metaKey)) return;
+ const target = event.target as HTMLElement | null;
+ if (
+ target?.tagName === "INPUT" ||
+ target?.tagName === "TEXTAREA" ||
+ target?.isContentEditable
+ ) {
+ return;
+ }
+ if (event.key === "=" || event.key === "+") {
+ event.preventDefault();
+ zoomIn();
+ } else if (event.key === "-" || event.key === "_") {
+ event.preventDefault();
+ zoomOut();
+ } else if (event.key === "0") {
+ event.preventDefault();
+ setZoom(1);
+ }
+ };
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [zoomIn, zoomOut]);
+
+ const totalPages = useMemo(() => totalPageCount(workspace), [workspace]);
+ const changedSet = useMemo(() => new Set(changedFileIds), [changedFileIds]);
+ // Page numbers are per track: "3" means the third page of each track.
+ const numberedPages = useMemo(
+ () =>
+ workspace.order.flatMap((id) =>
+ (workspace.tracks[id]?.pages ?? []).map((page, index) => ({
+ id: page.id,
+ pageNumber: index + 1,
+ })),
+ ),
+ [workspace],
+ );
+ const longestTrack = useMemo(
+ () =>
+ Math.max(
+ 0,
+ ...workspace.order.map((id) => workspace.tracks[id]?.pages.length ?? 0),
+ ),
+ [workspace],
+ );
+ const selectedPageIds = useMemo(
+ () => [...selection.selectedIds],
+ [selection.selectedIds],
+ );
+ const { setSelection, selectedIds } = selection;
+ const selectNumbersEverywhere = useCallback(
+ (pageNumbers: number[]) => {
+ const wanted = new Set(pageNumbers);
+ setSelection(
+ numberedPages
+ .filter((page) => wanted.has(page.pageNumber))
+ .map((page) => page.id),
+ );
+ },
+ [numberedPages, setSelection],
+ );
+ const selectNumbersInTrack = useCallback(
+ (fileId: FileId, pageNumbers: number[]) => {
+ const pages = workspace.tracks[fileId]?.pages ?? [];
+ const inTrack = new Set(pages.map((page) => page.id));
+ const chosen = pageNumbers
+ .map((number) => pages[number - 1]?.id)
+ .filter((id): id is string => id != null);
+ setSelection([
+ ...[...selectedIds].filter((id) => !inTrack.has(id)),
+ ...chosen,
+ ]);
+ },
+ [selectedIds, setSelection, workspace],
+ );
+ const numberSelection = useMemo(
+ () => ({
+ pages: numberedPages,
+ maxPages: longestTrack,
+ selectedPageIds,
+ onSelect: selectNumbersEverywhere,
+ }),
+ [numberedPages, longestTrack, selectedPageIds, selectNumbersEverywhere],
+ );
+
+ const insertBlank = useCallback(
+ (fileId: FileId, beforePageId: string | null) =>
+ dispatch({ type: "insertBlank", fileId, beforePageId }),
+ [dispatch],
+ );
+
+ const shiftPage = useCallback(
+ (pageId: string, by: -1 | 1) => dispatch({ type: "shiftPage", pageId, by }),
+ [dispatch],
+ );
+
+ const rotatePages = useCallback(
+ (pageIds: string[], delta: number) =>
+ dispatch({ type: "rotate", pageIds, delta }),
+ [dispatch],
+ );
+
+ const deletePages = useCallback(
+ (pageIds: string[]) => dispatch({ type: "delete", pageIds }),
+ [dispatch],
+ );
+
+ const rotateSelection = useCallback(
+ (delta: number) => rotatePages(Array.from(selection.selectedIds), delta),
+ [rotatePages, selection.selectedIds],
+ );
+
+ const deleteSelection = useCallback(
+ () => deletePages(Array.from(selection.selectedIds)),
+ [deletePages, selection.selectedIds],
+ );
+
+ const insertBlankAfterSelection = useCallback(
+ () =>
+ dispatch({
+ type: "insertBlankAfter",
+ pageIds: Array.from(selection.selectedIds),
+ }),
+ [dispatch, selection.selectedIds],
+ );
+
+ const splitAfterSelection = useCallback(
+ () =>
+ dispatch({
+ type: "splitAfterSelected",
+ pageIds: Array.from(selection.selectedIds),
+ }),
+ [dispatch, selection.selectedIds],
+ );
+
+ const clearSelection = selection.clear;
+ const toggleSelectAll =
+ totalPages > 0 && selection.selectedCount === totalPages
+ ? selection.clear
+ : selection.selectAll;
+
+ /**
+ * Moves one track before `beforeFileId` (or to the end when null). The
+ * workspace order is authoritative (a split adds a track with no file), so
+ * this reorders the workspace rather than the workbench file list.
+ */
+ // Track order follows the open-file list, so reordering a track reorders the
+ // files (and so Active Files) and lands all file types in one sequence. A
+ // split pins to its source, so it is not independently reorderable.
+ const reorderTracks = useCallback(
+ (sourceFileId: FileId, beforeFileId: FileId | null) => {
+ if (sourceFileId === beforeFileId) return;
+ if (workspace.tracks[sourceFileId]?.isNew) return;
+ const fileIds = fileState.files.ids;
+ if (!fileIds.includes(sourceFileId)) return;
+
+ const without = fileIds.filter((id) => id !== sourceFileId);
+ const at =
+ beforeFileId == null ? without.length : without.indexOf(beforeFileId);
+ const insertAt = at === -1 ? without.length : at;
+ const newOrder = [
+ ...without.slice(0, insertAt),
+ sourceFileId,
+ ...without.slice(insertAt),
+ ];
+ if (newOrder.every((id, i) => fileIds[i] === id)) return;
+ fileActions.reorderFiles(newOrder);
+
+ // Keep the workspace's own track sequence aligned with the files so page
+ // moves and splits read the same order, without clearing pending edits.
+ const srcIdx = newOrder.indexOf(sourceFileId);
+ const beforeTrackId =
+ newOrder
+ .slice(srcIdx + 1)
+ .find((id) => workspace.tracks[id] && !workspace.tracks[id]?.isNew) ??
+ null;
+ if (workspace.tracks[sourceFileId]) {
+ dispatch({
+ type: "reorderTrack",
+ sourceId: sourceFileId,
+ beforeId: beforeTrackId,
+ });
+ }
+ },
+ [dispatch, fileActions, fileState.files.ids, workspace],
+ );
+
+ const splitTrack = useCallback(
+ (fileId: FileId, startPageId: string) =>
+ dispatch({ type: "split", fileId, startPageId }),
+ [dispatch],
+ );
+
+ const sensors = useSensors(
+ // A short distance threshold keeps plain clicks (select) from starting a drag.
+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
+ );
+
+ // Rebuilt per edit rather than scanned per drag-over event: resolving the
+ // hovered page by walking every track is O(pages) on every pointer move.
+ const trackByPageId = useMemo(() => {
+ const map = new Map<string, FileId>();
+ workspace.order.forEach((fileId) => {
+ workspace.tracks[fileId]?.pages.forEach((page) =>
+ map.set(page.id, fileId),
+ );
+ });
+ return map;
+ }, [workspace]);
+
+ // The rows to render, in open-file order: each PDF file's track (followed by
+ // any splits made from it), each loading PDF, and each non-PDF as a disabled
+ // track. One sequence shared by the view and the track-reorder drag.
+ const displayRows = useMemo(() => {
+ const splitsByParent = new Map<FileId, FileId[]>();
+ for (const id of workspace.order) {
+ const track = workspace.tracks[id];
+ if (track?.isNew && track.splitFromFileId) {
+ const siblings = splitsByParent.get(track.splitFromFileId) ?? [];
+ siblings.push(id);
+ splitsByParent.set(track.splitFromFileId, siblings);
+ }
+ }
+ const pending = new Set(pendingFileIds);
+ const unsupported = new Set(unsupportedFileIds);
+ const rows: {
+ kind: "track" | "split" | "pending" | "disabled";
+ id: FileId;
+ }[] = [];
+ const placed = new Set<FileId>();
+ const place = (kind: (typeof rows)[number]["kind"], id: FileId) => {
+ rows.push({ kind, id });
+ placed.add(id);
+ };
+ for (const fileId of fileState.files.ids) {
+ const track = workspace.tracks[fileId];
+ if (track && !track.isNew) {
+ place("track", fileId);
+ for (const splitId of splitsByParent.get(fileId) ?? [])
+ place("split", splitId);
+ } else if (pending.has(fileId)) {
+ place("pending", fileId);
+ } else if (unsupported.has(fileId)) {
+ place("disabled", fileId);
+ }
+ }
+ // A split whose source has closed still holds savable pages: keep it.
+ for (const id of workspace.order)
+ if (!placed.has(id) && workspace.tracks[id]) place("split", id);
+ return rows;
+ }, [fileState.files.ids, workspace, pendingFileIds, unsupportedFileIds]);
+
+ const lastReorderableId = useMemo(() => {
+ for (let i = displayRows.length - 1; i >= 0; i--)
+ if (displayRows[i].kind !== "split") return displayRows[i].id;
+ return null;
+ }, [displayRows]);
+
+ /**
+ * Resolves the pointer position to "insert before this page". An anchor that
+ * is itself being dragged is fine: the reducer skips past the moved pages.
+ */
+ const resolveHint = useCallback(
+ (
+ overId: string | null,
+ pointerX: number,
+ pointerY: number,
+ ): DropHint | null => {
+ if (!overId) return null;
+
+ // Over a page: insert on whichever side of it the pointer is on.
+ if (overId.startsWith(PAGE_PREFIX)) {
+ const overPageId = overId.slice(PAGE_PREFIX.length);
+ const fileId = trackByPageId.get(overPageId);
+ if (!fileId) return null;
+ const pages = workspace.tracks[fileId]?.pages ?? [];
+ const overIndex = pages.findIndex((page) => page.id === overPageId);
+ if (overIndex === -1) return null;
+ const rect = document
+ .querySelector<HTMLElement>(`[data-page-id="${overPageId}"]`)
+ ?.getBoundingClientRect();
+ const dropAfter = rect ? pointerX > rect.left + rect.width / 2 : false;
+ return {
+ fileId,
+ beforePageId:
+ pages[dropAfter ? overIndex + 1 : overIndex]?.id ?? null,
+ };
+ }
+
+ // The lane itself (the gaps and empty space): drop into the gap nearest
+ // the pointer rather than jumping to the end, so a page can be dropped
+ // between two pages without hovering one of them exactly.
+ let fileId: FileId | undefined;
+ for (const prefix of [TRACK_PREFIX, ZONE_PREFIX])
+ if (overId.startsWith(prefix))
+ fileId = overId.slice(prefix.length) as FileId;
+ if (!fileId) return null;
+ const track = workspace.tracks[fileId];
+ if (!track) return null;
+ if (track.pages.length === 0) return { fileId, beforePageId: null };
+
+ const tiles = Array.from(
+ document
+ .querySelector<HTMLElement>(`[data-track-lane="${fileId}"]`)
+ ?.querySelectorAll<HTMLElement>("[data-page-id]") ?? [],
+ );
+ const nearest = tiles
+ .flatMap((tile) => {
+ const id = tile.getAttribute("data-page-id");
+ if (id == null) return [];
+ const rect = tile.getBoundingClientRect();
+ const dist = Math.hypot(
+ pointerX - (rect.left + rect.width / 2),
+ pointerY - (rect.top + rect.height / 2),
+ );
+ return [{ id, rect, dist }];
+ })
+ .reduce<{ id: string; rect: DOMRect; dist: number } | null>(
+ (best, candidate) =>
+ best == null || candidate.dist < best.dist ? candidate : best,
+ null,
+ );
+ if (nearest == null) return { fileId, beforePageId: null };
+ const overIndex = track.pages.findIndex((p) => p.id === nearest.id);
+ if (overIndex === -1) return { fileId, beforePageId: null };
+ const dropAfter = pointerX > nearest.rect.left + nearest.rect.width / 2;
+ return {
+ fileId,
+ beforePageId:
+ track.pages[dropAfter ? overIndex + 1 : overIndex]?.id ?? null,
+ };
+ },
+ [trackByPageId, workspace],
+ );
+
+ /**
+ * Track reorder target: insert before this file, or append when null.
+ */
+ const resolveTrackHint = useCallback(
+ (overId: string | null, pointerY: number): FileId | null | undefined => {
+ if (!overId || !overId.startsWith(ZONE_PREFIX)) return undefined;
+ const overFileId = overId.slice(ZONE_PREFIX.length) as FileId;
+ const index = displayRows.findIndex((row) => row.id === overFileId);
+ if (index === -1) return undefined;
+
+ const element = document.querySelector<HTMLElement>(
+ `[data-track-file-id="${overFileId}"]`,
+ );
+ const rect = element?.getBoundingClientRect();
+ const dropAfter = rect ? pointerY > rect.top + rect.height / 2 : false;
+ // Insert before the next reorderable (non-split) row, or append at the end.
+ for (let i = dropAfter ? index + 1 : index; i < displayRows.length; i++)
+ if (displayRows[i].kind !== "split") return displayRows[i].id;
+ return null;
+ },
+ [displayRows],
+ );
+
+ const handleDragStart = useCallback(
+ (event: DragStartEvent) => {
+ const activeId = String(event.active.id);
+ if (activeId.startsWith(HANDLE_PREFIX)) {
+ setDraggingTrack(activeId.slice(HANDLE_PREFIX.length) as FileId);
+ return;
+ }
+ const pageId = activeId.slice(PAGE_PREFIX.length);
+ // Dragging a page that is part of the selection moves the whole
+ // selection; dragging an unselected page moves only that page.
+ const ids = selection.selectedIds.has(pageId)
+ ? Array.from(selection.selectedIds)
+ : [pageId];
+ setDraggingIds(new Set(ids));
+ },
+ [selection.selectedIds],
+ );
+
+ // onDragMove, not onDragOver: which side of a tile the pointer is on changes
+ // WITHOUT the hovered droppable changing, and onDragOver only fires on the
+ // latter. Recomputing per move is what keeps the marker and the drop in sync.
+ const handleDragMove = useCallback(
+ (event: DragMoveEvent) => {
+ if (draggingTrack) {
+ const target = resolveTrackHint(
+ event.over ? String(event.over.id) : null,
+ pointerYOf(event),
+ );
+ setTrackDropTarget(target === undefined ? undefined : target);
+ return;
+ }
+ const next = resolveHint(
+ event.over ? String(event.over.id) : null,
+ pointerXOf(event),
+ pointerYOf(event),
+ );
+ // Most moves land on the same side of the same tile. Keeping the previous
+ // object bails the re-render out, so only a real change costs anything.
+ setDropHint((prev) => (sameHint(prev, next) ? prev : next));
+ },
+ [draggingTrack, resolveHint, resolveTrackHint],
+ );
+
+ const handleDragEnd = useCallback(
+ (event: DragEndEvent) => {
+ if (draggingTrack) {
+ const target = resolveTrackHint(
+ event.over ? String(event.over.id) : null,
+ pointerYOf(event),
+ );
+ const source = draggingTrack;
+ setDraggingTrack(null);
+ setTrackDropTarget(undefined);
+ if (target !== undefined) reorderTracks(source, target);
+ return;
+ }
+
+ const hint = resolveHint(
+ event.over ? String(event.over.id) : null,
+ pointerXOf(event),
+ pointerYOf(event),
+ );
+ setDraggingIds(new Set());
+ setDropHint(null);
+ if (!hint || draggingIds.size === 0) return;
+ dispatch({
+ type: "move",
+ pageIds: Array.from(draggingIds),
+ targetFileId: hint.fileId,
+ beforePageId: hint.beforePageId,
+ });
+ },
+ [
+ dispatch,
+ draggingIds,
+ draggingTrack,
+ reorderTracks,
+ resolveHint,
+ resolveTrackHint,
+ ],
+ );
+
+ const handleDragCancel = useCallback(() => {
+ setDraggingIds(new Set());
+ setDropHint(null);
+ setDraggingTrack(null);
+ setTrackDropTarget(undefined);
+ }, []);
+
+ const {
+ setHasUnsavedChanges,
+ registerNavigationWarningHandlers,
+ unregisterNavigationWarningHandlers,
+ } = useNavigationGuard();
+
+ useEffect(() => {
+ setHasUnsavedChanges(isDirty);
+ }, [isDirty, setHasUnsavedChanges]);
+
+ useEffect(() => {
+ // Only the save route is offered: edits live in memory, so "discard" needs
+ // no handler, and there is no separate export step to leave via.
+ registerNavigationWarningHandlers({
+ onApplyAndContinue: async () => {
+ // The prompt only holds the navigation back on a throw.
+ if (!(await save())) throw new Error("Saving page edits failed");
+ },
+ });
+ return () => unregisterNavigationWarningHandlers();
+ }, [
+ save,
+ registerNavigationWarningHandlers,
+ unregisterNavigationWarningHandlers,
+ ]);
+
+ useEffect(
+ () => () => {
+ setHasUnsavedChanges(false);
+ },
+ [setHasUnsavedChanges],
+ );
+
+ const undo = useCallback(() => dispatch({ type: "undo" }), [dispatch]);
+ const redo = useCallback(() => dispatch({ type: "redo" }), [dispatch]);
+ const saveNow = useCallback(() => {
+ void save();
+ }, [save]);
+
+ // Downloads what the editor shows: an unchanged track is its stored file, an
+ // edited one or a split is rendered from its pages without being saved.
+ const getExportFiles = useCallback(async (): Promise<
+ WorkbenchExportFile[] | null
+ > => {
+ const lookup = {
+ getStub: fileSelectors.getStirlingFileStub,
+ getFile: fileSelectors.getFile,
+ };
+ const trackIds = workspace.order.filter(
+ (id) => (workspace.tracks[id]?.pages.length ?? 0) > 0,
+ );
+ try {
+ assertFilesNotBlocked(
+ policyIdsForTracks(
+ workspace,
+ trackIds.filter((id) => changedSet.has(id)),
+ lookup.getStub,
+ ),
+ );
+ const files: WorkbenchExportFile[] = [];
+ for (const id of trackIds) {
+ const track = workspace.tracks[id];
+ if (!track) continue;
+ if (!changedSet.has(id)) {
+ const file = lookup.getFile(id);
+ if (file) files.push({ file, fileId: id });
+ continue;
+ }
+ const built = await buildTrackFile(track, lookup);
+ if (built) files.push({ file: built.file });
+ }
+ return files;
+ } catch (error) {
+ if (error instanceof PolicyBlockedError) {
+ alert({
+ alertType: "warning",
+ title: t("policy.recoveryTitle"),
+ body: t("policy.recoveryBody"),
+ });
+ } else {
+ console.error("[PageTracks] export failed", error);
+ alert({
+ alertType: "error",
+ title: t("pageTracks.exportFailed.title", "Couldn't download"),
+ body: t(
+ "pageTracks.exportFailed.body",
+ "The edited files couldn't be prepared. Try again.",
+ ),
+ });
+ }
+ return null;
+ }
+ }, [changedSet, fileSelectors, t, workspace]);
+
+ // Closing a file drops every page sourced from it, including ones moved into
+ // other tracks, so its pending edits are those of every track entangled with it.
+ const [closeRequest, setCloseRequest] = useState<FileId | "all" | null>(null);
+ const closeRequestEdits = useMemo(() => {
+ if (closeRequest === null || closeRequest === "all") return changedFileIds;
+ const entangled = tracksEntangledWith(workspace, new Set([closeRequest]));
+ return changedFileIds.filter((id) => entangled.has(id));
+ }, [changedFileIds, closeRequest, workspace]);
+
+ const closeRequested = useCallback(() => {
+ const request = closeRequest;
+ setCloseRequest(null);
+ if (request === "all") {
+ void fileActions.clearAllFiles();
+ return;
+ }
+ if (request === null) return;
+ if (closeRequestEdits.length > 0) {
+ dispatch({ type: "revert", fileIds: [request] });
+ }
+ void fileActions.removeFiles([request], false);
+ }, [closeRequest, closeRequestEdits, dispatch, fileActions]);
+
+ const saveAndCloseRequested = useCallback(async () => {
+ const request = closeRequest;
+ setCloseRequest(null);
+ if (request === null) return;
+ const versioned = await save(
+ request === "all" ? undefined : closeRequestEdits,
+ );
+ if (!versioned) return;
+ if (request === "all") {
+ await fileActions.clearAllFiles();
+ return;
+ }
+ // Saving versions the file under a new id; one that emptied is already closed.
+ const savedId = versioned.get(request);
+ if (savedId) setCloseOnceSaved(savedId);
+ }, [closeRequest, closeRequestEdits, fileActions, save]);
+
+ // The saved version only reaches file state on the next render, and removing
+ // it before then leaves its resources behind.
+ const [closeOnceSaved, setCloseOnceSaved] = useState<FileId | null>(null);
+ useEffect(() => {
+ if (!closeOnceSaved || !fileState.files.byId[closeOnceSaved]) return;
+ setCloseOnceSaved(null);
+ void fileActions.removeFiles([closeOnceSaved], false);
+ }, [closeOnceSaved, fileActions, fileState.files.byId]);
+
+ useWorkbenchViewFileActions(
+ useMemo(
+ () => ({ getExportFiles, onClose: () => setCloseRequest("all") }),
+ [getExportFiles],
+ ),
+ );
+
+ const closingAll = closeRequest === "all";
+ const hasCloseEdits = closeRequestEdits.length > 0;
+ const closeConfirmModal = (
+ <CloseFilesConfirmModal
+ opened={closeRequest !== null}
+ message={
+ hasCloseEdits
+ ? closeRequestEdits.length === 1
+ ? t("confirmCloseUnsaved", "This file has unsaved changes.")
+ : t("pageTracks.close.unsaved", "These files have unsaved changes.")
+ : closingAll
+ ? t(
+ "pageTracks.close.message",
+ "Are you sure you want to close all files?",
+ )
+ : t(
+ "confirmCloseMessage",
+ "Are you sure you want to close this file?",
+ )
+ }
+ files={
+ hasCloseEdits
+ ? closeRequestEdits.map((id) => ({
+ id,
+ name: workspace.tracks[id]?.name ?? id,
+ }))
+ : closingAll || closeRequest === null
+ ? []
+ : [
+ {
+ id: closeRequest,
+ name:
+ workspace.tracks[closeRequest]?.name ??
+ fileState.files.byId[closeRequest]?.name ??
+ closeRequest,
+ },
+ ]
+ }
+ closeLabel={
+ hasCloseEdits
+ ? t("confirmCloseDiscard", "Discard changes and close")
+ : closingAll
+ ? t("workbenchBar.closeAll", "Close All Files")
+ : t("confirmCloseConfirm", "Close File")
+ }
+ onClose={closeRequested}
+ onCancel={() => setCloseRequest(null)}
+ onSave={hasCloseEdits ? () => void saveAndCloseRequested() : undefined}
+ />
+ );
+
+ usePageTracksWorkbenchBarButtons({
+ totalPages,
+ selectedCount: selection.selectedCount,
+ canUndo,
+ canRedo,
+ isDirty,
+ saving,
+ wrap,
+ onToggleWrap: toggleWrap,
+ canZoomIn: zoom < ZOOM_MAX,
+ canZoomOut: zoom > ZOOM_MIN,
+ onZoomIn: zoomIn,
+ onZoomOut: zoomOut,
+ onToggleSelectAll: toggleSelectAll,
+ numberSelection,
+ onRotate: rotateSelection,
+ onDelete: deleteSelection,
+ onInsertBlankAfter: insertBlankAfterSelection,
+ onSplitAfter: splitAfterSelection,
+ onUndo: undo,
+ onRedo: redo,
+ onSave: saveNow,
+ });
+
+ const renderTrackRow = (fileId: FileId) => {
+ const track = workspace.tracks[fileId];
+ if (!track) return null;
+ const stub = fileState.files.byId[fileId];
+ return (
+ <TrackRow
+ track={track}
+ name={track.name}
+ isNew={track.isNew}
+ versionNumber={stub?.versionNumber}
+ selectedIds={selection.selectedIds}
+ draggingIds={draggingIds}
+ dropHint={dropHint}
+ wrap={wrap}
+ zoom={zoom}
+ scrollerRef={scrollerRef}
+ layoutVersion={layoutVersion}
+ trackDragging={draggingTrack === fileId}
+ changed={changedSet.has(fileId)}
+ thumbnails={thumbnails}
+ onSelectPage={selection.selectPage}
+ onSelectTrack={selection.selectTrack}
+ onSelectNumbers={selectNumbersInTrack}
+ onOpenInViewer={openInViewer}
+ onClearSelection={clearSelection}
+ onSplit={splitTrack}
+ onInsertBlank={insertBlank}
+ onRotate={rotatePages}
+ onDelete={deletePages}
+ onShiftPage={shiftPage}
+ onClose={setCloseRequest}
+ />
+ );
+ };
+
+ if (!hasPdfFiles && unsupportedFileIds.length === 0) {
+ return (
+ <Center h="100%">
+ {closeConfirmModal}
+ <Stack align="center" gap="xs">
+ <Text c="dimmed">
+ {t("pageTracks.empty.title", "No PDF files loaded")}
+ </Text>
+ <Text size="sm" c="dimmed">
+ {t(
+ "pageTracks.empty.body",
+ "Add PDFs to expand them into editable page tracks",
+ )}
+ </Text>
+ </Stack>
+ </Center>
+ );
+ }
+
+ return (
+ <div className={styles.root} data-testid="page-tracks">
+ {closeConfirmModal}
+ <LoadingOverlay
+ visible={saving}
+ loaderProps={{
+ children: (
+ <Stack align="center" gap="xs">
+ <Loader />
+ <Text size="sm">
+ {progress
+ ? t(
+ "pageTracks.savingProgress",
+ "Saving {{done}} of {{total}}",
+ {
+ done: progress.done,
+ total: progress.total,
+ },
+ )
+ : t("pageTracks.saving", "Saving...")}
+ </Text>
+ </Stack>
+ ),
+ }}
+ />
+
+ <DndContext
+ sensors={sensors}
+ collisionDetection={collisionDetection}
+ onDragStart={handleDragStart}
+ onDragMove={handleDragMove}
+ onDragEnd={handleDragEnd}
+ onDragCancel={handleDragCancel}
+ >
+ <div
+ ref={scrollerRef}
+ className={styles.scroller}
+ data-scrolling-container="true"
+ onClick={(event) => {
+ if (event.target === event.currentTarget) clearSelection();
+ }}
+ >
+ <div
+ ref={contentRef}
+ className={styles.scrollerContent}
+ onClick={(event) => {
+ if (event.target === event.currentTarget) clearSelection();
+ }}
+ >
+ {displayRows.map((row) => {
+ const dropBefore =
+ draggingTrack != null && trackDropTarget === row.id;
+ const dropAfterLast =
+ draggingTrack != null &&
+ trackDropTarget === null &&
+ row.id === lastReorderableId;
+ const slotClass = [
+ styles.trackSlot,
+ dropBefore ? styles.trackDropBefore : "",
+ dropAfterLast ? styles.trackDropAfterLast : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+ let content: ReactNode;
+ if (row.kind === "track" || row.kind === "split") {
+ content = renderTrackRow(row.id);
+ } else if (row.kind === "disabled") {
+ content = (
+ <DisabledFileTrack
+ fileId={row.id}
+ name={fileState.files.byId[row.id]?.name ?? row.id}
+ onClose={() => setCloseRequest(row.id)}
+ />
+ );
+ } else {
+ content = (
+ <div className={styles.track}>
+ <header className={styles.trackHeader}>
+ <span className={styles.trackName}>
+ <PrivateContent>
+ {truncateCenter(
+ fileState.files.byId[row.id]?.name ?? row.id,
+ 40,
+ )}
+ </PrivateContent>
+ </span>
+ <span className={styles.trackMeta}>
+ {t("pageTracks.readingPages", "Reading pages...")}
+ </span>
+ </header>
+ <div className={`${styles.lane} ${styles.laneEmpty}`}>
+ <Loader size="sm" />
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div key={row.id} className={slotClass}>
+ {content}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <DragOverlay dropAnimation={null}>
+ {draggingIds.size > 0 && (
+ <div className={styles.dragBadge}>
+ {t("pageTracks.dragging", "{{count}} pages", {
+ count: draggingIds.size,
+ })}
+ </div>
+ )}
+ </DragOverlay>
+ </DndContext>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/components/pageTracks/SelectByNumberPopover.tsx b/frontend/editor/src/core/components/pageTracks/SelectByNumberPopover.tsx
new file mode 100644
index 0000000000..72e1bc46dc
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/SelectByNumberPopover.tsx
@@ -0,0 +1,79 @@
+import { useState } from "react";
+import { Popover } from "@mantine/core";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import BulkSelectionPanel from "@app/components/shared/pageSelection/BulkSelectionPanel";
+import { parseSelection } from "@app/utils/bulkselection/parseSelection";
+
+export interface SelectByNumberPopoverProps {
+ label: string;
+ /** Pages the typed numbers can address, numbered as the user sees them. */
+ pages: { id: string; pageNumber: number }[];
+ /** Highest page number the selection syntax resolves against. */
+ maxPages: number;
+ selectedPageIds: string[];
+ /** Receives the 1-based page numbers the typed selection resolves to. */
+ onSelect: (pageNumbers: number[]) => void;
+ disabled?: boolean;
+ iconSize: string;
+ className?: string;
+ actionSize?: "sm" | "md";
+}
+
+/** A button opening the "1,3,5-10" page selection panel. */
+export function SelectByNumberPopover({
+ label,
+ pages,
+ maxPages,
+ selectedPageIds,
+ onSelect,
+ disabled = false,
+ iconSize,
+ className,
+ actionSize,
+}: SelectByNumberPopoverProps) {
+ const [csvInput, setCsvInput] = useState("");
+
+ const applyInput = (override?: string) => {
+ if (maxPages === 0) return;
+ onSelect(parseSelection(override ?? csvInput, maxPages));
+ };
+
+ return (
+ <Popover position="bottom" withArrow shadow="md" offset={8}>
+ <Popover.Target>
+ <div style={{ display: "inline-flex" }}>
+ <Tooltip content={label} position="bottom">
+ <ActionIcon
+ variant="quiet"
+ size={actionSize}
+ className={className}
+ disabled={disabled || maxPages === 0}
+ aria-label={label}
+ >
+ <Icon name="file-digit" size={iconSize} />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ </Popover.Target>
+ <Popover.Dropdown>
+ {/* Portalled, but still a React child of a draggable track header:
+ its pointer events must not reach the header's drag handle. */}
+ <div
+ style={{ minWidth: "24rem", maxWidth: "32rem" }}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <BulkSelectionPanel
+ csvInput={csvInput}
+ setCsvInput={setCsvInput}
+ selectedPageIds={selectedPageIds}
+ displayDocument={{ pages }}
+ onUpdatePagesFromCSV={applyInput}
+ />
+ </div>
+ </Popover.Dropdown>
+ </Popover>
+ );
+}
diff --git a/frontend/editor/src/core/components/pageTracks/TrackPageTile.tsx b/frontend/editor/src/core/components/pageTracks/TrackPageTile.tsx
new file mode 100644
index 0000000000..7616ae379c
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/TrackPageTile.tsx
@@ -0,0 +1,292 @@
+import React, { useCallback, useMemo } from "react";
+import { useDraggable, useDroppable } from "@dnd-kit/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { Checkbox } from "@app/ui/Checkbox";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import HoverActionMenu, {
+ HoverAction,
+} from "@app/components/shared/HoverActionMenu";
+import { useIsMobile } from "@app/hooks/useIsMobile";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { FileId } from "@app/types/file";
+import { TrackPage } from "@app/components/pageTracks/types";
+import {
+ TrackThumbnailStore,
+ useTrackThumbnail,
+} from "@app/components/pageTracks/hooks/useTrackThumbnails";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+import { BlankPagePreview } from "@app/components/pageTracks/BlankPagePreview";
+
+export const pageDroppableId = (pageId: string) => `page:${pageId}`;
+
+export interface TrackPageTileProps {
+ page: TrackPage;
+ /** The track this tile currently sits in. */
+ trackFileId: FileId;
+ /** 1-based position within the track. */
+ position: number;
+ isLast: boolean;
+ /** Horizontal offset within the lane, from the virtualiser. */
+ offsetX: number;
+ /** Vertical offset within the lane (0 in single-row mode; row top in wrap). */
+ offsetY: number;
+ selected: boolean;
+ dragging: boolean;
+ /** Draw the insertion line on this tile's leading edge. */
+ dropBefore: boolean;
+ /** Draw it on the trailing edge (last tile, appending to the track). */
+ dropAfterLast: boolean;
+ thumbnails: TrackThumbnailStore;
+ onSelect: (
+ fileId: FileId,
+ pageId: string,
+ modifiers: { shift: boolean },
+ ) => void;
+ /** Opens the track's page-view modal starting at this page. */
+ onViewPage: (pageId: string) => void;
+ onRotate: (pageIds: string[], delta: number) => void;
+ onDelete: (pageIds: string[]) => void;
+ /** Swaps the page with its neighbour: -1 left, 1 right. */
+ onShift: (pageId: string, by: -1 | 1) => void;
+}
+
+interface ShiftButtonProps {
+ direction: "left" | "right";
+ label: string;
+ forceVisible: boolean;
+ onShift: () => void;
+}
+
+/** Sits on the side of the page it moves towards. */
+function ShiftButton({
+ direction,
+ label,
+ forceVisible,
+ onShift,
+}: ShiftButtonProps) {
+ return (
+ <div
+ className={`${styles.shiftButton} ${direction === "left" ? styles.shiftLeft : styles.shiftRight}`}
+ data-force-visible={forceVisible}
+ // The tile is a drag source and a selection toggle; neither should fire.
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <Tooltip content={label} position={direction}>
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ aria-label={label}
+ onClick={onShift}
+ >
+ <Icon
+ name={direction === "left" ? "arrow-left" : "arrow-right"}
+ size={14}
+ />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ );
+}
+
+function TrackPageTileImpl({
+ page,
+ trackFileId,
+ position,
+ isLast,
+ offsetX,
+ offsetY,
+ selected,
+ dragging,
+ dropBefore,
+ dropAfterLast,
+ thumbnails,
+ onSelect,
+ onViewPage,
+ onRotate,
+ onDelete,
+ onShift,
+}: TrackPageTileProps) {
+ const { t } = useTranslation();
+ const isMobile = useIsMobile();
+ const dragData = { type: "page", pageId: page.id, fileId: trackFileId };
+ const {
+ attributes,
+ listeners,
+ setNodeRef: setDragRef,
+ } = useDraggable({ id: pageDroppableId(page.id), data: dragData });
+ const { setNodeRef: setDropRef } = useDroppable({
+ id: pageDroppableId(page.id),
+ data: dragData,
+ });
+
+ const setRefs = useCallback(
+ (element: HTMLElement | null) => {
+ setDragRef(element);
+ setDropRef(element);
+ thumbnails.observe(page)(element);
+ },
+ [setDragRef, setDropRef, thumbnails, page],
+ );
+
+ const thumbnail = useTrackThumbnail(thumbnails, page);
+
+ const handleClick = useCallback(
+ (event: React.MouseEvent) => {
+ onSelect(trackFileId, page.id, { shift: event.shiftKey });
+ },
+ [onSelect, trackFileId, page.id],
+ );
+
+ const stop = (event: React.MouseEvent) => event.stopPropagation();
+ const quarterTurn = page.rotation === 90 || page.rotation === 270;
+
+ const hoverActions = useMemo<HoverAction[]>(
+ () => [
+ {
+ id: "view",
+ icon: <Icon name="eye" size={16} />,
+ label: t("pageTracks.viewPage", "View page"),
+ onClick: (event) => {
+ event.stopPropagation();
+ onViewPage(page.id);
+ },
+ },
+ {
+ id: "rotate-left",
+ icon: <Icon name="rotate-ccw" size={16} />,
+ label: t("pageTracks.rotateLeft", "Rotate left"),
+ onClick: (event) => {
+ event.stopPropagation();
+ onRotate([page.id], -90);
+ },
+ },
+ {
+ id: "rotate-right",
+ icon: <Icon name="rotate-cw" size={16} />,
+ label: t("pageTracks.rotateRight", "Rotate right"),
+ onClick: (event) => {
+ event.stopPropagation();
+ onRotate([page.id], 90);
+ },
+ },
+ {
+ id: "delete",
+ icon: <Icon name="trash" size={16} />,
+ label: t("pageTracks.delete.page", "Delete page"),
+ color: "var(--c-danger)",
+ onClick: (event) => {
+ event.stopPropagation();
+ onDelete([page.id]);
+ },
+ },
+ ],
+ [t, onViewPage, onRotate, onDelete, page.id],
+ );
+
+ return (
+ <div
+ ref={setRefs}
+ className={[
+ styles.tile,
+ selected ? styles.tileSelected : "",
+ dragging ? styles.tileDragging : "",
+ dropBefore ? styles.dropBefore : "",
+ dropAfterLast ? styles.dropAfterLast : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ style={{ left: offsetX, top: offsetY }}
+ {...attributes}
+ {...listeners}
+ data-page-id={page.id}
+ data-selected={selected}
+ data-drop-before={dropBefore || undefined}
+ data-drop-after-last={dropAfterLast || undefined}
+ role="button"
+ tabIndex={0}
+ aria-pressed={selected}
+ aria-label={t("pageTracks.page", "Page {{number}}", {
+ number: position,
+ })}
+ onClick={handleClick}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onSelect(trackFileId, page.id, { shift: false });
+ }
+ }}
+ >
+ <div className={styles.thumbBox}>
+ <div className={styles.tileCheckbox} onClick={stop}>
+ <Checkbox
+ checked={selected}
+ aria-label={t("pageTracks.selectPage", "Select page {{number}}", {
+ number: position,
+ })}
+ onChange={() => onSelect(trackFileId, page.id, { shift: false })}
+ />
+ </div>
+
+ <div className={styles.pageShadow}>
+ {page.kind === "blank" ? (
+ <BlankPagePreview page={page} placement="tile" />
+ ) : thumbnail ? (
+ <PrivateContent>
+ <img
+ className={[
+ styles.thumb,
+ quarterTurn ? styles.thumbQuarterTurn : "",
+ "ph-no-capture",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ src={thumbnail}
+ alt=""
+ draggable={false}
+ data-original-rotation={page.rotation}
+ style={{ transform: `rotate(${page.rotation}deg)` }}
+ />
+ </PrivateContent>
+ ) : (
+ <div className={styles.thumbPending} />
+ )}
+ </div>
+
+ {position > 1 && (
+ <ShiftButton
+ direction="left"
+ label={t("pageTracks.moveLeft", "Move left")}
+ forceVisible={isMobile}
+ onShift={() => onShift(page.id, -1)}
+ />
+ )}
+ {!isLast && (
+ <ShiftButton
+ direction="right"
+ label={t("pageTracks.moveRight", "Move right")}
+ forceVisible={isMobile}
+ onShift={() => onShift(page.id, 1)}
+ />
+ )}
+
+ <HoverActionMenu
+ show={isMobile}
+ actions={hoverActions}
+ position="inside"
+ visibility="cssHover"
+ className={styles.pagePill}
+ />
+ </div>
+
+ <div className={styles.pageNumber} data-page-index={position}>
+ {position}
+ </div>
+ </div>
+ );
+}
+
+export const TrackPageTile = React.memo(TrackPageTileImpl);
+export default TrackPageTile;
diff --git a/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsx b/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsx
new file mode 100644
index 0000000000..9f2357bc32
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsx
@@ -0,0 +1,178 @@
+import { useEffect, useState } from "react";
+import { Modal, Loader, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { useFileSelectors } from "@app/contexts/FileContext";
+import { thumbnailGenerationService } from "@app/services/thumbnailGenerationService";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import {
+ TrackPage,
+ isSourcePage,
+ sourcePageKey,
+} from "@app/components/pageTracks/types";
+import { BlankPagePreview } from "@app/components/pageTracks/BlankPagePreview";
+import { TrackThumbnailStore } from "@app/components/pageTracks/hooks/useTrackThumbnails";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+
+interface TrackPageViewModalProps {
+ /** The track's pages, so the modal can page through them. */
+ pages: TrackPage[];
+ /** Index into `pages` of the page currently shown. */
+ index: number;
+ onIndexChange: (index: number) => void;
+ /** The tile thumbnail store, for an instant low-res placeholder per page. */
+ thumbnails: TrackThumbnailStore;
+ onClose: () => void;
+}
+
+// Rendered above the tile scale so the page reads as a full-screen preview
+// rather than a blown-up thumbnail.
+const PREVIEW_SCALE = 2;
+
+/**
+ * A large preview of one page, with previous/next paging through its track.
+ * Renders the source page at high resolution on open (and on each move),
+ * showing the low-res tile thumbnail meanwhile. Rotation is applied in CSS on
+ * an unrotated render, matching how the tiles draw the page.
+ */
+export function TrackPageViewModal({
+ pages,
+ index,
+ onIndexChange,
+ thumbnails,
+ onClose,
+}: TrackPageViewModalProps) {
+ const { t } = useTranslation();
+ const selectors = useFileSelectors();
+ const [hiRes, setHiRes] = useState<string | null>(null);
+ const [failed, setFailed] = useState(false);
+
+ const page = pages[index];
+ const total = pages.length;
+ const hasPrev = index > 0;
+ const hasNext = index < total - 1;
+
+ useEffect(() => {
+ if (!page || !isSourcePage(page)) return;
+ let cancelled = false;
+ setHiRes(null);
+ setFailed(false);
+ const file = selectors.getFile(page.sourceFileId);
+ if (!file) {
+ setFailed(true);
+ return;
+ }
+ void (async () => {
+ try {
+ const buffer = await file.arrayBuffer();
+ const [result] = await thumbnailGenerationService.generateThumbnails(
+ page.sourceFileId,
+ buffer,
+ [page.sourcePageNumber],
+ { scale: PREVIEW_SCALE, quality: 0.92 },
+ );
+ if (cancelled) return;
+ if (result?.success && result.thumbnail) setHiRes(result.thumbnail);
+ else setFailed(true);
+ } catch {
+ if (!cancelled) setFailed(true);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [selectors, page]);
+
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "ArrowLeft" && index > 0) {
+ event.preventDefault();
+ onIndexChange(index - 1);
+ } else if (event.key === "ArrowRight" && index < total - 1) {
+ event.preventDefault();
+ onIndexChange(index + 1);
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [index, total, onIndexChange]);
+
+ if (!page) return null;
+
+ const src = isSourcePage(page)
+ ? (hiRes ?? thumbnails.get(sourcePageKey(page)))
+ : null;
+ const quarterTurn = page.rotation === 90 || page.rotation === 270;
+ const prevLabel = t("pageTracks.prevPage", "Previous page");
+ const nextLabel = t("pageTracks.nextPage", "Next page");
+
+ return (
+ <Modal
+ opened
+ onClose={onClose}
+ centered
+ size="auto"
+ title={t("pageTracks.pagePosition", "Page {{number}} of {{total}}", {
+ number: index + 1,
+ total,
+ })}
+ >
+ <div className={styles.pageViewBody}>
+ <Tooltip content={prevLabel}>
+ <ActionIcon
+ className={styles.pageViewNav}
+ variant="quiet"
+ aria-label={prevLabel}
+ disabled={!hasPrev}
+ onClick={() => onIndexChange(index - 1)}
+ >
+ <Icon name="chevron-left" size="1.75rem" />
+ </ActionIcon>
+ </Tooltip>
+
+ <div className={styles.pageViewStage}>
+ {page.kind === "blank" ? (
+ <BlankPagePreview page={page} placement="view" />
+ ) : src ? (
+ <PrivateContent>
+ <img
+ className={[
+ styles.pageViewImage,
+ quarterTurn ? styles.pageViewQuarter : "",
+ "ph-no-capture",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ src={src}
+ alt=""
+ style={{ transform: `rotate(${page.rotation}deg)` }}
+ />
+ </PrivateContent>
+ ) : failed ? (
+ <Text c="dimmed" size="sm">
+ {t("pageTracks.viewError", "Couldn't render this page")}
+ </Text>
+ ) : (
+ <Loader />
+ )}
+ </div>
+
+ <Tooltip content={nextLabel}>
+ <ActionIcon
+ className={styles.pageViewNav}
+ variant="quiet"
+ aria-label={nextLabel}
+ disabled={!hasNext}
+ onClick={() => onIndexChange(index + 1)}
+ >
+ <Icon name="chevron-right" size="1.75rem" />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ </Modal>
+ );
+}
+
+export default TrackPageViewModal;
diff --git a/frontend/editor/src/core/components/pageTracks/TrackRow.tsx b/frontend/editor/src/core/components/pageTracks/TrackRow.tsx
new file mode 100644
index 0000000000..311b99712e
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/TrackRow.tsx
@@ -0,0 +1,707 @@
+import React, {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { useDraggable, useDroppable } from "@dnd-kit/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { SelectByNumberPopover } from "@app/components/pageTracks/SelectByNumberPopover";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { truncateCenter } from "@app/utils/textUtils";
+import { FileId } from "@app/types/file";
+import { Track } from "@app/components/pageTracks/types";
+import { TrackThumbnailStore } from "@app/components/pageTracks/hooks/useTrackThumbnails";
+import { PageClickModifiers } from "@app/components/pageTracks/hooks/useTrackSelection";
+import TrackPageTile from "@app/components/pageTracks/TrackPageTile";
+import TrackPageViewModal from "@app/components/pageTracks/TrackPageViewModal";
+import {
+ TRACK_GEOMETRY,
+ rootFontSizePx,
+} from "@app/components/pageTracks/constants";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+
+export const trackDroppableId = (fileId: FileId) => `track:${fileId}`;
+/** Whole-track drop zone, used when a track header is being dragged. */
+export const trackZoneId = (fileId: FileId) => `zone:${fileId}`;
+export const trackHandleId = (fileId: FileId) => `trackhandle:${fileId}`;
+
+export interface DropHint {
+ fileId: FileId;
+ /** Insert before this page, or append to the track when null. */
+ beforePageId: string | null;
+}
+
+/**
+ * The controls in the gap before a page, or after the last one. The gaps at
+ * either end of a track only insert: there is nothing there to split.
+ */
+function GapHandle({
+ left,
+ top,
+ width,
+ beforePosition,
+ onSplit,
+ onInsert,
+}: {
+ /** laneInner x of the gap centre. */
+ left: number;
+ /** laneInner y of the page's top. */
+ top: number;
+ width: number;
+ /** 1-based position of the page after the gap; one past the end for the last gap. */
+ beforePosition: number;
+ onSplit?: () => void;
+ onInsert: () => void;
+}) {
+ const { t } = useTranslation();
+ const splitLabel = t("pageTracks.splitHere", "Split here");
+ const insertLabel = t("pageTracks.insertBlank", "Insert blank page");
+ return (
+ <div
+ className={styles.gapHandle}
+ style={{ left, top, width, height: "var(--pt-tile-h)" }}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <Tooltip content={insertLabel} position="top">
+ <button
+ type="button"
+ className={styles.gapAction}
+ aria-label={insertLabel}
+ data-insert-before={beforePosition}
+ onClick={onInsert}
+ >
+ <Icon name="plus" size="1em" />
+ </button>
+ </Tooltip>
+ {onSplit && (
+ <Tooltip content={splitLabel} position="top">
+ <button
+ type="button"
+ className={styles.gapAction}
+ aria-label={splitLabel}
+ data-split-before={beforePosition}
+ onClick={onSplit}
+ >
+ <Icon name="scissors" size="1em" />
+ </button>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
+
+export interface TrackRowProps {
+ track: Track;
+ name: string;
+ /** True for a split track not yet backed by a saved file. */
+ isNew: boolean;
+ versionNumber: number | undefined;
+ selectedIds: Set<string>;
+ draggingIds: Set<string>;
+ dropHint: DropHint | null;
+ /** Pages wrap onto multiple rows instead of one horizontally scrolling row. */
+ wrap: boolean;
+ /** Scales the page tiles (and their gaps) without resizing the rest of the UI. */
+ zoom: number;
+ /** The scrolling container wrap-mode rows are virtualised against. */
+ scrollerRef: React.RefObject<HTMLDivElement | null>;
+ /** Bumped by the parent when the stacked track heights change, forcing this
+ * lane to re-measure its offset within the scroller. */
+ layoutVersion: number;
+ /** This track's header is the one being dragged. */
+ trackDragging: boolean;
+ changed: boolean;
+ thumbnails: TrackThumbnailStore;
+ onSelectPage: (
+ fileId: FileId,
+ pageId: string,
+ modifiers: PageClickModifiers,
+ ) => void;
+ onSelectTrack: (fileId: FileId) => void;
+ /** Selects these 1-based pages of the track, replacing its selection. */
+ onSelectNumbers: (fileId: FileId, pageNumbers: number[]) => void;
+ onOpenInViewer: (fileId: FileId) => void;
+ /** Called when the click landed on empty lane surface, not on a page. */
+ onClearSelection: () => void;
+ /** Split this track so `startPageId` begins a new track. */
+ onSplit: (fileId: FileId, startPageId: string) => void;
+ /** Insert a blank page before `beforePageId`, or at the end when null. */
+ onInsertBlank: (fileId: FileId, beforePageId: string | null) => void;
+ onRotate: (pageIds: string[], delta: number) => void;
+ onDelete: (pageIds: string[]) => void;
+ onShiftPage: (pageId: string, by: -1 | 1) => void;
+ /** Asks to close the file; the parent confirms before anything closes. */
+ onClose: (fileId: FileId) => void;
+}
+
+function TrackRowImpl({
+ track,
+ name,
+ versionNumber,
+ selectedIds,
+ draggingIds,
+ dropHint,
+ wrap,
+ zoom,
+ scrollerRef,
+ layoutVersion,
+ isNew,
+ trackDragging,
+ changed,
+ thumbnails,
+ onSelectPage,
+ onSelectTrack,
+ onSelectNumbers,
+ onOpenInViewer,
+ onClearSelection,
+ onSplit,
+ onInsertBlank,
+ onRotate,
+ onDelete,
+ onShiftPage,
+ onClose,
+}: TrackRowProps) {
+ const { t } = useTranslation();
+ const { setNodeRef, isOver } = useDroppable({
+ id: trackDroppableId(track.fileId),
+ data: { type: "track", fileId: track.fileId },
+ });
+
+ // Reordering tracks: the header is the handle, the whole section the target.
+ // Only the pointer listeners are applied, deliberately NOT dnd-kit's ARIA
+ // attributes: those would make the header a role="button" whose accessible
+ // name is everything inside it, with the real controls nested inside.
+ const { listeners: handleListeners, setNodeRef: setHandleRef } = useDraggable(
+ {
+ id: trackHandleId(track.fileId),
+ data: { type: "trackHandle", fileId: track.fileId },
+ },
+ );
+ const { setNodeRef: setZoneRef } = useDroppable({
+ id: trackZoneId(track.fileId),
+ data: { type: "zone", fileId: track.fileId },
+ });
+
+ // A lane can hold hundreds of pages. Mounting them all is what made a single
+ // click cost ~700ms and a drag ~300ms per pointer move: every tile is a
+ // dnd-kit draggable AND droppable, so the whole set gets re-registered on
+ // each render, re-measured on drag start and hit-tested on every move.
+ const laneRef = useRef<HTMLDivElement | null>(null);
+ const laneInnerRef = useRef<HTMLDivElement | null>(null);
+ // Collapsed hides the lane, leaving just the header. Local (not lifted) so it
+ // survives track reorder via the row's fileId key; a save remounts the row,
+ // which reasonably reopens it.
+ const [collapsed, setCollapsed] = useState(false);
+ // Which page (by id) the view modal is showing, or null when closed. Kept by
+ // id, not index, so an edit that reorders pages doesn't jump the preview.
+ const [viewPageId, setViewPageId] = useState<string | null>(null);
+ // Zoom scales the tile dimensions (and gaps) only; everything derived here,
+ // and the CSS vars the tiles read, moves with it so the geometry and the
+ // virtualiser stay in agreement at any zoom.
+ const geometry = useMemo(() => {
+ const px = rootFontSizePx();
+ const tileWidthRem = TRACK_GEOMETRY.tileWidthRem * zoom;
+ const tileHeightRem = TRACK_GEOMETRY.tileCanvasHeightRem * zoom;
+ const tileFooterRem = TRACK_GEOMETRY.tileFooterHeightRem * zoom;
+ const gapRem = TRACK_GEOMETRY.gapRem * zoom;
+ return {
+ gapPx: gapRem * px,
+ lanePadPx: TRACK_GEOMETRY.lanePaddingXRem * px,
+ tileWidthPx: tileWidthRem * px,
+ // Distance between the left edges of adjacent tiles (tile + gap).
+ colStride: (tileWidthRem + gapRem) * px,
+ // Distance between the top edges of adjacent wrapped rows.
+ rowStride: (tileHeightRem + tileFooterRem + gapRem) * px,
+ cssVars: {
+ "--pt-zoom": `${zoom}`,
+ "--pt-tile-w": `${tileWidthRem}rem`,
+ "--pt-tile-h": `${tileHeightRem}rem`,
+ "--pt-tile-footer-h": `${tileFooterRem}rem`,
+ "--pt-lane-pad-x": `${TRACK_GEOMETRY.lanePaddingXRem}rem`,
+ "--pt-gap": `${gapRem}rem`,
+ } as React.CSSProperties,
+ };
+ }, [zoom]);
+
+ const pageCount = track.pages.length;
+
+ // Wrap mode packs as many whole tiles as the lane's content width allows.
+ const [laneWidth, setLaneWidth] = useState(0);
+ // Seed the width synchronously before the first wrap paint so the column
+ // count is right immediately; the observer keeps it current on resize.
+ // Re-runs when the lane remounts on expand so the width is right again
+ // straight away.
+ useLayoutEffect(() => {
+ const element = laneRef.current;
+ if (!element) return;
+ const padding = 2 * geometry.lanePadPx;
+ setLaneWidth(Math.max(0, element.clientWidth - padding));
+ }, [wrap, collapsed, geometry.lanePadPx]);
+ // Keyed on `collapsed` so the observer follows the lane element as it
+ // unmounts (collapse) and remounts (expand).
+ useEffect(() => {
+ const element = laneRef.current;
+ if (!element || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver((entries) => {
+ setLaneWidth(entries[0]?.contentRect.width ?? 0);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [collapsed]);
+
+ const columns = useMemo(() => {
+ if (!wrap || laneWidth <= 0) return 1;
+ return Math.max(
+ 1,
+ Math.floor((laneWidth + geometry.gapPx) / geometry.colStride),
+ );
+ }, [wrap, laneWidth, geometry.gapPx, geometry.colStride]);
+
+ const rowCount = wrap ? Math.ceil(pageCount / columns) : pageCount;
+
+ // Spread the spare width so a wrapped row fills the lane edge to edge instead
+ // of bunching left. The stride is per-column (not per-row), so a short last
+ // row still lines its tiles up under the columns above it.
+ const wrapColStride = useMemo(() => {
+ if (!wrap || columns <= 1) return geometry.colStride;
+ const gap = (laneWidth - columns * geometry.tileWidthPx) / (columns - 1);
+ return geometry.tileWidthPx + Math.max(geometry.gapPx, gap);
+ }, [
+ wrap,
+ columns,
+ laneWidth,
+ geometry.tileWidthPx,
+ geometry.gapPx,
+ geometry.colStride,
+ ]);
+
+ // Wrap-mode rows are virtualised against the shared outer scroller, so each
+ // lane needs the offset of its content within that scroller's scroll height.
+ // One track above growing or shrinking shifts this, which is why the parent
+ // bumps layoutVersion on any height change.
+ const [scrollMargin, setScrollMargin] = useState(0);
+ useLayoutEffect(() => {
+ if (!wrap) {
+ setScrollMargin((prev) => (prev === 0 ? prev : 0));
+ return;
+ }
+ const inner = laneInnerRef.current;
+ const scroller = scrollerRef.current;
+ if (!inner || !scroller) return;
+ const margin =
+ inner.getBoundingClientRect().top -
+ scroller.getBoundingClientRect().top +
+ scroller.scrollTop;
+ setScrollMargin((prev) => (Math.abs(prev - margin) > 0.5 ? margin : prev));
+ }, [
+ wrap,
+ collapsed,
+ layoutVersion,
+ columns,
+ rowCount,
+ pageCount,
+ scrollerRef,
+ ]);
+
+ const virtualizer = useVirtualizer({
+ count: wrap ? rowCount : pageCount,
+ horizontal: !wrap,
+ getScrollElement: () => (wrap ? scrollerRef.current : laneRef.current),
+ estimateSize: () => (wrap ? geometry.rowStride : geometry.colStride),
+ overscan: wrap ? 3 : TRACK_GEOMETRY.overscan,
+ scrollMargin: wrap ? scrollMargin : 0,
+ });
+
+ // Zoom changes every tile's size, so drop the cached measurements and
+ // re-derive them from the new estimate.
+ useLayoutEffect(() => {
+ virtualizer.measure();
+ }, [virtualizer, zoom, wrap]);
+
+ const setLaneRef = useCallback(
+ (element: HTMLDivElement | null) => {
+ laneRef.current = element;
+ setNodeRef(element);
+ },
+ [setNodeRef],
+ );
+
+ const selectedInTrack = useMemo(
+ () =>
+ track.pages
+ .filter((page) => selectedIds.has(page.id))
+ .map((page) => page.id),
+ [track.pages, selectedIds],
+ );
+
+ const allSelectedInTrack =
+ track.pages.length > 0 && selectedInTrack.length === track.pages.length;
+ const selectAllLabel = allSelectedInTrack
+ ? t("workbenchBar.deselectAll", "Deselect All")
+ : t("workbenchBar.selectAll", "Select All");
+
+ const numberedPages = useMemo(
+ () =>
+ track.pages.map((page, index) => ({
+ id: page.id,
+ pageNumber: index + 1,
+ })),
+ [track.pages],
+ );
+ const handleSelectNumbers = useCallback(
+ (pageNumbers: number[]) => onSelectNumbers(track.fileId, pageNumbers),
+ [onSelectNumbers, track.fileId],
+ );
+
+ const handleSelectTrack = useCallback(
+ () => onSelectTrack(track.fileId),
+ [onSelectTrack, track.fileId],
+ );
+
+ const handleSplitPage = useCallback(
+ (startPageId: string) => onSplit(track.fileId, startPageId),
+ [onSplit, track.fileId],
+ );
+ const handleInsertBlank = useCallback(
+ (beforePageId: string | null) => onInsertBlank(track.fileId, beforePageId),
+ [onInsertBlank, track.fileId],
+ );
+
+ const hintActive = dropHint?.fileId === track.fileId;
+ const collapseLabel = collapsed
+ ? t("pageTracks.track.expand", "Expand")
+ : t("pageTracks.track.collapse", "Collapse");
+
+ const handleViewPage = useCallback((pageId: string) => {
+ setViewPageId(pageId);
+ }, []);
+ // -1 once the shown page has been deleted, which closes the modal.
+ const viewIndex =
+ viewPageId == null ? -1 : track.pages.findIndex((p) => p.id === viewPageId);
+
+ return (
+ <section
+ ref={setZoneRef}
+ style={geometry.cssVars}
+ className={[
+ styles.track,
+ isOver ? styles.trackDropActive : "",
+ trackDragging ? styles.trackDragging : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ data-track-file-id={track.fileId}
+ data-changed={changed}
+ aria-label={name}
+ >
+ <header
+ ref={setHandleRef}
+ className={styles.trackHeader}
+ {...handleListeners}
+ >
+ <Tooltip position="bottom" content={collapseLabel}>
+ <ActionIcon
+ className={styles.trackCollapse}
+ variant="quiet"
+ size="sm"
+ aria-label={collapseLabel}
+ aria-expanded={!collapsed}
+ onClick={() => setCollapsed((value) => !value)}
+ >
+ {collapsed ? (
+ <Icon name="chevron-right" size="1.25rem" />
+ ) : (
+ <Icon name="chevron-down" size="1.25rem" />
+ )}
+ </ActionIcon>
+ </Tooltip>
+ <span className={styles.trackName}>
+ <PrivateContent>{truncateCenter(name, 40)}</PrivateContent>
+ </span>
+ <span className={styles.trackMeta}>
+ {[
+ versionNumber != null && versionNumber > 1
+ ? `v${versionNumber}`
+ : null,
+ t("pageTracks.pageCount", "{{count}} pages", {
+ count: track.pages.length,
+ }),
+ changed ? t("pageTracks.edited", "edited") : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
+ <Tooltip
+ position="bottom"
+ content={t("openInViewer", "Open in Viewer")}
+ >
+ <ActionIcon
+ className={styles.trackLeadAction}
+ variant="quiet"
+ size="sm"
+ aria-label={t("openInViewer", "Open in Viewer")}
+ // An emptied track has nothing to show; a split has no file until
+ // it is saved.
+ disabled={track.pages.length === 0 || isNew}
+ onClick={() => onOpenInViewer(track.fileId)}
+ >
+ <Icon name="eye" size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+
+ <div className={styles.trackActions}>
+ <Tooltip position="bottom" content={selectAllLabel}>
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ aria-label={selectAllLabel}
+ disabled={track.pages.length === 0}
+ onClick={handleSelectTrack}
+ >
+ <Icon name="select-all" size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+ <SelectByNumberPopover
+ label={t("workbenchBar.selectByNumber", "Select by Page Numbers")}
+ iconSize="1rem"
+ actionSize="sm"
+ pages={numberedPages}
+ maxPages={track.pages.length}
+ selectedPageIds={selectedInTrack}
+ onSelect={handleSelectNumbers}
+ />
+ <Tooltip
+ position="bottom"
+ content={t("pageTracks.track.close", "Close file")}
+ >
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ accent="danger"
+ aria-label={t("pageTracks.track.close", "Close file")}
+ disabled={isNew}
+ onClick={() => onClose(track.fileId)}
+ >
+ <Icon name="x" size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ </header>
+
+ {!collapsed && (
+ <div
+ ref={setLaneRef}
+ data-track-lane={track.fileId}
+ className={[
+ styles.lane,
+ wrap ? styles.laneWrap : "",
+ track.pages.length === 0 ? styles.laneEmpty : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ // Only a click on the lane itself, never one that bubbled up from a
+ // page: clicking a tile would otherwise select it and immediately
+ // clear it again.
+ onClick={(event) => {
+ if (event.target === event.currentTarget) onClearSelection();
+ }}
+ >
+ {track.pages.length === 0 && (
+ <span className={styles.laneHint}>
+ {t(
+ "pageTracks.emptyTrack",
+ "No pages left. Drag pages here, or save to close this file.",
+ )}
+ </span>
+ )}
+ {pageCount > 0 && (
+ <div
+ ref={laneInnerRef}
+ className={styles.laneInner}
+ style={
+ {
+ "--pt-col-gap": `${wrapColStride - geometry.tileWidthPx}px`,
+ width: wrap ? "100%" : virtualizer.getTotalSize(),
+ height: wrap ? virtualizer.getTotalSize() : undefined,
+ } as React.CSSProperties
+ }
+ >
+ {virtualizer.getVirtualItems().map((item) => {
+ // Single row: each virtual item is a page, placed along the lane.
+ if (!wrap) {
+ const page = track.pages[item.index];
+ if (!page) return null;
+ return (
+ <React.Fragment key={page.id}>
+ <TrackPageTile
+ page={page}
+ trackFileId={track.fileId}
+ position={item.index + 1}
+ isLast={item.index === pageCount - 1}
+ offsetX={item.start}
+ offsetY={0}
+ selected={selectedIds.has(page.id)}
+ dragging={draggingIds.has(page.id)}
+ dropBefore={
+ hintActive && dropHint?.beforePageId === page.id
+ }
+ dropAfterLast={
+ hintActive &&
+ dropHint?.beforePageId == null &&
+ item.index === pageCount - 1
+ }
+ thumbnails={thumbnails}
+ onSelect={onSelectPage}
+ onViewPage={handleViewPage}
+ onRotate={onRotate}
+ onDelete={onDelete}
+ onShift={onShiftPage}
+ />
+ <GapHandle
+ left={
+ item.index > 0
+ ? item.start - geometry.gapPx / 2
+ : -geometry.lanePadPx / 2
+ }
+ top={0}
+ width={
+ item.index > 0 ? geometry.gapPx : geometry.lanePadPx
+ }
+ beforePosition={item.index + 1}
+ onSplit={
+ item.index > 0
+ ? () => handleSplitPage(page.id)
+ : undefined
+ }
+ onInsert={() => handleInsertBlank(page.id)}
+ />
+ {item.index === pageCount - 1 && (
+ <GapHandle
+ left={
+ item.start +
+ geometry.tileWidthPx +
+ geometry.gapPx / 2
+ }
+ top={0}
+ width={geometry.gapPx}
+ beforePosition={pageCount + 1}
+ onInsert={() => handleInsertBlank(null)}
+ />
+ )}
+ </React.Fragment>
+ );
+ }
+ // Wrap: each virtual item is a row of up to `columns` pages.
+ const rowTop = item.start - scrollMargin;
+ const rowStartIndex = item.index * columns;
+ const gapBefore = wrapColStride - geometry.tileWidthPx;
+ return Array.from({ length: columns }, (_unused, col) => {
+ const pageIndex = rowStartIndex + col;
+ const page = track.pages[pageIndex];
+ if (!page) return null;
+ return (
+ <React.Fragment key={page.id}>
+ <TrackPageTile
+ page={page}
+ trackFileId={track.fileId}
+ position={pageIndex + 1}
+ isLast={pageIndex === pageCount - 1}
+ offsetX={col * wrapColStride}
+ offsetY={rowTop}
+ selected={selectedIds.has(page.id)}
+ dragging={draggingIds.has(page.id)}
+ dropBefore={
+ hintActive && dropHint?.beforePageId === page.id
+ }
+ dropAfterLast={
+ hintActive &&
+ dropHint?.beforePageId == null &&
+ pageIndex === pageCount - 1
+ }
+ thumbnails={thumbnails}
+ onSelect={onSelectPage}
+ onViewPage={handleViewPage}
+ onRotate={onRotate}
+ onDelete={onDelete}
+ onShift={onShiftPage}
+ />
+ <GapHandle
+ left={
+ col > 0
+ ? col * wrapColStride - gapBefore / 2
+ : -geometry.lanePadPx / 2
+ }
+ top={rowTop}
+ width={col > 0 ? gapBefore : geometry.lanePadPx}
+ beforePosition={pageIndex + 1}
+ onSplit={
+ pageIndex > 0
+ ? () => handleSplitPage(page.id)
+ : undefined
+ }
+ onInsert={() => handleInsertBlank(page.id)}
+ />
+ {pageIndex === pageCount - 1 && (
+ <GapHandle
+ // In the last column the only room is the lane's padding.
+ left={
+ col * wrapColStride +
+ geometry.tileWidthPx +
+ (col < columns - 1
+ ? gapBefore
+ : geometry.lanePadPx) /
+ 2
+ }
+ top={rowTop}
+ width={
+ col < columns - 1 ? gapBefore : geometry.lanePadPx
+ }
+ beforePosition={pageCount + 1}
+ onInsert={() => handleInsertBlank(null)}
+ />
+ )}
+ </React.Fragment>
+ );
+ });
+ })}
+ </div>
+ )}
+ </div>
+ )}
+
+ {viewIndex >= 0 && (
+ // The modal portals to the body but is a React child of this section,
+ // so its events would bubble through the React tree to the lane/tiles.
+ // Contain them so a backdrop click can't clear or change the selection.
+ <div
+ style={{ display: "contents" }}
+ onClick={(event) => event.stopPropagation()}
+ onDoubleClick={(event) => event.stopPropagation()}
+ onPointerDown={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ <TrackPageViewModal
+ pages={track.pages}
+ index={viewIndex}
+ onIndexChange={(next) =>
+ setViewPageId(track.pages[next]?.id ?? null)
+ }
+ thumbnails={thumbnails}
+ onClose={() => setViewPageId(null)}
+ />
+ </div>
+ )}
+ </section>
+ );
+}
+
+export const TrackRow = React.memo(TrackRowImpl);
+export default TrackRow;
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
new file mode 100644
index 0000000000..4464ff6c13
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
@@ -0,0 +1,116 @@
+import { StirlingFileStub } from "@app/types/fileContext";
+import { FileId } from "@app/types/file";
+import { PDFDocument, PDFPage } from "@app/types/pageEditor";
+import { pdfExportService } from "@app/services/pdfExportService";
+import { policySourceIds } from "@app/services/policyFileGuard";
+import {
+ Track,
+ TrackPage,
+ TrackWorkspace,
+ isSourcePage,
+} from "@app/components/pageTracks/types";
+
+export interface TrackFileLookup {
+ getStub: (id: FileId) => StirlingFileStub | undefined;
+ getFile: (id: FileId) => File | undefined;
+}
+
+export interface BuiltTrackFile {
+ file: File;
+ /** The file the output descends from: the track's own, or a split's source. */
+ parentStub: StirlingFileStub;
+}
+
+/** Shape the export service expects: pages tagged with their source page. */
+function toExportDocument(
+ name: string,
+ ownFile: File,
+ pages: TrackPage[],
+): PDFDocument {
+ const exportPages: PDFPage[] = pages.map((page, index) => ({
+ id: page.id,
+ pageNumber: index + 1,
+ rotation: page.rotation,
+ thumbnail: null,
+ selected: false,
+ ...(isSourcePage(page)
+ ? {
+ originalPageNumber: page.sourcePageNumber,
+ originalFileId: page.sourceFileId,
+ }
+ : {
+ originalPageNumber: -1,
+ isBlankPage: true,
+ blankSize: { width: page.width, height: page.height },
+ }),
+ }));
+
+ return {
+ id: `page-tracks-${name}`,
+ name,
+ file: ownFile,
+ pages: exportPages,
+ totalPages: exportPages.length,
+ };
+}
+
+/**
+ * Renders a track's pages, as the editor shows them, into a PDF. A split has no
+ * file of its own, so it is named after its track and parented to the file its
+ * first source page came from, else the file it was cut from. Null when there
+ * are no pages or that file has closed.
+ */
+export async function buildTrackFile(
+ track: Track,
+ lookup: TrackFileLookup,
+): Promise<BuiltTrackFile | null> {
+ const { pages } = track;
+ const sourcePages = pages.filter(isSourcePage);
+ const anchorFileId = track.isNew
+ ? (sourcePages[0]?.sourceFileId ?? track.splitFromFileId)
+ : track.fileId;
+ if (!anchorFileId) return null;
+ const parentStub = lookup.getStub(anchorFileId);
+ const ownFile = lookup.getFile(anchorFileId);
+ if (!parentStub || !ownFile) return null;
+ const name = track.isNew ? track.name : parentStub.name;
+
+ const sourceFiles = new Map<string, File>();
+ for (const page of sourcePages) {
+ if (sourceFiles.has(page.sourceFileId)) continue;
+ const sourceFile = lookup.getFile(page.sourceFileId);
+ if (sourceFile) sourceFiles.set(page.sourceFileId, sourceFile);
+ }
+
+ const { blob } = await pdfExportService.exportPDFMultiFile(
+ toExportDocument(name, ownFile, pages),
+ sourceFiles,
+ [],
+ { filename: name },
+ );
+ return {
+ file: new File([blob], name, { type: "application/pdf" }),
+ parentStub,
+ };
+}
+
+/** Every file whose bytes building these tracks writes out, including consumed ancestors. */
+export function policyIdsForTracks(
+ workspace: TrackWorkspace,
+ trackIds: FileId[],
+ getStub: TrackFileLookup["getStub"],
+): string[] {
+ const fileIds = new Set<FileId>();
+ for (const id of trackIds) {
+ const track = workspace.tracks[id];
+ if (!track) continue;
+ if (!track.isNew) fileIds.add(id);
+ track.pages
+ .filter(isSourcePage)
+ .forEach((page) => fileIds.add(page.sourceFileId));
+ }
+ return [...fileIds].flatMap((id) => {
+ const stub = getStub(id);
+ return stub ? policySourceIds(stub) : [id];
+ });
+}
diff --git a/frontend/editor/src/core/components/pageTracks/constants.ts b/frontend/editor/src/core/components/pageTracks/constants.ts
new file mode 100644
index 0000000000..492e8b8681
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/constants.ts
@@ -0,0 +1,25 @@
+/**
+ * Lane geometry. Single source of truth: the numbers are pushed onto the track
+ * element as CSS custom properties AND used by the horizontal virtualiser, so
+ * the two can never drift apart.
+ */
+export const TRACK_GEOMETRY = {
+ tileWidthRem: 8.5,
+ tileCanvasHeightRem: 11.5,
+ tileFooterHeightRem: 1.375,
+ /** Wide enough for the gap's split and insert controls. */
+ gapRem: 1.5,
+ /** The lane's side padding: room for the insert control before the first
+ * page and after the last. Not zoomed, unlike the gaps. */
+ lanePaddingXRem: 1.5,
+ /** Extra tiles rendered either side of the visible window. */
+ overscan: 6,
+} as const;
+
+export const rootFontSizePx = (): number => {
+ if (typeof window === "undefined") return 16;
+ const parsed = parseFloat(
+ getComputedStyle(document.documentElement).fontSize,
+ );
+ return Number.isNaN(parsed) ? 16 : parsed;
+};
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx
new file mode 100644
index 0000000000..93f41b65ec
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx
@@ -0,0 +1,316 @@
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ useWorkbenchBarButtons,
+ WorkbenchBarButtonWithAction,
+} from "@app/hooks/useWorkbenchBarButtons";
+import { Icon } from "@app/ui/Icon";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+import {
+ SelectByNumberPopover,
+ SelectByNumberPopoverProps,
+} from "@app/components/pageTracks/SelectByNumberPopover";
+
+export interface PageTracksBarParams {
+ totalPages: number;
+ selectedCount: number;
+ canUndo: boolean;
+ canRedo: boolean;
+ isDirty: boolean;
+ saving: boolean;
+ wrap: boolean;
+ onToggleWrap: () => void;
+ canZoomIn: boolean;
+ canZoomOut: boolean;
+ onZoomIn: () => void;
+ onZoomOut: () => void;
+ /** Selects every page, or clears the selection when every page is selected. */
+ onToggleSelectAll: () => void;
+ /** Page-number selection across every track. */
+ numberSelection: Pick<
+ SelectByNumberPopoverProps,
+ "pages" | "maxPages" | "selectedPageIds" | "onSelect"
+ >;
+ onRotate: (delta: number) => void;
+ onDelete: () => void;
+ onInsertBlankAfter: () => void;
+ onSplitAfter: () => void;
+ onUndo: () => void;
+ onRedo: () => void;
+ onSave: () => void;
+}
+
+export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
+ const {
+ totalPages,
+ selectedCount,
+ canUndo,
+ canRedo,
+ isDirty,
+ saving,
+ wrap,
+ onToggleWrap,
+ canZoomIn,
+ canZoomOut,
+ onZoomIn,
+ onZoomOut,
+ onToggleSelectAll,
+ numberSelection,
+ onRotate,
+ onDelete,
+ onInsertBlankAfter,
+ onSplitAfter,
+ onUndo,
+ onRedo,
+ onSave,
+ } = params;
+ const { t } = useTranslation();
+
+ const labels = {
+ wrap: t("pageTracks.wrap.label", "Wrap pages"),
+ zoomIn: t("pageTracks.zoomIn", "Zoom in"),
+ zoomOut: t("pageTracks.zoomOut", "Zoom out"),
+ selectAll: t("workbenchBar.selectAll", "Select All"),
+ deselectAll: t("workbenchBar.deselectAll", "Deselect All"),
+ selectByNumber: t("workbenchBar.selectByNumber", "Select by Page Numbers"),
+ rotateLeft: t(
+ "pageTracks.rotateSelectedLeft",
+ "Rotate selected pages left",
+ ),
+ rotateRight: t(
+ "pageTracks.rotateSelectedRight",
+ "Rotate selected pages right",
+ ),
+ deleteSelected: t("pageTracks.deleteSelected", "Delete selected pages"),
+ insertBlankAfter: t(
+ "pageTracks.insertBlankAfterSelected",
+ "Insert blank pages after selected pages",
+ ),
+ splitAfter: t(
+ "pageTracks.splitAfterSelected",
+ "Split after selected pages",
+ ),
+ undo: t("pageTracks.undo", "Undo"),
+ redo: t("pageTracks.redo", "Redo"),
+ save: t("pageTracks.saveChanges", "Save changes to all files"),
+ };
+
+ const hasPages = totalPages > 0;
+ const hasSelection = selectedCount > 0;
+ const allSelected = hasPages && selectedCount === totalPages;
+ const selectAllLabel = allSelected ? labels.deselectAll : labels.selectAll;
+
+ const buttons = useMemo<WorkbenchBarButtonWithAction[]>(
+ () => [
+ {
+ id: "tracks-wrap",
+ icon: <Icon name="text-wrap" size="1.25rem" />,
+ tooltip: labels.wrap,
+ ariaLabel: labels.wrap,
+ section: "top" as const,
+ order: 5,
+ visible: hasPages,
+ active: wrap,
+ onClick: onToggleWrap,
+ },
+ {
+ id: "tracks-zoom-out",
+ icon: <Icon name="zoom-out" size="1.25rem" />,
+ tooltip: labels.zoomOut,
+ ariaLabel: labels.zoomOut,
+ section: "top" as const,
+ order: 6,
+ disabled: !canZoomOut,
+ visible: hasPages,
+ onClick: onZoomOut,
+ },
+ {
+ id: "tracks-zoom-in",
+ icon: <Icon name="zoom-in" size="1.25rem" />,
+ tooltip: labels.zoomIn,
+ ariaLabel: labels.zoomIn,
+ section: "top" as const,
+ order: 7,
+ disabled: !canZoomIn,
+ visible: hasPages,
+ onClick: onZoomIn,
+ },
+ {
+ id: "tracks-select-all",
+ icon: <Icon name="select-all" size="1.5rem" />,
+ tooltip: selectAllLabel,
+ ariaLabel: selectAllLabel,
+ section: "top" as const,
+ order: 10,
+ visible: hasPages,
+ active: allSelected,
+ onClick: onToggleSelectAll,
+ },
+ {
+ id: "tracks-select-by-number",
+ tooltip: labels.selectByNumber,
+ ariaLabel: labels.selectByNumber,
+ section: "top" as const,
+ order: 15,
+ visible: hasPages,
+ // The popover carries its own trigger, so the bar's click action and
+ // tooltip wrapper are bypassed.
+ render: () => (
+ <SelectByNumberPopover
+ label={labels.selectByNumber}
+ iconSize="1.5rem"
+ className="workbench-bar-action-icon"
+ {...numberSelection}
+ />
+ ),
+ },
+ {
+ id: "tracks-rotate-left",
+ icon: <Icon name="rotate-ccw" size="1.25rem" />,
+ tooltip: labels.rotateLeft,
+ ariaLabel: labels.rotateLeft,
+ section: "middle" as const,
+ order: 10,
+ disabled: !hasSelection,
+ visible: hasPages,
+ onClick: () => onRotate(-90),
+ },
+ {
+ id: "tracks-rotate-right",
+ icon: <Icon name="rotate-cw" size="1.25rem" />,
+ tooltip: labels.rotateRight,
+ ariaLabel: labels.rotateRight,
+ section: "middle" as const,
+ order: 20,
+ disabled: !hasSelection,
+ visible: hasPages,
+ onClick: () => onRotate(90),
+ },
+ {
+ id: "tracks-insert-blank-after",
+ icon: <Icon name="file-plus" size="1.25rem" />,
+ tooltip: labels.insertBlankAfter,
+ ariaLabel: labels.insertBlankAfter,
+ section: "middle" as const,
+ order: 25,
+ disabled: !hasSelection,
+ visible: hasPages,
+ onClick: onInsertBlankAfter,
+ },
+ {
+ id: "tracks-split-after",
+ icon: <Icon name="scissors" size="1.25rem" />,
+ tooltip: labels.splitAfter,
+ ariaLabel: labels.splitAfter,
+ section: "middle" as const,
+ order: 27,
+ disabled: !hasSelection,
+ visible: hasPages,
+ onClick: onSplitAfter,
+ },
+ {
+ id: "tracks-delete-selected",
+ icon: <Icon name="trash" size="1.5rem" />,
+ tooltip: labels.deleteSelected,
+ ariaLabel: labels.deleteSelected,
+ section: "middle" as const,
+ order: 30,
+ disabled: !hasSelection,
+ visible: hasPages,
+ onClick: onDelete,
+ },
+ {
+ id: "tracks-undo",
+ icon: <Icon name="undo-2" size="1.25rem" />,
+ tooltip: labels.undo,
+ ariaLabel: labels.undo,
+ section: "bottom" as const,
+ order: 10,
+ disabled: !canUndo,
+ visible: hasPages,
+ onClick: onUndo,
+ },
+ {
+ id: "tracks-redo",
+ icon: <Icon name="redo-2" size="1.25rem" />,
+ tooltip: labels.redo,
+ ariaLabel: labels.redo,
+ section: "bottom" as const,
+ order: 20,
+ disabled: !canRedo,
+ visible: hasPages,
+ onClick: onRedo,
+ },
+ {
+ id: "tracks-save",
+ tooltip: labels.save,
+ ariaLabel: labels.save,
+ section: "bottom" as const,
+ order: 30,
+ disabled: !isDirty || saving,
+ visible: hasPages,
+ onClick: onSave,
+ // Custom render for the unsaved-changes dot. A custom render also
+ // bypasses the bar's own tooltip wrapper, hence the Tooltip here.
+ render: ({ disabled, triggerAction }) => (
+ <Tooltip content={labels.save} position="bottom" offset={6} arrow>
+ <ActionIcon
+ variant="quiet"
+ hover={false}
+ // The bar's own class carries the muted colour and 24px clamp the
+ // default renderer would have applied.
+ className={`workbench-bar-action-icon ${styles.saveButton}`}
+ onClick={triggerAction}
+ disabled={disabled}
+ aria-label={labels.save}
+ >
+ <Icon name="save" size="1.5rem" />
+ {isDirty && <span className={styles.unsavedDot} aria-hidden />}
+ </ActionIcon>
+ </Tooltip>
+ ),
+ },
+ ],
+ [
+ labels.wrap,
+ labels.zoomIn,
+ labels.zoomOut,
+ selectAllLabel,
+ allSelected,
+ labels.selectByNumber,
+ labels.rotateLeft,
+ labels.rotateRight,
+ labels.deleteSelected,
+ labels.insertBlankAfter,
+ labels.splitAfter,
+ labels.undo,
+ labels.redo,
+ labels.save,
+ hasPages,
+ hasSelection,
+ canUndo,
+ canRedo,
+ isDirty,
+ saving,
+ wrap,
+ onToggleWrap,
+ canZoomIn,
+ canZoomOut,
+ onZoomIn,
+ onZoomOut,
+ onToggleSelectAll,
+ numberSelection,
+ onRotate,
+ onDelete,
+ onInsertBlankAfter,
+ onSplitAfter,
+ onUndo,
+ onRedo,
+ onSave,
+ ],
+ );
+
+ useWorkbenchBarButtons(buttons);
+}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts
new file mode 100644
index 0000000000..4f81d6ccf6
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackSave.ts
@@ -0,0 +1,243 @@
+import { useCallback, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { alert } from "@app/components/toast";
+import { useFileActions, useFileState } from "@app/contexts/FileContext";
+import {
+ createChildStub,
+ generateProcessedFileMetadata,
+} from "@app/contexts/file/fileActions";
+import { createStirlingFile, StirlingFileStub } from "@app/types/fileContext";
+import { FileId } from "@app/types/file";
+import {
+ PolicyBlockedError,
+ assertFilesNotBlocked,
+} from "@app/services/policyFileGuard";
+import { TrackWorkspace } from "@app/components/pageTracks/types";
+import {
+ buildTrackFile,
+ policyIdsForTracks,
+} from "@app/components/pageTracks/buildTrackFile";
+
+/**
+ * The page editor is a page-level rework of the open documents, which is what
+ * the Multi-Tool super tool has always represented in a file's history.
+ */
+const SAVE_TOOL_ID = "multiTool" as const;
+
+export interface TrackSaveProgress {
+ done: number;
+ total: number;
+}
+
+export interface TrackSaveOptions {
+ /**
+ * Called per committed file with its old and new ids. Saving replaces a file
+ * with a new version under a NEW id, so anything holding the old one (the
+ * viewer's active file, for instance) has to be re-pointed.
+ */
+ onVersioned?: (previousId: FileId, nextId: FileId) => void;
+ /**
+ * Called once a save has written its split tracks to their own new files.
+ * `dropTrackIds` are the synthetic split tracks to drop (their new files
+ * re-enter the workspace via sync); `order` is the sequence the workspace
+ * should take once those files arrive, so a saved file lands back in its old
+ * slot rather than at the end.
+ */
+ onMaterialized?: (result: {
+ dropTrackIds: FileId[];
+ order: FileId[];
+ /** Each new split file and the open file it should follow. */
+ placements: { fileId: FileId; afterFileId: FileId | null }[];
+ }) => void;
+}
+
+export interface TrackSaveHook {
+ saving: boolean;
+ progress: TrackSaveProgress | null;
+ /**
+ * Writes changed tracks back as a new version of their own file: all of them,
+ * or only those in `trackIds`. Resolves to each versioned file's old id mapped
+ * to its new one, or null if nothing was saved.
+ */
+ save: (trackIds?: FileId[]) => Promise<Map<FileId, FileId> | null>;
+}
+
+interface BuiltTrack {
+ /** The workspace track id (synthetic for a split). */
+ trackId: FileId;
+ /** The file to version, or null for a split that becomes a brand-new file. */
+ inputFileId: FileId | null;
+ parentStub: StirlingFileStub;
+ file: File;
+}
+
+export function useTrackSave(
+ workspace: TrackWorkspace,
+ changedFileIds: FileId[],
+ options: TrackSaveOptions = {},
+): TrackSaveHook {
+ const { selectors } = useFileState();
+ const { actions } = useFileActions();
+ const { t } = useTranslation();
+ const onVersionedRef = useRef(options.onVersioned);
+ onVersionedRef.current = options.onVersioned;
+ const onMaterializedRef = useRef(options.onMaterialized);
+ onMaterializedRef.current = options.onMaterialized;
+ const [saving, setSaving] = useState(false);
+ const [progress, setProgress] = useState<TrackSaveProgress | null>(null);
+
+ const save = useCallback(
+ async (trackIds?: FileId[]) => {
+ const toSave = trackIds
+ ? changedFileIds.filter((id) => trackIds.includes(id))
+ : changedFileIds;
+ if (saving || toSave.length === 0) return null;
+
+ // A file-backed track emptied of every page has nothing to version.
+ const emptied = toSave.filter((id) => {
+ const track = workspace.tracks[id];
+ return track != null && !track.isNew && track.pages.length === 0;
+ });
+ const rebuilt = toSave.filter(
+ (id) => (workspace.tracks[id]?.pages.length ?? 0) > 0,
+ );
+
+ setSaving(true);
+ setProgress({ done: 0, total: rebuilt.length });
+ const policyIds = policyIdsForTracks(
+ workspace,
+ rebuilt,
+ selectors.getStirlingFileStub,
+ );
+
+ try {
+ assertFilesNotBlocked(policyIds);
+ // Build every output first: a track can hold pages belonging to another
+ // track's file, and committing as we go would swap those bytes out from
+ // under a later build.
+ const built: BuiltTrack[] = [];
+ for (const id of rebuilt) {
+ const track = workspace.tracks[id];
+ if (!track) continue;
+ const output = await buildTrackFile(track, {
+ getStub: selectors.getStirlingFileStub,
+ getFile: selectors.getFile,
+ });
+ if (!output) continue;
+ built.push({
+ trackId: id,
+ inputFileId: track.isNew ? null : id,
+ ...output,
+ });
+ setProgress({ done: built.length, total: rebuilt.length });
+ }
+
+ // A policy can fail while the outputs are being built.
+ assertFilesNotBlocked(policyIds);
+
+ // Version each file-backed track in place (a new version of its own
+ // file). One at a time so each lands in its own slot rather than clumping
+ // at the top of the file list.
+ const versioned = new Map<FileId, FileId>();
+ for (const entry of built) {
+ if (entry.inputFileId == null) continue;
+ const processedFile = await generateProcessedFileMetadata(entry.file);
+ const outputStub = createChildStub(
+ entry.parentStub,
+ { toolId: SAVE_TOOL_ID, timestamp: Date.now() },
+ entry.file,
+ processedFile?.thumbnailUrl,
+ processedFile,
+ );
+ await actions.consumeFiles(
+ [entry.inputFileId],
+ [createStirlingFile(entry.file, outputStub.id)],
+ [outputStub],
+ { silent: true },
+ );
+ versioned.set(entry.inputFileId, outputStub.id);
+ onVersionedRef.current?.(entry.inputFileId, outputStub.id);
+ }
+
+ // A split becomes a brand-new active file, exactly like the Multi-Tool's
+ // apply: add the fresh files so they enter the workbench (and the
+ // workspace, via sync) as their own tracks.
+ const splitEntries = built.filter((entry) => entry.inputFileId == null);
+ const materializedIds = new Map<FileId, FileId>();
+ if (splitEntries.length > 0) {
+ const added = await actions.addFiles(
+ splitEntries.map((entry) => entry.file),
+ { selectFiles: false, skipUploadTracking: true },
+ );
+ // addFiles preserves input order (PDFs, auto-unzip skipped), so each
+ // new file lines up with the split track it was built from.
+ splitEntries.forEach((entry, index) => {
+ const file = added[index];
+ if (file) materializedIds.set(entry.trackId, file.fileId);
+ });
+ }
+
+ if (emptied.length > 0) {
+ // Every page moved out, so there is nothing left to version. Drop the
+ // file from the workbench but keep it in storage at its last version.
+ await actions.removeFiles(emptied, false);
+ }
+
+ // Put the saved files back where their tracks sat: a version and a
+ // materialised split each take a new id that sync would otherwise append
+ // at the end, so hand the editor the order to settle into. The synthetic
+ // split tracks are dropped so their new files take their place.
+ if (materializedIds.size > 0) {
+ const emptiedSet = new Set(emptied);
+ const order = workspace.order.flatMap((id) => {
+ if (emptiedSet.has(id)) return [];
+ return [versioned.get(id) ?? materializedIds.get(id) ?? id];
+ });
+ // Each new split file should sit right after its source in the open-
+ // file list (the source may itself have been versioned to a new id).
+ const placements = [...materializedIds.entries()].map(
+ ([trackId, fileId]) => {
+ const source = workspace.tracks[trackId]?.splitFromFileId;
+ return {
+ fileId,
+ afterFileId: source ? (versioned.get(source) ?? source) : null,
+ };
+ },
+ );
+ onMaterializedRef.current?.({
+ dropTrackIds: [...materializedIds.keys()],
+ order,
+ placements,
+ });
+ }
+
+ return versioned;
+ } catch (error) {
+ if (error instanceof PolicyBlockedError) {
+ alert({
+ alertType: "warning",
+ title: t("policy.recoveryTitle"),
+ body: t("policy.recoveryBody"),
+ });
+ } else {
+ console.error("[PageTracks] save failed", error);
+ alert({
+ alertType: "error",
+ title: t("pageTracks.saveFailed.title", "Couldn't save changes"),
+ body: t(
+ "pageTracks.saveFailed.body",
+ "Your edits haven't been lost. Try saving again.",
+ ),
+ });
+ }
+ return null;
+ } finally {
+ setSaving(false);
+ setProgress(null);
+ }
+ },
+ [actions, changedFileIds, saving, selectors, t, workspace],
+ );
+
+ return { saving, progress, save };
+}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackSelection.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackSelection.ts
new file mode 100644
index 0000000000..bfa692b6cc
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackSelection.ts
@@ -0,0 +1,146 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { FileId } from "@app/types/file";
+import { TrackWorkspace, allPages } from "@app/components/pageTracks/types";
+
+export interface PageClickModifiers {
+ /** Extend the selection from the last clicked page in the same track. */
+ shift: boolean;
+}
+
+export interface TrackSelectionHook {
+ selectedIds: Set<string>;
+ selectedCount: number;
+ selectPage: (
+ fileId: FileId,
+ pageId: string,
+ modifiers: PageClickModifiers,
+ ) => void;
+ setSelection: (pageIds: string[]) => void;
+ selectAll: () => void;
+ selectTrack: (fileId: FileId) => void;
+ clear: () => void;
+ /** Selected pages that live in this track, in track order. */
+ idsInTrack: (fileId: FileId) => string[];
+}
+
+export function useTrackSelection(
+ workspace: TrackWorkspace,
+): TrackSelectionHook {
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(
+ () => new Set<string>(),
+ );
+ const anchorRef = useRef<{ fileId: FileId; pageId: string } | null>(null);
+ // Read through a ref so the click handler stays referentially stable: it is
+ // passed down to every tile, and a new identity per edit would re-render the
+ // whole workspace.
+ const workspaceRef = useRef(workspace);
+ workspaceRef.current = workspace;
+
+ const livePageIds = useMemo(
+ () => new Set(allPages(workspace).map((page) => page.id)),
+ [workspace],
+ );
+
+ // Deleted, undone and re-synced pages must drop out of the selection or the
+ // action buttons stay enabled for pages that no longer exist.
+ useEffect(() => {
+ setSelectedIds((prev) => {
+ if (prev.size === 0) return prev;
+ const next = new Set<string>();
+ prev.forEach((id) => {
+ if (livePageIds.has(id)) next.add(id);
+ });
+ return next.size === prev.size ? prev : next;
+ });
+ if (anchorRef.current && !livePageIds.has(anchorRef.current.pageId)) {
+ anchorRef.current = null;
+ }
+ }, [livePageIds]);
+
+ /**
+ * A click toggles the page in or out of the selection, so pages accumulate
+ * without a modifier: picking a set to rotate or move is the whole job here,
+ * and replace-on-click would make anything past the first page a fight.
+ * Shift extends from the last clicked page instead.
+ */
+ const selectPage = useCallback(
+ (fileId: FileId, pageId: string, modifiers: PageClickModifiers) => {
+ const trackPages = workspaceRef.current.tracks[fileId]?.pages ?? [];
+ const anchor = anchorRef.current;
+
+ // Shift only ranges within one track: a range across tracks has no
+ // single ordering the user could predict.
+ if (modifiers.shift && anchor && anchor.fileId === fileId) {
+ const from = trackPages.findIndex((p) => p.id === anchor.pageId);
+ const to = trackPages.findIndex((p) => p.id === pageId);
+ if (from !== -1 && to !== -1) {
+ const [start, end] = from <= to ? [from, to] : [to, from];
+ const range = trackPages.slice(start, end + 1).map((p) => p.id);
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ range.forEach((id) => next.add(id));
+ return next;
+ });
+ // Anchor stays put so repeated shift-clicks re-extend from it.
+ return;
+ }
+ }
+
+ anchorRef.current = { fileId, pageId };
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(pageId)) next.delete(pageId);
+ else next.add(pageId);
+ return next;
+ });
+ },
+ [],
+ );
+
+ const setSelection = useCallback((pageIds: string[]) => {
+ setSelectedIds(new Set(pageIds));
+ }, []);
+
+ const selectAll = useCallback(() => {
+ setSelectedIds(new Set(livePageIds));
+ }, [livePageIds]);
+
+ const selectTrack = useCallback(
+ (fileId: FileId) => {
+ const trackPages = workspaceRef.current.tracks[fileId]?.pages ?? [];
+ const ids = trackPages.map((p) => p.id);
+ const allSelected =
+ ids.length > 0 && ids.every((id) => selectedIds.has(id));
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ ids.forEach((id) => (allSelected ? next.delete(id) : next.add(id)));
+ return next;
+ });
+ },
+ [selectedIds],
+ );
+
+ const clear = useCallback(() => {
+ setSelectedIds(new Set());
+ anchorRef.current = null;
+ }, []);
+
+ const idsInTrack = useCallback(
+ (fileId: FileId) =>
+ (workspace.tracks[fileId]?.pages ?? [])
+ .filter((page) => selectedIds.has(page.id))
+ .map((page) => page.id),
+ [workspace, selectedIds],
+ );
+
+ return {
+ selectedIds,
+ selectedCount: selectedIds.size,
+ selectPage,
+ setSelection,
+ selectAll,
+ selectTrack,
+ clear,
+ idsInTrack,
+ };
+}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.ts
new file mode 100644
index 0000000000..0f26487a3d
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.ts
@@ -0,0 +1,172 @@
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useSyncExternalStore,
+} from "react";
+import { useFileSelectors } from "@app/contexts/FileContext";
+import { useThumbnailGeneration } from "@app/hooks/useThumbnailGeneration";
+import {
+ SourceTrackPage,
+ TrackPage,
+ isSourcePage,
+ sourcePageKey,
+} from "@app/components/pageTracks/types";
+
+/** Pre-load a screen's worth either side so sideways scrolling stays smooth. */
+const ROOT_MARGIN = "300px";
+const MAX_IN_FLIGHT = 12;
+const NOTIFY_MS = 60;
+
+export interface TrackThumbnailStore {
+ subscribe: (listener: () => void) => () => void;
+ get: (key: string) => string | null;
+ /** Ref callback for a page tile, driving lazy loading via intersection.
+ * A blank page has nothing to render and is not observed. */
+ observe: (page: TrackPage) => (element: HTMLElement | null) => void;
+}
+
+/**
+ * Renders page thumbnails on demand, keyed by source page rather than by track
+ * position, so a page keeps its image when it is moved, reordered or undone.
+ *
+ * Results live outside React state: a track can hold thousands of pages, and
+ * pushing each arriving thumbnail through a prop would re-render every tile in
+ * the track. Tiles subscribe individually via {@link useTrackThumbnail}.
+ */
+export function useTrackThumbnails(): TrackThumbnailStore {
+ const selectors = useFileSelectors();
+ const { requestThumbnail, getThumbnailFromCache } = useThumbnailGeneration();
+
+ const resolvedRef = useRef(new Map<string, string>());
+ const listenersRef = useRef(new Set<() => void>());
+ const inFlightRef = useRef(new Set<string>());
+ const queueRef = useRef<SourceTrackPage[]>([]);
+ const notifyTimerRef = useRef<number | null>(null);
+ const observerRef = useRef<IntersectionObserver | null>(null);
+ const pageByElementRef = useRef(new Map<Element, SourceTrackPage>());
+ const elementByKeyRef = useRef(new Map<string, Element>());
+
+ const scheduleNotify = useCallback(() => {
+ if (notifyTimerRef.current != null) return;
+ notifyTimerRef.current = window.setTimeout(() => {
+ notifyTimerRef.current = null;
+ listenersRef.current.forEach((listener) => listener());
+ }, NOTIFY_MS);
+ }, []);
+
+ const pump = useCallback(() => {
+ while (
+ inFlightRef.current.size < MAX_IN_FLIGHT &&
+ queueRef.current.length > 0
+ ) {
+ const page = queueRef.current.shift();
+ if (!page) break;
+ const key = sourcePageKey(page);
+ if (resolvedRef.current.has(key) || inFlightRef.current.has(key))
+ continue;
+
+ const cached = getThumbnailFromCache(key);
+ if (cached) {
+ resolvedRef.current.set(key, cached);
+ scheduleNotify();
+ continue;
+ }
+
+ const file = selectors.getFile(page.sourceFileId);
+ if (!file) continue;
+
+ inFlightRef.current.add(key);
+ requestThumbnail(key, file, page.sourcePageNumber)
+ .then((thumbnail) => {
+ if (thumbnail) {
+ resolvedRef.current.set(key, thumbnail);
+ scheduleNotify();
+ }
+ })
+ .catch((error) => {
+ console.error("[PageTracks] thumbnail failed", error);
+ })
+ .finally(() => {
+ inFlightRef.current.delete(key);
+ pump();
+ });
+ }
+ }, [getThumbnailFromCache, requestThumbnail, scheduleNotify, selectors]);
+
+ const enqueue = useCallback(
+ (page: SourceTrackPage) => {
+ const key = sourcePageKey(page);
+ if (resolvedRef.current.has(key) || inFlightRef.current.has(key)) return;
+ if (queueRef.current.some((queued) => sourcePageKey(queued) === key))
+ return;
+ queueRef.current.push(page);
+ pump();
+ },
+ [pump],
+ );
+
+ useEffect(() => {
+ const observer = new IntersectionObserver(
+ (entries) => {
+ entries.forEach((entry) => {
+ if (!entry.isIntersecting) return;
+ const page = pageByElementRef.current.get(entry.target);
+ if (page) enqueue(page);
+ });
+ },
+ { rootMargin: ROOT_MARGIN },
+ );
+ observerRef.current = observer;
+ return () => {
+ observer.disconnect();
+ observerRef.current = null;
+ pageByElementRef.current.clear();
+ elementByKeyRef.current.clear();
+ if (notifyTimerRef.current != null) {
+ window.clearTimeout(notifyTimerRef.current);
+ notifyTimerRef.current = null;
+ }
+ };
+ }, [enqueue]);
+
+ return useMemo<TrackThumbnailStore>(
+ () => ({
+ subscribe: (listener) => {
+ listenersRef.current.add(listener);
+ return () => listenersRef.current.delete(listener);
+ },
+ get: (key) => resolvedRef.current.get(key) ?? null,
+ observe: (page) => (element) => {
+ if (!isSourcePage(page)) return;
+ const observer = observerRef.current;
+ const key = sourcePageKey(page);
+ const previous = elementByKeyRef.current.get(key);
+ if (previous && previous !== element) {
+ observer?.unobserve(previous);
+ pageByElementRef.current.delete(previous);
+ elementByKeyRef.current.delete(key);
+ }
+ if (!element) return;
+ elementByKeyRef.current.set(key, element);
+ pageByElementRef.current.set(element, page);
+ observer?.observe(element);
+ },
+ }),
+ [],
+ );
+}
+
+/** Subscribes a single tile to its own page's thumbnail. */
+export function useTrackThumbnail(
+ store: TrackThumbnailStore,
+ page: TrackPage,
+): string | null {
+ const key = isSourcePage(page) ? sourcePageKey(page) : null;
+ return useSyncExternalStore(
+ store.subscribe,
+ () => (key == null ? null : store.get(key)),
+ () => null,
+ );
+}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
new file mode 100644
index 0000000000..e35275d602
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts
@@ -0,0 +1,113 @@
+import { useCallback, useEffect, useMemo, useReducer } from "react";
+import { useFileState } from "@app/contexts/FileContext";
+import { FileId } from "@app/types/file";
+import { PageSize, TrackSource } from "@app/components/pageTracks/types";
+import { ProcessedFilePage } from "@app/types/fileContext";
+import {
+ changedTrackIds,
+ initialTrackEditorState,
+ TrackEditorAction,
+ TrackEditorState,
+ trackEditorReducer,
+} from "@app/components/pageTracks/trackWorkspaceReducer";
+
+export interface TrackWorkspaceHook {
+ state: TrackEditorState;
+ dispatch: (action: TrackEditorAction) => void;
+ /** PDFs that are open but whose page metadata hasn't been read yet. */
+ pendingFileIds: FileId[];
+ /** Open files the page editor can't edit (not PDFs); shown as disabled tracks. */
+ unsupportedFileIds: FileId[];
+ /** True when any open file is a PDF (drives the empty state). */
+ hasPdfFiles: boolean;
+ changedFileIds: FileId[];
+ isDirty: boolean;
+ canUndo: boolean;
+ canRedo: boolean;
+}
+
+/** PDFium reports the size as displayed, after the page's /Rotate. */
+function unrotatedSize(page: ProcessedFilePage): PageSize {
+ const width = page.width ?? 0;
+ const height = page.height ?? 0;
+ const quarterTurn = (page.rotation ?? 0) % 180 !== 0;
+ return quarterTurn ? { width: height, height: width } : { width, height };
+}
+
+const isPdf = (name: string | undefined): boolean =>
+ name?.toLowerCase().endsWith(".pdf") ?? false;
+
+export function useTrackWorkspace(): TrackWorkspaceHook {
+ const { state: fileState } = useFileState();
+ const [state, dispatch] = useReducer(
+ trackEditorReducer,
+ initialTrackEditorState,
+ );
+
+ // Only files whose page metadata has been hydrated can be expanded into a
+ // track: the per-page /Rotate baseline comes from it, and assuming 0 would
+ // silently un-rotate pre-rotated pages on save.
+ const { sources, pendingFileIds, unsupportedFileIds, hasPdfFiles } =
+ useMemo(() => {
+ const resolved: TrackSource[] = [];
+ const pending: FileId[] = [];
+ const unsupported: FileId[] = [];
+ let anyPdf = false;
+
+ for (const fileId of fileState.files.ids) {
+ const stub = fileState.files.byId[fileId];
+ // The page editor works on PDF pages; other open files show as disabled
+ // tracks so they are visible but clearly not editable here.
+ if (!isPdf(stub?.name)) {
+ unsupported.push(fileId);
+ continue;
+ }
+ anyPdf = true;
+
+ const pages = stub?.processedFile?.pages;
+ if (!pages || pages.length === 0) {
+ pending.push(fileId);
+ continue;
+ }
+
+ resolved.push({
+ fileId,
+ name: stub?.name ?? fileId,
+ pageCount: pages.length,
+ rotations: pages.map((page) => page.rotation ?? 0),
+ sizes: pages.map(unrotatedSize),
+ contentKey: `${stub?.size ?? 0}:${stub?.lastModified ?? 0}`,
+ });
+ }
+
+ return {
+ sources: resolved,
+ pendingFileIds: pending,
+ unsupportedFileIds: unsupported,
+ hasPdfFiles: anyPdf,
+ };
+ }, [fileState.files]);
+
+ useEffect(() => {
+ dispatch({ type: "sync", sources });
+ }, [sources]);
+
+ const changedFileIds = useMemo(() => changedTrackIds(state), [state]);
+
+ const stableDispatch = useCallback(
+ (action: TrackEditorAction) => dispatch(action),
+ [],
+ );
+
+ return {
+ state,
+ dispatch: stableDispatch,
+ pendingFileIds,
+ unsupportedFileIds,
+ hasPdfFiles,
+ changedFileIds,
+ isDirty: changedFileIds.length > 0,
+ canUndo: state.past.length > 0,
+ canRedo: state.future.length > 0,
+ };
+}
diff --git a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
new file mode 100644
index 0000000000..929ce299e1
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
@@ -0,0 +1,642 @@
+import { describe, expect, it } from "vitest";
+
+import { FileId } from "@app/types/file";
+import {
+ TrackSource,
+ isSourcePage,
+ sourcePageKey,
+ trackSignature,
+} from "@app/components/pageTracks/types";
+import {
+ TrackEditorState,
+ changedTrackIds,
+ initialTrackEditorState,
+ trackEditorReducer,
+} from "@app/components/pageTracks/trackWorkspaceReducer";
+
+const A = "file-a" as FileId;
+const B = "file-b" as FileId;
+
+const source = (
+ fileId: FileId,
+ pageCount: number,
+ rotations: number[] = [],
+ contentKey = "v1",
+ sizes: { width: number; height: number }[] = [],
+): TrackSource => ({
+ fileId,
+ name: `${fileId}.pdf`,
+ pageCount,
+ rotations: Array.from({ length: pageCount }, (_, i) => rotations[i] ?? 0),
+ sizes: Array.from(
+ { length: pageCount },
+ (_, i) => sizes[i] ?? { width: 0, height: 0 },
+ ),
+ contentKey,
+});
+
+const sync = (state: TrackEditorState, sources: TrackSource[]) =>
+ trackEditorReducer(state, { type: "sync", sources });
+
+const pagesOf = (state: TrackEditorState, fileId: FileId) =>
+ state.present.tracks[fileId]?.pages ?? [];
+
+const ids = (state: TrackEditorState, fileId: FileId) =>
+ pagesOf(state, fileId).map((p) =>
+ isSourcePage(p) ? `${p.sourceFileId}:${p.sourcePageNumber}` : "blank",
+ );
+
+/** Two files: A with 3 pages (middle one pre-rotated 90), B with 2. */
+function twoTracks(): TrackEditorState {
+ return sync(initialTrackEditorState, [
+ source(A, 3, [0, 90, 0]),
+ source(B, 2),
+ ]);
+}
+
+describe("trackEditorReducer sync", () => {
+ it("expands each file into its own track and seeds source rotations", () => {
+ const state = twoTracks();
+ expect(state.present.order).toEqual([A, B]);
+ expect(pagesOf(state, A).map((p) => p.rotation)).toEqual([0, 90, 0]);
+ expect(pagesOf(state, B)).toHaveLength(2);
+ expect(changedTrackIds(state)).toEqual([]);
+ });
+
+ it("keeps pending edits and their dirty state when another file opens", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, A)[0].id],
+ });
+ expect(changedTrackIds(state)).toEqual([A]);
+
+ const C = "file-c" as FileId;
+ state = sync(state, [source(A, 3, [0, 90, 0]), source(B, 2), source(C, 1)]);
+
+ expect(pagesOf(state, A)).toHaveLength(2);
+ // Re-baselining everything here would mark the pending delete as saved.
+ expect(changedTrackIds(state)).toEqual([A]);
+ });
+
+ it("rebuilds a track whose underlying file changed, discarding its edits", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, A)[0].id],
+ });
+ state = sync(state, [source(A, 5), source(B, 2)]);
+
+ expect(pagesOf(state, A)).toHaveLength(5);
+ expect(changedTrackIds(state)).toEqual([]);
+ });
+
+ it("rebuilds a track whose bytes were replaced with the same page layout", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, A)[0].id],
+ });
+ const keysOf = (current: TrackEditorState) =>
+ pagesOf(current, A).filter(isSourcePage).map(sourcePageKey);
+ const [staleKey] = keysOf(state);
+
+ state = sync(state, [source(A, 3, [0, 90, 0], "v2"), source(B, 2)]);
+
+ expect(pagesOf(state, A)).toHaveLength(3);
+ expect(changedTrackIds(state)).toEqual([]);
+ expect(state.past).toEqual([]);
+ // A thumbnail cached for the old bytes must not be served for the new ones.
+ expect(keysOf(state)).not.toContain(staleKey);
+ });
+
+ it("voids the edits of every track sharing pages with a replaced file", () => {
+ const C = "file-c" as FileId;
+ let state = sync(initialTrackEditorState, [
+ source(A, 3),
+ source(B, 2),
+ source(C, 2),
+ ]);
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: [pagesOf(state, A)[0].id],
+ targetFileId: B,
+ beforePageId: null,
+ });
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, C)[0].id],
+ });
+
+ state = sync(state, [source(A, 3, [], "v2"), source(B, 2), source(C, 2)]);
+
+ // The page moved out of A goes home rather than vanishing or duplicating.
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, `${A}:3`]);
+ expect(ids(state, B)).toEqual([`${B}:1`, `${B}:2`]);
+ expect(changedTrackIds(state)).toEqual([C]);
+ });
+
+ it("drops a split of a replaced file, returning its pages", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "split",
+ fileId: A,
+ startPageId: pagesOf(state, A)[1].id,
+ });
+ expect(state.present.order).toHaveLength(3);
+
+ state = sync(state, [source(A, 3, [0, 90, 0], "v2"), source(B, 2)]);
+
+ expect(state.present.order).toEqual([A, B]);
+ expect(pagesOf(state, A)).toHaveLength(3);
+ });
+
+ it("drops pages sourced from a file that is no longer open", () => {
+ let state = twoTracks();
+ const moved = pagesOf(state, B).map((p) => p.id);
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: moved,
+ targetFileId: A,
+ beforePageId: null,
+ });
+ expect(pagesOf(state, A)).toHaveLength(5);
+
+ state = sync(state, [source(A, 3, [0, 90, 0])]);
+
+ expect(state.present.order).toEqual([A]);
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, `${A}:3`]);
+ });
+});
+
+describe("trackEditorReducer operations", () => {
+ it("rotates only the given pages, normalising past a full turn", () => {
+ let state = twoTracks();
+ const [first, second] = pagesOf(state, A);
+ state = trackEditorReducer(state, {
+ type: "rotate",
+ pageIds: [first.id, second.id],
+ delta: 270,
+ });
+ expect(pagesOf(state, A).map((p) => p.rotation)).toEqual([270, 0, 0]);
+ });
+
+ it("moves a selection into another track, preserving its order", () => {
+ let state = twoTracks();
+ const [a1, , a3] = pagesOf(state, A);
+ const b2 = pagesOf(state, B)[1];
+
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: [a3.id, a1.id],
+ targetFileId: B,
+ beforePageId: b2.id,
+ });
+
+ // Order follows the workspace, not the order the ids were passed in.
+ expect(ids(state, B)).toEqual([`${B}:1`, `${A}:1`, `${A}:3`, `${B}:2`]);
+ expect(ids(state, A)).toEqual([`${A}:2`]);
+ expect(changedTrackIds(state)).toEqual([A, B]);
+ });
+
+ it("reorders within a track when the anchor is the moved page itself", () => {
+ let state = twoTracks();
+ const before = trackSignature(pagesOf(state, A));
+ const [a1] = pagesOf(state, A);
+
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: [a1.id],
+ targetFileId: A,
+ beforePageId: a1.id,
+ });
+
+ // A no-op drop must not register as an edit or fill the undo stack.
+ expect(trackSignature(pagesOf(state, A))).toEqual(before);
+ expect(state.past).toHaveLength(0);
+ expect(changedTrackIds(state)).toEqual([]);
+ });
+
+ it("shifts a page one place within its track, stopping at either end", () => {
+ let state = twoTracks();
+ const [a1] = pagesOf(state, A);
+ state = trackEditorReducer(state, {
+ type: "shiftPage",
+ pageId: a1.id,
+ by: 1,
+ });
+ expect(ids(state, A)).toEqual([`${A}:2`, `${A}:1`, `${A}:3`]);
+ expect(changedTrackIds(state)).toEqual([A]);
+
+ state = trackEditorReducer(state, {
+ type: "shiftPage",
+ pageId: a1.id,
+ by: -1,
+ });
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, `${A}:3`]);
+
+ const atStart = trackEditorReducer(state, {
+ type: "shiftPage",
+ pageId: a1.id,
+ by: -1,
+ });
+ expect(atStart).toBe(state);
+ });
+
+ it("appends when the anchor is null", () => {
+ let state = twoTracks();
+ const [a1] = pagesOf(state, A);
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: [a1.id],
+ targetFileId: A,
+ beforePageId: null,
+ });
+ expect(ids(state, A)).toEqual([`${A}:2`, `${A}:3`, `${A}:1`]);
+ });
+
+ it("empties a track without removing it, so save can close the file", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: pagesOf(state, B).map((p) => p.id),
+ });
+ expect(state.present.order).toContain(B);
+ expect(pagesOf(state, B)).toEqual([]);
+ expect(changedTrackIds(state)).toEqual([B]);
+ });
+});
+
+describe("trackEditorReducer split", () => {
+ it("splits a track in two, the new one sourced from the original", () => {
+ let state = twoTracks();
+ const a2 = pagesOf(state, A)[1];
+ state = trackEditorReducer(state, {
+ type: "split",
+ fileId: A,
+ startPageId: a2.id,
+ });
+
+ // The new track is inserted right after the one it came from.
+ const newId = state.present.order[1];
+ expect(state.present.order).toEqual([A, newId, B]);
+ expect(pagesOf(state, A)).toHaveLength(1);
+ expect(ids(state, newId)).toEqual([`${A}:2`, `${A}:3`]);
+ expect(state.present.tracks[newId]?.isNew).toBe(true);
+ // Both the shortened original and the new split are pending.
+ expect(changedTrackIds(state)).toContain(A);
+ expect(changedTrackIds(state)).toContain(newId);
+ });
+
+ it("ignores a split before the first page", () => {
+ const state = twoTracks();
+ const a1 = pagesOf(state, A)[0];
+ const next = trackEditorReducer(state, {
+ type: "split",
+ fileId: A,
+ startPageId: a1.id,
+ });
+ expect(next).toBe(state);
+ });
+
+ it("is undoable", () => {
+ let state = twoTracks();
+ const a2 = pagesOf(state, A)[1];
+ state = trackEditorReducer(state, {
+ type: "split",
+ fileId: A,
+ startPageId: a2.id,
+ });
+ expect(state.present.order).toHaveLength(3);
+
+ state = trackEditorReducer(state, { type: "undo" });
+ expect(state.present.order).toEqual([A, B]);
+ expect(pagesOf(state, A)).toHaveLength(3);
+ });
+
+ it("keeps the split through a sync, and drops it on request", () => {
+ let state = twoTracks();
+ const a2 = pagesOf(state, A)[1];
+ state = trackEditorReducer(state, {
+ type: "split",
+ fileId: A,
+ startPageId: a2.id,
+ });
+ const newId = state.present.order[1];
+
+ const C = "file-c" as FileId;
+ state = sync(state, [source(A, 3, [0, 90, 0]), source(B, 2), source(C, 1)]);
+ // The split is not derived from a file, so a sync leaves it in place.
+ expect(state.present.order).toContain(newId);
+ expect(ids(state, newId)).toEqual([`${A}:2`, `${A}:3`]);
+
+ state = trackEditorReducer(state, { type: "dropTracks", fileIds: [newId] });
+ expect(state.present.order).not.toContain(newId);
+ });
+});
+
+describe("trackEditorReducer splitAfterSelected", () => {
+ it("cuts a track after each selected page, the tails becoming new tracks", () => {
+ let state = twoTracks();
+ const [a1, a2] = pagesOf(state, A);
+ state = trackEditorReducer(state, {
+ type: "splitAfterSelected",
+ pageIds: [a1.id, a2.id],
+ });
+
+ const [, new1, new2] = state.present.order;
+ expect(state.present.order).toEqual([A, new1, new2, B]);
+ expect(ids(state, A)).toEqual([`${A}:1`]);
+ expect(ids(state, new1)).toEqual([`${A}:2`]);
+ expect(ids(state, new2)).toEqual([`${A}:3`]);
+ expect(state.present.tracks[new1]?.isNew).toBe(true);
+ expect(state.present.tracks[new2]?.isNew).toBe(true);
+ // B held no selected page, so it is untouched.
+ expect(ids(state, B)).toEqual([`${B}:1`, `${B}:2`]);
+ });
+
+ it("ignores a selected last page, which would only make an empty tail", () => {
+ const state = twoTracks();
+ const a3 = pagesOf(state, A)[2];
+ const next = trackEditorReducer(state, {
+ type: "splitAfterSelected",
+ pageIds: [a3.id],
+ });
+ expect(next).toBe(state);
+ });
+});
+
+describe("trackEditorReducer reconcileAfterSave", () => {
+ it("slots a saved split's new file back beside its source, not at the end", () => {
+ const C = "file-c" as FileId;
+ const BNew = "file-b2" as FileId;
+ const Split = "file-split" as FileId;
+
+ // Three files; split B so a synthetic track sits right after it.
+ let state = sync(initialTrackEditorState, [
+ source(A, 2),
+ source(B, 3),
+ source(C, 1),
+ ]);
+ const b2 = pagesOf(state, B)[1];
+ state = trackEditorReducer(state, {
+ type: "split",
+ fileId: B,
+ startPageId: b2.id,
+ });
+ const splitId = state.present.order[2];
+ expect(state.present.order).toEqual([A, B, splitId, C]);
+
+ // Saving versions B (new id) and writes the split to its own file; the
+ // editor is handed the order those new files should land in.
+ state = trackEditorReducer(state, {
+ type: "reconcileAfterSave",
+ dropTrackIds: [splitId],
+ order: [A, BNew, Split, C],
+ });
+
+ // The new files arrive: B is gone, BNew and Split are fresh sources.
+ state = sync(state, [
+ source(A, 2),
+ source(BNew, 1),
+ source(Split, 2),
+ source(C, 1),
+ ]);
+
+ expect(state.present.order).toEqual([A, BNew, Split, C]);
+ expect(state.pendingOrder).toBeNull();
+ });
+});
+
+describe("trackEditorReducer revert", () => {
+ it("reverts a file's track and every track it swapped pages with, keeping the rest", () => {
+ const C = "file-c" as FileId;
+ let state = sync(initialTrackEditorState, [
+ source(A, 3),
+ source(B, 2),
+ source(C, 2),
+ ]);
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: [pagesOf(state, A)[0].id],
+ targetFileId: B,
+ beforePageId: null,
+ });
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, C)[0].id],
+ });
+
+ state = trackEditorReducer(state, { type: "revert", fileIds: [A] });
+
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, `${A}:3`]);
+ expect(ids(state, B)).toEqual([`${B}:1`, `${B}:2`]);
+ expect(changedTrackIds(state)).toEqual([C]);
+ expect(state.past).toEqual([]);
+ });
+
+ it("drops a split of the reverted file, returning its pages", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "split",
+ fileId: A,
+ startPageId: pagesOf(state, A)[1].id,
+ });
+
+ state = trackEditorReducer(state, { type: "revert", fileIds: [A] });
+
+ expect(state.present.order).toEqual([A, B]);
+ expect(pagesOf(state, A)).toHaveLength(3);
+ expect(changedTrackIds(state)).toEqual([]);
+ });
+});
+
+describe("trackEditorReducer insertBlank", () => {
+ const LETTER = { width: 612, height: 792 };
+ const LANDSCAPE = { width: 842, height: 595 };
+
+ it("sizes and turns a blank page like the page before it", () => {
+ let state = sync(initialTrackEditorState, [
+ source(A, 2, [0, 90], "v1", [LETTER, LANDSCAPE]),
+ ]);
+ const [, a2] = pagesOf(state, A);
+ state = trackEditorReducer(state, {
+ type: "insertBlank",
+ fileId: A,
+ beforePageId: null,
+ });
+
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, "blank"]);
+ const blank = pagesOf(state, A)[2];
+ expect(blank).toMatchObject({ kind: "blank", rotation: 90, ...LANDSCAPE });
+ expect(blank.id).not.toBe(a2.id);
+ expect(changedTrackIds(state)).toEqual([A]);
+
+ state = trackEditorReducer(state, { type: "undo" });
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`]);
+ });
+
+ it("copies the page after it when inserted at the start", () => {
+ let state = sync(initialTrackEditorState, [
+ source(A, 2, [0, 0], "v1", [LETTER, LANDSCAPE]),
+ ]);
+ state = trackEditorReducer(state, {
+ type: "insertBlank",
+ fileId: A,
+ beforePageId: pagesOf(state, A)[0].id,
+ });
+
+ expect(ids(state, A)).toEqual(["blank", `${A}:1`, `${A}:2`]);
+ expect(pagesOf(state, A)[0]).toMatchObject(LETTER);
+ });
+
+ it("falls back to A4 when the neighbour's size is unknown", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "insertBlank",
+ fileId: A,
+ beforePageId: pagesOf(state, A)[1].id,
+ });
+
+ const blank = pagesOf(state, A)[1];
+ expect(blank.width).toBeCloseTo(595.28);
+ expect(blank.height).toBeCloseTo(841.89);
+ });
+
+ it("gives every blank page its own id", () => {
+ let state = twoTracks();
+ for (let i = 0; i < 2; i++) {
+ state = trackEditorReducer(state, {
+ type: "insertBlank",
+ fileId: A,
+ beforePageId: null,
+ });
+ }
+ const blanks = pagesOf(state, A).filter((p) => !isSourcePage(p));
+ expect(new Set(blanks.map((p) => p.id)).size).toBe(2);
+ });
+
+ it("adds a blank after each given page, across tracks, as one undo step", () => {
+ const LANDSCAPE = { width: 842, height: 595 };
+ let state = sync(initialTrackEditorState, [
+ source(A, 3, [0, 90, 0], "v1", [
+ { width: 0, height: 0 },
+ LANDSCAPE,
+ { width: 0, height: 0 },
+ ]),
+ source(B, 2),
+ ]);
+ const [, a2, a3] = pagesOf(state, A);
+ const [b1] = pagesOf(state, B);
+ state = trackEditorReducer(state, {
+ type: "insertBlankAfter",
+ pageIds: [a2.id, a3.id, b1.id],
+ });
+
+ expect(ids(state, A)).toEqual([
+ `${A}:1`,
+ `${A}:2`,
+ "blank",
+ `${A}:3`,
+ "blank",
+ ]);
+ expect(ids(state, B)).toEqual([`${B}:1`, "blank", `${B}:2`]);
+ expect(pagesOf(state, A)[2]).toMatchObject({ rotation: 90, ...LANDSCAPE });
+ const blanks = [...pagesOf(state, A), ...pagesOf(state, B)].filter(
+ (p) => !isSourcePage(p),
+ );
+ expect(new Set(blanks.map((p) => p.id)).size).toBe(3);
+
+ state = trackEditorReducer(state, { type: "undo" });
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, `${A}:3`]);
+ expect(ids(state, B)).toEqual([`${B}:1`, `${B}:2`]);
+ });
+
+ it("survives its neighbour's file closing", () => {
+ let state = twoTracks();
+ const b1 = pagesOf(state, B)[0];
+ state = trackEditorReducer(state, {
+ type: "move",
+ pageIds: [b1.id],
+ targetFileId: A,
+ beforePageId: null,
+ });
+ state = trackEditorReducer(state, {
+ type: "insertBlank",
+ fileId: A,
+ beforePageId: null,
+ });
+
+ state = sync(state, [source(A, 3, [0, 90, 0])]);
+
+ expect(ids(state, A)).toEqual([`${A}:1`, `${A}:2`, `${A}:3`, "blank"]);
+ });
+});
+
+describe("trackEditorReducer history", () => {
+ it("undoes and redoes an edit, restoring dirty state each way", () => {
+ let state = twoTracks();
+ const original = trackSignature(pagesOf(state, A));
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, A)[1].id],
+ });
+
+ state = trackEditorReducer(state, { type: "undo" });
+ expect(trackSignature(pagesOf(state, A))).toEqual(original);
+ expect(changedTrackIds(state)).toEqual([]);
+
+ state = trackEditorReducer(state, { type: "redo" });
+ expect(pagesOf(state, A)).toHaveLength(2);
+ expect(changedTrackIds(state)).toEqual([A]);
+ });
+
+ it("keeps history when tracks are merely reordered", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, A)[0].id],
+ });
+ expect(state.past).toHaveLength(1);
+
+ state = trackEditorReducer(state, {
+ type: "reorderTrack",
+ sourceId: B,
+ beforeId: A,
+ });
+
+ expect(state.present.order).toEqual([B, A]);
+ expect(state.past).toHaveLength(1);
+ // The pending delete survives the reorder rather than being re-baselined.
+ expect(pagesOf(state, A)).toHaveLength(2);
+ expect(changedTrackIds(state)).toEqual([A]);
+
+ state = trackEditorReducer(state, { type: "undo" });
+ expect(pagesOf(state, A)).toHaveLength(3);
+ });
+
+ it("clears history on a file-set change, since undo could revive dead pages", () => {
+ let state = twoTracks();
+ state = trackEditorReducer(state, {
+ type: "delete",
+ pageIds: [pagesOf(state, A)[0].id],
+ });
+ expect(state.past).toHaveLength(1);
+
+ state = sync(state, [source(A, 3, [0, 90, 0])]);
+ expect(state.past).toHaveLength(0);
+ expect(state.future).toHaveLength(0);
+ });
+
+ it("resets back to the last saved baseline", () => {
+ let state = twoTracks();
+ const original = trackSignature(pagesOf(state, A));
+ state = trackEditorReducer(state, {
+ type: "rotate",
+ pageIds: pagesOf(state, A).map((p) => p.id),
+ delta: 90,
+ });
+ state = trackEditorReducer(state, { type: "reset" });
+ expect(trackSignature(pagesOf(state, A))).toEqual(original);
+ });
+});
diff --git a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
new file mode 100644
index 0000000000..260ee4dd3e
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
@@ -0,0 +1,773 @@
+import { FileId } from "@app/types/file";
+import { createFileId } from "@app/types/fileContext";
+import {
+ BlankTrackPage,
+ PageSize,
+ Track,
+ TrackPage,
+ TrackSource,
+ TrackWorkspace,
+ emptyWorkspace,
+ isSourcePage,
+ trackSignature,
+} from "@app/components/pageTracks/types";
+
+const MAX_HISTORY = 100;
+
+/** A blank page's size when no neighbouring page records one. */
+const A4_SIZE: PageSize = { width: 595.28, height: 841.89 };
+
+export interface TrackEditorState {
+ present: TrackWorkspace;
+ /** Last saved (or freshly synced) state: what "dirty" is measured against. */
+ baseline: TrackWorkspace;
+ /** Per-file content/page-count/rotation fingerprint, so an outside edit rebuilds. */
+ sourceSignatures: Record<FileId, string>;
+ past: TrackWorkspace[];
+ future: TrackWorkspace[];
+ /** Monotonic page-id counter, held in state to keep the reducer pure. */
+ seq: number;
+ /**
+ * The order a save wants once its new files arrive. A saved file (a version,
+ * or a materialised split) gets a brand-new id, which sync would otherwise
+ * append at the end; this holds the intended sequence so the next sync can
+ * drop each new file into its old slot.
+ */
+ pendingOrder: FileId[] | null;
+}
+
+export type TrackEditorAction =
+ | { type: "sync"; sources: TrackSource[] }
+ | { type: "rotate"; pageIds: string[]; delta: number }
+ | { type: "delete"; pageIds: string[] }
+ | {
+ type: "move";
+ pageIds: string[];
+ targetFileId: FileId;
+ /** Insert before this page, or append when null. */
+ beforePageId: string | null;
+ }
+ | {
+ type: "split";
+ /** The track to split. */
+ fileId: FileId;
+ /** The page that becomes the first page of the new track. */
+ startPageId: string;
+ }
+ /** Splits every track after each selected page: the pages past each boundary
+ * become new tracks, so a page selection yields the same cuts the gap
+ * scissors make one at a time. */
+ | { type: "splitAfterSelected"; pageIds: string[] }
+ | {
+ type: "reorderTrack";
+ sourceId: FileId;
+ /** Move before this track, or to the end when null. */
+ beforeId: FileId | null;
+ }
+ | {
+ type: "insertBlank";
+ fileId: FileId;
+ /** Insert before this page, or append when null. */
+ beforePageId: string | null;
+ }
+ /** A blank page after each of these, sized and turned like it. */
+ | { type: "insertBlankAfter"; pageIds: string[] }
+ /** Swaps a page with its neighbour in the same track. */
+ | { type: "shiftPage"; pageId: string; by: -1 | 1 }
+ | { type: "dropTracks"; fileIds: FileId[] }
+ /** Drops the just-saved split tracks and records the order their new files
+ * should take, so sync slots each one back where its track sat. */
+ | {
+ type: "reconcileAfterSave";
+ dropTrackIds: FileId[];
+ /** Intended final order, in new file ids. */
+ order: FileId[];
+ }
+ /** Reverts these files' tracks, and every track entangled with them, to
+ * their saved state; entangled splits are dropped. */
+ | { type: "revert"; fileIds: FileId[] }
+ | { type: "undo" }
+ | { type: "redo" }
+ | { type: "reset" };
+
+export const initialTrackEditorState: TrackEditorState = {
+ present: emptyWorkspace,
+ baseline: emptyWorkspace,
+ sourceSignatures: {},
+ past: [],
+ future: [],
+ seq: 0,
+ pendingOrder: null,
+};
+
+const sourceSignature = (source: TrackSource): string =>
+ `${source.contentKey}:${source.pageCount}:${source.rotations.join(",")}`;
+
+function buildTrack(source: TrackSource, seq: number): [Track, number] {
+ const pages: TrackPage[] = [];
+ let next = seq;
+ for (let i = 0; i < source.pageCount; i++) {
+ pages.push({
+ kind: "source",
+ id: `tp-${next++}`,
+ sourceFileId: source.fileId,
+ sourcePageNumber: i + 1,
+ sourceContentKey: source.contentKey,
+ rotation: normalizeRotation(source.rotations[i] ?? 0),
+ width: source.sizes[i]?.width ?? 0,
+ height: source.sizes[i]?.height ?? 0,
+ });
+ }
+ return [
+ { fileId: source.fileId, name: source.name, isNew: false, pages },
+ next,
+ ];
+}
+
+/**
+ * A blank page that looks like `neighbour`: same size and rotation, so one
+ * inserted after a landscape page is landscape too. A4 when there is no
+ * neighbour or its size is unknown.
+ */
+function blankPageLike(
+ neighbour: TrackPage | undefined,
+ id: string,
+): BlankTrackPage {
+ const sized =
+ neighbour != null && neighbour.width > 0 && neighbour.height > 0;
+ return {
+ kind: "blank",
+ id,
+ rotation: neighbour?.rotation ?? 0,
+ width: sized ? neighbour.width : A4_SIZE.width,
+ height: sized ? neighbour.height : A4_SIZE.height,
+ };
+}
+
+/**
+ * A unique display name for a split, from the parent's with a `_split` suffix;
+ * a counter breaks ties when a document is split more than once.
+ */
+function splitName(base: string, taken: Set<string>): string {
+ const dot = base.lastIndexOf(".");
+ const stem = dot > 0 ? base.slice(0, dot) : base;
+ const ext = dot > 0 ? base.slice(dot) : "";
+ const primary = `${stem}_split${ext}`;
+ if (!taken.has(primary)) return primary;
+ let n = 2;
+ let candidate = `${stem}_split (${n})${ext}`;
+ while (taken.has(candidate)) candidate = `${stem}_split (${++n})${ext}`;
+ return candidate;
+}
+
+export const normalizeRotation = (degrees: number): number =>
+ (((Math.round(degrees / 90) * 90) % 360) + 360) % 360;
+
+/** Applies `mutate` to every track, dropping unchanged tracks by reference. */
+function mapTracks(
+ workspace: TrackWorkspace,
+ mutate: (pages: TrackPage[], fileId: FileId) => TrackPage[],
+): TrackWorkspace {
+ let changed = false;
+ const tracks: Record<FileId, Track> = {};
+ for (const fileId of workspace.order) {
+ const track = workspace.tracks[fileId];
+ if (!track) continue;
+ const pages = mutate(track.pages, fileId);
+ if (pages === track.pages) {
+ tracks[fileId] = track;
+ } else {
+ tracks[fileId] = { ...track, pages };
+ changed = true;
+ }
+ }
+ return changed ? { order: workspace.order, tracks } : workspace;
+}
+
+function withEdit(
+ state: TrackEditorState,
+ next: TrackWorkspace,
+): TrackEditorState {
+ if (next === state.present) return state;
+ return {
+ ...state,
+ present: next,
+ past: [...state.past, state.present].slice(-MAX_HISTORY),
+ future: [],
+ };
+}
+
+/**
+ * The given files plus every track sharing a page with them, transitively: a
+ * page moved between two tracks ties their edits together, so voiding one
+ * side's edits and keeping the other's would lose or duplicate that page.
+ */
+export function tracksEntangledWith(
+ workspace: TrackWorkspace,
+ fileIds: Set<FileId>,
+): Set<FileId> {
+ const involved = new Set(fileIds);
+ let grew = fileIds.size > 0;
+ while (grew) {
+ grew = false;
+ for (const id of workspace.order) {
+ const track = workspace.tracks[id];
+ if (!track) continue;
+ const sources = track.pages.filter(isSourcePage);
+ const touches =
+ involved.has(id) || sources.some((p) => involved.has(p.sourceFileId));
+ if (!touches) continue;
+ for (const fileId of [id, ...sources.map((p) => p.sourceFileId)]) {
+ if (involved.has(fileId)) continue;
+ involved.add(fileId);
+ grew = true;
+ }
+ }
+ }
+ return involved;
+}
+
+/**
+ * Reconciles the open files into the workspace. The workspace order is
+ * authoritative (splits and reorders live only here, not in the file list), so
+ * this preserves it: file-backed tracks are kept or rebuilt in place, split
+ * tracks are kept (their pages pruned if a source file closed), closed files
+ * drop out, and newly opened files are appended. A file whose bytes changed
+ * voids the edits of every track entangled with it: those rebuild from their
+ * files and entangled splits are dropped.
+ */
+function syncSources(
+ state: TrackEditorState,
+ sources: TrackSource[],
+): TrackEditorState {
+ const signatures: Record<FileId, string> = {};
+ sources.forEach((source) => {
+ signatures[source.fileId] = sourceSignature(source);
+ });
+ const liveIds = new Set(sources.map((s) => s.fileId));
+ const sourceById = new Map(sources.map((s) => [s.fileId, s]));
+ const replaced = new Set(
+ sources
+ .filter((s) => {
+ const previous = state.sourceSignatures[s.fileId];
+ return previous !== undefined && previous !== signatures[s.fileId];
+ })
+ .map((s) => s.fileId),
+ );
+ const reset = tracksEntangledWith(state.present, replaced);
+
+ // A closed file's bytes are gone, so pages it sourced can't be saved anywhere.
+ const pruneDead = (pages: TrackPage[]): TrackPage[] => {
+ const kept = pages.filter(
+ (p) => !isSourcePage(p) || liveIds.has(p.sourceFileId),
+ );
+ return kept.length === pages.length ? pages : kept;
+ };
+
+ let seq = state.seq;
+ // A file opening/closing, or its bytes changing, can leave undo entries
+ // referencing pages that no longer exist — drop history then, but keep it
+ // through a pure re-sync that changes nothing.
+ let historyValid = true;
+ const tracks: Record<FileId, Track> = {};
+ const baselineTracks: Record<FileId, Track> = {};
+ const order: FileId[] = [];
+
+ for (const id of state.present.order) {
+ const track = state.present.tracks[id];
+ if (!track) continue;
+
+ if (track.isNew) {
+ // Its pages go back to the files they came from, which are all rebuilt.
+ if (reset.has(id)) {
+ historyValid = false;
+ continue;
+ }
+ const pages = pruneDead(track.pages);
+ if (pages.length === 0) {
+ historyValid = false;
+ continue;
+ }
+ if (pages !== track.pages) historyValid = false;
+ tracks[id] = pages === track.pages ? track : { ...track, pages };
+ const prevBaseline = state.baseline.tracks[id];
+ if (prevBaseline) baselineTracks[id] = prevBaseline;
+ order.push(id);
+ continue;
+ }
+
+ const source = sourceById.get(track.fileId);
+ if (!source) {
+ // File-backed track whose file has closed.
+ historyValid = false;
+ continue;
+ }
+ if (reset.has(id)) {
+ // Pending edits describe bytes that no longer exist.
+ const [rebuilt, nextSeq] = buildTrack(source, seq);
+ seq = nextSeq;
+ tracks[id] = rebuilt;
+ baselineTracks[id] = rebuilt;
+ historyValid = false;
+ } else {
+ const pages = pruneDead(track.pages);
+ if (pages !== track.pages) historyValid = false;
+ const next =
+ pages === track.pages && track.name === source.name
+ ? track
+ : { ...track, pages, name: source.name };
+ tracks[id] = next;
+ baselineTracks[id] = state.baseline.tracks[id] ?? next;
+ }
+ order.push(id);
+ }
+
+ // Newly opened files, not yet represented, join at the end.
+ for (const source of sources) {
+ if (tracks[source.fileId]) continue;
+ const [track, nextSeq] = buildTrack(source, seq);
+ seq = nextSeq;
+ tracks[source.fileId] = track;
+ baselineTracks[source.fileId] = track;
+ order.push(source.fileId);
+ historyValid = false;
+ }
+
+ // A save's new files appended at the end above; a pending order from that save
+ // pulls each one back to the slot its track held. Applied once, then cleared,
+ // so a later unrelated sync can't reshuffle on a stale order.
+ const placed = new Set(
+ (state.pendingOrder ?? []).filter((id) => tracks[id] != null),
+ );
+ const finalOrder = state.pendingOrder
+ ? [
+ ...state.pendingOrder.filter((id) => placed.has(id)),
+ ...order.filter((id) => !placed.has(id)),
+ ]
+ : order;
+
+ const orderUnchanged =
+ finalOrder.length === state.present.order.length &&
+ finalOrder.every((id, i) => state.present.order[i] === id);
+ const tracksUnchanged =
+ orderUnchanged &&
+ finalOrder.every((id) => tracks[id] === state.present.tracks[id]);
+ const signaturesUnchanged =
+ liveIds.size === Object.keys(state.sourceSignatures).length &&
+ sources.every(
+ (s) => state.sourceSignatures[s.fileId] === signatures[s.fileId],
+ );
+ if (tracksUnchanged && signaturesUnchanged && state.pendingOrder == null)
+ return state;
+
+ return {
+ present: { order: finalOrder, tracks },
+ baseline: { order: finalOrder, tracks: baselineTracks },
+ sourceSignatures: signatures,
+ past: historyValid ? state.past : [],
+ future: historyValid ? state.future : [],
+ seq,
+ pendingOrder: null,
+ };
+}
+
+export function trackEditorReducer(
+ state: TrackEditorState,
+ action: TrackEditorAction,
+): TrackEditorState {
+ switch (action.type) {
+ case "sync":
+ return syncSources(state, action.sources);
+
+ case "rotate": {
+ if (action.pageIds.length === 0 || action.delta === 0) return state;
+ const ids = new Set(action.pageIds);
+ const next = mapTracks(state.present, (pages) => {
+ if (!pages.some((p) => ids.has(p.id))) return pages;
+ return pages.map((p) =>
+ ids.has(p.id)
+ ? { ...p, rotation: normalizeRotation(p.rotation + action.delta) }
+ : p,
+ );
+ });
+ return withEdit(state, next);
+ }
+
+ case "delete": {
+ if (action.pageIds.length === 0) return state;
+ const ids = new Set(action.pageIds);
+ const next = mapTracks(state.present, (pages) => {
+ const kept = pages.filter((p) => !ids.has(p.id));
+ return kept.length === pages.length ? pages : kept;
+ });
+ return withEdit(state, next);
+ }
+
+ case "move": {
+ const { pageIds, targetFileId, beforePageId } = action;
+ if (pageIds.length === 0) return state;
+ const target = state.present.tracks[targetFileId];
+ if (!target) return state;
+
+ const moving = new Set(pageIds);
+ // Take the pages in workspace order so a multi-select keeps its sequence.
+ const moved: TrackPage[] = [];
+ for (const fileId of state.present.order) {
+ for (const page of state.present.tracks[fileId]?.pages ?? []) {
+ if (moving.has(page.id)) moved.push(page);
+ }
+ }
+ if (moved.length === 0) return state;
+
+ // Resolve the anchor against the track as it stands now, skipping over
+ // the pages being moved: the anchor is often one of them (dropping a
+ // selection onto itself), and it will not exist after the strip below.
+ const anchorId = resolveAnchor(target.pages, beforePageId, moving);
+
+ const stripped = mapTracks(state.present, (pages) => {
+ const kept = pages.filter((p) => !moving.has(p.id));
+ return kept.length === pages.length ? pages : kept;
+ });
+
+ const targetPages = stripped.tracks[targetFileId]?.pages ?? [];
+ const anchorIndex =
+ anchorId == null
+ ? targetPages.length
+ : targetPages.findIndex((p) => p.id === anchorId);
+ const insertAt = anchorIndex === -1 ? targetPages.length : anchorIndex;
+
+ const nextTargetPages = [
+ ...targetPages.slice(0, insertAt),
+ ...moved,
+ ...targetPages.slice(insertAt),
+ ];
+
+ const next: TrackWorkspace = {
+ order: stripped.order,
+ tracks: {
+ ...stripped.tracks,
+ [targetFileId]: {
+ ...stripped.tracks[targetFileId],
+ pages: nextTargetPages,
+ },
+ },
+ };
+
+ if (trackSignaturesMatch(state.present, next)) return state;
+ return withEdit(state, next);
+ }
+
+ case "split": {
+ const { fileId, startPageId } = action;
+ const track = state.present.tracks[fileId];
+ if (!track) return state;
+ const idx = track.pages.findIndex((p) => p.id === startPageId);
+ // A split before the first page (or a missing page) is a no-op.
+ if (idx <= 0) return state;
+
+ const newId = createFileId();
+ const taken = new Set(
+ state.present.order
+ .map((id) => state.present.tracks[id]?.name)
+ .filter((name): name is string => name != null),
+ );
+ const newTrack: Track = {
+ fileId: newId,
+ name: splitName(track.name, taken),
+ isNew: true,
+ splitFromFileId: track.isNew ? track.splitFromFileId : fileId,
+ pages: track.pages.slice(idx),
+ };
+
+ const orderIdx = state.present.order.indexOf(fileId);
+ const nextOrder = [
+ ...state.present.order.slice(0, orderIdx + 1),
+ newId,
+ ...state.present.order.slice(orderIdx + 1),
+ ];
+ const next: TrackWorkspace = {
+ order: nextOrder,
+ tracks: {
+ ...state.present.tracks,
+ [fileId]: { ...track, pages: track.pages.slice(0, idx) },
+ [newId]: newTrack,
+ },
+ };
+ return withEdit(state, next);
+ }
+
+ case "splitAfterSelected": {
+ const selected = new Set(action.pageIds);
+ if (selected.size === 0) return state;
+ const taken = new Set(
+ state.present.order
+ .map((id) => state.present.tracks[id]?.name)
+ .filter((name): name is string => name != null),
+ );
+ const order: FileId[] = [];
+ const tracks: Record<FileId, Track> = {};
+ let changed = false;
+
+ for (const fileId of state.present.order) {
+ const track = state.present.tracks[fileId];
+ if (!track) continue;
+
+ // A boundary after a selected page, except the last page of the track:
+ // splitting there would just make an empty tail.
+ const boundaries = track.pages.reduce<number[]>((cuts, page, i) => {
+ if (selected.has(page.id) && i < track.pages.length - 1)
+ cuts.push(i + 1);
+ return cuts;
+ }, []);
+ if (boundaries.length === 0) {
+ tracks[fileId] = track;
+ order.push(fileId);
+ continue;
+ }
+
+ changed = true;
+ const starts = [0, ...boundaries];
+ const ends = [...boundaries, track.pages.length];
+ starts.forEach((start, segment) => {
+ const pages = track.pages.slice(start, ends[segment]);
+ if (segment === 0) {
+ tracks[fileId] = { ...track, pages };
+ order.push(fileId);
+ return;
+ }
+ const newId = createFileId();
+ const name = splitName(track.name, taken);
+ taken.add(name);
+ tracks[newId] = {
+ fileId: newId,
+ name,
+ isNew: true,
+ splitFromFileId: track.isNew ? track.splitFromFileId : fileId,
+ pages,
+ };
+ order.push(newId);
+ });
+ }
+
+ if (!changed) return state;
+ return withEdit(state, { order, tracks });
+ }
+
+ case "reorderTrack": {
+ const { sourceId, beforeId } = action;
+ const current = state.present.order;
+ if (!current.includes(sourceId)) return state;
+ const without = current.filter((id) => id !== sourceId);
+ const at = beforeId == null ? without.length : without.indexOf(beforeId);
+ const insertAt = at === -1 ? without.length : at;
+ const nextOrder = [
+ ...without.slice(0, insertAt),
+ sourceId,
+ ...without.slice(insertAt),
+ ];
+ if (nextOrder.every((id, i) => current[i] === id)) return state;
+ // Reorder is not a page edit, so it stays out of the undo history and
+ // does not touch the baseline (pending edits remain pending).
+ return {
+ ...state,
+ present: { order: nextOrder, tracks: state.present.tracks },
+ baseline: { order: nextOrder, tracks: state.baseline.tracks },
+ };
+ }
+
+ case "dropTracks": {
+ const drop = new Set(action.fileIds);
+ if (!state.present.order.some((id) => drop.has(id))) return state;
+ const order = state.present.order.filter((id) => !drop.has(id));
+ const tracks: Record<FileId, Track> = {};
+ const baselineTracks: Record<FileId, Track> = {};
+ for (const id of order) {
+ const track = state.present.tracks[id];
+ if (track) tracks[id] = track;
+ const baseline = state.baseline.tracks[id];
+ if (baseline) baselineTracks[id] = baseline;
+ }
+ // Removing a track is structural, like a sync: its pages must not linger
+ // in the undo history.
+ return {
+ ...state,
+ present: { order, tracks },
+ baseline: { order, tracks: baselineTracks },
+ past: [],
+ future: [],
+ };
+ }
+
+ case "reconcileAfterSave": {
+ const drop = new Set(action.dropTrackIds);
+ const order = state.present.order.filter((id) => !drop.has(id));
+ const tracks: Record<FileId, Track> = {};
+ const baselineTracks: Record<FileId, Track> = {};
+ for (const id of order) {
+ const track = state.present.tracks[id];
+ if (track) tracks[id] = track;
+ const baseline = state.baseline.tracks[id];
+ if (baseline) baselineTracks[id] = baseline;
+ }
+ return {
+ ...state,
+ present: { order, tracks },
+ baseline: { order, tracks: baselineTracks },
+ pendingOrder: action.order,
+ past: [],
+ future: [],
+ };
+ }
+
+ case "insertBlank": {
+ const track = state.present.tracks[action.fileId];
+ if (!track) return state;
+ const at =
+ action.beforePageId == null
+ ? track.pages.length
+ : track.pages.findIndex((p) => p.id === action.beforePageId);
+ if (at < 0) return state;
+ const blank = blankPageLike(
+ track.pages[at - 1] ?? track.pages[at],
+ `tp-${state.seq}`,
+ );
+ const pages = [
+ ...track.pages.slice(0, at),
+ blank,
+ ...track.pages.slice(at),
+ ];
+ const next: TrackWorkspace = {
+ order: state.present.order,
+ tracks: {
+ ...state.present.tracks,
+ [action.fileId]: { ...track, pages },
+ },
+ };
+ return { ...withEdit(state, next), seq: state.seq + 1 };
+ }
+
+ case "insertBlankAfter": {
+ const after = new Set(action.pageIds);
+ let seq = state.seq;
+ const next = mapTracks(state.present, (pages) => {
+ if (!pages.some((p) => after.has(p.id))) return pages;
+ return pages.flatMap((p) =>
+ after.has(p.id) ? [p, blankPageLike(p, `tp-${seq++}`)] : [p],
+ );
+ });
+ if (next === state.present) return state;
+ return { ...withEdit(state, next), seq };
+ }
+
+ case "shiftPage": {
+ const next = mapTracks(state.present, (pages) => {
+ const from = pages.findIndex((p) => p.id === action.pageId);
+ const to = from + action.by;
+ if (from < 0 || to < 0 || to >= pages.length) return pages;
+ const shifted = [...pages];
+ [shifted[from], shifted[to]] = [shifted[to], shifted[from]];
+ return shifted;
+ });
+ return withEdit(state, next);
+ }
+
+ case "revert": {
+ const involved = tracksEntangledWith(
+ state.present,
+ new Set(action.fileIds),
+ );
+ const order = state.present.order.filter(
+ (id) => !(involved.has(id) && state.present.tracks[id]?.isNew),
+ );
+ const tracks: Record<FileId, Track> = {};
+ const baselineTracks: Record<FileId, Track> = {};
+ for (const id of order) {
+ const track = state.present.tracks[id];
+ if (!track) continue;
+ const baseline = state.baseline.tracks[id];
+ tracks[id] = involved.has(id) && baseline ? baseline : track;
+ if (baseline) baselineTracks[id] = baseline;
+ }
+ // Undo entries could revive the reverted edits alongside the saved state.
+ return {
+ ...state,
+ present: { order, tracks },
+ baseline: { order, tracks: baselineTracks },
+ past: [],
+ future: [],
+ };
+ }
+
+ case "undo": {
+ if (state.past.length === 0) return state;
+ const previous = state.past[state.past.length - 1];
+ return {
+ ...state,
+ present: previous,
+ past: state.past.slice(0, -1),
+ future: [state.present, ...state.future].slice(0, MAX_HISTORY),
+ };
+ }
+
+ case "redo": {
+ if (state.future.length === 0) return state;
+ const [next, ...rest] = state.future;
+ return {
+ ...state,
+ present: next,
+ past: [...state.past, state.present].slice(-MAX_HISTORY),
+ future: rest,
+ };
+ }
+
+ case "reset":
+ return {
+ ...state,
+ present: state.baseline,
+ past: [],
+ future: [],
+ };
+
+ default:
+ return state;
+ }
+}
+
+/**
+ * The first page at or after `beforePageId` that is not itself being moved, or
+ * null to append. Returns null when the anchor is not in this track at all.
+ */
+function resolveAnchor(
+ pages: TrackPage[],
+ beforePageId: string | null,
+ moving: Set<string>,
+): string | null {
+ if (beforePageId == null) return null;
+ const start = pages.findIndex((p) => p.id === beforePageId);
+ if (start === -1) return null;
+ for (let i = start; i < pages.length; i++) {
+ if (!moving.has(pages[i].id)) return pages[i].id;
+ }
+ return null;
+}
+
+function trackSignaturesMatch(a: TrackWorkspace, b: TrackWorkspace): boolean {
+ if (a.order.length !== b.order.length) return false;
+ return a.order.every((fileId, i) => {
+ if (b.order[i] !== fileId) return false;
+ const left = a.tracks[fileId]?.pages ?? [];
+ const right = b.tracks[fileId]?.pages ?? [];
+ return (
+ left.length === right.length && left.every((p, j) => p.id === right[j].id)
+ );
+ });
+}
+
+/** File ids whose page list differs from the last saved baseline. */
+export function changedTrackIds(state: TrackEditorState): FileId[] {
+ return state.present.order.filter((fileId) => {
+ const current = state.present.tracks[fileId]?.pages ?? [];
+ const original = state.baseline.tracks[fileId]?.pages ?? [];
+ return trackSignature(current) !== trackSignature(original);
+ });
+}
diff --git a/frontend/editor/src/core/components/pageTracks/types.ts b/frontend/editor/src/core/components/pageTracks/types.ts
new file mode 100644
index 0000000000..bb70e2a28f
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/types.ts
@@ -0,0 +1,99 @@
+import { FileId } from "@app/types/file";
+
+/** Page size in PDF points, before the page's rotation is applied. */
+export interface PageSize {
+ width: number;
+ height: number;
+}
+
+interface TrackPageBase extends PageSize {
+ /** Per-instance; survives moves. */
+ id: string;
+ /** Absolute rotation in degrees. */
+ rotation: number;
+}
+
+/**
+ * A page copied from an open file. `sourceFileId`/`sourcePageNumber` point at
+ * the bytes to copy on save, so a page dragged into another track still knows
+ * where it came from. Its size is 0 x 0 when the file's metadata lacks it.
+ */
+export interface SourceTrackPage extends TrackPageBase {
+ kind: "source";
+ sourceFileId: FileId;
+ sourcePageNumber: number;
+ /** The source file's {@link TrackSource.contentKey} when this page was read. */
+ sourceContentKey: string;
+}
+
+/** An empty page inserted in the editor, written out at its own size. */
+export interface BlankTrackPage extends TrackPageBase {
+ kind: "blank";
+}
+
+export type TrackPage = SourceTrackPage | BlankTrackPage;
+
+export const isSourcePage = (page: TrackPage): page is SourceTrackPage =>
+ page.kind === "source";
+
+/**
+ * One track of pages. `fileId` is the map key and order entry: a real active
+ * file's id for a file-backed track, or a minted id for a split that has no
+ * file yet. `isNew` tells them apart — a split is written to a brand-new file
+ * on save, a file-backed track versions its own file.
+ */
+export interface Track {
+ fileId: FileId;
+ /** Display name: the file's name, or a derived one for a split. */
+ name: string;
+ /** True for a split not yet backed by a saved file. */
+ isNew: boolean;
+ /** For a split, the file it was cut from: parents the saved file when no
+ * source page is left to, as in a split of blank pages. */
+ splitFromFileId?: FileId;
+ pages: TrackPage[];
+}
+
+export interface TrackWorkspace {
+ order: FileId[];
+ tracks: Record<FileId, Track>;
+}
+
+/** Page counts + rotation baselines for the files a sync should cover. */
+export interface TrackSource {
+ fileId: FileId;
+ name: string;
+ pageCount: number;
+ rotations: number[];
+ /** Per page; 0 x 0 where the file's metadata does not record it. */
+ sizes: PageSize[];
+ /**
+ * Changes when the file's bytes are replaced under an unchanged id, which a
+ * disk reload does without necessarily moving the page count or rotations.
+ */
+ contentKey: string;
+}
+
+/** Cache key for a source page's thumbnail, shared by every instance of it. */
+export const sourcePageKey = (page: SourceTrackPage): string =>
+ `${page.sourceFileId}@${page.sourceContentKey}#${page.sourcePageNumber}`;
+
+export const trackSignature = (pages: TrackPage[]): string =>
+ pages
+ .map((p) =>
+ isSourcePage(p)
+ ? `${p.sourceFileId}:${p.sourcePageNumber}:${p.rotation}`
+ : `blank:${p.id}:${p.rotation}`,
+ )
+ .join("|");
+
+export const emptyWorkspace: TrackWorkspace = { order: [], tracks: {} };
+
+export const allPages = (workspace: TrackWorkspace): TrackPage[] =>
+ workspace.order.flatMap((fileId) => workspace.tracks[fileId]?.pages ?? []);
+
+export const totalPageCount = (workspace: TrackWorkspace): number =>
+ workspace.order.reduce(
+ (sum, fileId) => sum + (workspace.tracks[fileId]?.pages.length ?? 0),
+ 0,
+ );
diff --git a/frontend/editor/src/core/components/shared/CloseFilesConfirmModal.tsx b/frontend/editor/src/core/components/shared/CloseFilesConfirmModal.tsx
new file mode 100644
index 0000000000..5e14341317
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/CloseFilesConfirmModal.tsx
@@ -0,0 +1,66 @@
+import { Group, Modal, Stack, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui/Button";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+
+export interface CloseFileEntry {
+ /** Stable key: two open files can share a name, their ids cannot. */
+ id: string;
+ name: string;
+}
+
+export interface CloseFilesConfirmModalProps {
+ opened: boolean;
+ message: string;
+ files: CloseFileEntry[];
+ /** The destructive button's label: a plain close, or discarding unsaved changes. */
+ closeLabel: string;
+ onClose: () => void;
+ onCancel: () => void;
+ /** Offers saving before closing; omit when there is nothing to save. */
+ onSave?: () => void;
+}
+
+/** The "are you sure you want to close" confirmation, shared by every view that closes files. */
+export function CloseFilesConfirmModal({
+ opened,
+ message,
+ files,
+ closeLabel,
+ onClose,
+ onCancel,
+ onSave,
+}: CloseFilesConfirmModalProps) {
+ const { t } = useTranslation();
+ return (
+ <Modal
+ opened={opened}
+ onClose={onCancel}
+ title={t("confirmClose", "Confirm Close")}
+ centered
+ size="auto"
+ >
+ <Stack gap="md">
+ <Text size="md">{message}</Text>
+ {files.map((file) => (
+ <Text key={file.id} size="sm" c="dimmed" fw={500}>
+ <PrivateContent>{file.name}</PrivateContent>
+ </Text>
+ ))}
+ <Group justify="flex-end" gap="sm">
+ <Button variant="secondary" onClick={onCancel}>
+ {t("confirmCloseCancel", "Cancel")}
+ </Button>
+ <Button accent="danger" onClick={onClose}>
+ {closeLabel}
+ </Button>
+ {onSave && (
+ <Button onClick={onSave}>
+ {t("confirmCloseSave", "Save and close")}
+ </Button>
+ )}
+ </Group>
+ </Stack>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index f0e9371cc3..058ade1fc2 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -521,10 +521,10 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const { state } = useFileState();
const { actions: fileActions } = useFileActions();
const { actions: navActions } = useNavigationActions();
- const { workbench: currentWorkbench, selectedTool } = useNavigationState();
+ const { workbench: currentWorkbench } = useNavigationState();
const policyFileBadges = usePolicyFileBadges();
- const isMultiTool =
- currentWorkbench === "pageEditor" && selectedTool === "multiTool";
+ // The page editor lays out every open file, so an added file belongs there.
+ const staysOnAdd = currentWorkbench === "pageEditor";
const { requestNavigation } = useNavigationGuard();
const { activeFileId, setActiveFileId } = useViewer();
const { addFiles } = useFileHandler();
@@ -847,7 +847,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
return;
}
await addFiles(files);
- if (!isMultiTool) {
+ if (!staysOnAdd) {
navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");
}
}, [
@@ -855,7 +855,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
openGoogleDrivePicker,
addFiles,
navActions,
- isMultiTool,
+ staysOnAdd,
onPickGoogleDriveFiles,
]);
@@ -905,7 +905,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
await fileActions.addStirlingFileStubs([stub]);
- if (isMultiTool) {
+ if (staysOnAdd) {
fileActions.setSelectedFiles([
...state.ui.selectedFileIds,
stub.id,
@@ -930,7 +930,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
currentWorkbench,
activeFileId,
requestNavigation,
- isMultiTool,
+ staysOnAdd,
],
);
@@ -1002,14 +1002,14 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
await addFiles(files);
// A tool that pinned its own workbench surface owns it - switching to
// the viewer here strands the upload outside the tool being used.
- if (!isMultiTool && !currentWorkbench.startsWith("custom:")) {
+ if (!staysOnAdd && !currentWorkbench.startsWith("custom:")) {
navActions.setWorkbench(
files.length === 1 ? "viewer" : "fileEditor",
);
}
}
},
- [addFiles, navActions, isMultiTool, onUploadFiles, currentWorkbench],
+ [addFiles, navActions, staysOnAdd, onUploadFiles, currentWorkbench],
);
const handleNativeFilePick = useCallback(
diff --git a/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx b/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx
deleted file mode 100644
index 0c9aa31a75..0000000000
--- a/frontend/editor/src/core/components/shared/PageEditorFileDropdown.tsx
+++ /dev/null
@@ -1,267 +0,0 @@
-import React from "react";
-import { Menu, Loader, Group, Text, Checkbox } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@app/ui/Icon";
-import FitText from "@app/components/shared/FitText";
-import { getFileColorWithOpacity } from "@app/components/pageEditor/fileColors";
-import { useFilesModalContext } from "@app/contexts/FilesModalContext";
-import { PrivateContent } from "@app/components/shared/PrivateContent";
-import { useFileItemDragDrop } from "@app/components/shared/pageEditor/useFileItemDragDrop";
-
-import { FileId } from "@app/types/file";
-
-// Local interface for PageEditor file display
-interface PageEditorFile {
- fileId: FileId;
- name: string;
- versionNumber?: number;
- isSelected: boolean;
-}
-
-interface FileMenuItemProps {
- file: PageEditorFile;
- index: number;
- colorIndex: number;
- onToggleSelection: (fileId: FileId) => void;
- onReorder: (fromIndex: number, toIndex: number) => void;
-}
-
-const FileMenuItem: React.FC<FileMenuItemProps> = ({
- file,
- index,
- colorIndex,
- onToggleSelection,
- onReorder,
-}) => {
- const { t } = useTranslation();
- const {
- itemRef,
- isDragging,
- isDragOver,
- dropPosition,
- movedRef,
- onPointerDown,
- onPointerMove,
- onPointerUp,
- } = useFileItemDragDrop({
- fileId: file.fileId,
- index,
- onReorder,
- });
-
- const itemName =
- file?.name || t("pageEditor.fileDropdown.untitled", "Untitled");
- const fileColorBorder = getFileColorWithOpacity(colorIndex, 1);
- const fileColorBorderHover = getFileColorWithOpacity(colorIndex, 1.0);
-
- return (
- <div
- style={{
- position: "relative",
- marginBottom: "0.5rem",
- }}
- >
- {/* Drop indicator line */}
- {isDragOver && (
- <div
- style={{
- position: "absolute",
- ...(dropPosition === "above"
- ? { top: "-2px" }
- : { bottom: "-2px" }),
- left: 0,
- right: 0,
- height: "4px",
- backgroundColor: "rgb(59, 130, 246)",
- borderRadius: "2px",
- zIndex: 10,
- }}
- />
- )}
- <div
- ref={itemRef}
- onPointerDown={onPointerDown}
- onPointerMove={onPointerMove}
- onPointerUp={onPointerUp}
- onClick={(e) => {
- e.stopPropagation();
- if (movedRef.current) return; // ignore click after drag
- onToggleSelection(file.fileId);
- }}
- style={{
- padding: "0.75rem 0.75rem",
- cursor: isDragging ? "grabbing" : "grab",
- backgroundColor: file.isSelected
- ? "rgba(0, 0, 0, 0.05)"
- : "transparent",
- borderLeft: `6px solid ${fileColorBorder}`,
- opacity: isDragging ? 0.5 : 1,
- transition: "opacity 0.2s ease-in-out, background-color 0.15s ease",
- userSelect: "none",
- }}
- onMouseEnter={(e) => {
- if (!isDragging) {
- e.currentTarget.style.backgroundColor = "rgba(0, 0, 0, 0.05)";
- e.currentTarget.style.borderLeftColor = fileColorBorderHover;
- }
- }}
- onMouseLeave={(e) => {
- if (!isDragging) {
- e.currentTarget.style.backgroundColor = file.isSelected
- ? "rgba(0, 0, 0, 0.05)"
- : "transparent";
- e.currentTarget.style.borderLeftColor = fileColorBorder;
- }
- }}
- >
- <Group gap="xs" style={{ width: "100%" }}>
- <div
- style={{
- cursor: "grab",
- display: "flex",
- alignItems: "center",
- color: "var(--mantine-color-dimmed)",
- }}
- >
- <Icon name="grip-vertical" size={20} />
- </div>
- <Checkbox
- checked={file.isSelected}
- onChange={() => onToggleSelection(file.fileId)}
- onClick={(e) => e.stopPropagation()}
- size="sm"
- />
- <div style={{ flex: 1, textAlign: "left", minWidth: 0 }}>
- <PrivateContent>
- <FitText text={itemName} minimumFontScale={0.7} />
- </PrivateContent>
- </div>
- {file.versionNumber && file.versionNumber > 1 && (
- <Text size="xs" c="dimmed">
- v{file.versionNumber}
- </Text>
- )}
- </Group>
- </div>
- </div>
- );
-};
-
-interface PageEditorFileDropdownProps {
- files: PageEditorFile[];
- onToggleSelection: (fileId: FileId) => void;
- onReorder: (fromIndex: number, toIndex: number) => void;
- switchingTo?: string | null;
- viewOptionStyle: React.CSSProperties;
- fileColorMap: Map<string, number>;
- selectedCount: number;
- totalCount: number;
-}
-
-export const PageEditorFileDropdown: React.FC<PageEditorFileDropdownProps> = ({
- files,
- onToggleSelection,
- onReorder,
- switchingTo,
- viewOptionStyle,
- fileColorMap,
- selectedCount,
- totalCount,
-}) => {
- const { t } = useTranslation();
- const { openFilesModal } = useFilesModalContext();
-
- return (
- <Menu trigger="click" position="bottom" width="40rem">
- <Menu.Target>
- {/* role="button" so the aria-haspopup/aria-expanded Menu.Target stamps on
- this element are permitted. It stays a div because it renders inside
- the workbench SegmentedControl's <label>, which may not contain
- interactive content. */}
- <div
- role="button"
- className="ph-no-capture"
- style={{ ...viewOptionStyle, cursor: "pointer" }}
- >
- {switchingTo === "pageEditor" ? (
- <Loader size="xs" />
- ) : (
- <Icon name="layout-dashboard" size="1.4rem" />
- )}
- <span className="ph-no-capture">
- {t(
- "pageEditor.fileDropdown.selectedCount",
- "{{selected}}/{{total}} files selected",
- { selected: selectedCount, total: totalCount },
- )}
- </span>
- <Icon name="chevron-down" size={20} />
- </div>
- </Menu.Target>
- <Menu.Dropdown
- className="ph-no-capture"
- style={{
- backgroundColor: "var(--c-bg)",
- border: "1px solid var(--c-border-subtle)",
- borderRadius: "8px",
- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
- maxHeight: "80vh",
- overflowY: "auto",
- }}
- >
- {files.map((file, index) => {
- const colorIndex = fileColorMap.get(file.fileId) ?? 0;
-
- return (
- <FileMenuItem
- key={file.fileId}
- file={file}
- index={index}
- colorIndex={colorIndex}
- onToggleSelection={onToggleSelection}
- onReorder={onReorder}
- />
- );
- })}
-
- {/* Add File Button */}
- <div
- onClick={(e) => {
- e.stopPropagation();
- openFilesModal();
- }}
- style={{
- padding: "0.75rem 0.75rem",
- marginTop: "0.5rem",
- cursor: "pointer",
- backgroundColor: "transparent",
- borderTop: "1px solid var(--c-border-subtle)",
- transition: "background-color 0.15s ease",
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = "rgba(59, 130, 246, 0.25)";
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = "transparent";
- }}
- >
- <Group gap="xs" style={{ width: "100%" }}>
- <Icon
- name="plus"
- size={20}
- style={{ color: "var(--mantine-color-text)" }}
- />
- <Text
- size="sm"
- fw={500}
- style={{ color: "var(--mantine-color-text)" }}
- className="ph-no-capture"
- >
- {t("pageEditor.fileDropdown.addFile", "Add File")}
- </Text>
- </Group>
- </div>
- </Menu.Dropdown>
- </Menu>
- );
-};
diff --git a/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx b/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx
index c3b7559f2a..06cd875ac0 100644
--- a/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx
+++ b/frontend/editor/src/core/components/shared/PageSelectionSyntaxHint.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Text } from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
import { parseSelectionWithDiagnostics } from "@app/utils/bulkselection/parseSelection";
interface PageSelectionSyntaxHintProps {
diff --git a/frontend/editor/src/core/components/shared/TopControls.tsx b/frontend/editor/src/core/components/shared/TopControls.tsx
deleted file mode 100644
index d178bb7344..0000000000
--- a/frontend/editor/src/core/components/shared/TopControls.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-import React, { useState, useCallback, useMemo } from "react";
-import { Loader } from "@mantine/core";
-import { SegmentedControl } from "@app/ui/SegmentedControl";
-import { Icon } from "@app/ui/Icon";
-import { WorkbenchType, isValidWorkbench } from "@app/types/workbench";
-import { PageEditorFileDropdown } from "@app/components/shared/PageEditorFileDropdown";
-import type { CustomWorkbenchViewInstance } from "@app/contexts/ToolWorkflowContext";
-import { FileDropdownMenu } from "@app/components/shared/FileDropdownMenu";
-import {
- usePageEditorDropdownState,
- PageEditorDropdownState,
-} from "@app/components/pageEditor/hooks/usePageEditorDropdownState";
-import { FileId } from "@app/types/file";
-
-const viewOptionStyle: React.CSSProperties = {
- display: "inline-flex",
- flexDirection: "row",
- alignItems: "center",
- gap: "0.5rem",
- justifyContent: "center",
- padding: "2px 1rem",
-};
-
-// Helper function to create view options for SegmentedControl
-const createViewOptions = (
- currentView: WorkbenchType,
- switchingTo: WorkbenchType | null,
- activeFiles: Array<{ fileId: string; name: string; versionNumber?: number }>,
- currentFileIndex: number,
- onFileSelect?: (index: number) => void,
- onFileRemove?: (fileId: FileId) => void,
- pageEditorState?: PageEditorDropdownState,
- customViews?: CustomWorkbenchViewInstance[],
-) => {
- // Viewer dropdown logic
- const currentFile = activeFiles[currentFileIndex];
- const isInViewer = currentView === "viewer";
- const fileName = currentFile?.name || "";
- const viewerDisplayName = isInViewer && fileName ? fileName : "Viewer";
- const showViewerDropdown = isInViewer;
-
- const viewerOption = {
- label: showViewerDropdown ? (
- <FileDropdownMenu
- displayName={viewerDisplayName}
- activeFiles={activeFiles}
- currentFileIndex={currentFileIndex}
- onFileSelect={onFileSelect}
- onFileRemove={onFileRemove}
- switchingTo={switchingTo}
- viewOptionStyle={viewOptionStyle}
- />
- ) : (
- <div style={viewOptionStyle}>
- {switchingTo === "viewer" ? <Loader size="sm" /> : <Icon name="file" />}
- </div>
- ),
- value: "viewer",
- };
-
- // Page Editor dropdown logic
- const isInPageEditor = currentView === "pageEditor";
- const hasPageEditorFiles = pageEditorState && pageEditorState.totalCount > 0;
- const showPageEditorDropdown = isInPageEditor && hasPageEditorFiles;
-
- const pageEditorOption = {
- label: showPageEditorDropdown ? (
- <PageEditorFileDropdown
- files={pageEditorState.files}
- onToggleSelection={pageEditorState.onToggleSelection}
- onReorder={pageEditorState.onReorder}
- switchingTo={switchingTo}
- viewOptionStyle={viewOptionStyle}
- fileColorMap={pageEditorState.fileColorMap}
- selectedCount={pageEditorState.selectedCount}
- totalCount={pageEditorState.totalCount}
- />
- ) : (
- <div style={viewOptionStyle}>
- {switchingTo === "pageEditor" ? (
- <Loader size="sm" />
- ) : (
- <Icon name="layout-grid" />
- )}
- </div>
- ),
- value: "pageEditor",
- };
-
- const fileEditorOption = {
- label: (
- <div style={viewOptionStyle}>
- {switchingTo === "fileEditor" ? (
- <Loader size="sm" />
- ) : (
- <Icon name="folder" />
- )}
- </div>
- ),
- value: "fileEditor",
- };
-
- const baseOptions = [viewerOption, pageEditorOption, fileEditorOption];
-
- const customOptions = (customViews ?? [])
- .filter((view) => view.data != null)
- .map((view) => ({
- label: (
- <div style={viewOptionStyle}>
- {switchingTo === view.workbenchId ? (
- <Loader size="sm" />
- ) : (
- view.icon || <Icon name="file-pdf" />
- )}
- <span>{view.label}</span>
- </div>
- ),
- value: view.workbenchId,
- }));
-
- return [...baseOptions, ...customOptions];
-};
-
-interface TopControlsProps {
- currentView: WorkbenchType;
- setCurrentView: (view: WorkbenchType) => void;
- customViews?: CustomWorkbenchViewInstance[];
- activeFiles?: Array<{ fileId: string; name: string; versionNumber?: number }>;
- currentFileIndex?: number;
- onFileSelect?: (index: number) => void;
- onFileRemove?: (fileId: FileId) => void;
-}
-
-const TopControls = ({
- currentView,
- setCurrentView,
- customViews = [],
- activeFiles = [],
- currentFileIndex = 0,
- onFileSelect,
- onFileRemove,
-}: TopControlsProps) => {
- const [switchingTo, setSwitchingTo] = useState<WorkbenchType | null>(null);
-
- const pageEditorState = usePageEditorDropdownState();
-
- const handleViewChange = useCallback(
- (view: string) => {
- if (!isValidWorkbench(view)) {
- return;
- }
-
- const workbench = view;
-
- // Show immediate feedback
- setSwitchingTo(workbench);
-
- // Defer the heavy view change to next frame so spinner can render
- requestAnimationFrame(() => {
- // Give the spinner one more frame to show
- requestAnimationFrame(() => {
- setCurrentView(workbench);
-
- // Clear the loading state after view change completes
- setTimeout(() => setSwitchingTo(null), 300);
- });
- });
- },
- [setCurrentView],
- );
-
- // Memoize view options to prevent SegmentedControl re-renders
- const viewOptions = useMemo(
- () =>
- createViewOptions(
- currentView,
- switchingTo,
- activeFiles,
- currentFileIndex,
- onFileSelect,
- onFileRemove,
- pageEditorState,
- customViews,
- ),
- [
- currentView,
- switchingTo,
- activeFiles,
- currentFileIndex,
- onFileSelect,
- onFileRemove,
- pageEditorState,
- customViews,
- ],
- );
-
- return (
- <div className="absolute left-0 w-full top-0 z-[100] pointer-events-none">
- <div className="flex justify-center">
- <SegmentedControl
- data-tour="view-switcher"
- options={viewOptions}
- value={currentView}
- onChange={handleViewChange}
- variant="secondary"
- fullWidth
- style={{
- transition: "all 0.2s ease",
- opacity: switchingTo ? 0.8 : 1,
- pointerEvents: "auto",
- }}
- />
- </div>
- </div>
- );
-};
-
-export default TopControls;
diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.css b/frontend/editor/src/core/components/shared/WorkbenchBar.css
index b481864054..ebd1c26aeb 100644
--- a/frontend/editor/src/core/components/shared/WorkbenchBar.css
+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.css
@@ -101,12 +101,56 @@
height: 16px;
}
+.workbench-bar-views .mantine-SegmentedControl-control {
+ flex: 0 0 auto;
+}
+
+.workbench-bar-views .mantine-SegmentedControl-innerLabel {
+ gap: 0;
+}
+
+/* Animate to the label's measured pixel width, not a `fr`/`auto`/`max-content`
+ * keyword: only a length transitions in every engine (grid-column and size
+ * keywords animate in Chromium but snap in WebKit/Firefox). JS keeps
+ * --view-label-w in sync with the text's natural width. */
.workbench-bar-view-label {
- line-height: 1;
+ display: flex;
+ align-items: center;
+ width: 0;
+ /* The icon gap is margin, not padding: under border-box, padding would eat
+ into --view-label-w and clip the last letter. */
+ margin-left: 0;
+ opacity: 0;
+ overflow: hidden;
+ transition:
+ width 0.22s ease,
+ margin-left 0.22s ease,
+ opacity 0.16s ease;
}
-/* Segmented view switcher: size the icons to the pre-consolidation 16px
- * (centering + gap come from the shared SegmentedControl innerLabel). */
+.workbench-bar-view-label > span {
+ /* Never shrink below the text's natural width: the collapsed label is width 0,
+ and a shrunk flex item would both clip the label and mis-measure it. */
+ flex: none;
+ white-space: nowrap;
+ /* Roomy enough that overflow:hidden clips the text sideways without shaving
+ descenders (the g in "Page Editor") off the bottom. */
+ line-height: 1.4;
+}
+
+.workbench-bar-view-label.is-open {
+ width: var(--view-label-w, auto);
+ margin-left: 0.375rem;
+ opacity: 1;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .workbench-bar-view-label {
+ transition: none;
+ }
+}
+
+/* Segmented view switcher: size the icons to the pre-consolidation 16px. */
.workbench-bar-views .mantine-SegmentedControl-label svg {
font-size: 16px;
width: 16px;
@@ -125,12 +169,17 @@
justify-content: center;
height: 38px;
transform: translateX(var(--workbench-bar-search-offset, 0px));
+ /* The slot spans the whole centre and is shifted by a transform, so its empty
+ flanks can sit over the view switcher or the globals cluster and swallow
+ their clicks. Only the pill itself takes pointer events. */
+ pointer-events: none;
}
.workbench-bar-search .super-search {
flex: 0 1 24rem;
width: min(100%, 24rem);
max-width: 24rem;
+ pointer-events: auto;
}
.workbench-bar-search .super-search input {
@@ -277,6 +326,14 @@
color: var(--c-text) !important;
}
+/* The !important colour above overrides Mantine's disabled styling, so a
+ * disabled icon would otherwise look exactly like an enabled one. */
+.workbench-bar-action-icon:disabled,
+.workbench-bar-action-icon[data-disabled] {
+ color: var(--c-text-muted) !important;
+ opacity: 0.45;
+}
+
.workbench-bar-action-icon[data-variant="filled"] {
background: var(--c-primary) !important;
color: var(--c-text-on-primary) !important;
diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
index c664c8f8e5..96780cb815 100644
--- a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
@@ -1,5 +1,6 @@
import React, {
useCallback,
+ useEffect,
useLayoutEffect,
useMemo,
useRef,
@@ -100,16 +101,59 @@ export default function WorkbenchBar({
clearFilesPageReturnRoute();
navigate(target);
}, [returnRoute, navigate]);
- const { buttons, actions, allButtonsDisabled } = useWorkbenchBar();
- const {
- pageEditorFunctions,
- toolPanelMode,
- leftPanelView,
- customWorkbenchViews,
- } = useToolWorkflow();
+ const { buttons, actions, allButtonsDisabled, viewFileActions } =
+ useWorkbenchBar();
+ const { toolPanelMode, leftPanelView, customWorkbenchViews } =
+ useToolWorkflow();
const { selectedTool } = useNavigationState();
const isCustomView = !isBaseWorkbench(currentView);
const isViewer = currentView === "viewer";
+
+ // Which view's label is expanded, held back until the new view has mounted
+ const [openView, setOpenView] = useState(currentView);
+ useEffect(() => {
+ if (typeof window.requestIdleCallback === "function") {
+ const id = window.requestIdleCallback(() => setOpenView(currentView), {
+ timeout: 400,
+ });
+ return () => window.cancelIdleCallback?.(id);
+ }
+ const frame = requestAnimationFrame(() => setOpenView(currentView));
+ return () => cancelAnimationFrame(frame);
+ }, [currentView]);
+
+ // Publish each view label's natural width as --view-label-w so the open width
+ // animates to an exact length (see WorkbenchBar.css). A ResizeObserver keeps
+ // it current across font load, zoom and language change.
+ const labelSizeObserver = useMemo(
+ () =>
+ typeof ResizeObserver === "undefined"
+ ? null
+ : new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ const span = entry.target;
+ if (span instanceof HTMLElement) {
+ span.parentElement?.style.setProperty(
+ "--view-label-w",
+ `${Math.ceil(span.getBoundingClientRect().width)}px`,
+ );
+ }
+ }
+ }),
+ [],
+ );
+ useEffect(() => () => labelSizeObserver?.disconnect(), [labelSizeObserver]);
+ const measureViewLabel = useCallback(
+ (span: HTMLSpanElement | null) => {
+ if (!span) return;
+ span.parentElement?.style.setProperty(
+ "--view-label-w",
+ `${Math.ceil(span.getBoundingClientRect().width)}px`,
+ );
+ labelSizeObserver?.observe(span);
+ },
+ [labelSizeObserver],
+ );
const disableForFullscreen =
toolPanelMode === "fullscreen" && leftPanelView === "toolPicker";
const terminology = useFileActionTerminology();
@@ -154,19 +198,8 @@ export default function WorkbenchBar({
enforcingRun?.currentStep != null && enforcingRun.stepCount
? Math.round((enforcingRun.currentStep / enforcingRun.stepCount) * 100)
: undefined;
- const pageEditorTotalPages = pageEditorFunctions?.totalPages ?? 0;
- const pageEditorSelectedCount =
- pageEditorFunctions?.selectedPageIds?.length ?? 0;
-
- const totalItems = useMemo(() => {
- if (currentView === "pageEditor") return pageEditorTotalPages;
- return activeFiles.length;
- }, [currentView, pageEditorTotalPages, activeFiles.length]);
-
- const selectedCount = useMemo(() => {
- if (currentView === "pageEditor") return pageEditorSelectedCount;
- return selectedFileIds.length;
- }, [currentView, pageEditorSelectedCount, selectedFileIds.length]);
+ const totalItems = activeFiles.length;
+ const selectedCount = selectedFileIds.length;
// Registered into the bar's own row rather than the tool row below it. Already
// sorted by order when registered.
@@ -226,18 +259,24 @@ export default function WorkbenchBar({
return;
}
- if (currentView === "pageEditor") {
- pageEditorFunctions?.onExportAll?.();
- return;
- }
-
- const filesToExport =
- selectedFiles.length > 0 ? selectedFiles : activeFiles;
- const stubs = filesToExport.map((file) =>
- isStirlingFile(file)
- ? selectors.getStirlingFileStub(file.fileId)
- : undefined,
- );
+ const viewExport = await viewFileActions?.getExportFiles?.();
+ if (viewExport === null) return;
+ const filesToExport = viewExport
+ ? viewExport.map((entry) => entry.file)
+ : selectedFiles.length > 0
+ ? selectedFiles
+ : activeFiles;
+ const stubs = viewExport
+ ? viewExport.map((entry) =>
+ entry.fileId
+ ? selectors.getStirlingFileStub(entry.fileId)
+ : undefined,
+ )
+ : filesToExport.map((file) =>
+ isStirlingFile(file)
+ ? selectors.getStirlingFileStub(file.fileId)
+ : undefined,
+ );
// Enforce all files in one batch so the toast shows progress across the
// whole set (e.g. "report.pdf (2 of 5)") rather than N invisible solo runs.
@@ -287,8 +326,8 @@ export default function WorkbenchBar({
currentView,
selectedFiles,
activeFiles,
- pageEditorFunctions,
viewerContext,
+ viewFileActions,
selectors,
fileActions,
],
@@ -299,7 +338,9 @@ export default function WorkbenchBar({
}, [viewerContext]);
const handleClose = useCallback(async () => {
- if (currentView === "fileEditor") {
+ if (viewFileActions?.onClose) {
+ viewFileActions.onClose();
+ } else if (currentView === "fileEditor" || currentView === "pageEditor") {
await fileActions.clearAllFiles();
} else if (currentView === "viewer") {
const file =
@@ -324,22 +365,18 @@ export default function WorkbenchBar({
} else if (countBeforeRemove <= 1) {
setCurrentView("fileEditor");
}
- } else if (currentView === "pageEditor") {
- pageEditorFunctions?.closePdf?.();
}
}, [
currentView,
+ viewFileActions,
fileActions,
activeFiles,
activeFileId,
setActiveFileId,
- pageEditorFunctions,
setCurrentView,
]);
const downloadTooltip = useMemo(() => {
- if (currentView === "pageEditor")
- return t("workbenchBar.exportAll", "Export PDF");
if (currentView === "viewer") return terminology.download;
if (selectedCount > 0) return terminology.downloadSelected;
return terminology.downloadAll;
@@ -434,21 +471,16 @@ export default function WorkbenchBar({
icon: <Icon name="file" size={20} />,
},
]),
+ {
+ value: "pageEditor",
+ label: t("workbenchBar.pageEditor", "Page Editor"),
+ icon: <Icon name="rows-3" size={20} />,
+ },
{
value: "fileEditor",
label: t("workbenchBar.activeFiles", "Active Files"),
icon: <Icon name="folder" size={20} />,
},
- ...(selectedTool === "multiTool"
- ? [
- {
- value: "pageEditor" as WorkbenchType,
- label: t("workbenchBar.multiTool", "Multi-Tool"),
- // The registry's multiTool glyph: one tool, one mark, wherever it is drawn.
- icon: <Icon name="grid-2x2-plus" size="1rem" />,
- },
- ]
- : []),
...customWorkbenchViews
.filter((v) => v.data != null)
.map((v) => ({
@@ -551,7 +583,13 @@ export default function WorkbenchBar({
label: (
<>
{opt.icon}
- <span className="workbench-bar-view-label">{opt.label}</span>
+ <span
+ className={`workbench-bar-view-label${
+ opt.value === openView ? " is-open" : ""
+ }`}
+ >
+ <span ref={measureViewLabel}>{opt.label}</span>
+ </span>
</>
),
}))}
diff --git a/frontend/editor/src/core/components/shared/pageEditor/useFileItemDragDrop.ts b/frontend/editor/src/core/components/shared/pageEditor/useFileItemDragDrop.ts
deleted file mode 100644
index c1f5d9aaf3..0000000000
--- a/frontend/editor/src/core/components/shared/pageEditor/useFileItemDragDrop.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { useRef, useEffect, useState } from "react";
-import {
- draggable,
- dropTargetForElements,
-} from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
-
-import { FileId } from "@app/types/file";
-
-interface UseFileItemDragDropParams {
- fileId: FileId;
- index: number;
- onReorder: (fromIndex: number, toIndex: number) => void;
-}
-
-interface UseFileItemDragDropReturn {
- itemRef: React.RefObject<HTMLDivElement | null>;
- isDragging: boolean;
- isDragOver: boolean;
- dropPosition: "above" | "below";
- movedRef: React.MutableRefObject<boolean>;
- startRef: React.MutableRefObject<{ x: number; y: number } | null>;
- onPointerDown: (e: React.PointerEvent) => void;
- onPointerMove: (e: React.PointerEvent) => void;
- onPointerUp: () => void;
-}
-
-/**
- * Hook to handle drag and drop functionality for file items in a list.
- * Manages drag state, drop zones, and reordering logic using Pragmatic Drag and Drop.
- */
-export const useFileItemDragDrop = ({
- fileId,
- index,
- onReorder,
-}: UseFileItemDragDropParams): UseFileItemDragDropReturn => {
- const [isDragging, setIsDragging] = useState(false);
- const [isDragOver, setIsDragOver] = useState(false);
- const [dropPosition, setDropPosition] = useState<"above" | "below">("below");
- const itemRef = useRef<HTMLDivElement>(null);
-
- // Keep latest values without re-registering DnD
- const indexRef = useRef(index);
- const fileIdRef = useRef(fileId);
- const dropPositionRef = useRef<"above" | "below">("below");
- const onReorderRef = useRef(onReorder);
-
- useEffect(() => {
- indexRef.current = index;
- }, [index]);
- useEffect(() => {
- fileIdRef.current = fileId;
- }, [fileId]);
- useEffect(() => {
- dropPositionRef.current = dropPosition;
- }, [dropPosition]);
- useEffect(() => {
- onReorderRef.current = onReorder;
- }, [onReorder]);
-
- // Gesture guard for row click vs drag
- const movedRef = useRef(false);
- const startRef = useRef<{ x: number; y: number } | null>(null);
-
- const onPointerDown = (e: React.PointerEvent) => {
- startRef.current = { x: e.clientX, y: e.clientY };
- movedRef.current = false;
- };
-
- const onPointerMove = (e: React.PointerEvent) => {
- if (!startRef.current) return;
- const dx = e.clientX - startRef.current.x;
- const dy = e.clientY - startRef.current.y;
- if (dx * dx + dy * dy > 25) movedRef.current = true; // ~5px threshold
- };
-
- const onPointerUp = () => {
- startRef.current = null;
- };
-
- useEffect(() => {
- const element = itemRef.current;
- if (!element) return;
-
- const dragCleanup = draggable({
- element,
- getInitialData: () => ({
- type: "file-item",
- fileId: fileIdRef.current,
- fromIndex: indexRef.current,
- }),
- onDragStart: () => setIsDragging((p) => (p ? p : true)),
- onDrop: () => setIsDragging((p) => (p ? false : p)),
- canDrag: () => true,
- });
-
- const dropCleanup = dropTargetForElements({
- element,
- getData: () => ({
- type: "file-item",
- fileId: fileIdRef.current,
- toIndex: indexRef.current,
- }),
- onDragEnter: () => setIsDragOver((p) => (p ? p : true)),
- onDragLeave: () => {
- setIsDragOver((p) => (p ? false : p));
- setDropPosition("below");
- },
- onDrag: ({ source }) => {
- // Determine drop position based on cursor location
- const element = itemRef.current;
- if (!element) return;
-
- const rect = element.getBoundingClientRect();
- const clientY = source.element?.getBoundingClientRect().top || 0;
- const midpoint = rect.top + rect.height / 2;
-
- setDropPosition(clientY < midpoint ? "below" : "above");
- },
- onDrop: ({ source }) => {
- setIsDragOver(false);
- const dropPos = dropPositionRef.current;
- setDropPosition("below");
- const sourceData = source.data as {
- type?: string;
- fromIndex?: number;
- };
- if (sourceData?.type === "file-item") {
- const fromIndex = sourceData.fromIndex as number;
- let toIndex = indexRef.current;
-
- // Adjust toIndex based on drop position
- if (dropPos === "below" && fromIndex < toIndex) {
- // Dragging down, drop after target - no adjustment needed
- } else if (dropPos === "above" && fromIndex > toIndex) {
- // Dragging up, drop before target - no adjustment needed
- } else if (dropPos === "below" && fromIndex > toIndex) {
- // Dragging up but want below target
- toIndex = toIndex + 1;
- } else if (dropPos === "above" && fromIndex < toIndex) {
- // Dragging down but want above target
- toIndex = toIndex - 1;
- }
-
- if (fromIndex !== toIndex) {
- onReorderRef.current(fromIndex, toIndex);
- }
- }
- },
- });
-
- return () => {
- try {
- dragCleanup();
- } catch {
- /* cleanup */
- }
- try {
- dropCleanup();
- } catch {
- /* cleanup */
- }
- };
- }, []); // Stable - no dependencies
-
- return {
- itemRef,
- isDragging,
- isDragOver,
- dropPosition,
- movedRef,
- startRef,
- onPointerDown,
- onPointerMove,
- onPointerUp,
- };
-};
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel.stories.tsx b/frontend/editor/src/core/components/shared/pageSelection/AdvancedSelectionPanel.stories.tsx
similarity index 81%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel.stories.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/AdvancedSelectionPanel.stories.tsx
index 5f3f1138d5..1c6cb90f3b 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel.stories.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/AdvancedSelectionPanel.stories.tsx
@@ -1,8 +1,8 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
-import AdvancedSelectionPanel from "@app/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel";
+import AdvancedSelectionPanel from "@app/components/shared/pageSelection/AdvancedSelectionPanel";
const meta = {
- title: "PageEditor/BulkSelectionPanel/AdvancedSelectionPanel",
+ title: "Shared/PageSelection/AdvancedSelectionPanel",
component: AdvancedSelectionPanel,
} satisfies Meta<typeof AdvancedSelectionPanel>;
export default meta;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel.tsx b/frontend/editor/src/core/components/shared/pageSelection/AdvancedSelectionPanel.tsx
similarity index 94%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/AdvancedSelectionPanel.tsx
index cb1d14b36a..221e530d58 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/AdvancedSelectionPanel.tsx
@@ -1,7 +1,7 @@
import { useState } from "react";
import { Flex } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
import {
appendExpression,
insertOperatorSmart,
@@ -11,8 +11,8 @@ import {
rangeExpression,
LogicalOperator,
} from "@app/utils/bulkselection/selectionBuilders";
-import SelectPages from "@app/components/pageEditor/bulkSelectionPanel/SelectPages";
-import OperatorsSection from "@app/components/pageEditor/bulkSelectionPanel/OperatorsSection";
+import SelectPages from "@app/components/shared/pageSelection/SelectPages";
+import OperatorsSection from "@app/components/shared/pageSelection/OperatorsSection";
interface AdvancedSelectionPanelProps {
csvInput: string;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css b/frontend/editor/src/core/components/shared/pageSelection/BulkSelectionPanel.module.css
similarity index 100%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css
rename to frontend/editor/src/core/components/shared/pageSelection/BulkSelectionPanel.module.css
diff --git a/frontend/editor/src/core/components/pageEditor/BulkSelectionPanel.tsx b/frontend/editor/src/core/components/shared/pageSelection/BulkSelectionPanel.tsx
similarity index 79%
rename from frontend/editor/src/core/components/pageEditor/BulkSelectionPanel.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/BulkSelectionPanel.tsx
index e369c6b59f..1ee0e5924a 100644
--- a/frontend/editor/src/core/components/pageEditor/BulkSelectionPanel.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/BulkSelectionPanel.tsx
@@ -1,9 +1,9 @@
import { useState } from "react";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
-import PageSelectionInput from "@app/components/pageEditor/bulkSelectionPanel/PageSelectionInput";
-import SelectedPagesDisplay from "@app/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
+import PageSelectionInput from "@app/components/shared/pageSelection/PageSelectionInput";
+import SelectedPagesDisplay from "@app/components/shared/pageSelection/SelectedPagesDisplay";
import PageSelectionSyntaxHint from "@app/components/shared/PageSelectionSyntaxHint";
-import AdvancedSelectionPanel from "@app/components/pageEditor/bulkSelectionPanel/AdvancedSelectionPanel";
+import AdvancedSelectionPanel from "@app/components/shared/pageSelection/AdvancedSelectionPanel";
interface BulkSelectionPanelProps {
csvInput: string;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/OperatorsSection.stories.tsx b/frontend/editor/src/core/components/shared/pageSelection/OperatorsSection.stories.tsx
similarity index 75%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/OperatorsSection.stories.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/OperatorsSection.stories.tsx
index b913dbbde5..ddad2082ef 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/OperatorsSection.stories.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/OperatorsSection.stories.tsx
@@ -1,8 +1,8 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
-import OperatorsSection from "@app/components/pageEditor/bulkSelectionPanel/OperatorsSection";
+import OperatorsSection from "@app/components/shared/pageSelection/OperatorsSection";
const meta = {
- title: "PageEditor/BulkSelectionPanel/OperatorsSection",
+ title: "Shared/PageSelection/OperatorsSection",
component: OperatorsSection,
} satisfies Meta<typeof OperatorsSection>;
export default meta;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/OperatorsSection.tsx b/frontend/editor/src/core/components/shared/pageSelection/OperatorsSection.tsx
similarity index 96%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/OperatorsSection.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/OperatorsSection.tsx
index 682a134268..4f0b7aa210 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/OperatorsSection.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/OperatorsSection.tsx
@@ -1,7 +1,7 @@
import { Text, Group, Divider } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { useTranslation } from "react-i18next";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
import { LogicalOperator } from "@app/utils/bulkselection/selectionBuilders";
interface OperatorsSectionProps {
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/PageSelectionInput.tsx b/frontend/editor/src/core/components/shared/pageSelection/PageSelectionInput.tsx
similarity index 95%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/PageSelectionInput.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/PageSelectionInput.tsx
index 731614bab9..f055168dc8 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/PageSelectionInput.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/PageSelectionInput.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
import { Tooltip } from "@app/components/shared/Tooltip";
import { usePageSelectionTips } from "@app/components/tooltips/usePageSelectionTips";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
interface PageSelectionInputProps {
csvInput: string;
@@ -66,7 +66,6 @@ const PageSelectionInput = ({
)}
</Flex>
- {/* Text input */}
<TextInput
value={csvInput}
onChange={(e) => {
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectPages.stories.tsx b/frontend/editor/src/core/components/shared/pageSelection/SelectPages.stories.tsx
similarity index 89%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectPages.stories.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/SelectPages.stories.tsx
index 3f3ff93a94..54dbafbe0b 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectPages.stories.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/SelectPages.stories.tsx
@@ -1,8 +1,8 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
-import SelectPages from "@app/components/pageEditor/bulkSelectionPanel/SelectPages";
+import SelectPages from "@app/components/shared/pageSelection/SelectPages";
const meta = {
- title: "PageEditor/SelectPages",
+ title: "Shared/PageSelection/SelectPages",
component: SelectPages,
} satisfies Meta<typeof SelectPages>;
export default meta;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectPages.tsx b/frontend/editor/src/core/components/shared/pageSelection/SelectPages.tsx
similarity index 96%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectPages.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/SelectPages.tsx
index 5553579f59..ff768ac2b1 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectPages.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/SelectPages.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import { Text, NumberInput, Group } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { useTranslation } from "react-i18next";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
interface SelectPagesProps {
title: string;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay.stories.tsx b/frontend/editor/src/core/components/shared/pageSelection/SelectedPagesDisplay.stories.tsx
similarity index 82%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay.stories.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/SelectedPagesDisplay.stories.tsx
index 3b5d8421d1..57b3c92d66 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay.stories.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/SelectedPagesDisplay.stories.tsx
@@ -1,5 +1,5 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
-import SelectedPagesDisplay from "@app/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay";
+import SelectedPagesDisplay from "@app/components/shared/pageSelection/SelectedPagesDisplay";
const displayDocument = {
pages: [
@@ -11,7 +11,7 @@ const displayDocument = {
};
const meta = {
- title: "PageEditor/SelectedPagesDisplay",
+ title: "Shared/PageSelection/SelectedPagesDisplay",
component: SelectedPagesDisplay,
} satisfies Meta<typeof SelectedPagesDisplay>;
export default meta;
diff --git a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay.tsx b/frontend/editor/src/core/components/shared/pageSelection/SelectedPagesDisplay.tsx
similarity index 93%
rename from frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay.tsx
rename to frontend/editor/src/core/components/shared/pageSelection/SelectedPagesDisplay.tsx
index 672bb583c5..87a8c5ed56 100644
--- a/frontend/editor/src/core/components/pageEditor/bulkSelectionPanel/SelectedPagesDisplay.tsx
+++ b/frontend/editor/src/core/components/shared/pageSelection/SelectedPagesDisplay.tsx
@@ -1,6 +1,6 @@
import { Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import classes from "@app/components/pageEditor/bulkSelectionPanel/BulkSelectionPanel.module.css";
+import classes from "@app/components/shared/pageSelection/BulkSelectionPanel.module.css";
interface SelectedPagesDisplayProps {
selectedPageIds: string[];
diff --git a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
index 109af414a9..216399957f 100644
--- a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
+++ b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
@@ -33,7 +33,7 @@ export default function WorkbenchBarDesktopActions({
const { t } = useTranslation();
const exportDisabled = actionsDisabled || policyEnforcing;
const closeLabel =
- currentView === "fileEditor"
+ currentView === "fileEditor" || currentView === "pageEditor"
? t("workbenchBar.closeAll", "Close All")
: t("workbenchBar.closePdf", "Close PDF");
diff --git a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
index 7c4ff6bc49..a2aafe9302 100644
--- a/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
+++ b/frontend/editor/src/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
@@ -78,7 +78,7 @@ export default function WorkbenchBarMobileActions({
disabled={actionsDisabled}
onClick={() => void onClose()}
>
- {currentView === "fileEditor"
+ {currentView === "fileEditor" || currentView === "pageEditor"
? t("workbenchBar.closeAll", "Close All")
: t("workbenchBar.closePdf", "Close PDF")}
</Menu.Item>
diff --git a/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx b/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx
index 830bd6f7ca..c0ef31cd4f 100644
--- a/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx
+++ b/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx
@@ -7,7 +7,7 @@ import type {
ParticipantInfo,
SigningParticipantPreview,
} from "@app/types/signingSession";
-import { getFileColor } from "@app/components/pageEditor/fileColors";
+import { getFileColor } from "@app/utils/fileColors";
import "@app/components/shared/signing/signingDetail.css";
interface ParticipantListPanelProps {
diff --git a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx b/frontend/editor/src/core/contexts/FilesModalContext.test.tsx
index 0f537aff98..29d22a7900 100644
--- a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx
+++ b/frontend/editor/src/core/contexts/FilesModalContext.test.tsx
@@ -25,6 +25,7 @@ const state = vi.hoisted(() => ({
addStirlingFileStubs: vi.fn().mockResolvedValue(undefined),
setSelectedFiles: vi.fn(),
setWorkbench: vi.fn(),
+ workbench: "fileEditor",
getStirlingFile: vi.fn(),
apiGet: vi.fn(),
}));
@@ -49,14 +50,17 @@ vi.mock("@app/contexts/NavigationContext", () => ({
useNavigationActions: () => ({
actions: { setWorkbench: state.setWorkbench },
}),
- useNavigationState: () => ({ workbench: "pageEditor" }),
+ useNavigationState: () => ({ workbench: state.workbench }),
}));
vi.mock("@app/services/fileStorage", () => ({
fileStorage: { getStirlingFile: state.getStirlingFile },
}));
vi.mock("@app/services/apiClient", () => ({ default: { get: state.apiGet } }));
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.workbench = "fileEditor";
+});
describe("file picker caller contract", () => {
it("clears a caller's format and count restrictions when the next picker opens", () => {
@@ -288,6 +292,18 @@ describe("file picker caller contract", () => {
expect(state.setWorkbench).toHaveBeenCalledWith("fileEditor");
});
+ it("stays in the page editor, which lays out the added files itself", async () => {
+ state.workbench = "pageEditor";
+ const upload = new File(["upload"], "Upload.pdf");
+ const { result } = renderHook(useFilesModalContext, {
+ wrapper: FilesModalProvider,
+ });
+ act(() => result.current.openFilesModal());
+ await act(() => result.current.onRecentFileSelect([], [upload]));
+ expect(state.addFiles).toHaveBeenCalledWith([upload]);
+ expect(state.setWorkbench).not.toHaveBeenCalled();
+ });
+
it("does not close a reopened picker when a previous import finishes", async () => {
let finishImport!: () => void;
state.addFiles.mockReturnValueOnce(
diff --git a/frontend/editor/src/core/contexts/FilesModalContext.tsx b/frontend/editor/src/core/contexts/FilesModalContext.tsx
index 1790ad9b5c..7e9b8d2987 100644
--- a/frontend/editor/src/core/contexts/FilesModalContext.tsx
+++ b/frontend/editor/src/core/contexts/FilesModalContext.tsx
@@ -70,9 +70,9 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
const { actions } = useFileActions();
const fileCtx = useFileContext();
const { actions: navActions } = useNavigationActions();
- const { workbench: currentWorkbench, selectedTool } = useNavigationState();
- const isMultiTool =
- currentWorkbench === "pageEditor" && selectedTool === "multiTool";
+ const { workbench: currentWorkbench } = useNavigationState();
+ // The page editor lays out every open file, so an added file belongs there.
+ const staysOnAdd = currentWorkbench === "pageEditor";
const [isFilesModalOpen, setIsFilesModalOpen] = useState(false);
const [onModalClose, setOnModalClose] = useState<(() => void) | undefined>();
const [insertAfterPage, setInsertAfterPage] = useState<number | undefined>();
@@ -326,7 +326,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
);
const totalAdded = requestedIds.length + uploads.length;
- if (!isMultiTool && totalAdded > 0) {
+ if (!staysOnAdd && totalAdded > 0) {
navActions.setWorkbench(totalAdded === 1 ? "viewer" : "fileEditor");
}
reportUnavailable();
@@ -341,7 +341,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({
downloadRemoteFile,
importBundleToWorkbench,
navActions,
- isMultiTool,
+ staysOnAdd,
t,
],
);
diff --git a/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx b/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
deleted file mode 100644
index 2dcf29f71e..0000000000
--- a/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { renderHook, act } from "@testing-library/react";
-import type { ReactNode } from "react";
-import type { FileId, StirlingFileStub } from "@app/types/fileContext";
-
-const fileState = {
- state: {
- files: {
- ids: [] as FileId[],
- byId: {} as Record<FileId, Partial<StirlingFileStub>>,
- },
- },
-};
-
-vi.mock("@app/contexts/FileContext", () => ({
- useFileActions: () => ({ actions: {} }),
- useFileState: () => fileState,
-}));
-
-vi.mock("@app/contexts/NavigationContext", () => ({
- useNavigationState: () => ({ currentMode: "pageEditor" }),
-}));
-
-const { PageEditorProvider, usePageEditor } =
- await import("@app/contexts/PageEditorContext");
-
-const stub = (size: number, lastModified: number) =>
- ({ size, lastModified }) as Partial<StirlingFileStub>;
-
-const setFiles = (entries: [string, Partial<StirlingFileStub>][]) => {
- fileState.state = {
- files: {
- ids: entries.map(([id]) => id as FileId),
- byId: Object.fromEntries(entries),
- },
- };
-};
-
-const wrapper = ({ children }: { children: ReactNode }) => (
- <PageEditorProvider>{children}</PageEditorProvider>
-);
-
-describe("PageEditorContext contentRevision", () => {
- beforeEach(() => setFiles([["A", stub(100, 1)]]));
-
- it("does not bump when another file is added", () => {
- const view = renderHook(() => usePageEditor(), { wrapper });
- const before = view.result.current.contentRevision;
-
- act(() => {
- setFiles([
- ["A", stub(100, 1)],
- ["B", stub(200, 2)],
- ]);
- view.rerender();
- });
-
- expect(view.result.current.contentRevision).toBe(before);
- });
-
- it("does not bump when a file is removed", () => {
- setFiles([
- ["A", stub(100, 1)],
- ["B", stub(200, 2)],
- ]);
- const view = renderHook(() => usePageEditor(), { wrapper });
- const before = view.result.current.contentRevision;
-
- act(() => {
- setFiles([["A", stub(100, 1)]]);
- view.rerender();
- });
-
- expect(view.result.current.contentRevision).toBe(before);
- });
-
- it("bumps when the bytes behind an open file are replaced", () => {
- const view = renderHook(() => usePageEditor(), { wrapper });
- const before = view.result.current.contentRevision;
-
- act(() => {
- setFiles([["A", stub(555, 9)]]);
- view.rerender();
- });
-
- expect(view.result.current.contentRevision).toBe(before + 1);
- });
-
- it("still bumps on a replacement that arrives alongside an addition", () => {
- const view = renderHook(() => usePageEditor(), { wrapper });
- const before = view.result.current.contentRevision;
-
- act(() => {
- setFiles([
- ["A", stub(555, 9)],
- ["B", stub(200, 2)],
- ]);
- view.rerender();
- });
-
- expect(view.result.current.contentRevision).toBe(before + 1);
- });
-});
diff --git a/frontend/editor/src/core/contexts/PageEditorContext.tsx b/frontend/editor/src/core/contexts/PageEditorContext.tsx
deleted file mode 100644
index d58439f512..0000000000
--- a/frontend/editor/src/core/contexts/PageEditorContext.tsx
+++ /dev/null
@@ -1,595 +0,0 @@
-import React, {
- createContext,
- useContext,
- useState,
- useCallback,
- ReactNode,
- useMemo,
- useRef,
- useEffect,
-} from "react";
-import { FileId } from "@app/types/file";
-import { useFileActions, useFileState } from "@app/contexts/FileContext";
-import { PDFDocument, PDFPage } from "@app/types/pageEditor";
-import { MAX_PAGE_EDITOR_FILES } from "@app/components/pageEditor/fileColors";
-import { useNavigationState } from "@app/contexts/NavigationContext";
-
-// PageEditorFile is now defined locally in consuming components
-// Components should derive file list directly from FileContext
-
-/**
- * Computes file order based on the position of each file's first page
- * @param pages - Current page order
- * @returns Array of FileIds in order based on first page positions
- */
-function computeFileOrderFromPages(pages: PDFPage[]): FileId[] {
- // Find the first page for each file
- const fileFirstPagePositions = new Map<FileId, number>();
-
- pages.forEach((page, index) => {
- const fileId = page.originalFileId;
- if (!fileId) return;
-
- if (!fileFirstPagePositions.has(fileId)) {
- fileFirstPagePositions.set(fileId, index);
- }
- });
-
- // Sort files by their first page position
- const fileOrder = Array.from(fileFirstPagePositions.entries())
- .sort((a, b) => a[1] - b[1])
- .map((entry) => entry[0]);
-
- return fileOrder;
-}
-
-/**
- * Reorders pages based on file reordering while preserving interlacing and manual page order
- * @param currentPages - Current page order (may include manual reordering and interlacing)
- * @param fromIndex - Source file index in the file order
- * @param toIndex - Target file index in the file order
- * @param orderedFileIds - File IDs in their current order
- * @returns Reordered pages with updated page numbers
- */
-function reorderPagesForFileMove(
- currentPages: PDFPage[],
- fromIndex: number,
- toIndex: number,
- orderedFileIds: FileId[],
-): PDFPage[] {
- // Get the file ID being moved
- const movedFileId = orderedFileIds[fromIndex];
- const targetFileId = orderedFileIds[toIndex];
-
- // Extract pages belonging to the moved file (maintaining their relative order)
- const movedFilePages: PDFPage[] = [];
- const remainingPages: PDFPage[] = [];
-
- currentPages.forEach((page) => {
- if (page.originalFileId === movedFileId) {
- movedFilePages.push(page);
- } else {
- remainingPages.push(page);
- }
- });
-
- // Find the insertion point based on the target file
- let insertionIndex = 0;
-
- if (fromIndex < toIndex) {
- // Moving down: insert AFTER the last page of ANY file that should come before us
- // We need to find the last page belonging to any file at index <= toIndex in orderedFileIds
- const filesBeforeUs = new Set(orderedFileIds.slice(0, toIndex + 1));
- for (let i = remainingPages.length - 1; i >= 0; i--) {
- const pageFileId = remainingPages[i].originalFileId;
- if (pageFileId && filesBeforeUs.has(pageFileId)) {
- insertionIndex = i + 1;
- break;
- }
- }
- } else {
- // Moving up: insert BEFORE the first page of target file
- for (let i = 0; i < remainingPages.length; i++) {
- if (remainingPages[i].originalFileId === targetFileId) {
- insertionIndex = i;
- break;
- }
- }
- }
-
- // Insert moved pages at the calculated position
- const reorderedPages = [
- ...remainingPages.slice(0, insertionIndex),
- ...movedFilePages,
- ...remainingPages.slice(insertionIndex),
- ];
-
- // Renumber all pages sequentially (clone to avoid mutation)
- return reorderedPages.map((page, index) => ({
- ...page,
- pageNumber: index + 1,
- }));
-}
-
-interface PageEditorContextValue {
- // Current page order (updated by PageEditor, used for file reordering)
- currentPages: PDFPage[] | null;
- updateCurrentPages: (pages: PDFPage[] | null) => void;
-
- // Reordered pages (when file reordering happens)
- reorderedPages: PDFPage[] | null;
- clearReorderedPages: () => void;
-
- // Page editor's own file order (independent of FileContext global order)
- fileOrder: FileId[];
- setFileOrder: (order: FileId[]) => void;
-
- // Set file selection (calls FileContext actions)
- setFileSelection: (fileId: FileId, selected: boolean) => void;
-
- // Toggle file selection (calls FileContext actions)
- toggleFileSelection: (fileId: FileId) => void;
-
- // Select/deselect all files (calls FileContext actions)
- selectAll: () => void;
- deselectAll: () => void;
-
- // Reorder files (only affects page editor's local order)
- reorderFiles: (fromIndex: number, toIndex: number) => void;
-
- // Update file order based on page positions (when pages are manually reordered)
- updateFileOrderFromPages: (pages: PDFPage[]) => void;
- persistedDocument: PDFDocument | null;
- persistedDocumentSignature: string | null;
- savePersistedDocument: (document: PDFDocument, signature: string) => void;
- clearPersistedDocument: () => void;
- /** Bumps whenever the bytes behind the open files are replaced under an
- * unchanged file id, which is what a disk reload does. Anything laid out
- * from those bytes has to start over rather than merge into what replaced
- * them. */
- contentRevision: number;
-}
-
-const PageEditorContext = createContext<PageEditorContextValue | undefined>(
- undefined,
-);
-
-interface PageEditorProviderProps {
- children: ReactNode;
-}
-
-export function PageEditorProvider({ children }: PageEditorProviderProps) {
- const [currentPages, setCurrentPages] = useState<PDFPage[] | null>(null);
- const [reorderedPages, setReorderedPages] = useState<PDFPage[] | null>(null);
-
- const [persistedDocument, setPersistedDocument] =
- useState<PDFDocument | null>(null);
- const [persistedDocumentSignature, setPersistedDocumentSignature] = useState<
- string | null
- >(null);
-
- const savePersistedDocument = useCallback(
- (document: PDFDocument, signature: string) => {
- setPersistedDocument(document);
- setPersistedDocumentSignature(signature);
- },
- [],
- );
-
- const clearPersistedDocument = useCallback(() => {
- console.log("[PageEditorContext] Clearing persisted document");
- setPersistedDocument(null);
- setPersistedDocumentSignature(null);
- setCurrentPages(null);
- }, []);
-
- // Page editor's own file order (independent of FileContext)
- const [fileOrder, setFileOrder] = useState<FileId[]>([]);
-
- // Read from FileContext (for file metadata only, not order)
- const { actions: fileActions } = useFileActions();
- const { state } = useFileState();
-
- const navigationState = useNavigationState();
- const prevWorkbenchRef = useRef(navigationState.workbench);
- useEffect(() => {
- const prevWorkbench = prevWorkbenchRef.current;
- const nextWorkbench = navigationState.workbench;
- const isLeavingPageEditor =
- prevWorkbench === "pageEditor" && nextWorkbench !== "pageEditor";
- const isEnteringPageEditor =
- prevWorkbench !== "pageEditor" && nextWorkbench === "pageEditor";
-
- if (isLeavingPageEditor) {
- clearPersistedDocument();
- }
-
- if (isEnteringPageEditor) {
- prevFileContextIdsRef.current = state.files.ids;
- setReorderedPages(null);
- setCurrentPages(null); // Force clear current pages when entering
- setFileOrder((currentOrder) => {
- const validOrder = currentOrder.filter((id) =>
- state.files.ids.includes(id),
- );
- const newIds = state.files.ids.filter((id) => !validOrder.includes(id));
- if (newIds.length === 0 && validOrder.length === currentOrder.length) {
- return currentOrder;
- }
- return [...validOrder, ...newIds];
- });
- clearPersistedDocument();
- // Select all workbench files so they render as expanded pages
- fileActions.setSelectedFiles(state.files.ids);
- }
-
- prevWorkbenchRef.current = nextWorkbench;
- }, [
- navigationState.workbench,
- clearPersistedDocument,
- state.files.ids,
- setFileOrder,
- setReorderedPages,
- fileActions,
- ]);
-
- const fileContextSignature = useMemo(() => {
- return state.files.ids
- .map((id) => `${id}:${state.files.byId[id]?.versionNumber ?? 0}`)
- .join(",");
- }, [state.files.ids, state.files.byId]);
-
- // Bytes can be replaced under an unchanged id and version - reconciling a
- // record with its source does exactly that - and the laid-out document would
- // then describe pages that no longer exist. Keyed per id rather than joined:
- // a join also changes when the file set does, and adding a file would then
- // read as every open document being replaced.
- const fileContentKeys = useMemo(() => {
- const keys = new Map<FileId, string>();
- for (const id of state.files.ids) {
- const stub = state.files.byId[id];
- keys.set(id, `${stub?.size ?? 0}:${stub?.lastModified ?? 0}`);
- }
- return keys;
- }, [state.files.ids, state.files.byId]);
-
- const prevFileContextSignature = useRef<string | null>(null);
- const prevFileContentKeys = useRef<Map<FileId, string> | null>(null);
- const [contentRevision, setContentRevision] = useState(0);
- const haveFileIdSetsChanged = (prevIds: FileId[], currentIds: FileId[]) => {
- if (prevIds.length !== currentIds.length) {
- return true;
- }
- const prevSet = new Set(prevIds);
- for (const id of currentIds) {
- if (!prevSet.has(id)) {
- return true;
- }
- }
- return false;
- };
- useEffect(() => {
- const currentFileIds = state.files.ids;
- const prevFileIds = prevFileContextIdsRef.current;
- const idsChanged = haveFileIdSetsChanged(prevFileIds, currentFileIds);
- const previousContentKeys = prevFileContentKeys.current;
- // Only an id carried over from the previous set can have had its bytes
- // replaced. One that arrived or left is a file-set change, which the merge
- // below folds in without discarding the edits on everything else.
- const contentChanged =
- previousContentKeys !== null &&
- currentFileIds.some((id) => {
- const previousKey = previousContentKeys.get(id);
- return (
- previousKey !== undefined && previousKey !== fileContentKeys.get(id)
- );
- });
- prevFileContentKeys.current = fileContentKeys;
- // Clearing the persisted document only invalidates the cache. The live
- // document is held by the editor and has to be told to start over too.
- if (contentChanged) setContentRevision((revision) => revision + 1);
-
- if (
- !idsChanged &&
- !contentChanged &&
- prevFileContextSignature.current === fileContextSignature
- ) {
- return;
- }
-
- const previousSignature = prevFileContextSignature.current;
- prevFileContextSignature.current = fileContextSignature;
-
- if (!idsChanged && !contentChanged) {
- // Signature changed due to metadata/version updates but file set is unchanged.
- return;
- }
-
- console.log(
- "[PageEditorContext] Files changed, clearing persisted document:",
- {
- reason: idsChanged ? "file set" : "content",
- prev: previousSignature?.substring(0, 50),
- current: fileContextSignature.substring(0, 50),
- },
- );
- clearPersistedDocument();
- }, [
- fileContextSignature,
- fileContentKeys,
- clearPersistedDocument,
- state.files.ids,
- ]);
-
- // Keep a ref to always read latest state in stable callbacks
- const stateRef = useRef(state);
- useEffect(() => {
- stateRef.current = state;
- }, [state]);
-
- // Track the previous FileContext order to detect actual changes
- const prevFileContextIdsRef = useRef<FileId[]>([]);
-
- // Initialize fileOrder from FileContext when files change (add/remove only)
- useEffect(() => {
- const currentFileIds = state.files.ids;
- const prevFileIds = prevFileContextIdsRef.current;
-
- // Only react to FileContext changes, not our own fileOrder changes
- const fileContextChanged = haveFileIdSetsChanged(
- prevFileIds,
- currentFileIds,
- );
-
- if (!fileContextChanged) {
- return;
- }
-
- console.log("[PageEditorContext] FileContext files changed:", {
- prevCount: prevFileIds.length,
- currentCount: currentFileIds.length,
- added: currentFileIds.filter((id) => !prevFileIds.includes(id)).length,
- removed: prevFileIds.filter((id) => !currentFileIds.includes(id)).length,
- });
-
- clearPersistedDocument();
-
- prevFileContextIdsRef.current = currentFileIds;
-
- // Collect new file IDs outside the setState callback so we can clear them after
- let newFileIdsToProcess: FileId[] = [];
-
- // Use functional setState to read latest fileOrder without depending on it
- setFileOrder((currentOrder) => {
- // Identify new files
- const newFileIds = currentFileIds.filter(
- (id) => !currentOrder.includes(id),
- );
- newFileIdsToProcess = newFileIds; // Store for cleanup
-
- // Remove deleted files
- const validFileOrder = currentOrder.filter((id) =>
- currentFileIds.includes(id),
- );
-
- if (
- newFileIds.length === 0 &&
- validFileOrder.length === currentOrder.length
- ) {
- return currentOrder; // No changes needed
- }
-
- // Always append new files to end
- // If files have insertAfterPageId, page-level insertion is handled by usePageDocument
- return [...validFileOrder, ...newFileIds];
- });
-
- // Clear insertAfterPageId after a delay to allow usePageDocument to consume it first
- setTimeout(() => {
- newFileIdsToProcess.forEach((fileId) => {
- const stub = state.files.byId[fileId];
- if (stub?.insertAfterPageId) {
- fileActions.updateStirlingFileStub(fileId, {
- insertAfterPageId: undefined,
- });
- }
- });
- }, 100);
- }, [state.files.ids, state.files.byId, fileActions]);
-
- const updateCurrentPages = useCallback((pages: PDFPage[] | null) => {
- setCurrentPages(pages);
- }, []);
-
- const clearReorderedPages = useCallback(() => {
- setReorderedPages(null);
- }, []);
-
- const setFileSelection = useCallback(
- (fileId: FileId, selected: boolean) => {
- const currentSelection = stateRef.current.ui.selectedFileIds;
- const isAlreadySelected = currentSelection.includes(fileId);
-
- // Check if we're trying to select when at limit
- if (
- selected &&
- !isAlreadySelected &&
- currentSelection.length >= MAX_PAGE_EDITOR_FILES
- ) {
- console.warn(
- `Page editor supports maximum ${MAX_PAGE_EDITOR_FILES} files. Cannot select more files.`,
- );
- return;
- }
-
- // Update FileContext selection
- const newSelectedIds = selected
- ? [...currentSelection, fileId]
- : currentSelection.filter((id) => id !== fileId);
-
- fileActions.setSelectedFiles(newSelectedIds);
- },
- [fileActions],
- );
-
- const toggleFileSelection = useCallback(
- (fileId: FileId) => {
- const currentSelection = stateRef.current.ui.selectedFileIds;
- const isCurrentlySelected = currentSelection.includes(fileId);
-
- // If toggling on and at limit, don't allow
- if (
- !isCurrentlySelected &&
- currentSelection.length >= MAX_PAGE_EDITOR_FILES
- ) {
- console.warn(
- `Page editor supports maximum ${MAX_PAGE_EDITOR_FILES} files. Cannot select more files.`,
- );
- return;
- }
-
- // Update FileContext selection
- const newSelectedIds = isCurrentlySelected
- ? currentSelection.filter((id) => id !== fileId)
- : [...currentSelection, fileId];
-
- fileActions.setSelectedFiles(newSelectedIds);
- },
- [fileActions],
- );
-
- const selectAll = useCallback(() => {
- const allFileIds = stateRef.current.files.ids;
-
- if (allFileIds.length > MAX_PAGE_EDITOR_FILES) {
- console.warn(
- `Page editor supports maximum ${MAX_PAGE_EDITOR_FILES} files. Only first ${MAX_PAGE_EDITOR_FILES} files will be selected.`,
- );
- fileActions.setSelectedFiles(allFileIds.slice(0, MAX_PAGE_EDITOR_FILES));
- } else {
- fileActions.setSelectedFiles(allFileIds);
- }
- }, [fileActions]);
-
- const deselectAll = useCallback(() => {
- fileActions.setSelectedFiles([]);
- }, [fileActions]);
-
- const reorderFiles = useCallback(
- (fromIndex: number, toIndex: number) => {
- // Reorder local fileOrder array (page editor workspace only)
- const newOrder = [...fileOrder];
- const [movedFileId] = newOrder.splice(fromIndex, 1);
- newOrder.splice(toIndex, 0, movedFileId);
- setFileOrder(newOrder);
-
- // If current pages available, reorder them based on file move
- if (currentPages && currentPages.length > 0 && fromIndex !== toIndex) {
- // Get the current file order from pages (files that have pages loaded)
- const currentFileOrder: FileId[] = [];
- const filesSeen = new Set<FileId>();
- currentPages.forEach((page) => {
- const fileId = page.originalFileId;
- if (fileId && !filesSeen.has(fileId)) {
- filesSeen.add(fileId);
- currentFileOrder.push(fileId);
- }
- });
-
- // Get the target file ID from the NEW order (after the move)
- // When moving down: we want to position after the file at toIndex-1 (file just before insertion)
- // When moving up: we want to position before the file at toIndex+1 (file just after insertion)
- const targetFileId =
- fromIndex < toIndex
- ? newOrder[toIndex - 1] // Moving down: target is the file just before where we inserted
- : newOrder[toIndex + 1]; // Moving up: target is the file just after where we inserted
-
- // Find their positions in the current page order (not the full file list)
- const pageOrderFromIndex = currentFileOrder.findIndex(
- (id) => id === movedFileId,
- );
- const pageOrderToIndex = currentFileOrder.findIndex(
- (id) => id === targetFileId,
- );
-
- // Only reorder pages if both files have pages loaded
- if (pageOrderFromIndex >= 0 && pageOrderToIndex >= 0) {
- const reorderedPagesResult = reorderPagesForFileMove(
- currentPages,
- pageOrderFromIndex,
- pageOrderToIndex,
- currentFileOrder,
- );
- setReorderedPages(reorderedPagesResult);
- }
- }
- },
- [fileOrder, currentPages],
- );
-
- const updateFileOrderFromPages = useCallback((pages: PDFPage[]) => {
- if (!pages || pages.length === 0) return;
-
- // Compute the new file order based on page positions
- const newFileOrder = computeFileOrderFromPages(pages);
-
- if (newFileOrder.length > 0) {
- // Update local page editor file order (not FileContext)
- setFileOrder(newFileOrder);
- }
- }, []);
-
- const value: PageEditorContextValue = useMemo(
- () => ({
- currentPages,
- updateCurrentPages,
- reorderedPages,
- clearReorderedPages,
- fileOrder,
- setFileOrder,
- setFileSelection,
- toggleFileSelection,
- selectAll,
- deselectAll,
- reorderFiles,
- updateFileOrderFromPages,
- persistedDocument,
- persistedDocumentSignature,
- savePersistedDocument,
- clearPersistedDocument,
- contentRevision,
- }),
- [
- contentRevision,
- currentPages,
- updateCurrentPages,
- reorderedPages,
- clearReorderedPages,
- fileOrder,
- setFileSelection,
- toggleFileSelection,
- selectAll,
- deselectAll,
- reorderFiles,
- updateFileOrderFromPages,
- persistedDocument,
- persistedDocumentSignature,
- savePersistedDocument,
- clearPersistedDocument,
- ],
- );
-
- return (
- <PageEditorContext.Provider value={value}>
- {children}
- </PageEditorContext.Provider>
- );
-}
-
-export function usePageEditor() {
- const context = useContext(PageEditorContext);
- if (!context) {
- throw new Error("usePageEditor must be used within PageEditorProvider");
- }
- return context;
-}
diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
index c4a67c2569..b1ef312d05 100644
--- a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
@@ -16,7 +16,6 @@ import {
useToolManagement,
type ToolAvailabilityMap,
} from "@app/hooks/useToolManagement";
-import { PageEditorFunctions } from "@app/types/pageEditor";
import { ToolRegistryEntry, ToolRegistry } from "@app/data/toolsTaxonomy";
import {
useNavigationActions,
@@ -80,7 +79,6 @@ interface ToolWorkflowContextValue extends ToolWorkflowState {
/** Register work that turns the current preview into a real file. Tool
* selection runs it first, so a tool never acts on the wrong document. */
registerPreviewImport: (importFile: (() => Promise<void>) | null) => void;
- setPageEditorFunctions: (functions: PageEditorFunctions | null) => void;
setSearchQuery: (query: string) => void;
selectTool: (toolId: ToolId | null) => void;
@@ -157,7 +155,6 @@ export interface ToolWorkflowActionsValue {
/** Register work that turns the current preview into a real file. Tool
* selection runs it first, so a tool never acts on the wrong document. */
registerPreviewImport: (importFile: (() => Promise<void>) | null) => void;
- setPageEditorFunctions: (functions: PageEditorFunctions | null) => void;
setSearchQuery: (query: string) => void;
registerToolReset: (toolId: string, resetFunction: () => void) => void;
resetTool: (toolId: string) => void;
@@ -263,13 +260,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
[],
);
- const setPageEditorFunctions = useCallback(
- (functions: PageEditorFunctions | null) => {
- dispatch({ type: "SET_PAGE_EDITOR_FUNCTIONS", payload: functions });
- },
- [],
- );
-
const setSearchQuery = useCallback((query: string) => {
dispatch({ type: "SET_SEARCH_QUERY", payload: query });
}, []);
@@ -684,7 +674,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
setToolPanelMode: stableSetToolPanelMode,
setPreviewFile: stableSetPreviewFile,
registerPreviewImport,
- setPageEditorFunctions,
setSearchQuery,
registerToolReset,
resetTool,
@@ -701,7 +690,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
stableSetReaderMode,
stableSetToolPanelMode,
stableSetPreviewFile,
- setPageEditorFunctions,
setSearchQuery,
registerToolReset,
resetTool,
@@ -741,7 +729,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
setToolPanelMode,
setPreviewFile,
registerPreviewImport,
- setPageEditorFunctions,
setSearchQuery,
selectTool: actions.setSelectedTool,
clearToolSelection: () => actions.setSelectedTool(null),
@@ -784,7 +771,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
setReaderMode,
setToolPanelMode,
setPreviewFile,
- setPageEditorFunctions,
setSearchQuery,
actions.setSelectedTool,
registerToolReset,
diff --git a/frontend/editor/src/core/contexts/WorkbenchBarContext.tsx b/frontend/editor/src/core/contexts/WorkbenchBarContext.tsx
index 4c1e7198ab..df7fe0e1c4 100644
--- a/frontend/editor/src/core/contexts/WorkbenchBarContext.tsx
+++ b/frontend/editor/src/core/contexts/WorkbenchBarContext.tsx
@@ -8,12 +8,15 @@ import React, {
import {
WorkbenchBarAction,
WorkbenchBarButtonConfig,
+ WorkbenchViewFileActions,
} from "@app/types/workbenchBar";
interface WorkbenchBarContextValue {
buttons: WorkbenchBarButtonConfig[];
actions: Record<string, WorkbenchBarAction>;
allButtonsDisabled: boolean;
+ viewFileActions: WorkbenchViewFileActions | null;
+ setViewFileActions: (actions: WorkbenchViewFileActions | null) => void;
registerButtons: (buttons: WorkbenchBarButtonConfig[]) => void;
unregisterButtons: (ids: string[]) => void;
setAction: (id: string, action?: WorkbenchBarAction) => void;
@@ -36,6 +39,8 @@ export function WorkbenchBarProvider({
);
const [allButtonsDisabled, setAllButtonsDisabledState] =
useState<boolean>(false);
+ const [viewFileActions, setViewFileActions] =
+ useState<WorkbenchViewFileActions | null>(null);
const registerButtons = useCallback(
(newButtons: WorkbenchBarButtonConfig[]) => {
@@ -99,6 +104,8 @@ export function WorkbenchBarProvider({
buttons,
actions,
allButtonsDisabled,
+ viewFileActions,
+ setViewFileActions,
registerButtons,
unregisterButtons,
setAction,
@@ -109,6 +116,7 @@ export function WorkbenchBarProvider({
buttons,
actions,
allButtonsDisabled,
+ viewFileActions,
registerButtons,
unregisterButtons,
setAction,
diff --git a/frontend/editor/src/core/contexts/toolWorkflow/toolWorkflowState.ts b/frontend/editor/src/core/contexts/toolWorkflow/toolWorkflowState.ts
index 8daf383334..1f01ccf415 100644
--- a/frontend/editor/src/core/contexts/toolWorkflow/toolWorkflowState.ts
+++ b/frontend/editor/src/core/contexts/toolWorkflow/toolWorkflowState.ts
@@ -1,4 +1,3 @@
-import { PageEditorFunctions } from "@app/types/pageEditor";
import { type ToolPanelMode } from "@app/constants/toolPanel";
import { preferencesService } from "@app/services/preferencesService";
import { stripBasePath } from "@app/constants/app";
@@ -11,7 +10,6 @@ export interface ToolWorkflowState {
toolPanelMode: ToolPanelMode;
previewFile: File | null;
- pageEditorFunctions: PageEditorFunctions | null;
// Search State
searchQuery: string;
@@ -26,7 +24,6 @@ export type ToolWorkflowAction =
| { type: "SET_READER_MODE"; payload: boolean }
| { type: "SET_TOOL_PANEL_MODE"; payload: ToolPanelMode }
| { type: "SET_PREVIEW_FILE"; payload: File | null }
- | { type: "SET_PAGE_EDITOR_FUNCTIONS"; payload: PageEditorFunctions | null }
| { type: "SET_SEARCH_QUERY"; payload: string }
| { type: "RESET_UI_STATE" };
@@ -34,7 +31,6 @@ export const baseState: Omit<ToolWorkflowState, "toolPanelMode"> = {
leftPanelView: "toolPicker",
readerMode: false,
previewFile: null,
- pageEditorFunctions: null,
searchQuery: "",
};
@@ -67,8 +63,6 @@ export function toolWorkflowReducer(
return { ...state, toolPanelMode: action.payload };
case "SET_PREVIEW_FILE":
return { ...state, previewFile: action.payload };
- case "SET_PAGE_EDITOR_FUNCTIONS":
- return { ...state, pageEditorFunctions: action.payload };
case "SET_SEARCH_QUERY":
return { ...state, searchQuery: action.payload };
case "RESET_UI_STATE":
diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
index 9998b6355b..dd5e258863 100644
--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx
@@ -106,7 +106,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
automationSettings: null,
},
multiTool: {
- icon: <Icon name="grid-2x2-plus" size="1.5rem" />,
+ icon: <Icon name="rows-3" size="1.5rem" />,
name: t("home.multiTool.title", "Multi-Tool"),
component: null,
workbench: "pageEditor",
diff --git a/frontend/editor/src/core/hooks/useWorkbenchViewFileActions.ts b/frontend/editor/src/core/hooks/useWorkbenchViewFileActions.ts
new file mode 100644
index 0000000000..878c04f6e9
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useWorkbenchViewFileActions.ts
@@ -0,0 +1,13 @@
+import { useEffect } from "react";
+import { useWorkbenchBar } from "@app/contexts/WorkbenchBarContext";
+import { WorkbenchViewFileActions } from "@app/types/workbenchBar";
+
+/** Registers a view's download and close for the bar while it is mounted.
+ * Pass a memoised object: a new one re-registers. */
+export function useWorkbenchViewFileActions(actions: WorkbenchViewFileActions) {
+ const { setViewFileActions } = useWorkbenchBar();
+ useEffect(() => {
+ setViewFileActions(actions);
+ return () => setViewFileActions(null);
+ }, [actions, setViewFileActions]);
+}
diff --git a/frontend/editor/src/core/icons/icons.ts b/frontend/editor/src/core/icons/icons.ts
index 0ba8c69d89..72e74f14ed 100644
--- a/frontend/editor/src/core/icons/icons.ts
+++ b/frontend/editor/src/core/icons/icons.ts
@@ -306,6 +306,7 @@ import Terminal from "lucide-static/icons/terminal.svg?react";
import TextAlignCenter from "lucide-static/icons/text-align-center.svg?react";
import TextAlignEnd from "lucide-static/icons/text-align-end.svg?react";
import TextAlignStart from "lucide-static/icons/text-align-start.svg?react";
+import TextWrap from "lucide-static/icons/text-wrap.svg?react";
import ThumbsUp from "lucide-static/icons/thumbs-up.svg?react";
import Ticket from "lucide-static/icons/ticket.svg?react";
import Timeline from "lucide-static/icons/timeline.svg?react";
@@ -732,6 +733,7 @@ export const ICONS = {
"text-align-center": { Component: TextAlignCenter, kind: "lucide" },
"text-align-end": { Component: TextAlignEnd, kind: "lucide" },
"text-align-start": { Component: TextAlignStart, kind: "lucide" },
+ "text-wrap": { Component: TextWrap, kind: "lucide" },
"thumbs-up": { Component: ThumbsUp, kind: "lucide" },
ticket: { Component: Ticket, kind: "lucide" },
timeline: { Component: Timeline, kind: "lucide" },
diff --git a/frontend/editor/src/core/services/documentManipulationService.ts b/frontend/editor/src/core/services/documentManipulationService.ts
deleted file mode 100644
index 137cf8af30..0000000000
--- a/frontend/editor/src/core/services/documentManipulationService.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { PDFDocument, PDFPage } from "@app/types/pageEditor";
-import { convertSplitPageIdsToIndexes } from "@app/components/pageEditor/utils/splitPositions";
-
-/**
- * Service for applying DOM changes to PDF document state
- * Reads current DOM state and updates the document accordingly
- */
-export class DocumentManipulationService {
- /**
- * Apply all DOM changes (rotations, splits, reordering) to document state
- * Returns single document or multiple documents if splits are present
- */
- applyDOMChangesToDocument(
- pdfDocument: PDFDocument,
- currentDisplayOrder?: PDFDocument,
- splitPositions?: Set<string>,
- ): PDFDocument | PDFDocument[] {
- // Use current display order (from React state) if provided, otherwise use original order
- const baseDocument = currentDisplayOrder || pdfDocument;
-
- // Apply DOM changes to each page (rotation only now, splits are position-based)
- let updatedPages = baseDocument.pages.map((page) =>
- this.applyPageChanges(page),
- );
-
- // Convert position-based splits to page-based splits for export
- const resolvedSplitIndexes =
- splitPositions && splitPositions.size > 0
- ? convertSplitPageIdsToIndexes(baseDocument, splitPositions)
- : new Set<number>();
-
- if (resolvedSplitIndexes.size > 0) {
- updatedPages = updatedPages.map((page, index) => ({
- ...page,
- splitAfter: resolvedSplitIndexes.has(index),
- }));
- }
-
- // Create final document with reordered pages and applied changes
- const finalDocument = {
- ...pdfDocument, // Use original document metadata but updated pages
- pages: updatedPages, // Use reordered pages with applied changes
- };
-
- // Check for splits and return multiple documents if needed
- if (resolvedSplitIndexes.size > 0) {
- return this.createSplitDocuments(finalDocument);
- }
-
- return finalDocument;
- }
-
- /**
- * Check if document has split markers
- */
- private hasSplitMarkers(document: PDFDocument): boolean {
- return document.pages.some((page) => page.splitAfter);
- }
-
- /**
- * Create multiple documents from split markers
- */
- private createSplitDocuments(document: PDFDocument): PDFDocument[] {
- const documents: PDFDocument[] = [];
- const splitPoints: number[] = [];
-
- // Find split points
- document.pages.forEach((page, index) => {
- if (page.splitAfter) {
- splitPoints.push(index + 1);
- }
- });
-
- // Add end point if not already there
- if (
- splitPoints.length === 0 ||
- splitPoints[splitPoints.length - 1] !== document.pages.length
- ) {
- splitPoints.push(document.pages.length);
- }
-
- let startIndex = 0;
- let partNumber = 1;
-
- for (const endIndex of splitPoints) {
- const segmentPages = document.pages.slice(startIndex, endIndex);
-
- if (segmentPages.length > 0) {
- documents.push({
- ...document,
- id: `${document.id}_part_${partNumber}`,
- name: `${document.name.replace(/\.pdf$/i, "")}_part_${partNumber}.pdf`,
- pages: segmentPages,
- totalPages: segmentPages.length,
- });
- partNumber++;
- }
-
- startIndex = endIndex;
- }
-
- return documents;
- }
-
- /**
- * Apply DOM changes for a single page
- */
- private applyPageChanges(page: PDFPage): PDFPage {
- // Find the DOM element for this page
- const pageElement = document.querySelector(`[data-page-id="${page.id}"]`);
- if (!pageElement) {
- return page;
- }
-
- const updatedPage = { ...page };
-
- // Apply rotation changes from DOM
- updatedPage.rotation = this.getRotationFromDOM(pageElement, page);
-
- return updatedPage;
- }
-
- /**
- * Read rotation from DOM element
- */
- private getRotationFromDOM(
- pageElement: Element,
- originalPage: PDFPage,
- ): number {
- const img = pageElement.querySelector("img");
- if (img) {
- const originalRotation = parseInt(
- img.getAttribute("data-original-rotation") || "0",
- );
-
- const currentTransform = img.style.transform || "";
- const rotationMatch = currentTransform.match(/rotate\((-?\d+)deg\)/);
- const visualRotation = rotationMatch
- ? parseInt(rotationMatch[1])
- : originalRotation;
-
- const userChange =
- (((visualRotation - originalRotation) % 360) + 360) % 360;
-
- let finalRotation = (originalPage.rotation + userChange) % 360;
- if (finalRotation === 360) finalRotation = 0;
-
- return finalRotation;
- }
-
- return originalPage.rotation;
- }
-
- /**
- * Reset all DOM changes (useful for "discard changes" functionality)
- */
- resetDOMToDocumentState(pdfDocument: PDFDocument): void {
- console.log(
- "DocumentManipulationService: Resetting DOM to match document state",
- );
-
- pdfDocument.pages.forEach((page) => {
- const pageElement = document.querySelector(`[data-page-id="${page.id}"]`);
- if (pageElement) {
- const img = pageElement.querySelector("img");
- if (img) {
- // Reset rotation to match document state
- img.style.transform = `rotate(${page.rotation}deg)`;
- }
- }
- });
- }
-
- /**
- * Check if DOM state differs from document state
- */
- hasUnsavedChanges(pdfDocument: PDFDocument): boolean {
- return pdfDocument.pages.some((page) => {
- const pageElement = document.querySelector(`[data-page-id="${page.id}"]`);
- if (pageElement) {
- const domRotation = this.getRotationFromDOM(pageElement, page);
- return domRotation !== page.rotation;
- }
- return false;
- });
- }
-}
-
-// Export singleton instance
-export const documentManipulationService = new DocumentManipulationService();
diff --git a/frontend/editor/src/core/services/pdfExportHelpers.ts b/frontend/editor/src/core/services/pdfExportHelpers.ts
deleted file mode 100644
index 5e4cd3172a..0000000000
--- a/frontend/editor/src/core/services/pdfExportHelpers.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { PDFDocument } from "@app/types/pageEditor";
-import { pdfExportService } from "@app/services/pdfExportService";
-import { FileId } from "@app/types/file";
-
-/**
- * Export processed documents to File objects
- * Handles both single documents and split documents (multiple PDFs)
- */
-export async function exportProcessedDocumentsToFiles(
- processedDocuments: PDFDocument | PDFDocument[],
- sourceFiles: Map<FileId, File> | null,
- exportFilename: string,
-): Promise<File[]> {
- console.log("exportProcessedDocumentsToFiles called with:", {
- isArray: Array.isArray(processedDocuments),
- numDocs: Array.isArray(processedDocuments) ? processedDocuments.length : 1,
- hasSourceFiles: sourceFiles !== null,
- sourceFilesSize: sourceFiles?.size,
- });
-
- if (Array.isArray(processedDocuments)) {
- // Multiple documents (splits)
- const files: File[] = [];
- const baseName = exportFilename.replace(/\.pdf$/i, "");
-
- for (let i = 0; i < processedDocuments.length; i++) {
- const doc = processedDocuments[i];
- const partFilename = `${baseName}_part_${i + 1}.pdf`;
-
- const result = sourceFiles
- ? await pdfExportService.exportPDFMultiFile(doc, sourceFiles, [], {
- selectedOnly: false,
- filename: partFilename,
- })
- : await pdfExportService.exportPDF(doc, [], {
- selectedOnly: false,
- filename: partFilename,
- });
-
- files.push(
- new File([result.blob], result.filename, { type: "application/pdf" }),
- );
- }
-
- return files;
- } else {
- // Single document
- const result = sourceFiles
- ? await pdfExportService.exportPDFMultiFile(
- processedDocuments,
- sourceFiles,
- [],
- {
- selectedOnly: false,
- filename: exportFilename,
- },
- )
- : await pdfExportService.exportPDF(processedDocuments, [], {
- selectedOnly: false,
- filename: exportFilename,
- });
-
- return [
- new File([result.blob], result.filename, { type: "application/pdf" }),
- ];
- }
-}
diff --git a/frontend/editor/src/core/services/pdfExportService.ts b/frontend/editor/src/core/services/pdfExportService.ts
index 2e32319207..a13ea48730 100644
--- a/frontend/editor/src/core/services/pdfExportService.ts
+++ b/frontend/editor/src/core/services/pdfExportService.ts
@@ -131,11 +131,18 @@ export class PDFExportService {
}
}
+ // A page that cannot be written is a hard error: dropping it silently
+ // loses data, and still advancing insertIdx would set every later page's
+ // rotation on the wrong index. insertIdx only moves once a page lands.
let insertIdx = 0;
for (const page of pages) {
if (page.isBlankPage || page.originalPageNumber === -1) {
- // Insert a blank A4 page
- await addNewPage(destDocPtr, insertIdx, A4_WIDTH, A4_HEIGHT);
+ await addNewPage(
+ destDocPtr,
+ insertIdx,
+ page.blankSize?.width ?? A4_WIDTH,
+ page.blankSize?.height ?? A4_HEIGHT,
+ );
// Set absolute rotation (incl. 0) so editor rotation wins over source.
await setPageRotation(
destDocPtr,
@@ -143,39 +150,45 @@ export class PDFExportService {
degreesToPdfiumRotation(page.rotation),
);
insertIdx++;
- } else if (page.originalFileId && loadedDocs.has(page.originalFileId)) {
- const srcDocPtr = loadedDocs.get(page.originalFileId)!;
- const srcPageCount = m.FPDF_GetPageCount(srcDocPtr);
- const sourcePageIndex = page.originalPageNumber - 1;
-
- if (sourcePageIndex >= 0 && sourcePageIndex < srcPageCount) {
- // Import the specific page (1-based page range for FPDF_ImportPages)
- const pageRange = String(sourcePageIndex + 1);
- const imported = await importPages(
- destDocPtr,
- srcDocPtr,
- pageRange,
- insertIdx,
- );
- if (imported) {
- // Set absolute rotation (incl. 0) so editor rotation wins over source.
- await setPageRotation(
- destDocPtr,
- insertIdx,
- degreesToPdfiumRotation(page.rotation),
- );
- } else {
- console.warn(
- `[PDFExport] importPages failed for fileId=${page.originalFileId} pageRange=${pageRange} — page will be missing from output.`,
- );
- }
- insertIdx++;
- }
- } else {
- console.warn(
- `Cannot find source document for page ${page.pageNumber} (fileId: ${page.originalFileId})`,
+ continue;
+ }
+
+ const srcDocPtr = page.originalFileId
+ ? loadedDocs.get(page.originalFileId)
+ : undefined;
+ if (srcDocPtr == null) {
+ throw new Error(
+ `[PDFExport] no source document for page ${page.pageNumber} (fileId=${page.originalFileId})`,
+ );
+ }
+ const srcPageCount = m.FPDF_GetPageCount(srcDocPtr);
+ const sourcePageIndex = page.originalPageNumber - 1;
+ if (sourcePageIndex < 0 || sourcePageIndex >= srcPageCount) {
+ throw new Error(
+ `[PDFExport] page ${page.originalPageNumber} out of range for fileId=${page.originalFileId} (${srcPageCount} pages)`,
+ );
+ }
+
+ // Import the specific page (1-based page range for FPDF_ImportPages).
+ const pageRange = String(sourcePageIndex + 1);
+ const imported = await importPages(
+ destDocPtr,
+ srcDocPtr,
+ pageRange,
+ insertIdx,
+ );
+ if (!imported) {
+ throw new Error(
+ `[PDFExport] importPages failed for fileId=${page.originalFileId} pageRange=${pageRange}`,
);
}
+ // Set absolute rotation (incl. 0) so editor rotation wins over source.
+ await setPageRotation(
+ destDocPtr,
+ insertIdx,
+ degreesToPdfiumRotation(page.rotation),
+ );
+ insertIdx++;
}
// Save the assembled document
@@ -209,11 +222,19 @@ export class PDFExportService {
try {
const srcPageCount = m.FPDF_GetPageCount(srcDocPtr);
+ // A page that cannot be written is a hard error: dropping it silently
+ // loses data, and still advancing insertIdx would set every later page's
+ // rotation on the wrong index. insertIdx only moves once a page lands.
let insertIdx = 0;
for (const page of pages) {
if (page.isBlankPage || page.originalPageNumber === -1) {
- await addNewPage(destDocPtr, insertIdx, A4_WIDTH, A4_HEIGHT);
+ await addNewPage(
+ destDocPtr,
+ insertIdx,
+ page.blankSize?.width ?? A4_WIDTH,
+ page.blankSize?.height ?? A4_HEIGHT,
+ );
// Set absolute rotation (incl. 0) so editor rotation wins over source.
await setPageRotation(
destDocPtr,
@@ -221,32 +242,34 @@ export class PDFExportService {
degreesToPdfiumRotation(page.rotation),
);
insertIdx++;
- } else {
- const sourcePageIndex = page.originalPageNumber - 1;
-
- if (sourcePageIndex >= 0 && sourcePageIndex < srcPageCount) {
- const pageRange = String(sourcePageIndex + 1);
- const imported = await importPages(
- destDocPtr,
- srcDocPtr,
- pageRange,
- insertIdx,
- );
- if (imported) {
- // Set absolute rotation (incl. 0) so editor rotation wins over source.
- await setPageRotation(
- destDocPtr,
- insertIdx,
- degreesToPdfiumRotation(page.rotation),
- );
- } else {
- console.warn(
- `[PDFExport] importPages failed for page ${page.originalPageNumber} pageRange=${pageRange} — page will be missing from output.`,
- );
- }
- insertIdx++;
- }
+ continue;
+ }
+
+ const sourcePageIndex = page.originalPageNumber - 1;
+ if (sourcePageIndex < 0 || sourcePageIndex >= srcPageCount) {
+ throw new Error(
+ `[PDFExport] page ${page.originalPageNumber} out of range (${srcPageCount} pages)`,
+ );
+ }
+ const pageRange = String(sourcePageIndex + 1);
+ const imported = await importPages(
+ destDocPtr,
+ srcDocPtr,
+ pageRange,
+ insertIdx,
+ );
+ if (!imported) {
+ throw new Error(
+ `[PDFExport] importPages failed for page ${page.originalPageNumber} pageRange=${pageRange}`,
+ );
}
+ // Set absolute rotation (incl. 0) so editor rotation wins over source.
+ await setPageRotation(
+ destDocPtr,
+ insertIdx,
+ degreesToPdfiumRotation(page.rotation),
+ );
+ insertIdx++;
}
const resultBuf = await saveRawDocument(destDocPtr);
diff --git a/frontend/editor/src/core/tests/stubbed/page-editor-rotation.spec.ts b/frontend/editor/src/core/tests/stubbed/page-editor-rotation.spec.ts
deleted file mode 100644
index 31c3accf47..0000000000
--- a/frontend/editor/src/core/tests/stubbed/page-editor-rotation.spec.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-
-import { PDFDocument } from "@cantoo/pdf-lib";
-
-import { test, expect } from "@app/tests/helpers/stub-test-base";
-import { uploadFiles, dismissTourTooltip } from "@app/tests/helpers/ui-helpers";
-
-// Fixture: 4 portrait pages whose intrinsic /Rotate is 0, 90, 270, 180.
-// Page 3 (index 2) is 270 so a single rotate-right lands on a net-0 target -
-// the exact case the export used to drop, leaving the source rotation behind.
-const ROTATED_PDF = path.join(
- import.meta.dirname,
- "../test-fixtures/rotated-pages.pdf",
-);
-const SOURCE_ROTATIONS = [0, 90, 270, 180];
-
-/** Read the rotation each thumbnail is currently displaying (= page.rotation). */
-async function readEditorRotations(page: import("@playwright/test").Page) {
- const imgs = page.locator("[data-page-id] img[data-original-rotation]");
- await expect(imgs).toHaveCount(SOURCE_ROTATIONS.length, { timeout: 30_000 });
- const count = await imgs.count();
- const rots: number[] = [];
- for (let i = 0; i < count; i++) {
- rots.push(
- parseInt(
- (await imgs.nth(i).getAttribute("data-original-rotation")) || "NaN",
- 10,
- ),
- );
- }
- return rots;
-}
-
-// Skip the fixture's 30s auto-goto; vite's cold on-demand compile can exceed it.
-test.use({ autoGoto: false });
-
-test.describe("PageEditor (multitool) rotation save", () => {
- test("rotating a page persists the correct absolute rotation on export", async ({
- page,
- }) => {
- await page.goto("/editor", {
- waitUntil: "domcontentloaded",
- timeout: 120_000,
- });
- await uploadFiles(page, ROTATED_PDF);
- // Enter the multitool via in-app navigation, NOT page.goto: a full reload
- // wipes the in-memory workbench before PageEditorContext's "entering page
- // editor" effect can auto-select the file, leaving the editor empty.
- await dismissTourTooltip(page);
- await page.getByText("PDF Multi Tool", { exact: true }).first().click();
-
- // 1. Baseline: the multitool must seed page.rotation from the source /Rotate,
- // otherwise rotated pages render upright and every rotate is off-baseline.
- const baseline = await readEditorRotations(page);
- expect(
- baseline,
- "editor must show pages at their true source rotation",
- ).toEqual(SOURCE_ROTATIONS);
-
- // 2. Rotate page 3 (index 2, source /Rotate 270) right once via its
- // per-page hover menu. Target rotation is (270 + 90) % 360 = 0.
- const page3 = page.locator("[data-page-id]").nth(2);
- await page3.scrollIntoViewIfNeeded();
- await page3.hover();
- const rotateRight = page3.getByRole("button", { name: "Rotate Right" });
- await expect(rotateRight).toBeVisible({ timeout: 5_000 });
- await rotateRight.click();
-
- // Only page 3 changes (270 -> 0); the others keep their source rotation.
- await expect(page3.locator("img[data-original-rotation]")).toHaveAttribute(
- "data-original-rotation",
- "0",
- { timeout: 10_000 },
- );
- expect(await readEditorRotations(page)).toEqual([0, 90, 0, 180]);
-
- // 3. Ensure all pages are selected, then export, capturing the PDF.
- // Pages load all-selected, so "Select All" is disabled - only click it
- // if some pages got deselected.
- const selectAll = page.getByRole("button", {
- name: "Select All",
- exact: true,
- });
- if (await selectAll.isEnabled()) {
- await selectAll.click();
- }
- const tmpOut = path.join(os.tmpdir(), `rot-export-${process.pid}.pdf`);
- const [download] = await Promise.all([
- page.waitForEvent("download", { timeout: 30_000 }),
- page.getByRole("button", { name: "Export Selected Pages" }).click(),
- ]);
- await download.saveAs(tmpOut);
-
- // 4. The exported /Rotate must match what the editor showed: page 3 upright
- // (0), the untouched pages keeping their source rotation.
- const outDoc = await PDFDocument.load(fs.readFileSync(tmpOut));
- const outRotations = outDoc
- .getPages()
- .map(
- (p: { getRotation: () => { angle: number } }) => p.getRotation().angle,
- );
- fs.rmSync(tmpOut, { force: true });
- expect(outRotations).toEqual([0, 90, 0, 180]);
- });
-});
diff --git a/frontend/editor/src/core/tests/stubbed/page-tracks.spec.ts b/frontend/editor/src/core/tests/stubbed/page-tracks.spec.ts
new file mode 100644
index 0000000000..0b9cdc742c
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/page-tracks.spec.ts
@@ -0,0 +1,1353 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { PDFDocument, StandardFonts } from "@cantoo/pdf-lib";
+
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import { uploadFiles, dismissTourTooltip } from "@app/tests/helpers/ui-helpers";
+
+// 4 portrait pages whose intrinsic /Rotate is 0, 90, 270, 180.
+const ROTATED_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/rotated-pages.pdf",
+);
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+
+test.use({ autoGoto: false });
+
+/** The lane of one track, addressed by the file it saves back to. */
+function track(page: import("@playwright/test").Page, name: string) {
+ return page.locator(`section[aria-label="${name}"]`);
+}
+
+/**
+ * Switches workbench view. The switcher is a Mantine SegmentedControl whose
+ * radio input is visually hidden, so the click goes through the label. Only the
+ * active segment shows its text (the rest are icon-only), so the label is found
+ * by its text content and clicked as a whole rather than clicking the text node.
+ */
+async function switchView(
+ page: import("@playwright/test").Page,
+ label: string,
+) {
+ await page
+ .locator('[data-tour="view-switcher"]')
+ .first()
+ .locator(".mantine-SegmentedControl-label", { hasText: label })
+ .click();
+}
+
+/**
+ * Rotations as the editor is displaying them. Thumbnails load lazily, so this
+ * waits for the images before reading: an empty list means "not loaded yet",
+ * not "no rotation".
+ */
+async function readRotations(
+ lane: import("@playwright/test").Locator,
+ expectedCount: number,
+) {
+ const imgs = lane.locator("[data-page-id] img[data-original-rotation]");
+ await expect(imgs).toHaveCount(expectedCount, { timeout: 60_000 });
+ return imgs.evaluateAll((nodes) =>
+ nodes.map((node) => Number(node.getAttribute("data-original-rotation"))),
+ );
+}
+
+/**
+ * Presses on one tile and drags to a fraction across another, without
+ * releasing. dnd-kit's PointerSensor needs a real pointer sequence past its
+ * activation distance, and the intermediate moves let it measure the target.
+ */
+async function dragPageOver(
+ page: import("@playwright/test").Page,
+ from: import("@playwright/test").Locator,
+ to: import("@playwright/test").Locator,
+ fractionAcross = 0.25,
+) {
+ const source = await from.boundingBox();
+ const target = await to.boundingBox();
+ if (!source || !target) throw new Error("drag endpoints are not laid out");
+
+ await page.mouse.move(
+ source.x + source.width / 2,
+ source.y + source.height / 2,
+ );
+ await page.mouse.down();
+ const dropX = target.x + target.width * fractionAcross;
+ const dropY = target.y + target.height / 2;
+ for (const step of [0.2, 0.5, 0.8, 1]) {
+ await page.mouse.move(
+ source.x + (dropX - source.x) * step,
+ source.y + (dropY - source.y) * step,
+ { steps: 8 },
+ );
+ }
+}
+
+/**
+ * The file the viewer is showing, per the sidebar's "viewed" row marker. Note
+ * `.selected` is workbench selection, which is a different thing.
+ */
+function viewerActiveFile(page: import("@playwright/test").Page) {
+ return page.locator(".file-sidebar-file-item.viewed .file-sidebar-file-name");
+}
+
+/** The tile the insertion line is currently drawn against. */
+function dropTarget(page: import("@playwright/test").Page) {
+ return page.locator("[data-page-id][data-drop-before]");
+}
+
+async function dragPageOnto(
+ page: import("@playwright/test").Page,
+ from: import("@playwright/test").Locator,
+ to: import("@playwright/test").Locator,
+ fractionAcross = 0.25,
+) {
+ await dragPageOver(page, from, to, fractionAcross);
+ await page.mouse.up();
+}
+
+/** Drops `from` into the empty gap between two adjacent tiles, over neither. */
+async function dragPageIntoGap(
+ page: import("@playwright/test").Page,
+ from: import("@playwright/test").Locator,
+ leftTile: import("@playwright/test").Locator,
+ rightTile: import("@playwright/test").Locator,
+) {
+ const source = await from.boundingBox();
+ const left = await leftTile.boundingBox();
+ const right = await rightTile.boundingBox();
+ if (!source || !left || !right)
+ throw new Error("drag endpoints are not laid out");
+ const gapX = (left.x + left.width + right.x) / 2;
+ const gapY = left.y + left.height / 2;
+ await page.mouse.move(
+ source.x + source.width / 2,
+ source.y + source.height / 2,
+ );
+ await page.mouse.down();
+ for (const step of [0.2, 0.5, 0.8, 1]) {
+ await page.mouse.move(
+ source.x + (gapX - source.x) * step,
+ source.y + (gapY - source.y) * step,
+ { steps: 8 },
+ );
+ }
+ await page.mouse.up();
+}
+
+/** The order of the tracks, top to bottom. */
+async function trackOrder(page: import("@playwright/test").Page) {
+ return page
+ .locator("section[aria-label] header")
+ .evaluateAll((headers) =>
+ headers.map(
+ (h) =>
+ (h.closest("section") as HTMLElement).getAttribute("aria-label") ??
+ "",
+ ),
+ );
+}
+
+/** Drags a track's header onto another track, vertically. */
+async function dragTrackOnto(
+ page: import("@playwright/test").Page,
+ sourceName: string,
+ targetName: string,
+ fractionDown = 0.25,
+) {
+ const from = await page
+ .locator(`section[aria-label="${sourceName}"] header`)
+ .boundingBox();
+ const target = await page
+ .locator(`section[aria-label="${targetName}"]`)
+ .boundingBox();
+ if (!from || !target) throw new Error("tracks are not laid out");
+
+ await page.mouse.move(from.x + 140, from.y + from.height / 2);
+ await page.mouse.down();
+ const toX = target.x + 140;
+ const toY = target.y + target.height * fractionDown;
+ for (const step of [0.3, 0.7, 1]) {
+ await page.mouse.move(
+ from.x + 140 + (toX - (from.x + 140)) * step,
+ from.y + from.height / 2 + (toY - (from.y + from.height / 2)) * step,
+ { steps: 8 },
+ );
+ }
+ await page.mouse.up();
+}
+
+async function openPageEditor(page: import("@playwright/test").Page) {
+ await page.goto("/editor", {
+ waitUntil: "domcontentloaded",
+ timeout: 120_000,
+ });
+ await uploadFiles(page, [ROTATED_PDF, SAMPLE_PDF]);
+ await dismissTourTooltip(page);
+ await switchView(page, "Page Editor");
+ await expect(page.getByTestId("page-tracks")).toBeVisible({
+ timeout: 30_000,
+ });
+}
+
+test.describe("Page Editor tracks", () => {
+ test("expands every open PDF into its own track of pages", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+
+ const rotated = track(page, "rotated-pages.pdf");
+ const sample = track(page, "sample.pdf");
+ await expect(rotated).toBeVisible({ timeout: 30_000 });
+ await expect(sample).toBeVisible();
+
+ // Each track holds only its own file's pages.
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ await expect(sample.locator("[data-page-id]")).toHaveCount(1);
+
+ // Pages start at their true source rotation, not upright.
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+ });
+
+ test("rotating and deleting are held in memory until save, then versioned", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+
+ // Rotate page 3 right: 270 + 90 lands on 0, the case a save must not drop.
+ const third = rotated.locator("[data-page-id]").nth(2);
+ await third.hover();
+ await third.getByRole("button", { name: "Rotate right" }).click();
+ await expect(third.locator("img[data-original-rotation]")).toHaveAttribute(
+ "data-original-rotation",
+ "0",
+ );
+
+ // Delete the last page. Nothing is written yet, so the track just shrinks.
+ const fourth = rotated.locator("[data-page-id]").nth(3);
+ await fourth.hover();
+ await fourth.getByRole("button", { name: "Delete page" }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(3);
+ await expect(rotated).toContainText("edited");
+
+ // Undo restores it; redo takes it away again.
+ await page.getByRole("button", { name: "Undo" }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4);
+ await page.getByRole("button", { name: "Redo" }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(3);
+
+ await page
+ .getByRole("button", { name: "Save changes to all files" })
+ .click();
+
+ // The save landed as version 2 of the same file, with nothing pending.
+ const saved = track(page, "rotated-pages.pdf");
+ await expect(saved).toContainText("v2", { timeout: 90_000 });
+ await expect(saved).not.toContainText("edited");
+ await expect(saved.locator("[data-page-id]")).toHaveCount(3);
+
+ // The rebuilt track reads its rotations back out of the saved PDF, so this
+ // proves the bytes carry the absolute rotation the editor was showing,
+ // including page 3's 270 + 90 = 0, which a relative write would drop.
+ expect(await readRotations(saved, 3)).toEqual([0, 90, 0]);
+
+ // The other file was untouched, so it must still be at version 1.
+ await expect(track(page, "sample.pdf")).not.toContainText("v2");
+ });
+
+ test("dragging pages between tracks moves them, and an emptied track closes on save", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const sample = track(page, "sample.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ await expect(sample.locator("[data-page-id]")).toHaveCount(1);
+
+ // Move sample.pdf's only page in front of rotated-pages.pdf's first page.
+ await dragPageOnto(
+ page,
+ sample.locator("[data-page-id]").first(),
+ rotated.locator("[data-page-id]").first(),
+ );
+
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(5);
+ await expect(sample.locator("[data-page-id]")).toHaveCount(0);
+ // Both tracks are dirty: one gained a page, the other lost its last one.
+ await expect(rotated).toContainText("edited");
+ await expect(sample).toContainText("edited");
+
+ await page
+ .getByRole("button", { name: "Save changes to all files" })
+ .click();
+
+ // The emptied file leaves the workbench; the other keeps the moved page.
+ await expect(track(page, "sample.pdf")).toHaveCount(0, { timeout: 90_000 });
+ const saved = track(page, "rotated-pages.pdf");
+ await expect(saved).toContainText("v2");
+ await expect(saved.locator("[data-page-id]")).toHaveCount(5);
+ // The dragged page landed first, ahead of the original page 1.
+ expect(await readRotations(saved, 5)).toEqual([0, 0, 90, 270, 180]);
+ });
+
+ test("dragging within a track reorders only that track", async ({ page }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+
+ // Move the last page (180) to the front.
+ await dragPageOnto(
+ page,
+ rotated.locator("[data-page-id]").nth(3),
+ rotated.locator("[data-page-id]").first(),
+ );
+
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4);
+ expect(await readRotations(rotated, 4)).toEqual([180, 0, 90, 270]);
+ await expect(track(page, "sample.pdf")).not.toContainText("edited");
+ });
+
+ test("a page dropped in the gap between pages lands between them", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+
+ // Drop the last page into the gap between the first two, over neither tile.
+ const tiles = rotated.locator("[data-page-id]");
+ await dragPageIntoGap(page, tiles.nth(3), tiles.nth(0), tiles.nth(1));
+
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4);
+ expect(await readRotations(rotated, 4)).toEqual([0, 180, 90, 270]);
+ });
+
+ test("prompts when leaving with pending edits, and can save from the prompt", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+
+ const last = rotated.locator("[data-page-id]").nth(3);
+ await last.hover();
+ await last.getByRole("button", { name: "Delete page" }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(3);
+
+ await switchView(page, "Active Files");
+
+ await expect(
+ page.getByRole("heading", { name: "Unsaved Changes" }),
+ ).toBeVisible();
+ await page.getByRole("button", { name: "Save & Leave" }).click();
+
+ // Back in the editor, the delete is now version 2 rather than pending.
+ await switchView(page, "Page Editor");
+ const saved = track(page, "rotated-pages.pdf");
+ await expect(saved).toContainText("v2", { timeout: 90_000 });
+ await expect(saved.locator("[data-page-id]")).toHaveCount(3);
+ await expect(saved).not.toContainText("edited");
+ });
+
+ test("download writes out the pending edits without saving them", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ // One file only: WebKit surfaces just the first of several back-to-back downloads.
+ const sample = track(page, "sample.pdf");
+ await sample
+ .locator("header")
+ .getByRole("button", { name: "Close file" })
+ .click();
+ await page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Close File" })
+ .click();
+ await expect(sample).toHaveCount(0);
+
+ const last = rotated.locator("[data-page-id]").nth(3);
+ await last.hover();
+ await last.getByRole("button", { name: "Delete page" }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(3);
+
+ const download = page.waitForEvent("download", { timeout: 30_000 });
+ await page.getByRole("button", { name: "Download Files" }).click();
+ const edited = await download;
+ expect(edited.suggestedFilename()).toBe("rotated-pages.pdf");
+ const target = path.join(
+ fs.mkdtempSync(path.join(os.tmpdir(), "page-tracks-")),
+ "rotated-pages.pdf",
+ );
+ await edited.saveAs(target);
+ const pdf = await PDFDocument.load(fs.readFileSync(target));
+ expect(pdf.getPageCount()).toBe(3);
+
+ // Downloading is not saving: the edit is still pending on version 1.
+ await expect(rotated).toContainText("edited");
+ await expect(rotated).not.toContainText("v2");
+ });
+
+ test("close asks first, and offers save or discard when edits are pending", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ const closeAll = page
+ .locator(".workbench-bar")
+ .getByRole("button", { name: "Close All Files" });
+ const dialog = page.getByRole("dialog");
+
+ await closeAll.click();
+ await expect(dialog).toContainText(
+ "Are you sure you want to close all files?",
+ );
+ await dialog.getByRole("button", { name: "Cancel" }).click();
+ await expect(dialog).toHaveCount(0);
+
+ const last = rotated.locator("[data-page-id]").nth(3);
+ await last.hover();
+ await last.getByRole("button", { name: "Delete page" }).click();
+ await closeAll.click();
+ await expect(dialog).toContainText("This file has unsaved changes.");
+ await expect(dialog).toContainText("rotated-pages.pdf");
+ await dialog.getByRole("button", { name: "Cancel" }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(3);
+ await expect(rotated).toContainText("edited");
+
+ await closeAll.click();
+ await dialog
+ .getByRole("button", { name: "Discard changes and close" })
+ .click();
+ await expect(rotated).toHaveCount(0, { timeout: 30_000 });
+ await expect(track(page, "sample.pdf")).toHaveCount(0);
+ });
+
+ test("selecting a track from its header lets the bar act on just its pages", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+
+ const header = rotated.locator("header");
+ await header
+ .getByRole("button", { name: "Select All", exact: true })
+ .click();
+ // Like the bar's, the track's toggle names what the next click does.
+ await expect(
+ header.getByRole("button", { name: "Deselect All", exact: true }),
+ ).toBeVisible();
+ await page.getByRole("button", { name: "Delete selected pages" }).click();
+
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(0);
+ // The other track was never selected, so it is untouched.
+ await expect(
+ track(page, "sample.pdf").locator("[data-page-id]"),
+ ).toHaveCount(1);
+ });
+
+ test("a track's close button confirms, and offers save when that file has edits", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const sample = track(page, "sample.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ const closeOf = (lane: import("@playwright/test").Locator) =>
+ lane.locator("header").getByRole("button", { name: "Close file" });
+ const dialog = page.getByRole("dialog");
+
+ const last = rotated.locator("[data-page-id]").nth(3);
+ await last.hover();
+ await last.getByRole("button", { name: "Delete page" }).click();
+
+ await closeOf(sample).click();
+ await expect(dialog).toContainText(
+ "Are you sure you want to close this file?",
+ );
+ await dialog.getByRole("button", { name: "Close File" }).click();
+ await expect(sample).toHaveCount(0);
+ // Closing an unrelated file leaves the other track's pending edit alone.
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(3);
+ await expect(rotated).toContainText("edited");
+
+ await closeOf(rotated).click();
+ await expect(dialog).toContainText("This file has unsaved changes.");
+ await dialog.getByRole("button", { name: "Save and close" }).click();
+ await expect(rotated).toHaveCount(0, { timeout: 90_000 });
+ await expect(page.locator("[data-track-file-id]")).toHaveCount(0);
+ });
+
+ test("a page's move buttons shift it one place within its track", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+
+ const first = rotated.locator("[data-page-id]").first();
+ await first.hover();
+ // Only the directions a page can actually move are offered.
+ await expect(first.getByRole("button", { name: "Move left" })).toHaveCount(
+ 0,
+ );
+ await first.getByRole("button", { name: "Move right" }).click();
+ expect(await readRotations(rotated, 4)).toEqual([90, 0, 270, 180]);
+ await expect(rotated).toContainText("edited");
+
+ const last = rotated.locator("[data-page-id]").last();
+ await last.hover();
+ await expect(last.getByRole("button", { name: "Move right" })).toHaveCount(
+ 0,
+ );
+ await last.getByRole("button", { name: "Move left" }).click();
+ expect(await readRotations(rotated, 4)).toEqual([90, 0, 180, 270]);
+ });
+
+ test("page numbers typed in the bar select that page of every track", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const sample = track(page, "sample.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ const selectedIn = (lane: import("@playwright/test").Locator) =>
+ lane.locator('[data-page-id][data-selected="true"]');
+
+ await page
+ .locator(".workbench-bar")
+ .getByRole("button", { name: "Select by Page Numbers" })
+ .click();
+ await page.getByPlaceholder("1,3,5-10").fill("1,3");
+
+ await expect(selectedIn(rotated)).toHaveCount(2);
+ await expect(rotated.locator("[data-page-id]").nth(0)).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ await expect(rotated.locator("[data-page-id]").nth(2)).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ // sample.pdf has no page 3, so only its first page matches.
+ await expect(selectedIn(sample)).toHaveCount(1);
+ });
+
+ test("page numbers typed on a track select only within that track", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const sample = track(page, "sample.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ const selectedIn = (lane: import("@playwright/test").Locator) =>
+ lane.locator('[data-page-id][data-selected="true"]');
+
+ await sample.locator("[data-page-id]").first().click();
+ await expect(selectedIn(sample)).toHaveCount(1);
+
+ await rotated
+ .locator("header")
+ .getByRole("button", { name: "Select by Page Numbers" })
+ .click();
+ await page.getByPlaceholder("1,3,5-10").fill("2-3");
+
+ await expect(selectedIn(rotated)).toHaveCount(2);
+ await expect(rotated.locator("[data-page-id]").nth(1)).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ // Another track's selection is left as it was.
+ await expect(selectedIn(sample)).toHaveCount(1);
+
+ // Narrowing the typed range replaces this track's selection.
+ await page.getByPlaceholder("1,3,5-10").fill("4");
+ await expect(selectedIn(rotated)).toHaveCount(1);
+ await expect(rotated.locator("[data-page-id]").nth(3)).toHaveAttribute(
+ "data-selected",
+ "true",
+ );
+ });
+
+ test("a blank page inserted in a gap is written at the size and turn of the page before it", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ // One file only: WebKit surfaces just the first of several back-to-back downloads.
+ const sample = track(page, "sample.pdf");
+ await sample
+ .locator("header")
+ .getByRole("button", { name: "Close file" })
+ .click();
+ await page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Close File" })
+ .click();
+ await expect(sample).toHaveCount(0);
+
+ // The gap before page 3, i.e. after page 2 (400 x 600, /Rotate 90).
+ await rotated.locator('[data-insert-before="3"]').click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(5);
+ await expect(
+ rotated.locator("[data-page-id]").nth(2).locator("[data-blank-page]"),
+ ).toBeVisible();
+ await expect(rotated).toContainText("edited");
+
+ const download = page.waitForEvent("download", { timeout: 30_000 });
+ await page.getByRole("button", { name: "Download Files" }).click();
+ const target = path.join(
+ fs.mkdtempSync(path.join(os.tmpdir(), "page-tracks-")),
+ "rotated-pages.pdf",
+ );
+ await (await download).saveAs(target);
+
+ const pdf = await PDFDocument.load(fs.readFileSync(target));
+ expect(pdf.getPageCount()).toBe(5);
+ const blank = pdf.getPage(2);
+ expect(blank.getRotation().angle).toBe(90);
+ const box = blank.getMediaBox();
+ expect(Math.round(box.width)).toBe(400);
+ expect(Math.round(box.height)).toBe(600);
+ });
+
+ test("the bar inserts a blank page after every selected page", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(4, { timeout: 30_000 });
+ const insertAfter = page.getByRole("button", {
+ name: "Insert blank pages after selected pages",
+ });
+ await expect(insertAfter).toBeDisabled();
+
+ await tiles.nth(1).click();
+ await tiles.nth(3).click();
+ await insertAfter.click();
+
+ await expect(tiles).toHaveCount(6);
+ await expect(tiles.nth(2).locator("[data-blank-page]")).toBeVisible();
+ await expect(tiles.nth(5).locator("[data-blank-page]")).toBeVisible();
+ await expect(
+ track(page, "sample.pdf").locator("[data-page-id]"),
+ ).toHaveCount(1);
+
+ await page.getByRole("button", { name: "Undo" }).click();
+ await expect(tiles).toHaveCount(4);
+ });
+
+ test("the gaps at either end of a track insert but do not split", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ await expect(rotated.locator('[data-split-before="1"]')).toHaveCount(0);
+ await expect(rotated.locator('[data-split-before="5"]')).toHaveCount(0);
+
+ await rotated.locator('[data-insert-before="1"]').click();
+ await rotated.locator('[data-insert-before="6"]').click();
+
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(6);
+ await expect(tiles.first().locator("[data-blank-page]")).toBeVisible();
+ await expect(tiles.last().locator("[data-blank-page]")).toBeVisible();
+ });
+
+ test("the insertion line marks where a right-to-left drag actually lands", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+
+ const tiles = rotated.locator("[data-page-id]");
+ const second = tiles.nth(1);
+ const secondId = await second.getAttribute("data-page-id");
+
+ // Drag page 4 leftwards, crossing page 2's right half before settling on
+ // its left half. The line must follow the pointer across the midpoint, not
+ // stay where the tile was first entered.
+ await dragPageOver(page, tiles.nth(3), second, 0.25);
+ await expect(dropTarget(page)).toHaveAttribute(
+ "data-page-id",
+ secondId as string,
+ );
+
+ await page.mouse.up();
+
+ // And the drop lands exactly where the line was: 180 ahead of 90.
+ expect(await readRotations(rotated, 4)).toEqual([0, 180, 90, 270]);
+ });
+
+ test("the insertion line follows the pointer past a tile's midpoint", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+
+ const tiles = rotated.locator("[data-page-id]");
+ const thirdId = await tiles.nth(2).getAttribute("data-page-id");
+
+ // Settling on page 2's RIGHT half must mark page 3 instead, since the page
+ // is inserted after page 2.
+ await dragPageOver(page, tiles.nth(3), tiles.nth(1), 0.75);
+ await expect(dropTarget(page)).toHaveAttribute(
+ "data-page-id",
+ thirdId as string,
+ );
+
+ await page.mouse.up();
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 180, 270]);
+ });
+
+ test("clicking pages accumulates the selection instead of replacing it", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(4, { timeout: 30_000 });
+ const selected = rotated.locator('[data-page-id][data-selected="true"]');
+
+ await tiles.nth(0).click();
+ await expect(selected).toHaveCount(1);
+
+ // The second click must ADD, not move the selection onto page 2.
+ await tiles.nth(1).click();
+ await expect(selected).toHaveCount(2);
+
+ // Clicking a selected page takes it back out again.
+ await tiles.nth(1).click();
+ await expect(selected).toHaveCount(1);
+ await expect(tiles.nth(0)).toHaveAttribute("data-selected", "true");
+
+ // Shift extends from the last clicked page across the whole run.
+ await tiles.nth(3).click({ modifiers: ["Shift"] });
+ await expect(selected).toHaveCount(4);
+
+ // A selection spanning tracks is allowed too.
+ const sample = track(page, "sample.pdf");
+ await sample.locator("[data-page-id]").first().click();
+ await expect(
+ page.locator('[data-page-id][data-selected="true"]'),
+ ).toHaveCount(5);
+ });
+
+ test("the bar's select all toggles, selecting every page then clearing", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ const selected = page.locator('[data-page-id][data-selected="true"]');
+ const bar = page.locator(".workbench-bar");
+ const selectAll = bar.getByRole("button", {
+ name: "Select All",
+ exact: true,
+ });
+ const deselectAll = bar.getByRole("button", {
+ name: "Deselect All",
+ exact: true,
+ });
+
+ await rotated.locator("[data-page-id]").first().click();
+ await expect(deselectAll).toHaveCount(0);
+ await selectAll.click();
+ await expect(selected).toHaveCount(5);
+
+ // With everything selected the same button offers the opposite.
+ await deselectAll.click();
+ await expect(selected).toHaveCount(0);
+ await expect(selectAll).toBeVisible();
+ });
+
+ test("a bar action applies to every page the clicks accumulated", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ expect(await readRotations(rotated, 4)).toEqual([0, 90, 270, 180]);
+
+ await tiles.nth(0).click();
+ await tiles.nth(2).click();
+ await page
+ .getByRole("button", { name: "Rotate selected pages right" })
+ .click();
+
+ // Only the two clicked pages turn; the ones in between are untouched.
+ expect(await readRotations(rotated, 4)).toEqual([90, 90, 0, 180]);
+ });
+
+ test("clicking the empty space around the pages deselects everything", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(4, { timeout: 30_000 });
+ const anySelected = page.locator('[data-page-id][data-selected="true"]');
+
+ await tiles.nth(0).click();
+ await tiles.nth(2).click();
+ await expect(anySelected).toHaveCount(2);
+
+ // The lane runs past its last page; that surface is not a page.
+ const box = await rotated.locator("[data-track-lane]").boundingBox();
+ if (!box) throw new Error("lane is not laid out");
+ const last = await tiles.nth(3).boundingBox();
+ if (!last) throw new Error("tile is not laid out");
+ await page.mouse.click(
+ (last.x + last.width + box.x + box.width) / 2,
+ box.y + box.height / 2,
+ );
+ await expect(anySelected).toHaveCount(0);
+ });
+
+ test("a drag that lands on empty lane space keeps the moved selection", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const sample = track(page, "sample.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(4, { timeout: 30_000 });
+
+ await tiles.nth(0).click();
+ await tiles.nth(1).click();
+ await expect(
+ page.locator('[data-page-id][data-selected="true"]'),
+ ).toHaveCount(2);
+
+ // sample.pdf has one page, so the lane past it is empty space: the drop
+ // releases over the lane, which is also where a deselect click would land.
+ await dragPageOnto(
+ page,
+ tiles.nth(0),
+ sample.locator("[data-page-id]").first(),
+ 0.9,
+ );
+
+ await expect(sample.locator("[data-page-id]")).toHaveCount(3);
+ await expect(
+ page.locator('[data-page-id][data-selected="true"]'),
+ ).toHaveCount(2);
+ });
+
+ test("a long track mounts only a window of its pages", async ({ page }) => {
+ // Built here rather than committed as a fixture: the point is the page
+ // COUNT, and 300 pages of real PDF is a lot of bytes to carry in the repo.
+ const doc = await PDFDocument.create();
+ const font = await doc.embedFont(StandardFonts.Helvetica);
+ for (let i = 1; i <= 300; i++) {
+ doc
+ .addPage([595, 842])
+ .drawText(`page ${i}`, { x: 60, y: 700, size: 28, font });
+ }
+ const longPdf = path.join(os.tmpdir(), `tracks-long-${process.pid}.pdf`);
+ fs.writeFileSync(longPdf, await doc.save());
+
+ try {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto("/editor", {
+ waitUntil: "domcontentloaded",
+ timeout: 120_000,
+ });
+ await uploadFiles(page, longPdf);
+ await dismissTourTooltip(page);
+ await switchView(page, "Page Editor");
+
+ await expect(page.locator("section[aria-label]").first()).toContainText(
+ "300 pages",
+ { timeout: 60_000 },
+ );
+ // A single file opens wrapped; this test is about the single-row window.
+ await page.getByRole("button", { name: "Wrap pages" }).click();
+ const lane = page.locator("[data-track-lane]");
+
+ // Mounting all 300 is what made a click cost ~700ms and a drag ~300ms per
+ // pointer move, since every tile is a dnd-kit draggable AND droppable.
+ const mounted = await page.locator("[data-page-id]").count();
+ expect(mounted).toBeGreaterThan(0);
+ expect(mounted).toBeLessThan(40);
+
+ // The window follows the lane's scroll rather than being a fixed prefix.
+ const firstBefore = await page
+ .locator("[data-page-id]")
+ .first()
+ .getAttribute("data-page-id");
+ await lane.evaluate((el) => {
+ el.scrollLeft = 9000;
+ });
+ await expect
+ .poll(
+ async () =>
+ page.locator("[data-page-id]").first().getAttribute("data-page-id"),
+ { timeout: 30_000 },
+ )
+ .not.toBe(firstBefore);
+ expect(await page.locator("[data-page-id]").count()).toBeLessThan(40);
+ } finally {
+ fs.rmSync(longPdf, { force: true });
+ }
+ });
+
+ test("a single file wraps on entry: rows, no horizontal scroll, still virtualised", async ({
+ page,
+ }) => {
+ // Enough pages that one row overflows and a wrapped one spans many rows, so
+ // both the no-scroll and the still-virtualised claims are actually tested.
+ const doc = await PDFDocument.create();
+ const font = await doc.embedFont(StandardFonts.Helvetica);
+ for (let i = 1; i <= 300; i++) {
+ doc
+ .addPage([595, 842])
+ .drawText(`page ${i}`, { x: 60, y: 700, size: 28, font });
+ }
+ const wrapPdf = path.join(os.tmpdir(), `tracks-wrap-${process.pid}.pdf`);
+ fs.writeFileSync(wrapPdf, await doc.save());
+
+ try {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto("/editor", {
+ waitUntil: "domcontentloaded",
+ timeout: 120_000,
+ });
+ await uploadFiles(page, wrapPdf);
+ await dismissTourTooltip(page);
+ await switchView(page, "Page Editor");
+
+ const lane = page.locator("[data-track-lane]");
+ await expect(page.locator("section[aria-label]").first()).toContainText(
+ "300 pages",
+ { timeout: 60_000 },
+ );
+
+ // One file, so the editor opens wrapped: the lane doesn't scroll
+ // horizontally (overflow-x visible), it grows downward instead.
+ await expect
+ .poll(() => lane.evaluate((el) => getComputedStyle(el).overflowX), {
+ timeout: 30_000,
+ })
+ .toBe("visible");
+
+ // The pages occupy more than one row (distinct vertical offsets).
+ await expect
+ .poll(
+ () =>
+ page
+ .locator("[data-page-id]")
+ .evaluateAll(
+ (nodes) =>
+ new Set(
+ nodes.map((n) => Math.round((n as HTMLElement).offsetTop)),
+ ).size,
+ ),
+ { timeout: 30_000 },
+ )
+ .toBeGreaterThan(1);
+
+ // Still virtualised: a 300-page track mounts only a window, not all of it.
+ const mounted = await page.locator("[data-page-id]").count();
+ expect(mounted).toBeGreaterThan(0);
+ expect(mounted).toBeLessThan(200);
+
+ // Toggling off drops back to a single scrolling row (overflow-x auto),
+ // wider than the lane.
+ await page.getByRole("button", { name: "Wrap pages" }).click();
+ await expect
+ .poll(() => lane.evaluate((el) => getComputedStyle(el).overflowX), {
+ timeout: 30_000,
+ })
+ .toBe("auto");
+ await expect
+ .poll(
+ () => lane.evaluate((el) => el.scrollWidth > el.clientWidth + 1),
+ {
+ timeout: 30_000,
+ },
+ )
+ .toBe(true);
+ } finally {
+ fs.rmSync(wrapPdf, { force: true });
+ }
+ });
+
+ test("several files open unwrapped, in scrolling rows", async ({ page }) => {
+ // A long track so a single row overflows; paired with a second file so the
+ // editor sees more than one and leaves wrapping off.
+ const doc = await PDFDocument.create();
+ const font = await doc.embedFont(StandardFonts.Helvetica);
+ for (let i = 1; i <= 60; i++) {
+ doc
+ .addPage([595, 842])
+ .drawText(`page ${i}`, { x: 60, y: 700, size: 28, font });
+ }
+ const longPdf = path.join(os.tmpdir(), `tracks-multi-${process.pid}.pdf`);
+ fs.writeFileSync(longPdf, await doc.save());
+
+ try {
+ await page.setViewportSize({ width: 1280, height: 800 });
+ await page.goto("/editor", {
+ waitUntil: "domcontentloaded",
+ timeout: 120_000,
+ });
+ await uploadFiles(page, [longPdf, SAMPLE_PDF]);
+ await dismissTourTooltip(page);
+ await switchView(page, "Page Editor");
+
+ const longTrack = track(page, path.basename(longPdf));
+ await expect(longTrack).toContainText("60 pages", { timeout: 60_000 });
+
+ // Two files: the long track stays in a single horizontally scrolling row.
+ const lane = longTrack.locator("[data-track-lane]");
+ await expect
+ .poll(
+ () => lane.evaluate((el) => el.scrollWidth > el.clientWidth + 1),
+ {
+ timeout: 30_000,
+ },
+ )
+ .toBe(true);
+ } finally {
+ fs.rmSync(longPdf, { force: true });
+ }
+ });
+
+ test("collapsing a track hides its pages, and the header keeps the count", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+
+ await rotated
+ .getByRole("button", { name: "Collapse", exact: true })
+ .click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(0);
+ // The header, with its page count, stays visible while collapsed.
+ await expect(rotated).toContainText("4 pages");
+
+ await rotated.getByRole("button", { name: "Expand", exact: true }).click();
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4);
+ });
+
+ test("zooming scales the pages while the header keeps its size", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const firstTile = rotated.locator("[data-page-id]").first();
+ await expect(firstTile).toBeVisible({ timeout: 30_000 });
+
+ const pageNumber = firstTile.locator("[data-page-index]");
+ const fontSize = () =>
+ pageNumber.evaluate((el) => parseFloat(getComputedStyle(el).fontSize));
+
+ const tileBefore = await firstTile.boundingBox();
+ const headerBefore = await rotated.locator("header").boundingBox();
+ const fontBefore = await fontSize();
+ if (!tileBefore || !headerBefore) throw new Error("track is not laid out");
+
+ await page.getByRole("button", { name: "Zoom in" }).click();
+ await page.getByRole("button", { name: "Zoom in" }).click();
+
+ // The page tile grows...
+ await expect
+ .poll(async () => (await firstTile.boundingBox())?.width ?? 0, {
+ timeout: 30_000,
+ })
+ .toBeGreaterThan(tileBefore.width + 1);
+
+ // ...and so does the page number...
+ await expect
+ .poll(fontSize, { timeout: 30_000 })
+ .toBeGreaterThan(fontBefore);
+
+ // ...while the header (UI chrome) keeps its height.
+ const headerAfter = await rotated.locator("header").boundingBox();
+ expect(Math.round(headerAfter?.height ?? 0)).toBe(
+ Math.round(headerBefore.height),
+ );
+ });
+
+ test("the hover controls scale with the page on zoom", async ({ page }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const firstTile = rotated.locator("[data-page-id]").first();
+ await expect(firstTile).toBeVisible({ timeout: 30_000 });
+
+ const pill = firstTile.locator('[data-hover-action-menu="true"]');
+ const pillBefore = await pill.boundingBox();
+ if (!pillBefore) throw new Error("hover controls are not laid out");
+
+ await page.getByRole("button", { name: "Zoom in" }).click();
+ await page.getByRole("button", { name: "Zoom in" }).click();
+
+ // The pill grows with the page, so its buttons stay proportionate.
+ await expect
+ .poll(async () => (await pill.boundingBox())?.width ?? 0, {
+ timeout: 30_000,
+ })
+ .toBeGreaterThan(pillBefore.width + 1);
+ });
+
+ test("the page's view button opens a large preview of that page", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const firstTile = rotated.locator("[data-page-id]").first();
+ await expect(firstTile).toBeVisible({ timeout: 30_000 });
+
+ await firstTile.hover();
+ await firstTile.getByRole("button", { name: "View page" }).click();
+
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toContainText("Page 1 of 4");
+ await expect(dialog.locator("img")).toBeVisible({ timeout: 30_000 });
+
+ // Previous is disabled on the first page; Next pages forward.
+ await expect(
+ dialog.getByRole("button", { name: "Previous page" }),
+ ).toBeDisabled();
+ await dialog.getByRole("button", { name: "Next page" }).click();
+ await expect(dialog).toContainText("Page 2 of 4");
+
+ // Viewing must not select the page: the modal portals to the body but is a
+ // React child of the track, so its events must not bubble to the tiles.
+ const anySelected = page.locator('[data-page-id][data-selected="true"]');
+ await expect(anySelected).toHaveCount(0);
+ await page.keyboard.press("Escape");
+ await expect(dialog).toBeHidden();
+ await expect(anySelected).toHaveCount(0);
+ });
+
+ test("splitting a track immediately makes a second track, pending until save", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+ expect(await trackOrder(page)).toEqual(["rotated-pages.pdf", "sample.pdf"]);
+
+ // Split so page 3 starts a new track, via the handle in the gap before it.
+ await rotated.locator('[data-split-before="3"]').click();
+
+ // A new track appears at once, right after the one it came from.
+ await expect
+ .poll(() => trackOrder(page), { timeout: 30_000 })
+ .toEqual(["rotated-pages.pdf", "rotated-pages_split.pdf", "sample.pdf"]);
+
+ // The original keeps pages 1-2; the split holds 3-4.
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(2);
+ const split = track(page, "rotated-pages_split.pdf");
+ await expect(split.locator("[data-page-id]")).toHaveCount(2);
+
+ // Both halves are pending edits, not yet written.
+ await expect(rotated).toContainText("edited");
+ await expect(split).toContainText("edited");
+
+ // Undo restores the single track.
+ await page.getByRole("button", { name: "Undo" }).click();
+ await expect
+ .poll(() => trackOrder(page), { timeout: 30_000 })
+ .toEqual(["rotated-pages.pdf", "sample.pdf"]);
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4);
+ });
+
+ test("saving a split writes the new half to its own file", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ await expect(rotated.locator("[data-page-id]")).toHaveCount(4, {
+ timeout: 30_000,
+ });
+
+ await rotated.locator('[data-split-before="3"]').click();
+ const split = track(page, "rotated-pages_split.pdf");
+ await expect(split.locator("[data-page-id]")).toHaveCount(2, {
+ timeout: 30_000,
+ });
+
+ const saveButton = page.getByRole("button", {
+ name: "Save changes to all files",
+ });
+ await expect(saveButton).toBeEnabled();
+ await saveButton.click();
+
+ // The split becomes a real, separate active file that stays as its own
+ // track (it must not vanish on save), and nothing is left pending.
+ await expect(split).toBeVisible({ timeout: 60_000 });
+ await expect(split.locator("[data-page-id]")).toHaveCount(2);
+ await expect(saveButton).toBeDisabled({ timeout: 60_000 });
+ await expect(page.getByTestId("page-tracks")).not.toContainText("edited");
+ // It is a real workbench file now, listed in the sidebar.
+ await expect(
+ page.getByText("rotated-pages_split.pdf", { exact: true }).first(),
+ ).toBeVisible();
+ });
+
+ test("the eye opens that track's file in the viewer", async ({ page }) => {
+ await openPageEditor(page);
+ const sample = track(page, "sample.pdf");
+ await expect(sample.locator("[data-page-id]")).toHaveCount(1, {
+ timeout: 30_000,
+ });
+
+ // Second track, so landing on the first file would look like success.
+ await sample.getByRole("button", { name: "Open in Viewer" }).click();
+
+ await expect(page.getByTestId("page-tracks")).toHaveCount(0);
+ await expect(viewerActiveFile(page)).toHaveText("sample.pdf");
+ });
+
+ test("the eye prompts when edits are pending, then views the saved version", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(4, { timeout: 30_000 });
+
+ // Dirty the very file being opened: the save gives it a new id, so the
+ // viewer target has to follow the version bump.
+ const last = tiles.nth(3);
+ await last.hover();
+ await last.getByRole("button", { name: "Delete page" }).click();
+ await expect(tiles).toHaveCount(3);
+
+ await rotated.getByRole("button", { name: "Open in Viewer" }).click();
+
+ await expect(
+ page.getByRole("heading", { name: "Unsaved Changes" }),
+ ).toBeVisible();
+ await page.getByRole("button", { name: "Save & Leave" }).click();
+
+ // Landed in the viewer on the file the eye named. Saving gives every
+ // changed file a NEW id, and the viewer drops an active file that has left
+ // the workbench, so this only holds if the target is re-pointed.
+ await expect(page.getByTestId("page-tracks")).toHaveCount(0, {
+ timeout: 90_000,
+ });
+ await expect(viewerActiveFile(page)).toHaveText("rotated-pages.pdf", {
+ timeout: 60_000,
+ });
+
+ // And the pending edit was written rather than dropped.
+ await switchView(page, "Page Editor");
+ const saved = track(page, "rotated-pages.pdf");
+ await expect(saved).toContainText("v2", { timeout: 90_000 });
+ await expect(saved.locator("[data-page-id]")).toHaveCount(3);
+ });
+
+ test("dragging a track header reorders the tracks", async ({ page }) => {
+ await openPageEditor(page);
+ await expect(
+ track(page, "sample.pdf").locator("[data-page-id]"),
+ ).toHaveCount(1, { timeout: 30_000 });
+ expect(await trackOrder(page)).toEqual(["rotated-pages.pdf", "sample.pdf"]);
+
+ // Drop sample.pdf on the top half of rotated-pages.pdf: above it.
+ await dragTrackOnto(page, "sample.pdf", "rotated-pages.pdf", 0.2);
+ await expect
+ .poll(async () => trackOrder(page), { timeout: 30_000 })
+ .toEqual(["sample.pdf", "rotated-pages.pdf"]);
+
+ // Pages stayed with their own files rather than moving between tracks.
+ await expect(
+ track(page, "sample.pdf").locator("[data-page-id]"),
+ ).toHaveCount(1);
+ await expect(
+ track(page, "rotated-pages.pdf").locator("[data-page-id]"),
+ ).toHaveCount(4);
+ await expect(track(page, "rotated-pages.pdf")).not.toContainText("edited");
+ });
+
+ test("reordering tracks keeps pending page edits and their undo history", async ({
+ page,
+ }) => {
+ await openPageEditor(page);
+ const rotated = track(page, "rotated-pages.pdf");
+ const tiles = rotated.locator("[data-page-id]");
+ await expect(tiles).toHaveCount(4, { timeout: 30_000 });
+
+ const last = tiles.nth(3);
+ await last.hover();
+ await last.getByRole("button", { name: "Delete page" }).click();
+ await expect(tiles).toHaveCount(3);
+
+ await dragTrackOnto(page, "sample.pdf", "rotated-pages.pdf", 0.2);
+ await expect
+ .poll(async () => trackOrder(page), { timeout: 30_000 })
+ .toEqual(["sample.pdf", "rotated-pages.pdf"]);
+
+ // The edit is still pending, not silently re-baselined by the reorder.
+ const moved = track(page, "rotated-pages.pdf");
+ await expect(moved.locator("[data-page-id]")).toHaveCount(3);
+ await expect(moved).toContainText("edited");
+
+ // And it is still undoable. The toolbar re-renders on the reorder, so a
+ // single click can be dropped mid-render; retry until it lands (undoing
+ // past the baseline is a no-op, so an extra click is harmless).
+ const undo = page.getByRole("button", { name: "Undo" });
+ await expect
+ .poll(
+ async () => {
+ if ((await moved.locator("[data-page-id]").count()) === 4) return 4;
+ await undo.click();
+ return moved.locator("[data-page-id]").count();
+ },
+ { timeout: 30_000 },
+ )
+ .toBe(4);
+ await expect(moved).not.toContainText("edited");
+ });
+});
diff --git a/frontend/editor/src/core/types/pageEditor.ts b/frontend/editor/src/core/types/pageEditor.ts
index 573eb8c964..0fc9959a13 100644
--- a/frontend/editor/src/core/types/pageEditor.ts
+++ b/frontend/editor/src/core/types/pageEditor.ts
@@ -1,13 +1,5 @@
import { FileId } from "@app/types/file";
-export type PageSize = "A4" | "Letter" | "Legal" | "A3" | "A5";
-export type PageOrientation = "portrait" | "landscape";
-
-export interface PageBreakSettings {
- size: PageSize;
- orientation: PageOrientation;
-}
-
export interface PDFPage {
id: string;
pageNumber: number;
@@ -17,9 +9,10 @@ export interface PDFPage {
selected: boolean;
splitAfter?: boolean;
isBlankPage?: boolean;
+ /** A blank page's size in PDF points, before rotation; A4 when absent. */
+ blankSize?: { width: number; height: number };
isPlaceholder?: boolean;
originalFileId?: FileId;
- pageBreakSettings?: PageBreakSettings;
}
export interface PDFDocument {
@@ -47,35 +40,3 @@ export interface PageOperation {
error?: string;
};
}
-
-export interface UndoRedoState {
- operations: PageOperation[];
- currentIndex: number;
-}
-
-export interface PageEditorFunctions {
- closePdf: () => void;
- handleUndo: () => void;
- handleRedo: () => void;
- canUndo: boolean;
- canRedo: boolean;
- handleRotate: (direction: "left" | "right") => void;
- handleDelete: () => void;
- handleSplit: () => void;
- handleSplitAll: () => void;
- handlePageBreak: () => void;
- handlePageBreakAll: () => void;
- handleSelectAll: () => void;
- handleDeselectAll: () => void;
- handleSetSelectedPages: (pageNumbers: number[]) => void;
- showExportPreview: (selectedOnly: boolean) => void;
- onExportSelected: () => void;
- onExportAll: () => void;
- applyChanges: () => void;
- exportLoading: boolean;
- selectionMode: boolean;
- selectedPageIds: string[];
- displayDocument?: PDFDocument;
- splitPositions: Set<string>;
- totalPages: number;
-}
diff --git a/frontend/editor/src/core/types/workbench.ts b/frontend/editor/src/core/types/workbench.ts
index cc249eed25..57b9f2f744 100644
--- a/frontend/editor/src/core/types/workbench.ts
+++ b/frontend/editor/src/core/types/workbench.ts
@@ -1,6 +1,7 @@
// Define workbench values once as source of truth
export const BASE_WORKBENCH_TYPES = [
"viewer",
+ // Multi-file page editor: every open PDF as its own track of pages.
"pageEditor",
"fileEditor",
"myFiles",
diff --git a/frontend/editor/src/core/types/workbenchBar.ts b/frontend/editor/src/core/types/workbenchBar.ts
index 83e086c1ff..74bc53508f 100644
--- a/frontend/editor/src/core/types/workbenchBar.ts
+++ b/frontend/editor/src/core/types/workbenchBar.ts
@@ -1,4 +1,5 @@
import React from "react";
+import type { FileId } from "@app/types/file";
/** "bar-lead" follows the view switcher, for content naming what the view is showing;
* "bar" renders among the bar's own actions on the right; top/middle/bottom are lanes
@@ -48,3 +49,25 @@ export interface WorkbenchBarButtonConfig {
/** Optional active state to highlight the control */
active?: boolean;
}
+
+/** One file the bar's download writes out. */
+export interface WorkbenchExportFile {
+ file: File;
+ /** The workbench record these bytes are, if any: lets the download save back
+ * to its disk location and lets export policies version it. Omit for bytes
+ * the workbench does not hold, such as unsaved edits. */
+ fileId?: FileId;
+}
+
+/**
+ * Stands in for the bar's file-level download and close while a view that owns
+ * what it shows is open. Each is optional; the bar's default runs for the rest.
+ */
+export interface WorkbenchViewFileActions {
+ /**
+ * The files to download in place of the open ones, or null to cancel. The bar
+ * cancels silently, so a view returning null has already told the user why.
+ */
+ getExportFiles?: () => Promise<WorkbenchExportFile[] | null>;
+ onClose?: () => void;
+}
diff --git a/frontend/editor/src/core/components/pageEditor/fileColors.ts b/frontend/editor/src/core/utils/fileColors.ts
similarity index 57%
rename from frontend/editor/src/core/components/pageEditor/fileColors.ts
rename to frontend/editor/src/core/utils/fileColors.ts
index 18eedff990..5f376b8bfc 100644
--- a/frontend/editor/src/core/components/pageEditor/fileColors.ts
+++ b/frontend/editor/src/core/utils/fileColors.ts
@@ -1,10 +1,4 @@
-/**
- * File color palette for page editor
- * Each file gets a distinct color for visual organization
- * Colors are applied at 0.3 opacity for subtle highlighting
- * Maximum 20 files supported in page editor
- */
-
+/** Distinct colours for telling files or participants apart, indexed in order. */
export const FILE_COLORS = [
// Subtle colors (1-6) - fit well with UI theme
"rgb(59, 130, 246)", // Blue
@@ -33,13 +27,7 @@ export const FILE_COLORS = [
"rgb(192, 132, 252)", // Light Purple
] as const;
-export const MAX_PAGE_EDITOR_FILES = 20;
-
-/**
- * Get color for a file by its index
- * @param index - Zero-based file index
- * @returns RGB color string
- */
+/** Falls back to the first colour for an index past the palette. */
export function getFileColor(index: number): string {
if (index < 0 || index >= FILE_COLORS.length) {
console.warn(`File index ${index} out of range, using default color`);
@@ -47,18 +35,3 @@ export function getFileColor(index: number): string {
}
return FILE_COLORS[index];
}
-
-/**
- * Get color with specified opacity
- * @param index - Zero-based file index
- * @param opacity - Opacity value (0-1), defaults to 0.3
- * @returns RGBA color string
- */
-export function getFileColorWithOpacity(
- index: number,
- opacity: number = 0.2,
-): string {
- const rgb = getFileColor(index);
- // Convert rgb(r, g, b) to rgba(r, g, b, a)
- return rgb.replace("rgb(", "rgba(").replace(")", `, ${opacity})`);
-}
diff --git a/frontend/editor/src/core/utils/signingPreviews.ts b/frontend/editor/src/core/utils/signingPreviews.ts
index feae979a9b..ccb4290259 100644
--- a/frontend/editor/src/core/utils/signingPreviews.ts
+++ b/frontend/editor/src/core/utils/signingPreviews.ts
@@ -1,5 +1,5 @@
import type { SignaturePreview } from "@app/components/viewer/viewerTypes";
-import { getFileColor } from "@app/components/pageEditor/fileColors";
+import { getFileColor } from "@app/utils/fileColors";
import type { SigningParticipantPreview } from "@app/types/signingSession";
/** Only submitted marks overlay the original PDF; finalized PDFs already contain those marks. */