From 33b81c272ac930582445f696bbfd9649c09d6e2f Mon Sep 17 00:00:00 2001 From: Vladimir Tikhonov Date: Wed, 4 Nov 2026 17:12:39 +0100 Subject: [PATCH 1/3] Fix dead-key and input method typing in Safari shadow roots --- .changeset/safari-shadow-dom-composition.md | 5 + .../slate-react/src/components/editable.tsx | 16 +- .../integration/examples/shadow-dom.test.ts | 203 +++++++++++++++++- 3 files changed, 221 insertions(+), 3 deletions(-) create mode 100644 .changeset/safari-shadow-dom-composition.md diff --git a/.changeset/safari-shadow-dom-composition.md b/.changeset/safari-shadow-dom-composition.md new file mode 100644 index 0000000000..69c39d05d9 --- /dev/null +++ b/.changeset/safari-shadow-dom-composition.md @@ -0,0 +1,5 @@ +--- +'slate-react': patch +--- + +In Safari, typing with a dead key or an input method in an editor inside a shadow root no longer loses text diff --git a/packages/slate-react/src/components/editable.tsx b/packages/slate-react/src/components/editable.tsx index 36a1d64950..16da0e0086 100644 --- a/packages/slate-react/src/components/editable.tsx +++ b/packages/slate-react/src/components/editable.tsx @@ -329,7 +329,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() @@ -1509,6 +1514,15 @@ 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)) { + IS_COMPOSING.set(editor, false) + setIsComposing(false) + } } IS_FOCUSED.delete(editor) diff --git a/playwright/integration/examples/shadow-dom.test.ts b/playwright/integration/examples/shadow-dom.test.ts index f9308f5272..a0d5695344 100644 --- a/playwright/integration/examples/shadow-dom.test.ts +++ b/playwright/integration/examples/shadow-dom.test.ts @@ -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')) @@ -52,4 +168,87 @@ 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 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') + }) }) From 4d79f056e8dd50e05d5ab9581b582cf2e9df27a2 Mon Sep 17 00:00:00 2001 From: Vladimir Tikhonov Date: Wed, 4 Nov 2026 19:15:15 +0100 Subject: [PATCH 2/3] Put the caret where the user clicks during a Safari composition In WebKit, a click ends an open composition right after mousedown. In a shadow root, the re-render after compositionend then wrote the old Slate selection back over the click, so the caret stayed where the composition started. Clear the composing state on mousedown, so the re-render runs before the click moves the caret, and add a WebKit replay test for it. --- .changeset/safari-shadow-dom-composition.md | 2 +- .../slate-react/src/components/editable.tsx | 21 +++++++++++++ .../integration/examples/shadow-dom.test.ts | 31 +++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/.changeset/safari-shadow-dom-composition.md b/.changeset/safari-shadow-dom-composition.md index 69c39d05d9..af8e566605 100644 --- a/.changeset/safari-shadow-dom-composition.md +++ b/.changeset/safari-shadow-dom-composition.md @@ -2,4 +2,4 @@ 'slate-react': patch --- -In Safari, typing with a dead key or an input method in an editor inside a shadow root no longer loses text +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 diff --git a/packages/slate-react/src/components/editable.tsx b/packages/slate-react/src/components/editable.tsx index 16da0e0086..c34a238319 100644 --- a/packages/slate-react/src/components/editable.tsx +++ b/packages/slate-react/src/components/editable.tsx @@ -1535,6 +1535,27 @@ export const Editable = forwardRef( flushDOMSelectionChange, ] )} + onMouseDown={useCallback( + (event: React.MouseEvent) => { + // 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 && + ReactEditor.isComposing(editor) && + ReactEditor.hasTarget(editor, event.target) + ) { + IS_COMPOSING.set(editor, false) + setIsComposing(false) + } + + isEventHandled(event, attributes.onMouseDown) + }, + [editor, attributes.onMouseDown] + )} onClick={useCallback( (event: React.MouseEvent) => { if (ReactEditor.hasTarget(editor, event.target)) { diff --git a/playwright/integration/examples/shadow-dom.test.ts b/playwright/integration/examples/shadow-dom.test.ts index a0d5695344..fe4747f98e 100644 --- a/playwright/integration/examples/shadow-dom.test.ts +++ b/playwright/integration/examples/shadow-dom.test.ts @@ -218,6 +218,37 @@ test.describe('shadow-dom example', () => { }) } + 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, From 7b0a70fb611ddb8851310d648feae196c48e6f9e Mon Sep 17 00:00:00 2001 From: Vladimir Tikhonov Date: Tue, 1 Dec 2026 11:05:32 +0100 Subject: [PATCH 3/3] Clear composing on mousedown only where Safari ends the composition Safari on macOS ends an open composition when a mousedown runs its default action, so the editor clears its composing state then. It did that before calling the app's onMouseDown and without looking at the event. A prevented mousedown keeps the composition open, though. Clearing the state made the editor write its selection back to the DOM, and that cancelled the composition. - Call onMouseDown first. Skip the reset when it handles the event, or when the default is prevented, also by an element inside the editor. - Skip the reset on iOS and iPadOS, where WebKit doesn't end a composition on mousedown. iPadOS reports a Mac user agent, so check for touch too. - Use setComposing for the blur and mousedown resets. - Add unit tests for the mousedown and blur resets. --- .../slate-react/src/components/editable.tsx | 31 +-- .../test/composition-state-webkit.spec.tsx | 188 ++++++++++++++++++ .../slate-react/test/readonly-events.spec.tsx | 1 + 3 files changed, 207 insertions(+), 13 deletions(-) create mode 100644 packages/slate-react/test/composition-state-webkit.spec.tsx diff --git a/packages/slate-react/src/components/editable.tsx b/packages/slate-react/src/components/editable.tsx index e8a961c0d3..f65a3befe5 100644 --- a/packages/slate-react/src/components/editable.tsx +++ b/packages/slate-react/src/components/editable.tsx @@ -1525,8 +1525,7 @@ export const Editable = forwardRef( // `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) + setComposing(false) } } @@ -1538,28 +1537,34 @@ export const Editable = forwardRef( editor, attributes.onBlur, flushDOMSelectionChange, + setComposing, ] )} onMouseDown={useCallback( (event: React.MouseEvent) => { - // 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. + // 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 && + !IS_IOS && + !navigator.maxTouchPoints && ReactEditor.isComposing(editor) && ReactEditor.hasTarget(editor, event.target) ) { - IS_COMPOSING.set(editor, false) - setIsComposing(false) + setComposing(false) } - - isEventHandled(event, attributes.onMouseDown) }, - [editor, attributes.onMouseDown] + [attributes.onMouseDown, editor, setComposing] )} onClick={useCallback( (event: React.MouseEvent) => { diff --git a/packages/slate-react/test/composition-state-webkit.spec.tsx b/packages/slate-react/test/composition-state-webkit.spec.tsx new file mode 100644 index 0000000000..93b06bed10 --- /dev/null +++ b/packages/slate-react/test/composition-state-webkit.spec.tsx @@ -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 = {}) => { + const editor = withReact(createEditor()) + const composing: boolean[] = [] + const ComposingProbe = () => { + composing.push(useComposing()) + return null + } + const { getByRole, getByTestId } = render( + + ( +

+ + {children} + event.preventDefault()} + /> +

+ )} + {...props} + /> +
+ ) + 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('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('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) + }) +}) diff --git a/packages/slate-react/test/readonly-events.spec.tsx b/packages/slate-react/test/readonly-events.spec.tsx index 8501d17fb1..d2ca5e0c08 100644 --- a/packages/slate-react/test/readonly-events.spec.tsx +++ b/packages/slate-react/test/readonly-events.spec.tsx @@ -19,6 +19,7 @@ Object.defineProperty(HTMLElement.prototype, 'isContentEditable', { const events = [ ['onClick', fireEvent.click], + ['onMouseDown', fireEvent.mouseDown], ['onCopy', fireEvent.copy], ['onBeforeInput', fireEvent.compositionEnd], [