Skip to content

Commit

Permalink
Writing flow: fix edge detection in Chrome (#31150)
Browse files Browse the repository at this point in the history
* Writing flow: fix edge detection in Chrome

* Reduce loops
  • Loading branch information
ellatrix committed Apr 24, 2021
1 parent c54e251 commit cb9bac9
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion packages/dom/src/dom/get-rectangle-from-range.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,45 @@ export default function getRectangleFromRange( range ) {
// range; this a rectangle enclosing the union of the bounding rectangles
// for all the elements in the range.
if ( ! range.collapsed ) {
return range.getBoundingClientRect();
const rects = Array.from( range.getClientRects() );

// If there's just a single rect, return it.
if ( rects.length === 1 ) {
return rects[ 0 ];
}

// Ignore tiny selection at the edge of a range.
const filteredRects = rects.filter( ( { width } ) => width > 1 );

// If it's full of tiny selections, return browser default.
if ( filteredRects.length === 0 ) {
return range.getBoundingClientRect();
}

if ( filteredRects.length === 1 ) {
return filteredRects[ 0 ];
}

let {
top: furthestTop,
bottom: furthestBottom,
left: furthestLeft,
right: furthestRight,
} = filteredRects[ 0 ];

for ( const { top, bottom, left, right } of filteredRects ) {
if ( top < furthestTop ) furthestTop = top;
if ( bottom > furthestBottom ) furthestBottom = bottom;
if ( left < furthestLeft ) furthestLeft = left;
if ( right > furthestRight ) furthestRight = right;
}

return new window.DOMRect(
furthestLeft,
furthestTop,
furthestRight - furthestLeft,
furthestBottom - furthestTop
);
}

const { startContainer } = range;
Expand Down

0 comments on commit cb9bac9

Please sign in to comment.