Skip to content

Commit 6a03ef6

Browse files
fix(web): app keybindings on Mod+B, Mod+I and Mod+E win over composer formatting (#34493)
1 parent ccc9aaf commit 6a03ef6

4 files changed

Lines changed: 104 additions & 5 deletions

File tree

‎apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { act, fakeTimers, render } from "../../test/render";
1919

2020
import { flatToMarkdown, pmToFlat, serializeEditorDoc } from "~/composer-rich-text-doc";
2121
import { isMacPlatform } from "~/lib/utils";
22+
import { registerCommands } from "~/shortcuts/dispatcher";
2223
import {
2324
ComposerPromptEditorTiptap as ComposerPromptEditor,
2425
type ComposerPromptEditorHandle,
@@ -36,11 +37,13 @@ function Composer({
3637
richTextEnabled,
3738
skills,
3839
onChange,
40+
onCommandKeyDown = () => false,
3941
}: {
4042
value: string;
4143
richTextEnabled: boolean;
4244
skills: ReadonlyArray<ServerProviderSkill>;
4345
onChange?: ComposerPromptEditorProps["onChange"] | undefined;
46+
onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"] | undefined;
4447
}) {
4548
const [prompt, setPrompt] = useState({ value, cursor: value.length });
4649
return (
@@ -58,6 +61,7 @@ function Composer({
5861
onChange?.(...args);
5962
}}
6063
onPaste={() => {}}
64+
onCommandKeyDown={onCommandKeyDown}
6165
/>
6266
);
6367
}
@@ -67,9 +71,16 @@ function composer(
6771
richTextEnabled = true,
6872
skills: ReadonlyArray<ServerProviderSkill> = [],
6973
onChange?: ComposerPromptEditorProps["onChange"],
74+
onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"],
7075
) {
7176
return (
72-
<Composer value={value} richTextEnabled={richTextEnabled} skills={skills} onChange={onChange} />
77+
<Composer
78+
value={value}
79+
richTextEnabled={richTextEnabled}
80+
skills={skills}
81+
onChange={onChange}
82+
onCommandKeyDown={onCommandKeyDown}
83+
/>
7384
);
7485
}
7586

@@ -254,6 +265,55 @@ it.each([
254265
},
255266
);
256267

268+
it.each([
269+
["e", false, false],
270+
["i", false, false],
271+
["e", true, false],
272+
["e", false, true],
273+
])(
274+
"leaves Mod+%s to an app command bound to it instead of formatting (composer command: %s, declined capture command: %s)",
275+
async (key, composerClaimsKey, declinedCapture) => {
276+
const openUsage = vi.fn((event: KeyboardEvent) => {
277+
if (declinedCapture) return false;
278+
event.preventDefault();
279+
});
280+
using _commands = {
281+
[Symbol.dispose]: registerCommands(
282+
{ "usage.open": openUsage },
283+
{
284+
keybindings: () => [
285+
{
286+
command: "usage.open",
287+
shortcut: {
288+
key,
289+
metaKey: false,
290+
ctrlKey: false,
291+
shiftKey: false,
292+
altKey: false,
293+
modKey: true,
294+
},
295+
},
296+
],
297+
capture: declinedCapture,
298+
},
299+
),
300+
};
301+
const composerCommand = vi.fn(() => composerClaimsKey);
302+
await using screen = await mountEditor("word", true, [], undefined, composerCommand);
303+
const { editor } = screen;
304+
await act(async () => {
305+
editor.commands.focus();
306+
editor.commands.setTextSelection({ from: 1, to: 5 });
307+
});
308+
await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
309+
const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control";
310+
await userEvent.keyboard(`{${modifier}>}${key}{/${modifier}}`);
311+
expect(composerCommand).toHaveBeenCalled();
312+
expect(openUsage).toHaveBeenCalledTimes(composerClaimsKey ? 0 : 1);
313+
expect(serializeEditorDoc(editor.state.doc).value).toBe(declinedCapture ? "`word`" : "word");
314+
},
315+
);
316+
257317
it.each([false, true])(
258318
"composes an umlaut without wrapping the preedit text (rich text: %s)",
259319
async (richTextEnabled) => {

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,9 @@ import {
112112
} from "~/composer-undo-grouping";
113113
import { collectInlineContextIds } from "~/lib/composerContextReferences";
114114
import { resolveDiffThemeName } from "~/lib/diffRendering";
115+
import { isRichTextFormattingShortcut } from "~/keybindings";
115116
import { cn, isMacPlatform } from "~/lib/utils";
117+
import { hasCommandForKeyDown } from "~/shortcuts/dispatcher";
116118
import { basenameOfPath } from "~/pierre-icons";
117119
import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon";
118120
import { FileTagChipContent } from "./chat/FileTagChip";
@@ -1107,6 +1109,19 @@ function ComposerPromptEditorTiptapInner(
11071109
editable: !disabled,
11081110
editorProps: {
11091111
attributes: editorAttributes,
1112+
handleDOMEvents: {
1113+
// Composer commands keep precedence; otherwise true skips the editor's keymaps without
1114+
// preventDefault, so a bound app command still runs.
1115+
keydown: (_view, event) => {
1116+
if (!isRichTextFormattingShortcut(event)) return false;
1117+
if (readCallbacks().onCommandKeyDown?.(event.key, event)) {
1118+
event.preventDefault();
1119+
event.stopPropagation();
1120+
return true;
1121+
}
1122+
return hasCommandForKeyDown(event);
1123+
},
1124+
},
11101125
handleKeyDown: (view, event) => {
11111126
// In a right-to-left line the start is on the right.
11121127
const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft";

‎apps/web/src/keybindings.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,13 @@ export function isRichTextBoldShortcut(
398398
);
399399
}
400400

401+
/** Mod+B, Mod+I and Mod+E, the mark chords the rich-text composer binds. */
402+
export function isRichTextFormattingShortcut(event: ShortcutEventLike): boolean {
403+
if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return false;
404+
const keys = resolveEventKeys(event);
405+
return keys.has("b") || keys.has("i") || keys.has("e");
406+
}
407+
401408
export function isTerminalClearShortcut(
402409
event: ShortcutEventLike,
403410
platform = navigator.platform,

‎apps/web/src/shortcuts/dispatcher.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,16 +57,21 @@ function isInsideConfirmation(target: EventTarget | null): boolean {
5757
return target instanceof Element && target.closest('[role="alertdialog"]') !== null;
5858
}
5959

60-
function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
60+
function scopeCommandHandler(scope: CommandScope, event: KeyboardEvent) {
6161
const { commands, options } = scope;
62-
if (options.when && !options.when(event)) return false;
63-
if (options.onKeyDown && options.onKeyDown(event) !== false) return true;
6462
const command = resolveShortcutCommand(
6563
event,
6664
options.keybindings?.() ?? appAtomRegistry.get(primaryServerKeybindingsAtom),
6765
{ context: { ...readFocusContext(event), ...options.context?.() } },
6866
);
69-
const handler = command === null ? undefined : commands[command];
67+
return command === null ? undefined : commands[command];
68+
}
69+
70+
function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
71+
const { options } = scope;
72+
if (options.when && !options.when(event)) return false;
73+
if (options.onKeyDown && options.onKeyDown(event) !== false) return true;
74+
const handler = scopeCommandHandler(scope, event);
7075
if (handler === undefined) return false;
7176
if (isInsideConfirmation(event.target)) {
7277
event.preventDefault();
@@ -75,6 +80,18 @@ function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
7580
return handler(event) !== false;
7681
}
7782

83+
/**
84+
* Whether a bubble-phase command is bound to this keydown, for widgets that would otherwise
85+
* consume it. Capture scopes have already run (and declined) by the time a widget sees it.
86+
*/
87+
export function hasCommandForKeyDown(event: KeyboardEvent): boolean {
88+
return globalScopes.some(
89+
(scope) =>
90+
(!scope.options.when || scope.options.when(event)) &&
91+
scopeCommandHandler(scope, event) !== undefined,
92+
);
93+
}
94+
7895
function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boolean {
7996
for (let index = scopes.length - 1; index >= 0; index -= 1) {
8097
if (event.defaultPrevented) return true;

0 commit comments

Comments
 (0)