From 85e8bac45d89118b653ab43eab95afc3761a824d Mon Sep 17 00:00:00 2001 From: Calixte Denizet Date: Thu, 12 Sep 2024 15:35:15 +0200 Subject: [PATCH] [Editor] Avoid an extra new line when serializing a FreeText annotation (bug 1897909) The extra new line is added because of using shift+enter to add a new line in the text editor. --- src/display/editor/freetext.js | 8 +++++ test/integration/freetext_editor_spec.mjs | 43 +++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/display/editor/freetext.js b/src/display/editor/freetext.js index 1e590db4f..19f633758 100644 --- a/src/display/editor/freetext.js +++ b/src/display/editor/freetext.js @@ -403,8 +403,16 @@ class FreeTextEditor extends AnnotationEditor { // We don't use innerText because there are some bugs with line breaks. const buffer = []; this.editorDiv.normalize(); + let prevChild = null; for (const child of this.editorDiv.childNodes) { + if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") { + // It can happen if the user uses shift+enter to add a new line. + // If we don't skip it, we'll end up with an extra line (one for the + // text and one for the br element). + continue; + } buffer.push(FreeTextEditor.#getNodeContent(child)); + prevChild = child; } return buffer.join("\n"); } diff --git a/test/integration/freetext_editor_spec.mjs b/test/integration/freetext_editor_spec.mjs index 7857c208b..99292260f 100644 --- a/test/integration/freetext_editor_spec.mjs +++ b/test/integration/freetext_editor_spec.mjs @@ -3644,4 +3644,47 @@ describe("FreeText Editor", () => { ); }); }); + + describe("Freetext and shift+enter", () => { + let pages; + + beforeAll(async () => { + pages = await loadAndWait("empty.pdf", ".annotationEditorLayer"); + }); + + afterAll(async () => { + await closePages(pages); + }); + + it("must check that a freetext has the correct data", async () => { + await Promise.all( + pages.map(async ([browserName, page]) => { + await switchToFreeText(page); + + const rect = await getRect(page, ".annotationEditorLayer"); + const editorSelector = getEditorSelector(0); + + const data = "Hello\nPDF.js\nWorld\n!!"; + await page.mouse.click(rect.x + 100, rect.y + 100); + await page.waitForSelector(editorSelector, { + visible: true, + }); + for (const line of data.split("\n")) { + await page.type(`${editorSelector} .internal`, line); + await page.keyboard.down("Shift"); + await page.keyboard.press("Enter"); + await page.keyboard.up("Shift"); + } + + // Commit. + await page.keyboard.press("Escape"); + await page.waitForSelector(`${editorSelector} .overlay.enabled`); + await waitForSerialized(page, 1); + + const serialized = await getSerialized(page, x => x.value); + expect(serialized[0]).withContext(`In ${browserName}`).toEqual(data); + }) + ); + }); + }); });