Skip to content
Open
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
7 changes: 7 additions & 0 deletions .changeset/decorator-input-shortcuts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'lexical': patch
---

[fix] Keyboard shortcuts such as Ctrl+Backspace, Cmd+A, Cmd+B and Cmd+Z pressed in a text input or textarea inside a decorator node now act on that input instead of running the editor's command

Verify: keyboard shortcuts (Mod+Z, Mod+A, Ctrl/Alt+Backspace, Mod+B) pressed in a text input or textarea inside a decorator; the editor's undo and formatting no longer run for them.
36 changes: 35 additions & 1 deletion packages/lexical/src/LexicalEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2096,6 +2096,27 @@ const SHIFT_KEY_ANY = {shiftKey: 'any'} as const;
// module scope is a side effect to bundlers.
const ALT_SHIFT_KEY_ANY = {altKey: 'any', shiftKey: 'any'} as const;

/**
* Returns true if a keydown comes from an input embedded in a node's DOM that
* takes text: a `<textarea>`, a foreign contentEditable, or an `<input>` of a
* type the user types into. The browser's own editing shortcuts (delete word,
* select all, undo) apply there, so the editor's must not run. A checkbox or a
* button has no action of its own for them and keeps the editor's (#3761).
*/
function $isEventFromEmbeddedTextInput(event: KeyboardEvent): boolean {
const target = getComposedEventTarget(event);
return (
$isEventFromEmbeddedInput(event) &&
!(
isHTMLElement(target) &&
target.nodeName === 'INPUT' &&
/^(button|checkbox|color|file|image|radio|range|reset|submit)$/.test(
(target as HTMLInputElement).type,
)
)
);
}

/**
* The keydown shortcuts that the editor handles natively, compiled to
* dispatch by the pressed key and modifiers in O(1). Each shortcut's mask
Expand All @@ -2115,7 +2136,11 @@ function buildKeyDownShortcuts(): KeyDownShortcut[] {
dispatchCommand(editor, command, event);
},
});
/** preventDefault() and dispatch the command with a fixed payload */
/**
* preventDefault() and dispatch the command with a fixed payload, unless a
* text input embedded in a node's DOM has the focus (#3761): the browser's action
* (eg. deleting a word in the input) is the right one there.
*/
const prevent = <T>(
key: string,
modifiers: KeyboardEventModifierMask,
Expand All @@ -2125,6 +2150,9 @@ function buildKeyDownShortcuts(): KeyDownShortcut[] {
key,
modifiers,
onMatch: (event, editor) => {
if ($isEventFromEmbeddedTextInput(event)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the undo/redo entries this hands Ctrl+Z to the browser, and in Chromium the browser's undo stack is per page: when this input has no edit of its own on top of it, Chromium undoes the user's last typing in the editor and fires beforeinput historyUndo at the editor root. onBeforeInput skips that event because the focused element is a decorator input (the active-element fallback in $isInputEventTargetingCapturedSelection, lines 1218-1223), so the #6714 branch of $handleBeforeInput (lines 1394-1416) never prevents it. In the playground: type in the editor, click into an empty poll option, press Ctrl+Z: the editor text changes with no UNDO_COMMAND, focus leaves the poll, and the next Ctrl+Z restores it. Deciding historyUndo/historyRedo by their composed target in onBeforeInput (prevent when it is the editor root, keep the fallback for Firefox's #8738 retargeting) would close it.

return;
}
event.preventDefault();
dispatchCommand(editor, command, payload);
},
Expand Down Expand Up @@ -2206,6 +2234,9 @@ function buildKeyDownShortcuts(): KeyDownShortcut[] {
key: 'o',
modifiers: CTRL_KEY,
onMatch: (event: KeyboardEvent, editor: LexicalEditor) => {
if ($isEventFromEmbeddedTextInput(event)) {
return;
}
event.preventDefault();
dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, true);
},
Expand Down Expand Up @@ -2240,6 +2271,9 @@ function buildKeyDownShortcuts(): KeyDownShortcut[] {
key: 'a',
modifiers: CONTROL_OR_META,
onMatch: (event, editor) => {
if ($isEventFromEmbeddedTextInput(event)) {
return;
}
event.preventDefault();
if (dispatchCommand(editor, SELECT_ALL_COMMAND, event)) {
markHandledSelectionCommandInsertText(editor._inputState);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/

import {buildEditorFromExtensions} from '@lexical/extension';
import {RichTextExtension} from '@lexical/rich-text';
import {
$create,
$createParagraphNode,
$createTextNode,
$getRoot,
type AnyLexicalCommand,
COMMAND_PRIORITY_CRITICAL,
DecoratorNode,
DELETE_LINE_COMMAND,
DELETE_WORD_COMMAND,
type EditorConfig,
FORMAT_TEXT_COMMAND,
IS_APPLE,
isHTMLElement,
type LexicalCommand,
type LexicalEditor,
SELECT_ALL_COMMAND,
UNDO_COMMAND,
} from 'lexical';
import {assert, describe, expect, onTestFinished, test, vi} from 'vitest';
import {userEvent} from 'vitest/browser';

// https://github.com/facebook/lexical/issues/3761
// Shortcuts pressed in a decorator's own input must do what the input does,
// not run (and preventDefault) the editor's command.

class InputDecoratorNode extends DecoratorNode<unknown> {
$config() {
return this.config('input-decorator-3761', {extends: DecoratorNode});
}
isInline() {
return false;
}
createDOM(_config: EditorConfig, _editor: LexicalEditor): HTMLElement {
const div = document.createElement('div');
div.appendChild(document.createElement('input'));
return div;
}
}

function createEditor(): {
editor: LexicalEditor;
input: HTMLInputElement;
root: HTMLElement;
} {
const editor = buildEditorFromExtensions({
$initialEditorState: () => {
$getRoot().append(
$createParagraphNode().append($createTextNode('editor text')),
$create(InputDecoratorNode),
);
},
dependencies: [RichTextExtension],
name: 'test',
nodes: [InputDecoratorNode],
});
const root = document.createElement('div');
root.contentEditable = 'true';
document.body.appendChild(root);
editor.setRootElement(root);
onTestFinished(() => {
editor.setRootElement(null);
root.remove();
editor.dispose();
});
const input = root.querySelector<HTMLInputElement>(
'[data-lexical-decorator] input',
);
assert(isHTMLElement(input));
return {editor, input, root};
}

function spyOn<T>(editor: LexicalEditor, command: LexicalCommand<T>) {
const spy = vi.fn((_payload: unknown) => false);
onTestFinished(
editor.registerCommand(command, spy, COMMAND_PRIORITY_CRITICAL),
);
return spy;
}

const MOD = IS_APPLE ? 'metaKey' : 'ctrlKey';
const WORD = IS_APPLE ? 'altKey' : 'ctrlKey';

const SHORTCUTS: [string, KeyboardEventInit, AnyLexicalCommand][] = [
// Ctrl on Windows/Linux, Alt (Option) on Apple platforms
['Word+Backspace', {[WORD]: true, key: 'Backspace'}, DELETE_WORD_COMMAND],
['Word+Delete', {[WORD]: true, key: 'Delete'}, DELETE_WORD_COMMAND],
['Mod+A', {[MOD]: true, key: 'a'}, SELECT_ALL_COMMAND],
['Mod+B', {[MOD]: true, key: 'b'}, FORMAT_TEXT_COMMAND],
['Mod+Z', {[MOD]: true, key: 'z'}, UNDO_COMMAND],
...(IS_APPLE
? ([
[
'Cmd+Backspace',
{key: 'Backspace', metaKey: true},
DELETE_LINE_COMMAND,
],
] as [string, KeyboardEventInit, AnyLexicalCommand][])
: []),
];

function keyDown(target: HTMLElement, init: KeyboardEventInit) {
const event = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
...init,
});
target.dispatchEvent(event);
return event;
}

describe('Shortcuts in a decorator input (#3761)', () => {
for (const [name, init, command] of SHORTCUTS) {
test(`${name} in the input is left to the input`, () => {
const {editor, input} = createEditor();
input.focus();
const spy = spyOn(editor, command);
const event = keyDown(input, init);
expect(event.defaultPrevented).toBe(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Mod+Z this synthetic keydown passes even though Chromium's real undo then rewrites the editor (see the comment on LexicalEvents.ts line 2153). A real-key case like the two at the end of the file, typing in the editor first and then pressing Mod+Z in the input, asserting the editor's text and the focused element, would cover it.

expect(spy).not.toHaveBeenCalled();
});

test(`${name} in the editor still runs the command (control)`, () => {
const {editor, root} = createEditor();
root.focus();
editor.update(
() => {
$getRoot().selectStart();
},
{discrete: true},
);
const spy = spyOn(editor, command);
const event = keyDown(root, init);
expect(event.defaultPrevented).toBe(true);
expect(spy).toHaveBeenCalledTimes(1);
});
}

// Only a text input takes the shortcut: a button or a checkbox has no
// action of its own for it.
for (const control of ['button', 'checkbox'] as const) {
test(`Mod+Z on a ${control} in the decorator still runs the command`, () => {
const {editor, input} = createEditor();
const element = document.createElement(
control === 'button' ? 'button' : 'input',
);
if (control === 'checkbox') {
element.setAttribute('type', 'checkbox');
}
input.after(element);
element.focus();
const spy = spyOn(editor, UNDO_COMMAND);
const event = keyDown(element, {[MOD]: true, key: 'z'});
expect(event.defaultPrevented).toBe(true);
expect(spy).toHaveBeenCalledTimes(1);
});
}

test('a real Ctrl/Alt+Backspace deletes a word in the input', async () => {
const {editor, input} = createEditor();
const editorText = editor.read(() => $getRoot().getTextContent());
await userEvent.click(input);
await userEvent.keyboard('hello world');
await userEvent.keyboard(
IS_APPLE ? '{Alt>}{Backspace}{/Alt}' : '{Control>}{Backspace}{/Control}',
);
expect(input.value).toBe('hello ');
expect(editor.read(() => $getRoot().getTextContent())).toBe(editorText);
});

test('a real select all selects only the input', async () => {
const {editor, input} = createEditor();
const editorText = editor.read(() => $getRoot().getTextContent());
await userEvent.click(input);
await userEvent.keyboard('hello world');
await userEvent.keyboard(
IS_APPLE ? '{Meta>}a{/Meta}' : '{Control>}a{/Control}',
);
expect([input.selectionStart, input.selectionEnd]).toEqual([0, 11]);
await userEvent.keyboard('new');
expect(input.value).toBe('new');
expect(editor.read(() => $getRoot().getTextContent())).toBe(editorText);
});
});
Loading