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 Feb 9, 2024
1 parent 15f2e8f commit 2a740a7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/quill/src/core/selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 16 additions & 0 deletions packages/quill/test/unit/core/selection.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,22 @@ describe('Selection', () => {
);
});

test('selection starting at end of text node', function () {
const { reference, container } = setup();
container.style.width = `${reference.width * 4}px`;
const selection = createSelection(
`
<p>
0000
<b>0000</b>
0000
</p>`,
container,
);
const bounds = selection.getBounds(4, 1);
expect(bounds?.width).approximately(reference.width, 1);
});

test('multiple lines', () => {
const { reference, container } = setup();
const selection = createSelection(
Expand Down

0 comments on commit 2a740a7

Please sign in to comment.