Skip to content
Merged
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/guard-collapsetoend-empty-selection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

Skip `Selection.collapseToEnd()` during composition selection-sync when the live DOM selection has no ranges, so a cleared selection no longer throws `InvalidStateError` and unmounts the editor.
4 changes: 3 additions & 1 deletion packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,9 @@ export const Editable = forwardRef(

if (newDomRange) {
if (ReactEditor.isComposing(editor) && !IS_ANDROID) {
domSelection.collapseToEnd()
if (domSelection.rangeCount > 0) {
domSelection.collapseToEnd()
}
} else if (Range.isBackward(selection!)) {
domSelection.setBaseAndExtent(
newDomRange.endContainer,
Expand Down
49 changes: 48 additions & 1 deletion packages/slate-react/test/editable.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { useEffect } from 'react'
import { createEditor, Text, Transforms } from 'slate'
import { IS_COMPOSING } from 'slate-dom'
import { act, render } from '@testing-library/react'
import { Slate, withReact, Editable } from '../src'
import { Slate, withReact, Editable, ReactEditor } from '../src'

describe('slate-react', () => {
describe('Editable', () => {
Expand Down Expand Up @@ -237,5 +238,51 @@ describe('slate-react', () => {
expect(editableElement?.getAttribute('translate')).toBe('yes')
})
})

test('does not throw while composing when the live DOM selection has rangeCount 0', async () => {
const editor = withReact(createEditor())
const initialValue = [{ type: 'block', children: [{ text: 'test' }] }]

act(() => {
render(
<Slate
editor={editor}
initialValue={initialValue}
onChange={() => {}}
>
<Editable />
</Slate>
)
})

await act(async () => {
ReactEditor.focus(editor)
})

expect(editor.selection).not.toBeNull()
IS_COMPOSING.set(editor, true)

const win = ReactEditor.getWindow(editor)
const domSelection = win.getSelection()
expect(domSelection).not.toBeNull()
domSelection!.removeAllRanges()
expect(domSelection!.rangeCount).toBe(0)

const originalCollapseToEnd =
domSelection!.collapseToEnd.bind(domSelection)
domSelection!.collapseToEnd = () => {
if (domSelection!.rangeCount === 0) {
throw new DOMException(
"Failed to execute 'collapseToEnd' on 'Selection': there is no selection.",
'InvalidStateError'
)
}
return originalCollapseToEnd()
}

await act(async () => {
Transforms.select(editor, { path: [0, 0], offset: 2 })
})
})
})
})
Loading