Skip to content

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

Add table detection and editing to the v2 PDF text editor (#8335)

Anthony Stirlingfa2d7a373e85
diff --git a/.gitleaksignore b/.gitleaksignore
index deff1f394c..a48a94b673 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -35,3 +35,6 @@ app/saas/src/main/resources/application-staging.properties:generic-api-key:16
# Startup login test uses an unsigned JWT fixture with a literal "signature" suffix.
frontend/editor/src/core/tests/stubbed/startup-login.spec.ts:generic-api-key:42
+
+# Storybook storage-encryption status uses a mock master-key fingerprint.
+frontend/editor/src/portal/components/infrastructure/EncryptionPanel.stories.tsx:generic-api-key:33
diff --git a/frontend/editor/public/locales/en-GB/translation.toml b/frontend/editor/public/locales/en-GB/translation.toml
index 6b8c95e473..30a06b074c 100644
--- a/frontend/editor/public/locales/en-GB/translation.toml
+++ b/frontend/editor/public/locales/en-GB/translation.toml
@@ -7284,7 +7284,9 @@ view = "View"
[pdfTextEditor.sidebar]
addImage = "Add image"
+addTable = "Add table"
addText = "Add text"
+clickPageToAddTable = "Click page to add a table"
clickPageToAddText = "Click page to add text"
document = "Document"
group = "Group"
@@ -7293,11 +7295,13 @@ groupingAutoHint = "Groups equal-spaced lines into paragraphs. Changing this re-
groupingLine = "Line"
groupTooltip = "Merge selected runs into one paragraph ({{shortcut}})"
groupTooltipDisabled = "Select 2+ runs to merge"
+image = "Image"
noFile = "No file loaded"
noFileHint = "Pick a PDF from the Files panel on the left, or drop one in. The editor will open it automatically."
opening = "Opening document..."
paragraph = "Paragraph"
rulers = "Rulers and guides"
+table = "Table"
textBoxWidth = "New text box width"
textGrouping = "Text grouping"
ungroup = "Ungroup"
@@ -7319,6 +7323,24 @@ noDocument = "No document loaded."
pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
renderingPreview = "Rendering preview"
+[pdfTextEditor.table]
+addColumn = "Add column"
+addRow = "Add row"
+column = "Col"
+deleteColumn = "Delete column"
+deleteRow = "Delete row"
+done = "Done"
+doneHint = "Stop editing this as a table"
+edit = "Edit"
+editHint = "Edit as a table - type in cells, add or remove rows and columns"
+move = "Move"
+moveTable = "Drag to move the whole table"
+recognizedHint = "Recognized table - click to select all its text"
+resizeColumn = "Drag to resize this column (Alt: share with the next)"
+resizeRow = "Drag to resize this row (Alt: share with the next)"
+resizeTable = "Drag to resize the whole table"
+row = "Row"
+
[pdfTextEditor.toolbar]
addTextTooltip = "Add a text box - then click the page"
advancedColour = "Advanced colour"
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 030ab2da11..30ed37a2f8 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7428,7 +7428,9 @@ groupedTitle = "Part of a group in this PDF: it can be deleted but not moved."
[pdfTextEditor.sidebar]
addImage = "Add image"
+addTable = "Add table"
addText = "Add text"
+clickPageToAddTable = "Click page to add a table"
clickPageToAddText = "Click page to add text"
document = "Document"
group = "Group"
@@ -7437,11 +7439,14 @@ groupingAutoHint = "Groups equal-spaced lines into paragraphs. Changing this re-
groupingLine = "Line"
groupTooltip = "Merge selected runs into one paragraph ({{shortcut}})"
groupTooltipDisabled = "Select 2+ runs to merge"
+image = "Image"
noFile = "No file loaded"
noFileHint = "Pick a PDF from the Files panel on the left, or drop one in. The editor will open it automatically."
opening = "Opening document..."
paragraph = "Paragraph"
rulers = "Rulers and guides"
+table = "Table"
+text = "Text"
textBoxWidth = "New text box width"
textGrouping = "Text grouping"
ungroup = "Ungroup"
@@ -7463,6 +7468,24 @@ noDocument = "No document loaded."
pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
renderingPreview = "Rendering preview"
+[pdfTextEditor.table]
+addColumn = "Add column"
+addRow = "Add row"
+column = "Col"
+deleteColumn = "Delete column"
+deleteRow = "Delete row"
+done = "Done"
+doneHint = "Stop editing this as a table"
+edit = "Edit"
+editHint = "Edit as a table - type in cells, add or remove rows and columns"
+move = "Move"
+moveTable = "Drag to move the whole table"
+recognizedHint = "Recognized table - click to select all its text"
+resizeColumn = "Drag to resize this column (Alt: share with the next)"
+resizeRow = "Drag to resize this row (Alt: share with the next)"
+resizeTable = "Drag to resize the whole table"
+row = "Row"
+
[pdfTextEditor.toolbar]
addTextTooltip = "Add a text box - then click the page"
advancedColour = "Advanced colour"
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
new file mode 100644
index 0000000000..bf9fd8b041
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
@@ -0,0 +1,282 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import type { PageRect } from "@app/tools/pdfTextEditor/types";
+
+const fixture = path.join(
+ import.meta.dirname,
+ "../test-fixtures/table-sample.pdf",
+);
+const corpus: string[] = process.env.PDF_TABLE_CORPUS
+ ? JSON.parse(readFileSync(process.env.PDF_TABLE_CORPUS, "utf8"))
+ : [];
+
+test.use({ autoGoto: false });
+
+function readMergedTable() {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ const page = store.document?.page(0);
+ const table = page?.tables[0];
+ if (!page || !table) throw new Error("Table adoption failed");
+ const snapshot = table.snapshot();
+ return {
+ id: table.id,
+ rows: table.rows,
+ cols: table.cols,
+ pageRuled: table.pageRuled,
+ spans: snapshot.cells.filter(
+ (cell) => cell.rowSpan > 1 || cell.colSpan > 1,
+ ),
+ rules: page.rules.map(({ x, y, width, height }) => ({
+ x,
+ y,
+ width,
+ height,
+ })),
+ };
+}
+
+function expectNoRulesInside(rect: PageRect, rules: PageRect[]) {
+ for (const rule of rules) {
+ if (rule.width <= rule.height) {
+ const x = rule.x + rule.width / 2;
+ const overlap =
+ Math.min(rule.y + rule.height, rect.y + rect.height) -
+ Math.max(rule.y, rect.y);
+ if (x > rect.x + 1 && x < rect.x + rect.width - 1)
+ expect(overlap).toBeLessThanOrEqual(1);
+ } else {
+ const y = rule.y + rule.height / 2;
+ const overlap =
+ Math.min(rule.x + rule.width, rect.x + rect.width) -
+ Math.max(rule.x, rect.x);
+ if (y > rect.y + 1 && y < rect.y + rect.height - 1)
+ expect(overlap).toBeLessThanOrEqual(1);
+ }
+ }
+}
+
+test("merged cells retain their borders after a structural edit and export", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(180_000);
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await page
+ .getByTestId("pdf-editor-file-input")
+ .setInputFiles(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures/merged-table-sample.pdf",
+ ),
+ );
+ await page.waitForFunction(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.getState().firstPageRendered && !store.getState().loading;
+ });
+ await page
+ .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
+ .first()
+ .click();
+ const before = await page.evaluate(readMergedTable);
+ expect({
+ rows: before.rows,
+ cols: before.cols,
+ pageRuled: before.pageRuled,
+ }).toEqual({ rows: 7, cols: 5, pageRuled: true });
+ const expectedSpans = [
+ { row: 1, col: 0, rowSpan: 1, colSpan: 2 },
+ { row: 2, col: 0, rowSpan: 2, colSpan: 1 },
+ { row: 6, col: 0, rowSpan: 1, colSpan: 3 },
+ ];
+ expect(
+ before.spans.map(({ row, col, rowSpan, colSpan }) => ({
+ row,
+ col,
+ rowSpan,
+ colSpan,
+ })),
+ ).toEqual(expectedSpans);
+ await page.getByTestId(`pdf-editor-table-add-row-${before.id}`).click();
+ const after = await page.evaluate(readMergedTable);
+ expect(after.rows).toBe(8);
+ expect(after.cols).toBe(5);
+ for (const span of after.spans) expectNoRulesInside(span.rect, after.rules);
+ await page.keyboard.press("Control+z");
+ expect((await page.evaluate(readMergedTable)).rows).toBe(7);
+ await page.keyboard.press("Control+y");
+ expect((await page.evaluate(readMergedTable)).rows).toBe(8);
+ await page
+ .getByTestId(`pdf-editor-table-cell-${before.id}-7-0`)
+ .fill("Follow-up");
+ await page.getByTestId(`pdf-editor-table-cell-${before.id}-7-1`).fill("Kim");
+ await page.getByTestId(`pdf-editor-table-add-row-${before.id}`).focus();
+ const downloaded = page.waitForEvent("download");
+ await page.getByTestId("pdf-editor-download").click();
+ const saved = testInfo.outputPath("merged-edited.pdf");
+ await (await downloaded).saveAs(saved);
+ await testInfo.attach("edited merged table", {
+ path: saved,
+ contentType: "application/pdf",
+ });
+ await page.reload({ waitUntil: "domcontentloaded" });
+ await page.getByTestId("pdf-editor-file-input").setInputFiles(saved);
+ await page.waitForFunction(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.getState().firstPageRendered && !store.getState().loading;
+ });
+ await page
+ .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
+ .first()
+ .click();
+ const reopened = await page.evaluate(readMergedTable);
+ expect({ rows: reopened.rows, cols: reopened.cols }).toEqual({
+ rows: 8,
+ cols: 5,
+ });
+ expect(
+ reopened.spans.map(({ row, col, rowSpan, colSpan }) => ({
+ row,
+ col,
+ rowSpan,
+ colSpan,
+ })),
+ ).toEqual(expectedSpans);
+ for (const span of reopened.spans)
+ expectNoRulesInside(span.rect, reopened.rules);
+ await page.screenshot({
+ path: testInfo.outputPath("merged-reopened.png"),
+ fullPage: true,
+ });
+});
+
+for (const file of [fixture, ...corpus]) {
+ test(`table editing survives Done, undo and export: ${path.basename(file)}`, async ({
+ page,
+ }, testInfo) => {
+ test.setTimeout(180_000);
+ const errors: string[] = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible();
+ await page.getByTestId("pdf-editor-file-input").setInputFiles(file);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.waitForFunction(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.getState().firstPageRendered && !store.getState().loading;
+ });
+ const contentBefore = await page.evaluate(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.getState().pages.map((p) => ({
+ pageIndex: p.pageIndex,
+ text: p.runs
+ .map((r) => r.text)
+ .join("")
+ .replace(/\s/g, "")
+ .split("")
+ .sort()
+ .join(""),
+ }));
+ });
+ const chips = page.locator(
+ '[data-testid^="pdf-editor-recognized-table-edit-"]',
+ );
+ const detected = await chips.count();
+ await testInfo.attach("detection", {
+ body: JSON.stringify({ file, detected }),
+ contentType: "application/json",
+ });
+ if (detected === 0) {
+ expect(errors).toEqual([]);
+ return;
+ }
+ await chips.first().click();
+ const before = await page.evaluate(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ const table = store.getState().pages.find((p) => p.tables?.length)
+ ?.tables?.[0];
+ if (!table) throw new Error("Table adoption failed");
+ return {
+ id: table.id,
+ rows: table.rows,
+ cols: table.cols,
+ pageIndex: table.pageIndex,
+ };
+ });
+ await page.getByTestId(`pdf-editor-table-add-row-${before.id}`).click();
+ await page.getByTestId(`pdf-editor-table-done-${before.id}`).click();
+ await expect(page.getByTestId(`pdf-editor-table-${before.id}`)).toHaveCount(
+ 0,
+ );
+ await page.keyboard.press("Control+z");
+ const undone = await page.evaluate(
+ ({ pageIndex, id }) => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.document?.page(pageIndex).tables.find((t) => t.id === id)
+ ?.rows;
+ },
+ { pageIndex: before.pageIndex, id: before.id },
+ );
+ expect(undone).toBe(before.rows);
+ await page.keyboard.press("Control+y");
+ const redone = await page.evaluate(
+ ({ pageIndex, id }) => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.document?.page(pageIndex).tables.find((t) => t.id === id)
+ ?.rows;
+ },
+ { pageIndex: before.pageIndex, id: before.id },
+ );
+ expect(redone).toBe(before.rows + 1);
+ const downloadPromise = page.waitForEvent("download");
+ await page.getByTestId("pdf-editor-download").click();
+ const download = await downloadPromise;
+ const saved = testInfo.outputPath("edited.pdf");
+ await download.saveAs(saved);
+ await testInfo.attach("edited PDF", {
+ path: saved,
+ contentType: "application/pdf",
+ });
+ await page.reload({ waitUntil: "domcontentloaded" });
+ await page.getByTestId("pdf-editor-file-input").setInputFiles(saved);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.waitForFunction(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.getState().firstPageRendered && !store.getState().loading;
+ });
+ const contentAfter = await page.evaluate(() => {
+ const store = (window as unknown as { __editor_store: EditorStore })
+ .__editor_store;
+ return store.getState().pages.map((p) => ({
+ pageIndex: p.pageIndex,
+ text: p.runs
+ .map((r) => r.text)
+ .join("")
+ .replace(/\s/g, "")
+ .split("")
+ .sort()
+ .join(""),
+ }));
+ });
+ expect(contentAfter).toEqual(contentBefore);
+ await expect(page.getByTestId("pdf-editor-error")).toHaveCount(0);
+ await page.screenshot({
+ path: testInfo.outputPath("reopened.png"),
+ fullPage: true,
+ });
+ expect(errors).toEqual([]);
+ });
+}
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tables.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tables.spec.ts
new file mode 100644
index 0000000000..bf48369eff
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-tables.spec.ts
@@ -0,0 +1,379 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
+import path from "path";
+
+// Drives the real PDFium object path: insert a bordered table, grow it by a row
+// and a column, type into a cell, and undo/redo the lot. The unit tests cover
+// the bookkeeping; this proves the actual engine calls render and survive.
+
+// Browser-side reader: inlined into every page.evaluate because helpers from
+// this Node module are not in scope inside the page.
+const STORE = `(window).__editor_store`;
+
+test.describe("PDF text editor - tables", () => {
+ for (const layout of [
+ { name: "compact toolbar", width: 1100, height: 900, mobile: false },
+ { name: "phone action bar", width: 390, height: 844, mobile: true },
+ ]) {
+ test(`inserts a table from the ${layout.name}`, async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({
+ width: layout.width,
+ height: layout.height,
+ });
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeAttached();
+ await page
+ .getByTestId("pdf-editor-file-input")
+ .setInputFiles(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures/paragraph-sample.pdf",
+ ),
+ );
+ await page.waitForFunction(() => {
+ const state = (
+ window as unknown as { __editor_store: EditorStore }
+ ).__editor_store.getState();
+ return state.firstPageRendered && !state.loading;
+ });
+ if (!layout.mobile) {
+ await expect(page.getByTestId("pdf-editor-toolbar")).toHaveAttribute(
+ "data-compact",
+ "true",
+ );
+ await page.getByTestId("pdf-editor-overflow-menu").click();
+ }
+ await page.getByTestId("pdf-editor-add-table").click();
+ await page.waitForFunction(
+ () =>
+ (
+ window as unknown as { __editor_store: EditorStore }
+ ).__editor_store.getState().mode === "addTable",
+ );
+ const box = await page.getByTestId("pdf-editor-page-0").boundingBox();
+ if (!box) throw new Error("Rendered page not found");
+ await page.mouse.click(box.x + 20, box.y + 20);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ (
+ window as unknown as { __editor_store: EditorStore }
+ ).__editor_store.getState().pages[0].tables?.length ?? 0,
+ ),
+ )
+ .toBe(1);
+ });
+ }
+
+ test("insert, grow, fill, and undo a table", async ({ page }) => {
+ test.setTimeout(180_000);
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 15_000,
+ });
+ await page
+ .locator('[data-testid="pdf-editor-file-input"]')
+ .setInputFiles(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures",
+ "paragraph-sample.pdf",
+ ),
+ );
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.waitForTimeout(1200);
+
+ const runsBefore = (await page.evaluate(
+ `${STORE}.state.pages[0].runs.length`,
+ )) as number;
+
+ // Arm "Add table" and drop one onto the page.
+ await page.getByTestId("pdf-editor-add-table").click();
+ const box = await page.getByTestId("pdf-editor-page-0").boundingBox();
+ expect(box).not.toBeNull();
+ await page.mouse.click(
+ box!.x + box!.width * 0.4,
+ box!.y + box!.height * 0.4,
+ );
+
+ // A synthetic table now exists in the store.
+ await page.waitForFunction(
+ `(${STORE}.state.pages[0].tables ? ${STORE}.state.pages[0].tables.length : 0) > 0`,
+ undefined,
+ { timeout: 10_000 },
+ );
+ const tableId = (await page.evaluate(
+ `${STORE}.state.pages[0].tables[0].id`,
+ )) as string;
+ const dims0 = (await page.evaluate(
+ `(t => ({ rows: t.rows, cols: t.cols }))(${STORE}.state.pages[0].tables[0])`,
+ )) as { rows: number; cols: number };
+ expect(dims0).toEqual({ rows: 3, cols: 3 });
+
+ // Its overlay + controls render.
+ await expect(page.getByTestId(`pdf-editor-table-${tableId}`)).toBeVisible();
+
+ // Grow it by a row and a column.
+ await page.getByTestId(`pdf-editor-table-add-row-${tableId}`).click();
+ await page.getByTestId(`pdf-editor-table-add-col-${tableId}`).click();
+ await page.waitForTimeout(300);
+ const dims1 = (await page.evaluate(
+ `(t => ({ rows: t.rows, cols: t.cols }))(${STORE}.state.pages[0].tables[0])`,
+ )) as { rows: number; cols: number };
+ expect(dims1).toEqual({ rows: 4, cols: 4 });
+
+ // Type into the top-left cell.
+ const cell = page.getByTestId(`pdf-editor-table-cell-${tableId}-0-0`);
+ await cell.click();
+ await cell.type("Hello");
+ await page.mouse.click(box!.x + 5, box!.y + 5); // blur to commit
+ await page.waitForTimeout(500);
+
+ const afterFill = (await page.evaluate(
+ `(s => { const t = s.state.pages[0].tables[0]; const c = t.cells.find(x => x.row === 0 && x.col === 0); return { runs: s.state.pages[0].runs.length, filled: c ? c.runIds.length : 0 }; })(${STORE})`,
+ )) as { runs: number; filled: number };
+ // A new run backs the cell.
+ expect(afterFill.runs).toBeGreaterThan(runsBefore);
+ expect(afterFill.filled).toBe(1);
+
+ // Undo everything (fill, add-col, add-row, insert) and the table is gone.
+ for (let i = 0; i < 5; i++) {
+ await page.keyboard.press("Control+z");
+ await page.waitForTimeout(150);
+ }
+ const afterUndo = (await page.evaluate(
+ `(s => ({ tables: s.state.pages[0].tables ? s.state.pages[0].tables.length : 0, runs: s.state.pages[0].runs.length }))(${STORE})`,
+ )) as { tables: number; runs: number };
+ expect(afterUndo.tables).toBe(0);
+ expect(afterUndo.runs).toBe(runsBefore);
+
+ // Redo the insert and it comes back.
+ await page.keyboard.press("Control+y");
+ await page.waitForTimeout(300);
+ const afterRedo = (await page.evaluate(
+ `${STORE}.state.pages[0].tables ? ${STORE}.state.pages[0].tables.length : 0`,
+ )) as number;
+ expect(afterRedo).toBe(1);
+ });
+
+ test("resizes a column, a row, and the whole table", async ({ page }) => {
+ test.setTimeout(180_000);
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 15_000,
+ });
+ await page
+ .locator('[data-testid="pdf-editor-file-input"]')
+ .setInputFiles(
+ path.join(
+ import.meta.dirname,
+ "../test-fixtures",
+ "paragraph-sample.pdf",
+ ),
+ );
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.waitForTimeout(1200);
+
+ await page.getByTestId("pdf-editor-add-table").click();
+ const box = await page.getByTestId("pdf-editor-page-0").boundingBox();
+ expect(box).not.toBeNull();
+ await page.mouse.click(
+ box!.x + box!.width * 0.35,
+ box!.y + box!.height * 0.45,
+ );
+ await page.waitForFunction(
+ `(${STORE}.state.pages[0].tables ? ${STORE}.state.pages[0].tables.length : 0) > 0`,
+ undefined,
+ { timeout: 10_000 },
+ );
+ const tableId = (await page.evaluate(
+ `${STORE}.state.pages[0].tables[0].id`,
+ )) as string;
+
+ const geometry = async () =>
+ (await page.evaluate(
+ `(t => ({ cols: t.colEdges.slice(), rows: t.rowEdges.slice(), w: t.bounds.width, h: t.bounds.height }))(${STORE}.state.pages[0].tables[0])`,
+ )) as { cols: number[]; rows: number[]; w: number; h: number };
+
+ // Drag a handle by (dx, dy) CSS px from its centre.
+ const dragHandle = async (testid: string, dx: number, dy: number) => {
+ const b = await page.getByTestId(testid).boundingBox();
+ expect(b).not.toBeNull();
+ await page.mouse.move(b!.x + b!.width / 2, b!.y + b!.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(
+ b!.x + b!.width / 2 + dx,
+ b!.y + b!.height / 2 + dy,
+ { steps: 10 },
+ );
+ await page.mouse.up();
+ await page.waitForTimeout(300);
+ };
+
+ const start = await geometry();
+
+ // A plain edge drag resizes THAT column and the table grows with it.
+ await dragHandle(`pdf-editor-table-col-handle-${tableId}-1`, 50, 0);
+ const afterCol = await geometry();
+ expect(afterCol.cols[1]).toBeGreaterThan(start.cols[1]);
+ expect(afterCol.cols[0]).toBeCloseTo(start.cols[0], 3);
+ expect(afterCol.w).toBeGreaterThan(start.w);
+ // Columns after it keep their own widths - they slide, they do not shrink.
+ expect(afterCol.cols[2] - afterCol.cols[1]).toBeCloseTo(
+ start.cols[2] - start.cols[1],
+ 3,
+ );
+
+ // Alt makes the two neighbours share instead, at a fixed table width.
+ await page.keyboard.down("Alt");
+ await dragHandle(`pdf-editor-table-col-handle-${tableId}-1`, -30, 0);
+ await page.keyboard.up("Alt");
+ const afterShare = await geometry();
+ expect(afterShare.w).toBeCloseTo(afterCol.w, 3);
+ expect(afterShare.cols[1]).toBeLessThan(afterCol.cols[1]);
+
+ await dragHandle(`pdf-editor-table-row-handle-${tableId}-1`, 0, 20);
+ const afterRow = await geometry();
+ // CSS y grows downward, PDF y upward, so dragging down lowers the edge.
+ expect(afterRow.rows[1]).toBeLessThan(afterShare.rows[1]);
+ // That row got taller, so the table did too.
+ expect(afterRow.h).toBeGreaterThan(start.h);
+
+ await dragHandle(`pdf-editor-table-scale-handle-${tableId}`, 80, 50);
+ const afterScale = await geometry();
+ expect(afterScale.w).toBeGreaterThan(start.w);
+ expect(afterScale.h).toBeGreaterThan(start.h);
+
+ // Moving is a distinct gesture: the frame travels, no track changes.
+ const beforeMove = await geometry();
+ await dragHandle(`pdf-editor-table-move-handle-${tableId}`, 40, 25);
+ const afterMove = await geometry();
+ expect(afterMove.w).toBeCloseTo(beforeMove.w, 3);
+ expect(afterMove.h).toBeCloseTo(beforeMove.h, 3);
+ expect(afterMove.cols[0]).toBeGreaterThan(beforeMove.cols[0]);
+ expect(afterMove.rows[0]).toBeLessThan(beforeMove.rows[0]);
+
+ // Each drag is one undo step, and the geometry comes back exactly.
+ for (let i = 0; i < 5; i++) {
+ await page.keyboard.press("Control+z");
+ await page.waitForTimeout(200);
+ }
+ const afterUndo = await geometry();
+ expect(afterUndo.cols).toEqual(start.cols);
+ expect(afterUndo.rows).toEqual(start.rows);
+ });
+
+ test("recognizes a borderless table and makes it editable", async ({
+ page,
+ }) => {
+ test.setTimeout(180_000);
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 15_000,
+ });
+ await page
+ .locator('[data-testid="pdf-editor-file-input"]')
+ .setInputFiles(
+ path.join(import.meta.dirname, "../test-fixtures", "table-sample.pdf"),
+ );
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.waitForTimeout(1500);
+
+ // The grid is found from whitespace alone - the fixture draws no rules.
+ const recognized = page.locator(
+ '[data-testid^="pdf-editor-recognized-table-select-"]',
+ );
+ await expect(recognized).toHaveCount(1, { timeout: 15_000 });
+ await expect(recognized).toHaveText(/4×3/);
+
+ await page
+ .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
+ .first()
+ .click();
+ await page.waitForFunction(
+ `(${STORE}.state.pages[0].tables ? ${STORE}.state.pages[0].tables.length : 0) > 0`,
+ undefined,
+ { timeout: 10_000 },
+ );
+ const tableId = (await page.evaluate(
+ `${STORE}.state.pages[0].tables[0].id`,
+ )) as string;
+
+ // Every filled cell must own a distinct run: a column arrives as one
+ // paragraph run, and sharing it across cells would move a whole column when
+ // one row shifts.
+ const mapping = (await page.evaluate(
+ `(t => { const ids = t.cells.flatMap(c => c.runIds); return { rows: t.rows, cols: t.cols, filled: ids.length, unique: new Set(ids).size }; })(${STORE}.state.pages[0].tables[0])`,
+ )) as { rows: number; cols: number; filled: number; unique: number };
+ expect({ rows: mapping.rows, cols: mapping.cols }).toEqual({
+ rows: 4,
+ cols: 3,
+ });
+ expect(mapping.unique).toBe(mapping.filled);
+ const styleSize = (await page.evaluate(
+ `${STORE}.state.pages[0].tables[0].columnStyles[1].fontSize`,
+ )) as number;
+
+ // Structural editing is now available on a table the document merely drew.
+ await page.getByTestId(`pdf-editor-table-add-row-${tableId}`).click();
+ await page.getByTestId(`pdf-editor-table-add-col-${tableId}`).click();
+ await page.waitForTimeout(400);
+ expect(
+ await page.evaluate(
+ `(t => t.rows + "x" + t.cols)(${STORE}.state.pages[0].tables[0])`,
+ ),
+ ).toBe("5x4");
+
+ // The fixture's first column is left-aligned prose and the rest are
+ // right-aligned numbers; that has to survive into the model.
+ const styles = (await page.evaluate(
+ `${STORE}.state.pages[0].tables[0].columnStyles.map(s => s.align)`,
+ )) as string[];
+ expect(styles[0]).toBe("left");
+ expect(styles[1]).toBe("right");
+
+ // And an empty cell takes typed text, written in that column's style.
+ const runsBefore = (await page.evaluate(
+ `${STORE}.state.pages[0].runs.length`,
+ )) as number;
+ const cell = page.getByTestId(`pdf-editor-table-cell-${tableId}-4-1`);
+ await cell.click();
+ await cell.type("1,000,000");
+ await page.keyboard.press("Enter");
+ await page.waitForTimeout(600);
+ expect(
+ (await page.evaluate(`${STORE}.state.pages[0].runs.length`)) as number,
+ ).toBe(runsBefore + 1);
+
+ // It sits against the column's right edge, not the left one it was
+ // emitted at, and carries the column's size.
+ const placed = (await page.evaluate(
+ `(() => { const t = ${STORE}.state.pages[0].tables[0];
+ const c = t.cells.find(x => x.row === 4 && x.col === 1);
+ const run = ${STORE}.state.pages[0].runs.find(r => r.id === c.runIds[0]);
+ return { lead: run.bounds.x - c.rect.x,
+ trail: (c.rect.x + c.rect.width) - (run.bounds.x + run.bounds.width),
+ size: run.fontSize }; })()`,
+ )) as { lead: number; trail: number; size: number };
+ expect(placed.trail).toBeLessThan(placed.lead);
+ expect(placed.size).toBeCloseTo(styleSize, 1);
+
+ // Leaving the grid restores the recognized chip; the text stays put.
+ await page.getByTestId(`pdf-editor-table-done-${tableId}`).click();
+ await page.waitForTimeout(400);
+ expect(
+ await page.evaluate(`(${STORE}.state.pages[0].tables || []).length`),
+ ).toBe(0);
+ await expect(
+ page.locator('[data-testid^="pdf-editor-recognized-table-select-"]'),
+ ).toHaveCount(1);
+ });
+});
diff --git a/frontend/editor/src/core/tests/test-fixtures/generate-merged-table-sample.mjs b/frontend/editor/src/core/tests/test-fixtures/generate-merged-table-sample.mjs
new file mode 100644
index 0000000000..80ff19e007
--- /dev/null
+++ b/frontend/editor/src/core/tests/test-fixtures/generate-merged-table-sample.mjs
@@ -0,0 +1,116 @@
+// Reproduces a merged label bridging two text bands in a five-column grid.
+// Run with: node generate-merged-table-sample.mjs
+import { writeFileSync } from "node:fs";
+import path from "node:path";
+import { PDFDocument, StandardFonts, rgb } from "@cantoo/pdf-lib";
+
+const xs = [36, 132, 321, 393, 473, 576];
+const ys = [641, 607, 569, 515, 473, 431, 377, 339];
+const spans = [
+ { row: 1, col: 0, rowSpan: 1, colSpan: 2 },
+ { row: 2, col: 0, rowSpan: 2, colSpan: 1 },
+ { row: 6, col: 0, rowSpan: 1, colSpan: 3 },
+];
+const rows = [
+ ["Workstream", "Task", "Owner", "State", "Hours"],
+ ["North programme", "", "Ada", "Active", "18.5"],
+ ["Ops", "Archive intake\nBox 01 to Box 12", "Lin", "Ready", "7.0"],
+ ["", "Metadata review", "Sam", "Review", "12.5"],
+ ["QA", "Needs sign-off", "Jo", "Hold", "4.0"],
+ ["Docs", "Export proof\nKeep both lines", "May", "", "3.25"],
+ ["Shared checkpoint", "", "", "Review", "45.25"],
+];
+
+const document = await PDFDocument.create();
+const regular = await document.embedFont(StandardFonts.Helvetica);
+const bold = await document.embedFont(StandardFonts.HelveticaBold);
+const page = document.addPage([612, 792]);
+const black = rgb(0, 0, 0);
+page.drawText("Merged cells and multiple text runs", {
+ x: 36,
+ y: 721,
+ font: bold,
+ size: 23,
+ color: black,
+});
+for (let c = 0; c < xs.length; c++) {
+ for (let r = 0; r < rows.length; r++) {
+ if (
+ spans.some(
+ (s) =>
+ s.row <= r &&
+ r < s.row + s.rowSpan &&
+ s.col < c &&
+ c < s.col + s.colSpan,
+ )
+ )
+ continue;
+ page.drawLine({
+ start: { x: xs[c], y: ys[r + 1] },
+ end: { x: xs[c], y: ys[r] },
+ thickness: 0.8,
+ color: black,
+ });
+ }
+}
+for (let r = 0; r < ys.length; r++) {
+ for (let c = 0; c < xs.length - 1; c++) {
+ if (
+ spans.some(
+ (s) =>
+ s.row < r &&
+ r < s.row + s.rowSpan &&
+ s.col <= c &&
+ c < s.col + s.colSpan,
+ )
+ )
+ continue;
+ page.drawLine({
+ start: { x: xs[c], y: ys[r] },
+ end: { x: xs[c + 1], y: ys[r] },
+ thickness: 0.8,
+ color: black,
+ });
+ }
+}
+for (const [r, row] of rows.entries()) {
+ for (const [c, text] of row.entries()) {
+ if (!text) continue;
+ const span = spans.find((s) => s.row === r && s.col === c);
+ const font = r === 0 ? bold : regular;
+ const lines = text.split("\n");
+ let y =
+ (ys[r] + ys[r + (span?.rowSpan ?? 1)]) / 2 -
+ 3.85 +
+ (lines.length - 1) * 7;
+ for (const line of lines) {
+ const x =
+ c === 4 && r > 0
+ ? xs[c + 1] - 10 - font.widthOfTextAtSize(line, 11)
+ : xs[c] + 10;
+ if (r === 4 && c === 1) {
+ page.drawText("Needs ", {
+ x,
+ y,
+ font: regular,
+ size: 11,
+ color: black,
+ });
+ page.drawText("sign-off", {
+ x: x + regular.widthOfTextAtSize("Needs ", 11),
+ y,
+ font: bold,
+ size: 11,
+ color: black,
+ });
+ } else {
+ page.drawText(line, { x, y, font, size: 11, color: black });
+ }
+ y -= 14;
+ }
+ }
+}
+writeFileSync(
+ path.join(import.meta.dirname, "merged-table-sample.pdf"),
+ await document.save(),
+);
diff --git a/frontend/editor/src/core/tests/test-fixtures/generate-table-sample.mjs b/frontend/editor/src/core/tests/test-fixtures/generate-table-sample.mjs
new file mode 100644
index 0000000000..b6b8f85bc9
--- /dev/null
+++ b/frontend/editor/src/core/tests/test-fixtures/generate-table-sample.mjs
@@ -0,0 +1,72 @@
+import process from "node:process";
+// One-off script: generate `table-sample.pdf`, a borderless 4x3 grid of text
+// with a right-aligned numeric column under a left-aligned header. There are no
+// ruling lines, so detection has to find the grid from whitespace alone - the
+// case that separates real table recognition from reading borders.
+//
+// Run with: node generate-table-sample.mjs
+import { writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { PDFDocument, StandardFonts, rgb } from "@cantoo/pdf-lib";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+const HEADERS = ["Region", "2025", "2026"];
+const ROWS = [
+ ["EMEA", "812,400", "905,120"],
+ ["North America", "1,204,000", "1,150,900"],
+ ["APAC", "398,220", "441,000"],
+];
+// Column lefts for text, and right edges the numeric columns align against.
+const LEFTS = [40, 190, 300];
+const RIGHTS = [0, 270, 380];
+
+async function main() {
+ const doc = await PDFDocument.create();
+ const font = await doc.embedFont(StandardFonts.Helvetica);
+ const bold = await doc.embedFont(StandardFonts.HelveticaBold);
+ const page = doc.addPage([420, 240]);
+ const size = 10;
+ let y = 190;
+
+ page.drawText("Quarterly Results", {
+ x: 40,
+ y: 215,
+ size: 14,
+ font: bold,
+ color: rgb(0, 0, 0),
+ });
+
+ HEADERS.forEach((text, c) => {
+ page.drawText(text, {
+ x: LEFTS[c],
+ y,
+ size,
+ font: bold,
+ color: rgb(0, 0, 0),
+ });
+ });
+ y -= 22;
+
+ for (const row of ROWS) {
+ row.forEach((text, c) => {
+ // Column 0 is left-aligned prose; the numeric columns are right-aligned,
+ // so their lefts vary while the column band stays put.
+ const x =
+ c === 0 ? LEFTS[0] : RIGHTS[c] - font.widthOfTextAtSize(text, size);
+ page.drawText(text, { x, y, size, font, color: rgb(0, 0, 0) });
+ });
+ y -= 22;
+ }
+
+ const out = await doc.save();
+ const target = join(__dirname, "table-sample.pdf");
+ writeFileSync(target, out);
+ console.log(`wrote ${target} (${out.length} bytes)`);
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/frontend/editor/src/core/tests/test-fixtures/merged-table-sample.pdf b/frontend/editor/src/core/tests/test-fixtures/merged-table-sample.pdf
new file mode 100644
index 0000000000..334eb4973c
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/merged-table-sample.pdf differ
diff --git a/frontend/editor/src/core/tests/test-fixtures/table-sample.pdf b/frontend/editor/src/core/tests/test-fixtures/table-sample.pdf
new file mode 100644
index 0000000000..57ebfeabf3
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/table-sample.pdf differ
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/materialiseTable.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/materialiseTable.test.ts
new file mode 100644
index 0000000000..02cf14d524
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/materialiseTable.test.ts
@@ -0,0 +1,440 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import { Page } from "@app/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { MaterialiseTableCommand } from "@app/tools/pdfTextEditor/commands/MaterialiseTableCommand";
+import type { ScanColors } from "@app/tools/pdfTextEditor/util/scanSampling";
+
+// A fake PDFium that can MEASURE. The table-command fake reports "cannot
+// measure" so its callers take the fallback path; a rebuild has to fit emitted
+// text onto a measured box, so that path is exactly what needs covering here.
+interface FakeObj {
+ ptr: number;
+ kind: "rect" | "text" | "form";
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ fill: [number, number, number, number];
+}
+
+interface FakeDoc extends EditorDocument {
+ _objs: Map<number, FakeObj>;
+ _order: number[];
+ /** What each form XObject actually holds, which is what decides removal. */
+ _children: Map<number, number[]>;
+}
+
+/** Nominal glyph box the fake reports, per point of font size. */
+const CHAR_W = 4;
+const CAP_H = 0.72;
+
+function makeDoc(): { doc: FakeDoc; page: Page } {
+ const page = new Page({ index: 0, pagePtr: 1, width: 595, height: 842 });
+ page.loaded = true;
+ const objs = new Map<number, FakeObj>();
+ const order: number[] = [];
+ const children = new Map<number, number[]>();
+ const heap = new Map<number, number>();
+ let nextPtr = 100;
+ let nextAddr = 8;
+
+ const module = {
+ FPDFPageObj_CreateNewRect: (x: number, y: number, w: number, h: number) => {
+ const ptr = nextPtr++;
+ objs.set(ptr, {
+ ptr,
+ kind: "rect",
+ x,
+ y,
+ w,
+ h,
+ fill: [0, 0, 0, 255],
+ });
+ return ptr;
+ },
+ FPDFPageObj_NewTextObj: (_d: number, _family: string, size: number) => {
+ const ptr = nextPtr++;
+ objs.set(ptr, {
+ ptr,
+ kind: "text",
+ x: 0,
+ y: 0,
+ w: size * CHAR_W,
+ h: size * CAP_H,
+ fill: [0, 0, 0, 255],
+ });
+ return ptr;
+ },
+ FPDFText_SetText: () => true,
+ FPDFPageObj_SetFillColor: (
+ ptr: number,
+ r: number,
+ g: number,
+ b: number,
+ a: number,
+ ) => {
+ const o = objs.get(ptr);
+ if (o) o.fill = [r, g, b, a];
+ return true;
+ },
+ FPDFPageObj_GetBounds: (
+ ptr: number,
+ l: number,
+ b: number,
+ r: number,
+ t: number,
+ ) => {
+ const o = objs.get(ptr);
+ if (!o) return false;
+ heap.set(l, o.x);
+ heap.set(b, o.y);
+ heap.set(r, o.x + o.w);
+ heap.set(t, o.y + o.h);
+ return true;
+ },
+ FPDFPath_SetDrawMode: () => true,
+ FPDFPageObj_Transform: (
+ ptr: number,
+ a: number,
+ _b: number,
+ _c: number,
+ d: number,
+ e: number,
+ f: number,
+ ) => {
+ const o = objs.get(ptr);
+ if (!o) return;
+ o.x = o.x * a + e;
+ o.y = o.y * d + f;
+ o.w *= a;
+ o.h *= d;
+ },
+ FPDFPageObj_GetType: (ptr: number) => {
+ const kind = objs.get(ptr)?.kind;
+ return kind === "text" ? 1 : kind === "form" ? 5 : 2;
+ },
+ FPDFPage_CountObjects: () => order.length,
+ FPDFPage_GetObject: (_p: number, i: number) => order[i] ?? 0,
+ FPDFPage_InsertObject: (_p: number, ptr: number) => {
+ order.push(ptr);
+ },
+ FPDFPage_InsertObjectAtIndex: (_p: number, ptr: number, i: number) => {
+ order.splice(Math.min(Math.max(i, 0), order.length), 0, ptr);
+ return true;
+ },
+ FPDFFormObj_CountObjects: (form: number) => children.get(form)?.length ?? 0,
+ FPDFFormObj_GetObject: (form: number, i: number) =>
+ children.get(form)?.[i] ?? 0,
+ FPDFPageObj_Destroy: (ptr: number) => {
+ objs.delete(ptr);
+ },
+ FPDFPage_RemoveObject: (_p: number, ptr: number) => {
+ const at = order.indexOf(ptr);
+ if (at >= 0) order.splice(at, 1);
+ return true;
+ },
+ pdfium: {
+ wasmExports: {
+ malloc: () => {
+ const at = nextAddr;
+ nextAddr += 4;
+ return at;
+ },
+ free: () => {},
+ },
+ getValue: (addr: number) => heap.get(addr) ?? 0,
+ stringToUTF16: () => {},
+ },
+ };
+
+ const doc = {
+ module,
+ docPtr: 1,
+ _objs: objs,
+ _order: order,
+ _children: children,
+ page: () => page,
+ loadedPages: () => [page],
+ } as unknown as FakeDoc;
+ return { doc, page };
+}
+
+/** An invisible OCR word: a text object plus the run that points at it. */
+function addOcrRun(
+ doc: FakeDoc,
+ page: Page,
+ opts: {
+ id: string;
+ text: string;
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ size: number;
+ container: number;
+ },
+): TextRun {
+ const ptr = doc.module.FPDFPageObj_NewTextObj(1, "Helvetica", opts.size);
+ const obj = doc._objs.get(ptr)!;
+ obj.x = opts.x;
+ obj.y = opts.y;
+ obj.w = opts.w;
+ obj.h = opts.h;
+ doc._children.set(opts.container, [
+ ...(doc._children.get(opts.container) ?? []),
+ ptr,
+ ]);
+ const run = new TextRun({
+ id: opts.id,
+ pageIndex: 0,
+ pdfiumObjPtr: ptr,
+ bounds: { x: opts.x, y: opts.y, width: opts.w, height: opts.h },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: opts.x, f: opts.y },
+ text: opts.text,
+ fontId: "ocr",
+ fontSize: opts.size,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: true,
+ renderMode: 3,
+ topLevelContainerPtr: opts.container,
+ });
+ page.setRuns([...page.runs, run]);
+ return run;
+}
+
+const NAVY = { r: 31, g: 56, b: 100, a: 255 };
+const PAPER = { r: 250, g: 249, b: 246, a: 255 };
+const WHITE_INK = { r: 255, g: 255, b: 255, a: 255 };
+const BLACK_INK = { r: 10, g: 10, b: 10, a: 255 };
+const FORM = 9001;
+
+function scanColors(): ScanColors {
+ const cells = Array.from({ length: 2 }, (_, r) =>
+ Array.from({ length: 2 }, () =>
+ r === 0 ? { bg: NAVY, ink: WHITE_INK } : { bg: PAPER, ink: BLACK_INK },
+ ),
+ );
+ return { cells, paper: PAPER, rule: { r: 20, g: 20, b: 20, a: 255 } };
+}
+
+describe("MaterialiseTableCommand (measurable fake PDFium)", () => {
+ let doc: FakeDoc;
+ let page: Page;
+ let model: TableModel;
+
+ it("leaves the page intact when indexed insertion is unavailable", () => {
+ Object.defineProperty(doc.module, "FPDFPage_InsertObjectAtIndex", {
+ value: undefined,
+ });
+ const order = [...doc._order];
+ const runs = [...page.runs];
+ const before = model.snapshot();
+ const command = new MaterialiseTableCommand({ tableId: model.id });
+ expect(() => command.apply(doc)).toThrow(/unavailable/);
+ command.revert(doc);
+ expect(doc._order).toEqual(order);
+ expect(page.runs).toEqual(runs);
+ expect(model.snapshot()).toEqual(before);
+ });
+
+ beforeEach(() => {
+ ({ doc, page } = makeDoc());
+ // The OCR layer is ONE form object on the page; its words are inside it,
+ // which is the whole reason editing them does not survive a save.
+ doc._objs.set(FORM, {
+ ptr: FORM,
+ kind: "form",
+ x: 90,
+ y: 640,
+ w: 200,
+ h: 60,
+ fill: [0, 0, 0, 0],
+ });
+ doc._order.push(FORM);
+ // Two rows of two cells, each holding one invisible OCR word. The word
+ // boxes deliberately disagree with their declared font sizes, the way
+ // tesseract's do.
+ addOcrRun(doc, page, {
+ id: "ocr-h1",
+ text: "Region",
+ x: 100,
+ y: 690,
+ w: 30,
+ h: 7.2,
+ size: 9.5,
+ container: FORM,
+ });
+ addOcrRun(doc, page, {
+ id: "ocr-h2",
+ text: "Sales",
+ x: 200,
+ y: 690,
+ w: 26,
+ h: 7.2,
+ size: 10.4,
+ container: FORM,
+ });
+ addOcrRun(doc, page, {
+ id: "ocr-b1",
+ text: "North America",
+ x: 100,
+ y: 660,
+ w: 59,
+ h: 5.8,
+ size: 8.05,
+ container: FORM,
+ });
+ addOcrRun(doc, page, {
+ id: "ocr-b2",
+ text: "1,204,000",
+ x: 200,
+ y: 660,
+ w: 40,
+ h: 6.3,
+ size: 9.08,
+ container: FORM,
+ });
+ model = new TableModel({
+ id: "p0-table-0-editable",
+ pageIndex: 0,
+ colEdges: [90, 190, 290],
+ rowEdges: [700, 670, 640],
+ cellRuns: [
+ ["ocr-h1", "ocr-h2"],
+ ["ocr-b1", "ocr-b2"],
+ ],
+ hLinePtrs: [],
+ vLinePtrs: [],
+ lineWidth: 0.75,
+ fontSize: 9,
+ ruled: false,
+ adopted: true,
+ scanned: true,
+ });
+ page.tables.push(model);
+ });
+
+ const textObjs = (): FakeObj[] =>
+ doc._order.map((p) => doc._objs.get(p)!).filter((o) => o.kind === "text");
+
+ it("replaces OCR text with page-level objects, since form edits are lost on save", () => {
+ const before = textObjs().map((o) => o.ptr);
+ new MaterialiseTableCommand({
+ tableId: model.id,
+ colors: scanColors(),
+ }).apply(doc);
+
+ // The originals are gone from the page and the model, replaced by new ones.
+ const after = textObjs().map((o) => o.ptr);
+ expect(after.some((p) => before.includes(p))).toBe(false);
+ expect(after).toHaveLength(4);
+ expect(
+ model.cellRuns.flat().every((id) => id && !id.startsWith("ocr-")),
+ ).toBe(true);
+ expect(page.runs.some((r) => r.id.startsWith("ocr-"))).toBe(false);
+ // The form held nothing but this table, so it goes too.
+ expect(doc._order).not.toContain(FORM);
+ });
+
+ it("fits each replacement onto the box the scanned word occupied", () => {
+ new MaterialiseTableCommand({
+ tableId: model.id,
+ colors: scanColors(),
+ }).apply(doc);
+
+ const placed = textObjs();
+ // "North America": declared 8.05pt but 59pt wide - the box wins, so the
+ // replacement lands on the same 59 x 5.8 rectangle.
+ const wide = placed.find((o) => Math.round(o.w) === 59);
+ expect(wide).toBeDefined();
+ expect(wide!.x).toBeCloseTo(100, 1);
+ expect(wide!.y).toBeCloseTo(660, 1);
+ expect(wide!.h).toBeCloseTo(5.8, 1);
+ // Every replacement matches its original box, not its original font size.
+ const boxes = placed.map((o) =>
+ [o.w, o.h].map((v) => Math.round(v * 10) / 10),
+ );
+ expect(boxes).toContainEqual([30, 7.2]);
+ expect(boxes).toContainEqual([26, 7.2]);
+ expect(boxes).toContainEqual([40, 6.3]);
+ });
+
+ it("keeps a form that holds text the table did not claim", () => {
+ addOcrRun(doc, page, {
+ id: "ocr-heading",
+ text: "Regional performance",
+ x: 100,
+ y: 750,
+ w: 120,
+ h: 9,
+ size: 14,
+ container: FORM,
+ });
+ new MaterialiseTableCommand({
+ tableId: model.id,
+ colors: scanColors(),
+ }).apply(doc);
+
+ // Dropping the form would take the heading's only text layer with it.
+ expect(doc._order).toContain(FORM);
+ expect(page.runs.some((r) => r.id === "ocr-heading")).toBe(true);
+ });
+
+ it("gives each cell the ink it was scanned with, and reverts completely", () => {
+ const cmd = new MaterialiseTableCommand({
+ tableId: model.id,
+ colors: scanColors(),
+ });
+ cmd.apply(doc);
+
+ // White-on-navy would vanish if the rebuild forced everything to black.
+ const inks = textObjs().map((o) => o.fill.join(","));
+ expect(inks.filter((f) => f === "255,255,255,255")).toHaveLength(2);
+ expect(inks.filter((f) => f === "10,10,10,255")).toHaveLength(2);
+ // The navy header is a row fill, so a later move carries it along.
+ expect(model.rowFills).toHaveLength(1);
+ expect(model.rowFills[0].color).toEqual(NAVY);
+
+ cmd.revert(doc);
+ expect(model.ruled).toBe(false);
+ expect(model.rowFills).toHaveLength(0);
+ expect(model.cellRuns[0][0]).toBe("ocr-h1");
+ expect(page.runs.map((r) => r.id).sort()).toEqual([
+ "ocr-b1",
+ "ocr-b2",
+ "ocr-h1",
+ "ocr-h2",
+ ]);
+ expect(doc._order).toContain(FORM);
+ expect(textObjs()).toHaveLength(0);
+ expect(
+ doc._order.filter((p) => doc._objs.get(p)?.kind === "rect"),
+ ).toHaveLength(0);
+ });
+
+ it("keeps a form that also holds a non-text object, so nothing else is lost", () => {
+ // A logo sealed in the same form as the table's OCR text. Counting only
+ // the runs would call this form spent and delete the logo with it.
+ const logo = 8100;
+ doc._objs.set(logo, {
+ ptr: logo,
+ kind: "rect",
+ x: 100,
+ y: 700,
+ w: 20,
+ h: 20,
+ fill: [0, 0, 0, 255],
+ });
+ doc._children.set(FORM, [...(doc._children.get(FORM) ?? []), logo]);
+
+ new MaterialiseTableCommand({
+ tableId: model.id,
+ colors: scanColors(),
+ }).apply(doc);
+
+ expect(doc._order).toContain(FORM);
+ expect(doc._children.get(FORM)).toContain(logo);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/scanSampling.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/scanSampling.test.ts
new file mode 100644
index 0000000000..073a079ae1
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/scanSampling.test.ts
@@ -0,0 +1,58 @@
+import { describe, it, expect, vi } from "vitest";
+import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
+import { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import { sampleTableColors } from "@app/tools/pdfTextEditor/util/scanSampling";
+
+describe("scanned table color sampling", () => {
+ it.each([0, 90, 180, 270])(
+ "samples the displayed cells on a cropped page rotated %s degrees",
+ (rotation) => {
+ const swapped = rotation === 90 || rotation === 270;
+ const transform = DisplayTransform.fromCropAndRotate(
+ 50,
+ 100,
+ 300,
+ 400,
+ rotation / 90,
+ swapped ? 400 : 300,
+ swapped ? 300 : 400,
+ );
+ const table = new TableModel({
+ id: "table",
+ pageIndex: 0,
+ colEdges: [80, 180],
+ rowEdges: [300, 220],
+ cellRuns: [[null]],
+ hLinePtrs: [],
+ vLinePtrs: [],
+ lineWidth: 1,
+ fontSize: 11,
+ }).snapshot();
+ const corners = [transform.apply(92, 229.6), transform.apply(168, 290.4)];
+ const x = Math.round(Math.min(...corners.map((p) => p.x)) * 2);
+ const y = Math.round(
+ (transform.displayHeight - Math.max(...corners.map((p) => p.y))) * 2,
+ );
+ const width = Math.round(Math.abs(corners[1].x - corners[0].x) * 2);
+ const height = Math.round(Math.abs(corners[1].y - corners[0].y) * 2);
+ const getImageData = vi.fn(
+ (left: number, top: number, w: number, h: number) => {
+ const cell = left === x && top === y && w === width && h === height;
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let i = 0; i < data.length; i += 4)
+ data.set(cell ? [30, 50, 100, 255] : [250, 250, 250, 255], i);
+ return { data };
+ },
+ );
+ const canvas = {
+ width: transform.displayWidth * 2,
+ height: transform.displayHeight * 2,
+ getContext: () => ({ canvas, getImageData }),
+ } as unknown as HTMLCanvasElement;
+ const colors = sampleTableColors(canvas, table, transform);
+ expect(getImageData).toHaveBeenCalledWith(x, y, width, height);
+ expect(colors?.cells[0][0]?.bg).toEqual({ r: 30, g: 50, b: 100, a: 255 });
+ expect(colors?.paper).toEqual({ r: 250, g: 250, b: 250, a: 255 });
+ },
+ );
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableAdoption.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableAdoption.test.ts
new file mode 100644
index 0000000000..634394d553
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableAdoption.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect, vi } from "vitest";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { Page } from "@app/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import { adoptedTableModel } from "@app/tools/pdfTextEditor/util/tableAdoption";
+import { ImageObject } from "@app/tools/pdfTextEditor/model/ImageObject";
+
+vi.mock("@app/tools/pdfTextEditor/commands/editTextHelpers", () => ({
+ measureObjSpanPt: () => null,
+}));
+
+function fixture() {
+ const page = new Page({ index: 0, pagePtr: 1, width: 612, height: 792 });
+ const table = new TableModel({
+ id: "p0-table-0",
+ pageIndex: 0,
+ colEdges: [100, 200, 300],
+ rowEdges: [700, 670, 640],
+ cellRuns: [
+ ["ocr", null],
+ [null, null],
+ ],
+ hLinePtrs: [],
+ vLinePtrs: [],
+ lineWidth: 1,
+ fontSize: 11,
+ pageRuled: true,
+ }).snapshot();
+ const module = {} as WrappedPdfiumModule;
+ return { page, table, module };
+}
+
+describe("adopted table ownership", () => {
+ it("leaves a shared path on the page while adopting exclusively owned rules", () => {
+ const { page, table, module } = fixture();
+ const rule = {
+ x: 100,
+ y: 670,
+ width: 200,
+ height: 0,
+ ptr: 41,
+ thickness: 1,
+ color: { r: 0, g: 0, b: 0, a: 255 },
+ };
+ page.setRules([rule, { ...rule, x: 350 }, { ...rule, y: 640, ptr: 42 }]);
+ const model = adoptedTableModel(module, page, table);
+ expect(model.hLinePtrs).toEqual([42]);
+ expect(model.ruled).toBe(true);
+ page.setRules([rule, { ...rule, x: 350 }]);
+ expect(adoptedTableModel(module, page, table).ruled).toBe(false);
+ });
+
+ it("detects a scanned table from cached render modes without the optional accessor", () => {
+ const { page, table, module } = fixture();
+ page.setImages([
+ new ImageObject({
+ id: "scan",
+ pageIndex: 0,
+ pdfiumObjPtr: 50,
+ bounds: table.bounds,
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 },
+ }),
+ ]);
+ const run = new TextRun({
+ id: "ocr",
+ pageIndex: 0,
+ pdfiumObjPtr: 51,
+ text: "First",
+ bounds: table.bounds,
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 100, f: 670 },
+ fontId: "Helvetica",
+ fontSize: 11,
+ fontSubset: false,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ renderMode: 3,
+ });
+ page.setRuns([run]);
+ expect(adoptedTableModel(module, page, table).scanned).toBe(true);
+ run.renderMode = 0;
+ expect(adoptedTableModel(module, page, table).scanned).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts
new file mode 100644
index 0000000000..c516ce4f24
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts
@@ -0,0 +1,1063 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import { Page } from "@app/tools/pdfTextEditor/model/Page";
+import { ShapeObject } from "@app/tools/pdfTextEditor/model/ShapeObject";
+import type { PageRuleSnapshot } from "@app/tools/pdfTextEditor/types";
+import { MoveShapeCommand } from "@app/tools/pdfTextEditor/commands/MoveShapeCommand";
+import { DeleteShapeCommand } from "@app/tools/pdfTextEditor/commands/DeleteShapeCommand";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { InsertTableCommand } from "@app/tools/pdfTextEditor/commands/InsertTableCommand";
+import { FillTableCellCommand } from "@app/tools/pdfTextEditor/commands/FillTableCellCommand";
+import { ModifyTableCommand } from "@app/tools/pdfTextEditor/commands/ModifyTableCommand";
+import { ResizeTableCommand } from "@app/tools/pdfTextEditor/commands/ResizeTableCommand";
+import { HistoryStack } from "@app/tools/pdfTextEditor/store/HistoryStack";
+import { redrawGrid } from "@app/tools/pdfTextEditor/commands/tableHelpers";
+import { emitCellText } from "@app/tools/pdfTextEditor/commands/tableHelpers";
+
+// A fake PDFium module that tracks which object pointers are live on the page,
+// plus each object's kind, translation, and text. Enough to exercise the table
+// commands' object bookkeeping and reversibility without the wasm engine.
+interface FakeObj {
+ ptr: number;
+ kind: "rect" | "text";
+ dx: number;
+ dy: number;
+ /** Accumulated scale, so a background refit can be told from a move. */
+ sx: number;
+ sy: number;
+ text: string;
+ fill: [number, number, number, number];
+ /** PDF text render mode; 3 (invisible) is what an OCR layer carries. */
+ mode: number;
+}
+
+interface FakeDoc extends EditorDocument {
+ _objs: Map<number, FakeObj>;
+ _onPage: Set<number>;
+ _order: number[];
+}
+
+function makeDoc(): { doc: FakeDoc; page: Page } {
+ const page = new Page({ index: 0, pagePtr: 1, width: 612, height: 792 });
+ page.loaded = true;
+ const objs = new Map<number, FakeObj>();
+ const onPage = new Set<number>();
+ /** Page order, which index-based z-order calls need on top of the set. */
+ const order: number[] = [];
+ const heap = new Map<number, number>();
+ let nextPtr = 100;
+ let nextAddr = 8;
+
+ const module = {
+ FPDFPageObj_CreateNewRect: (x: number, y: number) => {
+ const ptr = nextPtr++;
+ objs.set(ptr, {
+ ptr,
+ kind: "rect",
+ dx: x,
+ dy: y,
+ sx: 1,
+ sy: 1,
+ text: "",
+ fill: [0, 0, 0, 255],
+ mode: 0,
+ });
+ return ptr;
+ },
+ FPDFPageObj_NewTextObj: () => {
+ const ptr = nextPtr++;
+ objs.set(ptr, {
+ ptr,
+ kind: "text",
+ dx: 0,
+ dy: 0,
+ sx: 1,
+ sy: 1,
+ text: "",
+ fill: [0, 0, 0, 255],
+ mode: 0,
+ });
+ return ptr;
+ },
+ FPDFText_SetText: (ptr: number) => {
+ const o = objs.get(ptr);
+ if (o) o.text = "set";
+ return true;
+ },
+ FPDFPageObj_SetFillColor: (
+ ptr: number,
+ r: number,
+ g: number,
+ b: number,
+ a: number,
+ ) => {
+ const o = objs.get(ptr);
+ if (o) o.fill = [r, g, b, a];
+ return true;
+ },
+ FPDFPageObj_GetFillColor: (
+ ptr: number,
+ r: number,
+ g: number,
+ b: number,
+ a: number,
+ ) => {
+ const o = objs.get(ptr);
+ if (!o) return false;
+ heap.set(r, o.fill[0]);
+ heap.set(g, o.fill[1]);
+ heap.set(b, o.fill[2]);
+ heap.set(a, o.fill[3]);
+ return true;
+ },
+ FPDFTextObj_GetTextRenderMode: (ptr: number) => objs.get(ptr)?.mode ?? 0,
+ FPDFTextObj_SetTextRenderMode: (ptr: number, mode: number) => {
+ const o = objs.get(ptr);
+ if (o) o.mode = mode;
+ return true;
+ },
+ FPDFPageObj_GetType: (ptr: number) =>
+ objs.get(ptr)?.kind === "text" ? 1 : 2,
+ FPDFPage_CountObjects: () => order.length,
+ FPDFPage_GetObject: (_p: number, i: number) => order[i] ?? 0,
+ FPDFPage_InsertObjectAtIndex: (_p: number, ptr: number, i: number) => {
+ onPage.add(ptr);
+ order.splice(Math.min(Math.max(i, 0), order.length), 0, ptr);
+ return true;
+ },
+ // No wasm heap behind the out-params here, so report "cannot measure" and
+ // let the caller fall back - the same path a build without the accessor
+ // takes.
+ FPDFPageObj_GetBounds: () => false,
+ FPDFPath_SetDrawMode: () => true,
+ FPDFPageObj_Transform: (
+ ptr: number,
+ a: number,
+ _b: number,
+ _c: number,
+ d: number,
+ e: number,
+ f: number,
+ ) => {
+ const o = objs.get(ptr);
+ if (o) {
+ o.dx += e;
+ o.dy += f;
+ o.sx *= a;
+ o.sy *= d;
+ }
+ },
+ FPDFPage_InsertObject: (_p: number, ptr: number) => {
+ onPage.add(ptr);
+ order.push(ptr);
+ },
+ FPDFPage_RemoveObject: (_p: number, ptr: number) => {
+ onPage.delete(ptr);
+ const at = order.indexOf(ptr);
+ if (at >= 0) order.splice(at, 1);
+ return true;
+ },
+ FPDFPageObj_Destroy: (ptr: number) => {
+ objs.delete(ptr);
+ },
+ pdfium: {
+ // A tiny heap, so the out-param accessors can actually round-trip.
+ wasmExports: {
+ malloc: () => {
+ const at = nextAddr;
+ nextAddr += 4;
+ return at;
+ },
+ free: () => {},
+ },
+ getValue: (addr: number) => heap.get(addr) ?? 0,
+ stringToUTF16: () => {},
+ },
+ };
+
+ const doc = {
+ module,
+ docPtr: 1,
+ _objs: objs,
+ _onPage: onPage,
+ _order: order,
+ page: () => page,
+ loadedPages: () => [page],
+ } as unknown as FakeDoc;
+ return { doc, page };
+}
+
+function liveRects(doc: FakeDoc): number {
+ let n = 0;
+ for (const ptr of doc._onPage) {
+ if (doc._objs.get(ptr)?.kind === "rect") n++;
+ }
+ return n;
+}
+
+function ruleShape(rule: PageRuleSnapshot): ShapeObject {
+ return new ShapeObject({
+ id: `shape-${rule.ptr}`,
+ pageIndex: 0,
+ bounds: { x: rule.x, y: rule.y, width: rule.width, height: rule.height },
+ pdfiumObjPtr: rule.ptr,
+ containerPtr: 0,
+ topLevelContainerPtr: 0,
+ containerTransform: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 },
+ });
+}
+
+describe("table commands (fake PDFium)", () => {
+ let doc: FakeDoc;
+ let page: Page;
+
+ beforeEach(() => {
+ ({ doc, page } = makeDoc());
+ });
+
+ function filledTable() {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const model = page.tables[0];
+ const fill = new FillTableCellCommand({
+ tableId: model.id,
+ row: 1,
+ col: 1,
+ text: "Primary",
+ });
+ fill.apply(doc);
+ const extra = emitCellText(doc, page, 240, 655, "Extra", 11)!.run;
+ model.cellExtraRuns[1][1] = [extra.id];
+ return {
+ model,
+ fill,
+ extra,
+ primary: page.findRun(model.cellRuns[1][1]!)!,
+ };
+ }
+
+ it.each(["add-row", "add-col"] as const)(
+ "%s moves every run and keeps cell mappings aligned",
+ (op) => {
+ const { model, primary, extra } = filledTable();
+ const before = {
+ primary: { ...primary.matrix },
+ extra: { ...extra.matrix },
+ };
+ const cmd = new ModifyTableCommand({ tableId: model.id, op, index: 1 });
+ cmd.apply(doc);
+ const row = op === "add-row" ? 2 : 1;
+ const col = op === "add-col" ? 2 : 1;
+ expect(model.runsAt(row, col)).toEqual([primary.id, extra.id]);
+ expect(extra.matrix.e - before.extra.e).toBe(
+ primary.matrix.e - before.primary.e,
+ );
+ expect(extra.matrix.f - before.extra.f).toBe(
+ primary.matrix.f - before.primary.f,
+ );
+ cmd.revert(doc);
+ expect(model.runsAt(1, 1)).toEqual([primary.id, extra.id]);
+ expect(extra.matrix).toEqual(before.extra);
+ },
+ );
+
+ it.each(["delete-row", "delete-col"] as const)(
+ "%s restores the original text objects and earlier undo still works",
+ (op) => {
+ const { model, fill, primary, extra } = filledTable();
+ primary.fontId = "pdf:embedded:CustomFace";
+ const cmd = new ModifyTableCommand({ tableId: model.id, op, index: 1 });
+ cmd.apply(doc);
+ expect(page.runs).toHaveLength(0);
+ expect(doc._onPage.has(extra.pdfiumObjPtr)).toBe(false);
+ cmd.revert(doc);
+ expect(page.findRun(primary.id)).toBe(primary);
+ expect(page.findRun(extra.id)).toBe(extra);
+ expect(primary.fontId).toBe("pdf:embedded:CustomFace");
+ expect(model.runsAt(1, 1)).toEqual([primary.id, extra.id]);
+ fill.revert(doc);
+ expect(page.findRun(primary.id)).toBeUndefined();
+ cmd.apply(doc);
+ cmd.revert(doc);
+ expect(page.findRun(extra.id)).toBe(extra);
+ },
+ );
+
+ it("publishes all runs belonging to a cell", () => {
+ const { model, primary, extra } = filledTable();
+ expect(
+ model.snapshot().cells.find((c) => c.row === 1 && c.col === 1)?.runIds,
+ ).toEqual([primary.id, extra.id]);
+ });
+
+ it("frees replaced ruling objects instead of leaking them on each redraw", () => {
+ const { model } = filledTable();
+ const count = doc._objs.size;
+ for (let i = 0; i < 20; i++) redrawGrid(doc, page, model);
+ expect(doc._objs.size).toBe(count);
+ expect(page.rules).toHaveLength(model.rows + model.cols + 2);
+ expect(page.rules.every((rule) => doc._onPage.has(rule.ptr))).toBe(true);
+ });
+
+ it("drops shape handles pointing at table rules destroyed by a redraw", () => {
+ const { model } = filledTable();
+ const shape = ruleShape(page.rules[0]);
+ page.setShapes([shape]);
+ redrawGrid(doc, page, model);
+ expect(page.shapes).toEqual([]);
+ expect(doc._objs.has(shape.pdfiumObjPtr)).toBe(false);
+ });
+
+ it("moves cached table rules and fills with their shape, including undo", () => {
+ filledTable();
+ const rule = page.rules[0];
+ const shape = ruleShape(rule);
+ page.setShapes([shape]);
+ page.setFills([{ ...rule }]);
+ const command = new MoveShapeCommand({
+ pageIndex: 0,
+ shapeId: shape.id,
+ dx: 15,
+ dy: -20,
+ });
+ command.apply(doc);
+ expect(page.rules[0]).toMatchObject({ x: rule.x + 15, y: rule.y - 20 });
+ expect(page.fills[0]).toMatchObject({ x: rule.x + 15, y: rule.y - 20 });
+ command.revert(doc);
+ expect(page.rules[0]).toEqual(rule);
+ expect(page.fills[0]).toEqual(rule);
+ });
+
+ it("removes deleted shapes from table recognition and restores them on undo", () => {
+ filledTable();
+ const rule = page.rules[0];
+ const shape = ruleShape(rule);
+ page.setShapes([shape]);
+ page.setFills([{ ...rule }]);
+ const command = new DeleteShapeCommand({ pageIndex: 0, shapeId: shape.id });
+ command.apply(doc);
+ expect(page.rules.some((entry) => entry.ptr === rule.ptr)).toBe(false);
+ expect(page.fills).toEqual([]);
+ command.revert(doc);
+ expect(page.rules).toContainEqual(rule);
+ expect(page.fills).toEqual([rule]);
+ expect(page.shapes).toEqual([shape]);
+ });
+
+ it("reuses a filled cell's identity on redo so subsequent text edits still apply", () => {
+ const { model, fill, primary } = filledTable();
+ fill.revert(doc);
+ fill.apply(doc);
+ expect(model.cellRuns[1][1]).toBe(primary.id);
+ expect(page.findRun(primary.id)).toBe(primary);
+ expect(doc._onPage.has(primary.pdfiumObjPtr)).toBe(true);
+ });
+
+ it("scales every run in a cell and exactly restores their origins on undo", () => {
+ const { model, primary, extra } = filledTable();
+ const before = [primary.snapshot(), extra.snapshot()];
+ const cmd = new ResizeTableCommand({
+ tableId: model.id,
+ edit: { kind: "scale", width: 600, height: 180 },
+ });
+ cmd.apply(doc);
+ expect(primary.fontSize).toBe(before[0].fontSize * 2);
+ expect(extra.fontSize).toBe(before[1].fontSize * 2);
+ cmd.revert(doc);
+ expect(primary.matrix).toEqual(before[0].matrix);
+ expect(extra.matrix).toEqual(before[1].matrix);
+ expect(extra.fontSize).toBe(before[1].fontSize);
+ expect(extra.bounds).toEqual(before[1].bounds);
+ });
+
+ it("does not draw separators through a cell merged across both axes", () => {
+ const { model } = filledTable();
+ model.cellSpans[0][0] = { rowSpan: 2, colSpan: 2 };
+ const rectangles = vi.spyOn(doc.module, "FPDFPageObj_CreateNewRect");
+ redrawGrid(doc, page, model);
+ expect(rectangles).toHaveBeenCalledWith(
+ 300,
+ 670 - model.lineWidth / 2,
+ 100,
+ model.lineWidth,
+ );
+ expect(rectangles).toHaveBeenCalledWith(
+ 200 - model.lineWidth / 2,
+ 610,
+ model.lineWidth,
+ 30,
+ );
+ });
+
+ it("keeps a vertical merge anchored on its spanned bottom when moving", () => {
+ const { model, primary, extra } = filledTable();
+ model.cellSpans[1][1] = { rowSpan: 2, colSpan: 1 };
+ const before = { primary: primary.matrix.f, extra: extra.matrix.f };
+ const cmd = new ResizeTableCommand({
+ tableId: model.id,
+ edit: { kind: "move", dx: 0, dy: 10 },
+ });
+ cmd.apply(doc);
+ expect(primary.matrix.f).toBeCloseTo(before.primary + 10);
+ expect(extra.matrix.f).toBeCloseTo(before.extra + 10);
+ cmd.revert(doc);
+ expect(primary.matrix.f).toBeCloseTo(before.primary);
+ expect(extra.matrix.f).toBeCloseTo(before.extra);
+ });
+
+ it("shrinks a merge when deleting its anchor column without losing its content", () => {
+ const { model, primary, extra } = filledTable();
+ model.cellSpans[1][1] = { rowSpan: 1, colSpan: 2 };
+ const cmd = new ModifyTableCommand({
+ tableId: model.id,
+ op: "delete-col",
+ index: 1,
+ });
+ cmd.apply(doc);
+ expect(model.runsAt(1, 1)).toEqual([primary.id, extra.id]);
+ expect(model.spanAt(1, 1).colSpan).toBe(1);
+ cmd.revert(doc);
+ expect(model.spanAt(1, 1).colSpan).toBe(2);
+ expect(model.runsAt(1, 1)).toEqual([primary.id, extra.id]);
+ });
+
+ it("expands a merge for an insertion inside it and restores it on undo", () => {
+ const { model } = filledTable();
+ model.cellSpans[1][1] = { rowSpan: 1, colSpan: 2 };
+ const cmd = new ModifyTableCommand({
+ tableId: model.id,
+ op: "add-col",
+ index: 2,
+ });
+ cmd.apply(doc);
+ expect(model.spanAt(1, 1).colSpan).toBe(3);
+ expect(model.isCovered(1, 2)).toBe(true);
+ cmd.revert(doc);
+ expect(model.spanAt(1, 1).colSpan).toBe(2);
+ });
+
+ it("inserts a 3x3 table with a full ruling grid, and reverts cleanly", () => {
+ const cmd = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ cmd.apply(doc);
+
+ expect(page.tables).toHaveLength(1);
+ const model = page.tables[0];
+ expect(model.rows).toBe(3);
+ expect(model.cols).toBe(3);
+ // (rows+1) horizontal + (cols+1) vertical ruling lines.
+ expect(liveRects(doc)).toBe(4 + 4);
+ expect(model.cellRuns.flat().every((c) => c === null)).toBe(true);
+
+ cmd.revert(doc);
+ expect(page.tables).toHaveLength(0);
+ expect(liveRects(doc)).toBe(0);
+ });
+
+ it("fills an empty cell and links a run, reversibly", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+
+ const fill = new FillTableCellCommand({
+ tableId,
+ row: 1,
+ col: 2,
+ text: "Hi",
+ });
+ fill.apply(doc);
+ expect(page.runs).toHaveLength(1);
+ expect(page.tables[0].cellRuns[1][2]).toBe(page.runs[0].id);
+
+ fill.revert(doc);
+ expect(page.runs).toHaveLength(0);
+ expect(page.tables[0].cellRuns[1][2]).toBeNull();
+ });
+
+ it("adds a row, shifting lower cell content down, and reverts", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ // Content in the last row.
+ new FillTableCellCommand({ tableId, row: 2, col: 0, text: "X" }).apply(doc);
+ const run = page.runs[0];
+ const yBefore = run.matrix.f;
+
+ // Insert a row at the top: the content row moves down by one row height.
+ const rowH = 90 / 3;
+ const add = new ModifyTableCommand({ tableId, op: "add-row", index: 0 });
+ add.apply(doc);
+ expect(page.tables[0].rows).toBe(4);
+ expect(run.matrix.f).toBeCloseTo(yBefore - rowH, 5);
+
+ add.revert(doc);
+ expect(page.tables[0].rows).toBe(3);
+ expect(run.matrix.f).toBeCloseTo(yBefore, 5);
+ });
+
+ it("adds a column, shifting right-hand content, and reverts", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 2,
+ cols: 2,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 0, col: 1, text: "R" }).apply(doc);
+ const run = page.runs[0];
+ const xBefore = run.matrix.e;
+
+ const colW = 300 / 2;
+ const add = new ModifyTableCommand({ tableId, op: "add-col", index: 0 });
+ add.apply(doc);
+ expect(page.tables[0].cols).toBe(3);
+ expect(run.matrix.e).toBeCloseTo(xBefore + colW, 5);
+
+ add.revert(doc);
+ expect(page.tables[0].cols).toBe(2);
+ expect(run.matrix.e).toBeCloseTo(xBefore, 5);
+ });
+
+ it("deletes a row with content and restores it on revert", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 1, col: 0, text: "M" }).apply(doc);
+ expect(page.runs).toHaveLength(1);
+
+ const del = new ModifyTableCommand({ tableId, op: "delete-row", index: 1 });
+ del.apply(doc);
+ expect(page.tables[0].rows).toBe(2);
+ expect(page.runs).toHaveLength(0); // the row's run was removed
+
+ del.revert(doc);
+ expect(page.tables[0].rows).toBe(3);
+ // Content re-emitted and relinked (fresh run id).
+ expect(page.runs).toHaveLength(1);
+ expect(page.tables[0].cellRuns[1][0]).toBe(page.runs[0].id);
+ });
+
+ it("round-trips through the history stack (insert, fill, add-row)", () => {
+ const history = new HistoryStack();
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 2,
+ cols: 2,
+ });
+ history.execute(insert, doc);
+ const tableId = insert.insertedTableId!;
+ history.execute(
+ new FillTableCellCommand({ tableId, row: 0, col: 0, text: "A" }),
+ doc,
+ );
+ history.execute(
+ new ModifyTableCommand({ tableId, op: "add-row", index: 2 }),
+ doc,
+ );
+ expect(page.tables[0].rows).toBe(3);
+ expect(page.runs).toHaveLength(1);
+
+ history.undo(doc); // undo add-row
+ history.undo(doc); // undo fill
+ history.undo(doc); // undo insert
+ expect(page.tables).toHaveLength(0);
+ expect(page.runs).toHaveLength(0);
+ expect(liveRects(doc)).toBe(0);
+
+ history.redo(doc); // redo insert
+ history.redo(doc); // redo fill
+ history.redo(doc); // redo add-row
+ expect(page.tables).toHaveLength(1);
+ expect(page.tables[0].rows).toBe(3);
+ expect(page.runs).toHaveLength(1);
+ });
+
+ it("drags a column edge, carrying that column's text with it", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ // Column 1 spans 200..300; its text sits a padding inset inside that.
+ new FillTableCellCommand({ tableId, row: 0, col: 1, text: "B" }).apply(doc);
+ const runId = page.tables[0].cellRuns[0][1]!;
+ const before = page.findRun(runId)!.bounds.x;
+
+ const resize = new ResizeTableCommand({
+ tableId,
+ edit: { kind: "col-edge", index: 1, x: 240 },
+ });
+ resize.apply(doc);
+
+ expect(page.tables[0].colEdges).toEqual([100, 240, 300, 400]);
+ // Cell 1 now starts 40pt further right, and so does its text.
+ expect(page.findRun(runId)!.bounds.x).toBeCloseTo(before + 40, 5);
+ // The grid is still one line per edge, no leaks.
+ expect(liveRects(doc)).toBe(4 + 4);
+
+ resize.revert(doc);
+ expect(page.tables[0].colEdges).toEqual([100, 200, 300, 400]);
+ expect(page.findRun(runId)!.bounds.x).toBeCloseTo(before, 5);
+ expect(liveRects(doc)).toBe(4 + 4);
+ });
+
+ it("drags a row edge, carrying that row's text with it", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ // Row 1 spans y 670..640; shrinking it from the top lifts its content.
+ new FillTableCellCommand({ tableId, row: 1, col: 0, text: "B" }).apply(doc);
+ const runId = page.tables[0].cellRuns[1][0]!;
+ const before = page.findRun(runId)!.bounds.y;
+
+ const resize = new ResizeTableCommand({
+ tableId,
+ edit: { kind: "row-edge", index: 2, y: 650 },
+ });
+ resize.apply(doc);
+
+ expect(page.tables[0].rowEdges).toEqual([700, 670, 650, 610]);
+ // Row 1's bottom moved up 10pt, so its text goes with it.
+ expect(page.findRun(runId)!.bounds.y).toBeCloseTo(before + 10, 5);
+
+ resize.revert(doc);
+ expect(page.tables[0].rowEdges).toEqual([700, 670, 640, 610]);
+ expect(page.findRun(runId)!.bounds.y).toBeCloseTo(before, 5);
+ });
+
+ it("scales the whole table and undoes back to the original geometry", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 2, col: 2, text: "C" }).apply(doc);
+ const runId = page.tables[0].cellRuns[2][2]!;
+ const run = page.findRun(runId)!;
+ const before = { x: run.bounds.x, y: run.bounds.y };
+
+ const history = new HistoryStack();
+ const resize = new ResizeTableCommand({
+ tableId,
+ edit: { kind: "scale", width: 600, height: 180 },
+ });
+ history.execute(resize, doc);
+
+ expect(page.tables[0].colEdges).toEqual([100, 300, 500, 700]);
+ expect(page.tables[0].rowEdges).toEqual([700, 640, 580, 520]);
+ // The bottom-right cell moved out with its corner.
+ expect(page.findRun(runId)!.bounds.x).toBeGreaterThan(before.x);
+ expect(page.findRun(runId)!.bounds.y).toBeLessThan(before.y);
+
+ history.undo(doc);
+ expect(page.tables[0].colEdges).toEqual([100, 200, 300, 400]);
+ expect(page.tables[0].rowEdges).toEqual([700, 670, 640, 610]);
+ expect(page.findRun(runId)!.bounds.x).toBeCloseTo(before.x, 5);
+ expect(page.findRun(runId)!.bounds.y).toBeCloseTo(before.y, 5);
+ expect(liveRects(doc)).toBe(4 + 4);
+ });
+
+ it("stretches an adopted row background when the table widens", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const model = page.tables[0];
+
+ // A header shading box covering row 0, as adoption would have bound it.
+ const fillPtr = doc.module.FPDFPageObj_CreateNewRect(100, 670, 300, 30);
+ model.rowFills = [
+ {
+ row: 0,
+ ptr: fillPtr,
+ rect: { x: 100, y: 670, width: 300, height: 30 },
+ color: { r: 200, g: 205, b: 215, a: 255 },
+ },
+ ];
+
+ new ModifyTableCommand({
+ tableId: model.id,
+ op: "add-col",
+ index: 3,
+ }).apply(doc);
+
+ // The table is now 400 wide, and the background covers all of it.
+ expect(model.colEdges[model.cols] - model.colEdges[0]).toBeCloseTo(400, 5);
+ expect(model.rowFills[0].rect.width).toBeCloseTo(400, 5);
+ expect(model.rowFills[0].rect.x).toBeCloseTo(100, 5);
+ // Widened by transform, not redrawn - that is what keeps it behind the text.
+ expect(doc._objs.get(fillPtr)!.sx).toBeCloseTo(400 / 300, 5);
+ expect(doc._objs.get(fillPtr)!.sy).toBeCloseTo(1, 5);
+ });
+
+ it("leaves a row background alone when the geometry does not move", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const model = page.tables[0];
+ const fillPtr = doc.module.FPDFPageObj_CreateNewRect(100, 670, 300, 30);
+ model.rowFills = [
+ {
+ row: 0,
+ ptr: fillPtr,
+ rect: { x: 100, y: 670, width: 300, height: 30 },
+ color: { r: 200, g: 205, b: 215, a: 255 },
+ },
+ ];
+ const before = { ...doc._objs.get(fillPtr)! };
+
+ redrawGrid(doc, page, model);
+
+ expect(doc._objs.get(fillPtr)!.sx).toBe(before.sx);
+ expect(doc._objs.get(fillPtr)!.dx).toBe(before.dx);
+ });
+
+ it("scales the cell text with the frame, and undo puts the size back", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 1, col: 1, text: "Hi" }).apply(
+ doc,
+ );
+ const model = page.tables[0];
+ const runId = model.cellRuns[1][1]!;
+ const sizeBefore = page.findRun(runId)!.fontSize;
+ const colSizeBefore = model.columnStyles[1].fontSize;
+
+ const history = new HistoryStack();
+ // Half the width, half the height: text has to come down with it or it
+ // spills over the column beside it.
+ history.execute(
+ new ResizeTableCommand({
+ tableId,
+ edit: { kind: "scale", width: 150, height: 45 },
+ }),
+ doc,
+ );
+
+ expect(page.findRun(runId)!.fontSize).toBeCloseTo(sizeBefore / 2, 5);
+ // New cells typed after the resize match what is now in the table.
+ expect(model.columnStyles[1].fontSize).toBeCloseTo(colSizeBefore / 2, 5);
+
+ history.undo(doc);
+ expect(page.findRun(runId)!.fontSize).toBeCloseTo(sizeBefore, 5);
+ expect(model.columnStyles[1].fontSize).toBeCloseTo(colSizeBefore, 5);
+ expect(model.colEdges).toEqual([100, 200, 300, 400]);
+ });
+
+ it("moves an edge without touching the text size", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 1, col: 1, text: "Hi" }).apply(
+ doc,
+ );
+ const runId = page.tables[0].cellRuns[1][1]!;
+ const sizeBefore = page.findRun(runId)!.fontSize;
+
+ new ResizeTableCommand({
+ tableId,
+ edit: { kind: "col-edge", index: 1, x: 240 },
+ }).apply(doc);
+
+ // Only a whole-table scale resizes type; dragging one boundary must not.
+ expect(page.findRun(runId)!.fontSize).toBe(sizeBefore);
+ });
+
+ it("keeps the text size stable across repeated grow/shrink cycles", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 1, col: 1, text: "Hi" }).apply(
+ doc,
+ );
+ const runId = page.tables[0].cellRuns[1][1]!;
+ const original = page.findRun(runId)!.fontSize;
+
+ // Grow and shrink with DIFFERENT ratios per axis - the case where taking
+ // the tighter axis per gesture used to ratchet the type down every cycle.
+ for (let i = 0; i < 6; i++) {
+ new ResizeTableCommand({
+ tableId,
+ edit: { kind: "scale", width: 450, height: 108 },
+ }).apply(doc);
+ new ResizeTableCommand({
+ tableId,
+ edit: { kind: "scale", width: 300, height: 90 },
+ }).apply(doc);
+ }
+
+ expect(page.tables[0].colEdges).toEqual([100, 200, 300, 400]);
+ expect(page.findRun(runId)!.fontSize).toBeCloseTo(original, 5);
+ });
+
+ it("does not resize text when a row is added and removed", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 0, col: 0, text: "A" }).apply(doc);
+ const runId = page.tables[0].cellRuns[0][0]!;
+ const original = page.findRun(runId)!.fontSize;
+
+ // Structural edits change the table's extent; the font reference has to
+ // follow, or the next scale would try to correct for them.
+ new ModifyTableCommand({ tableId, op: "add-row", index: 3 }).apply(doc);
+ new ModifyTableCommand({ tableId, op: "add-col", index: 3 }).apply(doc);
+ new ResizeTableCommand({
+ tableId,
+ edit: { kind: "scale", width: 400, height: 120 },
+ }).apply(doc);
+ new ResizeTableCommand({
+ tableId,
+ edit: {
+ kind: "scale",
+ width: page.tables[0].fontBase.width,
+ height: page.tables[0].fontBase.height,
+ },
+ }).apply(doc);
+
+ expect(page.findRun(runId)!.fontSize).toBeCloseTo(original, 5);
+ });
+
+ it("moves the whole table, carrying its text and background, reversibly", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 1, col: 1, text: "Hi" }).apply(
+ doc,
+ );
+ const model = page.tables[0];
+ const runId = model.cellRuns[1][1]!;
+ const fillPtr = doc.module.FPDFPageObj_CreateNewRect(100, 670, 300, 30);
+ model.rowFills = [
+ {
+ row: 0,
+ ptr: fillPtr,
+ rect: { x: 100, y: 670, width: 300, height: 30 },
+ color: { r: 200, g: 205, b: 215, a: 255 },
+ },
+ ];
+ const before = {
+ cols: [...model.colEdges],
+ rows: [...model.rowEdges],
+ runX: page.findRun(runId)!.matrix.e,
+ runY: page.findRun(runId)!.matrix.f,
+ size: page.findRun(runId)!.fontSize,
+ };
+
+ const move = new ResizeTableCommand({
+ tableId,
+ edit: { kind: "move", dx: 40, dy: -25 },
+ });
+ move.apply(doc);
+
+ expect(model.colEdges).toEqual(before.cols.map((x) => x + 40));
+ expect(model.rowEdges).toEqual(before.rows.map((y) => y - 25));
+ // Text travels with the grid, at the same size - a move is not a resize.
+ expect(page.findRun(runId)!.matrix.e).toBeCloseTo(before.runX + 40, 5);
+ expect(page.findRun(runId)!.matrix.f).toBeCloseTo(before.runY - 25, 5);
+ expect(page.findRun(runId)!.fontSize).toBe(before.size);
+ // And so does the row background.
+ expect(model.rowFills[0].rect.x).toBeCloseTo(140, 5);
+
+ move.revert(doc);
+ expect(model.colEdges).toEqual(before.cols);
+ expect(model.rowEdges).toEqual(before.rows);
+ expect(page.findRun(runId)!.matrix.e).toBeCloseTo(before.runX, 5);
+ expect(page.findRun(runId)!.matrix.f).toBeCloseTo(before.runY, 5);
+ });
+
+ it("keeps merged cells when the editor redraws the grid", () => {
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const model = page.tables[0];
+ // Row 0 merges columns 0-1, as an adopted table would record it.
+ model.cellSpans[0][0] = { rowSpan: 1, colSpan: 2 };
+
+ // A covered position is not a cell of its own, and the anchor's rect
+ // reaches across the merge.
+ expect(model.isCovered(0, 1)).toBe(true);
+ expect(model.isCovered(1, 1)).toBe(false);
+ expect(model.cellRect(0, 0).width).toBeCloseTo(200, 5);
+ const snap = model.snapshot();
+ expect(snap.cells.filter((c) => c.row === 0)).toHaveLength(2);
+ expect(snap.cells.find((c) => c.row === 0 && c.col === 0)?.colSpan).toBe(2);
+
+ // Redrawing must not paint a boundary through the merge. A plain grid
+ // would emit 4 horizontals + 4 verticals; here the vertical between
+ // columns 0 and 1 is drawn for 2 of the 3 rows, so it arrives as one
+ // shorter segment instead of a full-height line.
+ const before = liveRects(doc);
+ redrawGrid(doc, page, model);
+ expect(liveRects(doc)).toBe(before);
+ new ModifyTableCommand({
+ tableId: model.id,
+ op: "add-row",
+ index: 3,
+ }).apply(doc);
+ // The merge survives a structural edit.
+ expect(model.cellSpans[0][0]).toEqual({ rowSpan: 1, colSpan: 2 });
+ expect(model.isCovered(0, 1)).toBe(true);
+ });
+
+ it("moves every object a run is built from, not just the first", () => {
+ // A paragraph run groups several text objects. Moving only the
+ // representative strands the rest - the "Q1 Sales" / "North America"
+ // fragments left behind when a scanned table was dragged.
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 100,
+ y: 700,
+ width: 300,
+ height: 90,
+ rows: 3,
+ cols: 3,
+ });
+ insert.apply(doc);
+ const tableId = insert.insertedTableId!;
+ new FillTableCellCommand({ tableId, row: 1, col: 1, text: "Hi" }).apply(
+ doc,
+ );
+ const model = page.tables[0];
+ const run = page.findRun(model.cellRuns[1][1]!)!;
+ // A second text object belonging to the same run, as grouping produces.
+ const extraPtr = doc.module.FPDFPageObj_NewTextObj(1, "Helvetica", 10);
+ run.paragraphLeafPtrs = [run.pdfiumObjPtr, extraPtr];
+ const before = doc._objs.get(extraPtr)!.dx;
+
+ new ResizeTableCommand({
+ tableId,
+ edit: { kind: "move", dx: 30, dy: -20 },
+ }).apply(doc);
+
+ expect(doc._objs.get(extraPtr)!.dx).toBeCloseTo(before + 30, 5);
+ expect(doc._objs.get(extraPtr)!.dy).toBeCloseTo(-20, 5);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts
new file mode 100644
index 0000000000..16c6e1c7aa
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts
@@ -0,0 +1,649 @@
+import { describe, it, expect } from "vitest";
+import {
+ bandByRules,
+ clusterRowPins,
+ columnPins,
+ detectTables,
+ rowPins,
+ rowSpans,
+} from "@app/tools/pdfTextEditor/util/tableDetection";
+import type { TextRunSnapshot } from "@app/tools/pdfTextEditor/types";
+
+let seq = 0;
+function run(
+ x: number,
+ y: number,
+ width: number,
+ text: string,
+ extra: Partial<TextRunSnapshot> = {},
+): TextRunSnapshot {
+ return {
+ id: `r${seq++}`,
+ pageIndex: 0,
+ bounds: { x, y, width, height: 12 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: x, f: y },
+ text,
+ fontId: "base14:Helvetica",
+ fontSize: 12,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ ...extra,
+ };
+}
+
+// Build a grid: rows top-down at descending y, columns at the given x lefts.
+function grid(
+ xs: number[],
+ topY: number,
+ rowGap: number,
+ cells: string[][],
+): TextRunSnapshot[] {
+ const runs: TextRunSnapshot[] = [];
+ cells.forEach((rowCells, r) => {
+ const y = topY - r * rowGap;
+ rowCells.forEach((text, c) => {
+ if (text) runs.push(run(xs[c], y, 60, text));
+ });
+ });
+ return runs;
+}
+
+describe("detectTables", () => {
+ it("returns nothing for empty input", () => {
+ expect(detectTables([], 0)).toEqual([]);
+ });
+
+ it("recognizes a clean 3x3 invoice grid", () => {
+ const runs = grid([50, 200, 350], 700, 20, [
+ ["Item", "Qty", "Price"],
+ ["Widget", "2", "$10.00"],
+ ["Gadget", "5", "$25.00"],
+ ]);
+ const tables = detectTables(runs, 0);
+ expect(tables).toHaveLength(1);
+ const t = tables[0];
+ expect(t.rows).toBe(3);
+ expect(t.cols).toBe(3);
+ expect(t.cells).toHaveLength(9);
+ // Header row cells map to the right runs.
+ const a1 = t.cells.find((c) => c.row === 0 && c.col === 0);
+ expect(a1?.runIds).toHaveLength(1);
+ expect(t.colEdges).toHaveLength(4);
+ expect(t.rowEdges).toHaveLength(4);
+ });
+
+ it("does not treat a paragraph of prose as a table", () => {
+ // One run per line, all starting at the same left margin: a single column.
+ const runs: TextRunSnapshot[] = [];
+ for (let i = 0; i < 6; i++) {
+ runs.push(run(72, 700 - i * 16, 400, `Line ${i} of ordinary prose text`));
+ }
+ expect(detectTables(runs, 0)).toEqual([]);
+ });
+
+ it("separates two tables split by a large vertical gap", () => {
+ const top = grid([50, 200], 700, 18, [
+ ["A", "B"],
+ ["C", "D"],
+ ]);
+ // 200pt gap below the first table.
+ const bottom = grid([50, 200], 460, 18, [
+ ["E", "F"],
+ ["G", "H"],
+ ]);
+ const tables = detectTables([...top, ...bottom], 0);
+ expect(tables).toHaveLength(2);
+ expect(tables[0].bounds.y).toBeGreaterThan(tables[1].bounds.y);
+ });
+
+ it("detects the table but ignores a heading and trailing paragraph", () => {
+ const heading = [run(72, 760, 300, "Quarterly Results")];
+ const table = grid([72, 220, 380], 700, 20, [
+ ["Region", "Q1", "Q2"],
+ ["North", "100", "120"],
+ ["South", "90", "110"],
+ ]);
+ const paragraph: TextRunSnapshot[] = [];
+ for (let i = 0; i < 3; i++) {
+ paragraph.push(
+ run(72, 560 - i * 16, 420, `Footnote line ${i} explaining`),
+ );
+ }
+ const tables = detectTables([...heading, ...table, ...paragraph], 0);
+ expect(tables).toHaveLength(1);
+ expect(tables[0].rows).toBe(3);
+ expect(tables[0].cols).toBe(3);
+ });
+
+ it("tolerates slight baseline drift within a row", () => {
+ const runs = [
+ run(50, 701, 60, "Name"),
+ run(200, 699, 60, "Score"),
+ run(50, 681, 60, "Alice"),
+ run(200, 680, 60, "42"),
+ run(50, 660, 60, "Bob"),
+ run(200, 661, 60, "37"),
+ ];
+ const tables = detectTables(runs, 0);
+ expect(tables).toHaveLength(1);
+ expect(tables[0].rows).toBe(3);
+ expect(tables[0].cols).toBe(2);
+ });
+
+ it("ignores multi-line paragraph runs as cell content", () => {
+ const runs = grid([50, 200], 700, 20, [
+ ["A", "B"],
+ ["C", "D"],
+ ]);
+ runs[0] = { ...runs[0], paragraphLineCount: 4 };
+ // With one corner run consumed by a paragraph, the grid loses a column in
+ // that row but the remaining rows still form a 2-col table.
+ const tables = detectTables(runs, 0);
+ expect(tables.length).toBeLessThanOrEqual(1);
+ });
+
+ it("recognizes right-aligned numeric columns (varying left edges)", () => {
+ // Label column left-aligned at x=60; amount column right-aligned to x=300.
+ const runs = [
+ run(60, 700, 80, "Opening balance"),
+ run(285, 700, 15, "5"),
+ run(60, 680, 80, "Deposits"),
+ run(255, 680, 45, "1,200"),
+ run(60, 660, 80, "Fees"),
+ run(272, 660, 28, "37"),
+ ];
+ const tables = detectTables(runs, 0);
+ expect(tables).toHaveLength(1);
+ expect(tables[0].cols).toBe(2);
+ expect(tables[0].rows).toBe(3);
+ // All three amounts land in the second column.
+ const col1Runs = tables[0].cells
+ .filter((c) => c.col === 1)
+ .flatMap((c) => c.runIds);
+ expect(col1Runs).toHaveLength(3);
+ });
+
+ it("handles a wide 4-column table with a partially empty row", () => {
+ const runs = grid([40, 140, 260, 400], 700, 18, [
+ ["SKU", "Name", "Qty", "Total"],
+ ["001", "Bolt", "10", "$5"],
+ ["002", "Nut", "", "$3"],
+ ["003", "Washer", "20", "$8"],
+ ]);
+ const tables = detectTables(runs, 0);
+ expect(tables).toHaveLength(1);
+ expect(tables[0].cols).toBe(4);
+ expect(tables[0].rows).toBe(4);
+ });
+
+ // A column merged into one paragraph run, exactly as the editor's grouping
+ // hands it over: one run, N lines, real baselines and lefts.
+ function column(
+ lines: string[],
+ left: number,
+ topBaseline: number,
+ lineGap: number,
+ width: number,
+ lefts?: number[],
+ ): TextRunSnapshot {
+ const baselines = lines.map((_, i) => topBaseline - i * lineGap);
+ const bottom = baselines[baselines.length - 1] - 2;
+ const height = topBaseline + 10 - bottom;
+ return run(left, bottom, width, lines.join("\n"), {
+ bounds: { x: left, y: bottom, width, height },
+ paragraphLineCount: lines.length,
+ paragraphLineHeight: lineGap,
+ paragraphBaselines: baselines,
+ paragraphLineLefts: lefts ?? lines.map(() => left),
+ });
+ }
+
+ it("splits paragraph-merged columns into per-cell candidates", () => {
+ // Three columns, each arriving as ONE run of four lines - the shape the
+ // editor actually produces for a table.
+ const runs = [
+ column(["Region", "EMEA", "APAC", "LATAM"], 60, 700, 18, 50),
+ column(["2025", "812", "398", "88"], 200, 700, 18, 30),
+ column(["2026", "905", "441", "91"], 320, 700, 18, 30),
+ ];
+ const [table] = detectTables(runs, 0);
+ expect(table).toBeDefined();
+ expect({ rows: table.rows, cols: table.cols }).toEqual({
+ rows: 4,
+ cols: 3,
+ });
+ // Every cell is backed by its own line, so all 12 are occupied.
+ expect(table.cells.filter((c) => c.runIds.length > 0)).toHaveLength(12);
+ });
+
+ it("skips a paragraph run with no per-line baselines", () => {
+ const bad = run(60, 600, 50, "a\nb\nc", {
+ paragraphLineCount: 3,
+ bounds: { x: 60, y: 600, width: 50, height: 54 },
+ });
+ expect(detectTables([bad, run(200, 640, 30, "x")], 0)).toEqual([]);
+ });
+
+ it("keeps a left-aligned header and its right-aligned numbers in one column", () => {
+ // The header sits left in the band, the values right, with clear whitespace
+ // between them - that gap must not split the column in two.
+ const runs = [
+ column(["Region", "EMEA", "APAC"], 60, 700, 18, 50),
+ run(200, 692, 12, "Q1"),
+ column(["812,400", "398,220"], 228, 682, 18, 38),
+ run(300, 692, 12, "Q2"),
+ column(["905,120", "441,000"], 328, 682, 18, 38),
+ ];
+ const [table] = detectTables(runs, 0);
+ expect(table).toBeDefined();
+ expect(table.cols).toBe(3);
+ });
+
+ it("drops a heading above the grid and prose below it", () => {
+ const runs = [
+ run(60, 736, 120, "Table A: Headcount"),
+ ...grid([60, 200, 320], 718, 18, [
+ ["Team", "2025", "2026"],
+ ["Engineering", "22", "31"],
+ ["Design", "4", "6"],
+ ]),
+ run(60, 646, 300, "A sentence that follows the table closely."),
+ ];
+ const [table] = detectTables(runs, 0);
+ expect(table).toBeDefined();
+ expect({ rows: table.rows, cols: table.cols }).toEqual({
+ rows: 3,
+ cols: 3,
+ });
+ });
+
+ // A 3x3 block of single-line cells, used by the snapping tests below.
+ const BLOCK = () =>
+ grid([60, 200, 320], 700, 20, [
+ ["A1", "B1", "C1"],
+ ["A2", "B2", "C2"],
+ ["A3", "B3", "C3"],
+ ]);
+
+ /** A hairline rule box: vertical at x, or horizontal at y. */
+ const vRule = (x: number, from: number, to: number) => ({
+ x: x - 0.25,
+ y: from,
+ width: 0.5,
+ height: to - from,
+ });
+ const hRule = (y: number, from: number, to: number) => ({
+ x: from,
+ y: y - 0.25,
+ width: to - from,
+ height: 0.5,
+ });
+
+ it("gives the outer edges the same margin as the gaps between tracks", () => {
+ const [table] = detectTables(BLOCK(), 0);
+ // Text spans x 60..380; the boundary must clear it, not sit on the glyphs.
+ expect(table.colEdges[0]).toBeLessThan(60);
+ expect(table.colEdges[table.cols]).toBeGreaterThan(380);
+ expect(table.pageRuled).toBe(false);
+ });
+
+ it("snaps the grid onto the rules the page actually draws", () => {
+ const rules = [
+ vRule(50, 640, 730),
+ vRule(150, 640, 730),
+ vRule(300, 640, 730),
+ vRule(400, 640, 730),
+ hRule(716, 40, 420),
+ hRule(696, 40, 420),
+ hRule(676, 40, 420),
+ hRule(656, 40, 420),
+ ];
+ const [table] = detectTables(BLOCK(), 0, {}, rules);
+ expect(table.colEdges).toEqual([50, 150, 300, 400]);
+ expect(table.rowEdges).toEqual([716, 696, 676, 656]);
+ // Cells follow the drawn grid, so the overlay lands on the printed lines.
+ expect(table.bounds.x).toBe(50);
+ expect(table.bounds.width).toBe(350);
+ expect(table.pageRuled).toBe(true);
+ });
+
+ it("ignores rules that do not run along the table", () => {
+ // A short underline under one cell, and a rule far above the block.
+ const rules = [vRule(150, 695, 700), hRule(900, 40, 420)];
+ const plain = detectTables(BLOCK(), 0)[0];
+ const withStrays = detectTables(BLOCK(), 0, {}, rules)[0];
+ expect(withStrays.colEdges).toEqual(plain.colEdges);
+ expect(withStrays.rowEdges).toEqual(plain.rowEdges);
+ expect(withStrays.pageRuled).toBe(false);
+ });
+
+ it("keeps the derived grid when the drawn rules are an incomplete set", () => {
+ // One interior rule only: snap that edge, leave the rest, claim nothing.
+ const rules = [vRule(150, 640, 730)];
+ const table = detectTables(BLOCK(), 0, {}, rules)[0];
+ expect(table.colEdges).toContain(150);
+ expect(table.cols).toBe(3);
+ expect(table.pageRuled).toBe(false);
+ });
+
+ it("joins the per-cell edges of a stroked grid into whole rules", () => {
+ // Word and Chrome stroke a rectangle per cell, so each boundary arrives in
+ // one-row pieces. Unjoined, no piece spans enough of the table to count.
+ const rules = [];
+ const xs = [50, 150, 300, 400];
+ const ys = [716, 696, 676, 656];
+ for (let r = 0; r < ys.length - 1; r++) {
+ for (let c = 0; c < xs.length - 1; c++) {
+ rules.push(vRule(xs[c], ys[r + 1], ys[r]));
+ rules.push(vRule(xs[c + 1], ys[r + 1], ys[r]));
+ rules.push(hRule(ys[r], xs[c], xs[c + 1]));
+ rules.push(hRule(ys[r + 1], xs[c], xs[c + 1]));
+ }
+ }
+ const [table] = detectTables(BLOCK(), 0, {}, rules);
+ expect(table.colEdges).toEqual(xs);
+ expect(table.rowEdges).toEqual(ys);
+ expect(table.pageRuled).toBe(true);
+ });
+
+ it("refuses a rule set that does not separate the columns", () => {
+ // Four verticals, but bunched to one side: the right count, the wrong
+ // places. Adopting them would put several columns in one cell. All sit
+ // further than the snap tolerance from any derived edge, so none is taken.
+ const rules = [
+ vRule(45, 640, 730),
+ vRule(55, 640, 730),
+ vRule(65, 640, 730),
+ vRule(460, 640, 730),
+ ];
+ const plain = detectTables(BLOCK(), 0)[0];
+ const table = detectTables(BLOCK(), 0, {}, rules)[0];
+ expect(table.colEdges).toEqual(plain.colEdges);
+ expect(table.cols).toBe(3);
+ expect(table.pageRuled).toBe(false);
+ });
+
+ it("gives each row its own extent when a column is one merged run", () => {
+ // The whole column arrives as ONE paragraph run. Taking the run's box as
+ // the row's extent collapsed every row onto the same top and bottom, and
+ // the derived edges came out identical - a grid of zero-height rows.
+ const runs = [
+ column(["Team", "Engineering", "Design", "Support"], 60, 700, 18, 60),
+ column(["2025", "22", "4", "7"], 200, 700, 18, 30),
+ column(["2026", "31", "6", "9"], 320, 700, 18, 30),
+ ];
+ const [table] = detectTables(runs, 0);
+ expect(table.rows).toBe(4);
+ const gaps = table.rowEdges
+ .slice(0, -1)
+ .map((y, i) => y - table.rowEdges[i + 1]);
+ for (const gap of gaps) expect(gap).toBeGreaterThan(1);
+ expect(new Set(table.rowEdges).size).toBe(table.rowEdges.length);
+ });
+
+ it("ignores the rules of a second table further down the page", () => {
+ // Another table below has rules just as wide as this one's. Spanning the
+ // width is not enough - they must sit within this table to be its own.
+ const rules = [
+ hRule(716, 40, 420),
+ hRule(696, 40, 420),
+ hRule(676, 40, 420),
+ hRule(656, 40, 420),
+ hRule(500, 40, 420),
+ hRule(480, 40, 420),
+ hRule(460, 40, 420),
+ hRule(440, 40, 420),
+ vRule(50, 640, 730),
+ vRule(150, 640, 730),
+ vRule(300, 640, 730),
+ vRule(400, 640, 730),
+ ];
+ const [table] = detectTables(BLOCK(), 0, {}, rules);
+ expect(table.rowEdges).toEqual([716, 696, 676, 656]);
+ expect(table.pageRuled).toBe(true);
+ });
+
+ it("detects a generously spaced table", () => {
+ // Rows five times the type size apart - a form, a padded invoice, or the
+ // text layer over a scan. Splitting on a fixed multiple of the type size
+ // cut every one of these into single rows and found nothing.
+ const runs = grid([60, 200, 320], 700, 44, [
+ ["Region", "Q1", "Q2"],
+ ["EMEA", "812", "905"],
+ ["APAC", "398", "441"],
+ ["LATAM", "88", "91"],
+ ]);
+ const [table] = detectTables(runs, 0);
+ expect(table).toBeDefined();
+ expect({ rows: table.rows, cols: table.cols }).toEqual({
+ rows: 4,
+ cols: 3,
+ });
+ });
+
+ it("still splits where the gap breaks the table's own rhythm", () => {
+ // Three tight rows, then a jump several times their spacing: two tables.
+ const runs = [
+ ...grid([60, 200, 320], 700, 18, [
+ ["A", "1", "2"],
+ ["B", "3", "4"],
+ ["C", "5", "6"],
+ ]),
+ ...grid([60, 200, 320], 500, 18, [
+ ["D", "7", "8"],
+ ["E", "9", "10"],
+ ]),
+ ];
+ expect(detectTables(runs, 0)).toHaveLength(2);
+ });
+
+ it("reads merged cells from the boundaries the page leaves undrawn", () => {
+ // 4 columns. The boundary at x=150 is drawn only across row 1, and the one
+ // at x=300 is missing from row 2 - so row 0 merges cols 0-1, and row 2
+ // merges 0-1 and 2-3. This is the shape of a real banded, merged table.
+ const rows = [
+ { cands: [], cy: 706, top: 716, bottom: 696 },
+ { cands: [], cy: 686, top: 696, bottom: 676 },
+ { cands: [], cy: 666, top: 676, bottom: 656 },
+ ];
+ const lines = [
+ { at: 50, from: 656, to: 716 },
+ { at: 150, from: 676, to: 696 },
+ { at: 300, from: 696, to: 716 },
+ { at: 300, from: 676, to: 696 },
+ { at: 400, from: 656, to: 716 },
+ ];
+ const pins = columnPins(lines, rows, 50, 400);
+ expect(pins.map((p) => p.at)).toEqual([50, 150, 300, 400]);
+ expect([...pins[1].rows]).toEqual([1]);
+
+ expect(rowSpans(pins, 3, 0)).toEqual([
+ { start: 0, span: 2 },
+ { start: 2, span: 1 },
+ ]);
+ expect(rowSpans(pins, 3, 1)).toEqual([
+ { start: 0, span: 1 },
+ { start: 1, span: 1 },
+ { start: 2, span: 1 },
+ ]);
+ expect(rowSpans(pins, 3, 2)).toEqual([{ start: 0, span: 3 }]);
+ });
+
+ it("keeps the drawn columns when merged labels bridge the text bands", () => {
+ const xs = [36, 132, 321, 393, 473, 576];
+ const ys = [641, 607, 569, 515, 473, 431, 377, 339];
+ const cells = [
+ ["Workstream", "Task", "Owner", "State", "Hours"],
+ ["North programme", "", "Ada", "Active", "18.5"],
+ ["Ops", "Archive intake\nBox 01 to Box 12", "Lin", "Ready", "7.0"],
+ ["", "Metadata review", "Sam", "Review", "12.5"],
+ ["QA", "Needs sign-off", "Jo", "Hold", "4.0"],
+ ["Docs", "Export proof\nKeep both lines", "May", "", "3.25"],
+ ["Shared checkpoint", "", "", "Review", "45.25"],
+ ];
+ const spans = [
+ { row: 1, col: 0, rowSpan: 1, colSpan: 2 },
+ { row: 2, col: 0, rowSpan: 2, colSpan: 1 },
+ { row: 6, col: 0, rowSpan: 1, colSpan: 3 },
+ ];
+ const runs: TextRunSnapshot[] = [];
+ for (const [r, row] of cells.entries()) {
+ for (const [c, text] of row.entries()) {
+ if (!text) continue;
+ const span = spans.find((s) => s.row === r && s.col === c);
+ const centre = (ys[r] + ys[r + (span?.rowSpan ?? 1)]) / 2;
+ const lines = text.split("\n");
+ for (const [line, value] of lines.entries()) {
+ const width = value.length * 5.5;
+ const x = c === 4 && r > 0 ? xs[c + 1] - 10 - width : xs[c] + 10;
+ const y = centre - 6 + ((lines.length - 1) / 2 - line) * 14;
+ runs.push(run(x, y, width, value));
+ }
+ }
+ }
+ const rules = [];
+ for (let c = 0; c < xs.length; c++) {
+ for (let r = 0; r < cells.length; r++) {
+ if (
+ spans.some(
+ (s) =>
+ s.row <= r &&
+ r < s.row + s.rowSpan &&
+ s.col < c &&
+ c < s.col + s.colSpan,
+ )
+ )
+ continue;
+ rules.push(vRule(xs[c], ys[r + 1], ys[r]));
+ }
+ }
+ for (let r = 0; r < ys.length; r++) {
+ for (let c = 0; c < xs.length - 1; c++) {
+ if (
+ spans.some(
+ (s) =>
+ s.row < r &&
+ r < s.row + s.rowSpan &&
+ s.col <= c &&
+ c < s.col + s.colSpan,
+ )
+ )
+ continue;
+ rules.push(hRule(ys[r], xs[c], xs[c + 1]));
+ }
+ }
+ const [table] = detectTables(runs, 0, {}, rules);
+ expect({
+ rows: table.rows,
+ cols: table.cols,
+ pageRuled: table.pageRuled,
+ }).toEqual({
+ rows: 7,
+ cols: 5,
+ pageRuled: true,
+ });
+ expect(table.colEdges).toEqual(xs);
+ expect(table.rowEdges).toEqual(ys);
+ expect(
+ table.cells
+ .filter((c) => c.rowSpan > 1 || c.colSpan > 1)
+ .map((c) => ({
+ row: c.row,
+ col: c.col,
+ rowSpan: c.rowSpan,
+ colSpan: c.colSpan,
+ })),
+ ).toEqual(spans);
+ expect(
+ table.cells.find((c) => c.row === 2 && c.col === 1)?.runIds,
+ ).toHaveLength(2);
+ });
+
+ it("keeps a boundary that only crosses part of the table", () => {
+ // The old rule - at least half the table's height - threw this away, and
+ // with it the whole merge structure.
+ const rows = [
+ { cands: [], cy: 706, top: 716, bottom: 696 },
+ { cands: [], cy: 686, top: 696, bottom: 676 },
+ { cands: [], cy: 666, top: 676, bottom: 656 },
+ { cands: [], cy: 646, top: 656, bottom: 636 },
+ ];
+ const pins = columnPins([{ at: 150, from: 676, to: 696 }], rows, 50, 400);
+ expect(pins).toHaveLength(1);
+ expect([...pins[0].rows]).toEqual([1]);
+ });
+
+ it("ignores a rule that crosses no row band at all", () => {
+ const rows = [{ cands: [], cy: 706, top: 716, bottom: 696 }];
+ expect(
+ columnPins([{ at: 150, from: 100, to: 130 }], rows, 50, 400),
+ ).toEqual([]);
+ });
+
+ it("reads a cell merged downwards from a boundary that skips its column", () => {
+ // Four columns, and the boundary below row 0 is drawn only across columns
+ // 1-3: column 0's cell reaches down into row 1.
+ const pins = rowPins(
+ [
+ { at: 716, from: 50, to: 400 },
+ { at: 696, from: 150, to: 400 },
+ { at: 676, from: 50, to: 400 },
+ ],
+ [50, 150, 250, 400],
+ 676,
+ 716,
+ );
+ expect(pins.map((p) => p.at)).toEqual([716, 696, 676]);
+ expect([...pins[1].cols].sort()).toEqual([1, 2]);
+ expect([...pins[0].cols].sort()).toEqual([0, 1, 2]);
+ });
+
+ it("groups row boundaries per table, not across the gap between them", () => {
+ const pins = [
+ { at: 716, cols: new Set([0]) },
+ { at: 696, cols: new Set([0]) },
+ { at: 676, cols: new Set([0]) },
+ // A long way down the page: a second table, not a very tall row.
+ { at: 400, cols: new Set([0]) },
+ { at: 380, cols: new Set([0]) },
+ { at: 360, cols: new Set([0]) },
+ ];
+ const groups = clusterRowPins(pins);
+ expect(groups).toHaveLength(2);
+ expect(groups[0].map((p) => p.at)).toEqual([716, 696, 676]);
+ expect(groups[1].map((p) => p.at)).toEqual([400, 380, 360]);
+ });
+
+ it("bands candidates onto the drawn rows, wherever their text sits", () => {
+ // A vertically merged cell's text is centred over the rows it spans, so it
+ // falls between them; the drawn boundaries still say which row owns it.
+ const pins = [
+ { at: 716, cols: new Set([0]) },
+ { at: 696, cols: new Set([0]) },
+ { at: 676, cols: new Set([0]) },
+ ];
+ const cands = [
+ {
+ run: run(60, 700, 30, "A"),
+ left: 60,
+ right: 90,
+ cx: 75,
+ cy: 706,
+ height: 8,
+ },
+ {
+ run: run(60, 680, 30, "B"),
+ left: 60,
+ right: 90,
+ cx: 75,
+ cy: 686,
+ height: 8,
+ },
+ ];
+ const banded = bandByRules(cands, pins);
+ expect(banded).not.toBeNull();
+ expect(banded).toHaveLength(2);
+ expect(banded![0].cands).toHaveLength(1);
+ expect(banded![1].cands).toHaveLength(1);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableGeometry.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableGeometry.test.ts
new file mode 100644
index 0000000000..e6076945ce
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableGeometry.test.ts
@@ -0,0 +1,158 @@
+import { describe, it, expect } from "vitest";
+import {
+ insertColumnEdges,
+ removeColumnEdges,
+ insertRowEdges,
+ removeRowEdges,
+ uniformColumnEdges,
+ uniformRowEdges,
+ moveColumnEdge,
+ moveRowEdge,
+ resizeColumnTrack,
+ resizeRowTrack,
+ scaleColumnEdges,
+ scaleRowEdges,
+ MIN_TRACK,
+} from "@app/tools/pdfTextEditor/util/tableGeometry";
+
+describe("tableGeometry", () => {
+ it("builds uniform column edges", () => {
+ expect(uniformColumnEdges(100, 300, 3)).toEqual([100, 200, 300, 400]);
+ });
+
+ it("builds uniform row edges descending in y", () => {
+ expect(uniformRowEdges(700, 90, 3)).toEqual([700, 670, 640, 610]);
+ });
+
+ it("inserts a column, widening the grid and shifting tracks right", () => {
+ const edges = [100, 200, 300]; // 2 columns
+ const r = insertColumnEdges(edges, 1, 50);
+ expect(r.edges).toEqual([100, 200, 250, 350]); // 3 columns now
+ expect(r.shift).toEqual({ fromIndex: 1, delta: 50 });
+ });
+
+ it("inserts a column at the far left", () => {
+ const r = insertColumnEdges([100, 200, 300], 0, 40);
+ expect(r.edges).toEqual([100, 140, 240, 340]);
+ expect(r.shift).toEqual({ fromIndex: 0, delta: 40 });
+ });
+
+ it("removes a column and closes the gap", () => {
+ const edges = [100, 200, 250, 350]; // 3 columns
+ const r = removeColumnEdges(edges, 1); // drop the 50-wide middle column
+ expect(r.edges).toEqual([100, 200, 300]);
+ expect(r.shift).toEqual({ fromIndex: 2, delta: -50 });
+ });
+
+ it("insert then remove a column round-trips", () => {
+ const start = [100, 200, 300];
+ const inserted = insertColumnEdges(start, 1, 50);
+ const removed = removeColumnEdges(inserted.edges, 1);
+ expect(removed.edges).toEqual(start);
+ });
+
+ it("inserts a row, pushing lower rows down", () => {
+ const edges = [700, 670, 640]; // 2 rows, 30 tall each
+ const r = insertRowEdges(edges, 1, 30);
+ expect(r.edges).toEqual([700, 670, 640, 610]);
+ expect(r.shift).toEqual({ fromIndex: 1, delta: -30 });
+ });
+
+ it("removes a row and pulls lower rows up", () => {
+ const edges = [700, 670, 640, 610]; // 3 rows
+ const r = removeRowEdges(edges, 1);
+ expect(r.edges).toEqual([700, 670, 640]);
+ expect(r.shift).toEqual({ fromIndex: 2, delta: 30 });
+ });
+
+ it("insert then remove a row round-trips", () => {
+ const start = [700, 670, 640];
+ const inserted = insertRowEdges(start, 1, 30);
+ const removed = removeRowEdges(inserted.edges, 1);
+ expect(removed.edges).toEqual(start);
+ });
+
+ it("moves an internal column edge, resizing only its two neighbours", () => {
+ expect(moveColumnEdge([100, 200, 300, 400], 2, 340)).toEqual([
+ 100, 200, 340, 400,
+ ]);
+ });
+
+ it("clamps a column edge so neither neighbour drops below the minimum", () => {
+ const edges = [100, 200, 300];
+ expect(moveColumnEdge(edges, 1, 0)[1]).toBe(100 + MIN_TRACK);
+ expect(moveColumnEdge(edges, 1, 9999)[1]).toBe(300 - MIN_TRACK);
+ });
+
+ it("refuses to move an outer column edge", () => {
+ const edges = [100, 200, 300];
+ expect(moveColumnEdge(edges, 0, 50)).toEqual(edges);
+ expect(moveColumnEdge(edges, 2, 500)).toEqual(edges);
+ });
+
+ it("moves an internal row edge, honouring descending y", () => {
+ expect(moveRowEdge([700, 670, 640, 610], 1, 690)).toEqual([
+ 700, 690, 640, 610,
+ ]);
+ });
+
+ it("clamps a row edge between its neighbours", () => {
+ const edges = [700, 670, 640];
+ expect(moveRowEdge(edges, 1, 9999)[1]).toBe(700 - MIN_TRACK);
+ expect(moveRowEdge(edges, 1, 0)[1]).toBe(640 + MIN_TRACK);
+ });
+
+ it("scales columns about the left edge, keeping each column's share", () => {
+ // 100..400 (300 wide, split 1:2) doubled -> 100..700, still split 1:2.
+ expect(scaleColumnEdges([100, 200, 400], 600)).toEqual([100, 300, 700]);
+ });
+
+ it("scales rows about the top edge, keeping each row's share", () => {
+ expect(scaleRowEdges([700, 670, 610], 180)).toEqual([700, 640, 520]);
+ });
+
+ it("never scales a track below the minimum", () => {
+ const cols = scaleColumnEdges([0, 10, 20], 1);
+ expect(cols[cols.length - 1] - cols[0]).toBe(MIN_TRACK * 2);
+ const rows = scaleRowEdges([100, 90, 80], 1);
+ expect(rows[0] - rows[rows.length - 1]).toBe(MIN_TRACK * 2);
+ });
+
+ it("respects the minimum for unequal tracks while retaining their ratios", () => {
+ const cols = scaleColumnEdges([0, 10, 110], 1);
+ expect(cols[1] - cols[0]).toBeGreaterThanOrEqual(MIN_TRACK);
+ expect((cols[2] - cols[1]) / (cols[1] - cols[0])).toBeCloseTo(10);
+ const rows = scaleRowEdges([200, 190, 90], 1);
+ expect(rows[0] - rows[1]).toBeGreaterThanOrEqual(MIN_TRACK);
+ });
+
+ it("falls back to uniform tracks when the grid has no extent", () => {
+ expect(scaleColumnEdges([50, 50, 50], 100)).toEqual([50, 100, 150]);
+ expect(scaleRowEdges([50, 50, 50], 100)).toEqual([50, 0, -50]);
+ });
+
+ it("resizes one column and slides the rest along", () => {
+ // 3 columns of 100. Widening the first must not steal from the second.
+ const edges = [0, 100, 200, 300];
+ expect(resizeColumnTrack(edges, 1, 140)).toEqual([0, 140, 240, 340]);
+ // The last edge resizes the last column.
+ expect(resizeColumnTrack(edges, 3, 350)).toEqual([0, 100, 200, 350]);
+ });
+
+ it("will not shrink a column past the minimum", () => {
+ const edges = [0, 100, 200, 300];
+ expect(resizeColumnTrack(edges, 1, -50)[1]).toBe(MIN_TRACK);
+ });
+
+ it("leaves the outer left edge alone", () => {
+ const edges = [0, 100, 200];
+ expect(resizeColumnTrack(edges, 0, 40)).toEqual(edges);
+ });
+
+ it("resizes one row and slides the rest down", () => {
+ // Row edges descend; growing row 0 pushes everything below it down.
+ const edges = [700, 680, 660, 640];
+ expect(resizeRowTrack(edges, 1, 670)).toEqual([700, 670, 650, 630]);
+ expect(resizeRowTrack(edges, 1, 9999)[1]).toBe(700 - MIN_TRACK);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableStore.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableStore.test.ts
new file mode 100644
index 0000000000..250f81617e
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableStore.test.ts
@@ -0,0 +1,195 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
+import { Page } from "@app/tools/pdfTextEditor/model/Page";
+import { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@app/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import * as detection from "@app/tools/pdfTextEditor/util/tableDetection";
+
+async function makeStore() {
+ const page = new Page({ index: 0, pagePtr: 1, width: 612, height: 792 });
+ page.loaded = true;
+ const model = new TableModel({
+ id: "p0-table-0-editable",
+ pageIndex: 0,
+ colEdges: [100, 200, 300],
+ rowEdges: [700, 670, 640],
+ cellRuns: [
+ [null, null],
+ [null, null],
+ ],
+ hLinePtrs: [],
+ vLinePtrs: [],
+ lineWidth: 1,
+ fontSize: 11,
+ adopted: true,
+ });
+ page.tables = [model];
+ const doc = {
+ pageCount: 1,
+ page: () => page,
+ loadedPages: () => [page],
+ module: {},
+ dispose: () => {},
+ } as unknown as EditorDocument;
+ const store = new EditorStore();
+ await store.setDocument(doc);
+ store.publishPages([
+ {
+ pageIndex: 0,
+ width: page.width,
+ height: page.height,
+ dirty: false,
+ revision: page.revision,
+ runs: [],
+ images: [],
+ shapes: [],
+ tables: [model.snapshot()],
+ rules: [],
+ display: page.display.toData(),
+ },
+ ]);
+ return { store, page, model };
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("table session lifecycle", () => {
+ it("keeps released models when a detected positional id names another table", async () => {
+ const { store, page, model } = await makeStore();
+ store.releaseTable(0, model.id);
+ const other = new TableModel({
+ id: "p0-table-0",
+ pageIndex: 0,
+ colEdges: [350, 400, 450],
+ rowEdges: [500, 470, 440],
+ cellRuns: [
+ [null, null],
+ [null, null],
+ ],
+ hLinePtrs: [],
+ vLinePtrs: [],
+ lineWidth: 1,
+ fontSize: 11,
+ });
+ store.adoptTable(other.snapshot());
+ expect(page.tables).toHaveLength(2);
+ expect(page.tables[0]).toBe(model);
+ expect(model.editing).toBe(false);
+ expect(page.tables[1].id).toBe("p0-table-0-2-editable");
+ expect(page.tables[1].snapshot().bounds).toEqual(other.snapshot().bounds);
+ expect(store.getState().dirty).toBe(false);
+ store.dispose();
+ });
+
+ it.each([true, false])(
+ "keeps split runs and adoption synchronized through history (detected: %s)",
+ async (detected) => {
+ const { store, page, model } = await makeStore();
+ page.tables = [];
+ const run = new TextRun({
+ id: "column",
+ pageIndex: 0,
+ pdfiumObjPtr: 0,
+ text: "First\nSecond",
+ fontId: "Helvetica",
+ fontSize: 11,
+ fontSubset: false,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ bounds: { x: 110, y: 650, width: 40, height: 45 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 110, f: 690 },
+ renderMode: 3,
+ });
+ run.paragraphMemberPtrs = [0, 0];
+ run.paragraphMemberFs = [690, 660];
+ page.setRuns([run]);
+ const table = {
+ ...model.snapshot(),
+ id: "p0-table-0",
+ cells: [
+ {
+ row: 0,
+ col: 0,
+ rowSpan: 1,
+ colSpan: 1,
+ runIds: [run.id],
+ rect: run.bounds,
+ },
+ ],
+ };
+ vi.spyOn(detection, "detectTables").mockImplementation(() =>
+ detected
+ ? [
+ {
+ ...table,
+ cells: page.runs.map((r, row) => ({
+ row,
+ col: 0,
+ rowSpan: 1,
+ colSpan: 1,
+ runIds: [r.id],
+ rect: r.bounds,
+ })),
+ },
+ ]
+ : [],
+ );
+ store.adoptTable(table);
+ if (!detected) {
+ expect(page.tables).toEqual([]);
+ expect(page.runs).toEqual([run]);
+ expect(run.text).toBe("First\nSecond");
+ expect(store.getState().dirty).toBe(false);
+ } else {
+ expect(page.tables[0].cellRuns[1][0]).toBe(page.runs[1].id);
+ expect(page.runs[1].renderMode).toBe(3);
+ store.undo();
+ expect(page.tables).toEqual([]);
+ expect(page.runs).toEqual([run]);
+ expect(run.text).toBe("First\nSecond");
+ expect(store.getState().dirty).toBe(false);
+ store.redo();
+ expect(page.tables).toHaveLength(1);
+ expect(page.tables[0].cellRuns[1][0]).toBe(page.runs[1].id);
+ }
+ store.dispose();
+ },
+ );
+ it("hides a released grid while keeping it available to undo and re-adoption", async () => {
+ const { store, page, model } = await makeStore();
+ store.releaseTable(0, model.id);
+ expect(store.getState().pages[0].tables).toEqual([]);
+ expect(page.tables[0]).toBe(model);
+ expect(store.getState().dirty).toBe(false);
+ store.adoptTable({ ...model.snapshot(), id: "p0-table-0" });
+ expect(store.getState().pages[0].tables).toHaveLength(1);
+ expect(page.tables).toHaveLength(1);
+ store.dispose();
+ });
+
+ it("drops stale cell mappings and publishes fresh rules after regrouping", async () => {
+ const { store, page } = await makeStore();
+ vi.spyOn(PdfiumTextReader, "populate").mockImplementation(
+ (_doc, target) => {
+ target.setRules([
+ {
+ x: 100,
+ y: 700,
+ width: 200,
+ height: 1,
+ ptr: 42,
+ thickness: 1,
+ color: { r: 0, g: 0, b: 0, a: 255 },
+ },
+ ]);
+ target.loaded = true;
+ },
+ );
+ store.setGroupingMode("line");
+ expect(page.tables).toEqual([]);
+ expect(store.getState().pages[0].tables).toEqual([]);
+ expect(store.getState().pages[0].rules?.[0].ptr).toBe(42);
+ store.dispose();
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableStyle.test.ts b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableStyle.test.ts
new file mode 100644
index 0000000000..f773a9629e
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/__tests__/tableStyle.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect } from "vitest";
+import type { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import {
+ headerDiffers,
+ type StyledCell,
+ styleOfCells,
+} from "@app/tools/pdfTextEditor/util/tableStyle";
+
+// A cell whose text spans [left, right] inside a 100pt-wide cell at x=0.
+function cell(
+ left: number,
+ right: number,
+ extra: Partial<TextRun> = {},
+ cellX = 0,
+ cellWidth = 100,
+): StyledCell {
+ const run = {
+ id: `r${left}-${right}`,
+ fontId: "base14:Helvetica",
+ fontSize: 10,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ bounds: { x: left, y: 0, width: right - left, height: 10 },
+ ...extra,
+ } as unknown as TextRun;
+ return {
+ run,
+ rect: { x: cellX, y: 0, width: cellWidth, height: 12 },
+ left,
+ right,
+ };
+}
+
+describe("styleOfCells", () => {
+ it("returns null when the column has no text", () => {
+ expect(styleOfCells([])).toBeNull();
+ });
+
+ it("reads a left-aligned column from its shared left edge", () => {
+ const style = styleOfCells([cell(3, 40), cell(3, 22), cell(3, 61)]);
+ expect(style?.align).toBe("left");
+ });
+
+ it("reads a right-aligned column from its shared right edge", () => {
+ // Varying lefts, one right edge - the numeric-column case.
+ const style = styleOfCells([cell(60, 97), cell(75, 97), cell(52, 97)]);
+ expect(style?.align).toBe("right");
+ });
+
+ it("reads a centred column", () => {
+ const style = styleOfCells([cell(40, 60), cell(35, 65), cell(45, 55)]);
+ expect(style?.align).toBe("center");
+ });
+
+ it("guesses a lone entry's alignment from the edge it sits nearest", () => {
+ expect(styleOfCells([cell(80, 97)])?.align).toBe("right");
+ expect(styleOfCells([cell(3, 20)])?.align).toBe("left");
+ });
+
+ it("takes the median size and the most common face and colour", () => {
+ const red = { r: 200, g: 0, b: 0, a: 255 };
+ const style = styleOfCells([
+ cell(3, 40, { fontSize: 8, fill: red }),
+ cell(3, 40, { fontSize: 12, fill: red }),
+ cell(3, 40, { fontSize: 12, fill: { r: 0, g: 0, b: 0, a: 255 } }),
+ ]);
+ expect(style?.fontSize).toBe(12);
+ expect(style?.fill).toEqual(red);
+ });
+
+ it("maps an arbitrary face onto the nearest standard font", () => {
+ const style = styleOfCells([
+ cell(3, 40, { fontId: "pdf:12:Georgia-Bold" }),
+ cell(3, 40, { fontId: "pdf:12:Georgia-Bold" }),
+ ]);
+ expect(style?.family).toBe("Times-Bold");
+ // The source id is kept so two weights of one face stay distinguishable.
+ expect(style?.sourceFontId).toBe("pdf:12:Georgia-Bold");
+ });
+});
+
+describe("headerDiffers", () => {
+ const base = styleOfCells([cell(3, 40), cell(3, 40)])!;
+
+ it("is false without both styles", () => {
+ expect(headerDiffers(null, base)).toBe(false);
+ expect(headerDiffers(base, null)).toBe(false);
+ });
+
+ it("spots a header set in a different font object", () => {
+ const header = styleOfCells([
+ cell(3, 40, { fontId: "pdf:99:Chrom Sans OTF" }),
+ cell(3, 40, { fontId: "pdf:99:Chrom Sans OTF" }),
+ ])!;
+ // Same resolved family, different font - exactly the substituted-face case.
+ expect(header.family).toBe(base.family);
+ expect(headerDiffers(header, base)).toBe(true);
+ });
+
+ it("spots a bigger or differently coloured header", () => {
+ const bigger = { ...base, fontSize: base.fontSize + 3 };
+ expect(headerDiffers(bigger, base)).toBe(true);
+ const coloured = { ...base, fill: { r: 255, g: 0, b: 0, a: 255 } };
+ expect(headerDiffers(coloured, base)).toBe(true);
+ });
+
+ it("is false for a header set exactly like the body", () => {
+ expect(headerDiffers({ ...base }, base)).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/AdoptTableCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/AdoptTableCommand.ts
new file mode 100644
index 0000000000..19ee0c2046
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/AdoptTableCommand.ts
@@ -0,0 +1,71 @@
+import {
+ RolledBackError,
+ type Command,
+} from "@app/tools/pdfTextEditor/commands/Command";
+import { CompositeCommand } from "@app/tools/pdfTextEditor/commands/CompositeCommand";
+import { UngroupParagraphCommand } from "@app/tools/pdfTextEditor/commands/UngroupParagraphCommand";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import type { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import type { TableSnapshot } from "@app/tools/pdfTextEditor/types";
+import {
+ adoptedTableModel,
+ overlaps,
+} from "@app/tools/pdfTextEditor/util/tableAdoption";
+import { detectTables } from "@app/tools/pdfTextEditor/util/tableDetection";
+
+/** Keeps an adopted grid and the paragraph splits backing its cells in one undo step. */
+export class AdoptTableCommand implements Command {
+ readonly type = "adopt-table";
+ private readonly splits: CompositeCommand;
+ private model: TableModel | null = null;
+
+ constructor(
+ private readonly table: TableSnapshot,
+ private readonly tableId: string,
+ runIds: string[],
+ ) {
+ this.splits = new CompositeCommand(
+ runIds.map(
+ (runId) =>
+ new UngroupParagraphCommand({ pageIndex: table.pageIndex, runId }),
+ ),
+ );
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.table.pageIndex);
+ this.splits.apply(doc);
+ try {
+ const fresh = detectTables(
+ page.runs.map((run) => run.snapshot()),
+ page.index,
+ {},
+ page.rules,
+ );
+ const rebuilt = fresh.find((table) =>
+ overlaps(table.bounds, this.table.bounds),
+ );
+ if (!rebuilt)
+ throw new Error(
+ "Could not identify the table after splitting its text.",
+ );
+ this.model = adoptedTableModel(doc.module, page, {
+ ...rebuilt,
+ id: this.tableId,
+ });
+ page.tables = [...page.tables, this.model];
+ page.bumpRevision();
+ } catch (error) {
+ this.splits.revert(doc);
+ throw new RolledBackError(error);
+ }
+ }
+
+ revert(doc: EditorDocument): void {
+ const page = doc.page(this.table.pageIndex);
+ this.splits.revert(doc);
+ page.tables = page.tables.filter((table) => table !== this.model);
+ this.model = null;
+ page.bumpRevision();
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
index c605db06f3..8234214633 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
@@ -3,6 +3,7 @@ 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 type { PageRuleSnapshot } from "@app/tools/pdfTextEditor/types";
import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
interface PageInsertModule {
@@ -32,6 +33,8 @@ export class DeleteShapeCommand implements Command {
private readonly pageIndex: number;
private readonly shapeId: string;
private removed: ShapeObject | null = null;
+ private removedRules: PageRuleSnapshot[] = [];
+ private removedFills: PageRuleSnapshot[] = [];
/** Position among the shapes and in the page's object list, for revert. */
private shapeIndex = -1;
private objectIndex = -1;
@@ -60,6 +63,14 @@ export class DeleteShapeCommand implements Command {
if (!m.FPDFPage_RemoveObject(page.pagePtr, shape.pdfiumObjPtr)) return;
}
this.removed = shape;
+ this.removedRules = page.rules.filter(
+ (rule) => rule.ptr === shape.pdfiumObjPtr,
+ );
+ this.removedFills = page.fills.filter(
+ (fill) => fill.ptr === shape.pdfiumObjPtr,
+ );
+ page.setRules(page.rules.filter((rule) => rule.ptr !== shape.pdfiumObjPtr));
+ page.setFills(page.fills.filter((fill) => fill.ptr !== shape.pdfiumObjPtr));
page.setShapes(page.shapes.filter((s) => s !== shape));
page.markDirty();
page.markNeedsGenerate();
@@ -90,6 +101,10 @@ export class DeleteShapeCommand implements Command {
shape,
);
page.setShapes(shapes);
+ page.setRules([...page.rules, ...this.removedRules]);
+ page.setFills([...page.fills, ...this.removedFills]);
+ this.removedRules = [];
+ this.removedFills = [];
this.removed = null;
page.markDirty();
page.markNeedsGenerate();
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/FillTableCellCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/FillTableCellCommand.ts
new file mode 100644
index 0000000000..54836a01ec
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/FillTableCellCommand.ts
@@ -0,0 +1,96 @@
+import { locateTable } from "@app/tools/pdfTextEditor/util/locateTable";
+import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import { emitStyledCellText } from "@app/tools/pdfTextEditor/commands/tableHelpers";
+
+// Puts the first text into a previously-empty table cell: inserts a text run at
+// the cell's anchor and links it to the cell. Subsequent edits of that cell go
+// through the normal EditTextCommand path on the created run.
+export class FillTableCellCommand implements Command {
+ readonly type = "fill-table-cell";
+ private readonly tableId: string;
+ private readonly row: number;
+ private readonly col: number;
+ private readonly text: string;
+ private createdRunId: string | null = null;
+ private createdObjPtr = 0;
+ private createdRun: TextRun | null = null;
+
+ constructor(opts: {
+ tableId: string;
+ row: number;
+ col: number;
+ text: string;
+ }) {
+ this.tableId = opts.tableId;
+ this.row = opts.row;
+ this.col = opts.col;
+ this.text = opts.text;
+ }
+
+ get insertedRunId(): string | null {
+ return this.createdRunId;
+ }
+
+ apply(doc: EditorDocument): void {
+ const found = locateTable(doc, this.tableId);
+ if (!found) return;
+ const { page, model } = found;
+ if (
+ !Number.isInteger(this.row) ||
+ !Number.isInteger(this.col) ||
+ this.row < 0 ||
+ this.col < 0 ||
+ this.row >= model.rows ||
+ this.col >= model.cols ||
+ model.isCovered(this.row, this.col) ||
+ model.cellRuns[this.row]?.[this.col]
+ )
+ return;
+ if (this.createdRun) {
+ doc.module.FPDFPage_InsertObject(page.pagePtr, this.createdObjPtr);
+ page.setRuns([...page.runs, this.createdRun]);
+ model.cellRuns[this.row][this.col] = this.createdRun.id;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return;
+ }
+ const emitted = emitStyledCellText(
+ doc,
+ page,
+ model,
+ this.row,
+ this.col,
+ this.text,
+ );
+ if (!emitted) return;
+ model.cellRuns[this.row][this.col] = emitted.run.id;
+ this.createdRunId = emitted.run.id;
+ this.createdObjPtr = emitted.ptr;
+ this.createdRun = emitted.run;
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.createdRunId) return;
+ const found = locateTable(doc, this.tableId);
+ if (!found) return;
+ const { page } = found;
+ if (this.createdObjPtr) {
+ doc.module.FPDFPage_RemoveObject(page.pagePtr, this.createdObjPtr);
+ }
+ page.setRuns(page.runs.filter((r) => r.id !== this.createdRunId));
+ const model = page.tables.find((t) => t.id === this.tableId);
+ if (model && model.cellRuns[this.row]?.[this.col] === this.createdRunId) {
+ model.cellRuns[this.row][this.col] = null;
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ describe(): string {
+ return `Fill cell (${this.row}, ${this.col})`;
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertTableCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertTableCommand.ts
new file mode 100644
index 0000000000..9185a02c53
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/InsertTableCommand.ts
@@ -0,0 +1,116 @@
+import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import {
+ uniformColumnEdges,
+ uniformRowEdges,
+} from "@app/tools/pdfTextEditor/util/tableGeometry";
+import {
+ redrawGrid,
+ removeObjects,
+} from "@app/tools/pdfTextEditor/commands/tableHelpers";
+
+const DEFAULT_LINE_WIDTH = 0.75;
+const DEFAULT_FONT_SIZE = 11;
+
+// Draws a bordered grid of ruling lines on the page and registers a session
+// table for it. Cells start empty; content is added lazily when the user types.
+export class InsertTableCommand implements Command {
+ readonly type = "insert-table";
+ private readonly pageIndex: number;
+ private readonly x: number;
+ private readonly topY: number;
+ private readonly width: number;
+ private readonly height: number;
+ private readonly rows: number;
+ private readonly cols: number;
+ private readonly lineWidth: number;
+ private readonly fontSize: number;
+ private tableId: string | null = null;
+
+ constructor(opts: {
+ pageIndex: number;
+ /** Left edge in PDF points. */
+ x: number;
+ /** Top edge in PDF points (y-up). */
+ y: number;
+ width: number;
+ height: number;
+ rows: number;
+ cols: number;
+ lineWidth?: number;
+ fontSize?: number;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.x = opts.x;
+ this.topY = opts.y;
+ this.width = opts.width;
+ this.height = opts.height;
+ this.rows = Math.max(1, Math.round(opts.rows));
+ this.cols = Math.max(1, Math.round(opts.cols));
+ this.lineWidth = opts.lineWidth ?? DEFAULT_LINE_WIDTH;
+ this.fontSize = opts.fontSize ?? DEFAULT_FONT_SIZE;
+ }
+
+ /** Id of the table this command created, after apply. */
+ get insertedTableId(): string | null {
+ return this.tableId;
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const colEdges = uniformColumnEdges(this.x, this.width, this.cols);
+ const rowEdges = uniformRowEdges(this.topY, this.height, this.rows);
+ const cellRuns: (string | null)[][] = Array.from(
+ { length: this.rows },
+ () => Array.from({ length: this.cols }, () => null),
+ );
+ const id =
+ this.tableId ?? `p${page.index}-tbl-${page.tables.length}-${Date.now()}`;
+ const model = new TableModel({
+ id,
+ pageIndex: page.index,
+ colEdges,
+ rowEdges,
+ cellRuns,
+ hLinePtrs: [],
+ vLinePtrs: [],
+ lineWidth: this.lineWidth,
+ fontSize: this.fontSize,
+ });
+ redrawGrid(doc, page, model);
+ page.tables = [...page.tables, model];
+ this.tableId = id;
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.tableId) return;
+ const page = doc.page(this.pageIndex);
+ const model = page.tables.find((t) => t.id === this.tableId);
+ if (!model) return;
+ const m = doc.module;
+ removeObjects(m, page, [...model.hLinePtrs, ...model.vLinePtrs]);
+ // Any surviving cell runs (defensive: cell edits are separate history
+ // entries and are normally reverted before this one).
+ const cellRunIds = new Set(
+ model.cellRuns.flat().filter((r): r is string => r !== null),
+ );
+ if (cellRunIds.size > 0) {
+ for (const run of page.runs) {
+ if (cellRunIds.has(run.id) && run.pdfiumObjPtr) {
+ m.FPDFPage_RemoveObject(page.pagePtr, run.pdfiumObjPtr);
+ }
+ }
+ page.setRuns(page.runs.filter((r) => !cellRunIds.has(r.id)));
+ }
+ page.tables = page.tables.filter((t) => t.id !== this.tableId);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ describe(): string {
+ return `Insert ${this.rows}x${this.cols} table`;
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts
new file mode 100644
index 0000000000..2710eeec7e
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts
@@ -0,0 +1,461 @@
+import { locateTable } from "@app/tools/pdfTextEditor/util/locateTable";
+import {
+ RolledBackError,
+ 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 { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import type {
+ RowFill,
+ TableModel,
+} from "@app/tools/pdfTextEditor/model/TableModel";
+import type { PageRect, RGBA } from "@app/tools/pdfTextEditor/types";
+import type { ScanColors } from "@app/tools/pdfTextEditor/util/scanSampling";
+import {
+ measureObjBoxPt,
+ measureObjSpanPt,
+} from "@app/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ emitCellText,
+ redrawGrid,
+ removeObjects,
+} from "@app/tools/pdfTextEditor/commands/tableHelpers";
+
+const FPDF_PAGEOBJ_IMAGE = 3;
+const FPDF_PAGEOBJ_FORM = 5;
+const DEFAULT_LINE_WIDTH = 0.75;
+// Bleed so the scan's own printed rules are covered rather than left as a
+// halo. A scan is never perfectly square to the page, so its rules need more
+// room than a digital table's would.
+const MASK_BLEED_PT = 3;
+/** Below this a cell's shading is just the paper, and one rect covers both. */
+const SHADE_DELTA = 24;
+/** Bounds on the fit, so one bad measurement cannot stretch a word. */
+const MIN_SQUEEZE = 0.4;
+const MAX_STRETCH = 2.5;
+/** Rough cap-height fraction of an em, to start the fit near 1. */
+const CAP_RATIO = 0.72;
+const WHITE: RGBA = { r: 255, g: 255, b: 255, a: 255 };
+const BLACK: RGBA = { r: 0, g: 0, b: 0, a: 255 };
+
+interface FormModule {
+ FPDFFormObj_CountObjects?: (form: number) => number;
+ FPDFFormObj_GetObject?: (form: number, index: number) => number;
+}
+
+interface ZOrderModule {
+ FPDFPage_InsertObjectAtIndex?: (
+ page: number,
+ obj: number,
+ index: number,
+ ) => boolean | number;
+}
+
+const differs = (a: RGBA, b: RGBA): boolean =>
+ Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b) > SHADE_DELTA;
+
+/** Every object a run was built from; OCR emits one per word. */
+const memberPtrs = (run: TextRun): number[] => {
+ const members =
+ run.paragraphLeafPtrs.length > 0
+ ? run.paragraphLeafPtrs
+ : run.mergedFromPtrs.length > 0
+ ? run.mergedFromPtrs
+ : [run.pdfiumObjPtr];
+ return members.filter((p) => p > 0);
+};
+
+const fit = (ratio: number): number =>
+ Number.isFinite(ratio)
+ ? Math.min(MAX_STRETCH, Math.max(MIN_SQUEEZE, ratio))
+ : 1;
+
+// Turns a table that only exists as pixels into real page objects.
+//
+// A scan carries its table as a raster image with an INVISIBLE OCR text layer
+// on top, and that layer lives inside a form XObject. FPDFPage_GenerateContent
+// rewrites only the PAGE content stream, so anything done to an object inside
+// that form - render mode, transform - draws correctly in the live view and is
+// then dropped on save. So the OCR text is not un-hidden and moved: it is
+// re-emitted as new page-level objects in the colours the scan was printed in,
+// and the picture of the table is painted over.
+export class MaterialiseTableCommand implements Command {
+ readonly type = "materialise-table";
+ private readonly tableId: string;
+ private readonly colors: ScanColors | null;
+ /** Rectangles painted over the scan: the paper, then any shaded row. */
+ private paintedPtrs: number[] = [];
+ /** The replacement text this command created. */
+ private emittedPtrs: number[] = [];
+ /** Form containers dropped because the table was all they held. */
+ private droppedForms: { ptr: number; index: number }[] = [];
+ private prevRuns: TextRun[] | null = null;
+ private prevCellRuns: (string | null)[][] | null = null;
+ private prevExtraRuns: (string[] | null)[][] | null = null;
+ private prevRowFills: RowFill[] = [];
+ private wasRuled = false;
+ private prevLineColor: RGBA | null = null;
+
+ constructor(opts: { tableId: string; colors?: ScanColors | null }) {
+ this.tableId = opts.tableId;
+ this.colors = opts.colors ?? null;
+ }
+
+ apply(doc: EditorDocument): void {
+ const found = locateTable(doc, this.tableId);
+ if (!found) return;
+ if (!(doc.module as unknown as ZOrderModule).FPDFPage_InsertObjectAtIndex)
+ throw new RolledBackError(
+ new Error(
+ "Rebuilding scanned tables is unavailable in this PDF engine.",
+ ),
+ );
+ const { page, model } = found;
+ this.prevRuns = [...page.runs];
+ this.prevCellRuns = model.cellRuns.map((row) => [...row]);
+ this.prevExtraRuns = model.cellExtraRuns.map((row) =>
+ row.map((ids) => (ids ? [...ids] : null)),
+ );
+ this.paintBackground(doc, page, model);
+ this.reemitText(doc, page, model);
+ this.wasRuled = model.ruled;
+ model.ruled = true;
+ if (model.lineWidth <= 0) model.lineWidth = DEFAULT_LINE_WIDTH;
+ if (this.colors) {
+ this.prevLineColor = { ...model.lineColor };
+ model.lineColor = { ...this.colors.rule };
+ }
+ redrawGrid(doc, page, model);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.prevRuns) return;
+ const found = locateTable(doc, this.tableId);
+ if (!found) return;
+ const { page, model } = found;
+ const mod = doc.module as unknown as ZOrderModule;
+ if (this.emittedPtrs.length > 0) {
+ removeObjects(doc.module, page, this.emittedPtrs);
+ this.emittedPtrs = [];
+ }
+ // Lowest index last, so each form lands back where it was taken from.
+ for (const { ptr, index } of [...this.droppedForms].reverse()) {
+ mod.FPDFPage_InsertObjectAtIndex?.(page.pagePtr, ptr, index);
+ }
+ this.droppedForms = [];
+ if (this.paintedPtrs.length > 0) {
+ removeObjects(doc.module, page, this.paintedPtrs);
+ this.paintedPtrs = [];
+ model.rowFills = this.prevRowFills;
+ this.prevRowFills = [];
+ }
+ if (this.prevRuns) {
+ page.setRuns(this.prevRuns);
+ this.prevRuns = null;
+ }
+ if (this.prevCellRuns) {
+ model.cellRuns = this.prevCellRuns;
+ this.prevCellRuns = null;
+ }
+ if (this.prevExtraRuns) {
+ model.cellExtraRuns = this.prevExtraRuns;
+ this.prevExtraRuns = null;
+ }
+ if (this.prevLineColor) {
+ model.lineColor = this.prevLineColor;
+ this.prevLineColor = null;
+ }
+ if (!this.wasRuled) {
+ removeObjects(doc.module, page, [...model.hLinePtrs, ...model.vLinePtrs]);
+ model.hLinePtrs = [];
+ model.vLinePtrs = [];
+ model.ruled = false;
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ // Replace each cell's OCR text with a page-level text object standing where
+ // the original stood. Position and width are measured off the original
+ // rather than derived from the cell, so the rebuilt row keeps the spacing
+ // the scan had instead of snapping to a uniform inset.
+ private reemitText(doc: EditorDocument, page: Page, model: TableModel): void {
+ const replaced = new Set<string>();
+ const replacedPtrs = new Set<number>();
+ const cellRuns = model.cellRuns.map((row) => [...row]);
+ const extras = model.cellExtraRuns.map(() =>
+ Array.from({ length: model.cols }, () => null as string[] | null),
+ );
+ for (let r = 0; r < model.rows; r++) {
+ for (let c = 0; c < model.cols; c++) {
+ const ink = this.colors?.cells[r]?.[c]?.ink ?? BLACK;
+ const made: string[] = [];
+ for (const id of model.runsAt(r, c)) {
+ const run = page.findRun(id);
+ if (!run) continue;
+ replaced.add(id);
+ for (const ptr of memberPtrs(run)) replacedPtrs.add(ptr);
+ const fresh = this.reemitRun(doc, page, run, ink);
+ if (fresh) made.push(fresh);
+ }
+ if (made.length === 0) continue;
+ cellRuns[r][c] = made[0];
+ extras[r][c] = made.length > 1 ? made.slice(1) : null;
+ }
+ }
+ model.cellRuns = cellRuns;
+ model.cellExtraRuns = extras;
+ this.dropSpentForms(doc, page, replacedPtrs);
+ // The originals are invisible and stay where they were; dropping them from
+ // the model keeps a phantom selectable copy from trailing the moved table.
+ page.setRuns(page.runs.filter((run) => !replaced.has(run.id)));
+ }
+
+ // One replacement object, fitted to the box the original occupied.
+ //
+ // The OCR font SIZE is not usable: tesseract guesses it per word, and on one
+ // uniform scan it ranged 8.05 to 10.39, which reproduces as a table of
+ // mismatched text. The word BOX is reliable - OCR fits it to the ink it
+ // found in the picture - so the replacement is scaled onto that box instead.
+ private reemitRun(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ ink: RGBA,
+ ): string | null {
+ if (!run.text.trim()) return null;
+ const target = this.placeOf(doc, run);
+ if (!target || target.width <= 0 || target.height <= 0) return null;
+ const nominal = Math.min(72, Math.max(4, target.height / CAP_RATIO));
+ const emitted = emitCellText(doc, page, 0, 0, run.text, nominal, ink);
+ if (!emitted) return null;
+ this.emittedPtrs.push(emitted.ptr);
+ const box = measureObjBoxPt(doc.module, emitted.ptr);
+ if (box && box.width > 0 && box.height > 0) {
+ const sx = fit(target.width / box.width);
+ const sy = fit(target.height / box.height);
+ doc.module.FPDFPageObj_Transform(
+ emitted.ptr,
+ sx,
+ 0,
+ 0,
+ sy,
+ target.x - box.x * sx,
+ target.y - box.y * sy,
+ );
+ emitted.run.bounds = { ...target };
+ emitted.run.fontSize = nominal * sy;
+ emitted.run.matrix = {
+ a: sx,
+ b: 0,
+ c: 0,
+ d: sy,
+ e: target.x - box.x * sx,
+ f: target.y - box.y * sy,
+ };
+ }
+ return emitted.run.id;
+ }
+
+ // Where an OCR run actually sits on the page, measured across every object
+ // the run was built from - OCR emits one per word.
+ private placeOf(doc: EditorDocument, run: TextRun): PageRect | null {
+ const ptrs = memberPtrs(run);
+ if (ptrs.length === 0) return run.bounds;
+ const span = measureObjSpanPt(doc.module, ptrs);
+ let bottom = Infinity;
+ let top = -Infinity;
+ for (const ptr of ptrs) {
+ const box = measureObjBoxPt(doc.module, ptr);
+ if (!box) continue;
+ bottom = Math.min(bottom, box.y);
+ top = Math.max(top, box.y + box.height);
+ }
+ if (!span || !Number.isFinite(bottom)) return run.bounds;
+ return {
+ x: span.left,
+ y: bottom,
+ width: span.right - span.left,
+ height: top - bottom,
+ };
+ }
+
+ // Drop a form container whose ONLY contents were this table's text: it is
+ // now a duplicate of what was just emitted. The test walks the form's real
+ // children, not the runs pointing at it - a form holding a logo alongside
+ // the table would otherwise count as spent and take the logo with it.
+ private dropSpentForms(
+ doc: EditorDocument,
+ page: Page,
+ replacedPtrs: Set<number>,
+ ): void {
+ const m = doc.module;
+ const total = m.FPDFPage_CountObjects(page.pagePtr);
+ const found: { ptr: number; index: number }[] = [];
+ for (let i = 0; i < total; i++) {
+ const obj = m.FPDFPage_GetObject(page.pagePtr, i);
+ if (!obj || m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_FORM) continue;
+ if (this.formIsSpent(doc, obj, replacedPtrs))
+ found.push({ ptr: obj, index: i });
+ }
+ // Highest index first, so each removal leaves the earlier ones in place.
+ for (const entry of [...found].reverse()) {
+ m.FPDFPage_RemoveObject(page.pagePtr, entry.ptr);
+ }
+ this.droppedForms = found;
+ }
+
+ /** True when every object inside the form is one this rebuild replaced. */
+ private formIsSpent(
+ doc: EditorDocument,
+ formPtr: number,
+ replacedPtrs: Set<number>,
+ ): boolean {
+ const m = doc.module;
+ const forms = m as unknown as FormModule;
+ if (!forms.FPDFFormObj_CountObjects || !forms.FPDFFormObj_GetObject) {
+ return false;
+ }
+ const stack = [formPtr];
+ let leaves = 0;
+ while (stack.length > 0) {
+ const current = stack.pop() as number;
+ const count = forms.FPDFFormObj_CountObjects(current);
+ for (let i = 0; i < count; i++) {
+ const child = forms.FPDFFormObj_GetObject(current, i);
+ if (!child) continue;
+ if (m.FPDFPageObj_GetType(child) === FPDF_PAGEOBJ_FORM) {
+ stack.push(child);
+ continue;
+ }
+ if (!replacedPtrs.has(child)) return false;
+ leaves++;
+ }
+ }
+ return leaves > 0;
+ }
+
+ // Cover the scanned table in the colours it actually had: one rectangle of
+ // its paper to erase the scan, then a band per differently shaded row. Bands
+ // go in as row fills so they travel with the table; loose rectangles would
+ // stay put and ghost the old banding.
+ private paintBackground(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ ): void {
+ const paper = this.colors?.paper ?? WHITE;
+ const at = this.aboveImages(doc, page);
+ const ptrs: number[] = [];
+ const base = this.paintRect(
+ doc,
+ page,
+ model.colEdges[0] - MASK_BLEED_PT,
+ model.rowEdges[model.rows] - MASK_BLEED_PT,
+ model.colEdges[model.cols] + MASK_BLEED_PT,
+ model.rowEdges[0] + MASK_BLEED_PT,
+ paper,
+ at,
+ );
+ if (base) ptrs.push(base);
+ this.prevRowFills = model.rowFills;
+ const fills: RowFill[] = [...model.rowFills];
+ const left = model.colEdges[0];
+ const right = model.colEdges[model.cols];
+ for (let r = 0; r < model.rows; r++) {
+ const shade = this.rowShade(model, r, paper);
+ if (!shade) continue;
+ const rect = {
+ x: left,
+ y: model.rowEdges[r + 1],
+ width: right - left,
+ height: model.rowEdges[r] - model.rowEdges[r + 1],
+ };
+ const ptr = this.paintRect(
+ doc,
+ page,
+ rect.x,
+ rect.y,
+ rect.x + rect.width,
+ rect.y + rect.height,
+ shade,
+ at + ptrs.length,
+ );
+ if (!ptr) continue;
+ ptrs.push(ptr);
+ fills.push({ row: r, ptr, rect, color: { ...shade } });
+ }
+ model.rowFills = fills;
+ this.paintedPtrs = ptrs;
+ }
+
+ // What a whole row was shaded, or null if it matched the paper. Taking the
+ // most common cell colour keeps one misread cell from tinting the band.
+ private rowShade(model: TableModel, row: number, paper: RGBA): RGBA | null {
+ const counts = new Map<string, { n: number; c: RGBA }>();
+ for (let c = 0; c < model.cols; c++) {
+ const bg = this.colors?.cells[row]?.[c]?.bg;
+ if (!bg) continue;
+ const key = `${bg.r},${bg.g},${bg.b}`;
+ const hit = counts.get(key);
+ if (hit) hit.n++;
+ else counts.set(key, { n: 1, c: bg });
+ }
+ let best: RGBA | null = null;
+ let bestN = 0;
+ for (const entry of counts.values()) {
+ if (entry.n > bestN) {
+ bestN = entry.n;
+ best = entry.c;
+ }
+ }
+ return best && differs(best, paper) ? best : null;
+ }
+
+ /** One filled rectangle, inserted so it hides the scan but not the text. */
+ private paintRect(
+ doc: EditorDocument,
+ page: Page,
+ left: number,
+ bottom: number,
+ right: number,
+ top: number,
+ color: RGBA,
+ index: number,
+ ): number {
+ const m = doc.module;
+ const ptr = m.FPDFPageObj_CreateNewRect(
+ left,
+ bottom,
+ right - left,
+ top - bottom,
+ );
+ if (!ptr) return 0;
+ m.FPDFPageObj_SetFillColor(ptr, color.r, color.g, color.b, 255);
+ m.FPDFPath_SetDrawMode(ptr, 2, false);
+ const mod = m as unknown as ZOrderModule;
+ mod.FPDFPage_InsertObjectAtIndex?.(page.pagePtr, ptr, index);
+ return ptr;
+ }
+
+ /** Index just past the last image, so paint covers the scan and nothing else. */
+ private aboveImages(doc: EditorDocument, page: Page): number {
+ const m = doc.module;
+ const total = m.FPDFPage_CountObjects(page.pagePtr);
+ let index = 0;
+ for (let i = 0; i < total; i++) {
+ const obj = m.FPDFPage_GetObject(page.pagePtr, i);
+ if (obj && m.FPDFPageObj_GetType(obj) === FPDF_PAGEOBJ_IMAGE) {
+ index = i + 1;
+ }
+ }
+ return index;
+ }
+
+ describe(): string {
+ return "Rebuild scanned table";
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts
new file mode 100644
index 0000000000..3d49dd3dd5
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts
@@ -0,0 +1,447 @@
+import { locateTable } from "@app/tools/pdfTextEditor/util/locateTable";
+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 { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import type { TableCellStyle } from "@app/tools/pdfTextEditor/types";
+import { DeleteObjectCommand } from "@app/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { defaultCellStyle } from "@app/tools/pdfTextEditor/model/TableModel";
+import {
+ insertColumnEdges,
+ insertRowEdges,
+ removeColumnEdges,
+ removeRowEdges,
+} from "@app/tools/pdfTextEditor/util/tableGeometry";
+import {
+ bandColorFor,
+ paintRowFill,
+ redrawGrid,
+ removeObjects,
+ renormaliseFontBase,
+ shiftRunBy,
+} from "@app/tools/pdfTextEditor/commands/tableHelpers";
+import type { RowFill } from "@app/tools/pdfTextEditor/model/TableModel";
+
+export type TableOp = "add-row" | "delete-row" | "add-col" | "delete-col";
+
+// Structural edit of a session table: add or remove a row or column. Moves the
+// runs that live in the affected tracks, redraws the ruling lines, and keeps
+// the cell->run map in step. Deletes retain the original objects for undo.
+export class ModifyTableCommand implements Command {
+ readonly type = "modify-table";
+ private readonly tableId: string;
+ private readonly op: TableOp;
+ private readonly index: number;
+ /** Height (row) or width (column) of the affected track, resolved at apply. */
+ private size = 0;
+ private removed: DeleteObjectCommand[] = [];
+ private before: {
+ cellRuns: TableModel["cellRuns"];
+ cellExtraRuns: TableModel["cellExtraRuns"];
+ cellSpans: TableModel["cellSpans"];
+ origins: { id: string; e: number; f: number }[];
+ } | null = null;
+ /** Style of a deleted column, so undo brings the column back as it was. */
+ private removedStyle: TableCellStyle | null = null;
+ /** Background painted for an added row, so undo can take it away again. */
+ private paintedFill: RowFill | null = null;
+ /** Background of a deleted row, so undo can put it back. */
+ private removedFill: RowFill | null = null;
+
+ constructor(opts: { tableId: string; op: TableOp; index: number }) {
+ this.tableId = opts.tableId;
+ this.op = opts.op;
+ this.index = opts.index;
+ }
+
+ apply(doc: EditorDocument): void {
+ const found = locateTable(doc, this.tableId);
+ if (!found) return;
+ const { page, model } = found;
+ const isRow = this.op.endsWith("row");
+ const count = isRow ? model.rows : model.cols;
+ const adding = this.op.startsWith("add");
+ if (
+ !Number.isInteger(this.index) ||
+ this.index < 0 ||
+ this.index > count - (adding ? 0 : 1) ||
+ (!adding && count <= 1)
+ )
+ return;
+ this.before = {
+ cellRuns: model.cellRuns.map((row) => [...row]),
+ cellExtraRuns: model.cellExtraRuns.map((row) =>
+ row.map((ids) => (ids ? [...ids] : null)),
+ ),
+ cellSpans: model.cellSpans.map((row) =>
+ row.map((span) => (span ? { ...span } : null)),
+ ),
+ origins: [
+ ...new Set(
+ model.cellRuns.flatMap((row, r) =>
+ row.flatMap((_id, c) => model.runsAt(r, c)),
+ ),
+ ),
+ ].flatMap((id) => {
+ const run = page.findRun(id);
+ return run ? [{ id, e: run.matrix.e, f: run.matrix.f }] : [];
+ }),
+ };
+ switch (this.op) {
+ case "add-row":
+ this.addRow(doc, page, model);
+ break;
+ case "delete-row":
+ this.deleteRow(doc, page, model);
+ break;
+ case "add-col":
+ this.addColumn(doc, page, model);
+ break;
+ case "delete-col":
+ this.deleteColumn(doc, page, model);
+ break;
+ }
+ this.adjustSpans(model, isRow, adding);
+ // The table changed extent without its type changing, so the font
+ // reference moves with it.
+ renormaliseFontBase(model);
+ redrawGrid(doc, page, model);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ const found = locateTable(doc, this.tableId);
+ if (!found || !this.before) return;
+ const { page, model } = found;
+ switch (this.op) {
+ case "add-row":
+ if (this.paintedFill) {
+ removeObjects(doc.module, page, [this.paintedFill.ptr]);
+ model.rowFills = model.rowFills.filter((f) => f !== this.paintedFill);
+ this.paintedFill = null;
+ }
+ this.deleteRowAt(doc, page, model, this.index, this.size, false);
+ break;
+ case "delete-row":
+ this.reinsertRow(doc, page, model);
+ break;
+ case "add-col":
+ this.deleteColumnAt(doc, page, model, this.index, this.size, false);
+ break;
+ case "delete-col":
+ this.reinsertColumn(doc, page, model);
+ break;
+ }
+ model.cellRuns = this.before.cellRuns.map((row) => [...row]);
+ model.cellExtraRuns = this.before.cellExtraRuns.map((row) =>
+ row.map((ids) => (ids ? [...ids] : null)),
+ );
+ model.cellSpans = this.before.cellSpans.map((row) =>
+ row.map((span) => (span ? { ...span } : null)),
+ );
+ for (const spot of this.before.origins) {
+ const run = page.findRun(spot.id);
+ if (run)
+ shiftRunBy(
+ doc.module,
+ run,
+ spot.e - run.matrix.e,
+ spot.f - run.matrix.f,
+ );
+ }
+ renormaliseFontBase(model);
+ redrawGrid(doc, page, model);
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ private addRow(doc: EditorDocument, page: Page, model: TableModel): void {
+ const h = this.avgRowHeight(model);
+ this.size = h;
+ // Rows at/below the insertion move down by h.
+ this.shiftCells(doc, page, model, (r) => r >= this.index, 0, -h);
+ model.rowEdges = insertRowEdges(model.rowEdges, this.index, h).edges;
+ model.cellRuns.splice(
+ this.index,
+ 0,
+ Array.from({ length: model.cols }, () => null),
+ );
+ model.cellSpans.splice(
+ this.index,
+ 0,
+ Array.from({ length: model.cols }, () => null),
+ );
+ model.cellExtraRuns.splice(
+ this.index,
+ 0,
+ Array.from({ length: model.cols }, () => null),
+ );
+ this.shiftFillRows(model, this.index, 1);
+ // A banded table keeps its rhythm: the new row takes the paint the pattern
+ // calls for rather than arriving blank.
+ const color = bandColorFor(model, this.index);
+ if (color) {
+ this.paintedFill = paintRowFill(doc, page, model, this.index, color);
+ if (this.paintedFill) model.rowFills.push(this.paintedFill);
+ }
+ }
+
+ private deleteRow(doc: EditorDocument, page: Page, model: TableModel): void {
+ const h = model.rowEdges[this.index] - model.rowEdges[this.index + 1];
+ this.size = h;
+ this.deleteRowAt(doc, page, model, this.index, h, true);
+ }
+
+ // Shared by delete-row and revert-of-add-row. `capture` controls whether the
+ // removed cell content is recorded for later restoration.
+ private deleteRowAt(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ index: number,
+ h: number,
+ capture: boolean,
+ ): void {
+ this.removeTrackRuns(
+ doc,
+ page,
+ model,
+ (r, c) => r === index && model.spanAt(r, c).rowSpan === 1,
+ capture,
+ );
+ // Rows below the deleted one move up by h.
+ this.shiftCells(doc, page, model, (r) => r > index, 0, h);
+ model.rowEdges = removeRowEdges(model.rowEdges, index).edges;
+ model.cellRuns.splice(index, 1);
+ model.cellSpans.splice(index, 1);
+ model.cellExtraRuns.splice(index, 1);
+ const dropped = model.rowFills.find((f) => f.row === index) ?? null;
+ if (dropped) {
+ removeObjects(doc.module, page, [dropped.ptr]);
+ model.rowFills = model.rowFills.filter((f) => f !== dropped);
+ if (capture) this.removedFill = dropped;
+ }
+ this.shiftFillRows(model, index + 1, -1);
+ }
+
+ private reinsertRow(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ ): void {
+ const h = this.size;
+ // Rows currently at/below the slot move back down by h to make room.
+ this.shiftCells(doc, page, model, (r) => r >= this.index, 0, -h);
+ model.rowEdges = insertRowEdges(model.rowEdges, this.index, h).edges;
+ model.cellRuns.splice(
+ this.index,
+ 0,
+ Array.from({ length: model.cols }, () => null),
+ );
+ model.cellSpans.splice(
+ this.index,
+ 0,
+ Array.from({ length: model.cols }, () => null),
+ );
+ model.cellExtraRuns.splice(
+ this.index,
+ 0,
+ Array.from({ length: model.cols }, () => null),
+ );
+ this.shiftFillRows(model, this.index, 1);
+ if (this.removedFill) {
+ const back = paintRowFill(
+ doc,
+ page,
+ model,
+ this.index,
+ this.removedFill.color,
+ );
+ if (back) model.rowFills.push(back);
+ this.removedFill = null;
+ }
+ this.restoreCaptured(doc);
+ }
+
+ // Fills are bound by row index, so an insert or delete above them has to move
+ // them or every band below lands on the wrong row.
+ private shiftFillRows(model: TableModel, from: number, by: number): void {
+ for (const fill of model.rowFills) {
+ if (fill.row >= from) fill.row += by;
+ }
+ }
+
+ private addColumn(doc: EditorDocument, page: Page, model: TableModel): void {
+ const w = this.avgColWidth(model);
+ this.size = w;
+ this.shiftCells(doc, page, model, (_r, c) => c >= this.index, w, 0);
+ model.colEdges = insertColumnEdges(model.colEdges, this.index, w).edges;
+ for (const row of model.cellRuns) row.splice(this.index, 0, null);
+ for (const row of model.cellSpans) row.splice(this.index, 0, null);
+ for (const row of model.cellExtraRuns) row.splice(this.index, 0, null);
+ // A new column writes like the one it was added beside.
+ model.columnStyles.splice(this.index, 0, this.neighbourStyle(model));
+ }
+
+ private deleteColumn(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ ): void {
+ const w = model.colEdges[this.index + 1] - model.colEdges[this.index];
+ this.size = w;
+ this.deleteColumnAt(doc, page, model, this.index, w, true);
+ }
+
+ private deleteColumnAt(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ index: number,
+ w: number,
+ capture: boolean,
+ ): void {
+ this.removeTrackRuns(
+ doc,
+ page,
+ model,
+ (r, c) => c === index && model.spanAt(r, c).colSpan === 1,
+ capture,
+ );
+ this.shiftCells(doc, page, model, (_r, c) => c > index, -w, 0);
+ model.colEdges = removeColumnEdges(model.colEdges, index).edges;
+ for (const row of model.cellRuns) row.splice(index, 1);
+ for (const row of model.cellSpans) row.splice(index, 1);
+ for (const row of model.cellExtraRuns) row.splice(index, 1);
+ const [dropped] = model.columnStyles.splice(index, 1);
+ if (capture) this.removedStyle = dropped ?? null;
+ }
+
+ private reinsertColumn(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ ): void {
+ const w = this.size;
+ this.shiftCells(doc, page, model, (_r, c) => c >= this.index, w, 0);
+ model.colEdges = insertColumnEdges(model.colEdges, this.index, w).edges;
+ for (const row of model.cellRuns) row.splice(this.index, 0, null);
+ for (const row of model.cellSpans) row.splice(this.index, 0, null);
+ for (const row of model.cellExtraRuns) row.splice(this.index, 0, null);
+ model.columnStyles.splice(
+ this.index,
+ 0,
+ this.removedStyle ?? this.neighbourStyle(model),
+ );
+ this.restoreCaptured(doc);
+ }
+
+ private neighbourStyle(model: TableModel): TableCellStyle {
+ const src =
+ model.columnStyles[this.index - 1] ?? model.columnStyles[this.index];
+ return src
+ ? { ...src, fill: { ...src.fill } }
+ : defaultCellStyle(model.fontSize);
+ }
+
+ private avgRowHeight(model: TableModel): number {
+ const total = model.rowEdges[0] - model.rowEdges[model.rowEdges.length - 1];
+ return total / model.rows;
+ }
+
+ private avgColWidth(model: TableModel): number {
+ const total = model.colEdges[model.colEdges.length - 1] - model.colEdges[0];
+ return total / model.cols;
+ }
+
+ // Move every run whose cell matches `pred` by (dx, dy). Iterates a static
+ // copy of the current cell map so splices elsewhere don't interfere.
+ private shiftCells(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ pred: (r: number, c: number) => boolean,
+ dx: number,
+ dy: number,
+ ): void {
+ if (dx === 0 && dy === 0) return;
+ for (let r = 0; r < model.cellRuns.length; r++) {
+ for (let c = 0; c < model.cellRuns[r].length; c++) {
+ if (!pred(r, c)) continue;
+ for (const id of model.runsAt(r, c)) {
+ const run = page.findRun(id);
+ if (run) shiftRunBy(doc.module, run, dx, dy);
+ }
+ }
+ }
+ }
+
+ private removeTrackRuns(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ pred: (r: number, c: number) => boolean,
+ capture: boolean,
+ ): void {
+ const toRemove = new Set<string>();
+ for (let r = 0; r < model.cellRuns.length; r++) {
+ for (let c = 0; c < model.cellRuns[r].length; c++) {
+ if (pred(r, c)) for (const id of model.runsAt(r, c)) toRemove.add(id);
+ }
+ }
+ if (toRemove.size === 0) return;
+ if (capture) this.removed = [];
+ for (const runId of toRemove) {
+ const cmd = new DeleteObjectCommand({ pageIndex: page.index, runId });
+ cmd.apply(doc);
+ if (capture) this.removed.push(cmd);
+ }
+ }
+
+ private restoreCaptured(doc: EditorDocument): void {
+ for (const cmd of this.removed) cmd.revert(doc);
+ this.removed = [];
+ }
+
+ private adjustSpans(
+ model: TableModel,
+ isRow: boolean,
+ adding: boolean,
+ ): void {
+ if (!this.before) return;
+ for (let r = 0; r < this.before.cellSpans.length; r++) {
+ for (let c = 0; c < this.before.cellSpans[r].length; c++) {
+ const original = this.before.cellSpans[r][c];
+ if (!original) continue;
+ const start = isRow ? r : c;
+ const length = isRow ? original.rowSpan : original.colSpan;
+ if (!adding && start === this.index && length === 1) continue;
+ const next = adding
+ ? start + (start >= this.index ? 1 : 0)
+ : start - (start > this.index ? 1 : 0);
+ const row = isRow ? next : r;
+ const col = isRow ? c : next;
+ const span = { ...original };
+ if (
+ adding
+ ? start < this.index && this.index < start + length
+ : start <= this.index && this.index < start + length
+ ) {
+ if (isRow) span.rowSpan += adding ? 1 : -1;
+ else span.colSpan += adding ? 1 : -1;
+ }
+ model.cellSpans[row][col] =
+ span.rowSpan > 1 || span.colSpan > 1 ? span : null;
+ if (!adding && start === this.index) {
+ model.cellRuns[row][col] = this.before.cellRuns[r][c];
+ model.cellExtraRuns[row][col] = this.before.cellExtraRuns[r][c];
+ }
+ }
+ }
+ }
+
+ describe(): string {
+ return this.op;
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts
index bb06c33501..b180bad7ee 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/MoveShapeCommand.ts
@@ -45,6 +45,20 @@ export class MoveShapeCommand implements Command {
x: shape.bounds.x + dx,
y: shape.bounds.y + dy,
};
+ page.setRules(
+ page.rules.map((rule) =>
+ rule.ptr === shape.pdfiumObjPtr
+ ? { ...rule, x: rule.x + dx, y: rule.y + dy }
+ : rule,
+ ),
+ );
+ page.setFills(
+ page.fills.map((fill) =>
+ fill.ptr === shape.pdfiumObjPtr
+ ? { ...fill, x: fill.x + dx, y: fill.y + dy }
+ : fill,
+ ),
+ );
page.markDirty();
page.markNeedsGenerate();
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts
new file mode 100644
index 0000000000..d34ee20684
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts
@@ -0,0 +1,248 @@
+import { locateTable } from "@app/tools/pdfTextEditor/util/locateTable";
+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 { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import {
+ moveColumnEdge,
+ moveRowEdge,
+ resizeColumnTrack,
+ resizeRowTrack,
+ scaleColumnEdges,
+ scaleRowEdges,
+} from "@app/tools/pdfTextEditor/util/tableGeometry";
+import {
+ absoluteFontScale,
+ applyCellPlacement,
+ captureCellPlacement,
+ type CellPlacement,
+ redrawGrid,
+ setTableEdges,
+ shiftRunBy,
+} from "@app/tools/pdfTextEditor/commands/tableHelpers";
+import { SetFontSizeCommand } from "@app/tools/pdfTextEditor/commands/SetFontSizeCommand";
+
+// A geometry gesture, in PDF points. "col-edge"/"row-edge" move one internal
+// boundary, resizing only the two tracks it separates; "scale" resizes the
+// whole grid from its top-left corner, keeping every track's share; "move"
+// translates the whole thing, changing no track at all.
+export type TableResize =
+ | { kind: "col-edge"; index: number; x: number }
+ | { kind: "row-edge"; index: number; y: number }
+ | { kind: "scale"; width: number; height: number }
+ | { kind: "move"; dx: number; dy: number }
+ // "col-size"/"row-size" resize the single track before the edge, sliding the
+ // rest along, so the table grows or shrinks by what that track gained.
+ | { kind: "col-size"; index: number; x: number }
+ | { kind: "row-size"; index: number; y: number };
+
+// Geometric edit of a session table. Undo restores the exact edge arrays
+// captured at apply, so a resize is one history step no matter how far the
+// pointer travelled.
+export class ResizeTableCommand implements Command {
+ readonly type = "resize-table";
+ private readonly tableId: string;
+ private readonly edit: TableResize;
+ private before: { colEdges: number[]; rowEdges: number[] } | null = null;
+ private placement: CellPlacement[] | null = null;
+ // Exact pen origin AND box before the scale. Undo restores these rather than
+ // re-deriving a position: the font-size revert moves the origin too, so a
+ // delta computed after it drifts.
+ private prevOrigins: {
+ runId: string;
+ e: number;
+ f: number;
+ x: number;
+ y: number;
+ }[] = [];
+ private fontScale = 1;
+ /** Content scale before this command, so undo puts the reference back. */
+ private prevContentScale = 1;
+ private resizes: Command[] = [];
+
+ constructor(opts: { tableId: string; edit: TableResize }) {
+ this.tableId = opts.tableId;
+ this.edit = opts.edit;
+ }
+
+ apply(doc: EditorDocument): void {
+ const found = locateTable(doc, this.tableId);
+ if (!found) return;
+ const { page, model } = found;
+ this.before = {
+ colEdges: [...model.colEdges],
+ rowEdges: [...model.rowEdges],
+ };
+ const { colEdges, rowEdges } = this.nextEdges(model);
+ if (this.edit.kind === "scale") {
+ // Scaling the frame scales what is in it: text kept at its old size in a
+ // shrinking cell just spills over the column beside it.
+ this.placement = captureCellPlacement(doc, page, model);
+ this.prevOrigins = [
+ ...new Set(
+ model.cellRuns.flatMap((row, r) =>
+ row.flatMap((_id, c) => model.runsAt(r, c)),
+ ),
+ ),
+ ]
+ .map((id) => {
+ const run = page.findRun(id);
+ if (!run) return null;
+ return {
+ runId: id,
+ e: run.matrix.e,
+ f: run.matrix.f,
+ x: run.bounds.x,
+ y: run.bounds.y,
+ };
+ })
+ .filter((p) => p !== null);
+ // Derived from the table's size against a FIXED reference, not from this
+ // gesture: an incremental min(widthRatio, heightRatio) does not
+ // round-trip, so grow/shrink cycles walked the type steadily smaller.
+ this.prevContentScale = model.fontBase.scale;
+ const target = absoluteFontScale(model, colEdges, rowEdges);
+ this.fontScale = target / (model.fontBase.scale || 1);
+ model.fontBase.scale = target;
+ this.resizes = scaleCellFonts(doc, page, model, this.fontScale);
+ model.colEdges = [...colEdges];
+ model.rowEdges = [...rowEdges];
+ applyCellPlacement(doc, page, model, this.placement, this.fontScale);
+ redrawGrid(doc, page, model);
+ } else {
+ setTableEdges(doc, page, model, colEdges, rowEdges);
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ revert(doc: EditorDocument): void {
+ const found = locateTable(doc, this.tableId);
+ if (!found || !this.before) return;
+ const { page, model } = found;
+ if (this.edit.kind === "scale") {
+ for (let i = this.resizes.length - 1; i >= 0; i--) {
+ this.resizes[i].revert(doc);
+ }
+ this.resizes = [];
+ model.fontSize /= this.fontScale;
+ for (const style of model.columnStyles) style.fontSize /= this.fontScale;
+ if (model.headerStyle) model.headerStyle.fontSize /= this.fontScale;
+ model.fontBase.scale = this.prevContentScale;
+ model.colEdges = [...this.before.colEdges];
+ model.rowEdges = [...this.before.rowEdges];
+ // Put every entry back where it was, rather than re-deriving a position:
+ // reverting the font size moves the pen origin too, so a delta measured
+ // afterwards drifts by the cell's inset.
+ for (const spot of this.prevOrigins) {
+ const run = page.findRun(spot.runId);
+ if (!run) continue;
+ shiftRunBy(
+ doc.module,
+ run,
+ spot.e - run.matrix.e,
+ spot.f - run.matrix.f,
+ );
+ run.bounds = { ...run.bounds, x: spot.x, y: spot.y };
+ }
+ redrawGrid(doc, page, model);
+ } else {
+ setTableEdges(
+ doc,
+ page,
+ model,
+ this.before.colEdges,
+ this.before.rowEdges,
+ );
+ }
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ private nextEdges(model: TableModel): {
+ colEdges: number[];
+ rowEdges: number[];
+ } {
+ switch (this.edit.kind) {
+ case "col-edge":
+ return {
+ colEdges: moveColumnEdge(
+ model.colEdges,
+ this.edit.index,
+ this.edit.x,
+ ),
+ rowEdges: [...model.rowEdges],
+ };
+ case "row-edge":
+ return {
+ colEdges: [...model.colEdges],
+ rowEdges: moveRowEdge(model.rowEdges, this.edit.index, this.edit.y),
+ };
+ case "scale":
+ return {
+ colEdges: scaleColumnEdges(model.colEdges, this.edit.width),
+ rowEdges: scaleRowEdges(model.rowEdges, this.edit.height),
+ };
+ case "col-size":
+ return {
+ colEdges: resizeColumnTrack(
+ model.colEdges,
+ this.edit.index,
+ this.edit.x,
+ ),
+ rowEdges: [...model.rowEdges],
+ };
+ case "row-size":
+ return {
+ colEdges: [...model.colEdges],
+ rowEdges: resizeRowTrack(
+ model.rowEdges,
+ this.edit.index,
+ this.edit.y,
+ ),
+ };
+ case "move": {
+ const { dx, dy } = this.edit;
+ return {
+ colEdges: model.colEdges.map((x) => x + dx),
+ rowEdges: model.rowEdges.map((y) => y + dy),
+ };
+ }
+ }
+ }
+
+ describe(): string {
+ return `resize-table:${this.edit.kind}`;
+ }
+}
+
+// Resize every cell's text through the toolbar's own font-size command, so the
+// glyph scaling, matrix and letter-spacing bookkeeping stay in one place.
+function scaleCellFonts(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ scale: number,
+): Command[] {
+ if (scale === 1) return [];
+ const applied: Command[] = [];
+ for (let r = 0; r < model.rows; r++) {
+ for (let c = 0; c < model.cols; c++) {
+ for (const id of model.runsAt(r, c)) {
+ const run = page.findRun(id);
+ if (!run || run.fontSize <= 0) continue;
+ const cmd = new SetFontSizeCommand({
+ pageIndex: model.pageIndex,
+ runId: id,
+ nextSize: run.fontSize * scale,
+ });
+ cmd.apply(doc);
+ applied.push(cmd);
+ }
+ }
+ }
+ model.fontSize *= scale;
+ for (const style of model.columnStyles) style.fontSize *= scale;
+ if (model.headerStyle) model.headerStyle.fontSize *= scale;
+ return applied;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
index 14c3b89bb5..c7bfcc36d8 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/SetColourCommand.ts
@@ -111,7 +111,7 @@ export class SetColourCommand implements Command {
}
/** Read an object's current fill colour (0-255 RGBA), or null on failure. */
-function readObjFill(
+export function readObjFill(
m: import("@embedpdf/pdfium").WrappedPdfiumModule,
objPtr: number,
): RGBA | null {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts
index 6346aa8ced..e505272db0 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts
@@ -91,6 +91,7 @@ export class UngroupParagraphCommand implements Command {
fontSize: rep.fontSize,
fill: { ...rep.fill },
fontSubset: rep.fontSubset,
+ renderMode: rep.renderMode,
});
r.containerPtr = containers[i] ?? 0;
newRuns.push(r);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
index dcbca07c3a..0edffabec1 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/editTextHelpers.ts
@@ -1305,6 +1305,46 @@ export function measureObjRightEdgePt(
}
}
+/**
+ * Full page-space box of an object, or null when it cannot be measured.
+ *
+ * A freshly emitted text object knows its baseline but not its ink extent, and
+ * every run READ from the page stores the ink bottom - so a run whose box was
+ * estimated instead of measured draws in the wrong place until something
+ * recaptures it.
+ */
+export function measureObjBoxPt(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+): { x: number; y: number; width: number; height: number } | null {
+ const l = m.pdfium.wasmExports.malloc(4);
+ const b = m.pdfium.wasmExports.malloc(4);
+ const r = m.pdfium.wasmExports.malloc(4);
+ const t = m.pdfium.wasmExports.malloc(4);
+ try {
+ if (!m.FPDFPageObj_GetBounds(objPtr, l, b, r, t)) return null;
+ const left = m.pdfium.getValue(l, "float");
+ const bottom = m.pdfium.getValue(b, "float");
+ const right = m.pdfium.getValue(r, "float");
+ const top = m.pdfium.getValue(t, "float");
+ if (![left, bottom, right, top].every(Number.isFinite)) return null;
+ return {
+ x: Math.min(left, right),
+ y: Math.min(bottom, top),
+ width: Math.abs(right - left),
+ height: Math.abs(top - bottom),
+ };
+ } catch {
+ // Measuring is never worth failing the mutation that asked for it.
+ return null;
+ } finally {
+ m.pdfium.wasmExports.free(l);
+ m.pdfium.wasmExports.free(b);
+ m.pdfium.wasmExports.free(r);
+ m.pdfium.wasmExports.free(t);
+ }
+}
+
/**
* Horizontal span covered by `ptrs`, or null when nothing is measurable.
*
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/commands/tableHelpers.ts b/frontend/editor/src/core/tools/pdfTextEditor/commands/tableHelpers.ts
new file mode 100644
index 0000000000..a69e389c28
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/commands/tableHelpers.ts
@@ -0,0 +1,660 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@app/tools/pdfTextEditor/model/Page";
+import type { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+import { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import { BLACK } from "@app/tools/pdfTextEditor/model/Color";
+import type { RGBA } from "@app/tools/pdfTextEditor/types";
+import type { RowFill } from "@app/tools/pdfTextEditor/model/TableModel";
+import { writeUtf16 } from "@app/services/pdfiumService";
+import {
+ measureObjBoxPt,
+ measureObjSpanPt,
+ sanitizeForBase14,
+} from "@app/tools/pdfTextEditor/commands/editTextHelpers";
+import { transformObject } from "@app/tools/pdfTextEditor/util/objectTransform";
+
+const LINE_RGB = { r: 0, g: 0, b: 0 } as const;
+const CELL_FAMILY = "Helvetica";
+/** Inset of cell text from the cell's left/bottom edges, in points. */
+const CELL_PAD = 3;
+/** Within this, an entry reads as centred rather than set against an edge. */
+const ANCHOR_TOLERANCE_PT = 1.5;
+
+// A ruling line is a thin filled rectangle: robust across PDFium builds and
+// needs no stroke-path support. Returns the object pointer.
+function emitLineRect(
+ m: WrappedPdfiumModule,
+ page: Page,
+ rect: { x: number; y: number; width: number; height: number },
+ color: RGBA = { ...LINE_RGB, a: 255 },
+): number {
+ const ptr = m.FPDFPageObj_CreateNewRect(
+ rect.x,
+ rect.y,
+ rect.width,
+ rect.height,
+ );
+ if (!ptr) return 0;
+ m.FPDFPageObj_SetFillColor(ptr, color.r, color.g, color.b, color.a);
+ // Draw mode 2 = fill.
+ m.FPDFPath_SetDrawMode(ptr, 2, false);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ page.rules.push({
+ ...rect,
+ ptr,
+ thickness: Math.min(rect.width, rect.height),
+ color: { ...color },
+ });
+ return ptr;
+}
+
+// Stretch each adopted row background onto the row it belongs to. The object is
+// TRANSFORMED rather than redrawn: that keeps its exact paint and, crucially,
+// its place in the z-order, so it stays behind the text instead of covering it.
+export function refitRowFills(doc: EditorDocument, model: TableModel): void {
+ if (model.rowFills.length === 0) return;
+ const m = doc.module;
+ const left = model.colEdges[0];
+ const right = model.colEdges[model.colEdges.length - 1];
+ for (const fill of model.rowFills) {
+ if (fill.row >= model.rows) continue;
+ const target = {
+ x: left,
+ y: model.rowEdges[fill.row + 1],
+ width: right - left,
+ height: model.rowEdges[fill.row] - model.rowEdges[fill.row + 1],
+ };
+ const from = fill.rect;
+ if (from.width <= 0 || from.height <= 0) continue;
+ if (
+ Math.abs(from.x - target.x) < 0.01 &&
+ Math.abs(from.y - target.y) < 0.01 &&
+ Math.abs(from.width - target.width) < 0.01 &&
+ Math.abs(from.height - target.height) < 0.01
+ ) {
+ continue;
+ }
+ const sx = target.width / from.width;
+ const sy = target.height / from.height;
+ m.FPDFPageObj_Transform(
+ fill.ptr,
+ sx,
+ 0,
+ 0,
+ sy,
+ target.x - from.x * sx,
+ target.y - from.y * sy,
+ );
+ fill.rect = target;
+ }
+}
+
+interface ZOrderModule {
+ FPDFPage_InsertObjectAtIndex?: (
+ page: number,
+ obj: number,
+ index: number,
+ ) => boolean | number;
+}
+
+// Paint a row's background and put it at the BOTTOM of the page's object list.
+// Appending would place it last, which in PDF means on top - covering the very
+// text it is meant to sit behind.
+export function paintRowFill(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ row: number,
+ color: RGBA,
+): RowFill | null {
+ const m = doc.module;
+ const rect = {
+ x: model.colEdges[0],
+ y: model.rowEdges[row + 1],
+ width: model.colEdges[model.cols] - model.colEdges[0],
+ height: model.rowEdges[row] - model.rowEdges[row + 1],
+ };
+ if (rect.width <= 0 || rect.height <= 0) return null;
+ const ptr = m.FPDFPageObj_CreateNewRect(
+ rect.x,
+ rect.y,
+ rect.width,
+ rect.height,
+ );
+ if (!ptr) return null;
+ m.FPDFPageObj_SetFillColor(ptr, color.r, color.g, color.b, color.a);
+ m.FPDFPath_SetDrawMode(ptr, 2, false);
+ const ext = m as unknown as ZOrderModule;
+ if (ext.FPDFPage_InsertObjectAtIndex) {
+ ext.FPDFPage_InsertObjectAtIndex(page.pagePtr, ptr, 0);
+ } else {
+ // Without index insertion the fill would cover the text, so draw nothing.
+ m.FPDFPageObj_Destroy(ptr);
+ return null;
+ }
+ return { row, ptr, rect, color: { ...color } };
+}
+
+// The paint a row added at `row` should take, continuing whatever pattern the
+// table already has. Banding alternates, so the row two back is the match.
+export function bandColorFor(model: TableModel, row: number): RGBA | null {
+ if (model.rowFills.length === 0) return null;
+ const byRow = new Map(model.rowFills.map((f) => [f.row, f.color]));
+ for (let back = 2; back <= row; back += 2) {
+ const hit = byRow.get(row - back);
+ if (hit) return { ...hit };
+ }
+ // Not enough rows to see a pattern: match the nearest painted row instead.
+ let best: RowFill | null = null;
+ for (const fill of model.rowFills) {
+ if (!best || Math.abs(fill.row - row) < Math.abs(best.row - row)) {
+ best = fill;
+ }
+ }
+ return best ? { ...best.color } : null;
+}
+
+/** Remove and destroy objects that will be recreated on undo; never use for retained text. */
+export function removeObjects(
+ m: WrappedPdfiumModule,
+ page: Page,
+ ptrs: number[],
+): void {
+ for (const ptr of new Set(ptrs)) {
+ if (ptr && m.FPDFPage_RemoveObject(page.pagePtr, ptr))
+ m.FPDFPageObj_Destroy(ptr);
+ }
+ const removed = new Set(ptrs);
+ page.setRules(page.rules.filter((rule) => !removed.has(rule.ptr)));
+ page.setFills(page.fills.filter((fill) => !removed.has(fill.ptr)));
+ page.setShapes(
+ page.shapes.filter((shape) => !removed.has(shape.pdfiumObjPtr)),
+ );
+}
+
+// Remove the model's current ruling lines and draw a fresh grid for its current
+// geometry, updating the stored pointers. Used by every structural edit so line
+// bookkeeping stays trivial.
+export function redrawGrid(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+): void {
+ // Backgrounds move with the grid whether or not we own the lines.
+ refitRowFills(doc, model);
+ if (!model.ruled) return;
+ const m = doc.module;
+ removeObjects(m, page, [...model.hLinePtrs, ...model.vLinePtrs]);
+ const t = model.lineWidth;
+ // A merged cell is a boundary the page does NOT draw across those tracks, so
+ // each edge is emitted as the segments that survive the merges. Repainting a
+ // plain rectangle here would erase every merge on the first structural edit.
+ const hidden = hiddenEdges(model);
+ const hLinePtrs: number[] = [];
+ for (let r = 0; r < model.rowEdges.length; r++) {
+ for (const seg of edgeSegments(model.cols, r, hidden.h)) {
+ const ptr = emitLineRect(
+ m,
+ page,
+ {
+ x: model.colEdges[seg.from],
+ y: model.rowEdges[r] - t / 2,
+ width: model.colEdges[seg.to] - model.colEdges[seg.from],
+ height: t,
+ },
+ model.lineColor,
+ );
+ if (ptr) hLinePtrs.push(ptr);
+ }
+ }
+ const vLinePtrs: number[] = [];
+ for (let c = 0; c < model.colEdges.length; c++) {
+ for (const seg of edgeSegments(model.rows, c, hidden.v)) {
+ const ptr = emitLineRect(
+ m,
+ page,
+ {
+ x: model.colEdges[c] - t / 2,
+ y: model.rowEdges[seg.to],
+ width: t,
+ height: model.rowEdges[seg.from] - model.rowEdges[seg.to],
+ },
+ model.lineColor,
+ );
+ if (ptr) vLinePtrs.push(ptr);
+ }
+ }
+ model.hLinePtrs = hLinePtrs;
+ model.vLinePtrs = vLinePtrs;
+}
+
+// Where the table's own text sits inside its cells. A new entry has to land on
+// the same baseline and the same inset as the ones already there, so both are
+// measured off the existing runs rather than re-derived from the cell box - a
+// fixed pad puts new text a whole column-gap left of every neighbour.
+interface CellMetrics {
+ /** Baseline height above the row's bottom edge. */
+ baselineOffset: number;
+ /** Gap from the cell's left edge to the ink, per column. */
+ leftInset: number[];
+ /** Gap from the ink to the cell's right edge, per column. */
+ rightInset: number[];
+}
+
+function median(values: number[]): number | null {
+ if (values.length === 0) return null;
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+function measureCells(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+): CellMetrics {
+ const baselines: number[] = [];
+ const lefts: number[][] = Array.from({ length: model.cols }, () => []);
+ const rights: number[][] = Array.from({ length: model.cols }, () => []);
+ for (let r = 0; r < model.rows; r++) {
+ for (let c = 0; c < model.cols; c++) {
+ const id = model.cellRuns[r]?.[c];
+ if (!id) continue;
+ const run = page.findRun(id);
+ if (!run) continue;
+ baselines.push(run.matrix.f - model.rowEdges[r + 1]);
+ const box = run.pdfiumObjPtr
+ ? measureObjSpanPt(doc.module, [run.pdfiumObjPtr])
+ : null;
+ const left = box ? box.left : run.bounds.x;
+ const right = box ? box.right : run.bounds.x + run.bounds.width;
+ // A merged cell's inset is a property of the merge, not of any one
+ // column, so it must not pollute the column's pool.
+ if (model.spanAt(r, c).colSpan > 1) continue;
+ lefts[c].push(left - model.colEdges[c]);
+ rights[c].push(model.colEdges[c + 1] - right);
+ }
+ }
+ const allLefts = lefts.flat();
+ const allRights = rights.flat();
+ const fallbackLeft = median(allLefts) ?? CELL_PAD;
+ const fallbackRight = median(allRights) ?? CELL_PAD;
+ return {
+ baselineOffset: median(baselines) ?? -1,
+ leftInset: lefts.map((xs) => Math.max(0, median(xs) ?? fallbackLeft)),
+ rightInset: rights.map((xs) => Math.max(0, median(xs) ?? fallbackRight)),
+ };
+}
+
+// The stretches of one grid edge that are actually drawn. An edge is skipped
+// across any track where a merge straddles it; adjacent kept tracks are joined
+// into one rect so an unmerged edge still emits a single object.
+function edgeSegments(
+ count: number,
+ index: number,
+ hidden: Set<number>,
+): { from: number; to: number }[] {
+ const out: { from: number; to: number }[] = [];
+ let start: number | null = null;
+ for (let i = 0; i < count; i++) {
+ const drawn = !hidden.has(index * count + i);
+ if (drawn && start === null) start = i;
+ if (!drawn && start !== null) {
+ out.push({ from: start, to: i });
+ start = null;
+ }
+ }
+ if (start !== null) out.push({ from: start, to: count });
+ return out;
+}
+
+function hiddenEdges(model: TableModel): { h: Set<number>; v: Set<number> } {
+ const h = new Set<number>();
+ const v = new Set<number>();
+ for (let r = 0; r < model.rows; r++) {
+ for (let c = 0; c < model.cols; c++) {
+ const span = model.cellSpans[r]?.[c];
+ if (!span) continue;
+ const bottom = Math.min(r + span.rowSpan, model.rows);
+ const right = Math.min(c + span.colSpan, model.cols);
+ for (let rr = r; rr < bottom; rr++) {
+ for (let cc = c; cc < right; cc++) {
+ if (rr > r) h.add(rr * model.cols + cc);
+ if (cc > c) v.add(cc * model.rows + rr);
+ }
+ }
+ }
+ }
+ return { h, v };
+}
+
+/** Baseline anchor (x, y) for text placed in a cell, before alignment. */
+export function cellTextAnchor(
+ model: TableModel,
+ row: number,
+ col: number,
+): { x: number; y: number } {
+ const rect = model.cellRect(row, col);
+ const size = model.styleFor(row, col).fontSize;
+ const baseline =
+ rect.y + Math.max(CELL_PAD, (rect.height - size) / 2 + size * 0.2);
+ return { x: rect.x + CELL_PAD, y: baseline };
+}
+
+// Write text into a cell in that column's own style - family, size, colour -
+// and slide it to the column's alignment. The shift is measured off the emitted
+// object rather than predicted, so it matches the glyphs PDFium actually laid.
+export function emitStyledCellText(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ row: number,
+ col: number,
+ text: string,
+): EmittedText | null {
+ const style = model.styleFor(row, col);
+ const metrics = measureCells(doc, page, model);
+ const rect = model.cellRect(row, col);
+ const fallback = cellTextAnchor(model, row, col);
+ // Sit on the table's own baseline when it has one; centre only in an empty
+ // table where there is nothing to line up with.
+ const baseline =
+ metrics.baselineOffset >= 0
+ ? model.rowEdges[row + 1] + metrics.baselineOffset
+ : fallback.y;
+ const leftInset = metrics.leftInset[col] ?? CELL_PAD;
+ const emitted = emitCellText(
+ doc,
+ page,
+ rect.x + leftInset,
+ baseline,
+ text,
+ style.fontSize,
+ style.fill,
+ style.family,
+ );
+ if (!emitted) return null;
+ const span = measureObjSpanPt(doc.module, [emitted.ptr]);
+ if (span) {
+ const width = span.right - span.left;
+ const rightInset = metrics.rightInset[col] ?? CELL_PAD;
+ let dx = 0;
+ if (style.align === "right") {
+ dx = rect.x + rect.width - rightInset - span.right;
+ } else if (style.align === "center") {
+ dx = rect.x + (rect.width - width) / 2 - span.left;
+ }
+ // An entry wider than its cell keeps its alignment; it is only stopped
+ // from running out of the table.
+ if (dx !== 0) {
+ const clamped = Math.max(dx, model.colEdges[0] - span.left);
+ shiftRunBy(doc.module, emitted.run, clamped, 0);
+ }
+ emitted.run.bounds = {
+ ...emitted.run.bounds,
+ x: emitted.run.bounds.x,
+ width,
+ };
+ }
+ return emitted;
+}
+
+export interface EmittedText {
+ ptr: number;
+ run: TextRun;
+}
+
+// Insert a base-14 (Helvetica) text object at a page-space point and register a
+// matching run. Mirrors InsertTextCommand's core; used for cell content.
+export function emitCellText(
+ doc: EditorDocument,
+ page: Page,
+ x: number,
+ y: number,
+ text: string,
+ fontSize: number,
+ fill: RGBA = BLACK,
+ family: string = CELL_FAMILY,
+): EmittedText | null {
+ const m = doc.module;
+ const sanitized = sanitizeForBase14(text);
+ // PDFium can only build a text object for a base-14 name; a family it cannot
+ // resolve returns 0, so fall back rather than dropping the text.
+ const ptr =
+ m.FPDFPageObj_NewTextObj(doc.docPtr, family, fontSize) ||
+ m.FPDFPageObj_NewTextObj(doc.docPtr, CELL_FAMILY, fontSize);
+ if (!ptr) return null;
+ const textPtr = writeUtf16(m, sanitized);
+ try {
+ m.FPDFText_SetText(ptr, textPtr);
+ } finally {
+ m.pdfium.wasmExports.free(textPtr);
+ }
+ m.FPDFPageObj_SetFillColor(ptr, fill.r, fill.g, fill.b, fill.a);
+ m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, x, y);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+
+ const runId = `p${page.index}-cell-${page.runs.length}-${ptr}`;
+ // Measured, not estimated: a guessed box puts the editing overlay off the
+ // glyphs until something recaptures the run, which is why new cell text
+ // looked right only after a save.
+ const measured = measureObjBoxPt(m, ptr);
+ const run = new TextRun({
+ id: runId,
+ pageIndex: page.index,
+ pdfiumObjPtr: ptr,
+ bounds: measured ?? {
+ x,
+ y,
+ width: Math.max(1, text.length * fontSize * 0.55),
+ height: fontSize * 1.2,
+ },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: x, f: y },
+ text,
+ fontId: `base14:${family}`,
+ fontSize,
+ fill: { ...fill },
+ fontSubset: false,
+ });
+ page.setRuns([...page.runs, run]);
+ return { ptr, run };
+}
+
+/** Translate a run and its PDFium object by (dx, dy) page points. */
+export function shiftRunBy(
+ m: WrappedPdfiumModule,
+ run: TextRun,
+ dx: number,
+ dy: number,
+): void {
+ if (dx === 0 && dy === 0) return;
+ // Every object the run is built from, not just its representative: one run
+ // can be a paragraph PDFium grouped from several text objects, and moving
+ // only the first strands the rest where they were. OCR makes this obvious -
+ // it emits an object per word - but any merged cell has the same shape.
+ const members = new Set<number>();
+ for (const ptr of run.paragraphLeafPtrs) if (ptr) members.add(ptr);
+ for (const ptr of run.mergedFromPtrs) if (ptr) members.add(ptr);
+ if (members.size === 0 && run.pdfiumObjPtr) members.add(run.pdfiumObjPtr);
+ for (const ptr of members) {
+ transformObject(m, ptr, 1, 0, 0, 1, dx, dy);
+ }
+ run.matrix = { ...run.matrix, e: run.matrix.e + dx, f: run.matrix.f + dy };
+ run.bounds = { ...run.bounds, x: run.bounds.x + dx, y: run.bounds.y + dy };
+ run.dirty = true;
+}
+
+// Replace a table's grid with new edges, carrying each cell's text along with
+// its cell so content keeps its position within the cell rather than being
+// re-anchored. Used by every resize; reversible by calling it with the old
+// edges.
+export function setTableEdges(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ colEdges: number[],
+ rowEdges: number[],
+): void {
+ const moves: { run: TextRun; dx: number; dy: number }[] = [];
+ for (let r = 0; r < model.cellRuns.length; r++) {
+ for (let c = 0; c < model.cellRuns[r].length; c++) {
+ const id = model.cellRuns[r][c];
+ if (!id) continue;
+ const run = page.findRun(id);
+ if (!run) continue;
+ const from = model.cellRect(r, c);
+ const { colSpan } = model.spanAt(r, c);
+ const nextEdge = colEdges[Math.min(c + colSpan, colEdges.length - 1)];
+ // Follow the edge this entry is actually set against, judged from where
+ // it sits now rather than from the column's style: a left-aligned header
+ // over a right-aligned column has to track the left edge, or narrowing
+ // the column from the left strands it on the wrong side of the divider.
+ const span = run.pdfiumObjPtr
+ ? measureObjSpanPt(doc.module, [run.pdfiumObjPtr])
+ : null;
+ const left = span ? span.left : run.bounds.x;
+ const right = span ? span.right : run.bounds.x + run.bounds.width;
+ const lead = left - from.x;
+ const trail = from.x + from.width - right;
+ // The entry moves BY the edge's delta, keeping whatever inset it had -
+ // snapping it onto the edge instead would strip the cell's padding.
+ const dx =
+ Math.abs(lead - trail) <= ANCHOR_TOLERANCE_PT
+ ? (colEdges[c] + nextEdge) / 2 - (from.x + from.width / 2)
+ : trail < lead
+ ? nextEdge - (from.x + from.width)
+ : colEdges[c] - from.x;
+ const bottom = Math.min(r + model.spanAt(r, c).rowSpan, model.rows);
+ const dy = rowEdges[bottom] - from.y;
+ moves.push({ run, dx, dy });
+ // Other runs in the same cell ride along with it.
+ for (const extra of model.cellExtraRuns[r]?.[c] ?? []) {
+ const other = page.findRun(extra);
+ if (other) moves.push({ run: other, dx, dy });
+ }
+ }
+ }
+ model.colEdges = [...colEdges];
+ model.rowEdges = [...rowEdges];
+ renormaliseFontBase(model);
+ for (const mv of moves) shiftRunBy(doc.module, mv.run, mv.dx, mv.dy);
+ redrawGrid(doc, page, model);
+}
+
+// Keep the font reference in step with a size change that is NOT a content
+// scale - an edge drag or an added column changes the table's extent without
+// touching its type, and the reference has to move with it or the next scale
+// would try to correct for it.
+export function renormaliseFontBase(model: TableModel): void {
+ const width = model.colEdges[model.colEdges.length - 1] - model.colEdges[0];
+ const height = model.rowEdges[0] - model.rowEdges[model.rowEdges.length - 1];
+ const scale = model.fontBase.scale || 1;
+ if (width > 0) model.fontBase.width = width / scale;
+ if (height > 0) model.fontBase.height = height / scale;
+}
+
+/** The content scale the table's CURRENT size calls for. */
+export function absoluteFontScale(
+ model: TableModel,
+ colEdges: number[],
+ rowEdges: number[],
+): number {
+ const width = colEdges[colEdges.length - 1] - colEdges[0];
+ const height = rowEdges[0] - rowEdges[rowEdges.length - 1];
+ if (model.fontBase.width <= 0 || model.fontBase.height <= 0) return 1;
+ return Math.min(width / model.fontBase.width, height / model.fontBase.height);
+}
+
+// Where one cell's text sits relative to its cell, so it can be put back the
+// same way after the grid changes shape. Scaling a table has to carry the text
+// with it - moving it alone leaves entries hanging out of narrowed columns.
+export interface CellPlacement {
+ runId: string;
+ row: number;
+ col: number;
+ anchor: "left" | "right" | "center";
+ /** Gap from the anchor edge of its cell, in points. */
+ inset: number;
+ /** Baseline height above the row's bottom edge. */
+ baseline: number;
+}
+
+export function captureCellPlacement(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+): CellPlacement[] {
+ const out: CellPlacement[] = [];
+ for (let r = 0; r < model.rows; r++) {
+ for (let c = 0; c < model.cols; c++) {
+ for (const id of model.runsAt(r, c)) {
+ const run = page.findRun(id);
+ if (!run) continue;
+ const cell = model.cellRect(r, c);
+ const span = run.pdfiumObjPtr
+ ? measureObjSpanPt(doc.module, [run.pdfiumObjPtr])
+ : null;
+ const left = span ? span.left : run.bounds.x;
+ const right = span ? span.right : run.bounds.x + run.bounds.width;
+ const lead = left - cell.x;
+ const trail = cell.x + cell.width - right;
+ const anchor =
+ Math.abs(lead - trail) <= ANCHOR_TOLERANCE_PT
+ ? "center"
+ : trail < lead
+ ? "right"
+ : "left";
+ out.push({
+ runId: id,
+ row: r,
+ col: c,
+ anchor,
+ inset: anchor === "right" ? trail : lead,
+ baseline: run.matrix.f - cell.y,
+ });
+ }
+ }
+ }
+ return out;
+}
+
+// Put each entry back at its captured position in the grid as it stands now,
+// with insets and baselines scaled by `scale` so a resized table keeps its
+// proportions rather than just its content.
+export function applyCellPlacement(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+ plan: CellPlacement[],
+ scale: number,
+): void {
+ for (const spot of plan) {
+ const run = page.findRun(spot.runId);
+ if (!run) continue;
+ if (spot.row >= model.rows || spot.col >= model.cols) continue;
+ const span = run.pdfiumObjPtr
+ ? measureObjSpanPt(doc.module, [run.pdfiumObjPtr])
+ : null;
+ const left = span ? span.left : run.bounds.x;
+ const right = span ? span.right : run.bounds.x + run.bounds.width;
+ const cellLeft = model.colEdges[spot.col];
+ const cellRight =
+ model.colEdges[
+ Math.min(
+ spot.col + model.spanAt(spot.row, spot.col).colSpan,
+ model.cols,
+ )
+ ];
+ const inset = spot.inset * scale;
+ const dx =
+ spot.anchor === "right"
+ ? cellRight - inset - right
+ : spot.anchor === "center"
+ ? (cellLeft + cellRight) / 2 - (left + right) / 2
+ : cellLeft + inset - left;
+ const targetBaseline =
+ model.cellRect(spot.row, spot.col).y + spot.baseline * scale;
+ const dy = targetBaseline - run.matrix.f;
+ shiftRunBy(doc.module, run, dx, dy);
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx
index 94e0d06458..49dc6e91db 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/EditorTopBar.tsx
@@ -22,6 +22,8 @@ interface EditorTopBarProps {
controller: Controller;
addTextArmed: boolean;
onToggleAddText: () => void;
+ addTableArmed: boolean;
+ onToggleAddTable: () => void;
findOpen: boolean;
onToggleFind: () => void;
onShowHelp: () => void;
@@ -33,6 +35,8 @@ export function EditorTopBar({
controller,
addTextArmed,
onToggleAddText,
+ addTableArmed,
+ onToggleAddTable,
findOpen,
onToggleFind,
onShowHelp,
@@ -50,6 +54,12 @@ export function EditorTopBar({
? t("pdfTextEditor.sidebar.clickPageToAddText", "Click page to add text")
: t("pdfTextEditor.sidebar.addText", "Add text");
const addImageLabel = t("pdfTextEditor.sidebar.addImage", "Add image");
+ const addTableLabel = addTableArmed
+ ? t(
+ "pdfTextEditor.sidebar.clickPageToAddTable",
+ "Click page to add a table",
+ )
+ : t("pdfTextEditor.sidebar.addTable", "Add table");
const findLabel = t("pdfTextEditor.settings.find", "Find in document");
const helpLabel = t("pdfTextEditor.help.ariaLabel", "Keyboard shortcuts");
@@ -137,6 +147,14 @@ export function EditorTopBar({
>
{addTextLabel}
</Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="table" size={20} />}
+ onClick={onToggleAddTable}
+ data-testid="pdf-editor-add-table"
+ aria-pressed={addTableArmed}
+ >
+ {addTableLabel}
+ </Menu.Item>
<Menu.Item
leftSection={<Icon name="image" size={20} />}
onClick={() => session?.pickImage()}
@@ -187,6 +205,19 @@ export function EditorTopBar({
: t("pdfTextEditor.sidebar.addText", "Add text")}
</Button>
</Tooltip>
+ <Tooltip label={addTableLabel}>
+ <Button
+ size="sm"
+ variant={addTableArmed ? "primary" : "tertiary"}
+ accent={addTableArmed ? "default" : "neutral"}
+ leftSection={<Icon name="table" size={20} />}
+ onClick={onToggleAddTable}
+ aria-label={addTableLabel}
+ aria-pressed={addTableArmed}
+ data-testid="pdf-editor-add-table"
+ style={NO_SHRINK}
+ />
+ </Tooltip>
<Tooltip label={t("pdfTextEditor.sidebar.addImage", "Add image")}>
<Button
size="sm"
@@ -198,7 +229,9 @@ export function EditorTopBar({
aria-label={t("pdfTextEditor.sidebar.addImage", "Add image")}
data-testid="pdf-editor-add-image"
style={NO_SHRINK}
- />
+ >
+ {t("pdfTextEditor.sidebar.image", "Image")}
+ </Button>
</Tooltip>
<Tooltip
label={t("pdfTextEditor.settings.findTooltip", {
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx
index f79e6312b3..c4bea8f233 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/MobileActionBar.tsx
@@ -12,6 +12,7 @@ interface Props {
store: EditorStore;
controller: Controller;
addTextArmed: boolean;
+ addTableArmed: boolean;
findOpen: boolean;
}
@@ -19,6 +20,7 @@ export function MobileActionBar({
store,
controller,
addTextArmed,
+ addTableArmed,
findOpen,
}: Props) {
const { t } = useTranslation();
@@ -27,13 +29,18 @@ export function MobileActionBar({
return (
<>
- {addTextArmed && (
+ {(addTextArmed || addTableArmed) && (
<div className="pdf-editor-mbar__hint" role="status">
<span>
- {t(
- "pdfTextEditor.mobile.tapToPlace",
- "Tap the page where the text should go",
- )}
+ {addTableArmed
+ ? t(
+ "pdfTextEditor.sidebar.clickPageToAddTable",
+ "Click page to add a table",
+ )
+ : t(
+ "pdfTextEditor.mobile.tapToPlace",
+ "Tap the page where the text should go",
+ )}
</span>
<BarButton
icon="x"
@@ -118,6 +125,15 @@ export function MobileActionBar({
onClick={() => store.setMode(addTextArmed ? "select" : "addText")}
data-testid="pdf-editor-add-text"
/>
+ <BarButton
+ icon="table"
+ label={t("pdfTextEditor.sidebar.table", "Table")}
+ pressed={addTableArmed}
+ onClick={() =>
+ store.setMode(addTableArmed ? "select" : "addTable")
+ }
+ data-testid="pdf-editor-add-table"
+ />
<BarButton
icon="image-plus"
label={t("pdfTextEditor.mobile.addImage", "Image")}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx
index 186a8cb601..afc6bdf384 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PageStage.tsx
@@ -27,6 +27,7 @@ import { EditTextCommand } from "@app/tools/pdfTextEditor/commands/EditTextComma
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 { InsertTableCommand } from "@app/tools/pdfTextEditor/commands/InsertTableCommand";
import { MoveTextRunCommand } from "@app/tools/pdfTextEditor/commands/MoveTextRunCommand";
import { SetImageTransformCommand } from "@app/tools/pdfTextEditor/commands/SetImageTransformCommand";
import type { SelectionState } from "@app/tools/pdfTextEditor/types";
@@ -124,6 +125,12 @@ export function PageStage() {
hasDocument={state.hasDocument}
dirty={state.dirty}
addTextArmed={state.mode === "addText"}
+ addTableArmed={state.mode === "addTable"}
+ onToggleAddTable={() =>
+ store.setMode(
+ store.getState().mode === "addTable" ? "select" : "addTable",
+ )
+ }
onToggleAddText={() =>
store.setMode(
store.getState().mode === "addText" ? "select" : "addText",
@@ -335,6 +342,7 @@ export function PageStage() {
<PageView
key={page.pageIndex}
document={store.document}
+ store={store}
page={page}
scale={state.renderScale || DEFAULT_SCALE}
widthMode={state.widthMode}
@@ -392,6 +400,20 @@ export function PageStage() {
);
}}
onPageClick={(pageIndex, pageX, pageY) => {
+ if (state.mode === "addTable") {
+ const cmd = new InsertTableCommand({
+ pageIndex,
+ x: pageX,
+ y: pageY,
+ width: 360,
+ height: 24 * 3,
+ rows: 3,
+ cols: 3,
+ });
+ store.dispatch(cmd);
+ store.setMode("select");
+ return;
+ }
if (state.mode !== "addText") return;
const cmd = new InsertTextCommand({
pageIndex,
@@ -441,6 +463,7 @@ export function PageStage() {
store={store}
controller={controller}
addTextArmed={state.mode === "addText"}
+ addTableArmed={state.mode === "addTable"}
findOpen={state.findOpen}
/>
)}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
index e24a3e169a..2f30a9ea48 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
@@ -6,7 +6,9 @@ import { PdfiumPageRenderer } from "@app/tools/pdfTextEditor/pdfium/PdfiumPageRe
import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
import type { PageSnapshot } from "@app/tools/pdfTextEditor/types";
import { TextRunOverlay } from "@app/tools/pdfTextEditor/components/TextRunOverlay";
+import { TableOverlay } from "@app/tools/pdfTextEditor/components/TableOverlay";
import { ImageHandle } from "@app/tools/pdfTextEditor/components/ImageHandle";
+import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
import { ShapeHandle } from "@app/tools/pdfTextEditor/components/ShapeHandle";
import { AnnotationOutline } from "@app/tools/pdfTextEditor/components/AnnotationOutline";
import { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
@@ -15,6 +17,8 @@ import { useDevicePixelRatio } from "@app/tools/pdfTextEditor/hooks/useDevicePix
interface PageViewProps {
document: EditorDocument;
+ /** Store, for the table overlay's dispatch/selection. */
+ store: EditorStore;
page: PageSnapshot;
/** Fires when the page enters the viewport for the first time. */
onFirstVisible?: (pageIndex: number) => void;
@@ -79,6 +83,7 @@ function nearestScrollRoot(el: HTMLElement): HTMLElement | null {
// positioned, editable element per text run.
export function PageView({
document,
+ store,
page,
scale,
widthMode,
@@ -255,6 +260,8 @@ export function PageView({
>
<canvas
ref={canvasRef}
+ // Lets a rebuild sample the scan's own colours off the rendered page.
+ data-page-canvas={page.pageIndex}
style={{
display: "block",
width: raster.width,
@@ -373,6 +380,14 @@ export function PageView({
}
/>
))}
+ {/* Grid + empty-cell editors sit below the run overlays so filled
+ cells are edited through their own run. */}
+ <TableOverlay
+ page={page}
+ transform={transform}
+ scale={cssScale}
+ store={store}
+ />
{page.runs.map((run) => (
<TextRunOverlay
key={run.id}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/TableOverlay.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/TableOverlay.tsx
new file mode 100644
index 0000000000..20a3e658cd
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/TableOverlay.tsx
@@ -0,0 +1,864 @@
+import { useMemo, useRef, useState } from "react";
+import { Tooltip } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import type { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
+import type {
+ PageRect,
+ PageSnapshot,
+ RGBA,
+ TableCellStyle,
+ TableSnapshot,
+} from "@app/tools/pdfTextEditor/types";
+import type { EditorStore } from "@app/tools/pdfTextEditor/store/EditorStore";
+import { overlaps } from "@app/tools/pdfTextEditor/util/tableAdoption";
+import { detectTables } from "@app/tools/pdfTextEditor/util/tableDetection";
+import { ModifyTableCommand } from "@app/tools/pdfTextEditor/commands/ModifyTableCommand";
+import { FillTableCellCommand } from "@app/tools/pdfTextEditor/commands/FillTableCellCommand";
+import type { TableResize } from "@app/tools/pdfTextEditor/commands/ResizeTableCommand";
+import { ResizeTableCommand } from "@app/tools/pdfTextEditor/commands/ResizeTableCommand";
+import { MaterialiseTableCommand } from "@app/tools/pdfTextEditor/commands/MaterialiseTableCommand";
+import { CompositeCommand } from "@app/tools/pdfTextEditor/commands/CompositeCommand";
+import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
+import {
+ pageCanvas,
+ sampleTableColors,
+} from "@app/tools/pdfTextEditor/util/scanSampling";
+
+// Edge handles live wholly OUTSIDE the grid, in a margin strip below it
+// (columns) or left of it (rows), the way a spreadsheet puts them in its
+// headers. A handle laid over the grid covers the cells and swallows the clicks
+// that open one for typing.
+/** Depth of the margin strip the handles occupy, in CSS px. */
+const MARGIN = 12;
+/** Grab length of an edge handle along the edge it moves. */
+const GRAB = 13;
+
+/** Selection accent, matching the image handle's outline. */
+const ACCENT = "var(--c-accent-fg)";
+
+// The controls sit over page content, so they need to read as a floating
+// toolbar rather than as loose buttons tangled in the text behind them.
+const toolbarStyle: React.CSSProperties = {
+ position: "absolute",
+ display: "flex",
+ alignItems: "center",
+ gap: 2,
+ padding: 2,
+ background: "var(--c-surface)",
+ border: "1px solid var(--c-border)",
+ borderRadius: 6,
+ boxShadow: "0 1px 4px rgba(0,0,0,0.18)",
+ pointerEvents: "auto",
+ zIndex: 30,
+ whiteSpace: "nowrap",
+};
+
+const chipStyle: React.CSSProperties = {
+ display: "flex",
+ alignItems: "center",
+ gap: 4,
+ padding: "2px 6px",
+ fontSize: 11,
+ lineHeight: "16px",
+ color: ACCENT,
+ background: "transparent",
+ border: "none",
+ borderRadius: 4,
+ cursor: "pointer",
+};
+
+interface TableOverlayProps {
+ page: PageSnapshot;
+ transform: DisplayTransform;
+ scale: number;
+ store: EditorStore;
+}
+
+interface CssRect {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+// Map a PDF-space rect (y-up, origin bottom-left) to CSS px, honouring the
+// page's display transform (matches ImageHandle's projection).
+function rectToCss(
+ rect: PageRect,
+ transform: DisplayTransform,
+ scale: number,
+ pageHeight: number,
+): CssRect {
+ const corners = [
+ transform.apply(rect.x, rect.y),
+ transform.apply(rect.x + rect.width, rect.y),
+ transform.apply(rect.x, rect.y + rect.height),
+ transform.apply(rect.x + rect.width, rect.y + rect.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));
+ return {
+ left: minX * scale,
+ top: (pageHeight - maxY) * scale,
+ width: (maxX - minX) * scale,
+ height: (maxY - minY) * scale,
+ };
+}
+
+/** Draws recognized + inserted tables and their editing affordances. */
+export function TableOverlay({
+ page,
+ transform,
+ scale,
+ store,
+}: TableOverlayProps) {
+ const detected = useMemo(
+ () => detectTables(page.runs, page.pageIndex, {}, page.rules ?? []),
+ [page.runs, page.pageIndex, page.rules],
+ );
+ const synthetic = page.tables ?? [];
+ // A detected table that overlaps an inserted one is the inserted one's own
+ // cells being re-recognized - drop it so we don't draw two grids.
+ const detectedFiltered = detected.filter(
+ (d) => !synthetic.some((s) => overlaps(d.bounds, s.bounds)),
+ );
+
+ if (detectedFiltered.length === 0 && synthetic.length === 0) return null;
+
+ return (
+ <>
+ {detectedFiltered.map((table) => (
+ <RecognizedTable
+ key={table.id}
+ table={table}
+ page={page}
+ transform={transform}
+ scale={scale}
+ store={store}
+ />
+ ))}
+ {synthetic.map((table) => (
+ <EditableTable
+ key={table.id}
+ table={table}
+ page={page}
+ transform={transform}
+ scale={scale}
+ store={store}
+ />
+ ))}
+ </>
+ );
+}
+
+// The style a cell will be written in, mirroring TableModel.styleFor for the
+// snapshot the overlay renders from.
+function styleForCell(
+ table: TableSnapshot,
+ row: number,
+ col: number,
+): TableCellStyle {
+ const column = table.columnStyles[col] ?? null;
+ if (row === 0 && table.headerStyle) {
+ return { ...table.headerStyle, align: column?.align ?? "left" };
+ }
+ return (
+ column ?? {
+ family: "Helvetica",
+ fontSize: 11,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ align: "left",
+ sourceFontId: "base14:Helvetica",
+ }
+ );
+}
+
+// Base-14 PostScript names map onto the browser's generic families closely
+// enough for a faithful preview.
+function cssFontFamily(family: string): string {
+ if (/^Times/i.test(family)) return "Times New Roman, Times, serif";
+ if (/^Courier/i.test(family)) return "Courier New, Courier, monospace";
+ return "Helvetica, Arial, sans-serif";
+}
+
+function cssColour(fill: RGBA): string {
+ return `rgba(${fill.r}, ${fill.g}, ${fill.b}, ${fill.a / 255})`;
+}
+
+function justifyFor(align: TableCellStyle["align"]): string {
+ if (align === "right") return "flex-end";
+ if (align === "center") return "center";
+ return "flex-start";
+}
+
+// A grid recognized from ordinary text. Shows its structure and lets the user
+// select the whole thing, but structural edits need the tracked geometry that
+// only inserted tables carry.
+function RecognizedTable({
+ table,
+ page,
+ transform,
+ scale,
+ store,
+}: {
+ table: TableSnapshot;
+ page: PageSnapshot;
+ transform: DisplayTransform;
+ scale: number;
+ store: EditorStore;
+}) {
+ const { t } = useTranslation();
+ const box = rectToCss(table.bounds, transform, scale, page.height);
+ const runIds = table.cells.flatMap((c) => c.runIds);
+
+ return (
+ <div
+ data-testid={`pdf-editor-recognized-table-${table.id}`}
+ style={{
+ position: "absolute",
+ left: box.left,
+ top: box.top,
+ width: box.width,
+ height: box.height,
+ border: table.pageRuled
+ ? "1px solid color-mix(in srgb, var(--c-accent-fg) 35%, transparent)"
+ : "1px dashed color-mix(in srgb, var(--c-accent-fg) 55%, transparent)",
+ pointerEvents: "none",
+ boxSizing: "border-box",
+ }}
+ >
+ {!table.pageRuled && gridLines(table, box)}
+ <div style={{ ...toolbarStyle, top: -26, left: -1 }}>
+ <Tooltip
+ label={t(
+ "pdfTextEditor.table.recognizedHint",
+ "Recognized table - click to select all its text",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => store.selection.selectMany(runIds)}
+ data-testid={`pdf-editor-recognized-table-select-${table.id}`}
+ style={chipStyle}
+ >
+ <Icon name="table" size={13} />
+ {table.rows}×{table.cols}
+ </button>
+ </Tooltip>
+ <Tooltip
+ label={t(
+ "pdfTextEditor.table.editHint",
+ "Edit as a table - type in cells, add or remove rows and columns",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => store.adoptTable(table)}
+ data-testid={`pdf-editor-recognized-table-edit-${table.id}`}
+ style={chipStyle}
+ >
+ <Icon name="pencil" size={13} />
+ {t("pdfTextEditor.table.edit", "Edit")}
+ </button>
+ </Tooltip>
+ </div>
+ </div>
+ );
+}
+
+// Internal separators for a table, positioned relative to the outer box.
+function gridLines(table: TableSnapshot, box: CssRect) {
+ const w = table.bounds.width;
+ const h = table.bounds.height;
+ if (w <= 0 || h <= 0) return null;
+ const lines: React.ReactNode[] = [];
+ for (let i = 1; i < table.cols; i++) {
+ const fx = (table.colEdges[i] - table.bounds.x) / w;
+ lines.push(
+ <div
+ key={`v${i}`}
+ style={{
+ position: "absolute",
+ left: fx * box.width,
+ top: 0,
+ bottom: 0,
+ borderLeft:
+ "1px dashed color-mix(in srgb, var(--c-accent-fg) 35%, transparent)",
+ }}
+ />,
+ );
+ }
+ for (let i = 1; i < table.rows; i++) {
+ // rowEdges descend in y; top of the box is rowEdges[0].
+ const fy = (table.rowEdges[0] - table.rowEdges[i]) / h;
+ lines.push(
+ <div
+ key={`h${i}`}
+ style={{
+ position: "absolute",
+ top: fy * box.height,
+ left: 0,
+ right: 0,
+ borderTop:
+ "1px dashed color-mix(in srgb, var(--c-accent-fg) 35%, transparent)",
+ }}
+ />,
+ );
+ }
+ return lines;
+}
+
+// An inserted table with tracked geometry: supports add/remove row & column and
+// click-to-type empty cells.
+function EditableTable({
+ table,
+ page,
+ transform,
+ scale,
+ store,
+}: {
+ table: TableSnapshot;
+ page: PageSnapshot;
+ transform: DisplayTransform;
+ scale: number;
+ store: EditorStore;
+}) {
+ const { t } = useTranslation();
+ const box = rectToCss(table.bounds, transform, scale, page.height);
+ const [drag, setDrag] = useState<DragState | null>(null);
+ const origin = useRef<{ x: number; y: number } | null>(null);
+
+ // Client-space pointer delta -> raw-PDF delta. invert() is affine, so the
+ // translation cancels and the handler needs no container origin.
+ const toPdfDelta = (dx: number, dy: number) => {
+ const o = transform.invert(0, 0);
+ const p = transform.invert(dx / scale, -dy / scale);
+ return { x: p.x - o.x, y: p.y - o.y };
+ };
+
+ // A scanned table is a picture with invisible OCR text over it, so a
+ // structural edit moves text nobody can see and the page looks unchanged.
+ // Rebuild it as real objects first, in the SAME undo step, so one press of
+ // undo puts the scan back rather than stranding a half-built table.
+ const mutate = (cmd: Command): void => {
+ if (!table.scanned || table.ruled) {
+ store.dispatch(cmd);
+ return;
+ }
+ const canvas = pageCanvas(page.pageIndex);
+ const colors = canvas ? sampleTableColors(canvas, table, transform) : null;
+ store.dispatch(
+ new CompositeCommand([
+ new MaterialiseTableCommand({ tableId: table.id, colors }),
+ cmd,
+ ]),
+ );
+ };
+
+ const commitDrag = (d: DragState) => {
+ const delta = toPdfDelta(d.dx, d.dy);
+ let edit: TableResize;
+ if (d.kind === "col") {
+ const x = table.colEdges[d.index] + delta.x;
+ // Alt trades width with the neighbour at a fixed table size; the plain
+ // drag resizes just this column and the table grows or shrinks with it.
+ edit = d.alt
+ ? { kind: "col-edge", index: d.index, x }
+ : { kind: "col-size", index: d.index, x };
+ } else if (d.kind === "row") {
+ const y = table.rowEdges[d.index] + delta.y;
+ edit = d.alt
+ ? { kind: "row-edge", index: d.index, y }
+ : { kind: "row-size", index: d.index, y };
+ } else if (d.kind === "move") {
+ edit = { kind: "move", dx: delta.x, dy: delta.y };
+ } else {
+ edit = {
+ kind: "scale",
+ width: table.bounds.width + delta.x,
+ height: table.bounds.height - delta.y,
+ };
+ }
+ mutate(new ResizeTableCommand({ tableId: table.id, edit }));
+ };
+
+ const dragProps = (kind: DragState["kind"], index: number) => ({
+ active: drag?.kind === kind && drag.index === index,
+ onStart: (x: number, y: number, alt: boolean) => {
+ origin.current = { x, y };
+ setDrag({ kind, index, dx: 0, dy: 0, alt });
+ },
+ onMove: (x: number, y: number) => {
+ const start = origin.current;
+ if (!start) return;
+ setDrag((prev) => ({
+ kind,
+ index,
+ dx: x - start.x,
+ dy: y - start.y,
+ alt: prev?.alt ?? false,
+ }));
+ },
+ onEnd: () => {
+ if (drag && (drag.dx !== 0 || drag.dy !== 0)) commitDrag(drag);
+ origin.current = null;
+ setDrag(null);
+ },
+ });
+
+ const modify = (op: "add-row" | "delete-row" | "add-col" | "delete-col") => {
+ const index =
+ op === "add-row"
+ ? table.rows
+ : op === "delete-row"
+ ? table.rows - 1
+ : op === "add-col"
+ ? table.cols
+ : table.cols - 1;
+ if ((op === "delete-row" || op === "delete-col") && index < 1) return;
+ mutate(new ModifyTableCommand({ tableId: table.id, op, index }));
+ };
+
+ const emptyCells = table.cells.filter((c) => c.runIds.length === 0);
+
+ return (
+ <>
+ <div
+ data-testid={`pdf-editor-table-${table.id}`}
+ style={{
+ position: "absolute",
+ left: box.left,
+ top: box.top,
+ width: box.width,
+ height: box.height,
+ pointerEvents: "none",
+ boxSizing: "border-box",
+ // Outline what is being edited, but only draw cell separators the
+ // page does not already draw - dashes on top of printed rules are
+ // just fuzz over lines the reader can already see.
+ border:
+ table.ruled || table.pageRuled
+ ? "1px solid color-mix(in srgb, var(--c-accent-fg) 35%, transparent)"
+ : "1px dashed color-mix(in srgb, var(--c-accent-fg) 55%, transparent)",
+ }}
+ >
+ {!table.ruled && !table.pageRuled && gridLines(table, box)}
+ {emptyCells.map((cell) => {
+ const cell01 = rectToCss(cell.rect, transform, scale, page.height);
+ const style = styleForCell(table, cell.row, cell.col);
+ return (
+ <div
+ key={`c${cell.row}-${cell.col}`}
+ data-testid={`pdf-editor-table-cell-${table.id}-${cell.row}-${cell.col}`}
+ contentEditable
+ suppressContentEditableWarning
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ (e.target as HTMLElement).blur();
+ }
+ }}
+ onBlur={(e) => {
+ const text = e.currentTarget.textContent?.trim() ?? "";
+ if (!text) return;
+ e.currentTarget.textContent = "";
+ const cmd = new FillTableCellCommand({
+ tableId: table.id,
+ row: cell.row,
+ col: cell.col,
+ text,
+ });
+ mutate(cmd);
+ if (cmd.insertedRunId) {
+ store.selection.selectOne(cmd.insertedRunId);
+ }
+ }}
+ style={{
+ position: "absolute",
+ left: cell01.left - box.left,
+ top: cell01.top - box.top,
+ width: cell01.width,
+ height: cell01.height,
+ boxSizing: "border-box",
+ padding: 2,
+ // Type in the style the cell will actually be written in, so
+ // what you see while typing is what the PDF ends up with.
+ display: "flex",
+ alignItems: "center",
+ justifyContent: justifyFor(style.align),
+ textAlign: style.align,
+ fontFamily: cssFontFamily(style.family),
+ fontWeight: /bold/i.test(style.family) ? 700 : 400,
+ fontStyle: /italic|oblique/i.test(style.family)
+ ? "italic"
+ : "normal",
+ fontSize: Math.max(8, style.fontSize * scale),
+ color: cssColour(style.fill),
+ outline: "none",
+ cursor: "text",
+ pointerEvents: "auto",
+ }}
+ />
+ );
+ })}
+
+ {Array.from({ length: table.cols }, (_, i) => i + 1).map((i) => {
+ const fx = (table.colEdges[i] - table.bounds.x) / table.bounds.width;
+ const d = dragProps("col", i);
+ return (
+ <DragArea
+ key={`ch${i}`}
+ testid={`pdf-editor-table-col-handle-${table.id}-${i}`}
+ label={t(
+ "pdfTextEditor.table.resizeColumn",
+ "Drag to resize this column (Alt: share with the next)",
+ )}
+ cursor="col-resize"
+ orientation="vertical"
+ offset={d.active && drag ? drag.dx : 0}
+ guide={box.height}
+ style={{
+ left: fx * box.width - GRAB / 2,
+ top: box.height,
+ width: GRAB,
+ height: MARGIN,
+ }}
+ {...d}
+ />
+ );
+ })}
+
+ {Array.from({ length: table.rows }, (_, i) => i + 1).map((i) => {
+ const fy =
+ (table.rowEdges[0] - table.rowEdges[i]) / table.bounds.height;
+ const d = dragProps("row", i);
+ return (
+ <DragArea
+ key={`rh${i}`}
+ testid={`pdf-editor-table-row-handle-${table.id}-${i}`}
+ label={t(
+ "pdfTextEditor.table.resizeRow",
+ "Drag to resize this row (Alt: share with the next)",
+ )}
+ cursor="row-resize"
+ orientation="horizontal"
+ offset={d.active && drag ? drag.dy : 0}
+ guide={box.width}
+ style={{
+ top: fy * box.height - GRAB / 2,
+ left: -MARGIN,
+ width: MARGIN,
+ height: GRAB,
+ }}
+ {...d}
+ />
+ );
+ })}
+
+ {drag?.kind === "move" && (
+ <div
+ style={{
+ position: "absolute",
+ left: drag.dx,
+ top: drag.dy,
+ width: box.width,
+ height: box.height,
+ border: `1px dashed ${ACCENT}`,
+ pointerEvents: "none",
+ }}
+ />
+ )}
+
+ <DragArea
+ testid={`pdf-editor-table-scale-handle-${table.id}`}
+ label={t(
+ "pdfTextEditor.table.resizeTable",
+ "Drag to resize the whole table",
+ )}
+ cursor="nwse-resize"
+ orientation="grip"
+ offset={0}
+ guide={0}
+ style={{
+ left: box.width + MARGIN + (drag?.kind === "scale" ? drag.dx : 0),
+ top: box.height + MARGIN + (drag?.kind === "scale" ? drag.dy : 0),
+ width: 11,
+ height: 11,
+ }}
+ {...dragProps("scale", 0)}
+ />
+
+ {drag?.kind === "scale" && (
+ <div
+ style={{
+ position: "absolute",
+ left: 0,
+ top: 0,
+ width: Math.max(10, box.width + drag.dx),
+ height: Math.max(10, box.height + drag.dy),
+ border: `1px dashed ${ACCENT}`,
+ pointerEvents: "none",
+ }}
+ />
+ )}
+ </div>
+ <div
+ style={{ ...toolbarStyle, left: box.left - 1, top: box.top - 30 }}
+ data-testid={`pdf-editor-table-controls-${table.id}`}
+ >
+ <DragArea
+ testid={`pdf-editor-table-move-handle-${table.id}`}
+ label={t(
+ "pdfTextEditor.table.moveTable",
+ "Drag to move the whole table",
+ )}
+ cursor="move"
+ orientation="grip"
+ offset={0}
+ guide={0}
+ style={{ position: "relative", zIndex: "auto" }}
+ content={
+ <span
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 2,
+ padding: "2px 6px",
+ fontSize: 11,
+ lineHeight: "18px",
+ color: "var(--c-text)",
+ }}
+ >
+ <Icon name="move" size={13} />
+ {t("pdfTextEditor.table.move", "Move")}
+ </span>
+ }
+ {...dragProps("move", 0)}
+ />
+ <TableControl
+ label={t("pdfTextEditor.table.addRow", "Add row")}
+ testid={`pdf-editor-table-add-row-${table.id}`}
+ icon={<Icon name="plus" size={13} />}
+ text={t("pdfTextEditor.table.row", "Row")}
+ onClick={() => modify("add-row")}
+ />
+ <TableControl
+ label={t("pdfTextEditor.table.deleteRow", "Delete row")}
+ testid={`pdf-editor-table-del-row-${table.id}`}
+ icon={<Icon name="minus" size={13} />}
+ text={t("pdfTextEditor.table.row", "Row")}
+ disabled={table.rows < 2}
+ onClick={() => modify("delete-row")}
+ />
+ <TableControl
+ label={t("pdfTextEditor.table.addColumn", "Add column")}
+ testid={`pdf-editor-table-add-col-${table.id}`}
+ icon={<Icon name="plus" size={13} />}
+ text={t("pdfTextEditor.table.column", "Col")}
+ onClick={() => modify("add-col")}
+ />
+ <TableControl
+ label={t("pdfTextEditor.table.deleteColumn", "Delete column")}
+ testid={`pdf-editor-table-del-col-${table.id}`}
+ icon={<Icon name="minus" size={13} />}
+ text={t("pdfTextEditor.table.column", "Col")}
+ disabled={table.cols < 2}
+ onClick={() => modify("delete-col")}
+ />
+ {table.adopted && (
+ <TableControl
+ label={t(
+ "pdfTextEditor.table.doneHint",
+ "Stop editing this as a table",
+ )}
+ testid={`pdf-editor-table-done-${table.id}`}
+ icon={<Icon name="check" size={13} />}
+ text={t("pdfTextEditor.table.done", "Done")}
+ onClick={() => store.releaseTable(page.pageIndex, table.id)}
+ />
+ )}
+ </div>
+ </>
+ );
+}
+
+function TableControl({
+ label,
+ testid,
+ icon,
+ text,
+ disabled,
+ onClick,
+}: {
+ label: string;
+ testid: string;
+ icon: React.ReactNode;
+ text: string;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <Tooltip label={label}>
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={onClick}
+ data-testid={testid}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 2,
+ padding: "2px 6px",
+ fontSize: 11,
+ lineHeight: "18px",
+ color: disabled ? "var(--c-text-muted)" : "var(--c-text)",
+ background: "transparent",
+ border: "none",
+ borderRadius: 4,
+ cursor: disabled ? "default" : "pointer",
+ }}
+ >
+ {icon}
+ {text}
+ </button>
+ </Tooltip>
+ );
+}
+
+interface DragState {
+ kind: "col" | "row" | "scale" | "move";
+ /** Alt held: make the two neighbouring tracks trade instead of resizing one. */
+ alt: boolean;
+ index: number;
+ /** Pointer travel since the press, in CSS px. */
+ dx: number;
+ dy: number;
+}
+
+// Pointer-capturing grab area for one resize gesture. Draws its own indicator
+// so an edge that is only a hairline in the PDF still reads as draggable.
+function DragArea({
+ testid,
+ label,
+ cursor,
+ guide,
+ content,
+ orientation,
+ offset,
+ style,
+ active,
+ onStart,
+ onMove,
+ onEnd,
+}: {
+ testid: string;
+ label: string;
+ cursor: string;
+ /** Length of the alignment guide drawn back across the grid while active. */
+ guide: number;
+ /** Rendered instead of the grip/tick, for a handle that lives in the bar. */
+ content?: React.ReactNode;
+ orientation: "vertical" | "horizontal" | "grip";
+ offset: number;
+ style: React.CSSProperties;
+ active: boolean;
+ onStart: (x: number, y: number, alt: boolean) => void;
+ onMove: (x: number, y: number) => void;
+ onEnd: () => void;
+}) {
+ const [hover, setHover] = useState(false);
+ const lit = hover || active;
+ const shift =
+ orientation === "vertical"
+ ? `translateX(${offset}px)`
+ : `translateY(${offset}px)`;
+ return (
+ <div
+ data-testid={testid}
+ title={label}
+ aria-label={label}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ // The stage clears the selection on any press that reaches it.
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ onStart(e.clientX, e.clientY, e.altKey);
+ }}
+ onPointerMove={(e) => {
+ if (active) onMove(e.clientX, e.clientY);
+ }}
+ onPointerUp={(e) => {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ onEnd();
+ }}
+ onPointerCancel={onEnd}
+ onMouseEnter={() => setHover(true)}
+ onMouseLeave={() => setHover(false)}
+ style={{
+ position: "absolute",
+ pointerEvents: "auto",
+ // Above the page's run overlays, which otherwise swallow the press.
+ zIndex: 30,
+ cursor,
+ touchAction: "none",
+ ...style,
+ }}
+ >
+ {content ??
+ (orientation === "grip" ? (
+ <div
+ style={{
+ width: "100%",
+ height: "100%",
+ background: lit
+ ? ACCENT
+ : "color-mix(in srgb, var(--c-accent-fg) 70%, transparent)",
+ border: "1px solid var(--c-surface)",
+ borderRadius: 2,
+ boxSizing: "border-box",
+ }}
+ />
+ ) : (
+ <>
+ <div
+ style={{
+ position: "absolute",
+ ...(orientation === "vertical"
+ ? { left: GRAB / 2 - 1, top: 0, width: 2, height: "100%" }
+ : { top: GRAB / 2 - 1, left: 0, height: 2, width: "100%" }),
+ transform: shift,
+ background: ACCENT,
+ opacity: lit ? 1 : 0.5,
+ }}
+ />
+ {lit && (
+ <div
+ style={{
+ position: "absolute",
+ pointerEvents: "none",
+ ...(orientation === "vertical"
+ ? {
+ left: GRAB / 2 - 1,
+ bottom: "100%",
+ width: 2,
+ height: guide,
+ }
+ : {
+ top: GRAB / 2 - 1,
+ left: "100%",
+ height: 2,
+ width: guide,
+ }),
+ transform: shift,
+ background: ACCENT,
+ }}
+ />
+ )}
+ </>
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
index a2f4ed0743..f9f5289ffa 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
@@ -74,6 +74,7 @@ export function useDocumentLoader(store: EditorStore) {
images: page.images.map((img) => img.snapshot()),
shapes: page.shapes.map((shape) => shape.snapshot()),
annotations: page.annotations,
+ rules: page.rules,
display: page.display.toData(),
});
}
@@ -148,6 +149,7 @@ export function ensureAllPagesRead(store: EditorStore): void {
images: page.images.map((img) => img.snapshot()),
shapes: page.shapes.map((shape) => shape.snapshot()),
annotations: page.annotations,
+ rules: page.rules,
};
});
store.publishPages(next);
@@ -176,6 +178,7 @@ export function ensurePageRead(store: EditorStore, pageIndex: number): void {
images: page.images.map((img) => img.snapshot()),
shapes: page.shapes.map((shape) => shape.snapshot()),
annotations: page.annotations,
+ rules: page.rules,
}
: p,
);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts
index 6019a7d44c..1cd04c9466 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/Page.ts
@@ -3,7 +3,9 @@ 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 { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { PageRuleSnapshot } from "@app/tools/pdfTextEditor/types";
/** Wraps one PDFium page pointer. */
export class Page {
@@ -25,6 +27,15 @@ export class Page {
pendingFormRemovals: Map<number, number>;
/** Text-carrying annotations: rendered by the canvas, not editable. */
annotations: AnnotationBox[];
+ // Bounding boxes of the thin filled/stroked paths the page draws - table
+ // rules, underlines, borders. Table recognition snaps its grid onto these so
+ // the overlay lands on the lines the reader can see.
+ rules: PageRuleSnapshot[];
+ /** Filled area boxes (row shading and the like) in page coords. */
+ fills: PageRuleSnapshot[];
+ // Session tables the editor drew on this page. Not serialized: the PDF keeps
+ // only the ruling lines + cell text; this tracks them as an editable grid.
+ tables: TableModel[];
/** True if any object on this page has uncommitted mutation. */
dirty: boolean;
/** True if the lazy reader has populated runs/images. */
@@ -56,9 +67,12 @@ export class Page {
this.shapes = [];
this.pendingFormRemovals = new Map();
this.annotations = [];
+ this.tables = [];
this.dirty = false;
this.loaded = false;
this.revision = 0;
+ this.rules = [];
+ this.fills = [];
this.needsGenerateContent = false;
this.regenerated = false;
}
@@ -67,6 +81,14 @@ export class Page {
this.runs = runs;
}
+ setRules(rules: PageRuleSnapshot[]): void {
+ this.rules = rules;
+ }
+
+ setFills(fills: PageRuleSnapshot[]): void {
+ this.fills = fills;
+ }
+
setImages(images: ImageObject[]): void {
this.images = images;
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/model/TableModel.ts b/frontend/editor/src/core/tools/pdfTextEditor/model/TableModel.ts
new file mode 100644
index 0000000000..c7aa9e3497
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/model/TableModel.ts
@@ -0,0 +1,258 @@
+import type {
+ PageRect,
+ RGBA,
+ TableCellSnapshot,
+ TableCellStyle,
+ TableSnapshot,
+} from "@app/tools/pdfTextEditor/types";
+import { BLACK } from "@app/tools/pdfTextEditor/model/Color";
+
+/** How many grid tracks a cell covers. Absent means the ordinary 1x1. */
+export interface CellSpan {
+ rowSpan: number;
+ colSpan: number;
+}
+
+/** A background the page paints behind one row of the table. */
+export interface RowFill {
+ row: number;
+ ptr: number;
+ /** Where it sits right now, so the next fit is a delta from here. */
+ rect: PageRect;
+ /** The paint, so a row added later can continue the pattern. */
+ color: RGBA;
+}
+
+/** What a cell looks like when the table has nothing to copy from. */
+export function defaultCellStyle(fontSize: number): TableCellStyle {
+ return {
+ family: "Helvetica",
+ fontSize,
+ fill: { ...BLACK },
+ align: "left",
+ sourceFontId: "base14:Helvetica",
+ };
+}
+
+// Session model for a table the editor DREW (as opposed to one recognized from
+// arbitrary text). It tracks the grid geometry, the ruling-line PDFium object
+// pointers, and which run backs each cell, so structural edits (add/remove
+// row/column) can move the right objects and stay undoable. The PDF itself
+// still persists only the lines + text runs; this model is not serialized.
+export class TableModel {
+ readonly id: string;
+ readonly pageIndex: number;
+ /** Released grids remain in the session so existing undo steps can locate them. */
+ editing = true;
+ colEdges: number[];
+ rowEdges: number[];
+ /** Run id backing each cell, indexed [row][col]; null when the cell is empty. */
+ cellRuns: (string | null)[][];
+ // Further runs sharing a cell. OCR in particular splits one entry into
+ // several text objects ("Q1 Sales" arrives as two), and a cell that tracks
+ // only the first leaves the rest behind whenever the table moves.
+ cellExtraRuns: (string[] | null)[][];
+ // Merge structure, indexed [row][col] alongside cellRuns. An entry marks an
+ // ANCHOR and how far it reaches; the positions it covers stay null in both
+ // arrays, so every `if (!id) continue` loop keeps working untouched.
+ cellSpans: (CellSpan | null)[][];
+ /** Horizontal ruling-line object pointers, top-to-bottom. */
+ hLinePtrs: number[];
+ /** Vertical ruling-line object pointers, left-to-right. */
+ vLinePtrs: number[];
+ lineWidth: number;
+ /** Colour the ruling lines are drawn in, copied from the table's own. */
+ lineColor: RGBA;
+ // Background boxes the page paints behind whole rows (header shading), with
+ // the rect each currently occupies so it can be refitted when the grid moves.
+ rowFills: RowFill[];
+ // The size the text was set for, and how much it has been scaled since. Text
+ // scaling is derived from the table's size against THIS reference, never from
+ // the last gesture: min(widthRatio, heightRatio) applied per drag does not
+ // round-trip, so growing and shrinking repeatedly walked the type smaller.
+ fontBase: { width: number; height: number; scale: number };
+ fontSize: number;
+ // False for a table adopted from recognized text: its rules (if any) are the
+ // document's own objects, so structural edits must not draw or move any.
+ ruled: boolean;
+ /** True when the page draws this grid itself (an adopted ruled table). */
+ pageRuled: boolean;
+ // True when this grid wraps text the document already had, rather than one
+ // the editor inserted - it can be handed back without deleting anything.
+ adopted: boolean;
+ // A picture with invisible OCR text over it: a structural edit has to rebuild
+ // it as real objects before anything can move on screen.
+ scanned: boolean;
+ // Text style per column, so a cell filled later matches the ones already in
+ // that column rather than reverting to the editor's defaults.
+ columnStyles: TableCellStyle[];
+ /** Header-row style, when row 0 is set differently from the body. */
+ headerStyle: TableCellStyle | null;
+
+ constructor(init: {
+ id: string;
+ pageIndex: number;
+ colEdges: number[];
+ rowEdges: number[];
+ cellRuns: (string | null)[][];
+ cellSpans?: (CellSpan | null)[][];
+ cellExtraRuns?: (string[] | null)[][];
+ hLinePtrs: number[];
+ vLinePtrs: number[];
+ lineWidth: number;
+ lineColor?: RGBA;
+ rowFills?: RowFill[];
+ fontSize: number;
+ ruled?: boolean;
+ pageRuled?: boolean;
+ adopted?: boolean;
+ scanned?: boolean;
+ columnStyles?: TableCellStyle[];
+ headerStyle?: TableCellStyle | null;
+ }) {
+ this.id = init.id;
+ this.pageIndex = init.pageIndex;
+ this.colEdges = init.colEdges;
+ this.rowEdges = init.rowEdges;
+ this.cellRuns = init.cellRuns;
+ this.cellSpans =
+ init.cellSpans ?? init.cellRuns.map((row) => row.map(() => null));
+ this.cellExtraRuns =
+ init.cellExtraRuns ?? init.cellRuns.map((row) => row.map(() => null));
+ this.hLinePtrs = init.hLinePtrs;
+ this.vLinePtrs = init.vLinePtrs;
+ this.lineWidth = init.lineWidth;
+ this.lineColor = init.lineColor ?? { ...BLACK };
+ this.rowFills = init.rowFills ?? [];
+ this.fontBase = {
+ width: Math.max(
+ 1,
+ init.colEdges[init.colEdges.length - 1] - init.colEdges[0],
+ ),
+ height: Math.max(
+ 1,
+ init.rowEdges[0] - init.rowEdges[init.rowEdges.length - 1],
+ ),
+ scale: 1,
+ };
+ this.fontSize = init.fontSize;
+ this.ruled = init.ruled ?? true;
+ this.pageRuled = init.pageRuled ?? false;
+ this.adopted = init.adopted ?? false;
+ this.scanned = init.scanned ?? false;
+ const cols = init.colEdges.length - 1;
+ this.columnStyles = Array.from(
+ { length: Math.max(0, cols) },
+ (_, c) => init.columnStyles?.[c] ?? defaultCellStyle(init.fontSize),
+ );
+ this.headerStyle = init.headerStyle ?? null;
+ }
+
+ // The style a cell should be written in. Alignment always comes from the
+ // column - it is a property of the column, not of the header font - so the
+ // header contributes only its face, size and colour.
+ styleFor(row: number, col: number): TableCellStyle {
+ const column = this.columnStyles[col] ?? defaultCellStyle(this.fontSize);
+ if (row === 0 && this.headerStyle) {
+ return { ...this.headerStyle, align: column.align };
+ }
+ return column;
+ }
+
+ get rows(): number {
+ return this.rowEdges.length - 1;
+ }
+
+ get cols(): number {
+ return this.colEdges.length - 1;
+ }
+
+ /** Every run in this cell: the one that backs edits, then any others. */
+ runsAt(row: number, col: number): string[] {
+ const primary = this.cellRuns[row]?.[col];
+ if (!primary) return [];
+ return [primary, ...(this.cellExtraRuns[row]?.[col] ?? [])];
+ }
+
+ /** How far the cell at (row, col) reaches; 1x1 unless the page merged it. */
+ spanAt(row: number, col: number): CellSpan {
+ return this.cellSpans[row]?.[col] ?? { rowSpan: 1, colSpan: 1 };
+ }
+
+ // True when this position is swallowed by a merge anchored to its left or
+ // above. Such a position holds no run and gets no cell of its own.
+ isCovered(row: number, col: number): boolean {
+ for (let r = 0; r <= row; r++) {
+ for (let c = 0; c <= col; c++) {
+ if (r === row && c === col) continue;
+ const span = this.cellSpans[r]?.[c];
+ if (!span) continue;
+ if (row < r + span.rowSpan && col < c + span.colSpan) return true;
+ }
+ }
+ return false;
+ }
+
+ /** Rectangle of one cell in PDF page coords (y-up), spans included. */
+ cellRect(row: number, col: number): PageRect {
+ const { rowSpan, colSpan } = this.spanAt(row, col);
+ const x = this.colEdges[col];
+ const right = this.colEdges[Math.min(col + colSpan, this.cols)];
+ const top = this.rowEdges[row];
+ const bottom = this.rowEdges[Math.min(row + rowSpan, this.rows)];
+ return { x, y: bottom, width: right - x, height: top - bottom };
+ }
+
+ snapshot(): TableSnapshot {
+ const cells: TableCellSnapshot[] = [];
+ const covered = new Set<number>();
+ for (let r = 0; r < this.rows; r++) {
+ for (let c = 0; c < this.cols; c++) {
+ // A covered position is not a cell: emitting one would put a second
+ // editable box on top of the merged cell that owns the space.
+ if (covered.has(r * this.cols + c)) continue;
+ const { rowSpan, colSpan } = this.spanAt(r, c);
+ for (let rr = r; rr < Math.min(r + rowSpan, this.rows); rr++) {
+ for (let cc = c; cc < Math.min(c + colSpan, this.cols); cc++) {
+ if (rr !== r || cc !== c) covered.add(rr * this.cols + cc);
+ }
+ }
+ cells.push({
+ row: r,
+ col: c,
+ runIds: this.runsAt(r, c),
+ colSpan,
+ rowSpan,
+ rect: this.cellRect(r, c),
+ });
+ }
+ }
+ const x = this.colEdges[0];
+ const right = this.colEdges[this.colEdges.length - 1];
+ const top = this.rowEdges[0];
+ const bottom = this.rowEdges[this.rowEdges.length - 1];
+ return {
+ id: this.id,
+ pageIndex: this.pageIndex,
+ rows: this.rows,
+ cols: this.cols,
+ colEdges: [...this.colEdges],
+ rowEdges: [...this.rowEdges],
+ bounds: { x, y: bottom, width: right - x, height: top - bottom },
+ cells,
+ confidence: 1,
+ synthetic: true,
+ ruled: this.ruled,
+ pageRuled: this.pageRuled,
+ adopted: this.adopted,
+ scanned: this.scanned,
+ columnStyles: this.columnStyles.map((st) => ({
+ ...st,
+ fill: { ...st.fill },
+ })),
+ headerStyle: this.headerStyle
+ ? { ...this.headerStyle, fill: { ...this.headerStyle.fill } }
+ : null,
+ };
+ }
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index e90bc68415..49e4822da9 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -12,6 +12,7 @@ import type {
Affine,
GroupingMode,
PageRect,
+ PageRuleSnapshot,
RGBA,
} from "@app/tools/pdfTextEditor/types";
import { readUtf16 } from "@app/services/pdfiumService";
@@ -23,6 +24,14 @@ const FPDF_PAGEOBJ_PATH = 2;
const FPDF_PAGEOBJ_IMAGE = 3;
const FPDF_PAGEOBJ_FORM = 5;
+// A ruling line is hairline-thin on one axis and long on the other. Anything
+// squarer is a box, a shading or a glyph-like drawing.
+const RULE_MAX_THICKNESS_PT = 3;
+const RULE_MIN_LENGTH_PT = 6;
+// fpdf_edit.h path segment types.
+const SEG_LINETO = 0;
+const SEG_MOVETO = 2;
+
/** Reads the editable objects out of a PDFium page. */
export class PdfiumTextReader {
static populate(
@@ -37,6 +46,8 @@ export class PdfiumTextReader {
const runs: TextRun[] = [];
const images: ImageObject[] = [];
+ const rules: PageRuleSnapshot[] = [];
+ const fills: PageRuleSnapshot[] = [];
const shapes: ShapeObject[] = [];
// ONE text page for the whole walk: FPDFText_LoadPage runs full page text
@@ -51,6 +62,8 @@ export class PdfiumTextReader {
count,
runs,
images,
+ rules,
+ fills,
shapes,
doc,
page,
@@ -62,6 +75,8 @@ export class PdfiumTextReader {
page.setRuns(runs);
page.setImages(images);
+ page.setRules(rules);
+ page.setFills(fills);
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.
@@ -365,6 +380,8 @@ function walkObjects(
count: number,
runs: TextRun[],
images: ImageObject[],
+ rules: PageRuleSnapshot[],
+ fills: PageRuleSnapshot[],
shapes: ShapeObject[],
doc: EditorDocument,
page: Page,
@@ -404,19 +421,26 @@ function walkObjects(
run.topLevelContainerPtr = topLevelContainerPtr;
runs.push(run);
}
+ } else if (type === FPDF_PAGEOBJ_PATH) {
+ const painted = readRules(m, objPtr, transform);
+ if (painted.length > 0) rules.push(...painted);
+ else {
+ const fill = readAreaFill(m, objPtr, transform);
+ if (fill) fills.push(fill);
+ }
+ if (path.length <= 1) {
+ // PDFium can save shape removals only in 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_IMAGE) {
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 {
@@ -434,6 +458,8 @@ function walkObjects(
formCount,
runs,
images,
+ rules,
+ fills,
shapes,
doc,
page,
@@ -513,6 +539,224 @@ function getFormContainer(
return current;
}
+// The ruling lines a path object draws.
+//
+// A table's grid reaches us in three encodings: one thin filled rect per line
+// (the object's own box is the line), one stroked rectangle per cell or row,
+// and a single path whose subpaths are every line on the page. Only the first
+// is readable from the bounding box, so the axis-aligned edges are walked out
+// of the path itself and each is tested on its own.
+function readRules(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ transform: Affine,
+): PageRuleSnapshot[] {
+ const paint = readPaint(m, objPtr);
+ if (!paint) return [];
+ const decorate = (rects: PageRect[]): PageRuleSnapshot[] =>
+ rects.map((rect) => ({
+ ...rect,
+ ptr: objPtr,
+ thickness: paint.thickness || Math.min(rect.width, rect.height),
+ color: paint.color,
+ }));
+ // Only a STROKED path draws its outline as lines. A filled box is a shape -
+ // decomposing it would turn a header's shading into four phantom rules and
+ // invite the editor to delete the shading when it takes over the grid.
+ if (paint.stroked) {
+ const matrix = composeAffine(transform, readMatrix(m, objPtr));
+ const edges = ruleEdgesFromPath(m, objPtr, matrix);
+ if (edges.length > 0) return decorate(edges);
+ }
+ const local = readBounds(m, objPtr);
+ if (!local) return [];
+ const rect = isIdentity(transform) ? local : transformRect(transform, local);
+ return isRuleShaped(rect) ? decorate([rect]) : [];
+}
+
+// A filled area that is not a line: a row's shading, a cell's highlight. Kept
+// so a table the editor takes over can carry its background when it changes
+// shape, instead of leaving new cells unpainted.
+function readAreaFill(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ transform: Affine,
+): PageRuleSnapshot | null {
+ const paint = readPaint(m, objPtr);
+ if (!paint || paint.stroked) return null;
+ const local = readBounds(m, objPtr);
+ if (!local) return null;
+ const rect = isIdentity(transform) ? local : transformRect(transform, local);
+ if (rect.width < RULE_MIN_LENGTH_PT || rect.height < RULE_MIN_LENGTH_PT) {
+ return null;
+ }
+ return { ...rect, ptr: objPtr, thickness: 0, color: paint.color };
+}
+
+interface RulePaint {
+ stroked: boolean;
+ thickness: number;
+ color: RGBA;
+}
+
+// What a path paints, or null when it paints nothing (a clip, or a leftover).
+function readPaint(m: WrappedPdfiumModule, objPtr: number): RulePaint | null {
+ const fillPtr = m.pdfium.wasmExports.malloc(4);
+ const strokePtr = m.pdfium.wasmExports.malloc(4);
+ let fillMode = 1;
+ let stroked = false;
+ try {
+ if (m.FPDFPath_GetDrawMode(objPtr, fillPtr, strokePtr)) {
+ fillMode = m.pdfium.getValue(fillPtr, "i32");
+ stroked = m.pdfium.getValue(strokePtr, "i32") !== 0;
+ }
+ } catch {
+ // Older builds without the accessor: assume it paints.
+ } finally {
+ m.pdfium.wasmExports.free(fillPtr);
+ m.pdfium.wasmExports.free(strokePtr);
+ }
+ if (fillMode === 0 && !stroked) return null;
+ const mod = m as unknown as RulePaintModule;
+ const read = stroked
+ ? mod.FPDFPageObj_GetStrokeColor
+ : mod.FPDFPageObj_GetFillColor;
+ const color = read ? readRGBA(m, objPtr, read) : null;
+ return {
+ stroked,
+ thickness: stroked ? readStrokeWidth(m, objPtr) : 0,
+ color: color ?? { r: 0, g: 0, b: 0, a: 255 },
+ };
+}
+
+interface RulePaintModule {
+ FPDFPageObj_GetStrokeColor?: ColorReader;
+ FPDFPageObj_GetFillColor?: ColorReader;
+ FPDFPageObj_GetStrokeWidth?: (obj: number, w: number) => boolean | number;
+}
+
+type ColorReader = (
+ obj: number,
+ r: number,
+ g: number,
+ b: number,
+ a: number,
+) => boolean | number;
+
+function readRGBA(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ read: ColorReader,
+): RGBA | null {
+ 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 (!read(objPtr, r, g, b, a)) return null;
+ return {
+ r: m.pdfium.getValue(r, "i32") & 0xff,
+ g: m.pdfium.getValue(g, "i32") & 0xff,
+ b: m.pdfium.getValue(b, "i32") & 0xff,
+ a: m.pdfium.getValue(a, "i32") & 0xff,
+ };
+ } catch {
+ return null;
+ } finally {
+ m.pdfium.wasmExports.free(r);
+ m.pdfium.wasmExports.free(g);
+ m.pdfium.wasmExports.free(b);
+ m.pdfium.wasmExports.free(a);
+ }
+}
+
+function readStrokeWidth(m: WrappedPdfiumModule, objPtr: number): number {
+ const get = (m as unknown as RulePaintModule).FPDFPageObj_GetStrokeWidth;
+ if (!get) return 0;
+ const w = m.pdfium.wasmExports.malloc(4);
+ try {
+ if (!get(objPtr, w)) return 0;
+ const raw = m.pdfium.getValue(w, "float");
+ return Number.isFinite(raw) && raw > 0 ? raw : 0;
+ } catch {
+ return 0;
+ } finally {
+ m.pdfium.wasmExports.free(w);
+ }
+}
+
+function isRuleShaped(rect: PageRect): boolean {
+ return (
+ Math.min(rect.width, rect.height) <= RULE_MAX_THICKNESS_PT &&
+ Math.max(rect.width, rect.height) >= RULE_MIN_LENGTH_PT
+ );
+}
+
+// Axis-aligned straight edges of a path, each as a thin rect. Covers a stroked
+// rectangle (four edges) and a multi-subpath grid (every line at once).
+function ruleEdgesFromPath(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ matrix: Affine,
+): PageRect[] {
+ let count: number;
+ try {
+ count = m.FPDFPath_CountSegments(objPtr);
+ } catch {
+ return [];
+ }
+ // A one- or two-point path has no edge a bounding box would not already give.
+ if (count < 3) return [];
+ const xPtr = m.pdfium.wasmExports.malloc(4);
+ const yPtr = m.pdfium.wasmExports.malloc(4);
+ const out: PageRect[] = [];
+ try {
+ let prev: { x: number; y: number } | null = null;
+ let subpathStart: { x: number; y: number } | null = null;
+ for (let i = 0; i < count; i++) {
+ const seg = m.FPDFPath_GetPathSegment(objPtr, i);
+ if (!seg) return [];
+ if (!m.FPDFPathSegment_GetPoint(seg, xPtr, yPtr)) return [];
+ const local = {
+ x: m.pdfium.getValue(xPtr, "float"),
+ y: m.pdfium.getValue(yPtr, "float"),
+ };
+ const pt = applyAffine(matrix, local.x, local.y);
+ const type = m.FPDFPathSegment_GetType(seg);
+ if (type === SEG_MOVETO) {
+ subpathStart = pt;
+ } else if (type === SEG_LINETO && prev) {
+ pushEdge(out, prev, pt);
+ // A closed subpath draws its final edge back to where it started.
+ if (m.FPDFPathSegment_GetClose(seg) && subpathStart) {
+ pushEdge(out, pt, subpathStart);
+ }
+ }
+ prev = pt;
+ }
+ } catch {
+ return [];
+ } finally {
+ m.pdfium.wasmExports.free(xPtr);
+ m.pdfium.wasmExports.free(yPtr);
+ }
+ return out;
+}
+
+function pushEdge(
+ out: PageRect[],
+ a: { x: number; y: number },
+ b: { x: number; y: number },
+): void {
+ const rect = {
+ x: Math.min(a.x, b.x),
+ y: Math.min(a.y, b.y),
+ width: Math.abs(b.x - a.x),
+ height: Math.abs(b.y - a.y),
+ };
+ if (isRuleShaped(rect)) out.push(rect);
+}
+
function readBounds(m: WrappedPdfiumModule, objPtr: number): PageRect | null {
const lPtr = m.pdfium.wasmExports.malloc(4);
const bPtr = m.pdfium.wasmExports.malloc(4);
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts
index 95f0ba9ed1..309e5e0ac2 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/store/EditorStore.ts
@@ -20,10 +20,17 @@ import {
resetPerCharBranchPtrs,
} from "@app/tools/pdfTextEditor/commands/editTextHelpers";
import type { Command } from "@app/tools/pdfTextEditor/commands/Command";
+import { AdoptTableCommand } from "@app/tools/pdfTextEditor/commands/AdoptTableCommand";
+import {
+ adoptedTableId,
+ adoptedTableModel,
+ overlaps,
+} from "@app/tools/pdfTextEditor/util/tableAdoption";
import type { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
import type {
GroupingMode,
PageSnapshot,
+ TableSnapshot,
WidthMode,
} from "@app/tools/pdfTextEditor/types";
import { resetEmbeddedFaces } from "@app/tools/pdfTextEditor/util/embeddedFace";
@@ -43,7 +50,7 @@ function resetCharcodeCaches(): void {
resetEmbeddedFaces();
}
-export type InteractionMode = "select" | "addText";
+export type InteractionMode = "select" | "addText" | "addTable";
export interface LoadProgress {
/** Stage description shown in the loader: "Reading file", "Parsing PDF", "Loading page 3/60", etc. */
@@ -262,6 +269,8 @@ export class EditorStore {
shapes: live.shapes.map((shape) => shape.snapshot()),
// Regrouping re-populates the page, which re-reads its annotations.
annotations: live.annotations,
+ tables: [],
+ rules: live.rules,
};
});
this.patch({ groupingMode: mode, pages, dirty: this.isDirty() });
@@ -331,6 +340,63 @@ export class EditorStore {
this.patch({ dirty: this.isDirty() });
}
+ // Promote a recognized table to an editable session table.
+ //
+ // Paragraph grouping merges a whole table column into one run, so the same
+ // run would back several cells and a structural edit would move it once per
+ // cell. Splitting those runs first is what gives every cell its own text -
+ // that part and its grid share an undo step. A grid needing no splits is
+ // session state and must not mark the file unsaved.
+ adoptTable(table: TableSnapshot): void {
+ if (!this.doc) return;
+ const page = this.doc.page(table.pageIndex);
+ if (!page) return;
+ const baseId = adoptedTableId(table);
+ const existing = page.tables.find(
+ (t) => t.adopted && overlaps(t.snapshot().bounds, table.bounds),
+ );
+ if (existing) {
+ existing.editing = true;
+ page.bumpRevision();
+ this.resnapshot();
+ return;
+ }
+
+ const merged = [...new Set(table.cells.flatMap((c) => c.runIds))].filter(
+ (id) => (page.findRun(id)?.paragraphMemberPtrs.length ?? 0) >= 2,
+ );
+ let id = baseId;
+ let suffix = 2;
+ while (page.tables.some((t) => t.id === id))
+ id = `${table.id}-${suffix++}-editable`;
+ if (merged.length > 0) {
+ this.dispatch(new AdoptTableCommand(table, id, merged));
+ return;
+ }
+ page.tables = [
+ ...page.tables,
+ adoptedTableModel(this.doc.module, page, {
+ ...table,
+ id,
+ }),
+ ];
+ page.bumpRevision();
+ this.resnapshot();
+ }
+
+ /** Drop an adopted grid; the text it wrapped is untouched. */
+ releaseTable(pageIndex: number, tableId: string): void {
+ if (!this.doc) return;
+ const page = this.doc.page(pageIndex);
+ if (!page) return;
+ if (!page.tables.some((t) => t.id === tableId)) return;
+ const model = page.tables.find((t) => t.id === tableId);
+ if (!model?.adopted) return;
+ model.editing = false;
+ page.bumpRevision();
+ this.resnapshot();
+ }
+
/** Apply a command via the history stack, re-snapshot, and notify. */
dispatch(cmd: Command): void {
if (!this.doc) return;
@@ -481,6 +547,7 @@ export class EditorStore {
page.loaded = false;
page.setRuns([]);
page.setImages([]);
+ page.tables = [];
page.setShapes([]);
PdfiumTextReader.populate(doc, page, mode);
}
@@ -509,6 +576,10 @@ export class EditorStore {
revision: live.revision,
runs: live.runs.map((r) => r.snapshot()),
images: live.images.map((img) => img.snapshot()),
+ tables: live.tables
+ .filter((tbl) => tbl.editing)
+ .map((tbl) => tbl.snapshot()),
+ rules: live.rules,
shapes: live.shapes.map((shape) => shape.snapshot()),
};
});
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/types.ts b/frontend/editor/src/core/tools/pdfTextEditor/types.ts
index 881b593ea7..63bca5595a 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/types.ts
+++ b/frontend/editor/src/core/tools/pdfTextEditor/types.ts
@@ -94,6 +94,80 @@ export interface ImageObjectSnapshot {
locked?: boolean;
}
+// One ruling line the page draws, with the ink needed to reproduce it: a table
+// the editor takes over has to redraw its grid in the style it found.
+export interface PageRuleSnapshot extends PageRect {
+ /** PDFium object that drew it; several rules can share one object. */
+ ptr: number;
+ /** Painted thickness in points. */
+ thickness: number;
+ color: RGBA;
+}
+
+/** How a column's text is set, so new cells match the ones already there. */
+export interface TableCellStyle {
+ /** Base-14 PostScript name a new text object can actually be built with. */
+ family: string;
+ fontSize: number;
+ fill: RGBA;
+ /** Horizontal placement within the cell, read back from the existing text. */
+ align: "left" | "right" | "center";
+ // Two weights of a non-embedded font report the same substituted face name,
+ // so the id is what tells them apart.
+ sourceFontId: string;
+}
+
+/** One cell of a recognized or inserted table. */
+export interface TableCellSnapshot {
+ /** Zero-based row index (top-down). */
+ row: number;
+ /** Zero-based column index (left-to-right). */
+ col: number;
+ /** Cell rectangle in PDF page coords (y-up, origin bottom-left). */
+ rect: PageRect;
+ /** Ids of the text runs that sit inside this cell (usually 0 or 1). */
+ runIds: string[];
+ // Grid columns/rows this cell covers. > 1 when the page draws no boundary
+ // between them, i.e. a merged cell. Positions it covers are omitted from
+ // `cells` entirely, the way a table markup language omits them.
+ colSpan: number;
+ rowSpan: number;
+}
+
+// A table is a DERIVED view over the page's text runs (plus, for inserted
+// tables, drawn ruling lines) - the PDF objects remain the source of truth.
+export interface TableSnapshot {
+ id: string;
+ pageIndex: number;
+ rows: number;
+ cols: number;
+ // Column boundary x positions in PDF points, left-to-right (cols + 1 values).
+ colEdges: number[];
+ // Row boundary y positions in PDF points, top-to-bottom i.e. DESCENDING y
+ // (rows + 1 values).
+ rowEdges: number[];
+ /** Outer rectangle in PDF page coords (y-up). */
+ bounds: PageRect;
+ cells: TableCellSnapshot[];
+ /** Heuristic confidence 0..1 for a detected table; 1 for an inserted one. */
+ confidence: number;
+ /** True when the editor drew this table rather than detecting it. */
+ synthetic: boolean;
+ /** True when the editor owns this table's ruling lines and may redraw them. */
+ ruled: boolean;
+ // True when the PAGE already draws this grid, so the overlay has no need to
+ // outline cells the reader can see the borders of.
+ pageRuled: boolean;
+ /** True for a grid wrapped around the document's own text (see adoptTable). */
+ adopted: boolean;
+ /** True for a scan: a picture with invisible OCR text laid over it. */
+ scanned: boolean;
+ /** Per-column text style, copied from the table's own content. */
+ columnStyles: TableCellStyle[];
+ /** Style of the header row when it is set differently from the body. */
+ headerStyle: TableCellStyle | null;
+}
+
/** A vector path: a line, frame, box or other drawn shape. */
export interface ShapeObjectSnapshot {
id: string;
@@ -117,6 +191,11 @@ export interface PageSnapshot {
// Text-carrying annotations: drawn by the canvas, outside the editable
// object tree. Absent until the page has been read.
annotations?: AnnotationBox[];
+ // Tables the editor drew on this page (synthetic). Recognized tables are
+ // derived in the view from `runs`; these are the ones with tracked geometry.
+ tables?: TableSnapshot[];
+ /** The thin paths the page draws, so a grid can snap onto and adopt them. */
+ rules?: PageRuleSnapshot[];
// Raw-PDF -> display (CropBox/rotation) transform for the screen boundary.
display: DisplayTransformData;
}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/locateTable.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/locateTable.ts
new file mode 100644
index 0000000000..cf1e1af219
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/locateTable.ts
@@ -0,0 +1,17 @@
+import type { EditorDocument } from "@app/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@app/tools/pdfTextEditor/model/Page";
+import type { TableModel } from "@app/tools/pdfTextEditor/model/TableModel";
+
+/** Locate a session grid; missing tables return null after a document reload. */
+export function locateTable(
+ doc: EditorDocument,
+ tableId: string,
+): { page: Page; model: TableModel } | null {
+ const match = /^p(\d+)-/.exec(tableId);
+ const pages = match ? [doc.page(Number(match[1]))] : doc.loadedPages();
+ for (const page of pages) {
+ const model = page.tables.find((table) => table.id === tableId);
+ if (model) return { page, model };
+ }
+ return null;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/scanSampling.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/scanSampling.ts
new file mode 100644
index 0000000000..8fb6f274e1
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/scanSampling.ts
@@ -0,0 +1,285 @@
+import type {
+ PageRect,
+ RGBA,
+ TableSnapshot,
+} from "@app/tools/pdfTextEditor/types";
+import type { DisplayTransform } from "@app/tools/pdfTextEditor/model/DisplayTransform";
+
+/** What a scan actually looks like inside one cell. */
+export interface CellColors {
+ /** The cell's background - paper, or its shading if it has any. */
+ bg: RGBA;
+ /** The colour its text is printed in. */
+ ink: RGBA;
+}
+
+/** Colours read off a scan, in the same row/col shape as the table. */
+export interface ScanColors {
+ /** Per cell, or null where there was nothing readable to sample. */
+ cells: (CellColors | null)[][];
+ /** The table's dominant background, used behind the whole grid. */
+ paper: RGBA;
+ /** Darkest well-represented ink, used for the rebuilt rules. */
+ rule: RGBA;
+}
+
+/** Inset so a cell's own borders and its neighbours stay out of the sample. */
+const CELL_INSET = 0.12;
+// Colour buckets: wide enough that scan noise lands in one bin, narrow enough
+// to keep a light grey header apart from the paper it sits on. At 16 those two
+// shared a bucket, and the paper came out grey.
+const BUCKET = 8;
+/** A cell smaller than this many device pixels has nothing worth sampling. */
+const MIN_PX = 3;
+// A bucket under this share of the cell is noise, not its ink. Kept low: a
+// short entry in a wide cell covers very little of it, and at 2% "11.4%" on a
+// shaded row was discarded and a stray light bucket taken as its ink.
+const INK_MIN_SHARE = 0.004;
+/** Luma a candidate must clear, on the far side of the background. */
+const INK_MIN_CONTRAST = 30;
+/** Depth of the strip outside the table that stands in for the page's paper. */
+const PAPER_STRIP_PT = 10;
+
+const bucketOf = (c: RGBA): number =>
+ ((c.r / BUCKET) | 0) * 65536 +
+ ((c.g / BUCKET) | 0) * 256 +
+ ((c.b / BUCKET) | 0);
+
+/** Bucket tally holding the mean of what landed in it, not the first sample. */
+interface Bucket {
+ n: number;
+ r: number;
+ g: number;
+ b: number;
+}
+
+function add(into: Map<number, Bucket>, c: RGBA): void {
+ const k = bucketOf(c);
+ const hit = into.get(k);
+ if (hit) {
+ hit.n++;
+ hit.r += c.r;
+ hit.g += c.g;
+ hit.b += c.b;
+ } else {
+ into.set(k, { n: 1, r: c.r, g: c.g, b: c.b });
+ }
+}
+
+const meanOf = (b: Bucket): RGBA => ({
+ r: Math.round(b.r / b.n),
+ g: Math.round(b.g / b.n),
+ b: Math.round(b.b / b.n),
+ a: 255,
+});
+
+function dominant(counts: Map<number, Bucket>): RGBA | null {
+ let best: Bucket | null = null;
+ for (const entry of counts.values()) {
+ if (!best || entry.n > best.n) best = entry;
+ }
+ return best ? meanOf(best) : null;
+}
+
+const luma = (c: RGBA): number => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;
+
+const distance = (a: RGBA, b: RGBA): number =>
+ Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b);
+
+// The page canvas the viewer already painted. Sampling that rather than the
+// image object gets the colours after every transform the page applies, and
+// costs nothing extra to produce.
+export function pageCanvas(pageIndex: number): HTMLCanvasElement | null {
+ const el = document.querySelector(`canvas[data-page-canvas="${pageIndex}"]`);
+ return el instanceof HTMLCanvasElement && el.width > 0 && el.height > 0
+ ? el
+ : null;
+}
+
+// Reads the scan's own colours for a table: what each cell is filled with and
+// what its text is printed in. A rebuild uses these instead of flat white and
+// black, which is what left a rebuilt table sitting in a pale patch on a
+// tinted scan - and would have erased white-on-dark header text entirely.
+export function sampleTableColors(
+ canvas: HTMLCanvasElement,
+ table: TableSnapshot,
+ transform: DisplayTransform,
+): ScanColors | null {
+ const pageWidthPt = transform.displayWidth;
+ const pageHeightPt = transform.displayHeight;
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
+ if (!ctx || pageWidthPt <= 0 || pageHeightPt <= 0) return null;
+ const sx = canvas.width / pageWidthPt;
+ const sy = canvas.height / pageHeightPt;
+ const read = (rect: PageRect): Map<number, Bucket> | null => {
+ const corners = [
+ transform.apply(rect.x, rect.y),
+ transform.apply(rect.x + rect.width, rect.y),
+ transform.apply(rect.x, rect.y + rect.height),
+ transform.apply(rect.x + rect.width, rect.y + rect.height),
+ ];
+ const xs = corners.map((p) => p.x);
+ const ys = corners.map((p) => p.y);
+ const x = Math.min(...xs);
+ const y = Math.min(...ys);
+ return readRegion(
+ ctx,
+ { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y },
+ sx,
+ sy,
+ pageHeightPt,
+ );
+ };
+
+ // The paper comes from just OUTSIDE the table. Taking it from the cells lets
+ // a big shaded header pass itself off as the background, and then every
+ // ordinary row reads as the shaded one.
+ const b = table.bounds;
+ const strips: PageRect[] = [
+ { x: b.x, y: b.y + b.height, width: b.width, height: PAPER_STRIP_PT },
+ { x: b.x, y: b.y - PAPER_STRIP_PT, width: b.width, height: PAPER_STRIP_PT },
+ {
+ x: b.x - PAPER_STRIP_PT,
+ y: b.y,
+ width: PAPER_STRIP_PT,
+ height: b.height,
+ },
+ { x: b.x + b.width, y: b.y, width: PAPER_STRIP_PT, height: b.height },
+ ];
+ const margin = new Map<number, Bucket>();
+ for (const strip of strips) {
+ const got = read(strip);
+ if (got) for (const [k, v] of got) merge(margin, k, v);
+ }
+
+ const cells: (CellColors | null)[][] = [];
+ const inside = new Map<number, Bucket>();
+ for (let r = 0; r < table.rows; r++) {
+ const row: (CellColors | null)[] = [];
+ for (let c = 0; c < table.cols; c++) {
+ const rect = cellRect(table, r, c);
+ const counts = read(inset(rect));
+ if (counts) for (const [k, v] of counts) merge(inside, k, v);
+ row.push(counts ? colorsOf(counts) : null);
+ }
+ cells.push(row);
+ }
+
+ const paper = dominant(margin) ??
+ dominant(inside) ?? { r: 255, g: 255, b: 255, a: 255 };
+ let rule: RGBA = { r: 0, g: 0, b: 0, a: 255 };
+ let darkest = Infinity;
+ for (const entry of inside.values()) {
+ // The rule colour has to be genuinely present, not one stray dark pixel.
+ const c = meanOf(entry);
+ if (entry.n > 8 && luma(c) < darkest) {
+ darkest = luma(c);
+ rule = c;
+ }
+ }
+ return { cells, paper, rule };
+}
+
+/** One cell in page space, before any inset. */
+function cellRect(table: TableSnapshot, row: number, col: number): PageRect {
+ return {
+ x: table.colEdges[col],
+ y: table.rowEdges[row + 1],
+ width: table.colEdges[col + 1] - table.colEdges[col],
+ height: table.rowEdges[row] - table.rowEdges[row + 1],
+ };
+}
+
+/** Pull the sample away from a cell's own borders and its neighbours. */
+function inset(rect: PageRect): PageRect {
+ const dx = rect.width * CELL_INSET;
+ const dy = rect.height * CELL_INSET;
+ return {
+ x: rect.x + dx,
+ y: rect.y + dy,
+ width: rect.width - dx * 2,
+ height: rect.height - dy * 2,
+ };
+}
+
+function merge(into: Map<number, Bucket>, key: number, from: Bucket): void {
+ const hit = into.get(key);
+ if (hit) {
+ hit.n += from.n;
+ hit.r += from.r;
+ hit.g += from.g;
+ hit.b += from.b;
+ } else {
+ into.set(key, { ...from });
+ }
+}
+
+// One region's colours, bucketed. Returns null when the region falls outside
+// the canvas or is too small to say anything about.
+function readRegion(
+ ctx: CanvasRenderingContext2D,
+ rect: PageRect,
+ sx: number,
+ sy: number,
+ pageHeightPt: number,
+): Map<number, Bucket> | null {
+ const left = Math.round(rect.x * sx);
+ const width = Math.round(rect.width * sx);
+ // PDF y counts up from the bottom; the canvas counts down from the top.
+ const top = Math.round((pageHeightPt - (rect.y + rect.height)) * sy);
+ const height = Math.round(rect.height * sy);
+ if (width < MIN_PX || height < MIN_PX) return null;
+ if (left < 0 || top < 0) return null;
+ if (left + width > ctx.canvas.width || top + height > ctx.canvas.height) {
+ return null;
+ }
+ let data: Uint8ClampedArray;
+ try {
+ data = ctx.getImageData(left, top, width, height).data;
+ } catch {
+ return null;
+ }
+ const counts = new Map<number, Bucket>();
+ for (let i = 0; i < data.length; i += 4) {
+ add(counts, { r: data[i], g: data[i + 1], b: data[i + 2], a: 255 });
+ }
+ return counts;
+}
+
+// A cell's background and ink. The background is the most common colour - text
+// is always a minority of the pixels, which is what a mean over the whole cell
+// would smear away. The ink is the best-represented colour furthest from that
+// background, so it works the same on black-on-white and white-on-navy.
+function colorsOf(counts: Map<number, Bucket>): CellColors | null {
+ const bg = dominant(counts);
+ if (!bg) return null;
+ let total = 0;
+ for (const entry of counts.values()) total += entry.n;
+ const light = luma(bg) > 128;
+ let ink: RGBA | null = null;
+ let far = 0;
+ for (const entry of counts.values()) {
+ if (entry.n / total < INK_MIN_SHARE) continue;
+ const c = meanOf(entry);
+ // Ink on a pale cell is DARKER, ink on a dark cell is lighter. Without
+ // that direction the paper showing through a shaded cell scores as its
+ // ink, and the entry is painted in a colour close to its background.
+ const contrast = light ? luma(bg) - luma(c) : luma(c) - luma(bg);
+ if (contrast < INK_MIN_CONTRAST) continue;
+ const d = distance(c, bg);
+ if (d > far) {
+ far = d;
+ ink = c;
+ }
+ }
+ // An empty cell has no ink to find; a readable contrast against the
+ // background is what separates real text from paper grain.
+ return { bg, ink: ink ?? contrastTo(bg) };
+}
+
+/** Fallback ink when a cell holds no text to sample: whatever reads on it. */
+function contrastTo(bg: RGBA): RGBA {
+ return luma(bg) > 128
+ ? { r: 0, g: 0, b: 0, a: 255 }
+ : { r: 255, g: 255, b: 255, a: 255 };
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/tableAdoption.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/tableAdoption.ts
new file mode 100644
index 0000000000..f129e2c2c5
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/tableAdoption.ts
@@ -0,0 +1,310 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { Page } from "@app/tools/pdfTextEditor/model/Page";
+import { measureObjSpanPt } from "@app/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ type CellSpan,
+ defaultCellStyle,
+ type RowFill,
+ TableModel,
+} from "@app/tools/pdfTextEditor/model/TableModel";
+import type {
+ PageRect,
+ RGBA,
+ TableCellStyle,
+ TableSnapshot,
+} from "@app/tools/pdfTextEditor/types";
+import {
+ headerDiffers,
+ type StyledCell,
+ styleOfCells,
+} from "@app/tools/pdfTextEditor/util/tableStyle";
+
+const FALLBACK_FONT_SIZE = 11;
+/** PDF text render mode 3 = invisible, which is what an OCR layer writes. */
+const RENDER_INVISIBLE = 3;
+const LINE_WIDTH = 0.75;
+
+/** Id the editable twin of a recognized table takes. */
+export function adoptedTableId(table: TableSnapshot): string {
+ return `${table.id}-editable`;
+}
+
+// Builds the session model that makes a recognized table editable. The runs are
+// the document's own text and any ruling lines are its own drawing, so the model
+// is unruled: structural edits move text and never paint borders the page did
+// not already have.
+export function adoptedTableModel(
+ module: WrappedPdfiumModule,
+ page: Page,
+ table: TableSnapshot,
+): TableModel {
+ const cellRuns: (string | null)[][] = Array.from({ length: table.rows }, () =>
+ Array.from({ length: table.cols }, () => null),
+ );
+ const cellSpans: (CellSpan | null)[][] = Array.from(
+ { length: table.rows },
+ () => Array.from({ length: table.cols }, () => null),
+ );
+ const cellExtraRuns: (string[] | null)[][] = Array.from(
+ { length: table.rows },
+ () => Array.from({ length: table.cols }, () => null),
+ );
+ for (const cell of table.cells) {
+ const row = cellRuns[cell.row];
+ if (row) row[cell.col] = cell.runIds[0] ?? null;
+ if (cell.runIds.length > 1) {
+ const extras = cellExtraRuns[cell.row];
+ if (extras) extras[cell.col] = cell.runIds.slice(1);
+ }
+ if (cell.colSpan > 1 || cell.rowSpan > 1) {
+ const spanRow = cellSpans[cell.row];
+ if (spanRow) {
+ spanRow[cell.col] = { rowSpan: cell.rowSpan, colSpan: cell.colSpan };
+ }
+ }
+ }
+ const fontSize = cellFontSize(page, cellRuns);
+ const grid = adoptGrid(page, table);
+ const { columnStyles, headerStyle } = readStyles(
+ module,
+ page,
+ table,
+ cellRuns,
+ fontSize,
+ );
+ return new TableModel({
+ id: table.id.endsWith("-editable") ? table.id : adoptedTableId(table),
+ pageIndex: table.pageIndex,
+ colEdges: [...table.colEdges],
+ rowEdges: [...table.rowEdges],
+ cellRuns,
+ cellSpans,
+ cellExtraRuns,
+ hLinePtrs: grid.ptrs,
+ vLinePtrs: [],
+ lineWidth: grid.lineWidth,
+ lineColor: grid.lineColor,
+ rowFills: adoptRowFills(page, table),
+ fontSize,
+ // Taking over the page's own lines is what lets a new row or a resize
+ // carry the grid with it; without it the text moves and the printed rules
+ // stay behind.
+ ruled: grid.ptrs.length > 0,
+ pageRuled: table.pageRuled,
+ adopted: true,
+ scanned: looksScanned(page, table, cellRuns),
+ columnStyles,
+ headerStyle,
+ });
+}
+
+// A scan carries the table as a picture with an INVISIBLE OCR text layer over
+// it. Editing moves that text, so nothing appears to happen until the table is
+// rebuilt as real objects. Both halves are required: invisible text alone is
+// just hidden text, and an image alone is a table printed over a photo.
+function looksScanned(
+ page: Page,
+ table: TableSnapshot,
+ cellRuns: (string | null)[][],
+): boolean {
+ const overImage = page.images.some((img) =>
+ overlaps(img.bounds, table.bounds),
+ );
+ if (!overImage) return false;
+ let seen = 0;
+ let invisible = 0;
+ for (const row of cellRuns) {
+ for (const id of row) {
+ if (!id) continue;
+ const run = page.findRun(id);
+ if (!run?.pdfiumObjPtr) continue;
+ seen++;
+ if (run.renderMode === RENDER_INVISIBLE) {
+ invisible++;
+ }
+ }
+ }
+ return seen > 0 && invisible === seen;
+}
+
+// The lines the page draws for THIS table, and the ink they are drawn in. The
+// editor takes ownership of those objects so redrawGrid can maintain them; the
+// rules were already proven to separate this table's tracks, so nothing else on
+// the page is caught up in it.
+function adoptGrid(
+ page: Page,
+ table: TableSnapshot,
+): { ptrs: number[]; lineWidth: number; lineColor: RGBA } {
+ const fallback = {
+ ptrs: [] as number[],
+ lineWidth: LINE_WIDTH,
+ lineColor: { r: 0, g: 0, b: 0, a: 255 },
+ };
+ if (!table.pageRuled) return fallback;
+ const pad = 2;
+ const inside = page.rules.filter(
+ (r) =>
+ r.x >= table.bounds.x - pad &&
+ r.x + r.width <= table.bounds.x + table.bounds.width + pad &&
+ r.y >= table.bounds.y - pad &&
+ r.y + r.height <= table.bounds.y + table.bounds.height + pad,
+ );
+ if (inside.length === 0) return fallback;
+ const insideSet = new Set(inside);
+ const ptrs = [...new Set(inside.map((r) => r.ptr))].filter(
+ (p) => p > 0 && page.rules.every((r) => r.ptr !== p || insideSet.has(r)),
+ );
+ if (ptrs.length === 0) return fallback;
+ const widths = inside
+ .map((r) => r.thickness)
+ .filter((t) => t > 0)
+ .sort((a, b) => a - b);
+ const counts = new Map<string, { n: number; color: RGBA }>();
+ for (const r of inside) {
+ const key = `${r.color.r},${r.color.g},${r.color.b},${r.color.a}`;
+ const hit = counts.get(key);
+ if (hit) hit.n++;
+ else counts.set(key, { n: 1, color: r.color });
+ }
+ let best = fallback.lineColor;
+ let bestN = 0;
+ for (const entry of counts.values()) {
+ if (entry.n > bestN) {
+ bestN = entry.n;
+ best = entry.color;
+ }
+ }
+ return {
+ ptrs,
+ lineWidth:
+ widths.length > 0 ? widths[Math.floor(widths.length / 2)] : LINE_WIDTH,
+ lineColor: best,
+ };
+}
+
+// Backgrounds the page paints behind a whole row of this table. Bound to the
+// row they cover so a later widening or resize carries them along - otherwise
+// a new column lands outside the header's shading and reads as unstyled.
+function adoptRowFills(page: Page, table: TableSnapshot): RowFill[] {
+ const out: RowFill[] = [];
+ const width = table.bounds.width;
+ if (width <= 0) return out;
+ for (const fill of page.fills) {
+ // It has to span most of the table to be the ROW's background rather than
+ // one cell's highlight, which the editor has no model for yet.
+ const covered =
+ Math.min(fill.x + fill.width, table.bounds.x + width) -
+ Math.max(fill.x, table.bounds.x);
+ if (covered / width < 0.9) continue;
+ const mid = fill.y + fill.height / 2;
+ for (let r = 0; r < table.rows; r++) {
+ const top = table.rowEdges[r];
+ const bottom = table.rowEdges[r + 1];
+ if (mid > bottom && mid < top && fill.height <= (top - bottom) * 1.5) {
+ out.push({
+ row: r,
+ ptr: fill.ptr,
+ rect: {
+ x: fill.x,
+ y: fill.y,
+ width: fill.width,
+ height: fill.height,
+ },
+ color: { ...fill.color },
+ });
+ break;
+ }
+ }
+ }
+ return out;
+}
+
+// Read each column's style off the text already in it, taking the body rows
+// only: a bold header would otherwise make every new cell in the column bold.
+// The header keeps its own style when it differs.
+function readStyles(
+ module: WrappedPdfiumModule,
+ page: Page,
+ table: TableSnapshot,
+ cellRuns: (string | null)[][],
+ fontSize: number,
+): { columnStyles: TableCellStyle[]; headerStyle: TableCellStyle | null } {
+ const rectOf = (row: number, col: number): PageRect => ({
+ x: table.colEdges[col],
+ y: table.rowEdges[row + 1],
+ width: table.colEdges[col + 1] - table.colEdges[col],
+ height: table.rowEdges[row] - table.rowEdges[row + 1],
+ });
+ const collect = (rows: number[], col: number): StyledCell[] => {
+ const out: StyledCell[] = [];
+ for (const r of rows) {
+ const id = cellRuns[r]?.[col];
+ if (!id) continue;
+ const run = page.findRun(id);
+ if (!run) continue;
+ const span = run.pdfiumObjPtr
+ ? measureObjSpanPt(module, [run.pdfiumObjPtr])
+ : null;
+ out.push({
+ run,
+ rect: rectOf(r, col),
+ left: span ? span.left : run.bounds.x,
+ right: span ? span.right : run.bounds.x + run.bounds.width,
+ });
+ }
+ return out;
+ };
+ const bodyRows = Array.from({ length: table.rows }, (_, r) => r).slice(
+ table.rows > 1 ? 1 : 0,
+ );
+ const columnStyles = Array.from({ length: table.cols }, (_, c) => {
+ // A column with no body text still borrows its header's alignment.
+ return (
+ styleOfCells(collect(bodyRows, c)) ??
+ styleOfCells(collect([0], c)) ??
+ defaultCellStyle(fontSize)
+ );
+ });
+ const header =
+ table.rows > 1
+ ? styleOfCells(
+ Array.from({ length: table.cols }, (_, c) => collect([0], c)).flat(),
+ )
+ : null;
+ const body = styleOfCells(
+ Array.from({ length: table.cols }, (_, c) => collect(bodyRows, c)).flat(),
+ );
+ return {
+ columnStyles,
+ headerStyle: headerDiffers(header, body) ? header : null,
+ };
+}
+
+// New cell text should match what the table already uses, so take the size from
+// its existing runs rather than the editor default.
+function cellFontSize(page: Page, cellRuns: (string | null)[][]): number {
+ const sizes: number[] = [];
+ for (const row of cellRuns) {
+ for (const id of row) {
+ if (!id) continue;
+ const run = page.findRun(id);
+ if (run && run.fontSize > 0) sizes.push(run.fontSize);
+ }
+ }
+ if (sizes.length === 0) return FALLBACK_FONT_SIZE;
+ sizes.sort((a, b) => a - b);
+ return sizes[Math.floor(sizes.length / 2)];
+}
+
+/** Rectangle overlap test, used to re-find a table after its runs changed. */
+export function overlaps(
+ a: { x: number; y: number; width: number; height: number },
+ b: { x: number; y: number; width: number; height: number },
+): boolean {
+ return (
+ a.x < b.x + b.width &&
+ a.x + a.width > b.x &&
+ a.y < b.y + b.height &&
+ a.y + a.height > b.y
+ );
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/tableDetection.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/tableDetection.ts
new file mode 100644
index 0000000000..68cc3c8618
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/tableDetection.ts
@@ -0,0 +1,897 @@
+import type {
+ PageRect,
+ TableCellSnapshot,
+ TableSnapshot,
+ TextRunSnapshot,
+} from "@app/tools/pdfTextEditor/types";
+
+// Recognizes tabular layouts from a page's text runs. PDF has no native table
+// object, so a "table" here is a derived grid: runs that line up into shared
+// columns across several vertically-stacked rows. Pure and deterministic so it
+// can be unit-tested without PDFium.
+
+export interface TableDetectionOptions {
+ // Two runs share a row when their vertical centres are within this fraction
+ // of the median run height.
+ rowTolFactor: number;
+ // Two left edges share a column when within this fraction of median height.
+ colTolFactor: number;
+ // A vertical gap larger than this many row-heights breaks one table into two.
+ maxRowGapFactor: number;
+ /** Minimum rows for a run block to count as a table. */
+ minRows: number;
+ /** Minimum columns for a run block to count as a table. */
+ minCols: number;
+}
+
+// A rule counts as part of the grid only if it runs along most of the table.
+const RULE_COVERAGE = 0.5;
+/** How far outside the derived bounds a rule may still be the table's own. */
+const RULE_EDGE_MARGIN_PT = 12;
+/** A gap this many times the table's usual row gap ends the table. */
+const ROW_GAP_TOLERANCE = 2;
+
+export const DEFAULT_TABLE_OPTIONS: TableDetectionOptions = {
+ rowTolFactor: 0.6,
+ colTolFactor: 0.9,
+ maxRowGapFactor: 2.5,
+ minRows: 2,
+ minCols: 2,
+};
+
+interface Cand {
+ run: TextRunSnapshot;
+ left: number;
+ right: number;
+ cx: number;
+ cy: number;
+ height: number;
+}
+
+interface Row {
+ cands: Cand[];
+ cy: number;
+ top: number;
+ bottom: number;
+}
+
+function median(values: number[]): number {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 0
+ ? (sorted[mid - 1] + sorted[mid]) / 2
+ : sorted[mid];
+}
+
+// One candidate box per line of text. A table cell is a single line, but the
+// editor's paragraph grouping merges a whole table COLUMN into one multi-line
+// run, so a run must be expanded into its member lines or the cells never
+// appear. Returns [] for anything that cannot contribute.
+function toCandidates(run: TextRunSnapshot): Cand[] {
+ if (run.locked) return [];
+ if (!run.text || run.text.trim().length === 0) return [];
+ const { x, y, width, height } = run.bounds;
+ if (width <= 0 || height <= 0) return [];
+ const lines = run.paragraphLineCount ?? 1;
+ if (lines <= 1) {
+ return [
+ {
+ run,
+ left: x,
+ right: x + width,
+ cx: x + width / 2,
+ cy: y + height / 2,
+ height,
+ },
+ ];
+ }
+ return expandParagraph(run, lines);
+}
+
+// Split a multi-line run using the per-line geometry PDFium gave us. Baselines
+// and lefts are exact; only each line's width is estimated, from its share of
+// the longest line's character count.
+function expandParagraph(run: TextRunSnapshot, lines: number): Cand[] {
+ const baselines = run.paragraphBaselines;
+ const lefts = run.paragraphLineLefts;
+ const texts = run.text.split("\n");
+ // Without real baselines the line boxes would be guesswork, and a wrong row
+ // band is worse than no candidate.
+ if (!baselines || baselines.length !== lines || texts.length < lines)
+ return [];
+ const { x, y, width, height } = run.bounds;
+ // The run's box spans the first line's ascent to the last line's descent, so
+ // the per-line box follows from its own baseline.
+ const descent = baselines[lines - 1] - y;
+ const ascent = y + height - baselines[0];
+ const lineHeight = ascent + descent;
+ if (lineHeight <= 0) return [];
+ const lengths = texts.slice(0, lines).map((s) => s.trim().length);
+ const maxLen = Math.max(...lengths, 1);
+ const out: Cand[] = [];
+ for (let i = 0; i < lines; i++) {
+ if (lengths[i] === 0) continue;
+ const left = lefts?.[i] ?? x;
+ const w = Math.max(1, (width * lengths[i]) / maxLen);
+ const bottom = baselines[i] - descent;
+ out.push({
+ run,
+ left,
+ right: left + w,
+ cx: left + w / 2,
+ cy: bottom + lineHeight / 2,
+ height: lineHeight,
+ });
+ }
+ return out;
+}
+
+// Cluster candidates into rows by vertical-centre proximity, top-down.
+function groupRows(cands: Cand[], rowTol: number): Row[] {
+ const sorted = [...cands].sort((a, b) => b.cy - a.cy);
+ const rows: Row[] = [];
+ let current: Cand[] = [];
+ let ref = 0;
+ for (const c of sorted) {
+ if (current.length === 0 || Math.abs(c.cy - ref) <= rowTol) {
+ if (current.length === 0) ref = c.cy;
+ current.push(c);
+ // Track the row centre as a running mean so a slightly drifting baseline
+ // does not split one visual row in two.
+ ref += (c.cy - ref) / current.length;
+ } else {
+ rows.push(finishRow(current));
+ current = [c];
+ ref = c.cy;
+ }
+ }
+ if (current.length > 0) rows.push(finishRow(current));
+ return rows;
+}
+
+// The row's extent comes from the LINE boxes in it. Taking the parent run's
+// box instead collapses every row of a paragraph-merged column onto the same
+// top and bottom, and the derived row edges come out identical - a grid of
+// zero-height rows.
+function finishRow(cands: Cand[]): Row {
+ const ordered = [...cands].sort((a, b) => a.left - b.left);
+ const tops = ordered.map((c) => c.cy + c.height / 2);
+ const bottoms = ordered.map((c) => c.cy - c.height / 2);
+ return {
+ cands: ordered,
+ cy: ordered.reduce((s, c) => s + c.cy, 0) / ordered.length,
+ top: Math.max(...tops),
+ bottom: Math.min(...bottoms),
+ };
+}
+
+interface Band {
+ left: number;
+ right: number;
+}
+
+// Columns as vertical whitespace bands: merge the runs' x-intervals, splitting
+// only where a gap wider than `minGap` separates them. Alignment-agnostic, so a
+// right-aligned numeric column (varying lefts, shared band) stays one column.
+function columnBands(cands: Cand[], minGap: number): Band[] {
+ const intervals = cands
+ .map((c) => ({ left: c.left, right: c.right }))
+ .sort((a, b) => a.left - b.left);
+ const bands: Band[] = [];
+ for (const iv of intervals) {
+ const last = bands[bands.length - 1];
+ if (last && iv.left - last.right <= minGap) {
+ last.right = Math.max(last.right, iv.right);
+ } else {
+ bands.push({ left: iv.left, right: iv.right });
+ }
+ }
+ return bands;
+}
+
+// Two adjacent bands that never both appear in one row are one column whose
+// entries are aligned differently - a left-aligned header sitting above a
+// right-aligned number column leaves a whitespace gap between them, which would
+// otherwise split that column in two.
+function mergeAlignmentBands(bands: Band[], rows: Row[]): Band[] {
+ let merged = bands;
+ let changed = true;
+ while (changed && merged.length > 1) {
+ changed = false;
+ for (let i = 0; i < merged.length - 1; i++) {
+ const together = rows.some((r) => {
+ let a = false;
+ let b = false;
+ for (const c of r.cands) {
+ const idx = bandIndex(merged, c.cx);
+ if (idx === i) a = true;
+ else if (idx === i + 1) b = true;
+ }
+ return a && b;
+ });
+ if (together) continue;
+ merged = [
+ ...merged.slice(0, i),
+ { left: merged[i].left, right: merged[i + 1].right },
+ ...merged.slice(i + 2),
+ ];
+ changed = true;
+ break;
+ }
+ }
+ return merged;
+}
+
+// A drawn rule reduced to the coordinate it pins and the span it runs along.
+interface RuleLine {
+ at: number;
+ from: number;
+ to: number;
+}
+
+// Collinear pieces are one line. A grid of stroked cells contributes each
+// boundary once per cell, so without joining them no single piece ever spans
+// enough of the table to be recognized as one of its rules.
+const RULE_COLLINEAR_EPS = 0.75;
+const RULE_JOIN_GAP = 2;
+
+function ruleLines(rules: PageRect[], vertical: boolean): RuleLine[] {
+ const pieces: RuleLine[] = [];
+ for (const r of rules) {
+ if (r.width <= r.height !== vertical) continue;
+ pieces.push(
+ vertical
+ ? { at: r.x + r.width / 2, from: r.y, to: r.y + r.height }
+ : { at: r.y + r.height / 2, from: r.x, to: r.x + r.width },
+ );
+ }
+ pieces.sort((a, b) => a.at - b.at || a.from - b.from);
+ const out: RuleLine[] = [];
+ for (const piece of pieces) {
+ const last = out[out.length - 1];
+ if (
+ last &&
+ Math.abs(piece.at - last.at) <= RULE_COLLINEAR_EPS &&
+ piece.from <= last.to + RULE_JOIN_GAP
+ ) {
+ last.to = Math.max(last.to, piece.to);
+ continue;
+ }
+ out.push({ ...piece });
+ }
+ return out;
+}
+
+// The rules that belong to this table are the ones running along most of it. A
+// stray underline or a page border only clips a corner and is dropped.
+function pinsAcross(
+ lines: RuleLine[],
+ lo: number,
+ hi: number,
+ minCover: number,
+ atLo: number,
+ atHi: number,
+): number[] {
+ const span = hi - lo;
+ if (span <= 0) return [];
+ const hits = lines
+ .filter(
+ (l) =>
+ // Running the length of the table is not enough on its own: a second
+ // table further down the page has rules just as wide, and taking those
+ // in wrecks the grid. The line must sit within this table's extent too.
+ l.at >= atLo - RULE_EDGE_MARGIN_PT &&
+ l.at <= atHi + RULE_EDGE_MARGIN_PT &&
+ (Math.min(l.to, hi) - Math.max(l.from, lo)) / span >= minCover,
+ )
+ .map((l) => l.at)
+ .sort((a, b) => a - b);
+ const merged: number[] = [];
+ for (const v of hits) {
+ if (merged.length > 0 && v - merged[merged.length - 1] < 0.75) continue;
+ merged.push(v);
+ }
+ return merged;
+}
+
+// Move derived edges onto the lines the page actually draws. Text-derived edges
+// sit at the midpoint of the whitespace between columns, which is not where the
+// rule is - up to ~10pt out on a wide column - so the overlay reads as skewed
+// against a table the reader can see the borders of.
+// True when the drawn lines put every track's content in its OWN cell, in
+// order. Matching counts alone is not evidence: a page border plus some
+// unrelated graphics can add up to the right number of lines in the wrong
+// places, and adopting those would shred the grid.
+function pinsSeparate(centres: number[], pins: number[]): boolean {
+ if (pins.length !== centres.length + 1) return false;
+ const sorted = [...centres].sort((a, b) => a - b);
+ for (let i = 0; i < sorted.length; i++) {
+ if (sorted[i] <= pins[i] || sorted[i] >= pins[i + 1]) return false;
+ }
+ return true;
+}
+
+function snapAxis(
+ edges: number[],
+ pins: number[],
+ centres: number[],
+ tol: number,
+): { edges: number[]; drawn: boolean } {
+ if (pins.length === 0) return { edges, drawn: false };
+ const descending = edges[0] > edges[edges.length - 1];
+ // The drawn grid separates exactly the tracks we derived: it IS the table.
+ if (pinsSeparate(centres, pins)) {
+ return { edges: descending ? [...pins].reverse() : pins, drawn: true };
+ }
+ const snapped = edges.map((e) => {
+ let best = e;
+ let bestDist = tol;
+ for (const p of pins) {
+ const d = Math.abs(p - e);
+ if (d < bestDist) {
+ bestDist = d;
+ best = p;
+ }
+ }
+ return best;
+ });
+ // Two edges landing on one rule would collapse a track; keep the derived set.
+ for (let i = 1; i < snapped.length; i++) {
+ const ordered = descending
+ ? snapped[i] < snapped[i - 1]
+ : snapped[i] > snapped[i - 1];
+ if (!ordered) return { edges, drawn: false };
+ }
+ return { edges: snapped, drawn: false };
+}
+
+// A column boundary the page draws, and which of the table's rows it actually
+// separates. A merged cell shows up as a boundary that is simply ABSENT over
+// the rows it spans, so the rule's vertical coverage IS the merge structure.
+export interface ColumnPin {
+ at: number;
+ /** Indices of the row bands this boundary is drawn across. */
+ rows: Set<number>;
+}
+
+/** A rule counts as separating a row when it covers most of that row's band. */
+const PIN_ROW_COVERAGE = 0.6;
+/** How far past the text extent a column boundary may sit, as a width share. */
+const PIN_EDGE_MARGIN_FRACTION = 0.2;
+
+// A row boundary the page draws, and which columns it is drawn across. A cell
+// merged DOWNWARDS shows up as a boundary that skips its column.
+export interface RowPin {
+ at: number;
+ cols: Set<number>;
+}
+
+/** Row boundaries the page draws over a span of the page, top-down. */
+export function rowPins(
+ lines: RuleLine[],
+ colEdges: number[],
+ lo: number,
+ hi: number,
+): RowPin[] {
+ const cols = colEdges.length - 1;
+ const margin = Math.max(
+ RULE_EDGE_MARGIN_PT,
+ (hi - lo) * PIN_EDGE_MARGIN_FRACTION,
+ );
+ const out: RowPin[] = [];
+ for (const line of lines) {
+ if (line.at < lo - margin || line.at > hi + margin) continue;
+ const covered = new Set<number>();
+ for (let c = 0; c < cols; c++) {
+ const width = colEdges[c + 1] - colEdges[c];
+ if (width <= 0) continue;
+ const overlap =
+ Math.min(line.to, colEdges[c + 1]) - Math.max(line.from, colEdges[c]);
+ if (overlap / width >= PIN_ROW_COVERAGE) covered.add(c);
+ }
+ if (covered.size === 0) continue;
+ const near = out.find((p) => Math.abs(p.at - line.at) < 0.75);
+ if (near) {
+ for (const c of covered) near.cols.add(c);
+ } else {
+ out.push({ at: line.at, cols: covered });
+ }
+ }
+ return out.sort((a, b) => b.at - a.at);
+}
+
+// Split the page's row boundaries into one group per table: a gap much larger
+// than the usual row spacing is the space between two tables, not a tall row.
+export function clusterRowPins(pins: RowPin[]): RowPin[][] {
+ if (pins.length < 2) return pins.length > 0 ? [pins] : [];
+ const gaps: number[] = [];
+ for (let i = 1; i < pins.length; i++) gaps.push(pins[i - 1].at - pins[i].at);
+ const typical = median(gaps.filter((g) => g > 0));
+ const limit = typical > 0 ? typical * ROW_GAP_TOLERANCE : Infinity;
+ const out: RowPin[][] = [[pins[0]]];
+ for (let i = 1; i < pins.length; i++) {
+ if (pins[i - 1].at - pins[i].at > limit) out.push([]);
+ out[out.length - 1].push(pins[i]);
+ }
+ return out;
+}
+
+// Re-band candidates onto the row boundaries the page draws. Text banding
+// cannot see a vertically merged cell: its text is centred over the rows it
+// spans, so it lands between them and tears the table in two.
+export function bandByRules(cands: Cand[], pins: RowPin[]): Row[] | null {
+ if (pins.length < 3) return null;
+ const rows: Row[] = [];
+ for (let i = 0; i < pins.length - 1; i++) {
+ const hi = pins[i].at;
+ const lo = pins[i + 1].at;
+ const inBand = cands.filter((c) => c.cy <= hi && c.cy >= lo);
+ rows.push({
+ cands: [...inBand].sort((a, b) => a.left - b.left),
+ cy: (hi + lo) / 2,
+ top: hi,
+ bottom: lo,
+ });
+ }
+ return rows;
+}
+
+// Unlike the horizontal pins, a vertical rule is kept even when it spans only
+// part of the table: covering one row band is enough to make it a real column
+// boundary, and the rows it misses are the merges.
+export function columnPins(
+ lines: RuleLine[],
+ rows: Row[],
+ atLo: number,
+ atHi: number,
+): ColumnPin[] {
+ // The derived box comes from TEXT, so it can sit most of a column's padding
+ // inside the drawn frame - on the merged-cell fixture the outer rule was 34pt
+ // beyond it. Requiring the rule to cross this table's own row bands is the
+ // real filter, so the horizontal window can be generous.
+ const margin = Math.max(
+ RULE_EDGE_MARGIN_PT,
+ (atHi - atLo) * PIN_EDGE_MARGIN_FRACTION,
+ );
+ const out: ColumnPin[] = [];
+ for (const line of lines) {
+ if (line.at < atLo - margin) continue;
+ if (line.at > atHi + margin) continue;
+ const covered = new Set<number>();
+ for (let r = 0; r < rows.length; r++) {
+ const band = rows[r].top - rows[r].bottom;
+ if (band <= 0) continue;
+ const overlap =
+ Math.min(line.to, rows[r].top) - Math.max(line.from, rows[r].bottom);
+ if (overlap / band >= PIN_ROW_COVERAGE) covered.add(r);
+ }
+ if (covered.size === 0) continue;
+ const near = out.find((p) => Math.abs(p.at - line.at) < 0.75);
+ if (near) {
+ for (const r of covered) near.rows.add(r);
+ } else {
+ out.push({ at: line.at, rows: covered });
+ }
+ }
+ return out.sort((a, b) => a.at - b.at);
+}
+
+// Cells of one row, as [startCol, endCol] ranges. A boundary the page does not
+// draw across this row does not divide it, so the columns either side are one
+// merged cell.
+export function rowSpans(
+ pins: ColumnPin[],
+ cols: number,
+ row: number,
+): { start: number; span: number }[] {
+ const out: { start: number; span: number }[] = [];
+ let start = 0;
+ for (let c = 1; c < cols; c++) {
+ // pins[c] is the boundary between column c-1 and column c: the outer edge
+ // is pins[0], so interior boundary c sits at index c.
+ const pin = pins[c];
+ if (pin && !pin.rows.has(row)) continue;
+ out.push({ start, span: c - start });
+ start = c;
+ }
+ out.push({ start, span: cols - start });
+ return out;
+}
+
+// How far a cell reaches downwards: while the boundary below it is not drawn
+// across every column it occupies, it is one merged cell.
+function downSpan(
+ pins: RowPin[],
+ rows: number,
+ row: number,
+ start: number,
+ span: number,
+): number {
+ let reach = 1;
+ while (row + reach < rows) {
+ const pin = pins[row + reach];
+ if (!pin) break;
+ let dividesAll = true;
+ for (let c = start; c < start + span; c++) {
+ if (!pin.cols.has(c)) dividesAll = false;
+ }
+ if (dividesAll) break;
+ reach++;
+ }
+ return reach;
+}
+
+/** Index of the track in `edges` containing `x`, clamped to the outer tracks. */
+function edgeIndex(edges: number[], x: number): number {
+ const descending = edges[0] > edges[edges.length - 1];
+ for (let i = 0; i < edges.length - 1; i++) {
+ const lo = descending ? edges[i + 1] : edges[i];
+ const hi = descending ? edges[i] : edges[i + 1];
+ if (x >= lo && x <= hi) return i;
+ }
+ const firstMid = (edges[0] + edges[1]) / 2;
+ return Math.abs(x - firstMid) <= Math.abs(x - edges[edges.length - 1])
+ ? 0
+ : edges.length - 2;
+}
+
+/** Index of the band whose span contains `x`, else the nearest by centre. */
+function bandIndex(bands: Band[], x: number): number {
+ for (let i = 0; i < bands.length; i++) {
+ if (x >= bands[i].left && x <= bands[i].right) return i;
+ }
+ let best = 0;
+ let bestDist = Infinity;
+ for (let i = 0; i < bands.length; i++) {
+ const centre = (bands[i].left + bands[i].right) / 2;
+ const d = Math.abs(centre - x);
+ if (d < bestDist) {
+ bestDist = d;
+ best = i;
+ }
+ }
+ return best;
+}
+
+// Drop single-cell rows from the top and bottom of a block. A heading above a
+// table, or a prose line tight beneath it, sits too close for the gap rule to
+// separate but spans only one column, so it is not a row of the grid.
+function trimEdgeRows(block: Row[]): Row[] {
+ let start = 0;
+ let end = block.length;
+ while (start < end && block[start].cands.length < 2) start++;
+ while (end > start && block[end - 1].cands.length < 2) end--;
+ return block.slice(start, end);
+}
+
+// Split rows into vertically-contiguous blocks: a large vertical gap ends a
+// table (e.g. the gap between a table and the paragraph beneath it).
+//
+// "Large" is measured against the page's own row pitch, not against the glyph
+// height. A generously spaced table - a form, a padded invoice, the text layer
+// over a scan - has rows several times the type size apart, and a fixed
+// multiple of the type size cut every one of those tables into single rows.
+function splitBlocks(rows: Row[], minGap: number): Row[][] {
+ const gaps: number[] = [];
+ for (let i = 1; i < rows.length; i++) {
+ gaps.push(rows[i - 1].bottom - rows[i].top);
+ }
+ const typical = median(gaps.filter((g) => g > 0));
+ const maxGap = Math.max(minGap, typical * ROW_GAP_TOLERANCE);
+ const blocks: Row[][] = [];
+ let current: Row[] = [];
+ for (let i = 0; i < rows.length; i++) {
+ if (current.length === 0) {
+ current.push(rows[i]);
+ continue;
+ }
+ const prev = current[current.length - 1];
+ const gap = prev.bottom - rows[i].top;
+ if (gap > maxGap) {
+ blocks.push(current);
+ current = [rows[i]];
+ } else {
+ current.push(rows[i]);
+ }
+ }
+ if (current.length > 0) blocks.push(current);
+ return blocks;
+}
+
+// A merged label can bridge the whitespace between otherwise separate columns.
+// Use the drawn tracks when both axes form a grid and every column contains
+// text in multiple rows; unrelated page borders cannot establish empty tracks.
+function ruledColumnBands(block: Row[], rules: PageRect[]): Band[] | null {
+ const cands = block.flatMap((row) => row.cands);
+ if (cands.length === 0) return null;
+ const pins = columnPins(
+ ruleLines(rules, true),
+ block,
+ Math.min(...cands.map((c) => c.left)),
+ Math.max(...cands.map((c) => c.right)),
+ );
+ if (pins.length < 3) return null;
+ const edges = pins.map((pin) => pin.at);
+ const horizontal = rowPins(
+ ruleLines(rules, false),
+ edges,
+ block[block.length - 1].bottom,
+ block[0].top,
+ );
+ const rows = [block[0].top, ...block.map((row) => row.bottom)];
+ if (
+ horizontal.length !== rows.length ||
+ horizontal.some((pin, i) => Math.abs(pin.at - rows[i]) > RULE_COLLINEAR_EPS)
+ )
+ return null;
+ const bands = edges.slice(0, -1).map((left, i) => ({
+ left,
+ right: edges[i + 1],
+ }));
+ if (
+ bands.some(
+ (band) =>
+ block.filter((row) =>
+ row.cands.some((c) => c.cx > band.left && c.cx < band.right),
+ ).length < 2,
+ )
+ )
+ return null;
+ return bands;
+}
+
+function buildTable(
+ block: Row[],
+ bands: Band[],
+ pageIndex: number,
+ index: number,
+ opts: TableDetectionOptions,
+ rules: PageRect[],
+ snapTol: number,
+): TableSnapshot | null {
+ const cols = bands.length;
+ const rows = block.length;
+ if (rows < opts.minRows || cols < opts.minCols) return null;
+
+ // Inner edges sit at the midpoint of the whitespace between tracks. The outer
+ // ones get the SAME half-gap as a margin: taking the glyph extent instead
+ // makes the boundary graze the first and last row's text, which reads as a
+ // misdrawn grid on a table that has no printed border to check it against.
+ const colGaps: number[] = [];
+ for (let i = 1; i < cols; i++)
+ colGaps.push(bands[i].left - bands[i - 1].right);
+ const colPad = Math.max(1, median(colGaps) / 2);
+ const derivedCols: number[] = [bands[0].left - colPad];
+ for (let i = 1; i < cols; i++) {
+ derivedCols.push((bands[i - 1].right + bands[i].left) / 2);
+ }
+ derivedCols.push(bands[cols - 1].right + colPad);
+
+ const rowGaps: number[] = [];
+ for (let i = 1; i < rows; i++)
+ rowGaps.push(block[i - 1].bottom - block[i].top);
+ const rowPad = Math.max(1, median(rowGaps) / 2);
+ const derivedRows: number[] = [block[0].top + rowPad];
+ for (let i = 1; i < rows; i++) {
+ derivedRows.push((block[i - 1].bottom + block[i].top) / 2);
+ }
+ derivedRows.push(block[rows - 1].bottom - rowPad);
+
+ // Vertical boundaries come with the rows they are drawn across, so a rule
+ // that stops short is a merge rather than a rule to throw away.
+ const pins = columnPins(
+ ruleLines(rules, true),
+ block,
+ derivedCols[0],
+ derivedCols[cols],
+ );
+ const snappedCols = snapAxis(
+ derivedCols,
+ pins.map((p) => p.at),
+ bands.map((b) => (b.left + b.right) / 2),
+ snapTol,
+ );
+ const colEdges = snappedCols.edges;
+ const snappedRows = snapAxis(
+ derivedRows,
+ pinsAcross(
+ ruleLines(rules, false),
+ colEdges[0],
+ colEdges[cols],
+ RULE_COVERAGE,
+ derivedRows[rows],
+ derivedRows[0],
+ ),
+ block.map((r) => r.cy),
+ snapTol,
+ );
+ const rowEdges = snappedRows.edges;
+
+ // Spans are only trustworthy when the drawn boundaries ARE the columns; a
+ // grid inferred from whitespace has no evidence about what is merged.
+ const spannable = snappedCols.drawn && pins.length === cols + 1;
+ // The row boundaries as drawn, so a boundary that skips a column reads as a
+ // cell merged downwards.
+ const hPins = rowPins(
+ ruleLines(rules, false),
+ colEdges,
+ rowEdges[rows],
+ rowEdges[0],
+ );
+ const downMergeable = spannable && hPins.length === rows + 1;
+ const byCol = block.map((row) => {
+ const map = new Map<number, string[]>();
+ for (const c of row.cands) {
+ const col = edgeIndex(colEdges, c.cx);
+ const list = map.get(col) ?? [];
+ list.push(c.run.id);
+ map.set(col, list);
+ }
+ return map;
+ });
+
+ const cells: TableCellSnapshot[] = [];
+ const covered = new Set<string>();
+ let occupiedCells = 0;
+ for (let r = 0; r < rows; r++) {
+ const spans = spannable
+ ? rowSpans(pins, cols, r)
+ : Array.from({ length: cols }, (_, col) => ({ start: col, span: 1 }));
+ for (const { start, span } of spans) {
+ if (covered.has(`${r},${start}`)) continue;
+ const rowSpan = downMergeable ? downSpan(hPins, rows, r, start, span) : 1;
+ const runIds: string[] = [];
+ for (let rr = r; rr < r + rowSpan; rr++) {
+ for (let col = start; col < start + span; col++) {
+ runIds.push(...(byCol[rr]?.get(col) ?? []));
+ }
+ }
+ for (let rr = r; rr < r + rowSpan; rr++) {
+ for (let cc = start; cc < start + span; cc++) {
+ if (rr !== r || cc !== start) covered.add(`${rr},${cc}`);
+ }
+ }
+ if (runIds.length > 0) occupiedCells++;
+ cells.push({
+ row: r,
+ col: start,
+ runIds,
+ colSpan: span,
+ rowSpan,
+ rect: {
+ x: colEdges[start],
+ y: rowEdges[r + rowSpan],
+ width: colEdges[start + span] - colEdges[start],
+ height: rowEdges[r] - rowEdges[r + rowSpan],
+ },
+ });
+ }
+ }
+
+ // Reject prose masquerading as a table: a real grid fills a good share of its
+ // cells and has multiple rows contributing to each column alignment.
+ const fill = occupiedCells / cells.length;
+ if (fill < 0.4) return null;
+ const rowsWithMultipleCols = block.filter(
+ (r) => new Set(r.cands.map((c) => edgeIndex(colEdges, c.cx))).size >= 2,
+ ).length;
+ if (rowsWithMultipleCols < 2) return null;
+
+ const bounds: PageRect = {
+ x: colEdges[0],
+ y: rowEdges[rows],
+ width: colEdges[cols] - colEdges[0],
+ height: rowEdges[0] - rowEdges[rows],
+ };
+ const confidence = Math.min(
+ 1,
+ 0.5 * fill + 0.5 * (rowsWithMultipleCols / rows),
+ );
+
+ return {
+ id: `p${pageIndex}-table-${index}`,
+ pageIndex,
+ rows,
+ cols,
+ colEdges,
+ rowEdges,
+ bounds,
+ cells,
+ confidence,
+ synthetic: false,
+ // Only adoption can tell: it needs the render modes behind the text.
+ scanned: false,
+ ruled: false,
+ pageRuled: snappedCols.drawn && snappedRows.drawn,
+ adopted: false,
+ // Styles are read off the runs when the table is adopted for editing.
+ columnStyles: [],
+ headerStyle: null,
+ };
+}
+
+/** Recognize tables on one page from its text-run snapshots. */
+export function detectTables(
+ runs: TextRunSnapshot[],
+ pageIndex: number,
+ options: Partial<TableDetectionOptions> = {},
+ rules: PageRect[] = [],
+): TableSnapshot[] {
+ const opts = { ...DEFAULT_TABLE_OPTIONS, ...options };
+ const cands = runs.flatMap(toCandidates);
+ if (cands.length < opts.minRows * opts.minCols) return [];
+
+ const medHeight = median(cands.map((c) => c.height)) || 1;
+ const rowTol = medHeight * opts.rowTolFactor;
+ // Minimum whitespace between columns, scaled to the text size.
+ const minColGap = Math.max(3, medHeight * opts.colTolFactor);
+ const maxGap = medHeight * opts.maxRowGapFactor;
+
+ // Where the page draws a set of row boundaries, they define the rows for the
+ // candidates they enclose. Splitting on text gaps alone tears a vertically
+ // merged table in two, because the merged cell's text is centred over the
+ // rows it spans and so lands between them.
+ const allPins = rowPins(
+ ruleLines(rules, false),
+ [
+ Math.min(...cands.map((c) => c.left)),
+ Math.max(...cands.map((c) => c.right)),
+ ],
+ Math.min(...cands.map((c) => c.cy)),
+ Math.max(...cands.map((c) => c.cy)),
+ );
+ const blocks: Row[][] = [];
+ const claimed = new Set<Cand>();
+ for (const group of clusterRowPins(allPins)) {
+ if (group.length < 3) continue;
+ const top = group[0].at;
+ const bottom = group[group.length - 1].at;
+ const inside = cands.filter((c) => c.cy <= top && c.cy >= bottom);
+ if (inside.length < opts.minRows * opts.minCols) continue;
+ const banded = bandByRules(inside, group);
+ if (!banded) continue;
+ blocks.push(banded);
+ for (const c of inside) claimed.add(c);
+ }
+ // Whatever the rules did not claim still goes through text banding.
+ const loose = cands.filter((c) => !claimed.has(c));
+ if (loose.length > 0) {
+ blocks.push(
+ ...splitBlocks(
+ groupRows(loose, rowTol).filter((r) => r.cands.length >= 1),
+ maxGap,
+ ),
+ );
+ }
+
+ const tables: TableSnapshot[] = [];
+ for (const raw of blocks) {
+ const block = trimEdgeRows(raw);
+ // A table needs several rows that each span multiple columns. Derive the
+ // column bands from rows that already carry 2+ runs, so a stray full-width
+ // heading line does not smear the bands together.
+ const multiRunRows = block.filter((r) => r.cands.length >= 2);
+ if (multiRunRows.length < opts.minRows) continue;
+ const bands =
+ ruledColumnBands(block, rules) ??
+ mergeAlignmentBands(
+ columnBands(
+ multiRunRows.flatMap((r) => r.cands),
+ minColGap,
+ ),
+ block,
+ );
+ const table = buildTable(
+ block,
+ bands,
+ pageIndex,
+ tables.length,
+ opts,
+ rules,
+ Math.max(4, medHeight * 1.5),
+ );
+ if (table) tables.push(table);
+ }
+ return tables;
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/tableGeometry.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/tableGeometry.ts
new file mode 100644
index 0000000000..4f3112577d
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/tableGeometry.ts
@@ -0,0 +1,188 @@
+// Pure grid-geometry maths for structural table edits. Column edges run
+// left-to-right (ascending x); row edges run top-to-bottom (DESCENDING y, PDF
+// points). Kept free of PDFium so the arithmetic can be unit-tested directly.
+
+export interface EdgeEdit {
+ /** The boundary array after the edit. */
+ edges: number[];
+ // How much each existing track index shifts, and by how far, so the caller
+ // can move the runs that live in those tracks. delta is in PDF points.
+ shift: { fromIndex: number; delta: number };
+}
+
+/** Insert a new column at slot `k` (0..cols) of width `w`. */
+export function insertColumnEdges(
+ colEdges: number[],
+ k: number,
+ w: number,
+): EdgeEdit {
+ const out: number[] = [];
+ for (let i = 0; i < k; i++) out.push(colEdges[i]);
+ out.push(colEdges[k]);
+ for (let i = k; i < colEdges.length; i++) out.push(colEdges[i] + w);
+ return { edges: out, shift: { fromIndex: k, delta: w } };
+}
+
+/** Remove column `k`; tracks to its right shift left by the column's width. */
+export function removeColumnEdges(colEdges: number[], k: number): EdgeEdit {
+ const w = colEdges[k + 1] - colEdges[k];
+ const out: number[] = [];
+ for (let i = 0; i < colEdges.length; i++) {
+ if (i === k + 1) continue;
+ out.push(i <= k ? colEdges[i] : colEdges[i] - w);
+ }
+ return { edges: out, shift: { fromIndex: k + 1, delta: -w } };
+}
+
+/** Insert a new row at slot `k` (0..rows) of height `h`; rows below drop. */
+export function insertRowEdges(
+ rowEdges: number[],
+ k: number,
+ h: number,
+): EdgeEdit {
+ const out: number[] = [];
+ for (let i = 0; i < k; i++) out.push(rowEdges[i]);
+ out.push(rowEdges[k]);
+ // Rows below the insertion move DOWN (y decreases) by h.
+ for (let i = k; i < rowEdges.length; i++) out.push(rowEdges[i] - h);
+ return { edges: out, shift: { fromIndex: k, delta: -h } };
+}
+
+/** Remove row `k`; rows below shift up (y increases) by the row's height. */
+export function removeRowEdges(rowEdges: number[], k: number): EdgeEdit {
+ const h = rowEdges[k] - rowEdges[k + 1];
+ const out: number[] = [];
+ for (let i = 0; i < rowEdges.length; i++) {
+ if (i === k + 1) continue;
+ out.push(i <= k ? rowEdges[i] : rowEdges[i] + h);
+ }
+ return { edges: out, shift: { fromIndex: k + 1, delta: h } };
+}
+
+/** Uniform column edges spanning [x, x+width] across `cols` columns. */
+export function uniformColumnEdges(
+ x: number,
+ width: number,
+ cols: number,
+): number[] {
+ const step = width / cols;
+ return Array.from({ length: cols + 1 }, (_, i) => x + i * step);
+}
+
+// Uniform row edges spanning [topY-height, topY] across `rows` rows, returned
+// top-to-bottom (descending y).
+export function uniformRowEdges(
+ topY: number,
+ height: number,
+ rows: number,
+): number[] {
+ const step = height / rows;
+ return Array.from({ length: rows + 1 }, (_, i) => topY - i * step);
+}
+
+/** Smallest column width / row height a resize may produce, in points. */
+export const MIN_TRACK = 8;
+
+// Move internal column edge `k` to x, absorbing the change into the two columns
+// either side; every other edge holds still. Clamped so neither neighbour falls
+// below `min`. Outer edges (k = 0 or last) are not movable: resizing the table
+// as a whole is `scaleColumnEdges`.
+export function moveColumnEdge(
+ colEdges: number[],
+ k: number,
+ x: number,
+ min: number = MIN_TRACK,
+): number[] {
+ const out = [...colEdges];
+ if (k <= 0 || k >= colEdges.length - 1) return out;
+ const lo = colEdges[k - 1] + min;
+ const hi = colEdges[k + 1] - min;
+ if (hi < lo) return out;
+ out[k] = Math.min(Math.max(x, lo), hi);
+ return out;
+}
+
+// Move internal row edge `k` to y. Row edges descend, so the edge above bounds
+// it from ABOVE and the edge below from below.
+export function moveRowEdge(
+ rowEdges: number[],
+ k: number,
+ y: number,
+ min: number = MIN_TRACK,
+): number[] {
+ const out = [...rowEdges];
+ if (k <= 0 || k >= rowEdges.length - 1) return out;
+ const hi = rowEdges[k - 1] - min;
+ const lo = rowEdges[k + 1] + min;
+ if (hi < lo) return out;
+ out[k] = Math.min(Math.max(y, lo), hi);
+ return out;
+}
+
+/** Rescale columns to span `width` from the left edge, keeping their ratios. */
+export function scaleColumnEdges(
+ colEdges: number[],
+ width: number,
+ min: number = MIN_TRACK,
+): number[] {
+ const cols = colEdges.length - 1;
+ if (cols < 1) return [...colEdges];
+ const x0 = colEdges[0];
+ const span = colEdges[cols] - x0;
+ const target = Math.max(width, min * cols);
+ if (span <= 0) return uniformColumnEdges(x0, target, cols);
+ const smallest = Math.min(
+ ...colEdges.slice(1).map((x, i) => x - colEdges[i]),
+ );
+ if (smallest <= 0) return uniformColumnEdges(x0, target, cols);
+ const k = Math.max(target / span, min / smallest);
+ return colEdges.map((x) => x0 + (x - x0) * k);
+}
+
+/** Rescale rows to span `height` down from the top edge, keeping their ratios. */
+export function scaleRowEdges(
+ rowEdges: number[],
+ height: number,
+ min: number = MIN_TRACK,
+): number[] {
+ const rows = rowEdges.length - 1;
+ if (rows < 1) return [...rowEdges];
+ const y0 = rowEdges[0];
+ const span = y0 - rowEdges[rows];
+ const target = Math.max(height, min * rows);
+ if (span <= 0) return uniformRowEdges(y0, target, rows);
+ const smallest = Math.min(
+ ...rowEdges.slice(1).map((y, i) => rowEdges[i] - y),
+ );
+ if (smallest <= 0) return uniformRowEdges(y0, target, rows);
+ const k = Math.max(target / span, min / smallest);
+ return rowEdges.map((y) => y0 - (y0 - y) * k);
+}
+
+// Resize the single track BEFORE edge `k`, sliding everything after it along.
+// Unlike moveColumnEdge, which makes two neighbours trade width at a fixed
+// table size, this changes one column and the table grows or shrinks with it.
+export function resizeColumnTrack(
+ colEdges: number[],
+ k: number,
+ x: number,
+ min: number = MIN_TRACK,
+): number[] {
+ if (k < 1 || k > colEdges.length - 1) return [...colEdges];
+ const clamped = Math.max(x, colEdges[k - 1] + min);
+ const delta = clamped - colEdges[k];
+ return colEdges.map((v, i) => (i >= k ? v + delta : v));
+}
+
+/** As resizeColumnTrack, for the row above edge `k` (edges descend in y). */
+export function resizeRowTrack(
+ rowEdges: number[],
+ k: number,
+ y: number,
+ min: number = MIN_TRACK,
+): number[] {
+ if (k < 1 || k > rowEdges.length - 1) return [...rowEdges];
+ const clamped = Math.min(y, rowEdges[k - 1] - min);
+ const delta = clamped - rowEdges[k];
+ return rowEdges.map((v, i) => (i >= k ? v + delta : v));
+}
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/util/tableStyle.ts b/frontend/editor/src/core/tools/pdfTextEditor/util/tableStyle.ts
new file mode 100644
index 0000000000..6db53dcb5b
--- /dev/null
+++ b/frontend/editor/src/core/tools/pdfTextEditor/util/tableStyle.ts
@@ -0,0 +1,111 @@
+import type { TextRun } from "@app/tools/pdfTextEditor/model/TextRun";
+import type {
+ PageRect,
+ RGBA,
+ TableCellStyle,
+} from "@app/tools/pdfTextEditor/types";
+import {
+ familyOf,
+ nearestStandardFont,
+} from "@app/tools/pdfTextEditor/util/fontFamily";
+
+// Reads a table's existing text back into the style new cells should be written
+// in. PDF carries no table styling of its own, so "the column's style" is
+// whatever its current entries agree on.
+
+// One existing cell. `left`/`right` are the text's MEASURED extents, not
+// run.bounds: splitting a paragraph leaves every member line carrying the
+// parent's width, which makes both cell edges look equally well aligned.
+export interface StyledCell {
+ run: TextRun;
+ rect: PageRect;
+ left: number;
+ right: number;
+}
+
+/** Alignment is judged by which edge the entries line up against. */
+const ALIGN_TOLERANCE_PT = 1.5;
+
+function mode<T>(values: T[], key: (v: T) => string): T | null {
+ const counts = new Map<string, { n: number; value: T }>();
+ for (const v of values) {
+ const k = key(v);
+ const hit = counts.get(k);
+ if (hit) hit.n++;
+ else counts.set(k, { n: 1, value: v });
+ }
+ let best: { n: number; value: T } | null = null;
+ for (const entry of counts.values()) {
+ if (!best || entry.n > best.n) best = entry;
+ }
+ return best ? best.value : null;
+}
+
+function median(values: number[]): number {
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+// Left- vs right-aligned is decided by which edge the entries agree on: the
+// spread of their distances from the cell's left edge against the spread from
+// its right. Centred wins only when both edges vary but the centres do not.
+function alignmentOf(cells: StyledCell[]): TableCellStyle["align"] {
+ if (cells.length === 0) return "left";
+ // A single entry cannot show which edge the column agrees on, but the edge it
+ // sits closest to is still the better guess than assuming left.
+ if (cells.length === 1) {
+ const [c] = cells;
+ const lead = c.left - c.rect.x;
+ const trail = c.rect.x + c.rect.width - c.right;
+ if (Math.abs(lead - trail) <= ALIGN_TOLERANCE_PT) return "center";
+ return trail < lead ? "right" : "left";
+ }
+ const lefts = cells.map((c) => c.left - c.rect.x);
+ const rights = cells.map((c) => c.rect.x + c.rect.width - c.right);
+ const centres = cells.map(
+ (c) => (c.left + c.right) / 2 - (c.rect.x + c.rect.width / 2),
+ );
+ const spread = (xs: number[]) => Math.max(...xs) - Math.min(...xs);
+ const l = spread(lefts);
+ const r = spread(rights);
+ const c = spread(centres);
+ if (l <= ALIGN_TOLERANCE_PT && l <= r) return "left";
+ if (r <= ALIGN_TOLERANCE_PT && r < l) return "right";
+ if (c <= ALIGN_TOLERANCE_PT && c < l && c < r) return "center";
+ return l <= r ? "left" : "right";
+}
+
+function fillKey(fill: RGBA): string {
+ return `${fill.r},${fill.g},${fill.b},${fill.a}`;
+}
+
+/** The style a set of existing cells agree on, or null when there are none. */
+export function styleOfCells(cells: StyledCell[]): TableCellStyle | null {
+ if (cells.length === 0) return null;
+ const runs = cells.map((c) => c.run);
+ const familyRun = mode(runs, (r) => nearestStandardFont(familyOf(r.fontId)));
+ const fillRun = mode(runs, (r) => fillKey(r.fill));
+ return {
+ family: familyRun
+ ? nearestStandardFont(familyOf(familyRun.fontId))
+ : "Helvetica",
+ fontSize: median(runs.map((r) => r.fontSize).filter((n) => n > 0)) || 11,
+ fill: fillRun ? { ...fillRun.fill } : { r: 0, g: 0, b: 0, a: 255 },
+ align: alignmentOf(cells),
+ sourceFontId: familyRun ? familyRun.fontId : "base14:Helvetica",
+ };
+}
+
+// True when the header row is set differently enough from the body to be worth
+// keeping as its own style - a bold header is the common case.
+export function headerDiffers(
+ header: TableCellStyle | null,
+ body: TableCellStyle | null,
+): boolean {
+ if (!header || !body) return false;
+ return (
+ header.sourceFontId !== body.sourceFontId ||
+ Math.abs(header.fontSize - body.fontSize) > 0.5 ||
+ fillKey(header.fill) !== fillKey(body.fill)
+ );
+}