Skip to content

Commit

Permalink
Ignore selectionchange events originating from <input> and `<text…
Browse files Browse the repository at this point in the history
…area>` elements
  • Loading branch information
12joan committed Jan 16, 2025
1 parent 6aace0d commit 265681d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/empty-pillows-exercise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

Ignore selectionchange events originating from input and textarea elements (addresses Chrome bug https://issues.chromium.org/issues/389368412)
23 changes: 16 additions & 7 deletions packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -856,15 +856,25 @@ export const Editable = forwardRef(
useIsomorphicLayoutEffect(() => {
const window = ReactEditor.getWindow(editor)

// COMPAT: In Chrome, `selectionchange` events can fire when <input> and
// <textarea> elements are appended to the DOM, causing
// `editor.selection` to be overwritten in some circumstances.
// (2025/01/16) https://issues.chromium.org/issues/389368412
const onSelectionChange = ({ target }: Event) => {
const targetElement = target instanceof HTMLElement ? target : null
const targetTagName = targetElement?.tagName
if (targetTagName === 'INPUT' || targetTagName === 'TEXTAREA') {
return
}
scheduleOnDOMSelectionChange()
}

// Attach a native DOM event handler for `selectionchange`, because React's
// built-in `onSelect` handler doesn't fire for all selection changes. It's
// a leaky polyfill that only fires on keypresses or clicks. Instead, we
// want to fire for any change to the selection inside the editor.
// (2019/11/04) https://github.com/facebook/react/issues/5785
window.document.addEventListener(
'selectionchange',
scheduleOnDOMSelectionChange
)
window.document.addEventListener('selectionchange', onSelectionChange)

// Listen for dragend and drop globally. In Firefox, if a drop handler
// initiates an operation that causes the originally dragged element to
Expand All @@ -876,9 +886,8 @@ export const Editable = forwardRef(
window.document.addEventListener('drop', stoppedDragging)

return () => {
window.document.removeEventListener(
'selectionchange',
scheduleOnDOMSelectionChange
window.document.removeEventListener('selectionchange',

Check failure on line 889 in packages/slate-react/src/components/editable.tsx

View workflow job for this annotation

GitHub Actions / lint:eslint

Insert `⏎··········`
onSelectionChange
)
window.document.removeEventListener('dragend', stoppedDragging)
window.document.removeEventListener('drop', stoppedDragging)
Expand Down

0 comments on commit 265681d

Please sign in to comment.