Skip to content

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

Add extra page actions to Page Editor (#8408)

James Bruntonfc6e0cbde0c8
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index cbad6c6a68..9823ce48cb 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6752,8 +6752,12 @@ title = "Special Keywords"
[pageTracks]
blankPage = "Blank page"
deleteSelected = "Delete selected pages"
+downloadAsOneFile = "Download as one file"
+downloadEachPage = "Download each page individually"
+downloadSelectedPages = "Download selected pages"
dragging_one = "{{count}} page"
dragging_other = "{{count}} pages"
+duplicateSelected = "Duplicate selected pages"
edited = "edited"
emptyTrack = "No pages left. Drag pages here, or save to close this file."
insertBlank = "Insert blank page"
@@ -6772,7 +6776,10 @@ rotateLeft = "Rotate left"
rotateRight = "Rotate right"
rotateSelectedLeft = "Rotate selected pages left"
rotateSelectedRight = "Rotate selected pages right"
+saveAsOneFile = "Save as one file"
saveChanges = "Save changes to all files"
+saveEachPage = "Save each page individually"
+saveSelectedPages = "Save selected pages"
saving = "Saving..."
savingProgress = "Saving {{done}} of {{total}}"
selectPage = "Select page {{number}}"
diff --git a/frontend/editor/src/core/components/pageTracks/DownloadSelectedPagesMenu.tsx b/frontend/editor/src/core/components/pageTracks/DownloadSelectedPagesMenu.tsx
new file mode 100644
index 0000000000..613e2c48d5
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/DownloadSelectedPagesMenu.tsx
@@ -0,0 +1,52 @@
+import { Menu } from "@mantine/core";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon, IconName } from "@app/ui/Icon";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { SelectedPagesLayout } from "@app/components/pageTracks/buildTrackFile";
+
+interface DownloadSelectedPagesMenuProps {
+ label: string;
+ eachPageLabel: string;
+ oneFileLabel: string;
+ iconName: IconName;
+ disabled: boolean;
+ onDownload: (layout: SelectedPagesLayout) => void;
+}
+
+/** The selected-pages download for several pages, which can go out as one file or one per page. */
+export function DownloadSelectedPagesMenu({
+ label,
+ eachPageLabel,
+ oneFileLabel,
+ iconName,
+ disabled,
+ onDownload,
+}: DownloadSelectedPagesMenuProps) {
+ return (
+ <Menu shadow="md" position="bottom-start">
+ <Menu.Target>
+ <div style={{ display: "inline-flex" }}>
+ <Tooltip content={label} position="bottom" offset={6} arrow>
+ <ActionIcon
+ variant="quiet"
+ hover={false}
+ className="workbench-bar-action-icon"
+ disabled={disabled}
+ aria-label={label}
+ >
+ <Icon name={iconName} size="1.25rem" />
+ </ActionIcon>
+ </Tooltip>
+ </div>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item onClick={() => onDownload("eachPage")}>
+ {eachPageLabel}
+ </Menu.Item>
+ <Menu.Item onClick={() => onDownload("oneFile")}>
+ {oneFileLabel}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ );
+}
diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
index e739e8d8c8..5cfe773ae6 100644
--- a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
@@ -7,6 +7,7 @@ import {
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
+import type { TFunction } from "i18next";
import { Center, Loader, LoadingOverlay, Stack, Text } from "@mantine/core";
import {
CollisionDetection,
@@ -36,12 +37,16 @@ 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 { downloadFileWithPolicy } from "@app/services/exportWithPolicy";
import {
PolicyBlockedError,
assertFilesNotBlocked,
} from "@app/services/policyFileGuard";
import {
+ SelectedPagesLayout,
+ buildSelectedPagesFiles,
buildTrackFile,
+ policyIdsForPages,
policyIdsForTracks,
} from "@app/components/pageTracks/buildTrackFile";
import { tracksEntangledWith } from "@app/components/pageTracks/trackWorkspaceReducer";
@@ -49,6 +54,7 @@ import { useTrackWorkspace } from "@app/components/pageTracks/hooks/useTrackWork
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 { usePageTracksShortcuts } from "@app/components/pageTracks/hooks/usePageTracksShortcuts";
import { usePageTracksWorkbenchBarButtons } from "@app/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons";
import { totalPageCount } from "@app/components/pageTracks/types";
import { opensAsTrack } from "@app/components/pageTracks/trackFileKind";
@@ -111,6 +117,26 @@ const sameHint = (a: DropHint | null, b: DropHint | null): boolean =>
* the drag delta. Using this rather than a live pointermove listener keeps the
* side-of-tile decision consistent with the reported collision.
*/
+function alertExportFailure(error: unknown, t: TFunction) {
+ if (error instanceof PolicyBlockedError) {
+ alert({
+ alertType: "warning",
+ title: t("policy.recoveryTitle"),
+ body: t("policy.recoveryBody"),
+ });
+ return;
+ }
+ 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.",
+ ),
+ });
+}
+
function pointerYOf(event: DragMoveEvent | DragEndEvent): number {
const activator = event.activatorEvent;
const originY =
@@ -322,6 +348,7 @@ export default function PageTracks() {
[selection.selectedIds],
);
const { setSelection, selectedIds } = selection;
+ usePageTracksShortcuts({ selectedIds, dispatch });
const selectNumbersEverywhere = useCallback(
(pageNumbers: number[]) => {
const wanted = new Set(pageNumbers);
@@ -398,6 +425,15 @@ export default function PageTracks() {
[dispatch, selection.selectedIds],
);
+ const duplicateSelection = useCallback(
+ () =>
+ dispatch({
+ type: "duplicate",
+ pageIds: Array.from(selection.selectedIds),
+ }),
+ [dispatch, selection.selectedIds],
+ );
+
const splitAfterSelection = useCallback(
() =>
dispatch({
@@ -792,27 +828,52 @@ export default function PageTracks() {
}
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.",
- ),
- });
- }
+ alertExportFailure(error, t);
return null;
}
}, [changedSet, fileSelectors, t, workspace]);
+ const [downloadingSelection, setDownloadingSelection] = useState(false);
+ const downloadSelection = useCallback(
+ async (layout: SelectedPagesLayout) => {
+ const lookup = {
+ getStub: fileSelectors.getStirlingFileStub,
+ getFile: fileSelectors.getFile,
+ };
+ setDownloadingSelection(true);
+ try {
+ const policyIds = policyIdsForPages(
+ workspace,
+ selection.selectedIds,
+ lookup.getStub,
+ );
+ assertFilesNotBlocked(policyIds);
+ const built = await buildSelectedPagesFiles(
+ workspace,
+ selection.selectedIds,
+ layout,
+ lookup,
+ );
+ // A policy can fail while the files are being built.
+ assertFilesNotBlocked(policyIds);
+ for (const { file } of built) {
+ await downloadFileWithPolicy({ data: file, filename: file.name });
+ }
+ } catch (error) {
+ alertExportFailure(error, t);
+ } finally {
+ setDownloadingSelection(false);
+ }
+ },
+ [fileSelectors, selection.selectedIds, t, workspace],
+ );
+ const downloadSelectionNow = useCallback(
+ (layout: SelectedPagesLayout) => {
+ void downloadSelection(layout);
+ },
+ [downloadSelection],
+ );
+
// 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);
@@ -939,6 +1000,9 @@ export default function PageTracks() {
onDelete: deleteSelection,
onInsertBlankAfter: insertBlankAfterSelection,
onSplitAfter: splitAfterSelection,
+ onDuplicate: duplicateSelection,
+ downloadingSelection,
+ onDownloadSelected: downloadSelectionNow,
onUndo: undo,
onRedo: redo,
onSave: saveNow,
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
new file mode 100644
index 0000000000..62a4cf98e2
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.test.ts
@@ -0,0 +1,172 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { FileId } from "@app/types/file";
+import { StirlingFileStub } from "@app/types/fileContext";
+import { PDFDocument } from "@app/types/pageEditor";
+import {
+ BlankTrackPage,
+ SourceTrackPage,
+ TrackWorkspace,
+} from "@app/components/pageTracks/types";
+import {
+ buildSelectedPagesFiles,
+ policyIdsForPages,
+} from "@app/components/pageTracks/buildTrackFile";
+
+const exportPDFMultiFile = vi.hoisted(() => vi.fn());
+vi.mock("@app/services/pdfExportService", () => ({
+ pdfExportService: { exportPDFMultiFile },
+}));
+
+const A = "file-a" as FileId;
+const B = "file-b" as FileId;
+const SPLIT = "split-1" as FileId;
+
+const sourcePage = (
+ id: string,
+ sourceFileId: FileId,
+ sourcePageNumber: number,
+ rotation = 0,
+): SourceTrackPage => ({
+ kind: "source",
+ id,
+ sourceFileId,
+ sourcePageNumber,
+ sourceContentKey: "v1",
+ rotation,
+ width: 0,
+ height: 0,
+});
+
+const blankPage = (id: string): BlankTrackPage => ({
+ kind: "blank",
+ id,
+ rotation: 0,
+ width: 595,
+ height: 842,
+});
+
+const workspace: TrackWorkspace = {
+ order: [B, A, SPLIT],
+ tracks: {
+ [A]: {
+ fileId: A,
+ name: "a.pdf",
+ isNew: false,
+ pages: [sourcePage("a1", A, 1), sourcePage("a2", A, 2, 90)],
+ },
+ [B]: {
+ fileId: B,
+ name: "b.pdf",
+ isNew: false,
+ pages: [
+ sourcePage("b1", B, 1),
+ blankPage("blank-b"),
+ sourcePage("a3", A, 3),
+ ],
+ },
+ [SPLIT]: {
+ fileId: SPLIT,
+ name: "a (2).pdf",
+ isNew: true,
+ splitFromFileId: A,
+ pages: [blankPage("blank-split")],
+ },
+ },
+};
+
+const lookup = {
+ getStub: (id: FileId) =>
+ ({ id, name: `${id}.pdf` }) as unknown as StirlingFileStub,
+ getFile: (id: FileId) => new File([id], `${id}.pdf`),
+};
+
+const exportedPageIds = (call: number): string[] =>
+ (exportPDFMultiFile.mock.calls[call][0] as PDFDocument).pages.map(
+ (page) => page.id,
+ );
+
+describe("buildSelectedPagesFiles", () => {
+ beforeEach(() => {
+ exportPDFMultiFile.mockReset();
+ exportPDFMultiFile.mockResolvedValue({ blob: new Blob(["%PDF"]) });
+ });
+
+ it("writes one file per page in workspace order, named by track and position", async () => {
+ const built = await buildSelectedPagesFiles(
+ workspace,
+ new Set(["a2", "a3", "b1"]),
+ "eachPage",
+ lookup,
+ );
+
+ expect(built.map(({ file }) => file.name)).toEqual([
+ "b (page 1).pdf",
+ "b (page 3).pdf",
+ "a (page 2).pdf",
+ ]);
+ expect(built.map(({ parentStub }) => parentStub.id)).toEqual([B, A, A]);
+ expect([0, 1, 2].map(exportedPageIds)).toEqual([["b1"], ["a3"], ["a2"]]);
+ const [page] = (exportPDFMultiFile.mock.calls[2][0] as PDFDocument).pages;
+ expect(page).toMatchObject({
+ originalFileId: A,
+ originalPageNumber: 2,
+ rotation: 90,
+ });
+ });
+
+ it("merges pages from every track into one file named after the first", async () => {
+ const built = await buildSelectedPagesFiles(
+ workspace,
+ new Set(["a2", "blank-b", "b1"]),
+ "oneFile",
+ lookup,
+ );
+
+ expect(built.map(({ file }) => file.name)).toEqual([
+ "b (selected pages).pdf",
+ ]);
+ expect(exportedPageIds(0)).toEqual(["b1", "blank-b", "a2"]);
+ const sourceFiles = exportPDFMultiFile.mock.calls[0][1] as Map<
+ string,
+ File
+ >;
+ expect([...sourceFiles.keys()].sort()).toEqual([A, B]);
+ });
+
+ it("parents a blank page in a split to the file it was cut from", async () => {
+ const built = await buildSelectedPagesFiles(
+ workspace,
+ new Set(["blank-split"]),
+ "eachPage",
+ lookup,
+ );
+
+ expect(built.map(({ file }) => file.name)).toEqual(["a (2) (page 1).pdf"]);
+ expect(built[0]?.parentStub.id).toBe(A);
+ });
+
+ it("writes nothing when no selected page is still open", async () => {
+ expect(
+ await buildSelectedPagesFiles(
+ workspace,
+ new Set(["gone"]),
+ "oneFile",
+ lookup,
+ ),
+ ).toEqual([]);
+ expect(exportPDFMultiFile).not.toHaveBeenCalled();
+ });
+});
+
+describe("policyIdsForPages", () => {
+ it("covers only the files the selected pages copy from", () => {
+ const ids = policyIdsForPages(
+ workspace,
+ new Set(["a1", "blank-b"]),
+ (id) => ({ id }) as unknown as StirlingFileStub,
+ );
+ expect(ids).toContain(A);
+ expect(ids).not.toContain(B);
+ });
+});
diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
index 4c06298380..c64952c9ea 100644
--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts
@@ -11,6 +11,7 @@ import {
Track,
TrackPage,
TrackWorkspace,
+ allPages,
isSourcePage,
} from "@app/components/pageTracks/types";
@@ -115,8 +116,114 @@ export function policyIdsForTracks(
.filter(isSourcePage)
.forEach((page) => fileIds.add(page.sourceFileId));
}
+ return policyIdsForFiles(fileIds, getStub);
+}
+
+/** Every file whose bytes the selected pages copy, including consumed ancestors. */
+export function policyIdsForPages(
+ workspace: TrackWorkspace,
+ pageIds: ReadonlySet<string>,
+ getStub: TrackFileLookup["getStub"],
+): string[] {
+ const fileIds = new Set<FileId>();
+ for (const page of allPages(workspace)) {
+ if (pageIds.has(page.id) && isSourcePage(page)) {
+ fileIds.add(page.sourceFileId);
+ }
+ }
+ return policyIdsForFiles(fileIds, getStub);
+}
+
+function policyIdsForFiles(
+ fileIds: Set<FileId>,
+ getStub: TrackFileLookup["getStub"],
+): string[] {
return [...fileIds].flatMap((id) => {
const stub = getStub(id);
return stub ? policySourceIds(stub) : [id];
});
}
+
+/** How a download of the selected pages is split into files. */
+export type SelectedPagesLayout = "eachPage" | "oneFile";
+
+interface SelectedPage {
+ track: Track;
+ page: TrackPage;
+ /** 1-based position in its track, as the editor numbers it. */
+ pageNumber: number;
+}
+
+function selectedPagesInOrder(
+ workspace: TrackWorkspace,
+ selectedIds: ReadonlySet<string>,
+): SelectedPage[] {
+ return workspace.order.flatMap((trackId) => {
+ const track = workspace.tracks[trackId];
+ if (!track) return [];
+ return track.pages.flatMap((page, index) =>
+ selectedIds.has(page.id) ? [{ track, page, pageNumber: index + 1 }] : [],
+ );
+ });
+}
+
+const baseName = (track: Track): string => track.name.replace(/\.pdf$/i, "");
+
+/** Built as a split so it takes `name`, and blank pages alone still have the
+ * file of the track they sit in to parent to. */
+function buildPagesFile(
+ pages: TrackPage[],
+ name: string,
+ track: Track,
+ lookup: TrackFileLookup,
+): Promise<BuiltTrackFile | null> {
+ return buildTrackFile(
+ {
+ fileId: track.fileId,
+ name,
+ isNew: true,
+ splitFromFileId: track.isNew ? track.splitFromFileId : track.fileId,
+ pages,
+ },
+ lookup,
+ );
+}
+
+/**
+ * Renders the selected pages, as the editor shows them and in workspace order,
+ * without saving anything: one PDF per page named after its track and page
+ * number, or one PDF of them all named after the first page's track. Pages
+ * whose file has closed are skipped.
+ */
+export async function buildSelectedPagesFiles(
+ workspace: TrackWorkspace,
+ selectedIds: ReadonlySet<string>,
+ layout: SelectedPagesLayout,
+ lookup: TrackFileLookup,
+): Promise<BuiltTrackFile[]> {
+ const selected = selectedPagesInOrder(workspace, selectedIds);
+ const first = selected[0];
+ if (!first) return [];
+
+ if (layout === "oneFile") {
+ const output = await buildPagesFile(
+ selected.map(({ page }) => page),
+ `${baseName(first.track)} (selected pages).pdf`,
+ first.track,
+ lookup,
+ );
+ return output ? [output] : [];
+ }
+
+ const built: BuiltTrackFile[] = [];
+ for (const { track, page, pageNumber } of selected) {
+ const output = await buildPagesFile(
+ [page],
+ `${baseName(track)} (page ${pageNumber}).pdf`,
+ track,
+ lookup,
+ );
+ if (output) built.push(output);
+ }
+ return built;
+}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksShortcuts.test.ts b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksShortcuts.test.ts
new file mode 100644
index 0000000000..85069fde2b
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksShortcuts.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+import { TrackEditorAction } from "@app/components/pageTracks/trackWorkspaceReducer";
+import { usePageTracksShortcuts } from "@app/components/pageTracks/hooks/usePageTracksShortcuts";
+
+function setup(selected: string[]) {
+ const dispatch = vi.fn<(action: TrackEditorAction) => void>();
+ renderHook(() =>
+ usePageTracksShortcuts({ selectedIds: new Set(selected), dispatch }),
+ );
+ return { dispatch };
+}
+
+const press = (
+ key: string,
+ init: KeyboardEventInit = {},
+ target: EventTarget = document.body,
+) => {
+ const event = new KeyboardEvent("keydown", {
+ key,
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ });
+ target.dispatchEvent(event);
+ return event;
+};
+
+describe("usePageTracksShortcuts", () => {
+ it("undoes with Ctrl+Z and redoes with Ctrl+Shift+Z or Ctrl+Y", () => {
+ const { dispatch } = setup([]);
+ press("z", { ctrlKey: true });
+ press("Z", { metaKey: true, shiftKey: true });
+ press("y", { ctrlKey: true });
+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([
+ { type: "undo" },
+ { type: "redo" },
+ { type: "redo" },
+ ]);
+ });
+
+ it("deletes the selection with Delete or Backspace", () => {
+ const { dispatch } = setup(["a2"]);
+ press("Delete");
+ press("Backspace");
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ expect(dispatch).toHaveBeenLastCalledWith({
+ type: "delete",
+ pageIds: ["a2"],
+ });
+ });
+
+ it("leaves keys typed into a field or a dialog alone", () => {
+ const { dispatch } = setup(["a1"]);
+ const input = document.createElement("input");
+ const dialog = document.createElement("div");
+ dialog.setAttribute("role", "dialog");
+ const button = document.createElement("button");
+ dialog.append(button);
+ document.body.append(input, dialog);
+
+ press("Backspace", {}, input);
+ press("z", { ctrlKey: true }, button);
+ expect(dispatch).not.toHaveBeenCalled();
+
+ const checkbox = document.createElement("input");
+ checkbox.type = "checkbox";
+ document.body.append(checkbox);
+ press("Delete", {}, checkbox);
+ expect(dispatch).toHaveBeenCalledWith({ type: "delete", pageIds: ["a1"] });
+
+ input.remove();
+ dialog.remove();
+ checkbox.remove();
+ });
+});
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksShortcuts.ts b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksShortcuts.ts
new file mode 100644
index 0000000000..a3eed07b48
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksShortcuts.ts
@@ -0,0 +1,58 @@
+import { useEffect, useRef } from "react";
+import { TrackEditorAction } from "@app/components/pageTracks/trackWorkspaceReducer";
+
+interface PageTracksShortcutsParams {
+ selectedIds: ReadonlySet<string>;
+ dispatch: (action: TrackEditorAction) => void;
+}
+
+/** Inputs that take no typing, such as a page tile's checkbox, keep the shortcuts. */
+const NON_TEXT_INPUTS = new Set(["checkbox", "radio", "button", "submit"]);
+
+/** Typing in a field, or acting inside a dialog or menu over the editor, must not edit pages behind it. */
+function isOutsideEditor(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ if (target instanceof HTMLInputElement) {
+ return !NON_TEXT_INPUTS.has(target.type);
+ }
+ return (
+ target.tagName === "TEXTAREA" ||
+ target.tagName === "SELECT" ||
+ target.isContentEditable ||
+ target.closest('[role="dialog"], [role="menu"]') != null
+ );
+}
+
+export function usePageTracksShortcuts(params: PageTracksShortcutsParams) {
+ // Read through a ref so the listener is installed once, not per selection change.
+ const latest = useRef(params);
+ latest.current = params;
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.defaultPrevented || isOutsideEditor(event.target)) return;
+ const { selectedIds, dispatch } = latest.current;
+ const key = event.key.toLowerCase();
+ const command = event.ctrlKey || event.metaKey;
+
+ if (command && key === "z") {
+ event.preventDefault();
+ dispatch({ type: event.shiftKey ? "redo" : "undo" });
+ return;
+ }
+ if (command && key === "y") {
+ event.preventDefault();
+ dispatch({ type: "redo" });
+ return;
+ }
+ if (!command && (event.key === "Delete" || event.key === "Backspace")) {
+ if (selectedIds.size === 0) return;
+ event.preventDefault();
+ dispatch({ type: "delete", pageIds: [...selectedIds] });
+ }
+ };
+
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, []);
+}
diff --git a/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx
index 93f41b65ec..dfc7cceacc 100644
--- a/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx
+++ b/frontend/editor/src/core/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons.tsx
@@ -5,9 +5,13 @@ import {
WorkbenchBarButtonWithAction,
} from "@app/hooks/useWorkbenchBarButtons";
import { Icon } from "@app/ui/Icon";
+import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
+import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
import { ActionIcon } from "@app/ui/ActionIcon";
import { Tooltip } from "@app/components/shared/Tooltip";
import styles from "@app/components/pageTracks/PageTracks.module.css";
+import { SelectedPagesLayout } from "@app/components/pageTracks/buildTrackFile";
+import { DownloadSelectedPagesMenu } from "@app/components/pageTracks/DownloadSelectedPagesMenu";
import {
SelectByNumberPopover,
SelectByNumberPopoverProps,
@@ -37,6 +41,10 @@ export interface PageTracksBarParams {
onDelete: () => void;
onInsertBlankAfter: () => void;
onSplitAfter: () => void;
+ onDuplicate: () => void;
+ downloadingSelection: boolean;
+ /** Downloads the selected pages without saving the edits. */
+ onDownloadSelected: (layout: SelectedPagesLayout) => void;
onUndo: () => void;
onRedo: () => void;
onSave: () => void;
@@ -62,11 +70,16 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
onDelete,
onInsertBlankAfter,
onSplitAfter,
+ onDuplicate,
+ downloadingSelection,
+ onDownloadSelected,
onUndo,
onRedo,
onSave,
} = params;
const { t } = useTranslation();
+ const terminology = useFileActionTerminology();
+ const fileActionIcons = useFileActionIcons();
const labels = {
wrap: t("pageTracks.wrap.label", "Wrap pages"),
@@ -84,6 +97,10 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
"Rotate selected pages right",
),
deleteSelected: t("pageTracks.deleteSelected", "Delete selected pages"),
+ duplicate: t("pageTracks.duplicateSelected", "Duplicate selected pages"),
+ downloadSelected: terminology.downloadSelectedPages,
+ downloadEachPage: terminology.downloadEachPage,
+ downloadAsOneFile: terminology.downloadAsOneFile,
insertBlankAfter: t(
"pageTracks.insertBlankAfterSelected",
"Insert blank pages after selected pages",
@@ -99,6 +116,7 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
const hasPages = totalPages > 0;
const hasSelection = selectedCount > 0;
+ const multipleSelected = selectedCount > 1;
const allSelected = hasPages && selectedCount === totalPages;
const selectAllLabel = allSelected ? labels.deselectAll : labels.selectAll;
@@ -210,6 +228,17 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
visible: hasPages,
onClick: onSplitAfter,
},
+ {
+ id: "tracks-duplicate-selected",
+ icon: <Icon name="copy-plus" size="1.25rem" />,
+ tooltip: labels.duplicate,
+ ariaLabel: labels.duplicate,
+ section: "middle" as const,
+ order: 28,
+ disabled: !hasSelection,
+ visible: hasPages,
+ onClick: onDuplicate,
+ },
{
id: "tracks-delete-selected",
icon: <Icon name="trash" size="1.5rem" />,
@@ -221,6 +250,31 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
visible: hasPages,
onClick: onDelete,
},
+ {
+ id: "tracks-download-selected",
+ icon: <Icon name={fileActionIcons.download} size="1.25rem" />,
+ tooltip: labels.downloadSelected,
+ ariaLabel: labels.downloadSelected,
+ section: "middle" as const,
+ order: 29,
+ disabled: !hasSelection || downloadingSelection,
+ visible: hasPages,
+ // One page has only one way to go out, so it skips the menu.
+ onClick: () => onDownloadSelected("eachPage"),
+ // A custom render bypasses the bar's click action and tooltip wrapper.
+ render: multipleSelected
+ ? ({ disabled }) => (
+ <DownloadSelectedPagesMenu
+ label={labels.downloadSelected}
+ eachPageLabel={labels.downloadEachPage}
+ oneFileLabel={labels.downloadAsOneFile}
+ iconName={fileActionIcons.download}
+ disabled={disabled}
+ onDownload={onDownloadSelected}
+ />
+ )
+ : undefined,
+ },
{
id: "tracks-undo",
icon: <Icon name="undo-2" size="1.25rem" />,
@@ -283,6 +337,12 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
labels.rotateLeft,
labels.rotateRight,
labels.deleteSelected,
+ labels.duplicate,
+ labels.downloadSelected,
+ labels.downloadEachPage,
+ labels.downloadAsOneFile,
+ multipleSelected,
+ fileActionIcons.download,
labels.insertBlankAfter,
labels.splitAfter,
labels.undo,
@@ -306,6 +366,9 @@ export function usePageTracksWorkbenchBarButtons(params: PageTracksBarParams) {
onDelete,
onInsertBlankAfter,
onSplitAfter,
+ onDuplicate,
+ downloadingSelection,
+ onDownloadSelected,
onUndo,
onRedo,
onSave,
diff --git a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
index 929ce299e1..f4eeff45c0 100644
--- a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
+++ b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
@@ -552,6 +552,41 @@ describe("trackEditorReducer insertBlank", () => {
expect(ids(state, B)).toEqual([`${B}:1`, `${B}:2`]);
});
+ it("puts a copy after each given page, across tracks, as one undo step", () => {
+ let state = twoTracks();
+ const [a1, a2] = pagesOf(state, A);
+ const [b1] = pagesOf(state, B);
+ state = trackEditorReducer(state, {
+ type: "insertBlankAfter",
+ pageIds: [a1.id],
+ });
+ const blank = pagesOf(state, A)[1];
+ state = trackEditorReducer(state, {
+ type: "duplicate",
+ pageIds: [a2.id, blank.id, b1.id],
+ });
+
+ expect(ids(state, A)).toEqual([
+ `${A}:1`,
+ "blank",
+ "blank",
+ `${A}:2`,
+ `${A}:2`,
+ `${A}:3`,
+ ]);
+ expect(ids(state, B)).toEqual([`${B}:1`, `${B}:1`, `${B}:2`]);
+ expect(pagesOf(state, A)[4]).toMatchObject({ rotation: 90 });
+ const allIds = [...pagesOf(state, A), ...pagesOf(state, B)].map(
+ (p) => p.id,
+ );
+ expect(new Set(allIds).size).toBe(allIds.length);
+ expect(changedTrackIds(state)).toEqual([A, B]);
+
+ state = trackEditorReducer(state, { type: "undo" });
+ expect(ids(state, A)).toEqual([`${A}:1`, "blank", `${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];
diff --git a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
index 260ee4dd3e..1c21ad52c4 100644
--- a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
+++ b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
@@ -72,6 +72,7 @@ export type TrackEditorAction =
}
/** A blank page after each of these, sized and turned like it. */
| { type: "insertBlankAfter"; pageIds: string[] }
+ | { type: "duplicate"; pageIds: string[] }
/** Swaps a page with its neighbour in the same track. */
| { type: "shiftPage"; pageId: string; by: -1 | 1 }
| { type: "dropTracks"; fileIds: FileId[] }
@@ -659,6 +660,19 @@ export function trackEditorReducer(
return { ...withEdit(state, next), seq };
}
+ case "duplicate": {
+ const duplicated = new Set(action.pageIds);
+ let seq = state.seq;
+ const next = mapTracks(state.present, (pages) => {
+ if (!pages.some((p) => duplicated.has(p.id))) return pages;
+ return pages.flatMap((p) =>
+ duplicated.has(p.id) ? [p, { ...p, id: `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);
diff --git a/frontend/editor/src/core/hooks/useFileActionTerminology.ts b/frontend/editor/src/core/hooks/useFileActionTerminology.ts
index 2f8b9127ad..33a0196f09 100644
--- a/frontend/editor/src/core/hooks/useFileActionTerminology.ts
+++ b/frontend/editor/src/core/hooks/useFileActionTerminology.ts
@@ -21,6 +21,18 @@ export function useFileActionTerminology() {
download: t("download", "Download"),
downloadAll: t("workbenchBar.downloadAll", "Download All"),
downloadSelected: t("fileManager.downloadSelected", "Download Selected"),
+ downloadSelectedPages: t(
+ "pageTracks.downloadSelectedPages",
+ "Download selected pages",
+ ),
+ downloadEachPage: t(
+ "pageTracks.downloadEachPage",
+ "Download each page individually",
+ ),
+ downloadAsOneFile: t(
+ "pageTracks.downloadAsOneFile",
+ "Download as one file",
+ ),
downloadUnavailable: t(
"downloadUnavailable",
"Download unavailable for this item",
diff --git a/frontend/editor/src/desktop/hooks/useFileActionTerminology.ts b/frontend/editor/src/desktop/hooks/useFileActionTerminology.ts
index fdd3ead22c..27b7d0525c 100644
--- a/frontend/editor/src/desktop/hooks/useFileActionTerminology.ts
+++ b/frontend/editor/src/desktop/hooks/useFileActionTerminology.ts
@@ -21,6 +21,15 @@ export function useFileActionTerminology() {
download: t("save", "Save"),
downloadAll: t("workbenchBar.saveAll", "Save All"),
downloadSelected: t("fileManager.saveSelected", "Save Selected"),
+ downloadSelectedPages: t(
+ "pageTracks.saveSelectedPages",
+ "Save selected pages",
+ ),
+ downloadEachPage: t(
+ "pageTracks.saveEachPage",
+ "Save each page individually",
+ ),
+ downloadAsOneFile: t("pageTracks.saveAsOneFile", "Save as one file"),
downloadUnavailable: t("saveUnavailable", "Save unavailable for this item"),
noFilesInStorage: t(
"fileUpload.noFilesInStorageOpen",