Skip to content

Commit

Permalink
fix: insert new node in advance to avoid ime double input with editor…
Browse files Browse the repository at this point in the history
… marks (#4451)

* fix: insert new node in advance to avoid ime double input

* chore: add changeset

* refactor: minor refator as review
  • Loading branch information
githoniel committed Aug 16, 2021
1 parent d06706c commit 8e4120a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/old-bees-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

fix IME double input with editor mark
57 changes: 54 additions & 3 deletions packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ export const Editable = (props: EditableProps) => {
const state = useMemo(
() => ({
isComposing: false,
hasInsertPrefixInCompositon: false,
isDraggingInternally: false,
isUpdatingSelection: false,
latestElement: null as DOMElement | null,
Expand Down Expand Up @@ -724,6 +725,23 @@ export const Editable = (props: EditableProps) => {
) {
Editor.insertText(editor, event.data)
}

if (editor.selection && Range.isCollapsed(editor.selection)) {
const leafPath = editor.selection.anchor.path
const currentTextNode = Node.leaf(editor, leafPath)
if (state.hasInsertPrefixInCompositon) {
state.hasInsertPrefixInCompositon = false
Editor.withoutNormalizing(editor, () => {
// remove Unicode BOM prefix added in `onCompositionStart`
const text = currentTextNode.text.replace(/^\uFEFF/, '')
Transforms.delete(editor, {
distance: currentTextNode.text.length,
reverse: true,
})
Transforms.insertText(editor, text)
})
}
}
}
},
[attributes.onCompositionEnd]
Expand All @@ -746,9 +764,42 @@ export const Editable = (props: EditableProps) => {
hasEditableTarget(editor, event.target) &&
!isEventHandled(event, attributes.onCompositionStart)
) {
const { selection } = editor
if (selection && Range.isExpanded(selection)) {
Editor.deleteFragment(editor)
const { selection, marks } = editor
if (selection) {
if (Range.isExpanded(selection)) {
Editor.deleteFragment(editor)
return
}
const inline = Editor.above(editor, {
match: n => Editor.isInline(editor, n),
mode: 'highest',
})
if (inline) {
const [, inlinePath] = inline
if (Editor.isEnd(editor, selection.anchor, inlinePath)) {
const point = Editor.after(editor, inlinePath)!
Transforms.setSelection(editor, {
anchor: point,
focus: point,
})
}
}
// insert new node in advance to ensure composition text will insert
// along with final input text
// add Unicode BOM prefix to avoid normalize removing this node
if (marks) {
state.hasInsertPrefixInCompositon = true
Transforms.insertNodes(
editor,
{
text: '\uFEFF',
...marks,
},
{
select: true,
}
)
}
}
}
},
Expand Down

0 comments on commit 8e4120a

Please sign in to comment.