Skip to content
Open
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/safari-shadow-dom-composition.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

In Safari, when the editor is inside a shadow root, typing with a dead key or an input method no longer loses text, and a click during a composition now moves the caret
42 changes: 41 additions & 1 deletion packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,12 @@ export const Editable = forwardRef(
const el = ReactEditor.toDOMNode(editor, editor)
const root = el.getRootNode()

if (!processing.current && IS_WEBKIT && root instanceof ShadowRoot) {
if (
!processing.current &&
IS_WEBKIT &&
root instanceof ShadowRoot &&
!ReactEditor.isComposing(editor)
) {
processing.current = true

const active = getActiveElement()
Expand Down Expand Up @@ -1514,6 +1519,14 @@ export const Editable = forwardRef(
if (IS_WEBKIT) {
const domSelection = getSelection(root)
domSelection?.removeAllRanges()

// COMPAT: Removing the selection while an input method is
// composing makes Safari drop the composition without a
// `compositionend` event. Clear the composing state, or the
// editor ignores selection changes until the next key press.
if (ReactEditor.isComposing(editor)) {
setComposing(false)
}
}

IS_FOCUSED.delete(editor)
Expand All @@ -1524,8 +1537,35 @@ export const Editable = forwardRef(
editor,
attributes.onBlur,
flushDOMSelectionChange,
setComposing,
]
)}
onMouseDown={useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
// COMPAT: WebKit on macOS ends an open composition when a
// `mousedown` runs its default action. In a shadow root,
// the re-render that `compositionend` triggers can come
// after the click has moved the caret, and moves it back to
// where the composition started. Clear the composing state
// now, so the re-render happens before the caret moves. A
// prevented `mousedown` keeps the composition open, and
// WebKit on iOS and iPadOS doesn't end one on `mousedown`.
// iPadOS reports a Mac user agent, so rule out touch
// devices as well.
if (
!isEventHandled(event, attributes.onMouseDown) &&
!event.isDefaultPrevented() &&
IS_WEBKIT &&

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • IS_WEBKIT also matches iOS Safari and every iOS browser, since they all report AppleWebKit without Chrome
  • a tap sends a synthesized mousedown, so tapping in the editor during a kana composition clears composing here
  • the new tests skip everything but desktop WebKit, so nothing covers iOS
  • was this tried on iOS? if it doesn't end the composition there, gate it on !IS_IOS

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tried it on iPhone and iPad simulators with a Japanese keyboard: a tap never gets this far mid-composition. Only macOS WebKit ends a composition on mousedown anyway, so it's gated now, with unit tests. IS_IOS misses iPad Safari (it reports a Mac user agent), so there's a touch check as well.

!IS_IOS &&
!navigator.maxTouchPoints &&
ReactEditor.isComposing(editor) &&
ReactEditor.hasTarget(editor, event.target)
) {
setComposing(false)
}
},
[attributes.onMouseDown, editor, setComposing]
)}
onClick={useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
if (ReactEditor.hasTarget(editor, event.target)) {
Expand Down
188 changes: 188 additions & 0 deletions packages/slate-react/test/composition-state-webkit.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import React from 'react'
import { createEditor, Descendant } from 'slate'
import * as SlateDOM from 'slate-dom'
import { act, fireEvent, render } from '@testing-library/react'
import { Editable, ReactEditor, Slate, useComposing, withReact } from '../src'

// Safari on macOS. Tests for other environments replace these flags.
jest.mock('slate-dom', () => ({
...jest.requireActual('slate-dom'),
IS_WEBKIT: true,
IS_IOS: false,
}))

// jsdom does not implement `isContentEditable`.
Object.defineProperty(HTMLElement.prototype, 'isContentEditable', {
get() {
return (
this.closest('[contenteditable]')?.getAttribute('contenteditable') ===
'true'
)
},
})

afterEach(() => {
jest.restoreAllMocks()
delete (window.navigator as { maxTouchPoints?: number }).maxTouchPoints
})

const initialValue: Descendant[] = [
{ type: 'paragraph', children: [{ text: 'hello world' }] } as Descendant,
]

const setup = (props: React.ComponentProps<typeof Editable> = {}) => {
const editor = withReact(createEditor())
const composing: boolean[] = []
const ComposingProbe = () => {
composing.push(useComposing())
return null
}
const { getByRole, getByTestId } = render(
<Slate editor={editor} initialValue={initialValue}>
<Editable
tabIndex={0}
renderElement={({ attributes, children }) => (
<p {...attributes}>
<ComposingProbe />
{children}
<span
contentEditable={false}
data-testid="chip"
onMouseDown={event => event.preventDefault()}
/>
</p>
)}
{...props}
/>
</Slate>
)
const textbox = getByRole('textbox')
const chip = getByTestId('chip')
const isComposing = () => ({
rendered: composing[composing.length - 1],
editor: ReactEditor.isComposing(editor),
})
return { textbox, chip, isComposing }
}

const startComposition = async (textbox: HTMLElement) => {
await act(async () => {
fireEvent.compositionStart(textbox, { data: '' })
fireEvent.compositionUpdate(textbox, { data: 'k' })
})
}

const mouseDown = async (element: HTMLElement) => {
await act(async () => {
fireEvent.mouseDown(element)
})
}

const composingState = { rendered: true, editor: true }
const idleState = { rendered: false, editor: false }

describe('composition state in WebKit', () => {
test('mousedown clears the composing state', async () => {
const onMouseDown = jest.fn()
const { textbox, isComposing } = setup({ onMouseDown })

await startComposition(textbox)
expect(isComposing()).toEqual(composingState)

await mouseDown(textbox)

expect(onMouseDown).toHaveBeenCalledTimes(1)
expect(isComposing()).toEqual(idleState)
})

test.each<[string, (event: React.MouseEvent) => void | boolean]>([
['prevents the default', event => event.preventDefault()],
[
'prevents the default and returns false',
event => {
event.preventDefault()
return false
},
],
['stops propagation', event => event.stopPropagation()],
['returns true', () => true],
])(
'mousedown keeps the composing state when the handler %s',
async (_, handler) => {
const onMouseDown = jest.fn(handler)
const { textbox, isComposing } = setup({ onMouseDown })

await startComposition(textbox)
await mouseDown(textbox)

expect(onMouseDown).toHaveBeenCalledTimes(1)
expect(isComposing()).toEqual(composingState)
}
)

test('mousedown keeps the composing state when an element in the editor prevents the default', async () => {
const { textbox, chip, isComposing } = setup()

await startComposition(textbox)
await mouseDown(chip)

expect(isComposing()).toEqual(composingState)
})

test('mousedown keeps the composing state on iOS', async () => {
jest.replaceProperty(
jest.requireMock<typeof SlateDOM>('slate-dom'),
'IS_IOS',
true
)
const { textbox, isComposing } = setup()

await startComposition(textbox)
await mouseDown(textbox)

expect(isComposing()).toEqual(composingState)
})

test('mousedown keeps the composing state on iPadOS, which reports a Mac user agent', async () => {
Object.defineProperty(window.navigator, 'maxTouchPoints', {
configurable: true,
value: 5,
})
const { textbox, isComposing } = setup()

await startComposition(textbox)
await mouseDown(textbox)

expect(isComposing()).toEqual(composingState)
})

test('mousedown keeps the composing state outside WebKit', async () => {
jest.replaceProperty(
jest.requireMock<typeof SlateDOM>('slate-dom'),
'IS_WEBKIT',
false
)
const { textbox, isComposing } = setup()

await startComposition(textbox)
await mouseDown(textbox)

expect(isComposing()).toEqual(composingState)
})

test('blur clears the composing state', async () => {
const { textbox, isComposing } = setup()

await act(async () => {
textbox.focus()
})
await startComposition(textbox)
expect(isComposing()).toEqual(composingState)

await act(async () => {
textbox.blur()
})

expect(isComposing()).toEqual(idleState)
})
})
1 change: 1 addition & 0 deletions packages/slate-react/test/readonly-events.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Object.defineProperty(HTMLElement.prototype, 'isContentEditable', {

const events = [
['onClick', fireEvent.click],
['onMouseDown', fireEvent.mouseDown],
['onCopy', fireEvent.copy],
['onBeforeInput', fireEvent.compositionEnd],
[
Expand Down
Loading