Skip to content

Commit

Permalink
🐛 Fix Selection.getBounds() when starting range at end of text node
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
alecgibson committed Jun 2, 2023
1 parent b3d1532 commit 29463fa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions core/selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,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) {
Expand Down
16 changes: 16 additions & 0 deletions test/unit/core/selection.js
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,22 @@ describe('Selection', function () {
);
});

it('selection starting at end of text node', function () {
this.div.style.width = `${this.reference.width * 4}px`;
const selection = this.initialize(
Selection,
`
<p>
0000
<b>0000</b>
0000
</p>`,
this.div,
);
this.bounds = selection.getBounds(4, 1);
expect(this.bounds.width).toBeApproximately(this.reference.width, 1);
});

it('multiple lines', function () {
const selection = this.initialize(
Selection,
Expand Down

0 comments on commit 29463fa

Please sign in to comment.