From 60660bd260cf5f0ae9a1e03ec5a17ff8f9072e12 Mon Sep 17 00:00:00 2001 From: Alec Gibson <12036746+alecgibson@users.noreply.github.com> Date: Fri, 5 May 2023 12:05:45 +0100 Subject: [PATCH] Fix `Selection.getBounds()` when starting range at end of text node At the moment there's a bug when trying to get the bounds of a range which starts at the end of a text node at the end of a line. In this case, the returned bounds span the entire width of the editor, which isn't the desired result. This change fixes the issue by checking if the Quill range starts at the end of a leaf. If it does, we try to define the range starting at the beginning of the next leaf instead. --- CHANGELOG.md | 1 + packages/quill/src/core/selection.ts | 11 +++++++++++ packages/quill/test/unit/core/selection.spec.ts | 16 ++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d59716f014..71ddc858a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ - Fix toolbar button state not updated in some cases - Narrower `BubbleTheme.tooltip` type +- Fix `Selection.getBounds()` when starting range at end of text node # 2.0.0-rc.1 diff --git a/packages/quill/src/core/selection.ts b/packages/quill/src/core/selection.ts index fe52e266d3..9c3f87ffb7 100644 --- a/packages/quill/src/core/selection.ts +++ b/packages/quill/src/core/selection.ts @@ -183,6 +183,17 @@ class Selection { let node: Node; let [leaf, offset] = this.scroll.leaf(index); if (leaf == null) return null; + if (length > 0 && offset === leaf.length()) { + const [next] = this.scroll.leaf(index + 1); + if (next) { + const [line] = this.scroll.line(index); + const [nextLine] = this.scroll.line(index + 1); + if (line === nextLine) { + leaf = next; + offset = 0; + } + } + } [node, offset] = leaf.position(offset, true); const range = document.createRange(); if (length > 0) { diff --git a/packages/quill/test/unit/core/selection.spec.ts b/packages/quill/test/unit/core/selection.spec.ts index f3ba0e98df..4b866304f2 100644 --- a/packages/quill/test/unit/core/selection.spec.ts +++ b/packages/quill/test/unit/core/selection.spec.ts @@ -598,6 +598,22 @@ describe('Selection', () => { ); }); + test('selection starting at end of text node', () => { + const { reference, container } = setup(); + container.style.width = `${reference.width * 4}px`; + const selection = createSelection( + ` +

+ 0000 + 0000 + 0000 +

`, + container, + ); + const bounds = selection.getBounds(4, 1); + expect(bounds?.width).approximately(reference.width, 1); + }); + test('multiple lines', () => { const { reference, container } = setup(); const selection = createSelection(