Skip to content

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

Fix the caret landing one character off in multi-line plain text boxes (#8887)

Anthony Stirlingad38e38ce9bb
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
index 624d662e74..2fe42cc483 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
@@ -158,6 +158,50 @@ describe("caret offsets", () => {
expect(plainCaretOffset(el)).toBe(5);
});
+ it("round-trips every offset of plain text that spans lines", () => {
+ const el = host();
+ const text = "• First item\n• Second item\nthird";
+ // innerText's own <br>s, which jsdom does not produce for us.
+ el.innerHTML = "• First item<br>• Second item<br>third";
+ expect(readOverlayText(el)).toBe(text);
+ for (let offset = 0; offset <= text.length; offset += 1) {
+ restoreCaretOffset(el, offset);
+ expect(plainCaretOffset(el)).toBe(offset);
+ }
+ });
+
+ it.each([
+ ["consecutive breaks", "a<br><br>b", "a\n\nb"],
+ ["a trailing newline", "a<br><br>", "a\n"],
+ ["a trailing filler break", "a<br>", "a"],
+ ["a leading break", "<br>a", "\na"],
+ ["a break nested in a block", "<div>a<span>b<br>c</span></div>", "ab\nc"],
+ [
+ "a stray div after text",
+ "first<br>second<div>typed</div>",
+ "first\nsecond\ntyped",
+ ],
+ [
+ "stray divs around an empty one",
+ "<div>a</div><div><br></div><div>b</div>",
+ "a\n\nb",
+ ],
+ ["a break between two blocks", "<div>a</div><br><div>b</div>", "a\n\nb"],
+ [
+ "two breaks between two blocks",
+ "<div>a</div><br><br><div>b</div>",
+ "a\n\n\nb",
+ ],
+ ])("round-trips every offset through %s", (_shape, html, text) => {
+ const el = host();
+ el.innerHTML = html;
+ expect(readOverlayText(el)).toBe(text);
+ for (let offset = 0; offset <= text.length; offset += 1) {
+ restoreCaretOffset(el, offset);
+ expect(plainCaretOffset(el)).toBe(offset);
+ }
+ });
+
it("clamps past the end instead of throwing", () => {
const el = host();
paintLines(el, [line("abc")], OPTS);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
index a29363b440..a0122a8608 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
@@ -172,6 +172,10 @@ export function paintPlainText(el: HTMLElement, text: string): void {
el.innerText = text;
}
+function isLineBreak(node: Node): node is HTMLElement {
+ return node instanceof HTMLElement && node.tagName === "BR";
+}
+
/**
* Lines held by one painted line block.
*
@@ -193,7 +197,7 @@ function blockLines(element: HTMLElement): string[] {
lines[lines.length - 1] += node.textContent ?? "";
return;
}
- if (node instanceof HTMLElement && node.tagName === "BR") {
+ if (isLineBreak(node)) {
lines.push("");
return;
}
@@ -224,7 +228,7 @@ export function readOverlayText(element: HTMLElement): string {
continue;
}
if (!(node instanceof HTMLElement)) continue;
- if (node.tagName === "BR") {
+ if (isLineBreak(node)) {
lines.push("");
lastWasTrailingBr = true;
continue;
@@ -300,6 +304,8 @@ function plainOffset(
}
const host = document.createElement("div");
host.appendChild(range.cloneContents());
+ // A <br> just before the caret is a real break, not the trailing filler readOverlayText drops.
+ host.appendChild(document.createTextNode(""));
const chars = readOverlayText(host).length;
// A caret parked on the container BETWEEN two line children sits at the
// start of the next line - one past the end of the truncated text. Past the
@@ -308,8 +314,11 @@ function plainOffset(
const idx = Math.min(offset, el.childNodes.length);
const children = Array.from(el.childNodes);
const isLineChild = (n: Node) =>
- n instanceof HTMLElement && n.tagName !== "BR";
+ n instanceof HTMLElement && !isLineBreak(n);
+ // A <br> just before the caret already opened that line in the truncated text.
+ const afterBreak = idx > 0 && isLineBreak(children[idx - 1]);
if (
+ !afterBreak &&
children.slice(0, idx).some(isLineChild) &&
children.slice(idx).some(isLineChild)
) {
@@ -407,43 +416,88 @@ export function plainDomRange(el: HTMLElement, range: TextRange): Range | null {
return out;
}
-/** Where character `offset` of the run's model text falls in the overlay's DOM. */
-function domPosition(
- el: HTMLElement,
- offset: number,
-): { node: Node; offset: number } {
- const target = Math.max(0, offset);
+interface DomPoint {
+ node: Node;
+ offset: number;
+}
- const blocks = lineBlocks(el);
- let scope: HTMLElement = el;
- let remaining = target;
- if (blocks.length > 0) {
- scope = blocks[blocks.length - 1];
- remaining = (scope.textContent ?? "").length;
- let before = 0;
- for (const block of blocks) {
- const length = (block.textContent ?? "").length;
- if (target <= before + length) {
- scope = block;
- remaining = target - before;
- break;
- }
- before += length + 1;
+interface DomCursor {
+ target: number;
+ seen: number;
+ end: DomPoint;
+}
+
+/** Where character `offset` of the run's model text falls in the overlay's DOM, counted as readOverlayText counts. */
+function domPosition(el: HTMLElement, offset: number): DomPoint {
+ const cursor: DomCursor = {
+ target: Math.max(0, offset),
+ seen: 0,
+ end: { node: el, offset: 0 },
+ };
+ const children = Array.from(el.childNodes);
+ const lastContent = children
+ .filter((n) => n.nodeType === Node.TEXT_NODE || n instanceof HTMLElement)
+ .pop();
+ let sawBlock = false;
+ for (const node of children) {
+ let hit: DomPoint | null = null;
+ if (node.nodeType === Node.TEXT_NODE) {
+ hit = passText(cursor, node);
+ } else if (isLineBreak(node)) {
+ if (node === lastContent) break;
+ hit = passLineBreak(cursor, node);
+ } else if (node instanceof HTMLElement) {
+ hit = passBlock(cursor, node, sawBlock || cursor.seen > 0);
+ sawBlock = true;
}
+ if (hit) return hit;
}
+ return cursor.end;
+}
- const walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT);
- let seen = 0;
- let node = walker.nextNode();
- while (node) {
- const length = (node.nodeValue ?? "").length;
- if (seen + length >= remaining) {
- return { node, offset: remaining - seen };
- }
- seen += length;
- node = walker.nextNode();
+function passText(cursor: DomCursor, node: Node): DomPoint | null {
+ const length = (node.nodeValue ?? "").length;
+ if (cursor.target <= cursor.seen + length) {
+ return { node, offset: cursor.target - cursor.seen };
+ }
+ cursor.seen += length;
+ cursor.end = { node, offset: length };
+ return null;
+}
+
+function passLineBreak(cursor: DomCursor, br: HTMLElement): DomPoint | null {
+ const parent = br.parentNode;
+ if (!parent) return null;
+ const index = Array.prototype.indexOf.call(parent.childNodes, br);
+ if (cursor.seen === cursor.target) return { node: parent, offset: index };
+ cursor.seen += 1;
+ cursor.end = { node: parent, offset: index + 1 };
+ return null;
+}
+
+function passBlock(
+ cursor: DomCursor,
+ block: HTMLElement,
+ startsLine: boolean,
+): DomPoint | null {
+ if (startsLine) {
+ if (cursor.seen === cursor.target) return cursor.end;
+ cursor.seen += 1;
+ }
+ cursor.end = { node: block, offset: 0 };
+ if ((block.textContent ?? "") === "") return null;
+ return passInline(cursor, block);
+}
+
+function passInline(cursor: DomCursor, parent: Node): DomPoint | null {
+ for (const node of Array.from(parent.childNodes)) {
+ let hit: DomPoint | null = null;
+ if (node.nodeType === Node.TEXT_NODE) hit = passText(cursor, node);
+ else if (isLineBreak(node)) hit = passLineBreak(cursor, node);
+ else hit = passInline(cursor, node);
+ if (hit) return hit;
}
- return { node: scope, offset: 0 };
+ return null;
}
function setCollapsed(selection: Selection, node: Node, offset: number): void {