Skip to content

Commit 3db241b

Browse files
committed
fix(core)!: preserve text and caret through IME commits
Map source-mode carets against the live DOM and leave candidate keys and reconversion selections with the input method. Cover immediate typing, undo and external updates across browser event orders. BREAKING CHANGE: setMarkdown called during composition now defers the replacement until the final IME input. The latest replacement wins.
1 parent bf8813e commit 3db241b

11 files changed

Lines changed: 343 additions & 76 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ function Composer() {
100100
| Member | What it does |
101101
| --- | --- |
102102
| `getMarkdown()` | The document as Markdown. |
103-
| `setMarkdown(markdown, { history? })` | Replaces the document. `history: 'clear'` (default) clears undo history; `'keep'` makes the replacement one undo step. Does not emit `change`. |
103+
| `setMarkdown(markdown, { history? })` | Replaces the document. During IME composition, the latest replacement waits for the final input. `history: 'clear'` (default) clears undo history; `'keep'` makes the replacement one undo step. Does not emit `change`. |
104104
| `isEmpty` | True when the document holds only empty paragraphs. |
105105
| `state` | The document and selection, immutable. |
106106
| `commands.*` | Edits. Each applies one change, records one undo step, and returns `true` if it did something: `toggleBold`, `toggleItalic`, `toggleStrike`, `toggleCode`, `setParagraph`, `toggleHeading({ level })`, `toggleBulletList`, `toggleOrderedList`, `toggleTaskList`, `toggleBlockquote`, `toggleCallout({ type? })`, `setCallout({ type })`, `toggleDetails`, `toggleCodeBlock({ language? })`, `setLink({ href })`, `unsetLink`, `updateImage({ alt?, title?, align?, width? })`, `insertText(text, { range? })`, `insertToken(text)`, `insertMarkdown(markdown, options?)`, `insertTable({ rows?, cols? })`, `insertDivider`, `indent`, `outdent`, `undo`, `redo`, `selectAll`, `selectBlocks`, `focus(position?)`, `blur`, `scrollIntoView`. `selectBlocks` selects the blocks the selection touches as whole blocks, as Escape does; it returns `false` when read-only. `updateImage` changes the selected image; `null` removes its title, alignment or width, and a new width drops a height so the image keeps its aspect ratio. `toggleCallout` turns the selected blocks into a callout (`note` unless `type` says otherwise: `note`, `tip`, `important`, `warning` or `caution`), or back into paragraphs. `setCallout` changes the type of the whole callout or quote with the caret; `type: null` makes it a plain quote. `toggleDetails` makes the block with the caret the title of a collapsible section, or, on a title, removes the section and keeps its blocks. `toggleCallout`, `setCallout` and `toggleDetails` return `false` when the `markdown` option turns that syntax off. `scrollIntoView` changes nothing in the document: it scrolls the caret into view in the editor's scrolling containers and the window, for example after an `insertMarkdown` from code. |

‎docs/architecture.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ One `contentEditable` root, not one per block, so native selection crosses block
8080
## Input pipeline
8181

8282
1. **`beforeinput`, cancelled.** `insertText`, `insertParagraph`, `insertLineBreak`, all `delete*` types, `historyUndo`/`historyRedo` and `format*` map to commands. Word and line deletes use the browser's `getTargetRanges()`, so they follow the platform's word boundaries. So does `insertText` when its target range covers text while the selection is a caret: that is how mobile autocorrect and word suggestions replace a word. `insertParagraph` picks the item of an open autocomplete popup, because Android keyboards send Enter with keyCode 229, which `keydown` ignores.
83-
2. **IME composition, not cancelled.** While composing, the editor does not re-render the composed block or move the selection, and hides the toolbar. On each `input` it compares the block's DOM text with the model and applies the difference as one delete and one insert, so `change`, `getMarkdown()`, `isEmpty` and an open autocomplete popup follow the composed text (on Android every word is a composition). The renderer adopts the browser's DOM for the new block object instead of rebuilding it, and only updates its empty state, so the placeholder does not cover composed text. Marks stored before composing (Mod+B, then compose) apply to all of the composed text. The first change records one undo step for the whole composition. On `compositionend` the committed text is read once more; the block is rendered from the model on the next frame, so input that arrives after `compositionend` in the same task (Firefox sends the last `input` then) still counts as the composition, and nothing is re-rendered between two compositions in one keystroke (Korean syllables). A cross-block selection is deleted when composition starts, so a composition always stays inside one block. The unchanged suffix of the composed text container determines the caret after a commit, so a Japanese clause selection does not move later typing into the word. A pointer press outside that container ends the composition before the caret moves, even if the browser did not send `compositionend`.
83+
2. **IME composition, not cancelled.** While composing, the editor does not re-render the composed block or move the selection, and hides the toolbar. On each `input` it compares the block's DOM text with the model and applies the difference as one delete and one insert, so `change`, `getMarkdown()`, `isEmpty` and an open autocomplete popup follow the composed text (on Android every word is a composition). The renderer adopts the browser's DOM for the new block object instead of rebuilding it, and only updates its empty state, so the placeholder does not cover composed text. Marks stored before composing (Mod+B, then compose) apply to all of the composed text. The first change records one undo step for the whole composition. On `compositionend` the committed text is read once more; the block is rendered from the model on the next frame, so input that arrives after `compositionend` in the same task (Firefox sends the last `input` then) still counts as the composition, and nothing is re-rendered between two compositions in one keystroke (Korean syllables). A selection inside one text container stays available to the IME for reconversion. Selections across blocks, table cells or source lines are joined first. That edit shares the composition’s undo step. The unchanged suffix of the composed text container determines the caret after a commit, so a Japanese clause selection does not move later typing into the word. A pointer press outside that container ends the composition before the caret moves, even if the browser did not send `compositionend`.
8484
3. **Fallback.** An `input` event the editor did not cancel goes through the same read-back, and typed text then runs the Markdown shortcuts. A `beforeinput` that cannot be cancelled (from some Android keyboards) for typed text, a replacement, or a deletion inside one text container is left to the browser and read back, so it is not applied twice.
8585
4. **`keydown`**: an open menu takes the navigation keys first. A block selection takes its own keys next (see "Block selection"). Then extension key bindings run in order, ending with `defaultKeymap()` (marks, block types, Mod+K, undo/redo, Tab, submit, Escape). A binding that returns true stops the rest and prevents the browser default. Mod+/ (block menu) and Mod+Shift+V (plain paste) are handled by the editor itself.
8686
ArrowDown on the last line of a code block, table or divider that ends the document adds an empty paragraph below it, and ArrowUp on the first line of one that starts the document adds one above it (`exitBlock`). Elsewhere the browser moves the caret. When it passes over a block that holds a caret (Firefox skips list items, which are flex boxes, and WebKit skips code blocks and tables), the editor moves the caret into that block at the same horizontal position. After any caret key the editor keeps the caret 8 px clear of the scroll container's edge. Backspace at the start of a block is handled on `keydown`, because WebKit sends no `beforeinput` there when no editable text comes before the caret. A click in the empty space below such a final block also adds a paragraph. Enter three times at the end of a code block still leaves it.
@@ -214,7 +214,7 @@ One general popup; the caller owns the syntax. The editor implements the behavio
214214

215215
**Placement** (`anchor.ts`). The popup's start edge lines up with the trigger's (its right edge in right-to-left text), 4 px below the caret's line, so it does not move sideways while the query is typed. When the token wraps, it lines up with the caret. It keeps its side while open unless it no longer fits. It follows scrolling of any ancestor (the document `scroll` listener in the capture phase), and window and `visualViewport` resizes once per animation frame. It hides while the trigger is outside every clipping or scrolling ancestor.
216216

217-
**IME.** `keydown` with `isComposing` or keyCode 229 never reaches the popup. On Safari, which sends the Enter that commits a composition after `compositionend`, the first key within 100 ms after it does not either. While composing, the model follows the composed text, so the query does too; `items` gets `composing: true`, and an empty result does not hide a list that is shown (a Pinyin reading matches nothing until it is converted). The query is asked again once the composition ends. Showing or moving the popup never touches the composed block: the popup is outside the editor root. A click on an item while composing first reads the composition into the model and renders the block, which ends the browser's composition, then picks: the one place the editor ends a composition on purpose.
217+
**IME.** `keydown` with `isComposing` or keyCode 229 never reaches the popup. The editor also checks its active composition. Once it ends, an ordinary Enter or arrow key works immediately. While composing, the model follows the composed text, so the query does too; `items` gets `composing: true`, and an empty result does not hide a list that is shown (a Pinyin reading matches nothing until it is converted). The query is asked again once the composition ends. Showing or moving the popup never touches the composed block: the popup is outside the editor root. A click on an item while composing first reads the composition into the model and renders the block, which ends the browser's composition, then picks the suggestion.
218218

219219
**Accessibility.** The root keeps `role="textbox"` and has `aria-autocomplete="list"` when any suggestion exists. While the popup shows something, the root also has `aria-haspopup="listbox"`, `aria-controls` (the listbox) and `aria-activedescendant` (the highlighted option). `aria-expanded` is not supported on a textbox, so, as in CodeMirror, the listbox carries `aria-expanded="true"`. The listbox is named by the suggestion's `label`.
220220

@@ -330,7 +330,7 @@ Paragraphs, headings, quotes, list items and table cells have `dir="auto"`, so e
330330

331331
## React wrapper
332332

333-
`<MarkdownEditor>` creates one `Editor` per mount and forwards its `ref` to it. `onChange` fires at most once per animation frame. The wrapper keeps a short queue of the values it emitted, and calls `setMarkdown` only when a new `value` prop is not one of them, so a parent that re-renders with a slightly stale value does not overwrite newer typing. It calls `onChange` inside `flushSync`, so the parent renders each emitted value at once, as React does for a native input's `onChange`. Otherwise the update could still be queued when the parent sets a value that equals the one it last rendered, such as clearing the box right after fast typing and Mod+Enter, and the wrapper would not see a new `value` and would keep the typed text. A new `value` that arrives while an IME is composing is held and applied on `compositionend`. `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveUrl`, `onLinkClick` and `theme` go through `setOptions`, and so does `extensions`, which updates the callbacks of `suggestion()` extensions. The editor is recreated, keeping its Markdown, only when the names of its extensions change. The editor is created with wrappers that call the latest `onChange`, `onSubmit`, `onFocus` and `onBlur` props, so a parent may pass inline functions without recreating the editor or keeping refs. `useSuggestion(editor, name?)` subscribes to `suggestionChange` for apps that draw their own popup. `onSubmit(markdown)` receives the current Markdown after flushing pending changes.
333+
`<MarkdownEditor>` creates one `Editor` per mount and forwards its `ref` to it. `onChange` fires at most once per animation frame. The wrapper keeps a short queue of the values it emitted, and calls `setMarkdown` only when a new `value` prop is not one of them, so a parent that re-renders with a slightly stale value does not overwrite newer typing. It calls `onChange` inside `flushSync`, so the parent renders each emitted value at once, as React does for a native input's `onChange`. Otherwise the update could still be queued when the parent sets a value that equals the one it last rendered, such as clearing the box right after fast typing and Mod+Enter, and the wrapper would not see a new `value` and would keep the typed text. A new `value` that arrives while an IME is composing waits for the editor to reconcile the final native input, including input delivered after `compositionend`. `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveUrl`, `onLinkClick` and `theme` go through `setOptions`, and so does `extensions`, which updates the callbacks of `suggestion()` extensions. The editor is recreated, keeping its Markdown, only when the names of its extensions change. The editor is created with wrappers that call the latest `onChange`, `onSubmit`, `onFocus` and `onBlur` props, so a parent may pass inline functions without recreating the editor or keeping refs. `useSuggestion(editor, name?)` subscribes to `suggestionChange` for apps that draw their own popup. `onSubmit(markdown)` receives the current Markdown after flushing pending changes.
334334

335335
`useEditor(options, deps)` creates an editor on a detached element and `<EditorContent>` moves that element into the page, as in Tiptap. Autofocus waits until the element is mounted.
336336

‎docs/ime-checklist.md‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Manual IME checklist
22

3-
Automated tests (`e2e/ime.spec.ts`) simulate IME input in Chromium only: composition goes through the Chrome DevTools Protocol, and the events mobile keyboards send are dispatched by the test. They cannot show the candidate window, the order in which other browsers send events, or what a real keyboard does. Before a release, run this checklist by hand with real input methods.
3+
The browser tests in `e2e/ime.spec.ts` drive Chromium through the Chrome DevTools Protocol. In Chromium, Firefox and WebKit they also replay composition events with the last input arriving before or after `compositionend`. The native candidate window and operating-system keyboard still need a device check. Before a release, run this checklist by hand with real input methods.
44

55
## Setups
66

@@ -47,11 +47,10 @@ The last column names the automated test that covers the same behavior in Chromi
4747
| 24 | Android and iOS: with the tag popup open and a word still underlined, tap an item. The output has the picked tag once, and the underlined word is not added again. | a click on an item while composing commits the composed text once, then picks |
4848
| 25 | Android: type `#wor` in a word that already exists (`#wor` then `k`, all underlined by the keyboard). The popup opens as you type. | composed text in a token opens the popup and filters it |
4949
| 26 | Safari, Pinyin: in an empty paragraph, type a reading (`ceshi`) and pick a candidate with Space or a number. The output has the word picked (`测试`), not the reading. Then type a reading in another empty paragraph and delete it with Backspace: the paragraph stays empty. | the committed word replaces the reading; a composition deleted without a commit leaves the block empty (events only) |
50-
5150
| 27 | Japanese: convert a sentence with several clauses, select a clause in the middle, then commit and type another character. It appears after the committed sentence. | committing a Japanese clause selection leaves the caret after the word (Chromium CDP) |
5251
| 28 | Compose in a table cell, click a paragraph, type more text, then save and reload. Both the composed word and the later text remain. | leaving an unfinished table composition keeps later typing in saved Markdown |
52+
| 29 | In Markdown source mode, type 안녕하세요 at the end of a line, pause two seconds, commit and immediately type a space. Continue typing. Repeat with Japanese and Chinese candidates and in the middle of existing text. The space and the next character follow the committed word. | source mode inserts an immediate space; source mode keeps a space after the last committed Korean syllable |
53+
| 30 | Select an existing Japanese word, including a backward selection, and start reconversion (Windows conversion key or macOS Kana twice). Pick a different candidate, type punctuation, then undo both edits. The original word and surrounding text return. | reconversion keeps a backward selection |
54+
| 31 | In the link or image alt-text field, use Enter to confirm a candidate and Escape to dismiss the candidate list. The field keeps focus. A separate Enter applies the value and a separate Escape closes the field. | composition keys stay with the IME |
5355

54-
## Not handled yet
55-
56-
- A composition that starts over a selection inside one block deletes the selection first. Japanese reconversion (select text, then press the conversion key) may lose the selected text as the reading. Check on Windows (Microsoft IME, 変換 key) and macOS (Kana key twice).
57-
- Chinese IMEs type `、` for `/` by default. It does not open the slash menu.
56+
Some Chinese input methods type `、` on the slash key. The editor keeps it as punctuation. Enter `/` or `/` to open the slash menu.

0 commit comments

Comments
 (0)