Skip to content

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

feat(text-editor): Acrobat-style object editing (Backspace delete, drag-select, text box resize, shapes, Shift-resize) (#8325)

kmlaktse1907d78439d
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 8e091964e4..8bc6a8e4fa 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7303,7 +7303,7 @@ deleteDesc = "Remove selected"
duplicateDesc = "Duplicate selected"
groupDesc = "Group selected runs into one paragraph"
heading = "Editing"
-marqueeDesc = "Marquee multi-select"
+marqueeDesc = "Drag on empty space to select several objects (Shift adds)"
moveDesc = "Move text run"
selectAllDesc = "Select all"
shiftClickDesc = "Add / remove a run from selection"
@@ -7330,19 +7330,21 @@ heightHint = "A text box's height follows its type size and line count."
image = "Image"
images = "Images"
manyImages = "{{count}} images"
+manyShapes = "{{count}} shapes"
manyText = "Text · {{count}} boxes"
mixed = "{{count}} objects"
multiGeometry = "Select a single object to edit its position and size."
nothingSelected = "Nothing selected"
-nothingSelectedHint = "Click any text or image on the page to edit it here."
+nothingSelectedHint = "Click any text, image or shape on the page to edit it here."
oneImage = "Image"
+oneShape = "Shape"
oneText = "Text"
pages = "Pages"
tabDocument = "Document"
tabSelected = "Selected"
textBoxes = "Text boxes"
width = "Width"
-widthHint = "A text box's width follows its content and wrapping."
+widthHint = "Text re-wraps to fit the width."
x = "X"
y = "Y"
@@ -7401,6 +7403,9 @@ find = "Find in document"
findTooltip = "Find ({{shortcut}})"
view = "View"
+[pdfTextEditor.shape]
+groupedTitle = "Part of a group in this PDF: it can be deleted but not moved."
+
[pdfTextEditor.sidebar]
addImage = "Add image"
addText = "Add text"
@@ -7459,7 +7464,7 @@ caseUpper = "UPPERCASE"
changeCase = "Change case"
changeCaseTooltip = "Change case (text runs only)"
delete = "Delete selected"
-deleteTooltip = "Delete (Del)"
+deleteTooltip = "Delete (Del or Backspace)"
distributeHorizontally = "Distribute horizontally"
distributeLabel = "Distribute · needs 3+ objects"
distributeVertically = "Distribute vertically"
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
index 4dc3cefcec..b1de292e7b 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
@@ -4,16 +4,12 @@ import path from "path";
import type { EditorTestWindow } from "@app/tests/stubbed/editorTestTypes";
/**
- * Direct manipulation: grab a box's frame to move it.
+ * Direct manipulation: grab a box's frame to move it, or its right edge to
+ * re-wrap it to a new width.
*
- * The gesture used to require Ctrl, which nothing on the page advertised - the
- * sidebar carried a permanent instruction card instead. Ctrl still works, but
- * the frame is now the discoverable path.
- *
- * There is deliberately no drag-to-resize: re-wrapping runs through
- * ReflowWrapCommand, whose x-gap word grouping splits inside words on runs
- * with individually positioned glyphs. The last test here pins that down so
- * the handle is not reintroduced before the grouping is fixed.
+ * The move gesture used to require Ctrl, which nothing on the page advertised -
+ * the sidebar carried a permanent instruction card instead. Ctrl still works,
+ * but the frame is now the discoverable path.
*/
const SAMPLE = path.join(
import.meta.dirname,
@@ -56,6 +52,16 @@ async function shapeOf(page: Page, src: string): Promise<Shape> {
return out;
}
+async function textOf(page: Page, needle: string): Promise<string> {
+ return page.evaluate(
+ (n: string) =>
+ (window as unknown as EditorTestWindow).__editor_store.doc
+ .page(0)
+ .runs.find((r) => new RegExp(n).test(r.text))?.text ?? "",
+ needle,
+ );
+}
+
async function boxOf(page: Page, src: string) {
const id = await page.evaluate((needle: string) => {
const run = (window as unknown as EditorTestWindow).__editor_store.doc
@@ -128,20 +134,30 @@ test.describe("PDF text editor - edge gestures", () => {
expect(Math.abs(after.x - before.x)).toBeGreaterThan(5);
});
- test("a frame drag never rewrites the run's text", async ({ page }) => {
+ test("a left-frame drag never rewrites the run's text", async ({ page }) => {
+ await open(page);
+ const before = await textOf(page, "Open Source");
+ const box = await boxOf(page, "Open Source");
+
+ await page.mouse.move(box.x + 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 40, box.y + box.height / 2, { steps: 10 });
+ await page.mouse.up();
+ await page.waitForTimeout(600);
+
+ expect(await textOf(page, "Open Source")).toBe(before);
+ });
+
+ // A letter-spaced heading is drawn one glyph per object, which the reflow
+ // used to read as one word per glyph and wrap into one character per line.
+ test("a right-edge drag re-wraps between words, never inside them", async ({
+ page,
+ }) => {
await open(page);
- const textOf = (needle: string) =>
- page.evaluate(
- (n: string) =>
- (window as unknown as EditorTestWindow).__editor_store.doc
- .page(0)
- .runs.find((r) => new RegExp(n).test(r.text))?.text ?? "",
- needle,
- );
- const before = await textOf("Open Source");
+ const words = (text: string) => text.split(/\s+/).filter(Boolean);
+ const before = await textOf(page, "Open Source");
const box = await boxOf(page, "Open Source");
- // Straight at the right-hand edge - where a resize handle would have been.
await page.mouse.move(box.x + box.width - 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width * 0.5, box.y + box.height / 2, {
@@ -150,9 +166,9 @@ test.describe("PDF text editor - edge gestures", () => {
await page.mouse.up();
await page.waitForTimeout(600);
- // Moving must never reflow. A resize here used to shred the run into
- // one character per line.
- expect(await textOf("Open Source")).toBe(before);
+ const after = await textOf(page, "Open");
+ expect(after).toContain("\n");
+ expect(words(after)).toEqual(words(before));
});
test("the insert verbs live in the toolbar, not the panel", async ({
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-shapes.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
new file mode 100644
index 0000000000..97e5e2b7f6
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
@@ -0,0 +1,245 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "path";
+
+/**
+ * Vector shapes: what a delete or move leaves in the SAVED file, not just on
+ * screen. PDFium writes back a form XObject child's removal but not its new
+ * paint or position, so shapes inside a form are deleted at save time and are
+ * not movable; the sample keeps most of its shapes in one such form.
+ */
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../../public/samples/Sample.pdf",
+);
+
+interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+interface ShapeInfo {
+ id: string;
+ grouped: boolean;
+ bounds: Rect;
+}
+
+interface ShapeWindow {
+ __editor_store: {
+ doc: {
+ page(i: number): {
+ shapes: { id: string; containerPtr: number; bounds: Rect }[];
+ };
+ };
+ selection: { selectShape(id: string): void };
+ };
+}
+
+type PdfFile = string | { name: string; mimeType: string; buffer: Buffer };
+
+async function openPdf(page: Page, file: PdfFile): Promise<void> {
+ await page
+ .locator('[data-testid="pdf-editor-file-input"]')
+ .setInputFiles(file);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ await page.waitForTimeout(1500);
+}
+
+async function openSample(page: Page): Promise<void> {
+ await page.route("**/encode-charcodes", (route) => route.abort());
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openPdf(page, SAMPLE);
+}
+
+async function saveAndReopen(page: Page): Promise<void> {
+ const download = page.waitForEvent("download");
+ await page.getByTestId("pdf-editor-download").click();
+ const stream = await (await download).createReadStream();
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) chunks.push(chunk as Buffer);
+ await openPdf(page, {
+ name: "round-trip.pdf",
+ mimeType: "application/pdf",
+ buffer: Buffer.concat(chunks),
+ });
+}
+
+function shapes(page: Page): Promise<ShapeInfo[]> {
+ return page.evaluate(() =>
+ (window as unknown as ShapeWindow).__editor_store.doc
+ .page(0)
+ .shapes.map((s) => ({
+ id: s.id,
+ grouped: s.containerPtr !== 0,
+ bounds: { ...s.bounds },
+ })),
+ );
+}
+
+/** Ids change across a reopen, so a shape is matched by where it is drawn. */
+function drawnAt(list: ShapeInfo[], r: Rect, dx = 0): boolean {
+ return list.some(
+ (s) =>
+ Math.abs(s.bounds.x - (r.x + dx)) < 0.6 &&
+ Math.abs(s.bounds.y - r.y) < 0.6 &&
+ Math.abs(s.bounds.width - r.width) < 0.6 &&
+ Math.abs(s.bounds.height - r.height) < 0.6,
+ );
+}
+
+/** True when no other shape is drawn at the same place, so `drawnAt` is unambiguous. */
+function isUnique(list: ShapeInfo[], shape: ShapeInfo): boolean {
+ return list.filter((s) => drawnAt([s], shape.bounds)).length === 1;
+}
+
+async function deleteShape(page: Page, id: string): Promise<void> {
+ await page.evaluate(
+ (shapeId) =>
+ (window as unknown as ShapeWindow).__editor_store.selection.selectShape(
+ shapeId,
+ ),
+ id,
+ );
+ await page.keyboard.press("Backspace");
+ await page.waitForTimeout(500);
+}
+
+/** A point on the shape's overlay that nothing else covers. */
+async function grabPoint(
+ page: Page,
+ id: string,
+): Promise<{ x: number; y: number } | null> {
+ return page.evaluate((shapeId) => {
+ const el = document.querySelector(
+ `[data-testid="pdf-editor-shape-${shapeId}"]`,
+ );
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ for (let fx = 0.05; fx < 1; fx += 0.15) {
+ for (let fy = 0.05; fy < 1; fy += 0.15) {
+ const x = r.left + r.width * fx;
+ const y = r.top + r.height * fy;
+ if (document.elementFromPoint(x, y) === el) return { x, y };
+ }
+ }
+ return null;
+ }, id);
+}
+
+async function dragBy(
+ page: Page,
+ from: { x: number; y: number },
+ dx: number,
+): Promise<void> {
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(from.x + dx, from.y, { steps: 8 });
+ await page.mouse.up();
+ await page.waitForTimeout(500);
+}
+
+async function largestGrouped(page: Page): Promise<ShapeInfo> {
+ const all = await shapes(page);
+ const grouped = all.filter((s) => s.grouped && isUnique(all, s));
+ expect(
+ grouped.length,
+ "the sample keeps shapes inside a form",
+ ).toBeGreaterThan(0);
+ return grouped.sort(
+ (a, b) =>
+ b.bounds.width * b.bounds.height - a.bounds.width * a.bounds.height,
+ )[0];
+}
+
+async function grabbable(
+ page: Page,
+ grouped: boolean,
+): Promise<{ shape: ShapeInfo; at: { x: number; y: number } }> {
+ const all = await shapes(page);
+ for (const shape of all) {
+ if (shape.grouped !== grouped || !isUnique(all, shape)) continue;
+ const at = await grabPoint(page, shape.id);
+ if (at) return { shape, at };
+ }
+ throw new Error(`no uncovered ${grouped ? "grouped" : "page"} shape`);
+}
+
+test.describe("PDF text editor - vector shapes survive save", () => {
+ test("a deleted shape inside a form is gone from the saved file", async ({
+ page,
+ }) => {
+ await openSample(page);
+ const target = await largestGrouped(page);
+ await deleteShape(page, target.id);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(false);
+
+ await saveAndReopen(page);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(false);
+ });
+
+ test("an undone delete inside a form keeps the shape in the saved file", async ({
+ page,
+ }) => {
+ await openSample(page);
+ const target = await largestGrouped(page);
+ await deleteShape(page, target.id);
+ await page.keyboard.press("ControlOrMeta+z");
+ await page.waitForTimeout(500);
+
+ await saveAndReopen(page);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
+ });
+
+ test("undoing a delete after the save that removed it brings the shape back", async ({
+ page,
+ }) => {
+ await openSample(page);
+ const target = await largestGrouped(page);
+ await deleteShape(page, target.id);
+ const download = page.waitForEvent("download");
+ await page.getByTestId("pdf-editor-download").click();
+ await download;
+ await page.keyboard.press("ControlOrMeta+z");
+ await page.waitForTimeout(500);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
+
+ await saveAndReopen(page);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
+ });
+
+ test("a shape inside a form does not move", async ({ page }) => {
+ await openSample(page);
+ const { shape, at } = await grabbable(page, true);
+ await dragBy(page, at, 45);
+ expect(drawnAt(await shapes(page), shape.bounds)).toBe(true);
+ });
+
+ test("a page-level shape's move and delete are in the saved file", async ({
+ page,
+ }) => {
+ await openSample(page);
+ const { shape: moved, at } = await grabbable(page, false);
+ await dragBy(page, at, 45);
+ const after = (await shapes(page)).find((s) => s.id === moved.id);
+ const dx = (after?.bounds.x ?? moved.bounds.x) - moved.bounds.x;
+ expect(Math.abs(dx)).toBeGreaterThan(5);
+ const current = await shapes(page);
+ const removed = current.find(
+ (s) => !s.grouped && s.id !== moved.id && isUnique(current, s),
+ );
+ expect(removed, "the sample has a second page-level shape").toBeDefined();
+ await deleteShape(page, removed!.id);
+
+ await saveAndReopen(page);
+ const reopened = await shapes(page);
+ expect(drawnAt(reopened, moved.bounds, dx)).toBe(true);
+ expect(drawnAt(reopened, removed!.bounds)).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts
index 6dcd28fcb9..6d111274b4 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-vis-selection.spec.ts
@@ -401,7 +401,7 @@ test.describe("PDF text editor - selection affordances, visually", () => {
await page.keyboard.up("Control");
});
- // Breaks if collectRunsInRect works in the wrong coordinate space (page vs
+ // Breaks if collectIdsInRect works in the wrong coordinate space (page vs
// client), or intersects against the wrong box: runs whose glyphs are
// nowhere near the drag would come back selected.
test("the marquee selects exactly the runs whose glyph ink it encloses", async ({
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
index 79b864087d..b516208b23 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx
@@ -350,7 +350,9 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const hasSelection = useCallback(() => {
const s = store.selection.value;
- return s.runIds.length > 0 || s.imageIds.length > 0;
+ return (
+ s.runIds.length > 0 || s.imageIds.length > 0 || s.shapeIds.length > 0
+ );
}, [store]);
// Paste: create a fresh InsertTextCommand on the currently-visible page,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/wordGrouping.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/wordGrouping.test.ts
new file mode 100644
index 0000000000..f34c4be681
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/wordGrouping.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+import {
+ endsWithSpace,
+ groupWords,
+ type WordLeaf,
+} from "@app/tools/pdfTextEditor/util/wordGrouping";
+
+const FONT_SIZE = 20;
+const GLYPH_WIDTH = 10;
+
+/** Lay `text` out one object per character, `gap` points between glyphs. */
+function perGlyph(
+ text: string,
+ gap: number,
+ wordGap: number,
+ baseline = 100,
+): WordLeaf[] {
+ const leaves: WordLeaf[] = [];
+ let x = 0;
+ for (const ch of text) {
+ if (ch === " " && wordGap >= 0) {
+ x += wordGap - gap;
+ continue;
+ }
+ leaves.push({ text: ch, x, right: x + GLYPH_WIDTH, baseline });
+ x += GLYPH_WIDTH + gap;
+ }
+ return leaves;
+}
+
+const wordTexts = (leaves: WordLeaf[]) =>
+ groupWords(leaves, FONT_SIZE).map((w) =>
+ w.glyphs.map((g) => g.text).join(""),
+ );
+
+describe("groupWords", () => {
+ it("keeps a letter-spaced heading's words whole", () => {
+ // Tracking of 0.4em is wider than the fixed word-gap threshold, which is
+ // what used to turn every glyph into its own word.
+ const tracking = FONT_SIZE * 0.4;
+ const leaves = perGlyph(
+ "Open Source",
+ tracking,
+ tracking + FONT_SIZE * 0.3,
+ );
+ expect(wordTexts(leaves)).toEqual(["Open", "Source"]);
+ });
+
+ it("splits a letter-spaced heading at a real space glyph", () => {
+ const tracking = FONT_SIZE * 0.4;
+ const leaves = perGlyph("Open Source", tracking, -1);
+ const words = groupWords(leaves, FONT_SIZE);
+ expect(words.map((w) => w.glyphs.map((g) => g.text).join(""))).toEqual([
+ "Open ",
+ "Source",
+ ]);
+ expect(endsWithSpace(words[0])).toBe(true);
+ expect(endsWithSpace(words[1])).toBe(false);
+ });
+
+ it("splits untracked per-glyph text at word gaps", () => {
+ const leaves = perGlyph("carry out various", 0, FONT_SIZE * 0.25);
+ expect(wordTexts(leaves)).toEqual(["carry", "out", "various"]);
+ });
+
+ it("splits a short tracked line at its word gap", () => {
+ // Two gap samples, 8pt tracking and a 14pt word gap: an upper median
+ // would take 14 as the tracking and merge "I" into "am".
+ const leaves = perGlyph("I am", 8, 14);
+ expect(wordTexts(leaves)).toEqual(["I", "am"]);
+ });
+
+ it("keeps tightly kerned glyphs together", () => {
+ const leaves = perGlyph("AVATAR", -1.5, FONT_SIZE * 0.25);
+ expect(wordTexts(leaves)).toEqual(["AVATAR"]);
+ });
+
+ it("treats word-sized objects separated by spaces as words", () => {
+ const leaves: WordLeaf[] = [
+ { text: "Hello", x: 0, right: 50, baseline: 100 },
+ { text: "world", x: 55, right: 105, baseline: 100 },
+ ];
+ expect(wordTexts(leaves)).toEqual(["Hello", "world"]);
+ });
+
+ it("splits a word that continues onto the next line", () => {
+ const leaves = [
+ ...perGlyph("ab", 0, FONT_SIZE * 0.25, 100),
+ ...perGlyph("cd", 0, FONT_SIZE * 0.25, 76),
+ ];
+ expect(wordTexts(leaves)).toEqual(["ab", "cd"]);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
new file mode 100644
index 0000000000..c605db06f3
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
@@ -0,0 +1,160 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@app/tools/pdfTextEditor/model/Page";
+import type { ShapeObject } from "@app/tools/pdfTextEditor/model/ShapeObject";
+import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+
+interface PageInsertModule {
+ FPDFPage_InsertObjectAtIndex?: (
+ page: number,
+ obj: number,
+ index: number,
+ ) => boolean;
+}
+
+interface DrawMode {
+ fillMode: number;
+ stroke: boolean;
+}
+
+const IDENTITY = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+
+/**
+ * Remove a vector shape. A shape on the page leaves the object list at once.
+ * One inside a form XObject is hidden and queued in `pendingFormRemovals` for
+ * the save to remove: PDFium writes back a form child's removal but not its
+ * paint, and has no call to put a removed child back, so removing it here
+ * would make the delete impossible to undo.
+ */
+export class DeleteShapeCommand implements Command {
+ readonly type = "delete-shape";
+ private readonly pageIndex: number;
+ private readonly shapeId: string;
+ private removed: ShapeObject | null = null;
+ /** Position among the shapes and in the page's object list, for revert. */
+ private shapeIndex = -1;
+ private objectIndex = -1;
+ /** Paint a hidden form child had, for revert. */
+ private hiddenDrawMode: DrawMode | null = null;
+
+ constructor(opts: { pageIndex: number; shapeId: string }) {
+ this.pageIndex = opts.pageIndex;
+ this.shapeId = opts.shapeId;
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const shape = page.findShape(this.shapeId);
+ if (!shape || !shape.pdfiumObjPtr) return;
+ const m = doc.module;
+ this.shapeIndex = page.shapes.indexOf(shape);
+ if (shape.containerPtr) {
+ const drawMode = readDrawMode(m, shape.pdfiumObjPtr);
+ if (!drawMode) return;
+ if (!m.FPDFPath_SetDrawMode(shape.pdfiumObjPtr, 0, false)) return;
+ this.hiddenDrawMode = drawMode;
+ page.pendingFormRemovals.set(shape.pdfiumObjPtr, shape.containerPtr);
+ } else {
+ this.objectIndex = indexOnPage(doc, page.pagePtr, shape.pdfiumObjPtr);
+ if (!m.FPDFPage_RemoveObject(page.pagePtr, shape.pdfiumObjPtr)) return;
+ }
+ this.removed = shape;
+ page.setShapes(page.shapes.filter((s) => s !== shape));
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ const shape = this.removed;
+ if (!shape) return;
+ const page = doc.page(this.pageIndex);
+ const m = doc.module;
+ if (this.hiddenDrawMode) {
+ m.FPDFPath_SetDrawMode(
+ shape.pdfiumObjPtr,
+ this.hiddenDrawMode.fillMode,
+ this.hiddenDrawMode.stroke,
+ );
+ this.hiddenDrawMode = null;
+ if (!page.pendingFormRemovals.delete(shape.pdfiumObjPtr)) {
+ restoreOntoPage(doc, page, shape);
+ }
+ } else {
+ insertOnPage(doc, page, shape.pdfiumObjPtr, this.objectIndex);
+ }
+ const shapes = [...page.shapes];
+ shapes.splice(
+ this.shapeIndex >= 0 ? this.shapeIndex : shapes.length,
+ 0,
+ shape,
+ );
+ page.setShapes(shapes);
+ this.removed = null;
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+}
+
+/**
+ * A save has already removed this shape from its form, and a form child cannot
+ * be re-added, so it returns as a page object just below that form, mapped to
+ * the same place on the page.
+ */
+function restoreOntoPage(
+ doc: EditorDocument,
+ page: Page,
+ shape: ShapeObject,
+): void {
+ const t = shape.containerTransform;
+ transformObject(doc.module, shape.pdfiumObjPtr, t.a, t.b, t.c, t.d, t.e, t.f);
+ const formIndex = indexOnPage(doc, page.pagePtr, shape.topLevelContainerPtr);
+ insertOnPage(doc, page, shape.pdfiumObjPtr, formIndex);
+ shape.containerPtr = 0;
+ shape.topLevelContainerPtr = 0;
+ shape.containerTransform = { ...IDENTITY };
+}
+
+function insertOnPage(
+ doc: EditorDocument,
+ page: Page,
+ objPtr: number,
+ index: number,
+): void {
+ const m = doc.module;
+ const inserted =
+ index >= 0 &&
+ (m as unknown as PageInsertModule).FPDFPage_InsertObjectAtIndex?.(
+ page.pagePtr,
+ objPtr,
+ index,
+ );
+ if (!inserted) m.FPDFPage_InsertObject(page.pagePtr, objPtr);
+}
+
+function readDrawMode(m: WrappedPdfiumModule, objPtr: number): DrawMode | null {
+ const fillModePtr = m.pdfium.wasmExports.malloc(4);
+ const strokePtr = m.pdfium.wasmExports.malloc(4);
+ try {
+ if (!m.FPDFPath_GetDrawMode(objPtr, fillModePtr, strokePtr)) return null;
+ return {
+ fillMode: m.pdfium.getValue(fillModePtr, "i32"),
+ stroke: m.pdfium.getValue(strokePtr, "i32") !== 0,
+ };
+ } finally {
+ m.pdfium.wasmExports.free(fillModePtr);
+ m.pdfium.wasmExports.free(strokePtr);
+ }
+}
+
+function indexOnPage(
+ doc: EditorDocument,
+ pagePtr: number,
+ objPtr: number,
+): number {
+ const total = doc.module.FPDFPage_CountObjects(pagePtr);
+ for (let i = 0; i < total; i++) {
+ if (doc.module.FPDFPage_GetObject(pagePtr, i) === objPtr) return i;
+ }
+ return -1;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts
new file mode 100644
index 0000000000..bb06c33501
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts
@@ -0,0 +1,51 @@
+import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+
+/** Translate a vector shape by (dx, dy) in PDF page-space points. */
+export class MoveShapeCommand implements Command {
+ readonly type = "move-shape";
+ private readonly pageIndex: number;
+ private readonly shapeId: string;
+ private readonly dx: number;
+ private readonly dy: number;
+ private applied = false;
+
+ constructor(opts: {
+ pageIndex: number;
+ shapeId: string;
+ dx: number;
+ dy: number;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.shapeId = opts.shapeId;
+ this.dx = opts.dx;
+ this.dy = opts.dy;
+ }
+
+ apply(doc: EditorDocument): void {
+ this.shift(doc, this.dx, this.dy);
+ this.applied = true;
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.applied) return;
+ this.shift(doc, -this.dx, -this.dy);
+ this.applied = false;
+ }
+
+ private shift(doc: EditorDocument, dx: number, dy: number): void {
+ const page = doc.page(this.pageIndex);
+ const shape = page.findShape(this.shapeId);
+ // A form child's new position renders but is not written back on save.
+ if (!shape || !shape.pdfiumObjPtr || shape.containerPtr) return;
+ transformObject(doc.module, shape.pdfiumObjPtr, 1, 0, 0, 1, dx, dy);
+ shape.bounds = {
+ ...shape.bounds,
+ x: shape.bounds.x + dx,
+ y: shape.bounds.y + dy,
+ };
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
index e63f8a52c9..b2cc639239 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
@@ -9,6 +9,11 @@ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { readUtf16 } from "@app/services/pdfiumService";
import { rotationFromMatrix } from "@app/tools/pdfTextEditor/commands/editTextHelpers";
import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+import {
+ endsWithSpace,
+ groupWords,
+ type Word as GenericWord,
+} from "@app/tools/pdfTextEditor/util/wordGrouping";
/** Reflow a text run's EXISTING glyph objects to fit within `maxWidthPt`. */
@@ -21,12 +26,14 @@ interface Leaf {
baseline: number;
}
-interface Word {
- glyphs: Leaf[];
- x: number;
- right: number;
- baseline: number;
-}
+type Word = GenericWord<Leaf>;
+
+/**
+ * Narrowest wrap width, in font sizes. The text overlay draws no box narrower
+ * than this, so a narrower explicit width would wrap the text inside a box
+ * that does not match it.
+ */
+export const MIN_WRAP_WIDTH_EM = 4;
interface RunSnapshot {
text: string;
@@ -46,6 +53,7 @@ interface RunSnapshot {
mergedFromBounds: Array<{ x: number; right: number }>;
mergedFromCharStarts: number[];
pdfiumObjPtr: number;
+ wrapWidthPt: number | null;
}
export class ReflowWrapCommand implements Command {
@@ -53,15 +61,28 @@ export class ReflowWrapCommand implements Command {
private readonly pageIndex: number;
private readonly runId: string;
private readonly maxWidthPt: number;
+ private readonly explicit: boolean;
private applied = false;
/** Per-object translation applied, so revert can undo it exactly. */
private moves: Array<{ ptr: number; dx: number; dy: number }> = [];
private prev: RunSnapshot | null = null;
- constructor(opts: { pageIndex: number; runId: string; maxWidthPt: number }) {
+ /**
+ * `explicit` marks a width the user set directly (resize handle, width
+ * field): the paragraph re-lines even when nothing overflows, so widening
+ * rejoins lines an earlier wrap broke, and it is its own undo step rather
+ * than part of the typing burst.
+ */
+ constructor(opts: {
+ pageIndex: number;
+ runId: string;
+ maxWidthPt: number;
+ explicit?: boolean;
+ }) {
this.pageIndex = opts.pageIndex;
this.runId = opts.runId;
this.maxWidthPt = opts.maxWidthPt;
+ this.explicit = opts.explicit ?? false;
}
apply(doc: EditorDocument): void {
@@ -98,13 +119,17 @@ export class ReflowWrapCommand implements Command {
// loses its last word: "...carry out various" drops "various" onto a line
// of its own, on lines the user never touched.
const rawRightEdge = page.display.cropLeft + page.display.cropWidth;
+ const minWidth = fontSize * MIN_WRAP_WIDTH_EM;
+ const requested = this.explicit
+ ? Math.max(this.maxWidthPt, minWidth)
+ : this.maxWidthPt;
const maxWidth = Math.min(
- this.maxWidthPt,
- Math.max(fontSize * 4, rawRightEdge - startX),
+ requested,
+ Math.max(minWidth, rawRightEdge - startX),
);
// Reflow is only NEEDED when some line actually overflows the wrap width.
- {
+ if (!this.explicit) {
const rightByLine = new Map<number, number>();
for (const l of leaves) {
const key = Math.round(l.baseline / 2);
@@ -121,7 +146,7 @@ export class ReflowWrapCommand implements Command {
if (!overflows) return;
}
- const words = groupWords(leaves, fontSize * 0.18);
+ const words = groupWords(leaves, fontSize);
const spaceWidth = estimateSpaceWidth(words, fontSize);
// The gap that FOLLOWED this word in the document, when the next word was
// beside it on the same line. Justified text stretches its spaces line by
@@ -133,9 +158,13 @@ export class ReflowWrapCommand implements Command {
const gapAfter = (index: number): number => {
const a = words[index];
const b = words[index + 1];
- if (!a || !b) return spaceWidth;
- if (Math.abs(a.baseline - b.baseline) > 2) return spaceWidth;
+ // A trailing space glyph already separates it from whatever follows.
+ const carried = a ? endsWithSpace(a) : false;
+ if (!a || !b) return carried ? 0 : spaceWidth;
+ if (Math.abs(a.baseline - b.baseline) > 2)
+ return carried ? 0 : spaceWidth;
const gap = b.x - a.right;
+ if (carried) return Math.max(0, gap);
return gap > 0 ? gap : spaceWidth;
};
// Manual line breaks the user typed (Enter) live in run.text as "\n".
@@ -228,6 +257,7 @@ export class ReflowWrapCommand implements Command {
fontSize,
this.prev.text,
);
+ if (this.explicit) run.wrapWidthPt = maxWidth;
run.dirty = true;
page.markDirty();
page.markNeedsGenerate();
@@ -264,7 +294,8 @@ export class ReflowWrapCommand implements Command {
// Share the edit coalesce key for this run so the auto-reflow that fires on
// blur merges into the preceding typing burst's single undo step.
- coalesceKey(): string {
+ coalesceKey(): string | null {
+ if (this.explicit) return null;
return `edit-text:${this.pageIndex}:${this.runId}`;
}
@@ -315,34 +346,6 @@ function extractLeaves(
return leaves;
}
-/** Group consecutive same-baseline leaves into words. */
-function groupWords(leaves: Leaf[], gapThreshold: number): Word[] {
- const words: Word[] = [];
- let cur: Leaf[] = [];
- let prev: Leaf | null = null;
- const flush = () => {
- if (cur.length === 0) return;
- words.push({
- glyphs: cur,
- x: Math.min(...cur.map((g) => g.x)),
- right: Math.max(...cur.map((g) => g.right)),
- baseline: cur[0].baseline,
- });
- cur = [];
- };
- for (const g of leaves) {
- if (prev) {
- const sameLine = Math.abs(g.baseline - prev.baseline) <= 2;
- const gap = g.x - prev.right;
- if (!sameLine || gap > gapThreshold) flush();
- }
- cur.push(g);
- prev = g;
- }
- flush();
- return words;
-}
-
/** The non-whitespace char counts at which `text` has a hard "\n" break. */
function hardBreakNonWsCounts(
text: string,
@@ -369,6 +372,7 @@ function estimateSpaceWidth(words: Word[], fontSize: number): number {
for (let i = 1; i < words.length; i++) {
const a = words[i - 1];
const b = words[i];
+ if (endsWithSpace(a)) continue;
if (Math.abs(a.baseline - b.baseline) <= 2) {
const gap = b.x - a.right;
if (gap > 0) gaps.push(gap);
@@ -583,6 +587,7 @@ function snapshotRun(run: TextRun): RunSnapshot {
mergedFromBounds: run.mergedFromBounds.map((b) => ({ ...b })),
mergedFromCharStarts: [...run.mergedFromCharStarts],
pdfiumObjPtr: run.pdfiumObjPtr,
+ wrapWidthPt: run.wrapWidthPt,
};
}
@@ -603,6 +608,7 @@ function restoreRun(run: TextRun, prev: RunSnapshot): void {
run.mergedFromBounds = prev.mergedFromBounds.map((b) => ({ ...b }));
run.mergedFromCharStarts = [...prev.mergedFromCharStarts];
run.pdfiumObjPtr = prev.pdfiumObjPtr;
+ run.wrapWidthPt = prev.wrapWidthPt;
}
function cloneSlot(s: ParagraphLineSlot): ParagraphLineSlot {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 90306421d2..7f4492c921 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -51,7 +51,9 @@ export function EditorSidebar({
const controller = useToolbarController(store, state, selection);
const geometry = useSelectionGeometry(store, state, selection);
const hasSelection =
- selection.runIds.length > 0 || selection.imageIds.length > 0;
+ selection.runIds.length > 0 ||
+ selection.imageIds.length > 0 ||
+ selection.shapeIds.length > 0;
const [tab, setTab] = useState<SidebarTab>(initialTab);
// Picking something on the page is a request to see its properties, so the
@@ -151,7 +153,7 @@ function NothingSelected() {
<Text size="xs" c="dimmed" ta="center">
{t(
"pdfTextEditor.inspector.nothingSelectedHint",
- "Click any text or image on the page to edit it here.",
+ "Click any text, image or shape on the page to edit it here.",
)}
</Text>
</Stack>
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx
index 3bef5d01cf..94e0d06458 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx
@@ -226,6 +226,11 @@ export function EditorTopBar({
{hasSelection && (
<>
+ <ToolbarSeparator />
+ {/* Ahead of the formatting group: the band scrolls sideways
+ under macOS's hidden scrollbars, so anything past the edge
+ is invisible rather than visibly clipped. */}
+ <ObjectGroup controller={controller} />
<ToolbarSeparator />
{compact ? (
<Popover position="bottom-start" withinPortal shadow="md">
@@ -252,8 +257,6 @@ export function EditorTopBar({
) : (
<FormatGroup controller={controller} />
)}
- <ToolbarSeparator />
- <ObjectGroup controller={controller} />
</>
)}
</div>
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/HelpOverlay.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/HelpOverlay.tsx
index f4692f9305..5d7bc734ae 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/HelpOverlay.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/HelpOverlay.tsx
@@ -43,10 +43,10 @@ export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
),
},
{
- bindings: [mod("Drag", { shift: true })],
+ bindings: [{ code: "Drag" }, mod("Drag", { shift: true })],
description: t(
"pdfTextEditor.help.editing.marqueeDesc",
- "Marquee multi-select",
+ "Drag on empty space to select several objects (Shift adds)",
),
},
{
@@ -78,7 +78,7 @@ export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
),
},
{
- bindings: [{ code: "Delete" }],
+ bindings: [{ code: "Delete" }, { code: "Backspace" }],
description: t(
"pdfTextEditor.help.editing.deleteDesc",
"Remove selected",
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/ImageHandle.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/ImageHandle.tsx
index 8d9a169abf..ced0729984 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/ImageHandle.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/ImageHandle.tsx
@@ -30,6 +30,9 @@ export function ImageHandle({
}: ImageHandleProps) {
const [dragging, setDragging] = useState(false);
const [hovered, setHovered] = useState(false);
+ // Shift during a corner drag keeps the proportions, as in Acrobat. Read
+ // from every resize event, so pressing or releasing it mid-drag applies.
+ const [keepRatio, setKeepRatio] = useState(false);
// Map the image's raw-PDF AABB into display-PDF space (4 corners through the
// transform, then min/max), then to CSS px.
@@ -101,10 +104,13 @@ export function ImageHandle({
setDragging(true);
onSelect();
}}
- onResizeStart={() => {
+ lockAspectRatio={keepRatio}
+ onResizeStart={(e) => {
+ setKeepRatio(e.shiftKey);
if (locked) return;
onSelect();
}}
+ onResize={(e) => setKeepRatio(e.shiftKey)}
onDragStop={(_, data) => {
setDragging(false);
const next = cssToPdfBounds(data.x, data.y, width, height);
@@ -115,6 +121,7 @@ export function ImageHandle({
onTransformCommit(next);
}}
onResizeStop={(_e, _dir, ref, _delta, position) => {
+ setKeepRatio(false);
const next = cssToPdfBounds(
position.x,
position.y,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/MarqueeSelector.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/MarqueeSelector.tsx
index 1d07a76765..6c9a5b33f5 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/MarqueeSelector.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/MarqueeSelector.tsx
@@ -12,12 +12,32 @@ interface MarqueeRect {
height: number;
}
-// Ctrl+Shift+drag a rectangle on the page stack. Lets the user override
-// line/paragraph auto-grouping when it gets the structure wrong.
+// Pressing on these keeps their own gesture (edit, move, resize, guide drag),
+// so a plain drag only becomes a marquee when it starts on bare page or gutter.
+const OWN_GESTURE_SELECTOR = [
+ '[data-testid^="pdf-editor-run-"]',
+ '[data-testid^="pdf-editor-image-"]',
+ '[data-testid^="pdf-editor-shape-"]',
+ '[data-testid^="pdf-editor-ruler"]',
+ '[data-testid^="pdf-editor-guide-"]',
+ "button",
+ "input",
+ "textarea",
+ "[contenteditable='true']",
+].join(", ");
+
+/**
+ * Rectangle-select on the page stack, selecting every text run, image and
+ * shape it touches. A plain drag from bare page starts one, Shift extends the
+ * current selection, and Ctrl/Cmd+Shift starts one from anywhere, including
+ * over text, to override line/paragraph auto-grouping when it gets the
+ * structure wrong.
+ */
export function MarqueeSelector({ store }: MarqueeSelectorProps) {
const [rect, setRect] = useState<MarqueeRect | null>(null);
const startRef = useRef<{ x: number; y: number } | null>(null);
const liveRectRef = useRef<MarqueeRect | null>(null);
+ const additiveRef = useRef(false);
useEffect(() => {
function setLiveRect(next: MarqueeRect | null) {
@@ -25,12 +45,22 @@ export function MarqueeSelector({ store }: MarqueeSelectorProps) {
setRect(next);
}
function onPointerDown(e: PointerEvent) {
- if (!e.ctrlKey && !e.metaKey) return;
- if (!e.shiftKey) return;
+ if (e.button !== 0) return;
const target = e.target as HTMLElement | null;
if (!target?.closest('[data-testid="pdf-editor-pages"]')) return;
- e.preventDefault();
+ const forced = (e.ctrlKey || e.metaKey) && e.shiftKey;
+ if (forced) {
+ e.preventDefault();
+ } else {
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
+ if (store.getState().mode !== "select") return;
+ if (target.closest(OWN_GESTURE_SELECTOR)) return;
+ }
+ additiveRef.current = !forced && e.shiftKey;
startRef.current = { x: e.clientX, y: e.clientY };
+ // Without this, dragging across text runs paints a native text
+ // selection under the rectangle.
+ document.body.style.userSelect = "none";
setLiveRect({ left: e.clientX, top: e.clientY, width: 0, height: 0 });
}
function onPointerMove(e: PointerEvent) {
@@ -47,26 +77,39 @@ export function MarqueeSelector({ store }: MarqueeSelectorProps) {
const origin = startRef.current;
startRef.current = null;
setLiveRect(null);
- if (!origin || !r) return;
- if (r.width < 3 && r.height < 3) return;
- const hits = collectRunsInRect(r);
+ if (!origin) return;
+ document.body.style.userSelect = "";
+ if (!r || (r.width < 3 && r.height < 3)) return;
+ const runIds = collectIdsInRect(r, "pdf-editor-run-");
+ const imageIds = collectIdsInRect(r, "pdf-editor-image-");
+ const shapeIds = collectIdsInRect(r, "pdf-editor-shape-");
// A rectangle that caught nothing leaves the selection alone rather than
// silently wiping it.
- if (hits.length === 0) return;
- // Seam for an extending rectangle-select. No modifier is bound to it:
- // the marquee already claims Ctrl/Cmd+Shift and both Ctrl-click and
- // Shift-click already mean extend, so the gesture needs a UX decision.
- const additive = false;
- store.selection.selectMany(hits, additive);
+ if (runIds.length + imageIds.length + shapeIds.length === 0) return;
+ store.selection.selectMany(
+ runIds,
+ additiveRef.current,
+ imageIds,
+ shapeIds,
+ );
+ }
+ function onPointerCancel() {
+ if (!startRef.current) return;
+ startRef.current = null;
+ setLiveRect(null);
+ document.body.style.userSelect = "";
}
// Pointer events cover mouse, pen and touch with one code path.
window.addEventListener("pointerdown", onPointerDown);
window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerup", onPointerUp);
+ window.addEventListener("pointercancel", onPointerCancel);
return () => {
window.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("pointermove", onPointerMove);
window.removeEventListener("pointerup", onPointerUp);
+ window.removeEventListener("pointercancel", onPointerCancel);
+ document.body.style.userSelect = "";
};
}, [store]);
@@ -89,15 +132,17 @@ export function MarqueeSelector({ store }: MarqueeSelectorProps) {
);
}
-function collectRunsInRect(rect: MarqueeRect): string[] {
+function collectIdsInRect(rect: MarqueeRect, testIdPrefix: string): string[] {
+ const pages = document.querySelector('[data-testid="pdf-editor-pages"]');
+ if (!pages) return [];
const right = rect.left + rect.width;
const bottom = rect.top + rect.height;
const ids: string[] = [];
- const runs = document.querySelectorAll<HTMLElement>(
- '[data-testid^="pdf-editor-run-"]',
+ const elements = pages.querySelectorAll<HTMLElement>(
+ `[data-testid^="${testIdPrefix}"]`,
);
- for (const el of runs) {
- const id = el.dataset.testid?.replace(/^pdf-editor-run-/, "");
+ for (const el of elements) {
+ const id = el.dataset.testid?.slice(testIdPrefix.length);
if (!id) continue;
const b = el.getBoundingClientRect();
const intersects =
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx
index 381e034366..f79e6312b3 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx
@@ -67,29 +67,33 @@ export function MobileActionBar({
onClick={() => store.setMobileSheet("details")}
data-testid="pdf-editor-mobile-details"
/>
- <Menu shadow="md" position="top" withinPortal closeOnItemClick>
- <Menu.Target>
+ {(controller.hasRunSelection || controller.hasImageSelection) && (
+ <>
+ <Menu shadow="md" position="top" withinPortal closeOnItemClick>
+ <Menu.Target>
+ <BarButton
+ icon="layers"
+ label={t("pdfTextEditor.toolbar.arrange", "Arrange")}
+ data-testid="pdf-editor-arrange-menu"
+ />
+ </Menu.Target>
+ <Menu.Dropdown>
+ <ArrangeMenuItems controller={controller} />
+ </Menu.Dropdown>
+ </Menu>
<BarButton
- icon="layers"
- label={t("pdfTextEditor.toolbar.arrange", "Arrange")}
- data-testid="pdf-editor-arrange-menu"
+ icon={controller.selectionAllLocked ? "lock" : "lock-open"}
+ label={
+ controller.selectionAllLocked
+ ? t("pdfTextEditor.mobile.unlock", "Unlock")
+ : t("pdfTextEditor.mobile.lock", "Lock")
+ }
+ pressed={controller.selectionAllLocked}
+ onClick={controller.onToggleLock}
+ data-testid="pdf-editor-toggle-lock"
/>
- </Menu.Target>
- <Menu.Dropdown>
- <ArrangeMenuItems controller={controller} />
- </Menu.Dropdown>
- </Menu>
- <BarButton
- icon={controller.selectionAllLocked ? "lock" : "lock-open"}
- label={
- controller.selectionAllLocked
- ? t("pdfTextEditor.mobile.unlock", "Unlock")
- : t("pdfTextEditor.mobile.lock", "Lock")
- }
- pressed={controller.selectionAllLocked}
- onClick={controller.onToggleLock}
- data-testid="pdf-editor-toggle-lock"
- />
+ </>
+ )}
<BarButton
icon="trash"
label={t("pdfTextEditor.mobile.delete", "Delete")}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
index 4cf6b03112..d0ddd3d6fe 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
@@ -25,7 +25,9 @@ export function MobileEditorSheets(props: Omit<SidebarProps, "initialTab">) {
const controller = useToolbarController(store, state, selection);
const sheet = state.mobileSheet;
const hasSelection =
- selection.runIds.length > 0 || selection.imageIds.length > 0;
+ selection.runIds.length > 0 ||
+ selection.imageIds.length > 0 ||
+ selection.shapeIds.length > 0;
useEffect(() => {
if (sheet === "style" && !controller.hasRunSelection) {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx
index 06fcc880cb..186a8cb601 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx
@@ -25,6 +25,7 @@ import { MarqueeSelector } from "@app/tools/pdfTextEditor/components/MarqueeSele
import { PageView } from "@app/tools/pdfTextEditor/components/PageView";
import { EditTextCommand } from "@app/tools/pdfTextEditor/commands/EditTextCommand";
import { ReflowWrapCommand } from "@app/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { MoveShapeCommand } from "@app/tools/pdfTextEditor/commands/MoveShapeCommand";
import { InsertTextCommand } from "@app/tools/pdfTextEditor/commands/InsertTextCommand";
import { MoveTextRunCommand } from "@app/tools/pdfTextEditor/commands/MoveTextRunCommand";
import { SetImageTransformCommand } from "@app/tools/pdfTextEditor/commands/SetImageTransformCommand";
@@ -340,6 +341,7 @@ export function PageStage() {
showRulers={state.showRulers}
selectedRunIds={selection.runIds}
selectedImageIds={selection.imageIds}
+ selectedShapeIds={selection.shapeIds}
highlightedRunId={highlightedRunId}
onSelectRun={(runId, shiftKey) => {
if (shiftKey) store.selection.toggle(runId);
@@ -348,6 +350,16 @@ export function PageStage() {
onSelectImage={(imageId) =>
store.selection.selectImage(imageId)
}
+ onSelectShape={(shapeId, extend) => {
+ if (extend) store.selection.toggleShape(shapeId);
+ else store.selection.selectShape(shapeId);
+ }}
+ onMoveShape={(pageIndex, shapeId, dx, dy) => {
+ store.dispatch(
+ new MoveShapeCommand({ pageIndex, shapeId, dx, dy }),
+ );
+ store.selection.selectShape(shapeId);
+ }}
onEditRun={(pageIndex, runId, nextText) => {
// contentEditable can fire several input events per
// keystroke burst.
@@ -369,6 +381,16 @@ export function PageStage() {
new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }),
);
}}
+ onResizeRun={(pageIndex, runId, widthPt) => {
+ store.dispatch(
+ new ReflowWrapCommand({
+ pageIndex,
+ runId,
+ maxWidthPt: widthPt,
+ explicit: true,
+ }),
+ );
+ }}
onPageClick={(pageIndex, pageX, pageY) => {
if (state.mode !== "addText") return;
const cmd = new InsertTextCommand({
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
index 7696bd2714..e24a3e169a 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
@@ -7,6 +7,7 @@ import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocume
import type { PageSnapshot } from "@app/tools/pdfTextEditor/types";
import { TextRunOverlay } from "@app/tools/pdfTextEditor/components/TextRunOverlay";
import { ImageHandle } from "@app/tools/pdfTextEditor/components/ImageHandle";
+import { ShapeHandle } from "@app/tools/pdfTextEditor/components/ShapeHandle";
import { AnnotationOutline } from "@app/tools/pdfTextEditor/components/AnnotationOutline";
import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
import { PageGuides } from "@app/tools/pdfTextEditor/components/PageRulers";
@@ -25,10 +26,19 @@ interface PageViewProps {
showRulers?: boolean;
selectedRunIds: string[];
selectedImageIds: string[];
+ selectedShapeIds: string[];
/** Run id currently highlighted by the find-bar (yellow). */
highlightedRunId?: string | null;
onSelectRun: (runId: string, shiftKey: boolean) => void;
onSelectImage: (imageId: string) => void;
+ onSelectShape: (shapeId: string, extend: boolean) => void;
+ /** Fires when a shape drag completes; dx/dy in raw PDF points. */
+ onMoveShape?: (
+ pageIndex: number,
+ shapeId: string,
+ dx: number,
+ dy: number,
+ ) => void;
onEditRun: (pageIndex: number, runId: string, nextText: string) => void;
/** Ctrl+drag committed; dx/dy in PDF points. */
onMoveRun?: (
@@ -39,6 +49,8 @@ interface PageViewProps {
) => void;
/** Wrap-mode reflow request; maxWidthPt in PDF points. */
onWrapRun?: (pageIndex: number, runId: string, maxWidthPt: number) => void;
+ /** Right-edge drag to a new box width; widthPt in PDF points. */
+ onResizeRun?: (pageIndex: number, runId: string, widthPt: number) => void;
/** Fires when the user clicks on a non-text area of the page. */
onPageClick?: (pageIndex: number, pageX: number, pageY: number) => void;
/** Fires when an image's drag OR resize completes. */
@@ -73,12 +85,16 @@ export function PageView({
showRulers,
selectedRunIds,
selectedImageIds,
+ selectedShapeIds,
highlightedRunId,
onSelectRun,
onSelectImage,
+ onSelectShape,
+ onMoveShape,
onEditRun,
onMoveRun,
onWrapRun,
+ onResizeRun,
onPageClick,
onTransformImage,
onFirstVisible,
@@ -330,6 +346,19 @@ export function PageView({
scale={cssScale}
/>
))}
+ {/* Before images and runs: anything drawn over a shape wins its clicks. */}
+ {page.shapes.map((shape) => (
+ <ShapeHandle
+ key={shape.id}
+ shape={shape}
+ pageHeight={page.height}
+ transform={transform}
+ scale={cssScale}
+ selected={selectedShapeIds.includes(shape.id)}
+ onSelect={(extend) => onSelectShape(shape.id, extend)}
+ onMove={(dx, dy) => onMoveShape?.(page.pageIndex, shape.id, dx, dy)}
+ />
+ ))}
{page.images.map((image) => (
<ImageHandle
key={image.id}
@@ -362,6 +391,11 @@ export function PageView({
onWrap={(maxWidthPt) =>
onWrapRun?.(page.pageIndex, run.id, maxWidthPt)
}
+ onResize={
+ onResizeRun
+ ? (widthPt) => onResizeRun(page.pageIndex, run.id, widthPt)
+ : undefined
+ }
/>
))}
{showRulers && (
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/ShapeHandle.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/ShapeHandle.tsx
new file mode 100644
index 0000000000..5d8ac59a7d
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/ShapeHandle.tsx
@@ -0,0 +1,159 @@
+import { useEffect, useRef, useState } from "react";
+import type React from "react";
+import { useTranslation } from "react-i18next";
+import type { ShapeObjectSnapshot } from "@app/tools/pdfTextEditor/types";
+import type { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
+
+interface ShapeHandleProps {
+ shape: ShapeObjectSnapshot;
+ pageHeight: number;
+ /** Raw-PDF -> display (CropBox/rotation) transform. */
+ transform: DisplayTransform;
+ scale: number;
+ selected: boolean;
+ onSelect: (extend: boolean) => void;
+ /** Fires when a drag completes. dx/dy are raw PDF points. */
+ onMove: (dx: number, dy: number) => void;
+}
+
+/** A hairline rule is a fraction of a pixel tall; this keeps it grabbable. */
+const MIN_HIT_PX = 8;
+/** Below this the press was a click, not a drag. */
+const DRAG_THRESHOLD_PX = 3;
+
+/** Click-to-select, drag-to-move affordance for a vector shape. */
+export function ShapeHandle({
+ shape,
+ pageHeight,
+ transform,
+ scale,
+ selected,
+ onSelect,
+ onMove,
+}: ShapeHandleProps) {
+ const { t } = useTranslation();
+ const [hovered, setHovered] = useState(false);
+ const [dragOffset, setDragOffset] = useState<{ x: number; y: number } | null>(
+ null,
+ );
+ const originRef = useRef<{ x: number; y: number } | null>(null);
+ // Detaches an in-flight drag's window listeners. A page re-read can unmount
+ // the handle mid-drag, and a listener left behind would move a stale shape.
+ const endDragRef = useRef<(() => void) | null>(null);
+
+ useEffect(() => () => endDragRef.current?.(), []);
+
+ const b = shape.bounds;
+ const corners = [
+ transform.apply(b.x, b.y),
+ transform.apply(b.x + b.width, b.y),
+ transform.apply(b.x, b.y + b.height),
+ transform.apply(b.x + b.width, b.y + b.height),
+ ];
+ const minX = Math.min(...corners.map((c) => c.x));
+ const maxX = Math.max(...corners.map((c) => c.x));
+ const minY = Math.min(...corners.map((c) => c.y));
+ const maxY = Math.max(...corners.map((c) => c.y));
+ const rawWidth = (maxX - minX) * scale;
+ const rawHeight = (maxY - minY) * scale;
+ const width = Math.max(MIN_HIT_PX, rawWidth);
+ const height = Math.max(MIN_HIT_PX, rawHeight);
+ const left = minX * scale - (width - rawWidth) / 2;
+ const top = (pageHeight - maxY) * scale - (height - rawHeight) / 2;
+
+ function onPointerDown(e: React.PointerEvent<HTMLDivElement>) {
+ if (e.button !== 0) return;
+ // One drag at a time: a second finger or pen must not restart it.
+ if (endDragRef.current) return;
+ // Ctrl/Cmd+Shift+drag is the marquee gesture - let it reach the stage.
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey) return;
+ // Otherwise the stage's "press on empty space clears" handler would drop
+ // the selection this press is about to make.
+ e.stopPropagation();
+ e.preventDefault();
+ if (e.shiftKey) {
+ onSelect(true);
+ return;
+ }
+ if (!shape.movable) {
+ onSelect(false);
+ return;
+ }
+ originRef.current = { x: e.clientX, y: e.clientY };
+ setDragOffset({ x: 0, y: 0 });
+ const pointerId = e.pointerId;
+ const onPointerMove = (ev: PointerEvent) => {
+ if (ev.pointerId !== pointerId) return;
+ const origin = originRef.current;
+ if (!origin) return;
+ setDragOffset({ x: ev.clientX - origin.x, y: ev.clientY - origin.y });
+ };
+ const endDrag = () => {
+ window.removeEventListener("pointermove", onPointerMove);
+ window.removeEventListener("pointerup", onPointerUp);
+ window.removeEventListener("pointercancel", onPointerCancel);
+ endDragRef.current = null;
+ originRef.current = null;
+ setDragOffset(null);
+ };
+ const onPointerCancel = (ev: PointerEvent) => {
+ if (ev.pointerId === pointerId) endDrag();
+ };
+ const onPointerUp = (ev: PointerEvent) => {
+ if (ev.pointerId !== pointerId) return;
+ const origin = originRef.current;
+ endDrag();
+ if (!origin) return;
+ const cssDx = ev.clientX - origin.x;
+ const cssDy = ev.clientY - origin.y;
+ if (Math.hypot(cssDx, cssDy) < DRAG_THRESHOLD_PX) {
+ onSelect(false);
+ return;
+ }
+ const v = transform.invertVector(cssDx / scale, -cssDy / scale);
+ onMove(v.x, v.y);
+ };
+ endDragRef.current = endDrag;
+ window.addEventListener("pointermove", onPointerMove);
+ window.addEventListener("pointerup", onPointerUp);
+ window.addEventListener("pointercancel", onPointerCancel);
+ }
+
+ const dragging = dragOffset !== null;
+ return (
+ <div
+ data-testid={`pdf-editor-shape-${shape.id}`}
+ title={
+ shape.movable
+ ? undefined
+ : t(
+ "pdfTextEditor.shape.groupedTitle",
+ "Part of a group in this PDF: it can be deleted but not moved.",
+ )
+ }
+ onPointerDown={onPointerDown}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ style={{
+ position: "absolute",
+ left,
+ top,
+ width,
+ height,
+ transform: dragOffset
+ ? `translate(${dragOffset.x}px, ${dragOffset.y}px)`
+ : undefined,
+ outline: selected
+ ? "1px solid var(--c-primary)"
+ : hovered || dragging
+ ? "1px dashed var(--c-border-strong)"
+ : "none",
+ background:
+ selected || dragging ? "var(--c-primary-subtle)" : "transparent",
+ opacity: selected || dragging ? 0.6 : 1,
+ cursor: !shape.movable ? "pointer" : dragging ? "grabbing" : "move",
+ pointerEvents: "auto",
+ }}
+ />
+ );
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
index d103ab62bc..a2e0e8c31c 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
@@ -41,6 +41,7 @@ import {
measureMaxLineWidth,
resetTextMetricsCache,
} from "@app/tools/pdfTextEditor/util/textMetrics";
+import { MIN_WRAP_WIDTH_EM } from "@app/tools/pdfTextEditor/commands/ReflowWrapCommand";
import "@app/tools/pdfTextEditor/components/TextRunOverlay.css";
const RENDER_MODE_INVISIBLE = 3;
@@ -311,20 +312,16 @@ interface TextRunOverlayProps {
// Fires on blur in Wrap mode when the edited content overflows the locked box
// width.
onWrap?: (maxWidthPt: number) => void;
+ /** Fires when the user drags the right edge to a new width, in PDF points. */
+ onResize?: (widthPt: number) => void;
}
/**
- * Which gesture the pointer is over: the frame, or the text interior.
- *
- * There is deliberately no resize zone. Re-wrapping to an arbitrary width goes
- * through ReflowWrapCommand, whose word grouping is x-gap based - on a run
- * whose glyphs are individually positioned (letter-spaced headings, button
- * labels) every glyph becomes its own "word" and the line breaker splits
- * inside words, shredding "Open Source" into one character per line. Until
- * that grouping is token-aware, a drag handle would make the corruption a
- * one-gesture accident.
+ * Which gesture the pointer is over: the frame, the right edge, or the text
+ * interior. The right edge re-wraps the run to a new width; the rest of the
+ * frame moves it.
*/
-type EdgeZone = "move" | null;
+type EdgeZone = "move" | "resize" | null;
/** Grab band around the box, in CSS px. Matches the visible ring's reach. */
const EDGE_PX = 7;
@@ -340,12 +337,14 @@ function edgeZoneAt(
el: HTMLElement,
clientX: number,
clientY: number,
+ canResize: boolean,
): EdgeZone {
const r = el.getBoundingClientRect();
const nearLeft = clientX - r.left <= EDGE_PX;
const nearRight = r.right - clientX <= EDGE_PX;
const nearTop = clientY - r.top <= EDGE_PX;
const nearBottom = r.bottom - clientY <= EDGE_PX;
+ if (canResize && nearRight && !nearTop && !nearBottom) return "resize";
if (nearTop || nearBottom || nearLeft || nearRight) return "move";
return null;
}
@@ -365,6 +364,7 @@ export function TextRunOverlay({
onEdit,
onMove,
onWrap,
+ onResize,
}: TextRunOverlayProps) {
const { t } = useTranslation();
// Subscribed, so toggling the preference re-renders every overlay.
@@ -411,6 +411,12 @@ export function TextRunOverlay({
// Which edge the pointer is over, so the cursor can advertise the gesture
// before the user commits to it. Null means the text interior.
const [edgeZone, setEdgeZone] = useState<EdgeZone>(null);
+ // Live box width while the right edge is being dragged, in CSS px.
+ const [resizeWidthPx, setResizeWidthPx] = useState<number | null>(null);
+ // Detaches an in-flight resize's window listeners, so a cancelled or
+ // unmounted resize can never commit a width on a later pointerup.
+ const endResizeRef = useRef<(() => void) | null>(null);
+ useEffect(() => () => endResizeRef.current?.(), []);
const originalBoundsWidthRef = useRef<number>(run.bounds.width);
// Whether this run was a real (multi-line) paragraph when it first mounted.
@@ -667,8 +673,8 @@ export function TextRunOverlay({
// fit the content.
const wrapMode = widthMode === "wrap";
const wrapLockWidth = Math.max(
- originalBoundsWidthRef.current * scale,
- fontSizePx * 4,
+ (run.wrapWidthPt ?? originalBoundsWidthRef.current) * scale,
+ fontSizePx * MIN_WRAP_WIDTH_EM,
);
// The mode the user picked, and nothing else. Forcing a paragraph to wrap in
// Grow made the two modes indistinguishable for body text and contradicted
@@ -724,7 +730,10 @@ export function TextRunOverlay({
// underneath it.
// Wrap holds its width and pushes overflow onto new lines; widening to the
// page edge instead is Grow's job, and doing both makes the modes identical.
- const width = wantWrap ? wrapWidth : exact ? exactWidth : flowWidth;
+ const userWidthPx = (run.wrapWidthPt ?? 0) * scale;
+ const width = wantWrap
+ ? wrapWidth
+ : Math.max(exact ? exactWidth : flowWidth, userWidthPx);
const height = exact ? exact.heightPx : flowHeight;
// An exact layout is never wrapped - its lines are the PDF's own. Only the
// plain-text fallback, where CSS flow genuinely owns the layout, may wrap.
@@ -752,6 +761,49 @@ export function TextRunOverlay({
// Which dictionary the browser should load. "auto" falls back to the
// page's own language, which is what the element would inherit anyway.
+ // The reflow lays text out along the page axis, so a turned run has no
+ // meaningful width to drag.
+ const canResize = !!onResize && !runRotation;
+ const minResizePx = fontSizePx * MIN_WRAP_WIDTH_EM;
+
+ function startResize(
+ originX: number,
+ pointerId: number,
+ commit: (widthPt: number) => void,
+ ) {
+ if (endResizeRef.current) return;
+ const startWidth = width;
+ setResizeWidthPx(startWidth);
+ const widthAt = (clientX: number) =>
+ Math.max(minResizePx, startWidth + clientX - originX);
+ const onPointerMove = (ev: PointerEvent) => {
+ if (ev.pointerId === pointerId) setResizeWidthPx(widthAt(ev.clientX));
+ };
+ const endResize = () => {
+ window.removeEventListener("pointermove", onPointerMove);
+ window.removeEventListener("pointerup", onPointerUp);
+ window.removeEventListener("pointercancel", onPointerCancel);
+ endResizeRef.current = null;
+ setResizeWidthPx(null);
+ };
+ const onPointerCancel = (ev: PointerEvent) => {
+ if (ev.pointerId === pointerId) endResize();
+ };
+ const onPointerUp = (ev: PointerEvent) => {
+ if (ev.pointerId !== pointerId) return;
+ endResize();
+ if (Math.abs(ev.clientX - originX) < 1) {
+ onSelect(false);
+ return;
+ }
+ commit(widthAt(ev.clientX) / scale);
+ };
+ endResizeRef.current = endResize;
+ window.addEventListener("pointermove", onPointerMove);
+ window.addEventListener("pointerup", onPointerUp);
+ window.addEventListener("pointercancel", onPointerCancel);
+ }
+
const spellcheckLang = resolveLang(
spellcheck,
typeof document === "undefined" ? null : document.documentElement.lang,
@@ -799,7 +851,18 @@ export function TextRunOverlay({
e.stopPropagation();
// Locked runs are inert: no select, no drag, no edit.
if (run.locked) return;
- const zone = edgeZoneAt(e.currentTarget, e.clientX, e.clientY);
+ const zone = edgeZoneAt(
+ e.currentTarget,
+ e.clientX,
+ e.clientY,
+ canResize,
+ );
+ if (zone === "resize" && onResize) {
+ e.preventDefault();
+ e.currentTarget.blur();
+ startResize(e.clientX, e.pointerId, onResize);
+ return;
+ }
// Ctrl+drag still moves from anywhere inside, so existing muscle
// memory keeps working; grabbing the frame is the discoverable path.
@@ -976,12 +1039,15 @@ export function TextRunOverlay({
onPointerMove={(e) => {
// Only while idle: mid-drag the cursor is owned by the gesture.
if (run.locked || dragging) return;
- setEdgeZone(edgeZoneAt(e.currentTarget, e.clientX, e.clientY));
+ if (resizeWidthPx !== null) return;
+ setEdgeZone(
+ edgeZoneAt(e.currentTarget, e.clientX, e.clientY, canResize),
+ );
}}
style={{
left,
top,
- width,
+ width: resizeWidthPx ?? width,
minHeight: height,
// Live Ctrl+drag preview: follow the cursor via transform, and
// float above siblings + dim slightly so the move reads clearly.
@@ -1051,7 +1117,7 @@ export function TextRunOverlay({
: dragging
? "2px solid #2c7be5"
: selected
- ? edgeZone
+ ? edgeZone || resizeWidthPx !== null
? "2px solid #2c7be5"
: "1px solid #2c7be5"
: hovered
@@ -1063,9 +1129,11 @@ export function TextRunOverlay({
? "default"
: dragging
? "grabbing"
- : edgeZone === "move"
- ? "grab"
- : undefined,
+ : resizeWidthPx !== null || edgeZone === "resize"
+ ? "ew-resize"
+ : edgeZone === "move"
+ ? "grab"
+ : undefined,
overflow: "hidden",
}}
/>
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
index 0041f13d9b..5fad595a39 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx
@@ -48,6 +48,7 @@ export function SelectionInspector({
}: Props) {
const runCount = selection.runIds.length;
const imageCount = selection.imageIds.length;
+ const shapeCount = selection.shapeIds.length;
const { hasRunSelection, hasImageSelection } = controller;
return (
@@ -55,9 +56,12 @@ export function SelectionInspector({
<SelectionHeader
runCount={runCount}
imageCount={imageCount}
+ shapeCount={shapeCount}
fontNote={hasRunSelection ? fontNote : null}
/>
- <GeometrySection geometry={geometry} isImage={!hasRunSelection} />
+ {runCount + imageCount > 0 && (
+ <GeometrySection geometry={geometry} isImage={!hasRunSelection} />
+ )}
{hasRunSelection && (
<ParagraphSection
canGroup={canGroup}
@@ -75,18 +79,28 @@ export function SelectionInspector({
function SelectionHeader({
runCount,
imageCount,
+ shapeCount,
fontNote,
}: {
runCount: number;
imageCount: number;
+ shapeCount: number;
fontNote: string | null;
}) {
const { t } = useTranslation();
+ const kinds = [runCount, imageCount, shapeCount].filter((n) => n > 0).length;
let title: string;
- if (runCount > 0 && imageCount > 0) {
+ if (kinds > 1) {
title = t("pdfTextEditor.inspector.mixed", "{{count}} objects", {
- count: runCount + imageCount,
+ count: runCount + imageCount + shapeCount,
});
+ } else if (shapeCount > 0) {
+ title =
+ shapeCount === 1
+ ? t("pdfTextEditor.inspector.oneShape", "Shape")
+ : t("pdfTextEditor.inspector.manyShapes", "{{count}} shapes", {
+ count: shapeCount,
+ });
} else if (runCount > 0) {
title =
runCount === 1
@@ -255,19 +269,14 @@ function GeometrySection({
? undefined
: t(
"pdfTextEditor.inspector.widthHint",
- "A text box's width follows its content and wrapping.",
+ "Text re-wraps to fit the width.",
)
}
>
- {/* Read-only for text: setting a width goes through the reflow,
- which splits inside words on runs whose glyphs are positioned
- individually. Until that is token-aware this must not be a
- one-keystroke way to shred a heading. */}
<PointsInput
value={bounds.width}
- onCommit={isImage ? setWidth : () => undefined}
+ onCommit={setWidth}
min={1}
- disabled={!isImage}
label={t("pdfTextEditor.inspector.width", "Width")}
testId="pdf-editor-size-w"
/>
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/toolbar/ObjectGroup.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/toolbar/ObjectGroup.tsx
index f2840618bc..4d06b59cf9 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/toolbar/ObjectGroup.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/toolbar/ObjectGroup.tsx
@@ -9,7 +9,15 @@ import {
export function ObjectGroup({ controller }: { controller: Controller }) {
const { t } = useTranslation();
- const { selectionAllLocked, onToggleLock, onDelete } = controller;
+ const {
+ selectionAllLocked,
+ onToggleLock,
+ onDelete,
+ hasRunSelection,
+ hasImageSelection,
+ } = controller;
+ // Lock and arrange act on text and images only; shapes can just be deleted.
+ const arrangeable = hasRunSelection || hasImageSelection;
return (
<>
@@ -30,6 +38,7 @@ export function ObjectGroup({ controller }: { controller: Controller }) {
variant={selectionAllLocked ? "primary" : "tertiary"}
accent={selectionAllLocked ? "default" : "neutral"}
size="sm"
+ disabled={!arrangeable}
onClick={onToggleLock}
aria-label={
selectionAllLocked
@@ -47,7 +56,12 @@ export function ObjectGroup({ controller }: { controller: Controller }) {
}
/>
</Tooltip>
- <Tooltip label={t("pdfTextEditor.toolbar.deleteTooltip", "Delete (Del)")}>
+ <Tooltip
+ label={t(
+ "pdfTextEditor.toolbar.deleteTooltip",
+ "Delete (Del or Backspace)",
+ )}
+ >
<Button
variant="tertiary"
accent="danger"
@@ -63,6 +77,7 @@ export function ObjectGroup({ controller }: { controller: Controller }) {
<Menu.Target>
<Button
size="sm"
+ disabled={!arrangeable}
variant="secondary"
accent="neutral"
leftSection={<Icon name="layers" size={20} />}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
index 5472cfb825..a2f4ed0743 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
@@ -72,6 +72,7 @@ export function useDocumentLoader(store: EditorStore) {
revision: page.revision,
runs: page.runs.map((r) => r.snapshot()),
images: page.images.map((img) => img.snapshot()),
+ shapes: page.shapes.map((shape) => shape.snapshot()),
annotations: page.annotations,
display: page.display.toData(),
});
@@ -86,6 +87,7 @@ export function useDocumentLoader(store: EditorStore) {
revision: 0,
runs: [],
images: [],
+ shapes: [],
display: page.display.toData(),
});
}
@@ -144,6 +146,7 @@ export function ensureAllPagesRead(store: EditorStore): void {
revision: page.revision,
runs: page.runs.map((r) => r.snapshot()),
images: page.images.map((img) => img.snapshot()),
+ shapes: page.shapes.map((shape) => shape.snapshot()),
annotations: page.annotations,
};
});
@@ -171,6 +174,7 @@ export function ensurePageRead(store: EditorStore, pageIndex: number): void {
revision: page.revision,
runs: page.runs.map((r) => r.snapshot()),
images: page.images.map((img) => img.snapshot()),
+ shapes: page.shapes.map((shape) => shape.snapshot()),
annotations: page.annotations,
}
: p,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
index d88d93e407..600e641fcc 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
@@ -128,10 +128,16 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
onEscape();
return;
}
- if (e.key === "Delete") {
+ // Mac keyboards have no Delete key; their ⌫ arrives as Backspace.
+ if (e.key === "Delete" || e.key === "Backspace") {
if (isFocusInContentEditable()) return;
const sel = store.selection.value;
- if (sel.runIds.length === 0 && sel.imageIds.length === 0) return;
+ if (
+ sel.runIds.length === 0 &&
+ sel.imageIds.length === 0 &&
+ sel.shapeIds.length === 0
+ )
+ return;
e.preventDefault();
onDelete();
return;
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionActions.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
index a2f5da5e42..0bf5bbf947 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
@@ -3,6 +3,7 @@ import { DeleteImageCommand } from "@app/tools/pdfTextEditor/commands/DeleteImag
import { ReplaceImageCommand } from "@app/tools/pdfTextEditor/commands/ReplaceImageCommand";
import type { DecodedImage } from "@app/utils/pdfiumBitmapUtils";
import { DeleteObjectCommand } from "@app/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { DeleteShapeCommand } from "@app/tools/pdfTextEditor/commands/DeleteShapeCommand";
import { DuplicateRunCommand } from "@app/tools/pdfTextEditor/commands/DuplicateRunCommand";
import { SetColourCommand } from "@app/tools/pdfTextEditor/commands/SetColourCommand";
import { SetTextOutlineCommand } from "@app/tools/pdfTextEditor/commands/SetTextOutlineCommand";
@@ -170,10 +171,15 @@ export function useSelectionActions(store: EditorStore) {
const sel = store.selection.value;
const doc = store.document;
if (!doc) return;
- if (sel.runIds.length === 0 && sel.imageIds.length === 0) return;
+ if (
+ sel.runIds.length === 0 &&
+ sel.imageIds.length === 0 &&
+ sel.shapeIds.length === 0
+ )
+ return;
// Collect one command per object but dispatch them as ONE composite: a
// 30-object delete must be a single undo step, not 30.
- const cmds: Array<DeleteObjectCommand | DeleteImageCommand> = [];
+ const cmds: Command[] = [];
for (const page of doc.loadedPages()) {
for (const run of page.runs) {
if (sel.runIds.includes(run.id) && !run.locked) {
@@ -195,6 +201,16 @@ export function useSelectionActions(store: EditorStore) {
);
}
}
+ for (const shape of page.shapes) {
+ if (sel.shapeIds.includes(shape.id)) {
+ cmds.push(
+ new DeleteShapeCommand({
+ pageIndex: shape.pageIndex,
+ shapeId: shape.id,
+ }),
+ );
+ }
+ }
}
if (cmds.length === 1) store.dispatch(cmds[0]);
else if (cmds.length > 1) store.dispatch(new CompositeCommand(cmds));
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts
index 3ecbadf038..5735e79621 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts
@@ -34,7 +34,10 @@ export function useSelectionGeometry(
return useMemo(() => {
const runId = selection.runIds[0];
const imageId = selection.imageIds[0];
- const total = selection.runIds.length + selection.imageIds.length;
+ const total =
+ selection.runIds.length +
+ selection.imageIds.length +
+ selection.shapeIds.length;
if (total !== 1) return { single: null };
if (runId) {
@@ -42,7 +45,9 @@ export function useSelectionGeometry(
const run = page.runs.find((r) => r.id === runId);
if (!run) continue;
const pageIndex = page.pageIndex;
- const bounds = run.bounds;
+ const bounds = run.wrapWidthPt
+ ? { ...run.bounds, width: run.wrapWidthPt }
+ : run.bounds;
return {
single: {
bounds,
@@ -72,6 +77,7 @@ export function useSelectionGeometry(
pageIndex,
runId,
maxWidthPt: Math.max(1, next),
+ explicit: true,
}),
),
},
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index e32b0aa042..a60b5b3ab3 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useToolbarController.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useToolbarController.ts
@@ -520,7 +520,10 @@ export function useToolbarController(
selectionAllLocked,
hasRunSelection: selection.runIds.length > 0,
hasImageSelection: selection.imageIds.length > 0,
- selectionCount: selection.runIds.length + selection.imageIds.length,
+ selectionCount:
+ selection.runIds.length +
+ selection.imageIds.length +
+ selection.shapeIds.length,
canAlignLines,
disabled:
!state.hasDocument ||
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts
index 7eab70b45b..6019a7d44c 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts
@@ -1,5 +1,6 @@
import { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
import { ImageObject } from "@app/tools/pdfTextEditor/model/ImageObject";
+import type { ShapeObject } from "@app/tools/pdfTextEditor/model/ShapeObject";
import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
import type { AnnotationBox } from "@app/tools/pdfTextEditor/model/AnnotationBox";
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
@@ -15,6 +16,13 @@ export class Page {
readonly display: DisplayTransform;
runs: TextRun[];
images: ImageObject[];
+ shapes: ShapeObject[];
+ /**
+ * Deleted shapes still inside a form XObject (object ptr -> form ptr). They
+ * are hidden for now and removed on save: removal is the only change to a
+ * form's children that PDFium writes back, and it cannot be undone.
+ */
+ pendingFormRemovals: Map<number, number>;
/** Text-carrying annotations: rendered by the canvas, not editable. */
annotations: AnnotationBox[];
/** True if any object on this page has uncommitted mutation. */
@@ -45,6 +53,8 @@ export class Page {
opts.display ?? DisplayTransform.identity(opts.width, opts.height);
this.runs = [];
this.images = [];
+ this.shapes = [];
+ this.pendingFormRemovals = new Map();
this.annotations = [];
this.dirty = false;
this.loaded = false;
@@ -61,6 +71,10 @@ export class Page {
this.images = images;
}
+ setShapes(shapes: ShapeObject[]): void {
+ this.shapes = shapes;
+ }
+
setAnnotations(annotations: AnnotationBox[]): void {
this.annotations = annotations;
}
@@ -114,4 +128,8 @@ export class Page {
findImage(id: string): ImageObject | undefined {
return this.images.find((i) => i.id === id);
}
+
+ findShape(id: string): ShapeObject | undefined {
+ return this.shapes.find((s) => s.id === id);
+ }
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/ShapeObject.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/ShapeObject.ts
new file mode 100644
index 0000000000..74a7afb265
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/ShapeObject.ts
@@ -0,0 +1,45 @@
+import type {
+ Affine,
+ PageRect,
+ ShapeObjectSnapshot,
+} from "@app/tools/pdfTextEditor/types";
+
+/** A vector path object on a page; `bounds` is in raw PDF page space. */
+export class ShapeObject {
+ readonly id: string;
+ readonly pageIndex: number;
+ pdfiumObjPtr: number;
+ /** Owning form XObject, or 0 when the shape sits on the page. */
+ containerPtr: number;
+ /** The page-level form that holds the container, or 0 on the page. */
+ topLevelContainerPtr: number;
+ /** Maps the container's local space to page space; identity on the page. */
+ containerTransform: Affine;
+ bounds: PageRect;
+
+ constructor(
+ init: Omit<ShapeObjectSnapshot, "movable"> & {
+ pdfiumObjPtr: number;
+ containerPtr: number;
+ topLevelContainerPtr: number;
+ containerTransform: Affine;
+ },
+ ) {
+ this.id = init.id;
+ this.pageIndex = init.pageIndex;
+ this.pdfiumObjPtr = init.pdfiumObjPtr;
+ this.containerPtr = init.containerPtr;
+ this.topLevelContainerPtr = init.topLevelContainerPtr;
+ this.containerTransform = init.containerTransform;
+ this.bounds = init.bounds;
+ }
+
+ snapshot(): ShapeObjectSnapshot {
+ return {
+ id: this.id,
+ pageIndex: this.pageIndex,
+ bounds: { ...this.bounds },
+ movable: this.containerPtr === 0,
+ };
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts
index cc0d3b2f1b..72c0609b35 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/TextRun.ts
@@ -106,6 +106,12 @@ export class TextRun {
// Session-only lock: when true the run is skipped by all hit-tests (mouse,
// marquee, Ctrl+A) and edit gestures are no-ops.
locked: boolean;
+ /**
+ * Width the user resized the box to, in PDF points, or null to follow the
+ * ink. Kept apart from `bounds`, which a reflow sets to the glyphs' extent:
+ * text rarely fills its box, so the box would shrink back to the ink.
+ */
+ wrapWidthPt: number | null;
constructor(
init: TextRunSnapshot & {
@@ -148,6 +154,7 @@ export class TextRun {
this.paragraphSoftStarts = [];
this.coverRectPtr = 0;
this.locked = init.locked ?? false;
+ this.wrapWidthPt = init.wrapWidthPt ?? null;
}
// Captured pen positions are only valid for the text AND face they were
@@ -188,6 +195,7 @@ export class TextRun {
paragraphBaselines: this.lineBaselines(),
paragraphLineLefts: this.lineLefts(),
locked: this.locked || undefined,
+ wrapWidthPt: this.wrapWidthPt ?? undefined,
};
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index e3793d90d5..e90bc68415 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -1,6 +1,7 @@
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
import { ImageObject } from "@app/tools/pdfTextEditor/model/ImageObject";
+import { ShapeObject } from "@app/tools/pdfTextEditor/model/ShapeObject";
import type { Page } from "@app/tools/pdfTextEditor/model/Page";
import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
import { LineGrouper } from "@app/tools/pdfTextEditor/pdfium/LineGrouper";
@@ -18,6 +19,7 @@ import { registerEmbeddedFace } from "@app/tools/pdfTextEditor/util/embeddedFace
/** PDFium page-object type constants - mirrors `public/fpdf_edit.h`. */
const FPDF_PAGEOBJ_TEXT = 1;
+const FPDF_PAGEOBJ_PATH = 2;
const FPDF_PAGEOBJ_IMAGE = 3;
const FPDF_PAGEOBJ_FORM = 5;
@@ -35,6 +37,7 @@ export class PdfiumTextReader {
const runs: TextRun[] = [];
const images: ImageObject[] = [];
+ const shapes: ShapeObject[] = [];
// ONE text page for the whole walk: FPDFText_LoadPage runs full page text
// extraction, so opening it per text object made population O.
@@ -48,6 +51,7 @@ export class PdfiumTextReader {
count,
runs,
images,
+ shapes,
doc,
page,
[],
@@ -58,6 +62,7 @@ export class PdfiumTextReader {
page.setRuns(runs);
page.setImages(images);
+ page.setShapes(shapes);
// Annotation text is drawn by FPDF_ANNOT but lives outside the object
// tree, so record the boxes to explain why it can't be edited.
PdfiumAnnotationReader.populate(m, page);
@@ -360,6 +365,7 @@ function walkObjects(
count: number,
runs: TextRun[],
images: ImageObject[],
+ shapes: ShapeObject[],
doc: EditorDocument,
page: Page,
path: number[],
@@ -402,6 +408,15 @@ function walkObjects(
const indexId = [...path, i].join("-");
const img = readImage(m, page, objPtr, indexId, transform, containerPtr);
if (img) images.push(img);
+ } else if (type === FPDF_PAGEOBJ_PATH && path.length <= 1) {
+ // Shapes in nested forms are left alone: deleting one relies on form
+ // removal being written back, verified only for page-level forms.
+ const indexId = [...path, i].join("-");
+ const shape = readShape(m, page, objPtr, indexId, transform, {
+ containerPtr,
+ topLevelContainerPtr,
+ });
+ if (shape) shapes.push(shape);
} else if (type === FPDF_PAGEOBJ_FORM && depth < MAX_DEPTH) {
let formCount: number;
try {
@@ -419,6 +434,7 @@ function walkObjects(
formCount,
runs,
images,
+ shapes,
doc,
page,
[...path, i],
@@ -768,6 +784,75 @@ function readTextRun(
}
}
+/**
+ * Fraction of the page a shape may cover and still be offered for selection.
+ * Larger ones are page backgrounds: selectable, they would swallow every click
+ * and every drag-select on the page.
+ */
+const MAX_SHAPE_PAGE_COVERAGE = 0.9;
+
+function readShape(
+ m: WrappedPdfiumModule,
+ page: Page,
+ objPtr: number,
+ index: number | string,
+ transform: Affine,
+ containers: { containerPtr: number; topLevelContainerPtr: number },
+): ShapeObject | null {
+ if (!isPainted(m, objPtr)) return null;
+ const localBounds = readBounds(m, objPtr);
+ if (!localBounds) return null;
+ const bounds = isIdentity(transform)
+ ? localBounds
+ : transformRect(transform, localBounds);
+ const pageArea = page.width * page.height;
+ if (bounds.width * bounds.height >= pageArea * MAX_SHAPE_PAGE_COVERAGE) {
+ return null;
+ }
+ return new ShapeObject({
+ id: `p${page.index}-s${index}`,
+ pageIndex: page.index,
+ pdfiumObjPtr: objPtr,
+ ...containers,
+ containerTransform: transform,
+ bounds,
+ });
+}
+
+/** True when a path fills or strokes with any opacity; clip-only paths draw nothing. */
+function isPainted(m: WrappedPdfiumModule, objPtr: number): boolean {
+ const fillModePtr = m.pdfium.wasmExports.malloc(4);
+ const strokePtr = m.pdfium.wasmExports.malloc(4);
+ try {
+ if (!m.FPDFPath_GetDrawMode(objPtr, fillModePtr, strokePtr)) return false;
+ const fills = m.pdfium.getValue(fillModePtr, "i32") !== 0;
+ const strokes = m.pdfium.getValue(strokePtr, "i32") !== 0;
+ return (
+ (fills && readFill(m, objPtr).a > 0) ||
+ (strokes && readStrokeAlpha(m, objPtr) > 0)
+ );
+ } finally {
+ m.pdfium.wasmExports.free(fillModePtr);
+ m.pdfium.wasmExports.free(strokePtr);
+ }
+}
+
+function readStrokeAlpha(m: WrappedPdfiumModule, objPtr: number): number {
+ const r = m.pdfium.wasmExports.malloc(4);
+ const g = m.pdfium.wasmExports.malloc(4);
+ const b = m.pdfium.wasmExports.malloc(4);
+ const a = m.pdfium.wasmExports.malloc(4);
+ try {
+ if (!m.FPDFPageObj_GetStrokeColor(objPtr, r, g, b, a)) return 0;
+ return m.pdfium.getValue(a, "i32") & 0xff;
+ } finally {
+ m.pdfium.wasmExports.free(r);
+ m.pdfium.wasmExports.free(g);
+ m.pdfium.wasmExports.free(b);
+ m.pdfium.wasmExports.free(a);
+ }
+}
+
function readImage(
m: WrappedPdfiumModule,
page: Page,
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts
index 1682f200fe..e1f3516f53 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts
@@ -259,6 +259,7 @@ export class EditorStore {
revision: live.revision,
runs: live.runs.map((r) => r.snapshot()),
images: live.images.map((img) => img.snapshot()),
+ shapes: live.shapes.map((shape) => shape.snapshot()),
// Regrouping re-populates the page, which re-reads its annotations.
annotations: live.annotations,
};
@@ -474,6 +475,7 @@ export class EditorStore {
page.loaded = false;
page.setRuns([]);
page.setImages([]);
+ page.setShapes([]);
PdfiumTextReader.populate(doc, page, mode);
}
}
@@ -501,6 +503,7 @@ export class EditorStore {
revision: live.revision,
runs: live.runs.map((r) => r.snapshot()),
images: live.images.map((img) => img.snapshot()),
+ shapes: live.shapes.map((shape) => shape.snapshot()),
};
});
if (!changed) return;
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/store/Selection.ts b/frontend/editor/src/core/tools/pdfTextEditor/store/Selection.ts
index 4bb76362f8..c4a1f40418 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/store/Selection.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/store/Selection.ts
@@ -35,7 +35,7 @@ export class Selection {
readonly highlight: FindHighlight;
constructor() {
- this.state = { runIds: [], imageIds: [], caret: null };
+ this.state = { runIds: [], imageIds: [], shapeIds: [], caret: null };
this.listeners = new Set();
this.highlight = new FindHighlight();
}
@@ -50,11 +50,11 @@ export class Selection {
}
clear(): void {
- this.set({ runIds: [], imageIds: [], caret: null });
+ this.set({ runIds: [], imageIds: [], shapeIds: [], caret: null });
}
selectOne(runId: string, caret: number | null = null): void {
- this.set({ runIds: [runId], imageIds: [], caret });
+ this.set({ runIds: [runId], imageIds: [], shapeIds: [], caret });
}
toggle(runId: string): void {
@@ -74,24 +74,46 @@ export class Selection {
}
selectImage(imageId: string): void {
- this.set({ runIds: [], imageIds: [imageId], caret: null });
+ this.set({ runIds: [], imageIds: [imageId], shapeIds: [], caret: null });
+ }
+
+ selectShape(shapeId: string): void {
+ this.set({ runIds: [], imageIds: [], shapeIds: [shapeId], caret: null });
+ }
+
+ toggleShape(shapeId: string): void {
+ const shapeIds = this.state.shapeIds.includes(shapeId)
+ ? this.state.shapeIds.filter((id) => id !== shapeId)
+ : [...this.state.shapeIds, shapeId];
+ this.set({ ...this.state, shapeIds, caret: null });
}
/**
- * Replace the selection with `runIds`, or union them into it when additive
- * (an extending rectangle-select). Additive keeps order, dedupes, and leaves
- * any selected images alone.
+ * Replace the selection with the given runs, images and shapes, or union
+ * them into it when additive (an extending rectangle-select). Additive keeps
+ * order and dedupes.
*/
- selectMany(runIds: string[], additive = false): void {
+ selectMany(
+ runIds: string[],
+ additive = false,
+ imageIds: string[] = [],
+ shapeIds: string[] = [],
+ ): void {
if (!additive) {
- this.set({ runIds: [...runIds], imageIds: [], caret: null });
+ this.set({
+ runIds: [...runIds],
+ imageIds: [...imageIds],
+ shapeIds: [...shapeIds],
+ caret: null,
+ });
return;
}
- const merged = [...this.state.runIds];
- for (const id of runIds) {
- if (!merged.includes(id)) merged.push(id);
- }
- this.set({ ...this.state, runIds: merged, caret: null });
+ this.set({
+ runIds: unionInOrder(this.state.runIds, runIds),
+ imageIds: unionInOrder(this.state.imageIds, imageIds),
+ shapeIds: unionInOrder(this.state.shapeIds, shapeIds),
+ caret: null,
+ });
}
subscribe(listener: (s: SelectionState) => void): () => void {
@@ -111,3 +133,11 @@ export class Selection {
}
}
}
+
+function unionInOrder(existing: string[], added: string[]): string[] {
+ const merged = [...existing];
+ for (const id of added) {
+ if (!merged.includes(id)) merged.push(id);
+ }
+ return merged;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/types.ts b/frontend/editor/src/core/tools/pdfTextEditor/types.ts
index 6a1d6f304e..881b593ea7 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/types.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/types.ts
@@ -81,6 +81,8 @@ export interface TextRunSnapshot {
// Editor-only metadata: when true the run cannot be selected or edited via
// mouse/keyboard.
locked?: boolean;
+ /** Box width the user set by resize, in PDF points; absent = follow the ink. */
+ wrapWidthPt?: number;
}
export interface ImageObjectSnapshot {
@@ -92,6 +94,15 @@ export interface ImageObjectSnapshot {
locked?: boolean;
}
+/** A vector path: a line, frame, box or other drawn shape. */
+export interface ShapeObjectSnapshot {
+ id: string;
+ pageIndex: number;
+ bounds: PageRect;
+ /** False inside a form XObject, whose children PDFium cannot re-save moved. */
+ movable: boolean;
+}
+
export interface PageSnapshot {
pageIndex: number;
width: number;
@@ -102,6 +113,7 @@ export interface PageSnapshot {
revision: number;
runs: TextRunSnapshot[];
images: ImageObjectSnapshot[];
+ shapes: ShapeObjectSnapshot[];
// Text-carrying annotations: drawn by the canvas, outside the editable
// object tree. Absent until the page has been read.
annotations?: AnnotationBox[];
@@ -113,6 +125,8 @@ export interface SelectionState {
runIds: string[];
/** Selected image object ids. */
imageIds: string[];
+ /** Selected vector shape ids. */
+ shapeIds: string[];
/** Caret position when exactly one run is selected and the user is typing */
caret: number | null;
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts
index 58c06c1f8b..2f5917bf59 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/exportPdf.ts
@@ -22,6 +22,8 @@ export async function exportToBlob(
return { blob: pdfBlob(doc.openedBytes), filename: exportName(sourceName) };
}
+ commitPendingFormRemovals(doc);
+
// A signed document is appended to rather than rewritten, so the bytes the
// signature covers are still there and still verify for their revision.
const incremental = documentIsSigned(doc);
@@ -53,6 +55,27 @@ export async function exportToBlob(
return { blob: pdfBlob(bytes), filename: exportName(sourceName) };
}
+interface FormRemovalModule {
+ FPDFFormObj_RemoveObject?: (form: number, obj: number) => boolean;
+}
+
+/**
+ * Remove the form children that DeleteShapeCommand only hid. Done here, on the
+ * user's save, rather than in every serialize: other serializes (the charcode
+ * probe) must not make a delete permanent while it can still be undone.
+ */
+function commitPendingFormRemovals(doc: EditorDocument): void {
+ const m = doc.module as unknown as FormRemovalModule;
+ for (const page of doc.loadedPages()) {
+ if (page.pendingFormRemovals.size === 0) continue;
+ for (const [objPtr, formPtr] of page.pendingFormRemovals) {
+ m.FPDFFormObj_RemoveObject?.(formPtr, objPtr);
+ }
+ page.pendingFormRemovals.clear();
+ page.markNeedsGenerate();
+ }
+}
+
function pdfBlob(bytes: Uint8Array): Blob {
return new Blob([bytes as unknown as ArrayBuffer], {
type: "application/pdf",
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/wordGrouping.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/wordGrouping.ts
new file mode 100644
index 0000000000..998d393bf2
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/wordGrouping.ts
@@ -0,0 +1,134 @@
+/** A positioned piece of a text run: one PDF text object, often one glyph. */
+export interface WordLeaf {
+ text: string;
+ x: number;
+ right: number;
+ baseline: number;
+}
+
+export interface Word<L extends WordLeaf> {
+ glyphs: L[];
+ x: number;
+ right: number;
+ baseline: number;
+}
+
+const SAME_LINE_PT = 2;
+/** Gap that separates words when nothing better is known, in em. */
+const WORD_GAP_EM = 0.18;
+/** How far past a line's own letter-spacing a gap must reach to be a space, in em. */
+const SPACE_OVER_TRACKING_EM = 0.15;
+
+/**
+ * Group reading-ordered leaves into the words a reflow may break between.
+ *
+ * Whitespace in the text decides first. A raw x-gap cannot tell a word space
+ * from letter-spacing: a tracked heading drawn one glyph per object has glyph
+ * gaps wider than any fixed threshold, so every glyph became its own word and
+ * the line breaker split "Open Source" into one character per line. Between
+ * single-glyph leaves the gap is therefore judged against that line's own
+ * median glyph gap.
+ *
+ * A whitespace-only leaf stays on the word before it, so a word can end in a
+ * space; `endsWithSpace` reports that.
+ */
+export function groupWords<L extends WordLeaf>(
+ leaves: L[],
+ fontSize: number,
+): Word<L>[] {
+ const lineOf = lineIndices(leaves);
+ const trackingByLine = medianGlyphGapByLine(leaves, lineOf);
+ const words: Word<L>[] = [];
+ let cur: L[] = [];
+ const flush = () => {
+ if (cur.length === 0) return;
+ words.push({
+ glyphs: cur,
+ x: Math.min(...cur.map((g) => g.x)),
+ right: Math.max(...cur.map((g) => g.right)),
+ baseline: cur[0].baseline,
+ });
+ cur = [];
+ };
+ for (let i = 0; i < leaves.length; i++) {
+ const g = leaves[i];
+ const prev = leaves[i - 1];
+ const tracking = trackingByLine.get(lineOf[i]);
+ if (prev && startsNewWord(prev, g, fontSize, tracking)) flush();
+ cur.push(g);
+ }
+ flush();
+ return words;
+}
+
+export function endsWithSpace<L extends WordLeaf>(word: Word<L>): boolean {
+ const last = word.glyphs[word.glyphs.length - 1];
+ return last !== undefined && /\s$/.test(last.text);
+}
+
+function startsNewWord(
+ prev: WordLeaf,
+ g: WordLeaf,
+ fontSize: number,
+ tracking: number | undefined,
+): boolean {
+ if (!sameLine(prev, g)) return true;
+ if (isBlank(g)) return false;
+ if (/\s$/.test(prev.text) || /^\s/.test(g.text)) return true;
+ const gap = g.x - prev.right;
+ const threshold =
+ isSingleGlyph(prev) && isSingleGlyph(g) && tracking !== undefined
+ ? Math.max(
+ fontSize * WORD_GAP_EM,
+ tracking + fontSize * SPACE_OVER_TRACKING_EM,
+ )
+ : fontSize * WORD_GAP_EM;
+ return gap > threshold;
+}
+
+/** Line number of each leaf; leaves arrive in reading order. */
+function lineIndices(leaves: WordLeaf[]): number[] {
+ const out: number[] = [];
+ let line = 0;
+ for (let i = 0; i < leaves.length; i++) {
+ if (i > 0 && !sameLine(leaves[i - 1], leaves[i])) line += 1;
+ out.push(line);
+ }
+ return out;
+}
+
+function medianGlyphGapByLine(
+ leaves: WordLeaf[],
+ lineOf: number[],
+): Map<number, number> {
+ const gapsByLine = new Map<number, number[]>();
+ for (let i = 1; i < leaves.length; i++) {
+ const a = leaves[i - 1];
+ const b = leaves[i];
+ if (lineOf[i - 1] !== lineOf[i]) continue;
+ if (!isSingleGlyph(a) || !isSingleGlyph(b)) continue;
+ const gaps = gapsByLine.get(lineOf[i]) ?? [];
+ gaps.push(b.x - a.right);
+ gapsByLine.set(lineOf[i], gaps);
+ }
+ const medians = new Map<number, number>();
+ for (const [line, gaps] of gapsByLine) {
+ gaps.sort((x, y) => x - y);
+ // Lower median: with few samples the larger gaps are likely word spaces,
+ // and an upper median would raise the threshold above them.
+ medians.set(line, gaps[Math.floor((gaps.length - 1) / 2)]);
+ }
+ return medians;
+}
+
+function sameLine(a: WordLeaf, b: WordLeaf): boolean {
+ return Math.abs(a.baseline - b.baseline) <= SAME_LINE_PT;
+}
+
+function isBlank(leaf: WordLeaf): boolean {
+ return leaf.text.trim() === "";
+}
+
+function isSingleGlyph(leaf: WordLeaf): boolean {
+ return [...leaf.text.trim()].length === 1;
+}