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

Update editable.tsx: auto-focus fix for end of line with several chil… #4695

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .changeset/breezy-mice-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react: patch
---

Update editable.tsx: auto-focus fix for end of line with several children
28 changes: 28 additions & 0 deletions packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,34 @@ export const Editable = (props: EditableProps) => {
hasDomSelectionInEditor = true
}

state.isUpdatingSelection = false
})
})

// The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
// needs to be manually focused.
useEffect(() => {
if (ref.current && autoFocus) {
if (window.getSelection && document.createRange) {
const range = document.createRange()
ref.current.focus()
range.setStart(ref.current, ref.current.childNodes.length)
range.setEnd(ref.current, ref.current.childNodes.length)
const sel = window.getSelection()
sel?.removeAllRanges()
sel?.addRange(range)
}
ref.current.focus()
}
}, [autoFocus])

// Listen on the native `selectionchange` event to be able to update any time
// the selection changes. This is required because React's `onSelect` is leaky
// and non-standard so it doesn't fire until after a selection has been
// released. This causes issues in situations where another change happens
// while a selection is being dragged.
const onDOMSelectionChange = useCallback(
throttle(() => {
// If the DOM selection is in the editor and the editor selection is already correct, we're done.
if (
hasDomSelection &&
Expand Down
Loading