From 677da0ca87ffefb36676200fee5cf5cf0136b22e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Claud=C3=A9ric=20Demers?= Date: Sun, 26 Sep 2021 11:07:14 -0400 Subject: [PATCH] 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. --- .changeset/firefox-newline-bug.md | 5 +++++ .../slate-react/src/plugin/react-editor.ts | 19 ++++++++++++------- 2 files changed, 17 insertions(+), 7 deletions(-) create mode 100644 .changeset/firefox-newline-bug.md diff --git a/.changeset/firefox-newline-bug.md b/.changeset/firefox-newline-bug.md new file mode 100644 index 000000000..9f1457436 --- /dev/null +++ b/.changeset/firefox-newline-bug.md @@ -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. diff --git a/packages/slate-react/src/plugin/react-editor.ts b/packages/slate-react/src/plugin/react-editor.ts index 4e7e178c6..a41ce4bed 100644 --- a/packages/slate-react/src/plugin/react-editor.ts +++ b/packages/slate-react/src/plugin/react-editor.ts @@ -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-- }