Skip to content

[lexical] Bug Fix: Preserve raw IME input when Chinese composition is cancelled - #8181

Closed
ywsoul wants to merge 1 commit into
meta:mainfrom
ywsoul:fix/ime-composition-cancel-text-loss
Closed

ywsoul wants to merge 1 commit into
meta:mainfrom
ywsoul:fix/ime-composition-cancel-text-loss

Conversation

@ywsoul

@ywsoul ywsoul commented Feb 27, 2026

Copy link
Copy Markdown

Bug

When a user types pinyin (e.g. ceshi) in a Chinese IME on an empty Lexical editor and presses Enter to dismiss the IME without selecting a candidate, the editor clears the text instead of preserving the raw pinyin input.

Root Cause

On macOS Chrome with the native Chinese IME, pressing Enter to cancel composition triggers:

  1. compositionend(data='') — the browser clears the DOM text
  2. insertText(data='ceshi') — the browser restores the raw pinyin as committed text

Previously, Lexical would schedule the text node for removal upon seeing the empty composition result in step 1. By the time step 2 fires, the insertText event would either append to stale text (causing duplication like cesce's) or insert into a node that was about to be removed (causing text loss).

Fix

Two changes to $updateTextNodeFromDOMContent in LexicalUtils.ts:

  1. Clear stale text immediately — node.setTextContent('') ensures the browser's subsequent insertText event inserts into a clean node rather than appending to old composition text
  2. Defer removal with content check — the setTimeout callback now checks if the Lexical node has been repopulated by insertText before removing it

Test Plan

  • Added E2E test: Can cancel Chinese pinyin IME on empty editor and preserve raw input via insertText
  • All 16 Composition E2E tests pass
  • All 2574 unit tests pass (2 pre-existing failures unrelated to this change)

… cancelled

When a user types pinyin (e.g. "ceshi") in a Chinese IME on an empty editor and presses Enter to dismiss the IME without selecting a candidate, the browser fires compositionend(data='') which clears the DOM text, followed by an insertText event that restores the raw pinyin. Previously, Lexical would immediately schedule the text node for removal upon seeing the empty composition result, causing the subsequently restored text to either be lost or duplicated.

This fix makes two changes to $updateTextNodeFromDOMContent:

1. Clear the node's text content immediately (node.setTextContent('')) so that the browser's subsequent insertText event inserts into a clean node rather than appending to stale composition text.

2. Defer the node removal via setTimeout and re-check the node's text content before removing — if an insertText event has already restored text, the node is preserved.

Also adds an E2E test that simulates this exact scenario using CDP.
@vercel

vercel Bot commented Feb 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview, Comment Feb 27, 2026 6:21am
lexical-playground Ready Ready Preview, Comment Feb 27, 2026 6:21am

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Feb 27, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Feb 27, 2026
// subsequent insertText event from the browser inserts into a clean
// node rather than appending to stale composition text.
const editor = getActiveEditor();
node.setTextContent('');

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 reconciler will remove empty text nodes from the document. Not sure this is working the way you think it is

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.

Image

The above gif is the performance after annotating the code.

This line of code actually fixes the duplicate string caused by the input being intercepted.

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.

Does node.remove() have the same effect?

@etrepum

etrepum commented Feb 27, 2026

Copy link
Copy Markdown
Collaborator

Can you show a video of a reproduction for this? I'm not able to reproduce on macOS on any browser with the following steps:

@etrepum

etrepum commented Feb 27, 2026

Copy link
Copy Markdown
Collaborator

There are also no unit test failures, so I'm not sure where that information is coming from in your test plan

@ywsoul

ywsoul commented Feb 28, 2026

Copy link
Copy Markdown
Author

Can you show a video of a reproduction for this? I'm not able to reproduce on macOS on any browser with the following steps:

Thank you for your reply.

This is the problematic gif I recorded.

emptyInput

This is the gif after my local run repair, and the result is in line with the interaction expectations of the browser.

emptyInput-fix

@etrepum

etrepum commented Feb 28, 2026

Copy link
Copy Markdown
Collaborator

I still don't know how to reproduce what you've recorded, the expected behavior happens for me with the current playground:

chrome-ime.mov

This is using macOS 26.3 and Chrome 145.0.7632.117 with the Pinyin - Simplified IME

@ywsoul

ywsoul commented Feb 28, 2026

Copy link
Copy Markdown
Author

I still don't know how to reproduce what you've recorded, the expected behavior happens for me with the current playground:

chrome-ime.mov
This is using macOS 26.3 and Chrome 145.0.7632.117 with the Pinyin - Simplified IME

ok, i get it

I changed several input methods and finally found that this is an input method compatibility problem. The Xunfei input method I used was developed by an algorithm company in China. This input method is ok in other editors, but it is not effective in lexical. Therefore, this case is up to you to judge whether it needs to be combined.

@etrepum

etrepum commented Feb 28, 2026

Copy link
Copy Markdown
Collaborator

Maybe it would be better to report this as a bug to Xunfei, rather than add code to lexical to work around a bug in that non-standard IME? Since we don't have any automated CI coverage for mobile devices it can be risky to change this code.

@ywsoul

ywsoul commented Feb 28, 2026

Copy link
Copy Markdown
Author

Maybe it would be better to report this as a bug to Xunfei, rather than add code to lexical to work around a bug in that non-standard IME? Since we don't have any automated CI coverage for mobile devices it can be risky to change this code.

OK, thank you very much for your patient follow-up. I will turn off the PR later. At that time, I mentioned PR to Lexical because Xunfei was normal in my daily use, but there was a problem in Lexical, and thanks to Lexical, it was open source. Yes, I have found a solution, so I hope to solve this problem that others may also encounter. I understand your concern, so I plan to go to Xunfei to have a look.

Finally, I am a fan of Lexical. I like this editor very much. It realizes all my fantasies about the editor. I am also recommending Lexical to my friends around me. I wish you all the best!

@ywsoul ywsoul closed this Mar 1, 2026
justinchen13 added a commit to justinchen13/lexical that referenced this pull request Oct 17, 2026
…lled desktop WebKit compositions

## Description

With macOS system Pinyin in a desktop WKWebView, start after existing text (`abc`), type unconfirmed `ni`, then press Backspace twice or Escape. WebKit sends an empty DOM `compositionend` without `insertFromComposition`, but Lexical retains its composition key. The next ordinary Enter is dropped before `KEY_ENTER_COMMAND` can dispatch.

Finish empty desktop WebKit compositions immediately. Keep ignoring the trailing `keyCode=229` already consumed by the IME, preserving meta#7061's protection against extra body deletion; ordinary Backspace/Enter (`8`/`13`) work normally. Nonempty WebKit completion retains its deferred path. This system-Pinyin cancellation differs from the third-party Xunfei case in closed meta#8181.

Cancellation synchronizes current text and removes only a proven editor-owned placeholder. This requires tracking actual insertion and maintaining or invalidating its range through text edits, split/merge, JSON updates and active selection slices. The metadata belongs to the active node object: same-key ephemeral/export copies cannot change it, and editor-free copy edits remain supported. The text schema routes JSON writes through `setTextContent`; both affected generated updaters follow that schema. There is no old whole-node rollback or blanket NBSP removal; public APIs and node JSON format are unchanged.

The regressions enter through native DOM `compositionend` handlers, covering PlainText/RichText, trailing keys, real NBSP, empty roots, selection/format/type boundaries, model/JSON updates and live/copy isolation. The browser replays are synthetic. A separate system-Pinyin/HID capture validates the frozen implementation physically.

Reproduction sources, versioned failures, raw native records and exact commands are in the [commit-pinned evidence README](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/README.md), [source/build identity](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/source-manifest.json), and [content-hash index](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/evidence-index.json). Evidence lives on a separate fork branch; this PR contains only the ten source/test files.

## Test plan

### Before

Exact upstream baseline: `cb21da40de69c1eedc2b9ec60001fef0d3b1770a` (0.52.0). Historical run of the **original 58-case** regression file, before later JSON/copy cases were added:

```sh
VITEST_BROWSER=chromium pnpm run test-browser packages/lexical/src/__tests__/browser/LexicalSafariComposition.test.ts
```

Actual output, exit 1 ([log](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/logs/reviewed-final-regression.log)):

```text
 Test Files  1 failed (1)
      Tests  58 failed (58)
```

The [historical native dataset](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/historical-events-v2.jsonl)'s **before** variant used this exact unmodified upstream commit and reproduced six missing-Enter failures. It is reused as the baseline; its older after variant is not final-fix evidence. Additional intermediate-version failures are indexed in the README.

### After

The following existing checks apply to the identical final ten-file fingerprints; committing/publishing does not change those bytes.

```sh
MOZ_DISABLE_CONTENT_SANDBOX=1 VITEST_BROWSER=chromium,firefox,webkit pnpm run test-browser packages/lexical/src/__tests__/browser/LexicalSafariComposition.test.ts packages/lexical/src/__tests__/browser/LexicalComposition.test.ts
```

Actual output, exit 0 ([log](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/logs/v4-browser.log)):

```text
 Test Files  6 passed (6)
      Tests  358 passed | 2 skipped (360)
```

```sh
pnpm run test-unit packages/lexical/src packages/lexical-code-core/src packages/lexical-selection/src packages/lexical-clipboard/src packages/lexical-html/src packages/lexical-markdown/src packages/lexical-yjs/src
```

Actual output, exit 0 ([log](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/logs/v4-unit.log)):

```text
 Test Files  142 passed (142)
      Tests  3524 passed (3524)
```

Source/test TypeScript (`pnpm run tsc`, `pnpm run tsc-test`), ESLint and Prettier on all ten changed files exited 0. [ESLint](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/logs/v4-lint-final.log) reported 0 errors and 1 naming warning for the test's `slice` callback (`@lexical/rules-of-lexical`); the frozen spelling is retained. Generator drift, schema parity and clone/serialization are covered by the unit run. The previous Flow full-check reported `Found 0 errors` (exit 0); its 152 definition/config/lock inputs are unchanged, so it was reused. [Quality scope and log references](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/quality-scope.json).

Final native capture: macOS 27.0.1 (26A434), arm64, system WKWebView/WebKit 22625.1.29.11.28; exact input source `com.apple.inputmethod.SCIM.ITABC`. The separate source fixture rebuild and evidence verification commands are:

```sh
node /path/to/ime-repro/build.mjs .
python3 /path/to/ime-repro/verify.py --checkout .
```

Actual verifier output, exit 0 ([log](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/logs/final-native-verify.log), [raw events](https://github.com/13Cohen/lexical/blob/357bb810499d05054e7f1dde397bad0c02070488/packages/lexical/ime-cancellation-evidence/events.jsonl)):

```text
Native final active-node-v4: 14/14 scenarios passed (6 PlainText, 8 RichText).
All 276 DOM input/composition/key events and 64 keydowns are trusted; no modifier shortcut was used.
Exact system Pinyin verified; previous input source and application/focus restored.
Historical exact-upstream baseline reused: 6 missing-Enter failures; no baseline rerun.
```

All 14 following ordinary Enter presses dispatched once; consumed `229` keys did not cause an extra command/deletion. Space confirmation committed “你”; Enter confirmation committed raw “ni”. Cancellation, real NBSP, cross-paragraph text, active JSON/slices and independent copies passed. Seven cases invoke programmatic model APIs after a trusted native compositionstart, then continue real OS input/cancellation; these are explicit API/IME interactions, not remote collaboration. All 134 build inputs matched and the post-capture bundle rebuild was byte-identical.

Physical coverage is limited to this system WKWebView/Pinyin setup. Standalone Safari/Chrome/Firefox, other OSes/IMEs, CodeHighlight/custom-node native matrices, no-input immediate cancellation and live remote Yjs were not physically exercised. The full monorepo/CI matrix, E2E and release/site builds were not repeated; older full-suite results are historical only. Detailed environment/tool versions and reuse boundaries are in the evidence README.

This branch was successfully deployed

2 active deployments
Preview – lexical-playground — 673de4fb Deployed Feb 27, 2026 by vercel[bot]
Preview – lexical — 673de4fb Deployed Feb 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants