Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
37 changes: 36 additions & 1 deletion packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,12 @@
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 @@ -1427,7 +1432,7 @@
)
}
},
[

Check warning on line 1435 in packages/slate-react/src/components/editable.tsx

View workflow job for this annotation

GitHub Actions / lint:eslint

React Hook useCallback has a missing dependency: 'state'. Either include it or remove the dependency array
readOnly,
attributes.onInput,
editor,
Expand Down Expand Up @@ -1509,6 +1514,15 @@
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)) {
IS_COMPOSING.set(editor, false)
setIsComposing(false)
}
}

IS_FOCUSED.delete(editor)
Expand All @@ -1521,6 +1535,27 @@
flushDOMSelectionChange,
]
)}
onMouseDown={useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
// COMPAT: WebKit ends an open composition right after
// `mousedown`. 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.
if (
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.

ReactEditor.isComposing(editor) &&
ReactEditor.hasTarget(editor, event.target)
) {
IS_COMPOSING.set(editor, false)
setIsComposing(false)
}

isEventHandled(event, attributes.onMouseDown)

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.

  • the reset runs before attributes.onMouseDown, so a handler that calls preventDefault can't stop it
  • if WebKit keeps the composition open when mousedown is prevented, composing is now false mid-composition, intended?
  • other handlers in this file check isEventHandled first and skip the editor's own work when it returns true

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.

Not intended, good catch. Safari keeps the composition open when mousedown is prevented, and the early reset then cancelled it. The handler runs first now, and a handled or prevented event skips the reset.

},
[editor, attributes.onMouseDown]
)}
onClick={useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
if (ReactEditor.hasTarget(editor, event.target)) {
Expand Down
234 changes: 232 additions & 2 deletions playwright/integration/examples/shadow-dom.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,121 @@
import { test, expect } from '@playwright/test'
import { clearEditor } from '../support/editor'
import { test, expect, Locator } from '@playwright/test'
import { clearEditor, getEditorHandle } from '../support/editor'

/**
* Replays the DOM side of a macOS composition at the caret of an editor in a
* shadow root, since macOS input methods can't reach Playwright's WebKit. Each
* string in `composing` replaces the composition text, with `compositionupdate`
* and `insertCompositionText` events, then the replay waits for Slate's
* throttled `selectionchange` handler. `commit` ends the composition the way
* WebKit does, with `deleteCompositionText`, a cancelable
* `insertFromComposition` and `compositionend`.
*
* WebKit cancels a composition when script rewrites the composition text or
* moves the caret out of it. If that happens, the replay fires `compositionend`
* and returns `{ cancelled: true }`. The events are untrusted and have no
* target ranges.
*/
const composeLikeWebKit = (
editable: Locator,
{ composing, commit }: { composing: string[]; commit?: string }
) =>
editable.evaluate(
async (editable, { composing, commit }) => {
const root = editable.getRootNode()

if (!(root instanceof ShadowRoot)) {
throw new Error('The editor must be inside a shadow root')
}

const selection = document.getSelection()!
// In WebKit, only `getComposedRanges()` exposes the caret inside a
// shadow root.
const caret = () =>
selection.getComposedRanges({ shadowRoots: [root] })[0] ?? null
const start = caret()

if (!start?.collapsed || !(start.startContainer instanceof Text)) {
throw new Error('The selection must be collapsed in a text node')
}

const textNode = start.startContainer
const offset = start.startOffset
let compositionText = ''
const compositionIsIntact = () => {
const end = caret()
const endOffset = offset + compositionText.length
return (
textNode.isConnected &&
textNode.data.slice(offset, endOffset) === compositionText &&
end?.collapsed &&
end.startContainer === textNode &&
end.startOffset === endOffset
)
}
const fire = (event: Event) => editable.dispatchEvent(event)
const compositionEvent = (type: string, data: string) =>
new CompositionEvent(type, { bubbles: true, composed: true, data })
const inputEvent = (
type: 'beforeinput' | 'input',
inputType: string,
data: string | null,
cancelable = false
) =>
new InputEvent(type, {
bubbles: true,
composed: true,
cancelable,
inputType,
data,
isComposing: true,
})

fire(compositionEvent('compositionstart', ''))

for (const text of composing) {
fire(compositionEvent('compositionupdate', text))
fire(inputEvent('beforeinput', 'insertCompositionText', text))
textNode.replaceData(offset, compositionText.length, text)
compositionText = text
selection.collapse(textNode, offset + text.length)
fire(inputEvent('input', 'insertCompositionText', text))
// Wait longer than Slate's 100 ms `selectionchange` throttle.
await new Promise(resolve => setTimeout(resolve, 200))

if (!compositionIsIntact()) {
fire(compositionEvent('compositionend', ''))
return { cancelled: true }
}
}

if (commit === undefined) {
return { cancelled: false }
}

fire(inputEvent('beforeinput', 'deleteCompositionText', null))
textNode.deleteData(offset, compositionText.length)
selection.collapse(textNode, offset)
fire(inputEvent('input', 'deleteCompositionText', null))

const insert = inputEvent(
'beforeinput',
'insertFromComposition',
commit,
true
)
fire(insert)

if (!insert.defaultPrevented) {
textNode.insertData(offset, commit)
selection.collapse(textNode, offset + commit.length)
fire(inputEvent('input', 'insertFromComposition', commit))
}

fire(compositionEvent('compositionend', commit))
return { cancelled: false }
},
{ composing, commit }
)

test.describe('shadow-dom example', () => {
test.beforeEach(async ({ page }) => await page.goto('/examples/shadow-dom'))
Expand Down Expand Up @@ -52,4 +168,118 @@ test.describe('shadow-dom example', () => {

await expect(textbox).toContainText('New line text')
})

const compositions = [
// Option+E, then o
{
name: 'a dead-key accent',
before: 'C',
composing: ['´'],
commit: 'ó',
after: 'mo',
},
// Japanese Romaji input: kanji, Space, Return
{
name: 'a Japanese conversion',
before: 'A',
composing: ['k', 'か', 'かn', 'かんj', 'かんじ', '漢字'],
commit: '漢字',
after: 'b',
},
]

for (const { name, before, composing, commit, after } of compositions) {
test(`keeps ${name} and the letters after it in WebKit`, async ({
page,
browserName,
}) => {
test.skip(browserName !== 'webkit', 'Replays WebKit composition events')
const outerShadow = page.locator('[data-cy="outer-shadow-root"]')
const innerShadow = outerShadow.locator('> div')
const textbox = innerShadow.getByRole('textbox')
const editor = await getEditorHandle(textbox)
const text = before + commit + after

await clearEditor(textbox)
await page.keyboard.type(before)
await expect(textbox).toHaveText(before)

expect(await composeLikeWebKit(textbox, { composing, commit })).toEqual({
cancelled: false,
})
await page.keyboard.type(after)

await expect(textbox).toHaveText(text)
expect(await editor.evaluate(editor => editor.string([]))).toBe(text)
expect(await editor.evaluate(editor => editor.selection)).toEqual({
anchor: { path: [0, 0], offset: text.length },
focus: { path: [0, 0], offset: text.length },
})
})
}

test('types where you click mid-composition in WebKit', async ({
page,
browserName,
}) => {
test.skip(browserName !== 'webkit', 'Replays WebKit composition events')
const outerShadow = page.locator('[data-cy="outer-shadow-root"]')
const innerShadow = outerShadow.locator('> div')
const textbox = innerShadow.getByRole('textbox')
const editor = await getEditorHandle(textbox)

await clearEditor(textbox)
await page.keyboard.type('Hello')
await expect(textbox).toHaveText('Hello')

// Option+E, with no letter after it
expect(await composeLikeWebKit(textbox, { composing: ['´'] })).toEqual({
cancelled: false,
})

// WebKit ends a real composition right after `mousedown`, but it doesn't
// know about this replayed one, so this relies on Slate clearing the
// composing state on `mousedown` itself.
const text = textbox.locator('[data-slate-string]')
const box = (await text.boundingBox())!
await page.mouse.click(box.x + 1, box.y + box.height / 2)
await page.keyboard.type('Oh ')

await expect(textbox).toHaveText('Oh Hello')
expect(await editor.evaluate(editor => editor.string([]))).toBe('Oh Hello')
})

test('types where you click after blurring mid-composition in WebKit', async ({
page,
browserName,
}) => {
test.skip(browserName !== 'webkit', 'Replays WebKit composition events')
const outerShadow = page.locator('[data-cy="outer-shadow-root"]')
const innerShadow = outerShadow.locator('> div')
const textbox = innerShadow.getByRole('textbox')
const editor = await getEditorHandle(textbox)

await clearEditor(textbox)
await page.keyboard.type('Hello')
await expect(textbox).toHaveText('Hello')

// Option+E, with no letter after it
expect(await composeLikeWebKit(textbox, { composing: ['´'] })).toEqual({
cancelled: false,
})

// On blur, Slate removes the selection and WebKit drops the composition
// without a `compositionend` event, so the test doesn't fire one.
const link = page.getByRole('link', { name: 'GitHub' })
await link.focus()
await expect(link).toBeFocused()

const text = textbox.locator('[data-slate-string]')
const box = (await text.boundingBox())!
await page.mouse.click(box.x + 1, box.y + box.height / 2)
await page.keyboard.type('Oh ')

await expect(textbox).toHaveText('Oh Hello')
expect(await editor.evaluate(editor => editor.string([]))).toBe('Oh Hello')
})
})
Loading