1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-09 08:46:35 +02:00

Fix toSlatePoint when text node ends in \n in Firefox (#4547)

In Firefox, `range.cloneContents()` returns an extra trailing '\n', when the document ends with a new-line character. This results in the offset length being off by one, so we need to subtract one to account for this.
This commit is contained in:
Claudéric Demers
2021-09-26 11:07:14 -04:00
committed by GitHub
parent f9c41a569c
commit 677da0ca87
2 changed files with 17 additions and 7 deletions

View File

@@ -0,0 +1,5 @@
---
'slate-react': patch
---
Fixed a bug that caused the editor to be unable to resolve a Slate point from a DOM point when selecting an entire document that ended in a new line in Firefox.

View File

@@ -24,7 +24,7 @@ import {
normalizeDOMPoint,
hasShadowRoot,
} from '../utils/dom'
import { IS_CHROME } from '../utils/environment'
import { IS_CHROME, IS_FIREFOX } from '../utils/environment'
/**
* A React and DOM-specific version of the `Editor` interface.
@@ -463,6 +463,7 @@ export const ReactEditor = {
const range = window.document.createRange()
range.setStart(textNode, 0)
range.setEnd(nearestNode, nearestOffset)
const contents = range.cloneContents()
const removals = [
...Array.prototype.slice.call(
@@ -502,15 +503,19 @@ export const ReactEditor = {
}
}
// COMPAT: If the parent node is a Slate zero-width space, editor is
// because the text node should have no characters. However, during IME
// composition the ASCII characters will be prepended to the zero-width
// space, so subtract 1 from the offset to account for the zero-width
// space character.
if (
domNode &&
offset === domNode.textContent!.length &&
parentNode.hasAttribute('data-slate-zero-width')
// COMPAT: If the parent node is a Slate zero-width space, editor is
// because the text node should have no characters. However, during IME
// composition the ASCII characters will be prepended to the zero-width
// space, so subtract 1 from the offset to account for the zero-width
// space character.
(parentNode.hasAttribute('data-slate-zero-width') ||
// COMPAT: In Firefox, `range.cloneContents()` returns an extra trailing '\n'
// when the document ends with a new-line character. This results in the offset
// length being off by one, so we need to subtract one to account for this.
(IS_FIREFOX && domNode.textContent?.endsWith('\n')))
) {
offset--
}