Open nathanborror opened 8 years ago
Hi @nathanborror!
Can you verify whether https://github.com/facebook/draft-js/blob/master/src/component/selection/getVisibleSelectionRect.js#L29 properly returns a range
value in the null case?
Hey @hellendag :)
It's returning Range {startContainer: <span>, startOffset: 0, endContainer: <span>, endOffset: 0, collapsed: true, …}
I'm seeing something similar. For me, getVisibleSelectionRect
always returns null when the cursor is at the beginning of a line.
The value for the range is {collapsed:true, commonAncestorContainer: span, endContainer: span, endOffset:0, startContainer: span, startOffset: 0}
This is in Chrome.
I think the problem is because getVisibleSelectionRect
is executed on render
method so DOM is not ready yet.
I've solved this by reading getVisibleSelectionRect
on componentDidUpdate
(so we know the DOM has been updated with the proper position) and then forcing a re-render.
An simple implementation of this could be:
const Foo = React.createClass({
getInitialState () {
return {
menuPosition: null
},
componentDidUpdate () {
const menuPosition = getVisibleSelectionRect(window)
// the tricky part is to play with this if statement to do only the proper re-renders
if(this.state.menuPosition === null || this.state.menuPosition !== menuPosition) {
this.setState({menuPosition})
}
},
render () {
return (
<div>
<Editor {...whatever} />
<Menu position={this.state.menuPosition} />
</div>
)
}
})
The issue also occurs when we try to calculate getVisibleSelectionRect(window)
when no character is inside the editor (on the first onChange
call).
I wonder what would be the best way of getting the selection rect because of that, I wanted to use it to know where to open a suggestions box.
@jjjjw Were you able to solve this?
I'm trying to make a simple typeahead. This might be incorrect but my current approach uses a
selectionContainsEntity
function which accepts a decorator strategy and the current editor state. If the cursor is in or alongside a match then I toggle a state property to render the typeahead component which usesgetVisibleSelectionRect(window)
to determine where to position the typeahead suggestions.Mostly works but
getVisibleSelectionRect
seems to return null when the cursor is in the act of typing, moving the cursor into the entity returns the correct position but as soon as typing begins it goes back to null. Here's an example:If I remove the decorator and just always show the typeahead then
getVisibleSelectionRect
returns what you'd expect on each keystroke. Here's a simplified version of the code I'm working with: