Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writing Flow: Improve emulated caret positioning #5808

Merged
merged 3 commits into from
Apr 11, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions editor/components/writing-flow/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,20 @@ class WritingFlow extends Component {
return;
}

// Emulate a rect at which caret should be placed using mouse event.
const rect = target.getBoundingClientRect();
const targetRect = new DOMRect( event.clientX, rect.top, 0, rect.height );
// To generate a caret rect (where its height determines buffer offset
// for caret target point), the element must first be focused.
target.focus();
const rect = computeCaretRect( target );

// `computeCaretRect` may return undefined if it's unable to find a
// collapsed range.
if ( ! rect ) {
return;
}

placeCaretAtVerticalEdge( target, false, targetRect );
// Emulate a rect at which caret should be placed using mouse event.
const targetRect = new DOMRect( event.clientX, 0, 0, rect.height );
placeCaretAtVerticalEdge( target, true, targetRect );
}

render() {
Expand Down
6 changes: 6 additions & 0 deletions utils/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,12 @@ export function placeCaretAtVerticalEdge( container, isReverse, rect, mayUseScro
return;
}

// Offset by a buffer half the height of the caret rect. This is needed
// because caretRangeFromPoint may default to the end of the selection if
// offset is too close to the edge. It's unclear how to precisely calculate
// this threshold; it may be the padded area of some combination of line
// height, caret height, and font size. The buffer offset is effectively
// equivalent to a point at half the height of a line of text.
const buffer = rect.height / 2;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I should have better commented this.

const editableRect = container.getBoundingClientRect();
const x = rect.left + ( rect.width / 2 );
Expand Down