Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
Expand Down
3 changes: 3 additions & 0 deletions docs/ime-checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,8 @@ 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) |
| 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.
129 changes: 129 additions & 0 deletions e2e/ime.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,135 @@ 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);
});
}

/** 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;
Expand Down
43 changes: 39 additions & 4 deletions packages/editor/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,13 @@ export class Editor {
ended: boolean;
marks: EditorState['storedMarks'];
recorded: boolean;
/**
* 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;
/**
Expand Down Expand Up @@ -2244,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();
Expand All @@ -2263,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).
Expand Down Expand Up @@ -2317,13 +2328,33 @@ export class Editor {
const content = containerContent(getBlock((read ?? before).doc, composition.blockId), composition.cell);
// 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
const end: Position | null = composition.ended && content
? { blockId: composition.blockId, cell: composition.cell, offset: Math.max(0, inlineLength(content) - composition.trailing) }
: this.readDomSelection()?.focus;
: 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) {
Expand Down Expand Up @@ -3394,6 +3425,10 @@ 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. 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;
Expand Down
Loading