From b2e5756e8c3ffec495d0b7d76a2e7ce82ab44e86 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 08:47:25 +0000 Subject: [PATCH 1/3] fix(core): keep the caret where a tap put it while composing Android keyboards keep the word being typed in a composition. A tap moves the caret first, and the keyboard then finishes the word, so the browser sends only compositionend. When the tap landed in the composed block, the selection change was ignored while composing, and the commit put the caret after the word again. In source mode the whole document is that block, so no tap could move the caret there; in rich mode a tap in the same paragraph failed the same way. - Mark a composition that a pointer pressed inside without ending it. - On its commit, take the browser's caret instead of the end of the committed word. Reported in usememos/memos#6587. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MMvmJqj53yKuzHpU82eCUY --- docs/architecture.md | 2 +- docs/ime-checklist.md | 1 + e2e/ime.spec.ts | 40 +++++++++++++++++++++++++++++++++++ packages/editor/src/editor.ts | 17 ++++++++++++--- 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 63ee099..7e7b278 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -80,7 +80,7 @@ One `contentEditable` root, not one per block, so native selection crosses block ## Input pipeline 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. -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`. +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`. A pointer press inside it keeps the composition; when the keyboard then finishes the word (Android keyboards do this after a tap moved the caret), the caret stays where the tap put it. In source mode the whole document is that container. 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. 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. 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. When the browser does not move the caret off the edge line of its block at all (WebKit when no editable text lies past such a block, Firefox up from the first line of a code block), the editor moves it into the next block on the key's `keyup`. It waits for the `keyup` because on iOS a hardware keyboard's arrow moves the caret after the `keydown`'s tasks and the next frame, but before the `keyup`, so a check any sooner would move the caret a second time. 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. diff --git a/docs/ime-checklist.md b/docs/ime-checklist.md index 8d3788b..6b13821 100644 --- a/docs/ime-checklist.md +++ b/docs/ime-checklist.md @@ -52,5 +52,6 @@ The last column names the automated test that covers the same behavior in Chromi | 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 | | 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 | | 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 | +| 32 | Android (Gboard or an AOSP keyboard such as HeliBoard), in Markdown source mode and in a paragraph in rich mode: type a word and, while it is still underlined, tap earlier in the same text. Type a character. It appears where you tapped, not after the word. | a tap while composing moves the caret when the keyboard finishes the word (events only) | Some Chinese input methods type `、` on the slash key. The editor keeps it as punctuation. Enter `/` or `/` to open the slash menu. diff --git a/e2e/ime.spec.ts b/e2e/ime.spec.ts index a0a936e..bc72549 100644 --- a/e2e/ime.spec.ts +++ b/e2e/ime.spec.ts @@ -679,6 +679,46 @@ for (const move of ['caret key', 'pointer'] as const) { }); } +// Android keyboards keep the word being typed in a composition. A tap moves the +// caret first; the keyboard then finishes the word, and the browser sends only +// compositionend. The composition's own block holds the tap in source mode, +// where the document is one block, and in rich mode for a tap in the same paragraph. +for (const { mode, markdown, tapIn, expected } of [ + { mode: 'source', markdown: 'alpha\n\nbeta ', tapIn: 'alpha', expected: 'alXpha\n\nbeta gamma' }, + { mode: 'rich', markdown: 'alpha beta', tapIn: 'alpha', expected: 'alXpha betagamma' }, +]) { + test(`a tap while composing moves the caret when the keyboard finishes the word (${mode})`, async ({ page }) => { + await installIme(page); + await page.evaluate(({ mode, markdown, tapIn }) => { + const editor = (window as any).editor; + editor.setOptions({ mode }); + editor.setMarkdown(markdown); + editor.commands.focus('end'); + const ime = (window as any).ime; + ime.start(); + ime.update('gam'); + ime.update('gamma'); + const root = document.getElementById('editor')!; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let text: Text | null = null; + while (walker.nextNode()) { + if ((walker.currentNode as Text).data.includes(tapIn)) { + text = walker.currentNode as Text; + break; + } + } + text!.parentElement!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'touch' })); + getSelection()!.collapse(text!, text!.data.indexOf(tapIn) + 2); + document.dispatchEvent(new Event('selectionchange')); + text!.parentElement!.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'touch' })); + root.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: 'gamma' })); + }, { mode, markdown, tapIn }); + await frame(page); + await page.keyboard.type('X'); + expect(await md(page)).toBe(expected); + }); +} + test('leaving an unfinished table composition keeps later typing in saved Markdown', async ({ page }) => { await page.evaluate(() => { const editor = (window as any).editor; diff --git a/packages/editor/src/editor.ts b/packages/editor/src/editor.ts index 4b333df..21355d4 100644 --- a/packages/editor/src/editor.ts +++ b/packages/editor/src/editor.ts @@ -431,6 +431,8 @@ export class Editor { ended: boolean; marks: EditorState['storedMarks']; recorded: boolean; + /** A pointer went down in the editor while composing without ending the composition: the caret may have moved (see `syncComposition`). */ + pointer?: boolean; } | null = null; private pendingMarkdown: { markdown: string; history?: 'clear' | 'keep' } | null = null; /** @@ -2315,11 +2317,17 @@ export class Editor { const read = this.readDom(before, composition.marks, composition.blockId, ended); if (!read && !composition.ended) return; const content = containerContent(getBlock((read ?? before).doc, composition.blockId), composition.cell); + // A tap while composing moved the caret before the keyboard finished the + // word (Android keyboards compose every word): the caret is where it went. + // In source mode the whole document is the composed block, so every tap is one. + const live = composition.ended && composition.pointer && !replaced ? this.readDomSelection() : null; // A committed word ends before the unchanged suffix, even when the IME // left the DOM caret on an active clause or sent compositionend before input. - const focus = composition.ended && content - ? { blockId: composition.blockId, cell: composition.cell, offset: Math.max(0, inlineLength(content) - composition.trailing) } - : this.readDomSelection()?.focus; + const focus = live && isCollapsed(live) + ? live.focus + : composition.ended && content + ? { blockId: composition.blockId, cell: composition.cell, offset: Math.max(0, inlineLength(content) - composition.trailing) } + : this.readDomSelection()?.focus; const next = read ?? before; const selected = focus ? { ...next, selection: clampSelection(next.doc, { anchor: focus, focus }) } : next; if (!read) { @@ -3394,6 +3402,9 @@ export class Editor { const content = block && contentElement(block, this.composition.cell); // A suggestion commits in pick(), after its menu has received the click. if (target && !content?.contains(target) && !this.suggestions.contains(target)) this.endComposition(); + // A tap in the composed block or cell keeps the composition, and the + // browser moves the caret before the keyboard finishes the word. + else if (target && this.root.contains(target)) this.composition.pointer = true; } if (this.toolbar?.menu && !(target && this.toolbar.contains(target))) this.toolbar.closeMenu(); if (!this.blockMenu.isOpen) return; From 72e45ab8104c1d6d4bb657fa291fd48b7292bc99 Mon Sep 17 00:00:00 2001 From: boojack Date: Sun, 29 Nov 2026 22:49:07 +0800 Subject: [PATCH 2/3] fix(core): take the tap's caret only when the tap finished the word A press in the composed text was remembered for the rest of the composition, so a later commit took the DOM caret even when the input method had kept composing (a click on a Japanese clause) and left that caret inside the word. - Forget the press once more text is composed. - Treat the move as a caret move by the user: clear stored marks, break the undo group and emit selectionChange, which no commit did when the keyboard sent only compositionend. - Do not open an autocomplete popup at the tapped caret when the composition settles: nothing was typed there. - Keep a word selected by a long press or double tap while composing. A range that touches the end of the committed word is still left to the commit, since WebKit selects the composed text itself. --- docs/architecture.md | 2 +- docs/ime-checklist.md | 2 + e2e/ime.spec.ts | 89 +++++++++++++++++++++++++++++++++++ packages/editor/src/editor.ts | 47 +++++++++++++----- 4 files changed, 127 insertions(+), 13 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 7e7b278..2ac49b0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -80,7 +80,7 @@ One `contentEditable` root, not one per block, so native selection crosses block ## Input pipeline 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. -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`. A pointer press inside it keeps the composition; when the keyboard then finishes the word (Android keyboards do this after a tap moved the caret), the caret stays where the tap put it. In source mode the whole document is that container. +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`. A pointer press inside it keeps the composition; when the keyboard then finishes the word (Android keyboards do this after a tap moved the caret), the caret or the word selection stays where the press put it, `selectionChange` reports it, and no autocomplete popup opens there. A press the input method takes itself (a click on a clause) does not count once more text is composed. In source mode the whole document is that container. 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. 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. 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. When the browser does not move the caret off the edge line of its block at all (WebKit when no editable text lies past such a block, Firefox up from the first line of a code block), the editor moves it into the next block on the key's `keyup`. It waits for the `keyup` because on iOS a hardware keyboard's arrow moves the caret after the `keydown`'s tasks and the next frame, but before the `keyup`, so a check any sooner would move the caret a second time. 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. diff --git a/docs/ime-checklist.md b/docs/ime-checklist.md index 6b13821..79a8aef 100644 --- a/docs/ime-checklist.md +++ b/docs/ime-checklist.md @@ -53,5 +53,7 @@ The last column names the automated test that covers the same behavior in Chromi | 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 | | 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 | | 32 | Android (Gboard or an AOSP keyboard such as HeliBoard), in Markdown source mode and in a paragraph in rich mode: type a word and, while it is still underlined, tap earlier in the same text. Type a character. It appears where you tapped, not after the word. | a tap while composing moves the caret when the keyboard finishes the word (events only) | +| 33 | Same setup as 32: while a word is still underlined, long-press an earlier word to select it. It stays selected, and typing replaces it. Then tap inside an earlier `#tag`: the tag popup does not open until you type. | a word selected by a press while composing stays selected; a tap while composing reports the caret move and opens no popup (events only) | +| 34 | Japanese on Windows or macOS: type a sentence, click a clause in the underlined text, pick another candidate and commit. Type a character. It follows the committed text. | a press that keeps the word composing leaves the caret after the committed word (events only) | Some Chinese input methods type `、` on the slash key. The editor keeps it as punctuation. Enter `/` or `/` to open the slash menu. diff --git a/e2e/ime.spec.ts b/e2e/ime.spec.ts index bc72549..fa1f982 100644 --- a/e2e/ime.spec.ts +++ b/e2e/ime.spec.ts @@ -719,6 +719,95 @@ for (const { mode, markdown, tapIn, expected } of [ }); } +/** Adds `window.tap(el, select)`: a touch press on `el`, with `select` moving the selection in between as the browser does. */ +async function installTap(page: Page) { + await page.evaluate(() => { + (window as any).tap = (el: Element, select: () => void) => { + el.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'touch' })); + select(); + document.dispatchEvent(new Event('selectionchange')); + el.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'touch' })); + }; + }); +} + +test('a tap while composing reports the caret move and opens no popup where it lands', async ({ page }) => { + await installIme(page); + await installTap(page); + const moves = await page.evaluate(() => { + const editor = (window as any).editor; + editor.setMarkdown('#work buy'); + editor.commands.focus('end'); + const ime = (window as any).ime; + ime.start(); + ime.update('milk'); + let moves = 0; + editor.on('selectionChange', () => moves++); + const root = document.getElementById('editor')!; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let text = walker.nextNode() as Text; + while (!text.data.includes('work')) text = walker.nextNode() as Text; + // The caret lands inside the tag, where typing would open the tag popup. + (window as any).tap(text.parentElement, () => getSelection()!.collapse(text, text.data.indexOf('work') + 2)); + root.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: 'milk' })); + return moves; + }); + expect(moves).toBe(1); + await frame(page); + await expect(page.locator('.mbe-suggestion-menu')).toBeHidden(); + await page.keyboard.type('X'); + expect(await md(page)).toBe('#woXrk buymilk'); +}); + +test('a word selected by a press while composing stays selected when the keyboard finishes the word', async ({ page }) => { + await installIme(page); + await installTap(page); + await page.evaluate(() => { + const editor = (window as any).editor; + editor.setOptions({ mode: 'source' }); + editor.setMarkdown('alpha\n\nbeta '); + editor.commands.focus('end'); + const ime = (window as any).ime; + ime.start(); + ime.update('gamma'); + const root = document.getElementById('editor')!; + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let text = walker.nextNode() as Text; + while (!text.data.includes('alpha')) text = walker.nextNode() as Text; + const at = text.data.indexOf('alpha'); + // A long press or a double tap selects the word under it. + (window as any).tap(text.parentElement, () => getSelection()!.setBaseAndExtent(text, at, text, at + 5)); + root.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: 'gamma' })); + }); + await frame(page); + await page.keyboard.type('X'); + expect(await md(page)).toBe('X\n\nbeta gamma'); +}); + +// A desktop input method takes a click on the underlined text to pick a clause +// and keeps composing. The commit then leaves the caret after the word, even +// when the input method left the DOM caret on a clause. +test('a press that keeps the word composing leaves the caret after the committed word', async ({ page }) => { + await installIme(page); + await installTap(page); + await page.evaluate(() => { + const editor = (window as any).editor; + editor.setMarkdown('alpha beta'); + editor.commands.focus('end'); + const ime = (window as any).ime; + ime.start(); + ime.update('gam'); + const text = getSelection()!.focusNode as Text; + (window as any).tap(text.parentElement, () => getSelection()!.collapse(text, text.data.indexOf('gam') + 1)); + ime.update('gamma'); + getSelection()!.collapse(text, text.data.indexOf('gamma') + 2); + document.getElementById('editor')!.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: 'gamma' })); + }); + await frame(page); + await page.keyboard.type('X'); + expect(await md(page)).toBe('alpha betagammaX'); +}); + test('leaving an unfinished table composition keeps later typing in saved Markdown', async ({ page }) => { await page.evaluate(() => { const editor = (window as any).editor; diff --git a/packages/editor/src/editor.ts b/packages/editor/src/editor.ts index 21355d4..a27c1d5 100644 --- a/packages/editor/src/editor.ts +++ b/packages/editor/src/editor.ts @@ -431,8 +431,13 @@ export class Editor { ended: boolean; marks: EditorState['storedMarks']; recorded: boolean; - /** A pointer went down in the editor while composing without ending the composition: the caret may have moved (see `syncComposition`). */ + /** + * A pointer went down in the composed text without ending the composition, + * and nothing was composed since: the selection may have moved (see `syncComposition`). + */ pointer?: boolean; + /** The commit took its selection from that press, not from the end of the committed word. */ + moved?: boolean; } | null = null; private pendingMarkdown: { markdown: string; history?: 'clear' | 'keep' } | null = null; /** @@ -2246,7 +2251,8 @@ export class Editor { private settleComposition(): void { if (this.composing || this.destroyed) return; - const composed = this.composition?.recorded; + // A press moved the caret off the composed word: nothing was typed where it is now. + const composed = this.composition?.recorded && !this.composition.moved; this.composition = null; for (const id of this.unsettled) this.renderer.invalidate(id); this.unsettled.clear(); @@ -2265,6 +2271,9 @@ export class Editor { if (this.fromControl(e)) return; // Composition input, and the last of it when it arrives after compositionend. if (this.composing || (this.composition && COMPOSITION_INPUT.has(e.inputType))) { + // The word went on after a press (a click on a clause, a scroll): that + // press did not finish it, and the commit puts the caret after the word. + if (this.composing && this.composition) this.composition.pointer = false; const before = this.composedLength(); this.syncComposition(); // Composed text that grew opens a popup as typing does (Android composes every word). @@ -2317,21 +2326,35 @@ export class Editor { const read = this.readDom(before, composition.marks, composition.blockId, ended); if (!read && !composition.ended) return; const content = containerContent(getBlock((read ?? before).doc, composition.blockId), composition.cell); - // A tap while composing moved the caret before the keyboard finished the - // word (Android keyboards compose every word): the caret is where it went. - // In source mode the whole document is the composed block, so every tap is one. - const live = composition.ended && composition.pointer && !replaced ? this.readDomSelection() : null; // A committed word ends before the unchanged suffix, even when the IME // left the DOM caret on an active clause or sent compositionend before input. - const focus = live && isCollapsed(live) - ? live.focus - : composition.ended && content - ? { blockId: composition.blockId, cell: composition.cell, offset: Math.max(0, inlineLength(content) - composition.trailing) } - : this.readDomSelection()?.focus; + const end: Position | null = composition.ended && content + ? { blockId: composition.blockId, cell: composition.cell, offset: Math.max(0, inlineLength(content) - composition.trailing) } + : null; + // A press while composing moved the selection before the keyboard finished + // the word (Android keyboards compose every word): the selection is where + // it went. In source mode the whole document is the composed block, so + // every press is one. A selection that touches the end of the word is not + // taken: it is where the commit puts the caret anyway, or WebKit's own + // range over the composed text (see below). + const live = end && composition.pointer && !replaced ? this.readDomSelection() : null; + const pressed = end && live && !samePosition(live.anchor, end) && !samePosition(live.focus, end) ? live : null; + const focus = end ?? this.readDomSelection()?.focus; + const selection = pressed ?? (focus ? { anchor: focus, focus } : null); const next = read ?? before; - const selected = focus ? { ...next, selection: clampSelection(next.doc, { anchor: focus, focus }) } : next; + let selected = selection ? { ...next, selection: clampSelection(next.doc, selection) } : next; + if (pressed) { + // The same as any caret move by the user (see onSelectionChange). + composition.moved = true; + selected = { ...selected, storedMarks: null }; + this.shortcut = null; + this.history.breakGroup(); + } if (!read) { + const changed = !samePosition(selected.selection.anchor, before.selection.anchor) || !samePosition(selected.selection.focus, before.selection.focus); this.current = selected; + // Nothing was typed, so no commit reports the move. + if (pressed && changed) this.emit('selectionChange', { editor: this }); return; } if (!composition.recorded) { From e542e228a65498c8c12cfa5950a01528e6ab09b7 Mon Sep 17 00:00:00 2001 From: boojack Date: Sun, 29 Nov 2026 23:02:42 +0800 Subject: [PATCH 3/3] fix(core): do not count a press on the suggestion menu as a tap With the popup container inside the editor root, a press on the suggestion menu while composing marked the composition as tapped, and the pick that followed could take the input method's clause selection instead of the end of the composed word. Only a press in the composed text counts now. --- packages/editor/src/editor.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/editor/src/editor.ts b/packages/editor/src/editor.ts index a27c1d5..6973a06 100644 --- a/packages/editor/src/editor.ts +++ b/packages/editor/src/editor.ts @@ -3426,8 +3426,9 @@ export class Editor { // A suggestion commits in pick(), after its menu has received the click. if (target && !content?.contains(target) && !this.suggestions.contains(target)) this.endComposition(); // A tap in the composed block or cell keeps the composition, and the - // browser moves the caret before the keyboard finishes the word. - else if (target && this.root.contains(target)) this.composition.pointer = true; + // browser moves the caret before the keyboard finishes the word. A + // press on the suggestion menu is not one, also when the menu is in the root. + else if (content?.contains(target)) this.composition.pointer = true; } if (this.toolbar?.menu && !(target && this.toolbar.contains(target))) this.toolbar.closeMenu(); if (!this.blockMenu.isOpen) return;