Skip to content

Commit

Permalink
fix: toSlatePoint suppressThrow leaf without text node (#4813)
Browse files Browse the repository at this point in the history
  • Loading branch information
BitPhinix committed Jan 28, 2022
1 parent e998752 commit a5fd62d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 26 deletions.
5 changes: 5 additions & 0 deletions .changeset/kind-olives-add.md
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

Don't throw in toSlatePoint while using supressThrow if leaf has no text node
55 changes: 29 additions & 26 deletions packages/slate-react/src/plugin/react-editor.ts
Expand Up @@ -491,33 +491,36 @@ export const ReactEditor = {
// Calculate how far into the text node the `nearestNode` is, so that we
// can determine what the offset relative to the text node is.
if (leafNode) {
textNode = leafNode.closest('[data-slate-node="text"]')!
const window = ReactEditor.getWindow(editor)
const range = window.document.createRange()
range.setStart(textNode, 0)
range.setEnd(nearestNode, nearestOffset)

const contents = range.cloneContents()
const removals = [
...Array.prototype.slice.call(
contents.querySelectorAll('[data-slate-zero-width]')
),
...Array.prototype.slice.call(
contents.querySelectorAll('[contenteditable=false]')
),
]

removals.forEach(el => {
el!.parentNode!.removeChild(el)
})
textNode = leafNode.closest('[data-slate-node="text"]')

if (textNode) {
const window = ReactEditor.getWindow(editor)
const range = window.document.createRange()
range.setStart(textNode, 0)
range.setEnd(nearestNode, nearestOffset)

const contents = range.cloneContents()
const removals = [
...Array.prototype.slice.call(
contents.querySelectorAll('[data-slate-zero-width]')
),
...Array.prototype.slice.call(
contents.querySelectorAll('[contenteditable=false]')
),
]

removals.forEach(el => {
el!.parentNode!.removeChild(el)
})

// COMPAT: Edge has a bug where Range.prototype.toString() will
// convert \n into \r\n. The bug causes a loop when slate-react
// attempts to reposition its cursor to match the native position. Use
// textContent.length instead.
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/10291116/
offset = contents.textContent!.length
domNode = textNode
// COMPAT: Edge has a bug where Range.prototype.toString() will
// convert \n into \r\n. The bug causes a loop when slate-react
// attempts to reposition its cursor to match the native position. Use
// textContent.length instead.
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/10291116/
offset = contents.textContent!.length
domNode = textNode
}
} else if (voidNode) {
// For void nodes, the element with the offset key will be a cousin, not an
// ancestor, so find it by going down from the nearest void parent.
Expand Down

0 comments on commit a5fd62d

Please sign in to comment.