diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml index dabcc72ac58..ccbe8265a10 100644 --- a/frontend/public/locales/en-US/translation.toml +++ b/frontend/public/locales/en-US/translation.toml @@ -7660,6 +7660,7 @@ wholeWord = "Whole word" [pdfTextEditor.fontPicker] builtInGroup = "Built-in fonts" +closestMatch = "This font is missing some of the selected letters, so they are drawn in the closest matching font." deviceFontsNone = "No extra device fonts were found." deviceFontsUnavailable = "Device fonts are unavailable. The built-in fonts still work." deviceGroup = "Device fonts" @@ -7675,12 +7676,26 @@ mixed = "Mixed" needsShaping = "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font." noGlyphs = "This font has no characters for the selected text. The text was left unchanged." noMatch = "No matching font" +partOfRunUnsupported = "This text can only be restyled as a whole. Select the box instead of some of its words." placeholder = "Font family" scannedText = "Scanned text" serverFontFailed = "That server font could not be downloaded. The text was left unchanged." serverGroup = "Server fonts" someLeftUnchanged = "This font does not have the characters for some of the selected text. That text was left unchanged." +styleSkipped = "Some of the selected text has no version of its font in that style, so it was left unchanged." +styleUnavailable = "The selected text has no version of its font in that style, so it was left unchanged." useDeviceFonts = "Use device fonts" +weight = "Font weight" +weightBlack = "Black" +weightBold = "Bold" +weightExtraBold = "Extra bold" +weightExtraLight = "Extra light" +weightLight = "Light" +weightMedium = "Medium" +weightNumber = "Weight {{weight}}" +weightRegular = "Regular" +weightSemibold = "Semibold" +weightThin = "Thin" [pdfTextEditor.fonts] allPresent = "All letters & numbers present" @@ -7725,6 +7740,7 @@ helpDesc = "This help" saveDesc = "Save to your workspace" [pdfTextEditor.help.editing] +boldItalicDesc = "Bold / Italic, for the selected words or the whole box" deleteDesc = "Remove selected" duplicateDesc = "Duplicate selected" groupDesc = "Group selected runs into one paragraph" @@ -8072,6 +8088,9 @@ alignMiddle = "Align middle" alignRight = "Align right" alignTop = "Align top" arrange = "Arrange" +bold = "Bold" +boldOnly = "This font has only a bold version" +boldUnavailable = "No bold version of this font" bringForward = "Bring forward" bringToFront = "Bring to front" caseLower = "lowercase" @@ -8092,10 +8111,12 @@ fontColour = "Font colour" fontSize = "Font size" formatting = "Text formatting" italic = "Italic" +italicOnly = "This font has only an italic version" italicUnavailable = "This font has no italic version. Load your device fonts or pick another font family." lock = "Lock selection" lockTooltip = "Lock selection - prevents accidental edits" more = "More actions" +noBoldItalic = "No bold italic version of this font" order = "Order" outlineColour = "Outline colour" outlineWidth = "Outline width (0 = none)" diff --git a/frontend/src/editor/core/icons/icons.ts b/frontend/src/editor/core/icons/icons.ts index 84e0f2f3933..b977c4b8adc 100644 --- a/frontend/src/editor/core/icons/icons.ts +++ b/frontend/src/editor/core/icons/icons.ts @@ -24,6 +24,7 @@ import BadgeDollarSign from "lucide-static/icons/badge-dollar-sign.svg?react"; import Banknote from "lucide-static/icons/banknote.svg?react"; import Bell from "lucide-static/icons/bell.svg?react"; import Blocks from "lucide-static/icons/blocks.svg?react"; +import Bold from "lucide-static/icons/bold.svg?react"; import Bolt from "lucide-static/icons/bolt.svg?react"; import Book from "lucide-static/icons/book.svg?react"; import BookOpen from "lucide-static/icons/book-open.svg?react"; @@ -458,6 +459,7 @@ export const ICONS = { banknote: { Component: Banknote, kind: "lucide" }, bell: { Component: Bell, kind: "lucide" }, blocks: { Component: Blocks, kind: "lucide" }, + bold: { Component: Bold, kind: "lucide" }, bolt: { Component: Bolt, kind: "lucide" }, book: { Component: Book, kind: "lucide" }, "book-open": { Component: BookOpen, kind: "lucide" }, diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-toggle.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-toggle.spec.ts new file mode 100644 index 00000000000..f07b13287c4 --- /dev/null +++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-toggle.spec.ts @@ -0,0 +1,387 @@ +import { test, expect } from "@editor/tests/helpers/stub-test-base"; +import type { Page } from "@playwright/test"; +import { readFileSync } from "fs"; +import path from "path"; +import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor"; + +// The font list names each family once; the Bold and Italic toggles move text +// between the faces that family really has, and never make one up. + +const TAGGED_PDF = path.join( + import.meta.dirname, + "../test-fixtures/tagged-sample.pdf", +); +const COLOURED_PDF = path.join( + import.meta.dirname, + "../test-fixtures/coloured-word-sample.pdf", +); + +const FONTS = path.join( + import.meta.dirname, + "../../../../../../app/core/src/main/resources/static/fonts", +); + +/** A server family with a light and a semibold face, so the weight menu shows. */ +const SERVER_FAMILY = { + family: "Demo Sans", + faces: [ + ["Light", 300, false, "LiberationSans-Regular.ttf"], + ["Regular", 400, false, "LiberationSans-Regular.ttf"], + ["Semibold", 600, true, "LiberationSans-Bold.ttf"], + ["Bold", 700, true, "LiberationSans-Bold.ttf"], + ] as const, +}; + +async function serveFonts(page: Page) { + const id = (i: number) => String(i + 1).repeat(64); + await page.route("**/api/v1/ui-data/editor-fonts**", (route) => { + const face = /editor-fonts\/([0-9a-f]{64})/.exec(route.request().url()); + if (!face) + return route.fulfill({ + json: { + families: [ + { + family: SERVER_FAMILY.family, + faces: SERVER_FAMILY.faces.map(([style, weight, bold], i) => ({ + id: id(i), + style, + weight, + bold, + italic: false, + postscriptName: `DemoSans-${style}`, + })), + }, + ], + }, + }); + const index = SERVER_FAMILY.faces.findIndex((_, i) => id(i) === face[1]); + return route.fulfill({ + body: readFileSync(path.join(FONTS, SERVER_FAMILY.faces[index][3])), + contentType: "font/ttf", + }); + }); +} + +const FORMAT_CONTROLS = [ + "pdf-editor-font-family", + "pdf-editor-font-weight", + "pdf-editor-font-size", + "pdf-editor-colour", + "pdf-editor-bold", + "pdf-editor-italic", + "pdf-editor-change-case", +]; + +/** The formatting controls a user cannot see: past the toolbar's edge, or missing from the formatting menu. */ +async function unreachableControls(page: Page): Promise { + const menu = page.getByTestId("pdf-editor-format-menu"); + if ((await menu.count()) > 0) { + const family = page.getByTestId("pdf-editor-font-family"); + if (!(await family.isVisible())) await menu.click(); + await family.waitFor({ state: "visible" }); + const missing: string[] = []; + for (const id of FORMAT_CONTROLS) + if (!(await page.getByTestId(id).isVisible())) missing.push(id); + return missing; + } + return page.evaluate((ids) => { + const band = document + .querySelector(".pdf-editor-topbar__band")! + .getBoundingClientRect(); + return ids.filter((id) => { + const control = document.querySelector(`[data-testid="${id}"]`); + if (!control) return true; + const box = control.getBoundingClientRect(); + return box.left < band.left - 0.5 || box.right > band.right + 0.5; + }); + }, FORMAT_CONTROLS); +} + +async function openEditor(page: Page, file: string) { + await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("pdf-editor-root")).toBeVisible({ + timeout: 30_000, + }); + await openInTextEditor(page, file); + await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ + timeout: 60_000, + }); + await expect.poll(() => runs(page), { timeout: 30_000 }).not.toHaveLength(0); +} + +function runs( + page: Page, +): Promise> { + return page.evaluate(() => { + const w = window as unknown as { + __editor_store?: { + state: { + pages: { runs: { id: string; text: string; fontId: string }[] }[]; + }; + }; + }; + return (w.__editor_store?.state.pages[0]?.runs ?? []).map((r) => ({ + id: r.id, + text: r.text, + fontId: r.fontId, + })); + }); +} + +async function runId(page: Page, text: string): Promise { + const run = (await runs(page)).find((r) => r.text.startsWith(text)); + expect(run, `no run starting "${text}"`).toBeTruthy(); + return run!.id; +} + +async function fontIdOf(page: Page, id: string): Promise { + return (await runs(page)).find((r) => r.id === id)?.fontId; +} + +function runBox(page: Page, id: string) { + return page.getByTestId(`pdf-editor-run-${id}`); +} + +/** Put the run in the served family, whose extra weights bring up the weight menu. */ +async function pickServerFamily(page: Page, id: string) { + await runBox(page, id).click(); + await page.getByTestId("pdf-editor-font-family").click(); + await page + .getByRole("option", { name: SERVER_FAMILY.family, exact: true }) + .click(); + await expect.poll(() => fontIdOf(page, id)).toMatch(/Demo Sans/); +} + +test.describe("PDF text editor - Bold toggle", () => { + test("the font list names each family once and Bold picks the bold face", async ({ + page, + }) => { + await openEditor(page, TAGGED_PDF); + const body = await runId(page, "Revenue grew"); + await runBox(page, body).click(); + + const bold = page.getByTestId("pdf-editor-bold"); + await expect(bold).toBeEnabled(); + await expect(bold).toHaveAttribute("aria-pressed", "false"); + await expect( + page + .getByTestId("pdf-editor-italic") + .locator("xpath=preceding-sibling::*[1]"), + ).toHaveAttribute("data-testid", "pdf-editor-bold"); + + await page.getByTestId("pdf-editor-font-family").click(); + await expect( + page.getByRole("option", { name: "Helvetica", exact: true }), + ).toBeVisible(); + await expect( + page.getByRole("option", { name: /bold|oblique|italic/i }), + ).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect( + page.getByRole("option", { name: "Helvetica", exact: true }), + ).toBeHidden(); + + await bold.click(); + await expect.poll(() => fontIdOf(page, body)).toMatch(/Helvetica-Bold$/); + await expect(bold).toHaveAttribute("aria-pressed", "true"); + expect((await runs(page)).find((r) => r.id === body)?.text).toMatch( + /^Revenue grew in every region/, + ); + + await bold.click(); + await expect.poll(() => fontIdOf(page, body)).not.toMatch(/Bold/); + await expect(bold).toHaveAttribute("aria-pressed", "false"); + + await page.getByTestId("pdf-editor-undo").click(); + await expect.poll(() => fontIdOf(page, body)).toMatch(/Helvetica-Bold$/); + await page.getByTestId("pdf-editor-redo").click(); + await expect.poll(() => fontIdOf(page, body)).not.toMatch(/Bold/); + }); + + test("a half-bold selection shows mixed and goes all bold", async ({ + page, + }) => { + await openEditor(page, TAGGED_PDF); + const heading = await runId(page, "Quarterly report"); + const body = await runId(page, "Revenue grew"); + + const headingFont = await fontIdOf(page, heading); + + await runBox(page, body).click(); + await runBox(page, heading).click({ modifiers: ["Shift"] }); + + const bold = page.getByTestId("pdf-editor-bold"); + await expect(bold).toHaveAttribute("aria-pressed", "mixed"); + await bold.click(); + + await expect.poll(() => fontIdOf(page, body)).toMatch(/Helvetica-Bold$/); + await expect(bold).toHaveAttribute("aria-pressed", "true"); + expect(await fontIdOf(page, heading), "already bold, left as it was").toBe( + headingFont, + ); + }); + + test("Bold is off with a reason for a font that has no bold face", async ({ + page, + }) => { + await openEditor(page, COLOURED_PDF); + await runBox(page, await runId(page, "הטלפון")).click(); + + const bold = page.getByTestId("pdf-editor-bold"); + await expect(bold).toBeDisabled(); + await bold.hover(); + await expect(page.getByRole("tooltip")).toContainText( + "No bold version of this font", + ); + }); + + test("Bold onto a subset that lacks some letters draws them in the closest match and says so", async ({ + page, + }) => { + await openEditor(page, COLOURED_PDF); + const line = await runId(page, "Total due today"); + const before = await fontIdOf(page, line); + await runBox(page, line).click(); + + await page.getByTestId("pdf-editor-bold").click(); + + await expect( + page.getByText(/drawn in the closest matching font/), + ).toBeVisible(); + await expect.poll(() => fontIdOf(page, line)).not.toBe(before); + expect((await runs(page)).find((r) => r.id === line)?.text).toBe( + "Total due today by card", + ); + await expect(page.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "true", + ); + }); +}); + +test.describe("PDF text editor - formatting controls stay reachable", () => { + for (const width of [1280, 1440, 1600, 1920]) { + test(`every control, the weight menu included, is reachable at ${width}px`, async ({ + page, + }) => { + await serveFonts(page); + await page.setViewportSize({ width: 1920, height: 1000 }); + await openEditor(page, TAGGED_PDF); + await pickServerFamily(page, await runId(page, "Revenue grew")); + + await page.setViewportSize({ width, height: 1000 }); + + await expect.poll(() => unreachableControls(page)).toEqual([]); + }); + } +}); + +function fillOf(page: Page, id: string): Promise { + return page.evaluate((rid) => { + const w = window as unknown as { + __editor_store: { + state: { + pages: { + runs: { id: string; fill: { r: number; g: number; b: number } }[]; + }[]; + }; + }; + }; + const fill = w.__editor_store.state.pages[0].runs.find( + (r) => r.id === rid, + )?.fill; + return fill ? `${fill.r},${fill.g},${fill.b}` : undefined; + }, id); +} + +/** Narrow the window until the formatting controls fit inline with `slack` pixels to spare. */ +async function fitInlineWithSlack(page: Page, slack: number) { + const spare = await page.evaluate(() => { + const band = document.querySelector(".pdf-editor-topbar__band")!; + const last = document.querySelector( + '[data-testid="pdf-editor-change-case"]', + )!; + return Math.floor( + band.getBoundingClientRect().right - last.getBoundingClientRect().right, + ); + }); + const size = page.viewportSize()!; + await page.setViewportSize({ + width: size.width - spare + slack, + height: size.height, + }); +} + +test.describe("PDF text editor - formatting popovers stay open", () => { + test("the colour picker stays open when opening it widens the field past the toolbar's edge", async ({ + page, + }) => { + await page.setViewportSize({ width: 2200, height: 1000 }); + await openEditor(page, TAGGED_PDF); + const body = await runId(page, "Revenue grew"); + await runBox(page, body).click(); + await expect(page.getByTestId("pdf-editor-colour")).toBeVisible(); + // Narrower than the open colour field needs, wider than the closed one. + await fitInlineWithSlack(page, 12); + await expect(page.getByTestId("pdf-editor-format-menu")).toHaveCount(0); + await expect(page.getByTestId("pdf-editor-change-case")).toBeInViewport({ + ratio: 1, + }); + const before = await fillOf(page, body); + + await page.getByTestId("pdf-editor-colour").click(); + const saturation = page.locator(".mantine-ColorInput-saturation").first(); + await expect(saturation).toBeVisible(); + const box = (await saturation.boundingBox())!; + await saturation.click({ position: { x: box.width - 4, y: 4 } }); + + await expect.poll(() => fillOf(page, body)).not.toBe(before); + }); + + for (const width of [1920, 1280]) { + test(`the change-case menu, outline colour and weight menu open at ${width}px`, async ({ + page, + }) => { + await serveFonts(page); + await page.setViewportSize({ width: 2400, height: 1000 }); + await openEditor(page, TAGGED_PDF); + const body = await runId(page, "Revenue grew"); + await pickServerFamily(page, body); + await page.setViewportSize({ width, height: 1000 }); + const menu = page.getByTestId("pdf-editor-format-menu"); + await expect( + page.getByTestId("pdf-editor-font-weight").or(menu), + ).toBeVisible(); + const bold = page.getByTestId("pdf-editor-bold"); + // Folded, the controls show once the formatting menu has opened. + const openFormatting = () => + expect(async () => { + if ((await menu.count()) > 0 && !(await bold.isVisible())) + await menu.click(); + await expect(bold).toBeVisible({ timeout: 2_000 }); + }).toPass(); + + await openFormatting(); + await page.getByTestId("pdf-editor-font-weight").click(); + await expect( + page.getByRole("option", { name: /Semibold/ }), + ).toBeVisible(); + await page.getByRole("option", { name: /Semibold/ }).click(); + await expect.poll(() => fontIdOf(page, body)).toMatch(/Semibold/); + + await openFormatting(); + await page.getByTestId("pdf-editor-change-case").click(); + await expect( + page.getByTestId("pdf-editor-change-case-upper"), + ).toBeVisible(); + await page.getByTestId("pdf-editor-change-case-upper").click(); + await expect + .poll(async () => (await runs(page)).find((r) => r.id === body)?.text) + .toMatch(/^REVENUE GREW/); + + await openFormatting(); + await page.getByTestId("pdf-editor-colour-advanced").click(); + await expect(page.getByTestId("pdf-editor-outline-width")).toBeVisible(); + }); + } +}); diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-words.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-words.spec.ts new file mode 100644 index 00000000000..139eb5eed9d --- /dev/null +++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-words.spec.ts @@ -0,0 +1,234 @@ +import { test, expect } from "@editor/tests/helpers/stub-test-base"; +import type { Page } from "@playwright/test"; +import path from "path"; +import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor"; +import { + downloadBytes, + reopenSavedBytes, + saveAndDownload, +} from "@editor/tests/stubbed/saveHelpers"; + +// Bold on words selected inside a text box makes those words bold on the page, +// and only them, the way a word processor does. + +const TAGGED_PDF = path.join( + import.meta.dirname, + "../test-fixtures/tagged-sample.pdf", +); +const BODY = "Revenue grew in every region this quarter,"; + +interface Rect { + x: number; + y: number; + width: number; + height: number; +} + +interface EditorWindow { + __editor_store?: { + state: { pages: { runs: { id: string; text: string }[] }[] }; + selection: { value: { textRange: { start: number; end: number } | null } }; + }; +} + +async function openEditor(page: Page, file: string) { + await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" }); + await expect(page.getByTestId("pdf-editor-root")).toBeVisible({ + timeout: 30_000, + }); + await openInTextEditor(page, file); + await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ + timeout: 60_000, + }); + await expect.poll(() => bodyRun(page), { timeout: 30_000 }).toBeTruthy(); +} + +function bodyRun(page: Page): Promise<{ id: string; text: string } | null> { + return page.evaluate((body) => { + const w = window as unknown as EditorWindow; + return ( + w.__editor_store?.state.pages[0]?.runs.find((r) => + r.text.startsWith(body), + ) ?? null + ); + }, BODY); +} + +/** Where `word` sits in the run's box, read from the box's own text. */ +function wordRect(page: Page, runId: string, word: string): Promise { + return page.evaluate( + ({ runId, word }) => { + const el = document.querySelector( + `[data-testid="pdf-editor-run-${runId}"]`, + )!; + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + const nodes: Text[] = []; + let text = ""; + while (walker.nextNode()) { + nodes.push(walker.currentNode as Text); + text += (walker.currentNode as Text).data; + } + const locate = (at: number): [Text, number] => { + for (const node of nodes) { + if (at <= node.data.length) return [node, at]; + at -= node.data.length; + } + const last = nodes[nodes.length - 1]; + return [last, last.data.length]; + }; + const start = text.indexOf(word); + const range = document.createRange(); + range.setStart(...locate(start)); + range.setEnd(...locate(start + word.length)); + // A range starting at a line break also covers the end of the line before it. + const rects = range.getClientRects(); + const r = rects[rects.length - 1] ?? range.getBoundingClientRect(); + return { x: r.x, y: r.y, width: r.width, height: r.height }; + }, + { runId, word }, + ); +} + +/** How much ink the page bitmap has under each rect. */ +function inkUnder(page: Page, rects: Rect[]): Promise { + return page.evaluate((rects) => { + const canvas = Array.from( + document.querySelectorAll( + '[data-testid="pdf-editor-page-0"] canvas', + ), + ).find((c) => c.width > 0 && c.height > 0)!; + const box = canvas.getBoundingClientRect(); + const sx = canvas.width / box.width; + const sy = canvas.height / box.height; + const ctx = canvas.getContext("2d", { willReadFrequently: true })!; + return rects.map((r) => { + const data = ctx.getImageData( + Math.round((r.x - box.x) * sx), + Math.round((r.y - box.y) * sy), + Math.max(1, Math.round(r.width * sx)), + Math.max(1, Math.round(r.height * sy)), + ).data; + let ink = 0; + for (let i = 0; i < data.length; i += 4) + ink += 255 - (data[i] + data[i + 1] + data[i + 2]) / 3; + return ink / 255; + }); + }, rects); +} + +/** The ink under each rect once the bitmap has stopped changing. */ +async function settledInk(page: Page, rects: Rect[]): Promise { + let last = ""; + let ink: number[] = []; + await expect + .poll( + async () => { + ink = await inkUnder(page, rects); + const key = ink.map((v) => v.toFixed(1)).join(); + const same = key === last; + last = key; + return same; + }, + { timeout: 20_000, intervals: [300] }, + ) + .toBe(true); + return ink; +} + +function textRange(page: Page) { + return page.evaluate( + () => + (window as unknown as EditorWindow).__editor_store?.selection.value + .textRange ?? null, + ); +} + +async function wordRects(page: Page, runId: string, words: string[]) { + const rects: Rect[] = []; + for (const word of words) rects.push(await wordRect(page, runId, word)); + return rects; +} + +const WORDS = ["Revenue grew in", "every", "region", "led by demand"]; + +test.describe("PDF text editor - Bold on selected words", () => { + test("Bold on a double-clicked word and on a word picked out with Shift+arrows makes only those words heavier, and a save keeps them", async ({ + page, + }) => { + test.setTimeout(120_000); + await openEditor(page, TAGGED_PDF); + const { id } = (await bodyRun(page))!; + const rects = await wordRects(page, id, WORDS); + const before = await settledInk(page, rects); + const box = page.getByTestId(`pdf-editor-run-${id}`); + + await box.click({ position: { x: 4, y: 4 } }); + const every = rects[1]; + await page.mouse.dblclick( + every.x + every.width / 2, + every.y + every.height / 2, + ); + const start = BODY.indexOf("every"); + await expect + .poll(() => textRange(page)) + .toMatchObject({ start, end: expect.any(Number) }); + await expect(page.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "false", + ); + await page.keyboard.press("ControlOrMeta+b"); + + await expect + .poll(async () => (await inkUnder(page, [every]))[0], { + timeout: 20_000, + }) + .toBeGreaterThan(before[1] * 1.2); + const bolded = await settledInk(page, rects); + expect(bolded[0] / before[0]).toBeCloseTo(1, 1); + expect(bolded[3] / before[3]).toBeCloseTo(1, 1); + expect((await bodyRun(page))!.text.startsWith(BODY)).toBe(true); + + const region = await wordRect(page, id, "region"); + await page.mouse.dblclick( + region.x + region.width / 2, + region.y + region.height / 2, + ); + await page.keyboard.press("ArrowLeft"); + for (let i = 0; i < "region".length; i++) + await page.keyboard.press("Shift+ArrowRight"); + const regionAt = BODY.indexOf("region"); + await expect + .poll(() => textRange(page)) + .toEqual({ start: regionAt, end: regionAt + "region".length }); + await page.keyboard.press("ControlOrMeta+b"); + + await expect + .poll(async () => (await inkUnder(page, [region]))[0], { + timeout: 20_000, + }) + .toBeGreaterThan(before[2] * 1.2); + const bothBold = await settledInk(page, rects); + await expect(page.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "true", + ); + expect(bothBold[0] / before[0]).toBeCloseTo(1, 1); + expect(bothBold[3] / before[3]).toBeCloseTo(1, 1); + + const saved = await downloadBytes(await saveAndDownload(page, false)); + expect(saved.toString("latin1")).toContain("/Helvetica-Bold"); + await reopenSavedBytes(page, saved, "saved.pdf", 0, 60_000); + const reopened = (await bodyRun(page))!; + expect(reopened.text.startsWith(BODY)).toBe(true); + const reopenedRects = await wordRects(page, reopened.id, WORDS); + await expect + .poll(async () => (await inkUnder(page, reopenedRects))[1], { + timeout: 20_000, + }) + .toBeGreaterThan(before[1] * 1.2); + const after = await settledInk(page, reopenedRects); + expect(after[2]).toBeGreaterThan(before[2] * 1.2); + expect(after[0] / before[0]).toBeCloseTo(1, 1); + expect(after[3] / before[3]).toBeCloseTo(1, 1); + }); +}); diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts index 08e164fd23d..da73446ed30 100644 --- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts +++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts @@ -112,13 +112,13 @@ test.describe("PDF text editor - a restyle of many runs is one undo step", () => const picker = page.getByTestId("pdf-editor-font-family"); await picker.click(); - await page.getByRole("option", { name: "Helvetica", exact: true }).click(); + await page.getByRole("option", { name: "Times", exact: true }).click(); await page.waitForTimeout(2500); // Sanity: the change has to have landed, or the undo assertion is vacuous. const changed = await runsInModel(page); expect( - changed.filter((r) => /helvetica/i.test(r.fontId)).length, + changed.filter((r) => /times/i.test(r.fontId)).length, "the font change did not apply", ).toBeGreaterThan(1); diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts index 12fa95dcd5b..61f954c4866 100644 --- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts +++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts @@ -2,15 +2,10 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base"; import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor"; import path from "path"; -// Two toolbar changes: -// -// * The bold button was a second, weaker way to say what the font family -// picker already says, and it applied to whole runs rather than to the -// text the user had selected. The weight control is gone; Helvetica Bold -// and friends are still one dropdown pick away. -// * Fill colour and outline colour sat side by side, so the common case -// (change the text colour) had two pickers to choose between. Outline -// colour and width now live behind an advanced control. +// Fill colour and outline colour sat side by side, so the common case (change +// the text colour) had two pickers to choose between. Outline colour and width +// live behind an advanced control. The font list names a family once, so bold +// is the Bold toggle's, beside Italic. const PARAGRAPH_PDF = path.join( import.meta.dirname, @@ -55,33 +50,26 @@ function readRun(page: import("@playwright/test").Page, runId: string) { }, runId); } -test.describe("PDF text editor - the weight control is gone", () => { - test("the toolbar has no bold button", async ({ page }) => { +test.describe("PDF text editor - bold is a toggle, not a list entry", () => { + test("the toolbar has Bold beside Italic", async ({ page }) => { await openEditor(page, PARAGRAPH_PDF); await selectFirstRun(page); await expect(page.getByTestId("pdf-editor-toolbar")).toBeVisible(); - await expect( - page.getByTestId("pdf-editor-bold"), - "the bold weight control should have been dropped", - ).toHaveCount(0); - // Italic is a style, not a weight, and stays. + await expect(page.getByTestId("pdf-editor-bold")).toBeVisible(); await expect(page.getByTestId("pdf-editor-italic")).toBeVisible(); }); - test("bold is still reachable through the font family picker", async ({ - page, - }) => { + test("Bold makes the selected run bold", async ({ page }) => { await openEditor(page, PARAGRAPH_PDF); const runId = await selectFirstRun(page); const before = await readRun(page, runId); expect(before, "run should be in the model").not.toBeNull(); - await page.getByTestId("pdf-editor-font-family").click(); - await page.getByRole("option", { name: "Helvetica Bold" }).click(); - await page.waitForTimeout(600); + await page.getByTestId("pdf-editor-bold").click(); - const after = await readRun(page, runId); - expect(after!.fontId).toMatch(/Helvetica-Bold/); + await expect + .poll(async () => (await readRun(page, runId))?.fontId) + .toMatch(/Helvetica-Bold/); }); }); diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts index b175caf3a75..0a29a29c2e5 100644 --- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts +++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts @@ -637,7 +637,7 @@ test.describe("PDF text editor - font family, measured on the rendered page", () // Would catch: a weight change that only relabels the font in the store. The // glyph box barely moves between Helvetica and Helvetica Bold, so the only // honest evidence is how much darker the stems are - the ink area. - test("Helvetica Bold thickens the glyph ink without moving its box", async ({ + test("the Bold toggle thickens Helvetica's glyph ink without moving its box", async ({ page, }) => { test.setTimeout(120_000); @@ -648,7 +648,7 @@ test.describe("PDF text editor - font family, measured on the rendered page", () const regular = await settledInk(page); expect(regular.n, "regular render must be inked").toBeGreaterThan(100); - await setFamily(page, "Helvetica Bold"); + await page.getByTestId("pdf-editor-bold").click(); const bold = await settledInk(page, { differentFrom: regular }); expect( diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts index 5ddc0d923c7..8d0b75dc7b1 100644 --- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts +++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts @@ -1,4 +1,5 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base"; +import type { Page } from "@playwright/test"; import { openInTextEditor, scrollToEditorPage, @@ -49,7 +50,7 @@ const BIG_SAMPLE_PDF = path.join( // PDF text editor regression suite. It runs entirely in the browser via // PDFium WASM, so these tests do not need a real backend. -async function gotoEditor(page: import("@playwright/test").Page) { +async function gotoEditor(page: Page) { await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded", }); @@ -59,15 +60,30 @@ async function gotoEditor(page: import("@playwright/test").Page) { } /** Change the selected run's font family through the real toolbar dropdown. */ -async function selectFontFamily( - page: import("@playwright/test").Page, - optionLabel: string, -) { +async function selectFontFamily(page: Page, optionLabel: string) { await page.getByTestId("pdf-editor-font-family").click(); await page.getByRole("option", { name: optionLabel, exact: true }).click(); } -async function loadSamplePdf(page: import("@playwright/test").Page) { +/** Turn the selected text's bold face on or off through the Bold toggle, and wait until it is. */ +async function setBold(page: Page, on: boolean) { + const bold = page.getByTestId("pdf-editor-bold"); + await expect(bold).toBeEnabled(); + if ((await bold.getAttribute("aria-pressed")) !== String(on)) + await bold.click(); + await expect(bold).toHaveAttribute("aria-pressed", String(on)); +} + +/** Put the selected text in Helvetica Bold: the family from the list, then the Bold toggle. */ +async function selectHelveticaBold(page: Page) { + await selectFontFamily(page, "Helvetica"); + await expect(page.getByTestId("pdf-editor-font-family")).toHaveValue( + "Helvetica", + ); + await setBold(page, true); +} + +async function loadSamplePdf(page: Page) { // The visible "Open" flow goes through the left-sidebar Files panel. await openInTextEditor(page, SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -75,7 +91,7 @@ async function loadSamplePdf(page: import("@playwright/test").Page) { }); } -async function loadMultiPageSample(page: import("@playwright/test").Page) { +async function loadMultiPageSample(page: Page) { await openInTextEditor(page, MULTI_PAGE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ timeout: 30_000, @@ -84,7 +100,7 @@ async function loadMultiPageSample(page: import("@playwright/test").Page) { /** Type a string into a contenteditable using `execCommand('insertText')`. */ async function typeIntoRun( - page: import("@playwright/test").Page, + page: Page, runTestId: string, text: string, position: "end" | "start" = "end", @@ -385,9 +401,7 @@ test.describe("PDF text editor - whitespace preservation", () => { // These guard against a recurring class of regression where typed spaces // vanish from the saved PDF. - async function readFirstRunText( - page: import("@playwright/test").Page, - ): Promise { + async function readFirstRunText(page: Page): Promise { return await page.evaluate(() => { const store = ( window as unknown as { @@ -400,9 +414,7 @@ test.describe("PDF text editor - whitespace preservation", () => { }); } - async function saveAndReopen( - page: import("@playwright/test").Page, - ): Promise { + async function saveAndReopen(page: Page): Promise { const downloadPromise = page.waitForEvent("download"); await page.getByTestId("pdf-editor-download").click(); const download = await downloadPromise; @@ -1016,7 +1028,7 @@ test.describe("PDF text editor - whitespace preservation", () => { // Sequential-edit visual-integrity tests. - async function findTaglineRun(page: import("@playwright/test").Page) { + async function findTaglineRun(page: Page) { return await page.evaluate(() => { const store = ( window as unknown as { @@ -1054,7 +1066,7 @@ test.describe("PDF text editor - whitespace preservation", () => { }); } - async function readRun(page: import("@playwright/test").Page, id: string) { + async function readRun(page: Page, id: string) { return await page.evaluate((tid) => { const store = ( window as unknown as { @@ -1086,11 +1098,7 @@ test.describe("PDF text editor - whitespace preservation", () => { }, id); } - async function caretAt( - page: import("@playwright/test").Page, - tid: string, - pos: number, - ) { + async function caretAt(page: Page, tid: string, pos: number) { await page.evaluate( ({ tid, pos }) => { const el = document.querySelector( @@ -1128,7 +1136,7 @@ test.describe("PDF text editor - whitespace preservation", () => { } async function execAt( - page: import("@playwright/test").Page, + page: Page, tid: string, pos: number, cmd: "insertText" | "delete", @@ -1750,7 +1758,7 @@ test.describe("PDF text editor - whitespace preservation", () => { } async function snapshotIntegrity( - page: import("@playwright/test").Page, + page: Page, runId: string, baselineY: number, expectedText: string, @@ -2821,9 +2829,8 @@ test.describe("PDF text editor - bold/italic", () => { const before = await readState(runId); expect(before.undoDepth).toBeGreaterThan(0); - // Now pick the bold variant. It should dispatch another edit (undo stack - // grows). The dedicated weight button is gone; the picker is the way in. - await selectFontFamily(page, "Helvetica Bold"); + // Now the bold face. It should dispatch another edit (undo stack grows). + await setBold(page, true); // The toolbar's active state flips on local component state, which can beat // the command onto the screen - so wait for the history itself to grow. @@ -2915,10 +2922,8 @@ test.describe("PDF text editor - bold/italic", () => { // Bold then un-bold (the user's exact sequence). Each pick dispatches a // SetFontFamily command. - await selectFontFamily(page, "Helvetica Bold"); - await page.waitForTimeout(300); - await selectFontFamily(page, "Helvetica"); - await page.waitForTimeout(300); + await selectHelveticaBold(page); + await setBold(page, false); const after = await page.evaluate((id) => { const store = ( @@ -2963,27 +2968,26 @@ test.describe("PDF text editor - bold/italic", () => { const savedBytes = await downloadBytes(dl); await reopenSavedBytes(page, savedBytes, "round-trip.pdf"); - const reopenedRuns = await page.evaluate(() => { - const store = ( - window as unknown as { - __editor_store: { - doc: { page: (i: number) => { runs: Array<{ text: string }> } }; - }; - } - ).__editor_store; - return store.doc.page(0).runs.map((r) => r.text); - }); + const reopenedRuns = () => + page.evaluate(() => { + const store = ( + window as unknown as { + __editor_store: { + doc: { page: (i: number) => { runs: Array<{ text: string }> } }; + }; + } + ).__editor_store; + return store.doc.page(0).runs.map((r) => r.text); + }); // The CORE assertion: each distinctive tagline word appears in EXACTLY ONE - // run. - const countCarrying = (word: string) => - reopenedRuns.filter((t) => t.includes(word)).length; + // run. Polled, because the run list fills in as the reopened file loads. for (const word of ["Adobe", "Acrobat", "Alternative"]) { - expect( - countCarrying(word), - `Runs carrying "${word}": ${JSON.stringify( - reopenedRuns.filter((t) => t.includes(word)), - )}`, - ).toBe(1); + await expect + .poll( + async () => (await reopenedRuns()).filter((t) => t.includes(word)), + { message: `runs carrying "${word}"`, timeout: 15_000 }, + ) + .toHaveLength(1); } }); }); @@ -3915,11 +3919,7 @@ test.describe("PDF text editor - Ctrl+A select all", () => { test.describe("PDF text editor - stress: whitespace insertion variations", () => { /** Caret at char index `pos` inside `runTestId`. */ - async function placeCaret( - page: import("@playwright/test").Page, - runTestId: string, - pos: number, - ) { + async function placeCaret(page: Page, runTestId: string, pos: number) { await page.evaluate( ({ tid, pos }) => { const el = document.querySelector( @@ -3957,7 +3957,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () => } async function insertAt( - page: import("@playwright/test").Page, + page: Page, runTestId: string, pos: number, text: string, @@ -3969,7 +3969,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () => await page.waitForTimeout(250); } - async function readTagline(page: import("@playwright/test").Page) { + async function readTagline(page: Page) { return await page.evaluate(() => { const store = ( window as unknown as { @@ -4001,7 +4001,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () => }); } - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -4126,7 +4126,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () => }); test.describe("PDF text editor - stress: bold / font swap variations", () => { - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -4135,7 +4135,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { await page.waitForTimeout(500); } - async function selectTagline(page: import("@playwright/test").Page) { + async function selectTagline(page: Page) { // The page-0 runs are read lazily on first intersection; wait for them // to populate so the test actually runs instead of skipping on a race. await page @@ -4176,7 +4176,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { return id; } - async function readRun(page: import("@playwright/test").Page, id: string) { + async function readRun(page: Page, id: string) { return await page.evaluate((rid) => { const store = ( window as unknown as { @@ -4210,10 +4210,10 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { test.skip(true, "fixture missing tagline"); return; } - for (const family of ["Helvetica Bold", "Helvetica", "Helvetica Bold"]) { + await selectHelveticaBold(page); + for (const on of [false, true]) { await selectTagline(page); - await selectFontFamily(page, family); - await page.waitForTimeout(250); + await setBold(page, on); } const after = await readRun(page, id); if (!after) throw new Error("run vanished after 3 bold toggles"); @@ -4234,8 +4234,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { if (!before) throw new Error("baseline read failed"); // Re-select before each toolbar click. await selectTagline(page); - await selectFontFamily(page, "Helvetica Bold"); - await page.waitForTimeout(250); + await selectHelveticaBold(page); await selectTagline(page); await page.getByTestId("pdf-editor-italic").click(); await page.waitForTimeout(250); @@ -4264,13 +4263,16 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { const before = await readRun(page, id); if (!before) throw new Error("baseline read failed"); expect(before.merged).toBeGreaterThan(10); - await selectFontFamily(page, "Helvetica Bold"); - await page.waitForTimeout(250); + await selectHelveticaBold(page); const mid = await readRun(page, id); if (!mid) throw new Error("mid read failed"); expect(mid.merged).toBe(0); - await page.getByTestId("pdf-editor-undo").click(); - await page.waitForTimeout(400); + // The family pick and the Bold toggle are one undo step each. + for (let step = 0; step < 2; step++) + await page.getByTestId("pdf-editor-undo").click(); + await expect + .poll(async () => (await readRun(page, id))?.fontId) + .toBe(before.fontId); const after = await readRun(page, id); if (!after) throw new Error("post-undo read failed"); expect(after.fontId).toBe(before.fontId); @@ -4288,8 +4290,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { test.skip(true, "fixture missing tagline"); return; } - await selectFontFamily(page, "Helvetica Bold"); - await page.waitForTimeout(250); + await selectHelveticaBold(page); // Now insert text into the bolded run. await page.evaluate((tid) => { const el = document.querySelector( @@ -4349,7 +4350,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { } // Change font family through the real toolbar dropdown (the tagline run // is already selected). The Select's onChange dispatches SetFontFamily. - await selectFontFamily(page, "Times Roman"); + await selectFontFamily(page, "Times"); await page.waitForTimeout(300); const mid = await readRun(page, id); if (!mid) throw new Error("mid read failed"); @@ -4366,7 +4367,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => { }); test.describe("PDF text editor - stress: add / remove cycles (no leaks)", () => { - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -4605,7 +4606,7 @@ test.describe("PDF text editor - stress: add / remove cycles (no leaks)", () => }); test.describe("PDF text editor - stress: save+reopen multi-cycle", () => { - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -4614,7 +4615,7 @@ test.describe("PDF text editor - stress: save+reopen multi-cycle", () => { await page.waitForTimeout(500); } - async function saveAndReopenLocal(page: import("@playwright/test").Page) { + async function saveAndReopenLocal(page: Page) { const downloadPromise = page.waitForEvent("download"); await page.getByTestId("pdf-editor-download").click(); const dl = await downloadPromise; @@ -4789,7 +4790,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => { // The AddText flow has its own input path (singleton run, base-14 Helvetica // from the start, no LineGrouper). - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -4799,7 +4800,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => { } async function addNewTextBox( - page: import("@playwright/test").Page, + page: Page, position: { x: number; y: number } = { x: 200, y: 600 }, ): Promise { await page.getByTestId("pdf-editor-add-text").click(); @@ -4819,11 +4820,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => { return newId; } - async function clearAndType( - page: import("@playwright/test").Page, - runId: string, - text: string, - ) { + async function clearAndType(page: Page, runId: string, text: string) { await page.evaluate( ({ rid, t }) => { const el = document.querySelector( @@ -4845,11 +4842,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => { await page.waitForTimeout(300); } - async function typeCharByChar( - page: import("@playwright/test").Page, - runId: string, - sequence: string, - ) { + async function typeCharByChar(page: Page, runId: string, sequence: string) { // First clear the placeholder. await page.evaluate((rid) => { const el = document.querySelector( @@ -4890,7 +4883,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => { } } - async function readRun(page: import("@playwright/test").Page, id: string) { + async function readRun(page: Page, id: string) { return await page.evaluate((rid) => { const store = ( window as unknown as { @@ -4926,7 +4919,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => { }, id); } - async function saveAndReopenLocal(page: import("@playwright/test").Page) { + async function saveAndReopenLocal(page: Page) { const downloadPromise = page.waitForEvent("download"); await page.getByTestId("pdf-editor-download").click(); const dl = await downloadPromise; @@ -5167,7 +5160,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide // User-reported: "I can add spaces but after adding them I can't remove // them". - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -5177,7 +5170,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide } async function addNewTextBox( - page: import("@playwright/test").Page, + page: Page, position: { x: number; y: number } = { x: 200, y: 600 }, ): Promise { await page.getByTestId("pdf-editor-add-text").click(); @@ -5196,11 +5189,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide }); } - async function clearAndType( - page: import("@playwright/test").Page, - id: string, - text: string, - ) { + async function clearAndType(page: Page, id: string, text: string) { await page.evaluate( ({ rid, t }) => { const el = document.querySelector( @@ -5222,11 +5211,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide await page.waitForTimeout(300); } - async function backspace( - page: import("@playwright/test").Page, - id: string, - n: number, - ) { + async function backspace(page: Page, id: string, n: number) { for (let i = 0; i < n; i++) { await page.evaluate((rid) => { const el = document.querySelector( @@ -5247,7 +5232,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide } } - async function readRun(page: import("@playwright/test").Page, id: string) { + async function readRun(page: Page, id: string) { return await page.evaluate((rid) => { const store = ( window as unknown as { @@ -5449,7 +5434,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () => // User reported the textbox visually "doesn't have the same width as the // text". - async function loadFixture(page: import("@playwright/test").Page) { + async function loadFixture(page: Page) { await gotoEditor(page); await openInTextEditor(page, USER_SAMPLE_PDF); await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({ @@ -5459,7 +5444,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () => } async function overlayCssWidth( - page: import("@playwright/test").Page, + page: Page, runTestId: string, ): Promise { return await page.evaluate((tid) => { @@ -5469,10 +5454,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () => }, runTestId); } - async function cssTextWidth( - page: import("@playwright/test").Page, - runTestId: string, - ): Promise { + async function cssTextWidth(page: Page, runTestId: string): Promise { // Measure the text content's intrinsic CSS width via the same canvas // measureText the overlay component uses. return await page.evaluate((tid) => { diff --git a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx index d99e80a9da6..aeb9df1095f 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx @@ -33,6 +33,7 @@ import { useUnsavedChangesGuard } from "@editor/tools/pdfTextEditor/hooks/useUns import { useDeferredPanelView } from "@editor/tools/pdfTextEditor/hooks/useDeferredPanelView"; import { useEditorTestGlobal } from "@editor/tools/pdfTextEditor/hooks/useEditorTestGlobal"; import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions"; +import { useFontChangeWarning } from "@editor/tools/pdfTextEditor/components/fontPickFailure"; import { useEditorKeyboardShortcuts } from "@editor/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts"; import { useEditorClipboard } from "@editor/tools/pdfTextEditor/hooks/useEditorClipboard"; import { useOpenAtViewerText } from "@editor/tools/pdfTextEditor/hooks/useOpenAtViewerText"; @@ -173,6 +174,7 @@ export default function PdfTextEditor(_props: BaseToolProps) { useScanPrefit(store, state); const sel = useSelectionActions(store); + const warnAboutFontChange = useFontChangeWarning(); // Guards against re-entrant saves while a (synchronous) serialize runs. const savingRef = useRef(false); @@ -641,6 +643,14 @@ export default function PdfTextEditor(_props: BaseToolProps) { onFindNext: handleFindNext, onEscape: handleEscape, onMergeSelection: handleMergeSelection, + onToggleBold: useCallback( + () => void warnAboutFontChange(sel.toggleBold), + [warnAboutFontChange, sel.toggleBold], + ), + onToggleItalic: useCallback( + () => void warnAboutFontChange(sel.toggleItalic), + [warnAboutFontChange, sel.toggleItalic], + ), }); useEditorClipboard({ diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/boldToggle.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/boldToggle.test.ts new file mode 100644 index 00000000000..e7057587e29 --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/boldToggle.test.ts @@ -0,0 +1,139 @@ +import { act, renderHook } from "@testing-library/react"; +import { beforeAll, expect, test, vi } from "vitest"; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("@editor/services/apiClient", () => ({ default: { get } })); + +import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions"; +import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore"; +import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers"; +import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun"; +import { + editorStores, + savedBytes, + servePdfiumWasm, +} from "@editor/tools/pdfTextEditor/__tests__/editorStores"; + +const FPDF_PAGEOBJ_TEXT = 1; + +servePdfiumWasm(); +const { storeWith, fixture } = editorStores(); + +beforeAll(() => { + get.mockRejectedValue(new Error("no server fonts")); + // jsdom has no canvas; text measurement falls back without one. + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null); +}); + +function runOf(store: EditorStore, text: string): TextRun { + return store.document!.page(0).runs.find((r) => r.text === text)!; +} + +/** The /BaseFont each piece of a run is drawn in, with the text it draws, as "text@Font". */ +function pieces(store: EditorStore, text: string): string[] { + const doc = store.document!; + const m = doc.module; + const page = doc.page(0); + const buf = m.pdfium.wasmExports.malloc(2048); + const name = m.pdfium.wasmExports.malloc(256); + const textPage = m.FPDFText_LoadPage(page.pagePtr); + try { + return collectMemberPtrs(runOf(store, text)) + .filter((ptr) => ptr && m.FPDFPageObj_GetType(ptr) === FPDF_PAGEOBJ_TEXT) + .map((ptr) => { + m.FPDFTextObj_GetText(ptr, textPage, buf, 2048); + m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(ptr), name, 256); + const font = m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, ""); + return `${m.pdfium.UTF16ToString(buf)}@${font}`; + }); + } finally { + m.FPDFText_ClosePage(textPage); + m.pdfium.wasmExports.free(buf); + m.pdfium.wasmExports.free(name); + } +} + +function fonts(store: EditorStore, text: string): string[] { + return [...new Set(pieces(store, text).map((p) => p.split("@")[1]))].sort(); +} + +/** The run's text as its objects draw it, spaces aside. */ +function drawnText(store: EditorStore, text: string): string { + return pieces(store, text) + .map((p) => p.split("@")[0]) + .join("") + .replace(/\s+/g, ""); +} + +function select(store: EditorStore, text: string): void { + store.selection.selectOne(runOf(store, text).id); +} + +async function toggleBold(store: EditorStore) { + const { result } = renderHook(() => useSelectionActions(store)); + let failure: unknown; + await act(async () => { + failure = await result.current.toggleBold(); + }); + return failure; +} + +test("Bold off moves a heading to the document's regular face, keeps its text, and undoes and redoes", async () => { + const store = await fixture("mushroom-life.pdf"); + const heading = "Spore Stage"; + expect(fonts(store, heading)).toEqual(["LMRoman12-Bold"]); + select(store, heading); + + expect(await toggleBold(store)).toBeNull(); + + expect(fonts(store, heading)).toEqual(["LMRoman12-Regular"]); + expect(drawnText(store, heading)).toBe("SporeStage"); + + store.undo(); + expect(fonts(store, heading)).toEqual(["LMRoman12-Bold"]); + store.redo(); + expect(fonts(store, heading)).toEqual(["LMRoman12-Regular"]); + expect(drawnText(store, heading)).toBe("SporeStage"); + + const saved = await storeWith(await savedBytes(store)); + expect(fonts(saved, heading)).toEqual(["LMRoman12-Regular"]); +}); + +test("a letter the regular subset lacks stays in the bold face it was drawn in, and the user is told", async () => { + const store = await fixture("mushroom-life.pdf"); + select(store, "Introduction"); + + expect(await toggleBold(store)).toBe("closestMatch"); + + expect(pieces(store, "Introduction")).toEqual([ + "I@LMRoman12-Bold", + "ntroduction@LMRoman12-Regular", + ]); +}); + +test("Bold on draws the letters the bold subset lacks in the closest match and says so", async () => { + const store = await fixture("coloured-word-sample.pdf"); + const line = "Total due today by card"; + expect(fonts(store, line)).toEqual(["LiberationSans", "LiberationSans-Bold"]); + select(store, line); + + expect(await toggleBold(store)).toBe("closestMatch"); + + const bold = () => + pieces(store, line) + .filter((p) => p.endsWith("@LiberationSans-Bold")) + .map((p) => p.split("@")[0]) + .join(""); + expect(bold()).toMatch(/otal.*d.*e.*today.*y.*ca.*d/); + expect(bold()).not.toMatch(/[Tubr]/); + expect(drawnText(store, line)).toBe("Totalduetodaybycard"); + expect( + store.document!.page(0).runs.find((r) => r.text === line)?.fontId, + ).toMatch(/^pdf:\d+:/); + + store.undo(); + expect(bold()).toBe("today "); + store.redo(); + expect(bold()).not.toMatch(/[Tubr]/); + expect(drawnText(store, line)).toBe("Totalduetodaybycard"); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorStores.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorStores.ts new file mode 100644 index 00000000000..82064257bc3 --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorStores.ts @@ -0,0 +1,65 @@ +import { readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { afterAll, afterEach, beforeAll, vi } from "vitest"; +import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument"; +import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader"; +import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore"; +import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf"; + +export const FIXTURES = path.join( + import.meta.dirname, + "../../../tests/test-fixtures", +); + +/** Serves the bundled PDFium wasm to the editor's loader in place of `fetch` for the calling file's tests; call at its top level. */ +export function servePdfiumWasm(): void { + beforeAll(async () => { + const wasm = await readFile( + createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"), + ); + vi.stubGlobal( + "fetch", + vi.fn(async (url: string) => + String(url).endsWith(".wasm") + ? new Response(wasm, { + headers: { "Content-Type": "application/wasm" }, + }) + : new Response(null, { status: 404 }), + ), + ); + }); + afterAll(() => vi.unstubAllGlobals()); +} + +/** Opens PDFs into editor stores with page 0 read, each disposed after the test that opened it; call at a test file's top level. */ +export function editorStores() { + const stores: EditorStore[] = []; + afterEach(() => { + for (const store of stores.splice(0)) store.dispose(); + }); + async function storeWith(bytes: Uint8Array): Promise { + const doc = await EditorDocument.open(bytes); + const store = new EditorStore(); + stores.push(store); + await store.setDocument(doc); + PdfiumTextReader.populate(doc, doc.page(0)); + return store; + } + async function fixture(name: string): Promise { + return storeWith(new Uint8Array(await readFile(path.join(FIXTURES, name)))); + } + return { storeWith, fixture }; +} + +// jsdom's Blob reads back through FileReader only. +export async function savedBytes(store: EditorStore): Promise { + const blob = await exportToBlob(store.document!); + const buffer = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as ArrayBuffer); + reader.onerror = () => reject(reader.error); + reader.readAsArrayBuffer(blob); + }); + return new Uint8Array(buffer); +} diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts index 0c1f8f8b898..daac07029ac 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts @@ -1,10 +1,12 @@ import { describe, expect, it, beforeEach, vi } from "vitest"; import { - canToggleItalic, fallbackFamilyFor, fallbackFontIdFor, - italicCapability, } from "@editor/tools/pdfTextEditor/util/fontCapability"; +import { + canRestyle, + restyledFace, +} from "@editor/tools/pdfTextEditor/util/fontFaces"; import { resetFontCompletions, resolveOriginalFonts, @@ -78,65 +80,106 @@ beforeEach(() => { stubQueryLocalFonts(null); }); -describe("italicCapability", () => { +const NO_DOCUMENT = { documentFamilies: [] }; + +describe("restyledFace for italic", () => { it("flips a base-14 family in place", () => { - expect(italicCapability("base14:Helvetica", true, null)).toEqual({ - family: "Helvetica-Oblique", - source: "base14", - }); - expect(italicCapability("base14:Times-BoldItalic", false, null)).toEqual({ - family: "Times-Bold", - source: "base14", - }); + expect( + restyledFace( + "base14:Helvetica", + { italic: true }, + { ...NO_DOCUMENT, externalFonts: null }, + ), + ).toBe("Helvetica-Oblique"); + expect( + restyledFace( + "base14:Times-BoldItalic", + { italic: false }, + { ...NO_DOCUMENT, externalFonts: null }, + ), + ).toBe("Times-Bold"); }); it("refuses an embedded family with no device fonts loaded", () => { - expect(italicCapability("pdf:4242:Calibri", true, null).family).toBeNull(); + expect( + restyledFace( + "pdf:4242:Calibri", + { italic: true }, + { ...NO_DOCUMENT, externalFonts: null }, + ), + ).toBeNull(); }); it("refuses a subset family whose installed face has no italic cut", () => { expect( - italicCapability("pdf:4242:Stencil", true, STENCIL).family, + restyledFace( + "pdf:4242:Stencil", + { italic: true }, + { ...NO_DOCUMENT, externalFonts: STENCIL }, + ), ).toBeNull(); }); it("uses the installed italic cut of the run's own family", () => { - expect(italicCapability("pdf:4242:Calibri", true, CALIBRI)).toEqual({ - family: "Calibri Italic", - source: "device", - }); + expect( + restyledFace( + "pdf:4242:Calibri", + { italic: true }, + { ...NO_DOCUMENT, externalFonts: CALIBRI }, + ), + ).toBe("Calibri Italic"); }); it("never substitutes a different typeface", () => { // The whole point: Calibri does not become Helvetica just to look slanted. - const cap = italicCapability("pdf:4242:Calibri", true, STENCIL); - expect(cap.family).toBeNull(); - expect(cap.source).toBeNull(); + expect( + restyledFace( + "pdf:4242:Calibri", + { italic: true }, + { ...NO_DOCUMENT, externalFonts: STENCIL }, + ), + ).toBeNull(); }); -}); -describe("italicCapability answers", () => { - it("are kept per font list, so a new list is asked afresh", () => { - const before = italicCapability("pdf:4242:Calibri", true, STENCIL); - expect(before.family).toBeNull(); - expect(italicCapability("pdf:4242:Calibri", true, STENCIL)).toBe(before); - const found = italicCapability("pdf:4242:Calibri", true, CALIBRI); - expect(found.family).toBe("Calibri Italic"); - expect(italicCapability("pdf:4242:Calibri", true, CALIBRI)).toBe(found); + it("is read from the font list asked with, so a new list is asked afresh", () => { + const ask = (fonts: LocalFont[]) => + restyledFace( + "pdf:4242:Calibri", + { italic: true }, + { ...NO_DOCUMENT, externalFonts: fonts }, + ); + expect(ask(STENCIL)).toBeNull(); + expect(ask(STENCIL)).toBeNull(); + expect(ask(CALIBRI)).toBe("Calibri Italic"); + expect(ask(CALIBRI)).toBe("Calibri Italic"); }); }); -describe("canToggleItalic", () => { +describe("canRestyle to italic", () => { it("is false for an empty selection", () => { - expect(canToggleItalic([], CALIBRI)).toBe(false); + expect( + canRestyle( + [], + { italic: true }, + { documentFamilies: [], externalFonts: CALIBRI }, + ), + ).toBe(false); }); it("needs EVERY run to be capable", () => { expect( - canToggleItalic(["base14:Helvetica", "base14:Times-Roman"], null), + canRestyle( + ["base14:Helvetica", "base14:Times-Roman"], + { italic: true }, + { documentFamilies: [], externalFonts: null }, + ), ).toBe(true); expect( - canToggleItalic(["base14:Helvetica", "pdf:1:Stencil"], STENCIL), + canRestyle( + ["base14:Helvetica", "pdf:1:Stencil"], + { italic: true }, + { documentFamilies: [], externalFonts: STENCIL }, + ), ).toBe(false); }); }); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFaces.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFaces.test.ts new file mode 100644 index 00000000000..f845a3e9a1a --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFaces.test.ts @@ -0,0 +1,345 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { + familyKey, + parseFaceName, +} from "@editor/tools/pdfTextEditor/util/faceNames"; +import { + BUILT_IN_FAMILIES, + canRestyle, + documentFamilies, + externalFamilies, + faceKeepingStyle, + restyledFace, + type FaceSources, +} from "@editor/tools/pdfTextEditor/util/fontFaces"; +import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState"; +import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts"; +import type { + PageSnapshot, + SelectionState, +} from "@editor/tools/pdfTextEditor/types"; + +// Names as pdffonts lists them in the test fixtures and the regression corpus. +const REAL_NAMES: Array<[string, string, number, boolean]> = [ + ["AAAAAA+LiberationSans", "LiberationSans", 400, false], + ["BAAAAA+LiberationSans-Bold", "LiberationSans", 700, false], + ["CAAAAA+LiberationSans-Italic", "LiberationSans", 400, true], + ["DAAAAA+LiberationSans-BoldItalic", "LiberationSans", 700, true], + ["Arial,Bold", "Arial", 700, false], + ["Arial,BoldItalic", "Arial", 700, true], + ["EAAAAA+Arial-BoldMT", "Arial", 700, false], + ["XOAUWI+ArialMT", "Arial", 400, false], + ["Helvetica-Oblique", "Helvetica", 400, true], + ["Helvetica-BoldOblique", "Helvetica", 700, true], + ["Times-BoldItalic", "Times", 700, true], + ["Times-Roman", "Times", 400, false], + ["YNEWNN+TimesNewRomanPSMT", "TimesNewRoman", 400, false], + ["ESSOFH+Times-New-Roman,", "Times New Roman", 400, false], + ["CLJQKD+Trebuchet-MS-Bold", "Trebuchet MS", 700, false], + ["JUEZMN+TrebuchetMS-Bold", "TrebuchetMS", 700, false], + ["DWPUQU+Georgia-Bold-Italic", "Georgia", 700, true], + ["XRKQNH+Palatino-Roman", "Palatino", 400, false], + ["QMJUWP+NimbusRomNo9L-Medi", "NimbusRomNo9L", 700, false], + ["NimbusRomNo9L-MediItal", "NimbusRomNo9L", 700, true], + ["NimbusSanL-Bold", "NimbusSanL", 700, false], + ["NimbusSanL-ReguItal", "NimbusSanL", 400, true], + ["URWBookmanL-Ligh", "URWBookmanL", 300, false], + ["URWBookmanL-DemiBoldItal", "URWBookmanL", 600, true], + ["Roboto-Medium", "Roboto", 500, false], + ["Franklin Gothic Medium", "Franklin Gothic", 500, false], + ["XICEAB+NimbusRomNo9L-ReguItal", "NimbusRomNo9L", 400, true], + ["ONWLAQ+LMRoman12-Bold", "LMRoman12", 700, false], + ["AAAAAA+HiraginoSans-W4", "HiraginoSans", 400, false], + ["KVGQPY+StandardSymL-Slant_167", "StandardSymL", 400, true], + [ + "AAAAAA+.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000", + ".SFNS", + 600, + false, + ], + ["JAAAAA+.SFNS-Bold", ".SFNS", 700, false], + ["Calibri Bold", "Calibri", 700, false], + ["Segoe UI Semibold", "Segoe UI", 600, false], + ["Segoe UI Semi Bold Italic", "Segoe UI", 600, true], + ["MinionPro-BoldIt", "MinionPro", 700, true], + ["HelveticaNeueBold", "HelveticaNeue", 700, false], + ["Calibri Light", "Calibri", 300, false], + ["Arial Black", "Arial", 900, false], +]; + +describe("parseFaceName", () => { + it.each(REAL_NAMES)( + "reads %s as %s at %i", + (name, family, weight, italic) => { + const parsed = parseFaceName(name); + expect(parsed.family).toBe(family); + expect(parsed.weight).toBe(weight); + expect(parsed.italic).toBe(italic); + }, + ); + + it("keys one family the same whatever its separators", () => { + expect(familyKey(parseFaceName("Trebuchet-MS-Bold").family)).toBe( + familyKey(parseFaceName("TrebuchetMS").family), + ); + expect(familyKey(parseFaceName("Times-New-Roman,").family)).toBe( + familyKey(parseFaceName("TimesNewRomanPSMT").family), + ); + expect(familyKey(parseFaceName("Courier-New").family)).toBe( + familyKey(parseFaceName("CourierNewPSMT").family), + ); + }); + + it("leaves a name with no style words whole", () => { + expect(parseFaceName("Helvetica Neue").family).toBe("Helvetica Neue"); + expect(parseFaceName("Book Antiqua").family).toBe("Book Antiqua"); + expect(parseFaceName("CairoFont-8-0").family).toBe("CairoFont 8 0"); + }); +}); + +describe("family grouping", () => { + it("lists each built-in family once with all four faces", () => { + expect(BUILT_IN_FAMILIES.map((entry) => entry.label)).toEqual([ + "Helvetica", + "Times", + "Courier", + ]); + expect(BUILT_IN_FAMILIES.map((entry) => entry.value)).toEqual([ + "Helvetica", + "Times-Roman", + "Courier", + ]); + for (const entry of BUILT_IN_FAMILIES) expect(entry.faces).toHaveLength(4); + }); + + it("groups document faces of one family whatever their name spelling", () => { + const families = documentFamilies([ + "pdf:1:Arial", + "pdf:2:Arial,Bold", + "pdf:3:Arial-BoldMT", + "pdf:4:Arial,Italic", + "pdf:5:Georgia-Bold", + ]); + expect(families.map((entry) => entry.label)).toEqual(["Arial", "Georgia"]); + expect(families[0].faces.map((f) => [f.value, f.weight, f.italic])).toEqual( + [ + ["pdf:1:Arial", 400, false], + ["pdf:2:Arial,Bold", 700, false], + ["pdf:4:Arial,Italic", 400, true], + ], + ); + }); + + it("lists a bold-only family under its family name, standing for it by the bold face", () => { + const [georgia] = documentFamilies(["pdf:5:Georgia-Bold"]); + expect(georgia.label).toBe("Georgia"); + expect(georgia.value).toBe("pdf:5:Georgia-Bold"); + }); + + it("names an external face so the face lookup finds it again", () => { + const fonts: LocalFont[] = [ + face("Segoe UI", "Regular"), + face("Segoe UI", "Semibold"), + face("Segoe UI", "Bold"), + face("Segoe UI", "Bold Italic"), + face("Acme Display Bold", "Regular"), + ]; + const families = externalFamilies(fonts); + expect(families.map((entry) => entry.label)).toEqual([ + "Acme Display", + "Segoe UI", + ]); + expect(families[0].faces).toEqual([ + { value: "Acme Display Bold", weight: 700, italic: false }, + ]); + expect(families[1].faces.map((f) => f.value)).toEqual([ + "Segoe UI", + "Segoe UI Semibold", + "Segoe UI Bold", + "Segoe UI Bold Italic", + ]); + }); +}); + +function face(family: string, style: string): LocalFont { + return { + family, + style, + fullName: style === "Regular" ? family : `${family} ${style}`, + postscriptName: `${family.replace(/ /g, "")}-${style.replace(/ /g, "")}`, + }; +} + +const NO_SOURCES: FaceSources = { documentFamilies: [], externalFonts: null }; + +describe("restyledFace", () => { + const liberation = documentFamilies([ + "pdf:1:LiberationSans", + "pdf:2:LiberationSans-Bold", + "pdf:3:LiberationSans-Italic", + ]); + const sources: FaceSources = { + documentFamilies: liberation, + externalFonts: null, + }; + + it("moves a document run to the document's own bold face", () => { + expect(restyledFace("pdf:1:LiberationSans", { bold: true }, sources)).toBe( + "pdf:2:LiberationSans-Bold", + ); + expect( + restyledFace("pdf:2:LiberationSans-Bold", { bold: false }, sources), + ).toBe("pdf:1:LiberationSans"); + }); + + it("has nothing for a style the family lacks, and nothing to do for one it is in", () => { + expect( + restyledFace("pdf:3:LiberationSans-Italic", { bold: true }, sources), + ).toBeNull(); + expect( + restyledFace("pdf:2:LiberationSans-Bold", { bold: true }, sources), + ).toBeUndefined(); + }); + + it("flips a built-in face in place", () => { + expect( + restyledFace("base14:Times-Italic", { bold: true }, NO_SOURCES), + ).toBe("Times-BoldItalic"); + }); + + it("never synthesises bold for a family with no bold face", () => { + expect( + restyledFace("pdf:9:Garamond", { bold: true }, NO_SOURCES), + ).toBeNull(); + expect(canRestyle(["pdf:9:Garamond"], { bold: true }, NO_SOURCES)).toBe( + false, + ); + }); + + it("reaches a weight beyond regular and bold", () => { + const sfns = documentFamilies([ + "pdf:1:.SFNS-Regular", + "pdf:2:.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000", + "pdf:3:.SFNS-Bold", + ]); + expect( + restyledFace( + "pdf:1:.SFNS-Regular", + { weight: 600 }, + { documentFamilies: sfns, externalFonts: null }, + ), + ).toBe("pdf:2:.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000"); + }); + + it("keeps a run's weight and slant when its family is picked", () => { + const [helvetica] = BUILT_IN_FAMILIES; + expect(faceKeepingStyle(helvetica, { weight: 700, italic: true })).toBe( + "Helvetica-BoldOblique", + ); + const [georgia] = documentFamilies(["pdf:5:Georgia-Bold"]); + expect(faceKeepingStyle(georgia, { weight: 400, italic: false })).toBe( + "pdf:5:Georgia-Bold", + ); + }); +}); + +function run(id: string, fontId: string) { + return { + id, + pageIndex: 0, + bounds: { x: 0, y: 0, width: 10, height: 10 }, + matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }, + text: "x", + fontId, + fontSize: 12, + fill: { r: 0, g: 0, b: 0, a: 255 }, + fontSubset: false, + }; +} + +function toolbarFor(runs: ReturnType[], selected: string[]) { + const pages = [{ pageIndex: 0, runs, images: [] } as unknown as PageSnapshot]; + return deriveToolbarState(pages, { + runIds: selected, + imageIds: [], + } as unknown as SelectionState); +} + +describe("toolbar bold state", () => { + it("offers bold for a document font whose bold face is elsewhere in the document", () => { + const state = toolbarFor( + [run("a", "pdf:1:LiberationSans"), run("b", "pdf:2:LiberationSans-Bold")], + ["a"], + ); + expect(state.bold).toBe(false); + expect(state.canBold).toBe(true); + }); + + it("disables bold for a family with no bold face", () => { + const state = toolbarFor([run("a", "pdf:1:Garamond")], ["a"]); + expect(state.canBold).toBe(false); + }); + + it("shows a bold-only family as bold and locked", () => { + const state = toolbarFor([run("a", "pdf:1:Georgia-Bold")], ["a"]); + expect(state.bold).toBe(true); + expect(state.canBold).toBe(false); + }); + + it("marks a half-bold selection mixed and lets the toggle make it all bold", () => { + const state = toolbarFor( + [run("a", "base14:Helvetica"), run("b", "base14:Helvetica-Bold")], + ["a", "b"], + ); + expect(state.mixed.bold).toBe(true); + expect(state.bold).toBe(false); + expect(state.canBold).toBe(true); + }); + + it("says Bold is off for want of a bold italic face, not of a bold one", () => { + const state = toolbarFor( + [ + run("a", "pdf:1:Georgia-Italic"), + run("b", "pdf:2:Georgia-Bold"), + run("c", "pdf:3:Georgia"), + ], + ["a"], + ); + expect(state.canBold).toBe(false); + expect(state.boldNeedsBoldItalic).toBe(true); + expect( + toolbarFor([run("a", "pdf:1:Garamond-Italic")], ["a"]) + .boldNeedsBoldItalic, + ).toBe(false); + }); + + it("says Italic is off for want of a bold italic face, not of an italic one", () => { + const state = toolbarFor( + [run("a", "pdf:1:Georgia-Bold"), run("b", "pdf:2:Georgia-Italic")], + ["a"], + ); + expect(state.canItalic).toBe(false); + expect(state.italicNeedsBoldItalic).toBe(true); + expect( + toolbarFor([run("a", "pdf:1:Garamond-Bold")], ["a"]) + .italicNeedsBoldItalic, + ).toBe(false); + }); + + it("lists the weights of a family with more than regular and bold", () => { + const sfns = toolbarFor( + [ + run("a", "pdf:1:.SFNS-Regular"), + run("b", "pdf:2:.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000"), + run("c", "pdf:3:.SFNS-Bold"), + ], + ["a"], + ); + expect(sfns.weights).toEqual([400, 600, 700]); + expect(sfns.weight).toBe(400); + expect(toolbarFor([run("a", "base14:Helvetica")], ["a"]).weights).toEqual( + [], + ); + }); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFacesFixtures.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFacesFixtures.test.ts new file mode 100644 index 00000000000..193ae7042bb --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFacesFixtures.test.ts @@ -0,0 +1,81 @@ +// @vitest-environment node +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { expect, test } from "vitest"; +import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument"; +import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader"; +import { parseFaceName } from "@editor/tools/pdfTextEditor/util/faceNames"; +import { documentFontIds } from "@editor/tools/pdfTextEditor/util/documentFontStyle"; +import { + documentFamilies, + type FontFamilyEntry, +} from "@editor/tools/pdfTextEditor/util/fontFaces"; +import { + FIXTURES, + servePdfiumWasm, +} from "@editor/tools/pdfTextEditor/__tests__/editorStores"; + +servePdfiumWasm(); + +/** The document fonts on a fixture's first page as families, or null when it does not open. */ +async function familiesOf(file: string): Promise { + let doc: EditorDocument; + try { + doc = await EditorDocument.open( + new Uint8Array(await readFile(path.join(FIXTURES, file))), + ); + } catch { + return null; + } + try { + PdfiumTextReader.populate(doc, doc.page(0)); + return documentFamilies([ + ...doc.page(0).runs.map((run) => run.fontId), + ...documentFontIds(), + ]); + } finally { + doc.dispose(); + } +} + +function faces(entry: FontFamilyEntry | undefined) { + return entry?.faces.map((f) => `${f.weight}${f.italic ? "i" : ""}`); +} + +test("every fixture lists each family once, with no style left in its name", async () => { + const files = (await readdir(FIXTURES)).filter((f) => f.endsWith(".pdf")); + let opened = 0; + for (const file of files) { + const families = await familiesOf(file); + if (!families) continue; + opened++; + const keys = families.map((entry) => entry.key); + expect(new Set(keys).size, file).toBe(keys.length); + for (const entry of families) + expect(parseFaceName(entry.label).family, file).toBe(entry.label); + } + expect(opened).toBeGreaterThan(50); +}, 300_000); + +test("the four Liberation Sans subsets of one paragraph are one family", async () => { + const families = (await familiesOf("mixed-style-sample.pdf"))!; + const liberation = families.find((e) => e.key === "liberationsans"); + expect(faces(liberation)).toEqual(["400", "700", "400i", "700i"]); +}); + +test("base-14 fonts the PDF does not embed are known by the name it gives them", async () => { + const families = (await familiesOf("table-sample.pdf"))!; + expect(families.map((e) => e.label)).toEqual(["Helvetica"]); + expect(faces(families[0])).toEqual(["400", "700"]); +}); + +test("cairo's Georgia faces group and its bold-only Trebuchet stands for itself", async () => { + const families = (await familiesOf("cairo-styles.pdf"))!; + expect(faces(families.find((e) => e.key === "georgia"))).toEqual([ + "400", + "700", + "400i", + "700i", + ]); + expect(faces(families.find((e) => e.key === "trebuchetms"))).toEqual(["700"]); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts index 17575b5860c..203d54f81d2 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts @@ -1,12 +1,10 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { - groupByFamily, isLocalFontAccessSupported, listLocalFonts, listLocalFontsIfGranted, resetLocalFontsCache, } from "@editor/tools/pdfTextEditor/util/localFonts"; -import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts"; type QueryStub = () => Promise; @@ -24,15 +22,6 @@ function face( return { family, style, postscriptName, fullName: `${family} ${style}` }; } -function mkFont(family: string, style: string): LocalFont { - return { - family, - style, - fullName: `${family} ${style}`, - postscriptName: `${family}-${style}`, - }; -} - beforeEach(() => { resetLocalFontsCache(); setQuery(null); @@ -206,44 +195,3 @@ describe("listLocalFontsIfGranted", () => { await expect(listLocalFontsIfGranted()).resolves.toBeNull(); }); }); - -describe("groupByFamily", () => { - it("collapses faces into families sorted case-insensitively", () => { - const grouped = groupByFamily([ - mkFont("inter", "Regular"), - mkFont("Arial", "Bold"), - mkFont("Zapfino", "Regular"), - mkFont("bahnschrift", "Light"), - ]); - expect(grouped.map((f) => f.family)).toEqual([ - "Arial", - "bahnschrift", - "inter", - "Zapfino", - ]); - }); - - it("merges faces of one family and sorts its styles", () => { - const grouped = groupByFamily([ - mkFont("Inter", "Regular"), - mkFont("Inter", "Bold"), - mkFont("inter", "Italic"), - ]); - expect(grouped).toHaveLength(1); - expect(grouped[0]?.family).toBe("Inter"); - expect(grouped[0]?.styles).toEqual(["Bold", "Italic", "Regular"]); - }); - - it("de-duplicates styles case-insensitively and skips empty ones", () => { - const grouped = groupByFamily([ - mkFont("Inter", "Bold"), - mkFont("Inter", "bold"), - mkFont("Inter", ""), - ]); - expect(grouped[0]?.styles).toEqual(["Bold"]); - }); - - it("returns an empty list for no faces", () => { - expect(groupByFamily([])).toEqual([]); - }); -}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionToolbarState.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionToolbarState.test.tsx new file mode 100644 index 00000000000..713d7321c3c --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionToolbarState.test.tsx @@ -0,0 +1,166 @@ +import { MantineProvider } from "@mantine/core"; +import { act, render, renderHook, screen } from "@testing-library/react"; +import { beforeAll, expect, test, vi } from "vitest"; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("@editor/services/apiClient", () => ({ default: { get } })); + +import { FormatGroup } from "@editor/tools/pdfTextEditor/components/toolbar/FormatGroup"; +import { StyleTextRangeCommand } from "@editor/tools/pdfTextEditor/commands/StyleTextRangeCommand"; +import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController"; +import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun"; +import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore"; +import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types"; +import { + editorStores, + servePdfiumWasm, +} from "@editor/tools/pdfTextEditor/__tests__/editorStores"; + +servePdfiumWasm(); +const { fixture } = editorStores(); + +beforeAll(() => { + get.mockRejectedValue(new Error("no server fonts")); + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null); +}); + +/** tagged-sample.pdf with "every" redrawn in Helvetica-Bold and "region" in Times-Roman. */ +async function styledLine(): Promise<{ store: EditorStore; run: TextRun }> { + const store = await fixture("tagged-sample.pdf"); + // A revision no page has, so the first dispatch publishes the page as read. + store.publishPages([ + { + pageIndex: 0, + revision: -1, + runs: [], + images: [], + shapes: [], + annotations: [], + rules: [], + } as unknown as PageSnapshot, + ]); + const run = store + .document!.page(0) + .runs.find((r) => r.text.startsWith("Revenue"))!; + const at = (word: string) => run.text.indexOf(word); + store.dispatch( + new StyleTextRangeCommand({ + pageIndex: 0, + runId: run.id, + faces: [ + { start: at("every"), end: at("every") + 5, face: "Helvetica-Bold" }, + { start: at("region"), end: at("region") + 6, face: "Times-Roman" }, + ], + }), + ); + return { store, run }; +} + +function select(store: EditorStore, run: TextRun, part: string | null): void { + store.selection.selectOne(run.id); + if (part === null) return; + const start = run.text.indexOf(part); + store.selection.setTextRange(run.id, { start, end: start + part.length }); +} + +function toolbar(store: EditorStore) { + return renderHook(() => + useToolbarController(store, store.getState(), store.selection.value), + ).result.current.state; +} + +test("Bold reads on for a selected bold word inside a regular box", async () => { + const { store, run } = await styledLine(); + select(store, run, "every"); + + const state = toolbar(store); + + expect(state.bold).toBe(true); + expect(state.mixed.bold).toBe(false); + expect(state.weight).toBe(700); + expect(state.fontFamily).toMatch(/Helvetica-Bold$/); +}); + +test("Bold reads mixed for a selection of bold and regular words of one family, which is not a mixed family", async () => { + const { store, run } = await styledLine(); + select(store, run, "in every"); + + const state = toolbar(store); + + expect(state.bold).toBe(false); + expect(state.mixed.bold).toBe(true); + expect(state.weight).toBeNull(); + expect(state.mixed.fontFamily).toBe(false); +}); + +test("the family reads as the selected words' own, and as mixed when they differ", async () => { + const { store, run } = await styledLine(); + select(store, run, "region"); + expect(toolbar(store).fontFamily).toMatch(/Times-Roman$/); + expect(toolbar(store).mixed.fontFamily).toBe(false); + + select(store, run, "every region"); + expect(toolbar(store).mixed.fontFamily).toBe(true); +}); + +test("with no characters selected the controls describe the box", async () => { + const { store, run } = await styledLine(); + select(store, run, null); + + const state = toolbar(store); + + expect(state.bold).toBe(false); + expect(state.mixed.bold).toBe(false); + expect(state.fontFamily).toBe(run.fontId); +}); + +function Toolbar({ store }: { store: EditorStore }) { + const controller = useToolbarController( + store, + store.getState(), + store.selection.value, + ); + return ; +} + +function renderToolbar(store: EditorStore) { + return render( + + + , + ); +} + +test("the Bold toggle and family field show a selection of mixed words as mixed", async () => { + const { store, run } = await styledLine(); + select(store, run, "every region"); + + renderToolbar(store); + + expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "mixed", + ); + expect(screen.getByTestId("pdf-editor-font-family")).toHaveAttribute( + "placeholder", + "pdfTextEditor.fontPicker.mixed", + ); +}); + +test("the Bold toggle shows on for a bold word and off for a regular one beside it", async () => { + const { store, run } = await styledLine(); + select(store, run, "every"); + const { unmount } = renderToolbar(store); + expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "true", + ); + unmount(); + + act(() => select(store, run, "grew")); + renderToolbar(store); + expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "false", + ); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts index 426c0716c79..fe1418fbc67 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts @@ -20,15 +20,26 @@ import { loadedExternalFonts, } from "@editor/tools/pdfTextEditor/util/externalFonts"; import { - familyOptions, listLocalFonts, pickLocalFontFace, resetLocalFontsCache, } from "@editor/tools/pdfTextEditor/util/localFonts"; import { deviceFontIdFor } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed"; -import { italicCapability } from "@editor/tools/pdfTextEditor/util/fontCapability"; +import { + externalFamilies, + restyledFace, + type StyleRequest, +} from "@editor/tools/pdfTextEditor/util/fontFaces"; import { resetFontCompletions } from "@editor/tools/pdfTextEditor/util/documentFontCompletion"; +/** The face a run's font moves to for `request` among the external fonts loaded so far. */ +function faceWithLoadedFonts(fontId: string, request: StyleRequest) { + return restyledFace(fontId, request, { + documentFamilies: [], + externalFonts: loadedExternalFonts(), + }); +} + const requestsAtImport = get.mock.calls.length; const REGULAR = "1".repeat(64); @@ -464,14 +475,12 @@ describe("server fonts", () => { serveManifestAndFaces(); await loadServerFonts(); - expect(italicCapability("device:Acme Sans", true)).toEqual({ - family: "Acme Sans Italic", - source: "device", - }); - expect(italicCapability("device:Acme Sans Bold", true)).toEqual({ - family: null, - source: null, - }); + expect(faceWithLoadedFonts("device:Acme Sans", { italic: true })).toBe( + "Acme Sans Italic", + ); + expect( + faceWithLoadedFonts("device:Acme Sans Bold", { italic: true }), + ).toBeNull(); }); it("loads the new face after a refresh replaces the one already loaded", async () => { @@ -559,17 +568,17 @@ describe("server fonts", () => { }); const fonts = (await loadServerFonts()) ?? []; - expect(familyOptions(fonts, []).map((option) => option.value)).toEqual([ + expect(externalFamilies(fonts)[0].faces.map((face) => face.value)).toEqual([ "Acme Sans", "Acme Sans Bold", + "Acme Sans Italic", ]); expect(serverFaceFor("Acme Sans")?.id).toBe(REGULAR); expect(serverFaceFor("Acme Sans Bold")?.id).toBe(BOLD); expect(serverFaceFor("Acme Sans Italic")?.id).toBe(ITALIC); - expect(italicCapability("device:Acme Sans", true)).toEqual({ - family: "Acme Sans Italic", - source: "device", - }); + expect(faceWithLoadedFonts("device:Acme Sans", { italic: true })).toBe( + "Acme Sans Italic", + ); }); it("italicises a server Times New Roman with its own italic face", async () => { @@ -586,27 +595,23 @@ describe("server fonts", () => { ], }, }); - expect(italicCapability("pdf:1:Times New Roman", true)).toEqual({ - family: "Times-Italic", - source: "base14", - }); + expect(faceWithLoadedFonts("pdf:1:Times New Roman", { italic: true })).toBe( + "Times-Italic", + ); const fonts = await loadServerFonts(); - expect(italicCapability("device:Times New Roman", true)).toEqual({ - family: "Times New Roman Italic", - source: "device", - }); - expect(italicCapability("device:Times New Roman Italic", false)).toEqual({ - family: "Times New Roman", - source: "device", - }); + expect( + faceWithLoadedFonts("device:Times New Roman", { italic: true }), + ).toBe("Times New Roman Italic"); + expect( + faceWithLoadedFonts("device:Times New Roman Italic", { italic: false }), + ).toBe("Times New Roman"); expect( pickLocalFontFace(fonts ?? [], "Times New Roman Italic")?.style, ).toBe("Italic"); - expect(italicCapability("base14:Times-Roman", true)).toEqual({ - family: "Times-Italic", - source: "base14", - }); + expect(faceWithLoadedFonts("base14:Times-Roman", { italic: true })).toBe( + "Times-Italic", + ); }); }); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/styleTextRange.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/styleTextRange.test.ts new file mode 100644 index 00000000000..81c6b3e1913 --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/styleTextRange.test.ts @@ -0,0 +1,442 @@ +import { act, renderHook } from "@testing-library/react"; +import { beforeAll, expect, test, vi } from "vitest"; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("@editor/services/apiClient", () => ({ default: { get } })); + +import { + useSelectionActions, + type FontPickFailure, +} from "@editor/tools/pdfTextEditor/hooks/useSelectionActions"; +import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore"; +import { + collectMemberPtrs, + drawnEndPt, +} from "@editor/tools/pdfTextEditor/commands/editTextHelpers"; +import { readTextSource } from "@editor/tools/pdfTextEditor/commands/textPieces"; +import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand"; +import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun"; +import { + editorStores, + savedBytes, + servePdfiumWasm, +} from "@editor/tools/pdfTextEditor/__tests__/editorStores"; + +const FPDF_PAGEOBJ_TEXT = 1; +const REVENUE = "Revenue grew in every region this quarter,"; + +servePdfiumWasm(); +const { storeWith, fixture } = editorStores(); + +beforeAll(() => { + get.mockRejectedValue(new Error("no server fonts")); + // jsdom has no canvas; text measurement falls back without one. + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null); +}); + +function runStarting(store: EditorStore, text: string): TextRun { + const run = store.document!.page(0).runs.find((r) => r.text.startsWith(text)); + expect(run, `no run starting "${text}"`).toBeTruthy(); + return run!; +} + +interface Drawn { + text: string; + font: string; + x: number; + right: number; +} + +/** Each object of the run with the text it draws, its /BaseFont and where its ink starts and ends. */ +function drawn(store: EditorStore, run: TextRun): Drawn[] { + const doc = store.document!; + const m = doc.module; + const page = doc.page(0); + const buf = m.pdfium.wasmExports.malloc(2048); + const name = m.pdfium.wasmExports.malloc(256); + const box = m.pdfium.wasmExports.malloc(16); + const textPage = m.FPDFText_LoadPage(page.pagePtr); + try { + return collectMemberPtrs(run) + .filter((ptr) => ptr && m.FPDFPageObj_GetType(ptr) === FPDF_PAGEOBJ_TEXT) + .map((ptr) => { + m.FPDFTextObj_GetText(ptr, textPage, buf, 2048); + m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(ptr), name, 256); + m.FPDFPageObj_GetBounds(ptr, box, box + 4, box + 8, box + 12); + return { + text: m.pdfium.UTF16ToString(buf).trim(), + font: m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, ""), + x: m.pdfium.getValue(box, "float"), + right: m.pdfium.getValue(box + 8, "float"), + }; + }); + } finally { + m.FPDFText_ClosePage(textPage); + m.pdfium.wasmExports.free(buf); + m.pdfium.wasmExports.free(name); + m.pdfium.wasmExports.free(box); + } +} + +/** The run's words as "text@Font", objects split at spaces. */ +function faces(store: EditorStore, run: TextRun): string[] { + return drawn(store, run).flatMap((piece) => + piece.text.split(/\s+/).map((word) => `${word}@${piece.font}`), + ); +} + +function wordsIn(store: EditorStore, run: TextRun, font: string): string[] { + return faces(store, run) + .filter((face) => face.endsWith(`@${font}`)) + .map((face) => face.split("@")[0]); +} + +function pageText(store: EditorStore): string { + const doc = store.document!; + const m = doc.module; + const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr); + const count = m.FPDFText_CountChars(textPage); + const buf = m.pdfium.wasmExports.malloc((count + 1) * 2); + try { + m.FPDFText_GetText(textPage, 0, count, buf); + return m.pdfium.UTF16ToString(buf); + } finally { + m.pdfium.wasmExports.free(buf); + m.FPDFText_ClosePage(textPage); + } +} + +/** Where the engine puts the first letter of `needle` on the page, from the page's own text. */ +function originOf(store: EditorStore, needle: string): number { + const at = pageText(store).indexOf(needle); + expect(at, `"${needle}" is not on the page`).toBeGreaterThanOrEqual(0); + const doc = store.document!; + const m = doc.module; + const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr); + const xy = m.pdfium.wasmExports.malloc(16); + try { + m.FPDFText_GetCharOrigin(textPage, at, xy, xy + 8); + return m.pdfium.getValue(xy, "double"); + } finally { + m.pdfium.wasmExports.free(xy); + m.FPDFText_ClosePage(textPage); + } +} + +/** + * The objects of `run` that together draw `word`, in order, and for each after + * the first how far it starts from where the one before it left the pen. + */ +function seamsIn(store: EditorStore, run: TextRun, word: string): number[] { + const m = store.document!.module; + const objects = drawn(store, run).flatMap((piece, i) => { + const ptr = collectMemberPtrs(run).filter( + (p) => p && m.FPDFPageObj_GetType(p) === FPDF_PAGEOBJ_TEXT, + )[i]; + const source = readTextSource(m, ptr); + return source && piece.text ? [{ ...piece, ptr, source }] : []; + }); + objects.sort((a, b) => a.source.matrix[4] - b.source.matrix[4]); + for (let first = 0; first < objects.length; first++) { + let spelled = ""; + for (let last = first; last < objects.length; last++) { + spelled += objects[last].text; + if (!word.startsWith(spelled)) break; + if (spelled !== word) continue; + return objects.slice(first + 1, last + 1).map((piece, k) => { + const before = objects[first + k]; + const penEnd = drawnEndPt( + m, + [before.ptr], + [before.text], + before.source.size, + ); + return piece.source.matrix[4] - penEnd - run.charSpacingPt; + }); + } + } + throw new Error(`no objects of the run spell "${word}"`); +} + +function selectText(store: EditorStore, run: TextRun, part: string): void { + const start = run.text.indexOf(part); + expect(start, `"${part}" is not in the run`).toBeGreaterThanOrEqual(0); + store.selection.selectOne(run.id); + store.selection.setTextRange(run.id, { start, end: start + part.length }); +} + +async function perform( + store: EditorStore, + action: ( + actions: ReturnType, + ) => Promise, +): Promise { + const { result } = renderHook(() => useSelectionActions(store)); + let failure: FontPickFailure | null = null; + await act(async () => { + failure = await action(result.current); + }); + return failure; +} + +test("Bold on one word mid-line bolds that word only and moves the rest of the line by the width it gains", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + const before = { + grew: originOf(store, "grew"), + every: originOf(store, "every"), + region: originOf(store, "region"), + led: originOf(store, "led by"), + }; + selectText(store, run, "every"); + + expect(await perform(store, (a) => a.toggleBold())).toBeNull(); + + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["every"]); + expect(originOf(store, "grew")).toBeCloseTo(before.grew, 1); + expect(originOf(store, "every")).toBeCloseTo(before.every, 1); + // Helvetica-Bold "every" is about 1.6pt wider than the regular cut at this size. + const moved = originOf(store, "region") - before.region; + expect(moved).toBeGreaterThan(0.5); + expect(moved).toBeLessThan(4); + expect(originOf(store, "led by")).toBeCloseTo(before.led, 1); + expect(run.text).toBe(`${REVENUE}\nled by demand for the new product line.`); +}); + +test("Italic on a range across a word boundary slants exactly those letters", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + const ew = originOf(store, "ew in"); + selectText(store, run, "ew in ev"); + + expect(await perform(store, (a) => a.toggleItalic())).toBeNull(); + + const pieces = drawn(store, run).filter((p) => p.text); + expect( + pieces.filter((p) => p.font === "Helvetica-Oblique").map((p) => p.text), + ).toEqual(["ew", "in", "ev"]); + expect(pieces.find((p) => p.text === "gr")?.font).toBe("Helvetica"); + expect(pieces.find((p) => p.text === "ery")?.font).toBe("Helvetica"); + // One word, so the slanted half starts where the upright half ends. + expect(Math.abs(originOf(store, "ew in") - ew)).toBeLessThan(0.3); +}); + +test("Bold on the first word of a line toggles off again", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + selectText(store, run, "Revenue"); + + await perform(store, (a) => a.toggleBold()); + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["Revenue"]); + await perform(store, (a) => a.toggleBold()); + + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual([]); + expect(pageText(store)).toContain(REVENUE); +}); + +test("a weight picked for part of a line applies to that part only", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + selectText(store, run, "region"); + + expect(await perform(store, (a) => a.changeFontWeight(700))).toBeNull(); + + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["region"]); +}); + +test("a family picked for part of a line redraws that part in the family, keeping its style", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + selectText(store, run, "every region"); + + expect(await perform(store, (a) => a.changeFontFamily("Times-Roman"))).toBe( + null, + ); + + expect(wordsIn(store, run, "Times-Roman")).toEqual(["every", "region"]); + expect(wordsIn(store, run, "Helvetica")).toContain("quarter,"); +}); + +test("undo puts the line back exactly and redo restyles it again", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + const before = drawn(store, run); + selectText(store, run, "every"); + await perform(store, (a) => a.toggleBold()); + const after = drawn(store, run); + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["every"]); + + store.undo(); + expect(drawn(store, run)).toEqual(before); + expect(pageText(store)).toContain(REVENUE); + + store.redo(); + expect(drawn(store, run)).toEqual(after); + store.undo(); + store.redo(); + expect(drawn(store, run)).toEqual(after); +}); + +test("a save keeps the styled word in its own face and the line in reading order", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + selectText(store, run, "every"); + await perform(store, (a) => a.toggleBold()); + + const reopened = await storeWith(await savedBytes(store)); + const saved = runStarting(reopened, "Revenue grew"); + expect(wordsIn(reopened, saved, "Helvetica-Bold")).toEqual(["every"]); + expect(pageText(reopened)).toContain(REVENUE); + expect(saved.text.split("\n")[0]).toBe(REVENUE); +}); + +test("a range spanning two lines of a paragraph restyles both parts and leaves the other lines alone", async () => { + const store = await fixture("paragraph-sample.pdf"); + const run = runStarting(store, "First line of the body"); + const lines = run.text.split("\n"); + const third = drawn(store, run).find((p) => + p.text.startsWith("left margin"), + )!; + selectText(store, run, "together.\nSecond line"); + + expect(await perform(store, (a) => a.toggleBold())).toBeNull(); + + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual([ + "together.", + "Second", + "line", + ]); + expect(run.text.split("\n")).toEqual(lines); + expect( + drawn(store, run).find((p) => p.text.startsWith("left margin")), + ).toEqual(third); + expect(pageText(store)).toContain("grouped together."); +}); + +test("letters the bold subset lacks stay in the regular face and the user is told", async () => { + const store = await fixture("mushroom-life.pdf"); + const run = runStarting(store, "Mushrooms represent"); + selectText(store, run, "unique"); + + expect(await perform(store, (a) => a.toggleBold())).toBe("closestMatch"); + + const bold = wordsIn(store, run, "LMRoman12-Bold").join(""); + expect(bold.length).toBeGreaterThan(0); + expect(bold).toBe("uniue"); + expect( + faces(store, run) + .map((face) => face.split("@")[0]) + .join(""), + ).toContain("unique"); + expect(run.text).toContain("a unique posi-"); +}); + +test.each([ + [ + "before its last letter", + "represent one of nature’s", + "nature’s", + "of nature’s most", + ], + ["mid-word", "unique", "unique", "a unique posi"], + [ + "at the start of a word", + "biological", + "biological", + "the biological world", + ], +])( + "a letter the bold subset lacks %s abuts the letters around it and reads as one word, on the page and after a save", + async (_where, part, word, reads) => { + const store = await fixture("mushroom-life.pdf"); + const run = runStarting(store, "Mushrooms represent"); + selectText(store, run, part); + + expect(await perform(store, (a) => a.toggleBold())).toBe("closestMatch"); + + const seams = seamsIn(store, run, word); + expect(seams.length).toBeGreaterThan(0); + for (const seam of seams) expect(Math.abs(seam)).toBeLessThan(0.01); + expect(pageText(store)).toContain(reads); + const reopened = await storeWith(await savedBytes(store)); + expect(pageText(reopened)).toContain(reads); + }, +); + +test("typing straight after a bolded word goes on in bold", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + selectText(store, run, "every"); + await perform(store, (a) => a.toggleBold()); + + const at = run.text.indexOf("every") + "every".length; + store.dispatch( + new EditTextCommand({ + pageIndex: 0, + runId: run.id, + nextText: `${run.text.slice(0, at)}one${run.text.slice(at)}`, + }), + ); + + expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["every", "one"]); + expect(pageText(store)).toContain("in everyone region"); + expect(wordsIn(store, run, "Helvetica")).toContain("region"); +}); + +test("right-to-left text refuses a change to part of its line and stays as drawn", async () => { + const store = await fixture("coloured-word-sample.pdf"); + const run = runStarting(store, "הטלפון"); + const before = drawn(store, run); + selectText(store, run, "שלום"); + + expect(await perform(store, (a) => a.toggleBold())).toBeNull(); + + expect(store.getState().error).toMatch(/right-to-left/); + expect(drawn(store, run)).toEqual(before); + expect(store.history.canUndo).toBe(false); +}); + +test("text that needs shaping refuses a change to part of it", async () => { + const store = await fixture("shaped-line-sample.pdf"); + const run = store.document!.page(0).runs[0]; + const before = drawn(store, run); + store.selection.selectOne(run.id); + store.selection.setTextRange(run.id, { start: 0, end: 3 }); + + expect(await perform(store, (a) => a.changeFontFamily("Times-Roman"))).toBe( + "needsShaping", + ); + expect(drawn(store, run)).toEqual(before); +}); + +test("in a wrapped box a change rewraps the paragraph only when a line would overflow", async () => { + const store = await fixture("paragraph-sample.pdf"); + store.setWidthMode("wrap"); + const run = runStarting(store, "First line of the body"); + const text = run.text; + selectText(store, run, "bottom"); + await perform(store, (a) => a.toggleBold()); + expect(run.text).toBe(text); + + selectText(store, run, "Second line continues the paragraph and shares"); + await perform(store, (a) => a.toggleBold()); + expect(run.text).not.toBe(text); + expect(run.text.replace(/\s+/g, " ")).toBe(text.replace(/\s+/g, " ")); + + store.undo(); + expect(run.text).toBe(text); +}); + +test("with the whole box's text selected Bold applies to the box as before", async () => { + const store = await fixture("tagged-sample.pdf"); + const run = runStarting(store, "Revenue grew"); + store.selection.selectOne(run.id); + store.selection.setTextRange(run.id, { start: 0, end: run.text.length }); + + await perform(store, (a) => a.toggleBold()); + + const live = runStarting(store, "Revenue grew"); + expect(new Set(drawn(store, live).map((p) => p.font))).toEqual( + new Set(["Helvetica-Bold"]), + ); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts index d45ba6d810a..e8a444f065e 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts +++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts @@ -92,3 +92,32 @@ describe("deriveToolbarState documentFontId", () => { expect(s.documentFontId).toBeNull(); }); }); + +describe("deriveToolbarState for characters selected inside a run", () => { + const pages = mkPages([mkRun("a", "base14:Helvetica")]); + + it("describes the selected characters' fonts, not the run's", () => { + const s = deriveToolbarState(pages, mkSel(["a"]), null, [ + "base14:Helvetica-Bold", + ]); + expect(s.bold).toBe(true); + expect(s.fontFamily).toBe("base14:Helvetica-Bold"); + }); + + it("reads bold and regular cuts of one family as one family with Bold mixed", () => { + const s = deriveToolbarState(pages, mkSel(["a"]), null, [ + "base14:Helvetica", + "base14:Helvetica-Bold", + ]); + expect(s.mixed.bold).toBe(true); + expect(s.mixed.fontFamily).toBe(false); + }); + + it("reads two families as mixed", () => { + const s = deriveToolbarState(pages, mkSel(["a"]), null, [ + "base14:Helvetica", + "base14:Times-Roman", + ]); + expect(s.mixed.fontFamily).toBe(true); + }); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts index 39a3c0e7fed..df2cda5c490 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts +++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts @@ -48,6 +48,7 @@ import { } from "@editor/tools/pdfTextEditor/util/fontFamily"; import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers"; import { fallbackFamilyFor } from "@editor/tools/pdfTextEditor/util/fontCapability"; +import { fontCompletionFor } from "@editor/tools/pdfTextEditor/util/documentFontCompletion"; import { isScanRun, setScanOverride, @@ -64,7 +65,8 @@ interface LineToEmit { } // Re-emit a run's text in another family: PDFium has no SetFont accessor. -// Device fonts embed when pre-warmed, else the nearest standard face. +// Device fonts embed when pre-warmed, else the nearest standard face. A +// document fontId reuses that font of the PDF, the run's own one to restore it. // Letters the family has no glyph for stay in the font that drew them, and a // change that would still leave a letter undrawn is not made. export class SetFontFamilyCommand implements Command { @@ -99,10 +101,11 @@ export class SetFontFamilyCommand implements Command { if (!run) return; refuseRedrawOfReadOnlyText(run); if (needsShaping(run.text)) return; - // A document fontId as nextFamily puts the run back in the font it was changed away from. - const restoring = isDocumentFontId(this.nextFamily); + const toDocumentFont = isDocumentFontId(this.nextFamily); const documentFont = run.documentFont; - if (restoring && documentFont?.fontId !== this.nextFamily) return; + const restoring = + toDocumentFont && documentFont?.fontId === this.nextFamily; + if (toDocumentFont && !documentFontHandle(this.nextFamily)) return; const scanPrev = setScanOverride(doc, page, run, (o) => ({ ...o, family: this.nextFamily, @@ -161,12 +164,12 @@ export class SetFontFamilyCommand implements Command { created.push(...line.ptrs); } - // A restore drawn only in fallback faces did not put the run back in its font. - const restoreFont = documentFontHandle(this.nextFamily); - const notRestored = - restoring && - !created.some((ptr) => m.FPDFTextObj_GetFont(ptr) === restoreFont); - if (created.length === 0 || notRestored || losesLetters(dropped)) { + // A move to a document font drawn only in fallback faces did not put the run in that font. + const targetFont = documentFontHandle(this.nextFamily); + const notInTarget = + toDocumentFont && + !created.some((ptr) => m.FPDFTextObj_GetFont(ptr) === targetFont); + if (created.length === 0 || notInTarget || losesLetters(dropped)) { // Nothing usable emitted (e.g. all-whitespace dropped), or a letter went undrawn - restore and bail. for (const ptr of created) removeAndDestroyObject(m, page.pagePtr, ptr); this.reinsertOriginals(m, page); @@ -189,6 +192,9 @@ export class SetFontFamilyCommand implements Command { run.fontId = this.nextFamily; run.fontSubset = documentFont?.subset ?? false; run.documentFont = null; + } else if (toDocumentFont) { + run.fontId = this.nextFamily; + run.fontSubset = isSubsetFont(m, targetFont); } else { run.fontId = embedded ? deviceFontId(this.nextFamily) @@ -234,7 +240,7 @@ export class SetFontFamilyCommand implements Command { const run = page.findRun(this.runId); if (!run || isScanRun(run) || run.scanEdit) return null; const restoring = isDocumentFontId(this.nextFamily); - if (restoring && run.documentFont?.fontId !== this.nextFamily) return null; + if (restoring && !documentFontHandle(this.nextFamily)) return null; const emitLines = linesToEmit(run, readRunTags(doc, page, run)); const keptFonts = this.keptFontSpans(doc, page, run, emitLines); warmOnPageAdvances(doc.module, page.pagePtr); @@ -254,6 +260,36 @@ export class SetFontFamilyCommand implements Command { return restoring && !drawsRestoreFont ? "notRestored" : null; } + /** + * How much of the run's visible text the next font has glyphs for: the rest + * is drawn in the closest font that has them, and none means the change + * would not put the run in that font at all. + */ + coverage(doc: EditorDocument): "all" | "some" | "none" { + const page = doc.page(this.pageIndex); + const run = page.findRun(this.runId); + if (!run || isScanRun(run) || run.scanEdit) return "all"; + const draws = this.nextFontDraws(doc, page); + if (!draws) return "all"; + const visible = [...run.text].filter( + (ch) => !/\s/.test(ch) && !DRAWS_NOTHING.test(ch), + ); + const drawn = visible.filter(draws).length; + if (drawn === visible.length) return "all"; + return drawn === 0 ? "none" : "some"; + } + + /** Whether the next font has a glyph for a character; null when that cannot be known. */ + private nextFontDraws( + doc: EditorDocument, + page: Page, + ): ((ch: string) => boolean) | null { + const target = documentFontHandle(this.nextFamily); + if (!target) return familyDraws(doc, this.nextFamily); + return (ch) => + charcodesResolveFully(doc.module, target, ch, page.pagePtr, doc.docPtr); + } + private emit( doc: EditorDocument, page: Page, @@ -261,17 +297,21 @@ export class SetFontFamilyCommand implements Command { lines: readonly LineToEmit[], keptFonts: ReadonlyArray | undefined, ): EmittedLine[] { - // Only a restore reuses a document font for the run; either way `keptFonts` holds the letters that stay where they are. - const restoring = isDocumentFontId(this.nextFamily); + // Only a document font is reused for the run; either way `keptFonts` holds the letters that stay where they are. + const targetFont = documentFontHandle(this.nextFamily); return emitRunLines({ doc, page, run, lines: lines.map(({ text, tags }) => ({ text, tags })), origins: lines.map((line) => ({ x: line.x, y: line.y })), - originalFontPtr: restoring ? documentFontHandle(this.nextFamily) : 0, - originalFontSubset: restoring ? run.documentFont?.subset : run.fontSubset, - fallbackFamily: restoring + originalFontPtr: targetFont, + originalFontSubset: !targetFont + ? run.fontSubset + : run.documentFont?.fontId === this.nextFamily + ? run.documentFont.subset + : isSubsetFont(doc.module, targetFont), + fallbackFamily: targetFont ? fallbackFamilyFor(this.nextFamily) : this.nextFamily, fontSpansByLine: keptFonts, @@ -281,9 +321,9 @@ export class SetFontFamilyCommand implements Command { /** * Per line, the stretches the next font has no glyph for, each with the font * its letters are drawn in. Undefined when the next font draws every letter. - * A restore keeps only letters still in a font of the document: one the - * editor drew, in the family being left or a stand-in for it, goes back with - * the rest of the run. + * A move to a document font keeps only letters still in a font of the + * document: one the editor drew, in the family being left or a stand-in for + * it, goes with the rest of the run. */ private keptFontSpans( doc: EditorDocument, @@ -293,22 +333,26 @@ export class SetFontFamilyCommand implements Command { ): Array | undefined { const m = doc.module; const restoreFont = documentFontHandle(this.nextFamily); - const draws = restoreFont - ? (ch: string) => - charcodesResolveFully(m, restoreFont, ch, page.pagePtr, doc.docPtr) - : familyDraws(doc, this.nextFamily); + const draws = this.nextFontDraws(doc, page); if (!draws) return undefined; const lacks = (ch: string) => !/\s/.test(ch) && !draws(ch); if (![...run.text].some(lacks)) return undefined; const fontAt = sourceFontAt(m, page.pagePtr, run); const leaving = familyOf(run.fontId); + // A run still in a document font was drawn by the PDF, so a font named like it is that face, not a stand-in. const drawnByEditor = (font: number) => !!doc.ownedFontAt(font) || - [leaving, nearestStandardFont(leaving)].includes( - stripSubsetTag(readFontName(m, font) ?? ""), - ); + (!isDocumentFontId(run.fontId) && + [leaving, nearestStandardFont(leaving)].includes( + stripSubsetTag(readFontName(m, font) ?? ""), + )); + // A face completed from its real font draws a missing letter closer than the face the run is leaving. + const completed = + run.documentFont?.fontId !== this.nextFamily && + !!fontCompletionFor(this.nextFamily); const keeps = (font: number) => - !restoreFont || (font !== restoreFont && !drawnByEditor(font)); + !restoreFont || + (!completed && font !== restoreFont && !drawnByEditor(font)); const fallbackFamily = restoreFont ? fallbackFamilyFor(this.nextFamily) : this.nextFamily; @@ -386,11 +430,15 @@ function familyDraws( */ const NEEDS_SHAPING = /\p{M}|\u200c|\u200d|[\u1100-\u11ff]|\p{Script=Arabic}|\p{Script=Syriac}|\p{Script=Nko}|\p{Script=Mandaic}|\p{Script=Mongolian}|\p{Script=Phags_Pa}|\p{Script=Adlam}/u; -const ATTACHES_TO_PREVIOUS = /\p{M}|\u200c|\u200d/u; +export const ATTACHES_TO_PREVIOUS = /\p{M}|\u200c|\u200d/u; /** Format and control characters draw nothing, so losing one loses no letter. */ const DRAWS_NOTHING = /[\p{Cf}\p{Cc}]/u; -function losesLetters(dropped: readonly string[]): boolean { +export function isSubsetFont(m: WrappedPdfiumModule, font: number): boolean { + return /^[A-Z]{6}\+/.test(readFontName(m, font) ?? ""); +} + +export function losesLetters(dropped: readonly string[]): boolean { return dropped.some((ch) => !DRAWS_NOTHING.test(ch)); } diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/StyleTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/StyleTextRangeCommand.ts new file mode 100644 index 00000000000..c69068b9c67 --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/StyleTextRangeCommand.ts @@ -0,0 +1,961 @@ +import i18n from "i18next"; +import type { WrappedPdfiumModule } from "@embedpdf/pdfium"; +import { + RolledBackError, + type Command, +} from "@editor/tools/pdfTextEditor/commands/Command"; +import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm"; +import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand"; +import { + refuseRedrawOfReadOnlyText, + unsafeRtlEditMessage, +} from "@editor/tools/pdfTextEditor/commands/readOnlyText"; +import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit"; +import { + charcodesResolveFully, + collectMemberPtrs, + contentIndices, + drawnEndPt, + droppedCharsOf, + emitTextLine, + measureObjSpanPt, + removeAndDestroyObject, + restoreContentOrder, + rotationFromMatrix, + warmOnPageAdvances, + type FontSpan, +} from "@editor/tools/pdfTextEditor/commands/editTextHelpers"; +import { piecesFromObjects } from "@editor/tools/pdfTextEditor/commands/partialEdit"; +import { + ATTACHES_TO_PREVIOUS, + isSubsetFont, + losesLetters, +} from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand"; +import { + charOrigins, + readMatrix, + readTextSource, + writeMatrix, + type Point, + type TextSource, +} from "@editor/tools/pdfTextEditor/commands/textPieces"; +import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers"; +import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument"; +import type { Page } from "@editor/tools/pdfTextEditor/model/Page"; +import { + cloneParagraphLineSlot, + type ParagraphLineSlot, + type TextRun, +} from "@editor/tools/pdfTextEditor/model/TextRun"; +import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags"; +import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks"; +import { hasRtl } from "@editor/tools/pdfTextEditor/util/bidi"; +import { needsShaping } from "@editor/tools/pdfTextEditor/util/complexShaping"; +import { + deviceFamilyOf, + familyCoverage, +} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed"; +import { + documentFontIdAt, + noteDocumentFontStyle, +} from "@editor/tools/pdfTextEditor/util/documentFontStyle"; +import { fallbackFamilyFor } from "@editor/tools/pdfTextEditor/util/fontCapability"; +import { + base14FontId, + deviceFontId, + documentFontHandle, + nearestStandardFont, + stripSubsetTag, +} from "@editor/tools/pdfTextEditor/util/fontFamily"; +import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform"; +import type { RGBA, TextRange } from "@editor/tools/pdfTextEditor/types"; + +/** + * Characters `start` to `end` of a run's text, as code units, to draw in + * `face`: a value the font list gives, which is a document fontId, a standard + * font name or a device family. + */ +export interface FaceStretch { + start: number; + end: number; + face: string; +} + +/** Characters `start` to `end` of a run's text, drawn in one font. */ +export interface FontStretch { + start: number; + end: number; + fontId: string; +} + +/** Some of one run's characters, selected apart from the rest of it. */ +export interface SelectedPart { + page: Page; + run: TextRun; + range: TextRange; +} + +/** Why a run's selected characters cannot be restyled on their own. */ +export type RangeRefusal = "rightToLeft" | "needsShaping" | "unsupported"; + +interface Piece { + ptr: number; + text: string; + /** Where the piece's text starts in the run's text. */ + start: number; + bounds: { x: number; right: number }; +} + +interface Line { + /** Index into the run's paragraph line slots; -1 when the run has none. */ + slot: number; + pieces: Piece[]; +} + +interface Target { + fontPtr: number; + fallbackFamily: string; +} + +interface Unit { + /** Code units of the piece's text. */ + start: number; + end: number; + /** The face of each code unit of the unit, null where it keeps its own. */ + targets: Array; +} + +interface RunSnapshot { + bounds: TextRun["bounds"]; + pdfiumObjPtr: number; + mergedFromPtrs: number[]; + mergedFromTexts: string[]; + mergedFromBounds: Array<{ x: number; right: number }>; + mergedFromCharStarts: number[]; + paragraphMemberPtrs: number[]; + paragraphLeafPtrs: number[]; + paragraphLeafContainers: number[]; + paragraphLineSlots: ParagraphLineSlot[]; +} + +/** + * Restyle some characters of a run, leaving the rest of it as it is drawn. The + * objects holding those characters are redrawn word by word where their words + * already stood, each stretch in its own font as typing beside a styled word + * draws it, and the text after them on the line moves by the width the change + * adds or takes away. A character the new face has no glyph for stays in the + * font that drew it. Lines drawn right to left or needing shaping are refused, + * as their letters cannot be redrawn one stretch at a time. + */ +export class StyleTextRangeCommand implements Command { + readonly type = "style-text-range"; + private readonly pageIndex: number; + private readonly runId: string; + private readonly faces: readonly FaceStretch[]; + private readonly wrapWidthPt: number | null; + private prev: RunSnapshot | null = null; + private removed: Array<{ ptr: number; index: number }> = []; + private created: number[] = []; + private shifted: Array<{ ptr: number; dx: number; matrix: Float32Array }> = + []; + private reflow: ReflowWrapCommand | null = null; + + /** `wrapWidthPt` is the width the run's lines rewrap to when a change makes one overflow it; null never rewraps. */ + constructor(opts: { + pageIndex: number; + runId: string; + faces: readonly FaceStretch[]; + wrapWidthPt?: number | null; + }) { + this.pageIndex = opts.pageIndex; + this.runId = opts.runId; + this.faces = opts.faces; + this.wrapWidthPt = opts.wrapWidthPt ?? null; + } + + /** Why this change cannot be made, or null when it can. */ + refusal(doc: EditorDocument): RangeRefusal | null { + const page = doc.page(this.pageIndex); + const run = page.findRun(this.runId); + if (!run) return "unsupported"; + const lines = runLines(doc, page, run); + if (typeof lines === "string") return lines; + const changes = this.changes(doc, page, run, lines).targets; + return piecesRefusal(doc, lines, (piece) => touches(piece, changes)); + } + + /** + * How much of the selection that is not already in its new face that face + * has glyphs for. The rest stays in the font that drew it. + */ + coverage(doc: EditorDocument): "all" | "some" | "none" | "unchanged" { + const page = doc.page(this.pageIndex); + const run = page.findRun(this.runId); + const lines = run && linesOf(doc, page, run); + if (!run || !lines) return "unchanged"; + const { targets, kept } = this.changes(doc, page, run, lines); + if (kept === 0) return targets.size === 0 ? "unchanged" : "all"; + return targets.size === 0 ? "none" : "some"; + } + + apply(doc: EditorDocument): void { + const page = doc.page(this.pageIndex); + const run = page.findRun(this.runId); + this.prev = null; + if (!run) return; + refuseRedrawOfReadOnlyText(run); + const refusal = this.refusal(doc); + if (refusal === "rightToLeft") + throw new RolledBackError(new Error(unsafeRtlEditMessage())); + if (refusal === "needsShaping") + throw new RolledBackError(new Error(cannotRestyleMessage())); + if (refusal) return; + liftRunToPage(doc, page, run); + const lines = linesOf(doc, page, run); + if (!lines) return; + const { targets } = this.changes(doc, page, run, lines); + if (targets.size === 0) return; + + const m = doc.module; + this.prev = snapshotRun(run); + this.removed = []; + this.created = []; + this.shifted = []; + this.reflow = null; + const touched = lines.flatMap((line) => + line.pieces.filter((piece) => touches(piece, targets)), + ); + const order = contentIndices( + m, + page.pagePtr, + touched.map((piece) => piece.ptr), + ); + const origins = charOrigins( + m, + page.pagePtr, + new Map(touched.map((piece) => [piece.ptr, piece.text])), + ); + const spanBefore = measureObjSpanPt(m, collectMemberPtrs(run)); + warmOnPageAdvances(m, page.pagePtr); + + const redrawn = new Map(); + const dropped = droppedCharsOf(() => { + for (const line of lines) { + if (!line.pieces.some((piece) => touches(piece, targets))) continue; + line.pieces = this.redrawLine(doc, page, run, line, targets, { + origins, + order, + redrawn, + }); + } + }); + if (losesLetters(dropped)) { + this.takeBackObjects(doc, page); + restoreRun(run, this.prev); + this.prev = null; + throw new RolledBackError(new Error(missingGlyphsMessage())); + } + updateRunModel(run, lines, redrawn); + const spanAfter = measureObjSpanPt(m, collectMemberPtrs(run)); + if (spanBefore && spanAfter) + run.bounds = { + ...run.bounds, + width: Math.max( + 0, + run.bounds.width + spanAfter.right - spanBefore.right, + ), + }; + run.charPositionsKey = null; + run.dirty = true; + page.markDirty(); + page.markNeedsGenerate(); + if (this.wrapWidthPt !== null && this.wrapWidthPt > 0) { + this.reflow = new ReflowWrapCommand({ + pageIndex: this.pageIndex, + runId: this.runId, + maxWidthPt: this.wrapWidthPt, + keepClearBelow: true, + }); + this.reflow.apply(doc); + } + } + + revert(doc: EditorDocument): void { + if (!this.prev) return; + const page = doc.page(this.pageIndex); + const run = page.findRun(this.runId); + if (!run) return; + this.reflow?.revert(doc); + this.reflow = null; + this.takeBackObjects(doc, page); + restoreRun(run, this.prev); + this.prev = null; + run.charPositionsKey = null; + run.dirty = true; + page.markDirty(); + page.markNeedsGenerate(); + } + + private takeBackObjects(doc: EditorDocument, page: Page): void { + const m = doc.module; + for (const ptr of this.created) + removeAndDestroyObject(m, page.pagePtr, ptr); + for (const { ptr } of this.removed) + m.FPDFPage_InsertObject(page.pagePtr, ptr); + restoreContentOrder(m, page.pagePtr, this.removed); + for (const { ptr, dx, matrix } of [...this.shifted].reverse()) { + transformObject(m, ptr, 1, 0, 0, 1, -dx, 0); + writeMatrix(m, ptr, matrix); + } + this.created = []; + this.removed = []; + this.shifted = []; + } + + /** The face each character of the selection changes to, and how many the face it was given has no glyph for. */ + private changes( + doc: EditorDocument, + page: Page, + run: TextRun, + lines: readonly Line[], + ): { targets: Map; kept: number } { + const m = doc.module; + const fontAt = new Map(); + for (const line of lines) + for (const piece of line.pieces) { + const font = piece.ptr ? m.FPDFTextObj_GetFont(piece.ptr) : 0; + for (let c = 0; c < piece.text.length; c++) + fontAt.set(piece.start + c, font); + } + const targets = new Map(); + const idOf = fontIdNamer(doc); + let kept = 0; + for (const { start, end, face } of this.faces) { + const target = targetOf(face); + const draws = facesDraw(doc, page, face, target); + const faceId = fontIdOfFace(face); + for (let c = Math.max(0, start); c < Math.min(end, run.text.length);) { + const ch = String.fromCodePoint(run.text.codePointAt(c)!); + const at = c; + c += ch.length; + const font = fontAt.get(at); + if (/\s/.test(ch) || font === undefined) continue; + const already = target.fontPtr + ? font === target.fontPtr + : idOf(font) === faceId; + if (already) continue; + if (!draws(ch)) { + kept++; + continue; + } + for (let u = at; u < c; u++) targets.set(u, target); + } + } + return { targets, kept }; + } + + private redrawLine( + doc: EditorDocument, + page: Page, + run: TextRun, + line: Line, + targets: ReadonlyMap, + read: { + origins: ReadonlyMap>; + order: ReadonlyMap; + redrawn: Map; + }, + ): Piece[] { + const m = doc.module; + let offset = 0; + const out: Piece[] = []; + for (const piece of line.pieces) { + if (!touches(piece, targets)) { + if (Math.abs(offset) > 0.001 && piece.ptr) { + const matrix = readMatrix(m, piece.ptr); + if (matrix) { + transformObject(m, piece.ptr, 1, 0, 0, 1, offset, 0); + this.shifted.push({ ptr: piece.ptr, dx: offset, matrix }); + } + } + out.push({ + ...piece, + bounds: { + x: piece.bounds.x + offset, + right: piece.bounds.right + offset, + }, + }); + continue; + } + const source = readTextSource(m, piece.ptr)!; + const units = unitsOf(piece, targets); + const origins = read.origins.get(piece.ptr); + const placed = + origins && units.every((unit) => origins.has(unit.start)) + ? origins + : null; + const index = contentIndices(m, page.pagePtr, [piece.ptr]).get(piece.ptr); + m.FPDFPage_RemoveObject(page.pagePtr, piece.ptr); + this.removed.push({ + ptr: piece.ptr, + index: read.order.get(piece.ptr) ?? index ?? 0, + }); + const drawn: Piece[] = []; + const draw = (unit: Unit, x: number): DrawnUnit => { + const result = drawUnit(doc, page, run, piece, source, unit, x); + drawn.push(...result.pieces); + return result; + }; + if (placed) { + let before: { end: number; penEnd: number } | null = null; + for (const unit of units) { + const origin = placed.get(unit.start)!.x; + // A word split only where its font changes reads as one word only when its parts abut. + if (before?.end === unit.start) offset = before.penEnd - origin; + const result = draw(unit, origin + offset); + offset += result.widthChange; + before = { end: unit.end, penEnd: result.penEnd }; + } + } else { + offset += draw( + { + start: 0, + end: piece.text.length, + targets: pieceTargets(piece, targets), + }, + source.matrix[4] + offset, + ).widthChange; + } + const ptrs = drawn.map((p) => p.ptr); + this.created.push(...ptrs); + if (index !== undefined) + restoreContentOrder( + m, + page.pagePtr, + ptrs.map((ptr, k) => ({ ptr, index: index + k })), + ); + read.redrawn.set(piece.ptr, drawn); + out.push(...drawn); + } + return out; + } +} + +/** The face of each code unit of a piece, a space taking the one before it. */ +function pieceTargets( + piece: Piece, + targets: ReadonlyMap, +): Array { + const out: Array = []; + for (let c = 0; c < piece.text.length; c++) { + const own = targets.get(piece.start + c) ?? null; + out.push(/\s/.test(piece.text[c]) && c > 0 ? out[c - 1] : own); + } + return out; +} + +/** The run's lines, or why none of its pieces can be restyled on their own. */ +function runLines( + doc: EditorDocument, + page: Page, + run: TextRun, +): Line[] | RangeRefusal { + if (run.textReadOnly) return "rightToLeft"; + if (isScanRun(run) || run.scanEdit || rotationFromMatrix(run.matrix)) + return "unsupported"; + return linesOf(doc, page, run) ?? "unsupported"; +} + +/** Why the pieces `restyles` picks cannot be redrawn on their own, or null when they can. */ +function piecesRefusal( + doc: EditorDocument, + lines: readonly Line[], + restyles: (piece: Piece) => boolean, +): RangeRefusal | null { + for (const line of lines) { + const picked = line.pieces.filter(restyles); + if (picked.length === 0) continue; + // A line's later pieces are moved along it, which is only the way it reads when it runs left to right. + if (hasRtl(line.pieces.map((piece) => piece.text).join(""))) + return "rightToLeft"; + if ( + picked.some( + (p) => needsShaping(p.text) || ATTACHES_TO_PREVIOUS.test(p.text), + ) + ) + return "needsShaping"; + for (const piece of picked) { + const at = line.pieces.indexOf(piece); + if (line.pieces[at + 1]?.text === "") return "unsupported"; + const source = readTextSource(doc.module, piece.ptr); + if (!source || !upright(source.matrix)) return "unsupported"; + } + } + return null; +} + +/** Why the characters `range` covers cannot be restyled apart from the rest of `run`, or null when they can. */ +export function rangeRefusal( + doc: EditorDocument, + page: Page, + run: TextRun, + range: TextRange, +): RangeRefusal | null { + const lines = runLines(doc, page, run); + if (typeof lines === "string") return lines; + return piecesRefusal( + doc, + lines, + (piece) => + piece.start < range.end && piece.start + piece.text.length > range.start, + ); +} + +/** + * The stretches of a piece drawn apart: each run of letters in one face, split + * at spaces. Each goes where its first letter stood, so the words a change + * leaves alone keep their places on a justified or kerned line. + */ +function unitsOf(piece: Piece, targets: ReadonlyMap): Unit[] { + const units: Unit[] = []; + let open: Unit | null = null; + for (let c = 0; c < piece.text.length; c++) { + const ch = piece.text[c]; + if (/\s/.test(ch)) { + open = null; + continue; + } + const target = targets.get(piece.start + c) ?? null; + const low = c > 0 && /[\udc00-\udfff]/.test(ch); + if (open && (low || open.targets[open.targets.length - 1] === target)) { + open.end = c + 1; + open.targets.push(target); + } else { + open = { start: c, end: c + 1, targets: [target] }; + units.push(open); + } + } + return units; +} + +interface DrawnUnit { + pieces: Piece[]; + widthChange: number; + /** + * Where a letter drawn straight after the unit starts: its pen position plus + * the run's letter spacing, as within one object, not its ink edge. + */ + penEnd: number; +} + +function drawUnit( + doc: EditorDocument, + page: Page, + run: TextRun, + piece: Piece, + source: TextSource, + unit: Unit, + x: number, +): DrawnUnit { + const m = doc.module; + const text = piece.text.slice(unit.start, unit.end); + const size = source.size * Math.hypot(source.matrix[0], source.matrix[1]); + const ownFallback = + deviceFamilyOf(doc, source.font) ?? + fallbackFamilyFor( + `pdf:${source.font}:${stripSubsetTag(readFontName(m, source.font) ?? "")}`, + ); + const fill: RGBA = source.fill ?? run.fill; + const common = { + doc, + page, + y: source.matrix[5], + fontSize: size, + fill, + renderMode: source.renderMode, + stroke: source.stroke, + strokeWidth: source.strokeWidth ?? undefined, + tags: uniformTags(readTagMarks(m, piece.ptr)), + charSpacingPt: run.charSpacingPt, + }; + const spans: FontSpan[] = []; + unit.targets.forEach((target, i) => { + const font = target ? target.fontPtr : source.font; + const family = target ? target.fallbackFamily : ownFallback; + const last = spans[spans.length - 1]; + if (last && last.fontPtr === font && last.fallbackFamily === family) + last.end = i + 1; + else spans.push({ end: i + 1, fontPtr: font, fallbackFamily: family }); + }); + const restyled = unit.targets.some(Boolean); + const outTexts: string[] = []; + const ptrs = emitTextLine({ + ...common, + text, + x, + originalFontPtr: spans.length === 1 ? spans[0].fontPtr : 0, + originalFontSubset: isSubsetFont(m, spans[0].fontPtr), + fallbackFamily: spans[0].fallbackFamily, + fontSpans: spans.length > 1 ? spans : undefined, + outTexts, + }); + let widthChange = 0; + if (restyled) { + // Against the letters drawn as they were from the same place, ink to ink: + // a subset font's advances cannot be looked up by character. What that + // draw drops is no loss. + let before = 0; + droppedCharsOf(() => { + const probe = emitTextLine({ + ...common, + text, + x, + originalFontPtr: source.font, + originalFontSubset: isSubsetFont(m, source.font), + fallbackFamily: ownFallback, + }); + before = measureObjSpanPt(m, probe)?.right ?? x; + for (const ptr of probe) removeAndDestroyObject(m, page.pagePtr, ptr); + }); + widthChange = (measureObjSpanPt(m, ptrs)?.right ?? x) - before; + } + return { + pieces: placedPieces(m, ptrs, outTexts, text, piece.start + unit.start, x), + widthChange, + penEnd: drawnEndPt(m, ptrs, outTexts, size) + run.charSpacingPt, + }; +} + +function placedPieces( + m: WrappedPdfiumModule, + ptrs: readonly number[], + texts: readonly string[], + text: string, + start: number, + x: number, +): Piece[] { + let cursor = 0; + return ptrs.map((ptr, i) => { + const carried = (texts[i] ?? "").trim(); + const at = carried ? text.indexOf(carried, cursor) : -1; + const from = at >= 0 ? at : cursor; + const piece = carried && at >= 0 ? carried : text.slice(cursor); + cursor = from + piece.length; + const span = measureObjSpanPt(m, [ptr]); + return { + ptr, + text: piece, + start: start + from, + bounds: span ? { x: span.left, right: span.right } : { x, right: x }, + }; + }); +} + +/** The run's pieces line by line, each with where its text sits in the run's; null when they cannot be matched to it. */ +function linesOf(doc: EditorDocument, page: Page, run: TextRun): Line[] | null { + const m = doc.module; + const boundsOf = (ptr: number) => { + const span = ptr ? measureObjSpanPt(m, [ptr]) : null; + return span ? { x: span.left, right: span.right } : { x: 0, right: 0 }; + }; + let lines: Line[]; + if (run.paragraphLineSlots.length > 0) { + lines = run.paragraphLineSlots.map((slot, i) => ({ + slot: i, + pieces: slot.mergedFromPtrs.map((ptr, k) => ({ + ptr, + text: slot.mergedFromTexts[k] ?? "", + start: slot.startChar + (slot.mergedFromCharStarts[k] ?? 0), + bounds: slot.mergedFromBounds[k] ?? boundsOf(ptr), + })), + })); + } else { + const parallel = + run.mergedFromPtrs.length > 0 && + run.mergedFromTexts.length === run.mergedFromPtrs.length && + run.mergedFromCharStarts.length === run.mergedFromPtrs.length; + const own = parallel + ? run + : piecesFromObjects( + m, + page.pagePtr, + collectMemberPtrs(run).filter(Boolean), + run.text, + ); + if (!own) return null; + const byLine = new Map(); + own.mergedFromPtrs.forEach((ptr, k) => { + const start = own.mergedFromCharStarts[k] ?? 0; + const lineIndex = run.text.slice(0, start).split("\n").length - 1; + const pieces = byLine.get(lineIndex) ?? []; + pieces.push({ + ptr, + text: own.mergedFromTexts[k] ?? "", + start, + bounds: (parallel && run.mergedFromBounds[k]) || boundsOf(ptr), + }); + byLine.set(lineIndex, pieces); + }); + lines = [...byLine.keys()] + .sort((a, b) => a - b) + .map((key) => ({ slot: -1, pieces: byLine.get(key)! })); + } + const spelled = lines.every((line) => + line.pieces.every( + (piece) => + run.text.slice(piece.start, piece.start + piece.text.length) === + piece.text, + ), + ); + return spelled ? lines : null; +} + +/** Each stretch of the run's text drawn in one font, by the font of the piece drawing it; a space takes the font before it. */ +function fontStretchesOf( + doc: EditorDocument, + page: Page, + run: TextRun, +): FontStretch[] { + const m = doc.module; + const lines = isScanRun(run) || run.scanEdit ? null : linesOf(doc, page, run); + const fontAt = new Array(run.text.length).fill(0); + for (const line of lines ?? []) + for (const piece of line.pieces) { + const font = piece.ptr ? m.FPDFTextObj_GetFont(piece.ptr) : 0; + for (let c = 0; c < piece.text.length; c++) + if (piece.start + c < fontAt.length) fontAt[piece.start + c] = font; + } + for (let c = 1; c < fontAt.length; c++) fontAt[c] ||= fontAt[c - 1]; + for (let c = fontAt.length - 2; c >= 0; c--) fontAt[c] ||= fontAt[c + 1]; + const runFont = documentFontHandle(run.fontId); + const idOf = fontIdNamer(doc); + const stretches: FontStretch[] = []; + for (let c = 0; c < fontAt.length;) { + const font = fontAt[c]; + let end = c + 1; + while (end < fontAt.length && fontAt[end] === font) end++; + stretches.push({ + start: c, + end, + fontId: !font || font === runFont ? run.fontId : idOf(font), + }); + c = end; + } + return stretches; +} + +/** + * The fonts drawing the selected characters of `run`, one entry per font, + * spaces left out unless nothing else is selected. + */ +export function rangeFontIds( + doc: EditorDocument, + page: Page, + run: TextRun, + range: TextRange, +): string[] { + const stretches = fontStretchesOf(doc, page, run).filter( + (s) => s.end > range.start && s.start < range.end, + ); + const inked = stretches.filter((s) => + /\S/.test( + run.text.slice( + Math.max(s.start, range.start), + Math.min(s.end, range.end), + ), + ), + ); + return [ + ...new Set((inked.length > 0 ? inked : stretches).map((s) => s.fontId)), + ]; +} + +/** The selected stretches of `run`, each with the font that draws it, spaces left with their neighbours. */ +export function selectedFontStretches( + doc: EditorDocument, + page: Page, + run: TextRun, + range: TextRange, +): FontStretch[] { + return fontStretchesOf(doc, page, run) + .map((s) => ({ + ...s, + start: Math.max(s.start, range.start), + end: Math.min(s.end, range.end), + })) + .filter( + (s) => s.end > s.start && /\S/.test(run.text.slice(s.start, s.end)), + ); +} + +/** Names fonts as {@link fontIdOf} does, each font once. */ +function fontIdNamer(doc: EditorDocument): (font: number) => string { + const names = new Map(); + return (font) => { + let name = names.get(font); + if (name === undefined) names.set(font, (name = fontIdOf(doc, font))); + return name; + }; +} + +/** The fontId a font a run is drawn in goes by, as the reader or a font change would name it. */ +function fontIdOf(doc: EditorDocument, font: number): string { + const device = deviceFamilyOf(doc, font); + if (device) return deviceFontId(device); + const read = documentFontIdAt(font); + if (read) return read; + const name = stripSubsetTag(readFontName(doc.module, font) ?? ""); + if (name && nearestStandardFont(name) === name) return base14FontId(name); + noteDocumentFontStyle(doc.module, font); + return documentFontIdAt(font) ?? `pdf:${font}:${name}`; +} + +function fontIdOfFace(face: string): string { + if (documentFontHandle(face)) return face; + return nearestStandardFont(face) === face + ? base14FontId(face) + : deviceFontId(face); +} + +function targetOf(face: string): Target { + const handle = documentFontHandle(face); + return handle + ? { fontPtr: handle, fallbackFamily: fallbackFamilyFor(face) } + : { fontPtr: 0, fallbackFamily: face }; +} + +function facesDraw( + doc: EditorDocument, + page: Page, + face: string, + target: Target, +): (ch: string) => boolean { + if (target.fontPtr) + return (ch) => + charcodesResolveFully( + doc.module, + target.fontPtr, + ch, + page.pagePtr, + doc.docPtr, + ); + const covers = familyCoverage(doc, face); + return covers ? (ch) => covers(ch.codePointAt(0)!) : () => true; +} + +function touches(piece: Piece, targets: ReadonlyMap): boolean { + for (let c = 0; c < piece.text.length; c++) + if (targets.has(piece.start + c)) return true; + return false; +} + +/** Unrotated, unslanted and scaled alike both ways, as a redrawn word is: a word processor's 0.2% stretch is within that. */ +function upright(matrix: Float32Array): boolean { + const [a, b, c, d] = matrix; + return ( + a > 0 && + Math.abs(b) < 1e-3 * a && + Math.abs(c) < 1e-3 * a && + Math.abs(a - d) < 0.01 * a + ); +} + +function updateRunModel( + run: TextRun, + lines: readonly Line[], + redrawn: ReadonlyMap, +): void { + for (const line of lines) { + if (line.slot < 0) continue; + const slot = run.paragraphLineSlots[line.slot]; + slot.mergedFromPtrs = line.pieces.map((p) => p.ptr); + slot.mergedFromTexts = line.pieces.map((p) => p.text); + slot.mergedFromBounds = line.pieces.map((p) => ({ ...p.bounds })); + slot.mergedFromCharStarts = line.pieces.map( + (p) => p.start - slot.startChar, + ); + } + const all = lines.flatMap((line) => line.pieces); + const own = run.paragraphLineSlots.length > 0 ? lines[0].pieces : all; + run.mergedFromPtrs = own.map((p) => p.ptr); + run.mergedFromTexts = own.map((p) => p.text); + run.mergedFromBounds = own.map((p) => ({ ...p.bounds })); + const ownStart = run.paragraphLineSlots[0]?.startChar ?? 0; + run.mergedFromCharStarts = own.map((p) => p.start - ownStart); + if ( + run.paragraphLineSlots.length > 0 || + run.paragraphLeafPtrs.length > 0 || + run.paragraphMemberPtrs.length > 0 + ) { + run.paragraphLeafPtrs = all.map((p) => p.ptr); + run.paragraphLeafContainers = all.map(() => 0); + } + const replaced = (ptr: number) => redrawn.get(ptr)?.[0]?.ptr ?? ptr; + run.paragraphMemberPtrs = run.paragraphMemberPtrs.map(replaced); + run.pdfiumObjPtr = replaced(run.pdfiumObjPtr); +} + +function snapshotRun(run: TextRun): RunSnapshot { + return { + bounds: { ...run.bounds }, + pdfiumObjPtr: run.pdfiumObjPtr, + mergedFromPtrs: [...run.mergedFromPtrs], + mergedFromTexts: [...run.mergedFromTexts], + mergedFromBounds: run.mergedFromBounds.map((b) => ({ ...b })), + mergedFromCharStarts: [...run.mergedFromCharStarts], + paragraphMemberPtrs: [...run.paragraphMemberPtrs], + paragraphLeafPtrs: [...run.paragraphLeafPtrs], + paragraphLeafContainers: [...run.paragraphLeafContainers], + paragraphLineSlots: run.paragraphLineSlots.map(cloneParagraphLineSlot), + }; +} + +function restoreRun(run: TextRun, snap: RunSnapshot): void { + run.bounds = { ...snap.bounds }; + run.pdfiumObjPtr = snap.pdfiumObjPtr; + run.mergedFromPtrs = [...snap.mergedFromPtrs]; + run.mergedFromTexts = [...snap.mergedFromTexts]; + run.mergedFromBounds = snap.mergedFromBounds.map((b) => ({ ...b })); + run.mergedFromCharStarts = [...snap.mergedFromCharStarts]; + run.paragraphMemberPtrs = [...snap.paragraphMemberPtrs]; + run.paragraphLeafPtrs = [...snap.paragraphLeafPtrs]; + run.paragraphLeafContainers = [...snap.paragraphLeafContainers]; + run.paragraphLineSlots = snap.paragraphLineSlots.map(cloneParagraphLineSlot); +} + +function cannotRestyleMessage(): string { + return i18n.t( + "pdfTextEditor.fontPicker.needsShaping", + "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font.", + ); +} + +function missingGlyphsMessage(): string { + return i18n.t( + "pdfTextEditor.fontPicker.missingGlyphs", + "This font is missing some of the selected characters, and they could not be kept in their current font. The text was left unchanged.", + ); +} + +/** + * The run and the characters of it the selection holds, when they leave some + * of its letters out; null when nothing within a run is selected or the whole + * of one is, which a change applies to as a box. + */ +export function selectedPartOfRun( + doc: EditorDocument | null, + selection: { runIds: readonly string[]; textRange: TextRange | null }, +): SelectedPart | null { + const range = selection.textRange; + if (!doc || !range || selection.runIds.length !== 1) return null; + for (const page of doc.loadedPages()) { + const run = page.findRun(selection.runIds[0]); + if (!run) continue; + const start = Math.max(0, Math.min(range.start, run.text.length)); + const end = Math.max(start, Math.min(range.end, run.text.length)); + if (end === start) return null; + const outside = run.text.slice(0, start) + run.text.slice(end); + return /\S/.test(outside) ? { page, run, range: { start, end } } : null; + } + return null; +} diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css index b05caf2472b..02614f6b237 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css @@ -36,6 +36,13 @@ padding-bottom: 0.125rem; } +.pdf-editor-topbar__format { + display: flex; + align-items: center; + gap: 0.25rem; + flex: 0 0 auto; +} + .pdf-editor-topbar__file { display: flex; align-items: center; diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx index 6041d5efd7e..2578294f88b 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx @@ -1,4 +1,10 @@ -import { useCallback, useRef, useState } from "react"; +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; import { Icon } from "@editor/ui/Icon"; import { Group, Menu, Popover, Tooltip } from "@mantine/core"; import { useTranslation } from "react-i18next"; @@ -75,7 +81,7 @@ function FormatMenu({ controller }: { controller: Controller }) { - + @@ -113,6 +119,44 @@ export function EditorTopBar({ const barRef = useRef(null); const barWidth = useElementWidth(barRef); const compact = barWidth !== null && barWidth < COMPACT_BELOW_PX; + const bandRef = useRef(null); + // The bar width the formatting controls need inline; 0 until they are seen not to fit. + const [formatNeeds, setFormatNeeds] = useState(0); + const foldFormat = compact || (barWidth !== null && barWidth < formatNeeds); + const formatShape = [ + controller.hasRunSelection, + controller.hasImageSelection, + controller.state.weights.length > 0, + ].join(); + // Other controls may fit again; measuring them inline happens before paint. + useLayoutEffect(() => setFormatNeeds(0), [formatShape]); + // The controls can grow after they mount (the device-fonts button, a loader), which re-renders only them. + const [formatGroup, setFormatGroup] = useState(null); + const [formatWidth, setFormatWidth] = useState(0); + useEffect(() => { + if (!formatGroup || typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(([entry]) => + setFormatWidth(entry.contentRect.width), + ); + observer.observe(formatGroup); + return () => observer.disconnect(); + }, [formatGroup]); + useLayoutEffect(() => { + const band = bandRef.current; + if (!band || barWidth === null || foldFormat || !hasSelection) return; + // The colour field widens while its picker is open; folding then would + // remount the controls and close the picker under the pointer. + if (formatGroup?.querySelector('[aria-expanded="true"]')) return; + const overflow = band.scrollWidth - band.clientWidth; + if (overflow > 0) setFormatNeeds(Math.ceil(barWidth + overflow)); + }, [ + barWidth, + foldFormat, + hasSelection, + formatGroup, + formatWidth, + formatShape, + ]); const addTextLabel = addTextArmed ? t("pdfTextEditor.sidebar.clickPageToAddText", "Click page to add text") @@ -149,7 +193,7 @@ export function EditorTopBar({ {/* Shown from the first frame, idle until the document is read, so the bar does not pop in after the load. */} -
+
- {compact ? ( + {foldFormat ? ( ) : ( - +
+ +
)} )} diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx index f3b42b35ec2..aa9e0871864 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx @@ -14,6 +14,7 @@ import { forgetServerFontList, } from "@editor/tools/pdfTextEditor/util/serverFonts"; import { resetLocalFontsCache } from "@editor/tools/pdfTextEditor/util/localFonts"; +import { documentFamilies } from "@editor/tools/pdfTextEditor/util/fontFaces"; const MANIFEST = { families: [ @@ -79,15 +80,49 @@ describe("font picker server fonts", () => { expect(get).toHaveBeenCalledWith(SERVER_FONTS_URL, expect.anything()); }); - it("offers the bold cut of a server family that has one", async () => { + it("lists a server family once, leaving its bold face to the Bold toggle", async () => { const onChange = vi.fn(async () => null); const input = renderPicker(onChange); fireEvent.click(input); - fireEvent.click(await screen.findByText("Acme Sans Bold")); + fireEvent.click(await screen.findByText("Acme Sans")); + + await waitFor(() => expect(onChange).toHaveBeenCalledWith("Acme Sans")); + expect(screen.queryByText("Acme Sans Bold")).not.toBeInTheDocument(); + }); + + it("lists each built-in family once", async () => { + const input = renderPicker(async () => null); + + fireEvent.click(input); + await screen.findByText("Acme Sans"); + + const options = screen.getAllByRole("option").map((o) => o.textContent); + expect(options).toEqual(["Helvetica", "Times", "Courier", "Acme Sans"]); + }); + + it("lists a family that has only a bold face under its family name", async () => { + get.mockImplementation(async (url: string) => { + if (url !== SERVER_FONTS_URL) throw new Error(`unexpected ${url}`); + return { + data: { + families: [ + { + family: "Acme Display Bold", + faces: [{ ...MANIFEST.families[0].faces[0], id: "3".repeat(64) }], + }, + ], + }, + }; + }); + const onChange = vi.fn(async () => null); + const input = renderPicker(onChange); + + fireEvent.click(input); + fireEvent.click(await screen.findByText("Acme Display")); await waitFor(() => - expect(onChange).toHaveBeenCalledWith("Acme Sans Bold"), + expect(onChange).toHaveBeenCalledWith("Acme Display Bold"), ); }); @@ -118,7 +153,7 @@ describe("font picker server fonts", () => { const input = renderPicker(onChange); fireEvent.click(input); - fireEvent.click(await screen.findByText("Acme Sans Bold")); + fireEvent.click(await screen.findByText("Acme Sans")); await waitFor(() => expect(alert).toHaveBeenCalledWith({ @@ -148,7 +183,8 @@ describe("font picker server fonts", () => { fireEvent.click(input); - expect(await screen.findAllByText("Acme Sans Bold")).toHaveLength(1); + expect(await screen.findAllByText("Acme Sans")).toHaveLength(1); + expect(screen.queryByText("Acme Sans Bold")).not.toBeInTheDocument(); }); it("raises nothing when the font applies", async () => { @@ -200,10 +236,10 @@ describe("font picker server fonts", () => { fireEvent.click(input); fireEvent.change(input, { target: { value: "Acme" } }); - fireEvent.click(await screen.findByText("Acme Sans Bold")); + fireEvent.click(await screen.findByText("Acme Sans")); await waitFor(() => expect(input).not.toBeDisabled()); - expect(input).toHaveValue("Acme Sans Bold"); + expect(input).toHaveValue("Acme Sans"); }); it("names the font a scan was matched to, not a document font", async () => { @@ -310,4 +346,29 @@ describe("font picker document font", () => { expect(onChange).toHaveBeenCalledWith("pdf:7:Garamond"), ); }); + + it("lists the document's faces of the text's own family once", async () => { + render( + + + , + ); + const input = screen.getByTestId("pdf-editor-font-family"); + expect(input).toHaveValue("Calibri"); + + fireEvent.click(input); + + expect( + await screen.findAllByRole("option", { name: "Calibri" }), + ).toHaveLength(1); + }); }); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx index 102a52f165b..82e3a022fa4 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx @@ -22,18 +22,26 @@ import type { import { useTranslation } from "react-i18next"; import { Button } from "@editor/ui/Button"; import { Icon } from "@editor/ui/Icon"; -import { alert } from "@editor/components/toast"; import { useServerFontsGroupLabel } from "@editor/tools/pdfTextEditor/hooks/useServerFontsGroupLabel"; import type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions"; -import { familyOf } from "@editor/tools/pdfTextEditor/util/fontFamily"; +import { useFontChangeWarning } from "@editor/tools/pdfTextEditor/components/fontPickFailure"; +import { + familyOf, + isDocumentFontId, +} from "@editor/tools/pdfTextEditor/util/fontFamily"; +import { + BUILT_IN_FAMILIES, + documentFamilies as groupDocumentFonts, + externalFamilies, + fontFamilyKey, + type FontFamilyEntry, +} from "@editor/tools/pdfTextEditor/util/fontFaces"; import { - familyOptions, isLocalFontAccessSupported, listLocalFontsIfGranted, loadedLocalFonts, retryLocalFonts, subscribeLocalFonts, - type FontFamilyOption, } from "@editor/tools/pdfTextEditor/util/localFonts"; import { loadedServerFonts, @@ -41,58 +49,26 @@ import { subscribeServerFonts, } from "@editor/tools/pdfTextEditor/util/serverFonts"; -/** Base-14 families, renderable by every viewer without embedding. */ -export const BUILT_IN_FONT_FAMILIES: FontFamilyOption[] = [ - { value: "Helvetica", label: "Helvetica" }, - { value: "Helvetica-Bold", label: "Helvetica Bold" }, - { value: "Times-Roman", label: "Times Roman" }, - { value: "Times-Bold", label: "Times Bold" }, - { value: "Times-Italic", label: "Times Italic" }, - { value: "Courier", label: "Courier" }, - { value: "Courier-Bold", label: "Courier Bold" }, -]; - -const BUILT_IN_NAMES = BUILT_IN_FONT_FAMILIES.map((option) => option.value); +function itemOf(entry: FontFamilyEntry): ComboboxItem { + return { value: entry.value, label: entry.label }; +} -const PICK_FAILURE_TEXT: Record = { - needsShaping: [ - "pdfTextEditor.fontPicker.needsShaping", - "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font.", - ], - serverFontFailed: [ - "pdfTextEditor.fontPicker.serverFontFailed", - "That server font could not be downloaded. The text was left unchanged.", - ], - embeddingForbidden: [ - "pdfTextEditor.fontPicker.embeddingForbidden", - "This font's licence does not allow embedding it in a PDF. The text was left unchanged.", - ], - embedFailed: [ - "pdfTextEditor.fontPicker.embedFailed", - "This font could not be embedded in the PDF. The text was left unchanged.", - ], - noGlyphs: [ - "pdfTextEditor.fontPicker.noGlyphs", - "This font has no characters for the selected text. The text was left unchanged.", - ], - missingGlyphs: [ - "pdfTextEditor.fontPicker.missingGlyphs", - "This font is missing some of the selected characters, and they could not be kept in their current font. The text was left unchanged.", - ], - documentFontCannotDraw: [ - "pdfTextEditor.fontPicker.documentFontCannotDraw", - "The editor can't draw this text in the document's own font, so it was left in its current font.", - ], - someLeftUnchanged: [ - "pdfTextEditor.fontPicker.someLeftUnchanged", - "This font does not have the characters for some of the selected text. That text was left unchanged.", - ], -}; +function withoutKeys( + entries: FontFamilyEntry[], + taken: FontFamilyEntry[], +): FontFamilyEntry[] { + const keys = new Set(taken.map((entry) => entry.key)); + return entries.filter((entry) => !keys.has(entry.key)); +} type DeviceFontNotice = "unavailable" | "none"; interface FontFamilySelectProps { value: string | null; + /** The selection's fontId, which names the family its face belongs to; null for scanned text. */ + fontId?: string | null; + /** The document's own fonts as families, offered for the selection's family and the one it can be restored to. */ + documentFamilies?: FontFamilyEntry[]; /** Set for scanned text: `value` is the matched font (null while none is in force) and `label` the matcher's name for it. */ scanned?: { label?: string }; /** The document font the selection was changed from, offered so the text can go back to it. */ @@ -101,19 +77,25 @@ interface FontFamilySelectProps { mixed?: boolean; disabled?: boolean; touch?: boolean; + /** False renders the list inside the toolbar's own popover rather than portalled out of it. */ + withinPortal?: boolean; } /** Font picker. Device fonts are additive: no prompt until the user asks. */ export function FontFamilySelect({ value, + fontId = null, + documentFamilies = [], scanned, documentFontId = null, onChange, mixed = false, disabled = false, touch = false, + withinPortal = true, }: FontFamilySelectProps) { const { t } = useTranslation(); + const warnAbout = useFontChangeWarning(); const [loading, setLoading] = useState(false); const [applying, setApplying] = useState(false); const [notice, setNotice] = useState(null); @@ -134,15 +116,15 @@ export function FontFamilySelect({ ); const serverOptions = useMemo( - () => familyOptions(serverFonts, BUILT_IN_NAMES), + () => withoutKeys(externalFamilies(serverFonts), BUILT_IN_FAMILIES), [serverFonts], ); const deviceOptions = useMemo( () => - familyOptions(localFonts, [ - ...BUILT_IN_NAMES, - ...serverOptions.map((option) => option.value), + withoutKeys(externalFamilies(localFonts), [ + ...BUILT_IN_FAMILIES, + ...serverOptions, ]), [localFonts, serverOptions], ); @@ -166,44 +148,78 @@ export function FontFamilySelect({ if (supported && !loadedLocalFonts()) void listLocalFontsIfGranted(); }, [supported]); - const isKnown = useCallback( - (family: string) => - [...BUILT_IN_FONT_FAMILIES, ...serverOptions, ...deviceOptions].some( - (option) => option.value === family, - ), + const listed = useMemo( + () => [...BUILT_IN_FAMILIES, ...serverOptions, ...deviceOptions], [serverOptions, deviceOptions], ); - // The run's own face when we hold no bytes for it. Shown so the user can see - // what the text IS, listed disabled so picking it can't substitute Helvetica. - const documentFamily = useMemo( - () => (!mixed && value && !isKnown(value) ? value : null), - [mixed, value, isKnown], + const familyHolding = useCallback( + (face: string | null) => + face && isDocumentFontId(face) + ? (documentFamilies.find((entry) => + entry.faces.some((f) => f.value === face), + ) ?? + groupDocumentFonts([face])[0] ?? + null) + : null, + [documentFamilies], + ); + + const restoreFamily = useMemo( + () => familyHolding(documentFontId), + [familyHolding, documentFontId], + ); + + const currentKey = useMemo( + () => (mixed || !value ? null : fontFamilyKey(fontId ?? value)), + [mixed, value, fontId], + ); + + // The run's own family when no other list names it, so the user can see what the text IS. + const currentDocumentFamily = useMemo(() => { + if (!currentKey || listed.some((entry) => entry.key === currentKey)) + return null; + return ( + familyHolding(fontId) ?? + documentFamilies.find((entry) => entry.key === currentKey) ?? + null + ); + }, [currentKey, listed, familyHolding, fontId, documentFamilies]); + + // Listed disabled so picking a face we hold no bytes for can't substitute Helvetica. + const unknownFamily = useMemo( + () => + currentKey && + value && + !currentDocumentFamily && + restoreFamily?.key !== currentKey && + !listed.some((entry) => entry.key === currentKey) + ? value + : null, + [currentKey, value, currentDocumentFamily, restoreFamily, listed], ); const data = useMemo(() => { + const documentItems: ComboboxItem[] = []; + if (restoreFamily) documentItems.push(itemOf(restoreFamily)); + // The text is already in this family and the toggles move it between its faces, so the entry names it and does nothing. + if (currentDocumentFamily && currentDocumentFamily !== restoreFamily) + documentItems.push({ ...itemOf(currentDocumentFamily), disabled: true }); + // Always list the current font: a Select whose value has no option filters by stale search text. + if (unknownFamily) + documentItems.push({ + value: unknownFamily, + label: scanned?.label ?? unknownFamily, + disabled: true, + }); if ( serverOptions.length === 0 && deviceOptions.length === 0 && - !documentFamily && - !documentFontId + documentItems.length === 0 ) { - return BUILT_IN_FONT_FAMILIES; + return BUILT_IN_FAMILIES.map(itemOf); } const groups: ComboboxItemGroup[] = []; - // Always list the current font: a Select whose value has no option filters by stale search text. - const documentItems: ComboboxItem[] = []; - if (documentFontId) - documentItems.push({ - value: documentFontId, - label: familyOf(documentFontId), - }); - if (documentFamily) - documentItems.push({ - value: documentFamily, - label: scanned?.label ?? documentFamily, - disabled: true, - }); if (documentItems.length > 0) { groups.push({ group: scanned @@ -214,45 +230,55 @@ export function FontFamilySelect({ } groups.push({ group: t("pdfTextEditor.fontPicker.builtInGroup", "Built-in fonts"), - items: BUILT_IN_FONT_FAMILIES, + items: BUILT_IN_FAMILIES.map(itemOf), }); if (serverOptions.length > 0) { groups.push({ group: serverGroupLabel, - items: serverOptions, + items: serverOptions.map(itemOf), }); } if (deviceOptions.length > 0) { groups.push({ group: t("pdfTextEditor.fontPicker.deviceGroup", "Device fonts"), - items: deviceOptions, + items: deviceOptions.map(itemOf), }); } return groups; }, [ serverOptions, deviceOptions, - documentFamily, - documentFontId, + restoreFamily, + currentDocumentFamily, + unknownFamily, scanned, serverGroupLabel, t, ]); - const pickFailureText = useCallback( - (failure: FontPickFailure): string => { - const [key, fallback] = PICK_FAILURE_TEXT[failure]; - return t(key, fallback); - }, - [t], - ); - // Mantine shows nothing for a value with no matching option; the document // font is in `data` precisely so a recognised face still gets named. const selected = useMemo(() => { - if (mixed || !value) return null; - return isKnown(value) || documentFamily === value ? value : null; - }, [mixed, value, isKnown, documentFamily]); + if (!currentKey) return null; + if (unknownFamily) return unknownFamily; + const candidates = [...listed, currentDocumentFamily, restoreFamily].filter( + (entry): entry is FontFamilyEntry => entry !== null, + ); + const faceNames = fontId ? [fontId, familyOf(fontId)] : [value]; + const entry = + candidates.find((candidate) => + candidate.faces.some((face) => faceNames.includes(face.value)), + ) ?? candidates.find((candidate) => candidate.key === currentKey); + return entry?.value ?? null; + }, [ + currentKey, + unknownFamily, + listed, + currentDocumentFamily, + restoreFamily, + fontId, + value, + ]); const selectedLabel = useMemo(() => { if (!selected) return ""; @@ -273,20 +299,13 @@ export function FontFamilySelect({ setNotice(null); setApplying(true); try { - const failure = await onChange(family); - if (failure) { - alert({ - alertType: "warning", - title: pickFailureText(failure), - expandable: false, - }); - } + await warnAbout(() => onChange(family)); } finally { setApplying(false); setSearch(selectedLabelRef.current); } }, - [onChange, pickFailureText], + [onChange, warnAbout], ); const placeholder = useMemo(() => { @@ -308,6 +327,7 @@ export function FontFamilySelect({ w={touch ? undefined : 138} style={touch ? { flex: 1, minWidth: 0 } : { flexShrink: 0 }} searchable + comboboxProps={{ withinPortal }} data={data} value={selected} searchValue={search} diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx index 92b17ee0f94..9e99ac8e7c4 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx @@ -70,6 +70,13 @@ function shortcutSections(t: TFunction): Section[] { "Group selected runs into one paragraph", ), }, + { + bindings: [mod("KeyB"), mod("KeyI")], + description: t( + "pdfTextEditor.help.editing.boldItalicDesc", + "Bold / Italic, for the selected words or the whole box", + ), + }, { bindings: [mod("KeyD")], description: t( diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx index 9279bc70f4c..b498af24be8 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx @@ -543,11 +543,7 @@ export const PageView = memo(function PageView({ findRange={findMatch?.runId === run.id ? findMatch.range : null} onSelect={(shiftKey) => onSelectRun(run.id, shiftKey)} onEdit={(nextText) => onEditRun(page.pageIndex, run.id, nextText)} - onTextRangeChange={ - ACCESSIBILITY_EDITING - ? (range) => onSelectRunText?.(run.id, range) - : undefined - } + onTextRangeChange={(range) => onSelectRunText?.(run.id, range)} textRange={ selectedRunIds.length === 1 && selectedRunIds[0] === run.id ? selectedTextRange diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/fontPickFailure.ts b/frontend/src/editor/core/tools/pdfTextEditor/components/fontPickFailure.ts new file mode 100644 index 00000000000..a3e30571754 --- /dev/null +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/fontPickFailure.ts @@ -0,0 +1,75 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { alert } from "@editor/components/toast"; +import type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions"; + +const PICK_FAILURE_TEXT: Record = { + needsShaping: [ + "pdfTextEditor.fontPicker.needsShaping", + "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font.", + ], + serverFontFailed: [ + "pdfTextEditor.fontPicker.serverFontFailed", + "That server font could not be downloaded. The text was left unchanged.", + ], + embeddingForbidden: [ + "pdfTextEditor.fontPicker.embeddingForbidden", + "This font's licence does not allow embedding it in a PDF. The text was left unchanged.", + ], + embedFailed: [ + "pdfTextEditor.fontPicker.embedFailed", + "This font could not be embedded in the PDF. The text was left unchanged.", + ], + noGlyphs: [ + "pdfTextEditor.fontPicker.noGlyphs", + "This font has no characters for the selected text. The text was left unchanged.", + ], + missingGlyphs: [ + "pdfTextEditor.fontPicker.missingGlyphs", + "This font is missing some of the selected characters, and they could not be kept in their current font. The text was left unchanged.", + ], + documentFontCannotDraw: [ + "pdfTextEditor.fontPicker.documentFontCannotDraw", + "The editor can't draw this text in the document's own font, so it was left in its current font.", + ], + someLeftUnchanged: [ + "pdfTextEditor.fontPicker.someLeftUnchanged", + "This font does not have the characters for some of the selected text. That text was left unchanged.", + ], + closestMatch: [ + "pdfTextEditor.fontPicker.closestMatch", + "This font is missing some of the selected letters, so they are drawn in the closest matching font.", + ], + styleUnavailable: [ + "pdfTextEditor.fontPicker.styleUnavailable", + "The selected text has no version of its font in that style, so it was left unchanged.", + ], + styleSkipped: [ + "pdfTextEditor.fontPicker.styleSkipped", + "Some of the selected text has no version of its font in that style, so it was left unchanged.", + ], + partOfRunUnsupported: [ + "pdfTextEditor.fontPicker.partOfRunUnsupported", + "This text can only be restyled as a whole. Select the box instead of some of its words.", + ], +}; + +/** Applies a font or style change and warns about whatever it could not do as asked. */ +export function useFontChangeWarning(): ( + change: () => void | Promise, +) => Promise { + const { t } = useTranslation(); + return useCallback( + async (change) => { + const failure = await change(); + if (!failure) return; + const [key, fallback] = PICK_FAILURE_TEXT[failure]; + alert({ + alertType: "warning", + title: t(key, fallback), + expandable: false, + }); + }, + [t], + ); +} diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx index 953c3ed35f1..acad60bea6e 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx @@ -1,8 +1,16 @@ import { MantineProvider } from "@mantine/core"; -import { act, render, screen } from "@testing-library/react"; +import { + act, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; +const { alert } = vi.hoisted(() => ({ alert: vi.fn() })); +vi.mock("@editor/components/toast", () => ({ alert })); vi.mock("@editor/tools/pdfTextEditor/components/FontFamilySelect", () => ({ FontFamilySelect: () => null, })); @@ -10,6 +18,7 @@ vi.mock("@editor/tools/pdfTextEditor/components/FontFamilySelect", () => ({ import { FormatGroup } from "@editor/tools/pdfTextEditor/components/toolbar/FormatGroup"; import type { Controller } from "@editor/tools/pdfTextEditor/components/toolbar/toolbarShared"; import { EMPTY_TOOLBAR } from "@editor/tools/pdfTextEditor/util/toolbarState"; +import type { ToolbarState } from "@editor/tools/pdfTextEditor/types"; const BLACK = { r: 0, g: 0, b: 0, a: 255 }; const RED = { r: 204, g: 0, b: 0, a: 255 }; @@ -69,3 +78,150 @@ describe("FormatGroup fill colour field", () => { expect(field.value).toBe("#cc0000"); }); }); + +function styleController( + state: Partial, + actions: Partial = {}, +): Controller { + return { + ...controller(BLACK, vi.fn()), + state: { + ...EMPTY_TOOLBAR, + fill: BLACK, + fontSize: 12, + ...state, + mixed: { ...EMPTY_TOOLBAR.mixed, ...state.mixed }, + }, + onToggleBold: vi.fn(async () => null), + onChangeFontWeight: vi.fn(async () => null), + ...actions, + }; +} + +function renderGroup(ctl: Controller) { + return render( + + + , + ); +} + +describe("FormatGroup style toggles", () => { + it("makes text bold from the Bold toggle beside Italic", async () => { + const ctl = styleController({ canBold: true, canItalic: true }); + renderGroup(ctl); + const bold = screen.getByTestId("pdf-editor-bold"); + + expect(bold.nextElementSibling).toBe( + screen.getByTestId("pdf-editor-italic"), + ); + expect(bold).toHaveAttribute("aria-pressed", "false"); + await userEvent.click(bold); + + expect(ctl.onToggleBold).toHaveBeenCalledTimes(1); + }); + + it("disables Bold and says why when the font has no bold face", async () => { + renderGroup(styleController({ canBold: false })); + const bold = screen.getByTestId("pdf-editor-bold"); + + expect(bold).toBeDisabled(); + fireEvent.mouseEnter(bold); + expect( + await screen.findByText("pdfTextEditor.toolbar.boldUnavailable"), + ).toBeInTheDocument(); + }); + + it("says when only the bold italic face is missing", () => { + renderGroup( + styleController({ + italic: true, + canItalic: true, + canBold: false, + boldNeedsBoldItalic: true, + }), + ); + + fireEvent.mouseEnter(screen.getByTestId("pdf-editor-bold")); + return expect( + screen.findByText("pdfTextEditor.toolbar.noBoldItalic"), + ).resolves.toBeInTheDocument(); + }); + + it("says the same on Italic for bold text", () => { + renderGroup( + styleController({ + bold: true, + canBold: true, + canItalic: false, + italicNeedsBoldItalic: true, + }), + ); + + fireEvent.mouseEnter(screen.getByTestId("pdf-editor-italic")); + return expect( + screen.findByText("pdfTextEditor.toolbar.noBoldItalic"), + ).resolves.toBeInTheDocument(); + }); + + it("shows a bold-only font as bold, locked", () => { + renderGroup(styleController({ bold: true, canBold: false })); + const bold = screen.getByTestId("pdf-editor-bold"); + + expect(bold).toBeDisabled(); + expect(bold).toHaveAttribute("aria-pressed", "true"); + }); + + it("shows a half-bold selection as mixed", () => { + renderGroup( + styleController({ canBold: true, mixed: { bold: true } as never }), + ); + + expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute( + "aria-pressed", + "mixed", + ); + }); + + it("tells the user when the italic toggle left text as it was", async () => { + alert.mockReset(); + const ctl = styleController( + { canItalic: true }, + { onToggleItalic: vi.fn(async () => "styleSkipped" as const) }, + ); + renderGroup(ctl); + + await userEvent.click(screen.getByTestId("pdf-editor-italic")); + + await waitFor(() => + expect(alert).toHaveBeenCalledWith({ + alertType: "warning", + expandable: false, + title: "pdfTextEditor.fontPicker.styleSkipped", + }), + ); + }); +}); + +describe("FormatGroup weight menu", () => { + it("stays hidden for a family with only regular and bold", () => { + renderGroup(styleController({ weights: [] })); + + expect( + screen.queryByTestId("pdf-editor-font-weight"), + ).not.toBeInTheDocument(); + }); + + it("reaches a weight the toggles cannot", async () => { + Element.prototype.scrollIntoView = vi.fn(); + const ctl = styleController({ weights: [300, 400, 700], weight: 400 }); + renderGroup(ctl); + + await userEvent.click(screen.getByTestId("pdf-editor-font-weight")); + await userEvent.click( + await screen.findByText("pdfTextEditor.fontPicker.weightLight"), + ); + + expect(ctl.onChangeFontWeight).toHaveBeenCalledWith(300); + }); +}); diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx index 614dbccb2d0..bfebe1a2f65 100644 --- a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx +++ b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx @@ -6,6 +6,7 @@ import { Menu, NumberInput, Popover, + Select, Tooltip, } from "@mantine/core"; import { useTranslation } from "react-i18next"; @@ -16,17 +17,84 @@ import { } from "@editor/tools/pdfTextEditor/model/Color"; import { familyOf } from "@editor/tools/pdfTextEditor/util/fontFamily"; import { FontFamilySelect } from "@editor/tools/pdfTextEditor/components/FontFamilySelect"; +import { useFontChangeWarning } from "@editor/tools/pdfTextEditor/components/fontPickFailure"; import { NO_SHRINK, type Controller, } from "@editor/tools/pdfTextEditor/components/toolbar/toolbarShared"; +const WEIGHT_NAMES: Record = { + 100: ["pdfTextEditor.fontPicker.weightThin", "Thin"], + 200: ["pdfTextEditor.fontPicker.weightExtraLight", "Extra light"], + 300: ["pdfTextEditor.fontPicker.weightLight", "Light"], + 400: ["pdfTextEditor.fontPicker.weightRegular", "Regular"], + 500: ["pdfTextEditor.fontPicker.weightMedium", "Medium"], + 600: ["pdfTextEditor.fontPicker.weightSemibold", "Semibold"], + 700: ["pdfTextEditor.fontPicker.weightBold", "Bold"], + 800: ["pdfTextEditor.fontPicker.weightExtraBold", "Extra bold"], + 900: ["pdfTextEditor.fontPicker.weightBlack", "Black"], +}; + +type TranslatedText = [key: string, fallback: string]; + +interface ToggleTexts { + name: TranslatedText; + /** Why the toggle is off when the text is in the style and its font has no face without it. */ + only: TranslatedText; + /** Why the toggle is off when the font has no face in the style. */ + unavailable: TranslatedText; +} + +const BOLD_TEXTS: ToggleTexts = { + name: ["pdfTextEditor.toolbar.bold", "Bold"], + only: ["pdfTextEditor.toolbar.boldOnly", "This font has only a bold version"], + unavailable: [ + "pdfTextEditor.toolbar.boldUnavailable", + "No bold version of this font", + ], +}; + +const ITALIC_TEXTS: ToggleTexts = { + name: ["pdfTextEditor.toolbar.italic", "Italic"], + only: [ + "pdfTextEditor.toolbar.italicOnly", + "This font has only an italic version", + ], + unavailable: [ + "pdfTextEditor.toolbar.italicUnavailable", + "This font has no italic version. Load your device fonts or pick another font family.", + ], +}; + +const NO_BOLD_ITALIC: TranslatedText = [ + "pdfTextEditor.toolbar.noBoldItalic", + "No bold italic version of this font", +]; + +/** A style toggle's look: filled when the whole selection has the style, outlined when only some of it does. */ +function toggleLook(on: boolean, mixed: boolean) { + if (mixed) return { variant: "secondary", accent: "default" } as const; + return on + ? ({ variant: "primary", accent: "default" } as const) + : ({ variant: "tertiary", accent: "neutral" } as const); +} + interface FormatGroupProps { controller: Controller; touch?: boolean; + /** + * Set when the controls sit in another popover. Their own dropdowns then + * render inside it: one portalled out of it reads as a click outside, which + * closes the popover and the dropdown with it. + */ + inPopover?: boolean; } -export function FormatGroup({ controller, touch = false }: FormatGroupProps) { +export function FormatGroup({ + controller, + touch = false, + inPopover = false, +}: FormatGroupProps) { const { t } = useTranslation(); const { state, @@ -37,9 +105,12 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) { onChangeFontSize, onChangeFill, onChangeOutline, + onToggleBold, onToggleItalic, + onChangeFontWeight, onChangeCase, } = controller; + const warnAbout = useFontChangeWarning(); const [fillPickerOpen, setFillPickerOpen] = useState(false); // What the colour field holds while it has focus. The toolbar can redraw a // pick after the model has it, and that late value would replace the text @@ -56,17 +127,41 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) { scanFont === undefined ? documentFamily : (scanFont?.family ?? null); const inputSize = touch ? "lg" : "xs"; const buttonSize = touch ? "xl" : "sm"; + const weightName = (weight: number) => + WEIGHT_NAMES[weight] + ? t(...WEIGHT_NAMES[weight]) + : t("pdfTextEditor.fontPicker.weightNumber", "Weight {{weight}}", { + weight, + }); const readOnlyNote = selectionTextReadOnly ? t( "pdfTextEditor.run.readOnlyOrderTitle", "This line's text can't be edited: it mixes right-to-left and left-to-right text in an order the editor can't redraw safely", ) : null; + const toggleTooltip = ( + texts: ToggleTexts, + can: boolean, + needsBoldItalic: boolean, + on: boolean, + ) => + readOnlyNote ?? + t( + ...(can + ? texts.name + : needsBoldItalic + ? NO_BOLD_ITALIC + : on + ? texts.only + : texts.unavailable), + ); return ( <> + {state.weights.length > 0 && !state.mixed.fontFamily && ( +