#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Support images in Page Editor (#8410)
James Brunton06a10136f692
diff --git a/frontend/editor/scripts/generate-tool-api-types.mts b/frontend/editor/scripts/generate-tool-api-types.mtsindex ce1c384556..420c455b70 100644--- a/frontend/editor/scripts/generate-tool-api-types.mts+++ b/frontend/editor/scripts/generate-tool-api-types.mts@@ -261,7 +261,10 @@ export type ToolFormat = ${union(formats)};export const TOOL_FORMATS = ${JSON.stringify(formats)} as const satisfies readonly ToolFormat[];/** Filename extensions from the backend ToolFormat declarations. */-export const TOOL_FORMAT_EXTENSIONS: Record<ToolFormat, readonly string[]> = ${JSON.stringify(vocabulary.extensions)};+export const TOOL_FORMAT_EXTENSIONS = ${JSON.stringify(vocabulary.extensions)} as const satisfies Record<ToolFormat, readonly string[]>;++/** The filename extensions of one format, as literals. */+export type ToolFormatExtension<F extends ToolFormat> = (typeof TOOL_FORMAT_EXTENSIONS)[F][number];/** How many files go in and come out. A multi-output tool returns its results zipped, and the caller unpacks them. */export type ToolArity = ${union(vocabulary.arities as string[])};diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx b/frontend/editor/src/core/components/pageTracks/PageTracks.tsxindex 7ca7de5da7..e739e8d8c8 100644--- a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx@@ -51,6 +51,7 @@ import { useTrackThumbnails } from "@app/components/pageTracks/hooks/useTrackThuimport { useTrackSave } from "@app/components/pageTracks/hooks/useTrackSave";import { usePageTracksWorkbenchBarButtons } from "@app/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons";import { totalPageCount } from "@app/components/pageTracks/types";+import { opensAsTrack } from "@app/components/pageTracks/trackFileKind";import TrackRow, { DropHint } from "@app/components/pageTracks/TrackRow";import { DisabledFileTrack } from "@app/components/pageTracks/DisabledFileTrack";import styles from "@app/components/pageTracks/PageTracks.module.css";@@ -60,9 +61,6 @@ 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;@@ -144,7 +142,7 @@ export default function PageTracks() {dispatch,pendingFileIds,unsupportedFileIds,- hasPdfFiles,+ hasEditableFiles,changedFileIds,isDirty,canUndo,@@ -232,9 +230,10 @@ export default function PageTracks() {// 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,+ fileState.files.ids.filter((id) => {+ const stub = fileState.files.byId[id];+ return stub != null && opensAsTrack(stub);+ }).length === 1,);const toggleWrap = useCallback(() => setWrap((prev) => !prev), []);@@ -483,8 +482,8 @@ export default function PageTracks() {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+ // The rows to render, in open-file order: each PDF or image's track (followed+ // by any splits made from it), each loading PDF, and any other file as a disabled// track. One sequence shared by the view and the track-reorder drag.const displayRows = useMemo(() => {const splitsByParent = new Map<FileId, FileId[]>();@@ -980,7 +979,7 @@ export default function PageTracks() {);};- if (!hasPdfFiles && unsupportedFileIds.length === 0) {+ if (!hasEditableFiles && unsupportedFileIds.length === 0) {return (<Center h="100%">{closeConfirmModal}diff --git a/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsx b/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsxindex 9f2357bc32..ee30b24a5e 100644--- a/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsx+++ b/frontend/editor/src/core/components/pageTracks/TrackPageViewModal.tsx@@ -12,6 +12,7 @@ import {isSourcePage,sourcePageKey,} from "@app/components/pageTracks/types";+import { isPageImage } from "@app/components/pageTracks/trackFileKind";import { BlankPagePreview } from "@app/components/pageTracks/BlankPagePreview";import { TrackThumbnailStore } from "@app/components/pageTracks/hooks/useTrackThumbnails";import styles from "@app/components/pageTracks/PageTracks.module.css";@@ -64,6 +65,11 @@ export function TrackPageViewModal({setFailed(true);return;}+ if (isPageImage(file)) {+ const url = URL.createObjectURL(file);+ setHiRes(url);+ return () => URL.revokeObjectURL(url);+ }void (async () => {try {const buffer = await file.arrayBuffer();diff --git a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts b/frontend/editor/src/core/components/pageTracks/buildTrackFile.tsindex 4464ff6c13..4c06298380 100644--- a/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts+++ b/frontend/editor/src/core/components/pageTracks/buildTrackFile.ts@@ -3,6 +3,10 @@ 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 {+ asPdfSource,+ toPdfName,+} from "@app/components/pageTracks/trackFileKind";import {Track,TrackPage,@@ -58,7 +62,8 @@ function toExportDocument(* 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.+ * are no pages or that file has closed. The output is always a PDF, so a track+ * that was an image is renamed to match.*/export async function buildTrackFile(track: Track,@@ -73,13 +78,14 @@ export async function buildTrackFile(const parentStub = lookup.getStub(anchorFileId);const ownFile = lookup.getFile(anchorFileId);if (!parentStub || !ownFile) return null;- const name = track.isNew ? track.name : parentStub.name;+ const name = toPdfName(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);+ if (sourceFile)+ sourceFiles.set(page.sourceFileId, await asPdfSource(sourceFile));}const { blob } = await pdfExportService.exportPDFMultiFile(diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.tsindex 0f26487a3d..1b8515cbcb 100644--- a/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.ts+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackThumbnails.ts@@ -13,11 +13,16 @@ import {isSourcePage,sourcePageKey,} from "@app/components/pageTracks/types";+import { isPageImage } from "@app/components/pageTracks/trackFileKind";+import { generateImageThumbnail } from "@app/utils/thumbnailUtils";/** 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;+/** Longest side of an image page's tile, in pixels: near the 842px a PDF A4+ * page renders its tile at, so an image is as sharp as its neighbours. */+const IMAGE_PAGE_THUMBNAIL_SIZE = 1024;export interface TrackThumbnailStore {subscribe: (listener: () => void) => () => void;@@ -37,7 +42,8 @@ export interface TrackThumbnailStore {*/export function useTrackThumbnails(): TrackThumbnailStore {const selectors = useFileSelectors();- const { requestThumbnail, getThumbnailFromCache } = useThumbnailGeneration();+ const { requestThumbnail, getThumbnailFromCache, addThumbnailToCache } =+ useThumbnailGeneration();const resolvedRef = useRef(new Map<string, string>());const listenersRef = useRef(new Set<() => void>());@@ -78,7 +84,15 @@ export function useTrackThumbnails(): TrackThumbnailStore {if (!file) continue;inFlightRef.current.add(key);- requestThumbnail(key, file, page.sourcePageNumber)+ const rendering = isPageImage(file)+ ? generateImageThumbnail(file, IMAGE_PAGE_THUMBNAIL_SIZE).then(+ (thumbnail) => {+ addThumbnailToCache(key, thumbnail);+ return thumbnail;+ },+ )+ : requestThumbnail(key, file, page.sourcePageNumber);+ rendering.then((thumbnail) => {if (thumbnail) {resolvedRef.current.set(key, thumbnail);@@ -93,7 +107,13 @@ export function useTrackThumbnails(): TrackThumbnailStore {pump();});}- }, [getThumbnailFromCache, requestThumbnail, scheduleNotify, selectors]);+ }, [+ addThumbnailToCache,+ getThumbnailFromCache,+ requestThumbnail,+ scheduleNotify,+ selectors,+ ]);const enqueue = useCallback((page: SourceTrackPage) => {diff --git a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.tsindex e35275d602..af465e5198 100644--- a/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts+++ b/frontend/editor/src/core/components/pageTracks/hooks/useTrackWorkspace.ts@@ -3,6 +3,8 @@ 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 { isPdfFile } from "@app/utils/fileUtils";+import { isPageImage } from "@app/components/pageTracks/trackFileKind";import {changedTrackIds,initialTrackEditorState,@@ -16,10 +18,10 @@ export interface TrackWorkspaceHook {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. */+ /** Open files the page editor can't edit (neither PDFs nor images); shown as disabled tracks. */unsupportedFileIds: FileId[];- /** True when any open file is a PDF (drives the empty state). */- hasPdfFiles: boolean;+ /** True when any open file can be expanded into a track (drives the empty state). */+ hasEditableFiles: boolean;changedFileIds: FileId[];isDirty: boolean;canUndo: boolean;@@ -34,9 +36,6 @@ function unrotatedSize(page: ProcessedFilePage): PageSize {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(@@ -47,24 +46,43 @@ export function useTrackWorkspace(): TrackWorkspaceHook {// 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 } =+ const { sources, pendingFileIds, unsupportedFileIds, hasEditableFiles } =useMemo(() => {const resolved: TrackSource[] = [];const pending: FileId[] = [];const unsupported: FileId[] = [];- let anyPdf = false;+ let anyEditable = 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)) {+ if (!stub) {+ unsupported.push(fileId);+ continue;+ }+ const contentKey = `${stub.size}:${stub.lastModified}`;+ // An image has no metadata to wait for: it is one unrotated page whose+ // size is only known once decoded, which happens on save.+ if (isPageImage(stub)) {+ anyEditable = true;+ resolved.push({+ fileId,+ name: stub.name,+ pageCount: 1,+ rotations: [0],+ sizes: [{ width: 0, height: 0 }],+ contentKey,+ });+ continue;+ }+ // Other open files show as disabled tracks so they are visible but+ // clearly not editable here.+ if (!isPdfFile(stub)) {unsupported.push(fileId);continue;}- anyPdf = true;+ anyEditable = true;- const pages = stub?.processedFile?.pages;+ const pages = stub.processedFile?.pages;if (!pages || pages.length === 0) {pending.push(fileId);continue;@@ -72,11 +90,11 @@ export function useTrackWorkspace(): TrackWorkspaceHook {resolved.push({fileId,- name: stub?.name ?? fileId,+ name: stub.name,pageCount: pages.length,rotations: pages.map((page) => page.rotation ?? 0),sizes: pages.map(unrotatedSize),- contentKey: `${stub?.size ?? 0}:${stub?.lastModified ?? 0}`,+ contentKey,});}@@ -84,7 +102,7 @@ export function useTrackWorkspace(): TrackWorkspaceHook {sources: resolved,pendingFileIds: pending,unsupportedFileIds: unsupported,- hasPdfFiles: anyPdf,+ hasEditableFiles: anyEditable,};}, [fileState.files]);@@ -104,7 +122,7 @@ export function useTrackWorkspace(): TrackWorkspaceHook {dispatch: stableDispatch,pendingFileIds,unsupportedFileIds,- hasPdfFiles,+ hasEditableFiles,changedFileIds,isDirty: changedFileIds.length > 0,canUndo: state.past.length > 0,diff --git a/frontend/editor/src/core/components/pageTracks/trackFileKind.test.ts b/frontend/editor/src/core/components/pageTracks/trackFileKind.test.tsnew file mode 100644index 0000000000..7608943321--- /dev/null+++ b/frontend/editor/src/core/components/pageTracks/trackFileKind.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";++import {+ isPageImage,+ opensAsTrack,+ toPdfName,+} from "@app/components/pageTracks/trackFileKind";++const file = (name: string, type = "") => ({ name, type });++describe("trackFileKind", () => {+ it("opens PDFs and browser-decodable images as tracks", () => {+ expect(opensAsTrack(file("report.PDF"))).toBe(true);+ expect(opensAsTrack(file("download", "application/pdf"))).toBe(true);+ expect(isPageImage(file("photo.JPEG"))).toBe(true);+ expect(isPageImage(file("scan.webp"))).toBe(true);+ expect(opensAsTrack(file("scan.tiff"))).toBe(false);+ expect(opensAsTrack(file("logo.svg"))).toBe(false);+ expect(opensAsTrack(file("notes.docx"))).toBe(false);+ expect(opensAsTrack(file("png"))).toBe(false);+ });++ it("names a saved track as a PDF", () => {+ expect(toPdfName("report.pdf")).toBe("report.pdf");+ expect(toPdfName("photo.final.png")).toBe("photo.final.pdf");+ expect(toPdfName("photo_split.jpeg")).toBe("photo_split.pdf");+ expect(toPdfName("untitled")).toBe("untitled.pdf");+ });+});diff --git a/frontend/editor/src/core/components/pageTracks/trackFileKind.ts b/frontend/editor/src/core/components/pageTracks/trackFileKind.tsnew file mode 100644index 0000000000..f6484b254d--- /dev/null+++ b/frontend/editor/src/core/components/pageTracks/trackFileKind.ts@@ -0,0 +1,40 @@+import type { StirlingFileStub } from "@app/types/fileContext";+import type { ToolFormatExtension } from "@app/types/toolIO";+import { convertImageToPdf } from "@app/utils/imageToPdfUtils";+import {+ detectFileExtension,+ isPdfFile,+ splitFileName,+} from "@app/utils/fileUtils";++type FileLike = Pick<StirlingFileStub, "name" | "type">;++/**+ * The IMAGE formats the browser can decode, so a one-page track can draw and+ * embed them without the backend.+ */+const BROWSER_DECODABLE_EXTENSIONS: ReadonlySet<string> = new Set<+ ToolFormatExtension<"IMAGE">+>(["png", "jpg", "gif", "bmp", "webp"]);++/** An image the page editor shows as a track holding one page: the image. */+export const isPageImage = (file: FileLike): boolean =>+ BROWSER_DECODABLE_EXTENSIONS.has(detectFileExtension(file.name));++export const opensAsTrack = (file: FileLike): boolean =>+ isPdfFile(file) || isPageImage(file);++/** Everything a track is saved as is a PDF, whatever the file was before. */+export const toPdfName = (name: string): string =>+ `${splitFileName(name)[0]}.pdf`;++/**+ * The file as a PDF the export service can copy pages from. An image becomes a+ * single page the size of its pixels at 72 dpi, so it keeps its own aspect and+ * resolution rather than being fitted to a paper size.+ */+export async function asPdfSource(file: File): Promise<File> {+ return isPageImage(file)+ ? convertImageToPdf(file, { pageFormat: "keep" })+ : file;+}diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.tsindex c2add8f07d..b7d22ed595 100644--- a/frontend/editor/src/core/types/toolIO.ts+++ b/frontend/editor/src/core/types/toolIO.ts@@ -66,7 +66,7 @@ export const TOOL_FORMATS = [] as const satisfies readonly ToolFormat[];/** Filename extensions from the backend ToolFormat declarations. */-export const TOOL_FORMAT_EXTENSIONS: Record<ToolFormat, readonly string[]> = {+export const TOOL_FORMAT_EXTENSIONS = {PDF: ["pdf"],PDF_ENCRYPTED: ["pdf"],IMAGE: [@@ -104,7 +104,11 @@ export const TOOL_FORMAT_EXTENSIONS: Record<ToolFormat, readonly string[]> = {CBR: ["cbr"],ANY: [],NONE: [],-};+} as const satisfies Record<ToolFormat, readonly string[]>;++/** The filename extensions of one format, as literals. */+export type ToolFormatExtension<F extends ToolFormat> =+ (typeof TOOL_FORMAT_EXTENSIONS)[F][number];/** How many files go in and come out. A multi-output tool returns its results zipped, and the caller unpacks them. */export type ToolArity = "SISO" | "SIMO" | "MISO" | "MIMO";diff --git a/frontend/editor/src/core/utils/fileUtils.ts b/frontend/editor/src/core/utils/fileUtils.tsindex 333ccb82d3..8e6150ccc8 100644--- a/frontend/editor/src/core/utils/fileUtils.ts+++ b/frontend/editor/src/core/utils/fileUtils.ts@@ -136,9 +136,10 @@ export function getFileFormats(if (file.processedFile?.isEncrypted) return ["PDF_ENCRYPTED"];if (isPdfFile(file)) return ["PDF"];const extension = detectFileExtension(file.name);- return TOOL_FORMATS.filter((format) =>- TOOL_FORMAT_EXTENSIONS[format].includes(extension),- );+ return TOOL_FORMATS.filter((format) => {+ const extensions: readonly string[] = TOOL_FORMAT_EXTENSIONS[format];+ return extensions.includes(extension);+ });}export type NonPdfFileType =diff --git a/frontend/editor/src/core/utils/thumbnailUtils.test.ts b/frontend/editor/src/core/utils/thumbnailUtils.test.tsindex 694b557a7f..4aa77b7a85 100644--- a/frontend/editor/src/core/utils/thumbnailUtils.test.ts+++ b/frontend/editor/src/core/utils/thumbnailUtils.test.ts@@ -281,6 +281,18 @@ describe("generateThumbnailForFile — images", () => {expect(calls[0].resizeHeight).toBe(320);});+ it("fits a requested box without enlarging a smaller image", async () => {+ const { generateImageThumbnail } =+ await import("@app/utils/thumbnailUtils");+ const { calls } = stubBitmapPipeline();+ await generateImageThumbnail(fileWithHeader(pngHeader(4000, 3000)), 1024);+ await generateImageThumbnail(fileWithHeader(pngHeader(200, 100)), 1024);+ expect(calls.map((call) => [call.resizeWidth, call.resizeHeight])).toEqual([+ [1024, 768],+ [200, 100],+ ]);+ });+it("reads JPEG dimensions from the start-of-frame marker", async () => {const { generateThumbnailForFile } =await import("@app/utils/thumbnailUtils");diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.tsindex de6d56d97b..9131c0ce9b 100644--- a/frontend/editor/src/core/utils/thumbnailUtils.ts+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts@@ -417,13 +417,16 @@ function readJpegDimensions(return null;}-/** Resize a known source into a thumbnail-sized box, longest side first. */-function thumbnailResizeOptions(source: { width: number; height: number }): {+/** Resize a known source to fit a `maxSize` box, longest side first, never+ * enlarging it. */+function thumbnailResizeOptions(+ source: { width: number; height: number },+ maxSize: number,+): {resizeWidth: number;resizeHeight: number;} {- const scale =- IMAGE_THUMBNAIL_MAX_SIZE / Math.max(source.width, source.height);+ const scale = Math.min(1, maxSize / Math.max(source.width, source.height));return {resizeWidth: Math.max(1, Math.round(source.width * scale)),resizeHeight: Math.max(1, Math.round(source.height * scale)),@@ -476,6 +479,31 @@ async function encodeThumbnailJpeg(bitmap: ImageBitmap): Promise<string> {return canvas.toDataURL("image/jpeg", 0.8);}+/**+ * A JPEG data URL of the image with its longest side at most `maxSize` pixels,+ * decoded at that size rather than at full resolution. Throws when the header+ * gives no dimensions or the browser cannot decode the image.+ */+export async function generateImageThumbnail(+ file: File,+ maxSize: number,+): Promise<string> {+ const source = await readImageDimensions(file);+ // Without a header ratio a width-only request would let an extreme portrait+ // ask for a maxSize x tens-of-millions bitmap.+ if (!source) throw new Error("image dimensions unavailable");+ const bitmap = await createImageBitmap(file, {+ ...thumbnailResizeOptions(source, maxSize),+ resizeQuality: "high",+ imageOrientation: "from-image",+ });+ try {+ return await encodeThumbnailJpeg(bitmap);+ } finally {+ bitmap.close();+ }+}+/*** Generate thumbnail for any file type - always returns a thumbnail (placeholder if needed)*/@@ -492,21 +520,7 @@ export async function generateThumbnailForFile(file: File): Promise<string> {// without intrinsic size, exotic codecs) falls back to the data URL.if (file.type.startsWith("image/")) {try {- const source = await readImageDimensions(file);- // Without a header ratio a width-only request would let an extreme- // portrait ask for a 320 x tens-of-millions bitmap, so unknown sizes take- // the data URL path below instead of decoding.- if (!source) throw new Error("image dimensions unavailable");- const bitmap = await createImageBitmap(file, {- ...thumbnailResizeOptions(source),- resizeQuality: "high",- imageOrientation: "from-image",- });- try {- return await encodeThumbnailJpeg(bitmap);- } finally {- bitmap.close();- }+ return await generateImageThumbnail(file, IMAGE_THUMBNAIL_MAX_SIZE);} catch {return new Promise((resolve, reject) => {const reader = new FileReader();