From cf9d13072c4bb488bfa5352979e12f92c6751fda Mon Sep 17 00:00:00 2001 From: Brendan Allan <14191578+Brendonovich@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:12:50 +0800 Subject: [PATCH] feat(app): dispatch command shortcuts through @opentui/keymap (#64394) --- bun.lock | 1 + packages/app/component-tests/composer.spec.ts | 3 +- packages/app/package.json | 1 + .../app/src/composer/editor/interaction.ts | 25 -- packages/app/src/composer/model.ts | 20 +- packages/app/src/runtime/i18n/en.ts | 1 + .../app/src/shell/commands/command.test.ts | 31 --- packages/app/src/shell/commands/command.tsx | 146 ++-------- .../app/src/shell/commands/keymap.test.ts | 159 +++++++++++ packages/app/src/shell/commands/keymap.ts | 257 ++++++++++++++++++ .../app/test-browser/composer-ime.test.ts | 29 +- 11 files changed, 476 insertions(+), 197 deletions(-) create mode 100644 packages/app/src/shell/commands/keymap.test.ts create mode 100644 packages/app/src/shell/commands/keymap.ts diff --git a/bun.lock b/bun.lock index c34eb189eac..01aad3f8b35 100644 --- a/bun.lock +++ b/bun.lock @@ -66,6 +66,7 @@ "@opencode/session-ui": "workspace:*", "@opencode/ui": "workspace:*", "@opencode/util": "workspace:*", + "@opentui/keymap": "catalog:", "@pierre/highlights": "catalog:", "@pierre/trees": "1.0.0-beta.6", "@sentry/solid": "catalog:", diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 974cd782497..3fb3fde481d 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -216,7 +216,8 @@ story( await input.fill("") await input.press("ArrowUp") await expect(input).toHaveText("Explain the latest changes") - await input.press("ControlOrMeta+u") + await component.getByRole("button", { name: "Add images and files", exact: true }).click() + await page.getByRole("menuitem", { name: /^Images and files/ }).click() await input.press("ArrowDown") await expect(input).toBeEmpty() }, diff --git a/packages/app/package.json b/packages/app/package.json index 6b76d843204..08fe999299d 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -67,6 +67,7 @@ "@opencode/session-ui": "workspace:*", "@opencode/ui": "workspace:*", "@opencode/util": "workspace:*", + "@opentui/keymap": "catalog:", "@pierre/highlights": "catalog:", "@pierre/trees": "1.0.0-beta.6", "@sentry/solid": "catalog:", diff --git a/packages/app/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index 41a149a0ded..bc73927b3d9 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -474,19 +474,6 @@ export function createComposerEditor(input: { flushFocus() - if ( - mode() === "normal" && - (event.metaKey || event.ctrlKey) && - !event.altKey && - !event.shiftKey && - event.key.toLowerCase() === "u" - ) { - event.preventDefault() - attach() - - return true - } - const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey const open = isComposerPopoverOpen(readState()) @@ -537,18 +524,6 @@ export function createComposerEditor(input: { return true } - const stop = - (input.view.submit.working?.() || input.view.submit.held?.()) && - ((event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "g") || - event.key === "Escape") - - if (stop) { - event.preventDefault() - input.view.submit.onStop() - - return true - } - if ( !event.altKey && !event.ctrlKey && diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts index c4c4a931c7c..9520c38c73b 100644 --- a/packages/app/src/composer/model.ts +++ b/packages/app/src/composer/model.ts @@ -2,7 +2,7 @@ import { ImagePreview } from "@opencode/ui/image-preview" import { useDialog } from "@opencode/ui/context/dialog" import type { ReferenceInfo } from "@opencode/client/promise" import type { Links, MountedSession } from "@opencode/plugin/gui" -import { createComponent, createEffect, createMemo, on, onCleanup } from "solid-js" +import { createComponent, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js" import { Predicate } from "effect" import type { ComposerSuggestion } from "./types" import { createComposerEditor, type ComposerEditorModel } from "./editor/interaction" @@ -33,6 +33,7 @@ import type { PromptHistoryComment } from "./history/entry" import { createComposerHistory } from "./history/store" import { createComposerSubmit } from "./submit" import { composerSubmitView } from "./machine" +import { isComposerPopoverOpen } from "./suggestions/machine" import { useAttachmentDestination } from "./attachments/destination" import { parseClientSlashCommand } from "./client-slash-command" @@ -73,6 +74,8 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? ), ) let editor: HTMLDivElement | undefined + // The element `prompt.stop` binds its keys to. + const [editorElement, setEditorElement] = createSignal() // A path attachment's image is read through the server, which can see both local and uploaded paths. const pathImages = new Map>() const pathImageReads = new AbortController() @@ -457,6 +460,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? onEditor(element) { // SAFETY: the editor's only `setEditor` call passes its editable root, a `
` (`editor/editor.tsx`). editor = element as HTMLDivElement + setEditorElement(editor) if (adapter.kind === "active-session") adapter.setEditor(editor) }, @@ -607,6 +611,20 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? disabled: mode() === "normal", onSelect: () => void controller.dispatch({ type: "mode.normal" }), }, + { + id: "prompt.stop", + title: language.t("command.prompt.stop"), + category: language.t("command.category.session"), + keybind: "escape,ctrl+g", + editable: true, + target: editorElement, + disabled: !adapter.working() && !submitView().held, + // An open list, a queued prompt being edited and shell mode each take the key first in the editor. + skip: (event) => + isComposerPopoverOpen(controller.state) || + (event.key === "Escape" && (!!options?.queue?.editing() || mode() === "shell")), + onSelect: () => void submission.stop(), + }, ]) // SAFETY: the `model` getter defined on the controller above completes `ComposerModel`. diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 5cde85e6411..9335b49977d 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -105,6 +105,7 @@ export const dict = { "command.prompt.mode.shell": "Shell", "command.prompt.mode.normal": "Prompt", "command.prompt.mode.toggle": "Toggle shell mode", + "command.prompt.stop": "Stop session", "command.permissions.autoaccept.enable": "Auto-accept permissions", "command.permissions.autoaccept.disable": "Stop auto-accepting permissions", "command.permissions.autoaccept.project": "Auto-accept permissions for this project", diff --git a/packages/app/src/shell/commands/command.test.ts b/packages/app/src/shell/commands/command.test.ts index 72ddf29c6e1..aee190e37fa 100644 --- a/packages/app/src/shell/commands/command.test.ts +++ b/packages/app/src/shell/commands/command.test.ts @@ -5,11 +5,9 @@ import { addCommandRegistration, commandPaletteOptions, CommandCatalog, - commandKeymap, formatKeybind, matchKeybind, parseKeybind, - resolveKeybindOption, type CommandOption, } from "./command" @@ -62,35 +60,6 @@ test("command registrations shadow keyed owners, restore the previous owner, and expect(unkeyed.map((entry) => entry.options)).toEqual([two, one]) }) -test.each([true, false])("resolveKeybindOption prefers a contextual command only in its context: %p", (inside) => { - const fallback = { id: "tab.close", title: "Close tab" } - const contextual = { id: "terminal.close", title: "Close terminal", when: () => inside } - - expect(resolveKeybindOption([fallback, contextual], new KeyboardEvent("keydown"))).toBe( - inside ? contextual : fallback, - ) -}) - -test("commandKeymap puts a user's binding before a default on the same keys", () => { - const rename = { id: "session.rename", title: "Rename session", keybind: "ctrl+r" } - const focus = { id: "input.focus", title: "Focus input", keybind: "ctrl+r" } - const event = new KeyboardEvent("keydown", { key: "r", ctrlKey: true }) - const keymap = (custom: string[]) => commandKeymap([rename, focus], (id) => custom.includes(id)).get("r:1") - - expect(resolveKeybindOption(keymap([]), event)).toBe(rename) - expect(resolveKeybindOption(keymap(["input.focus"]), event)).toBe(focus) - expect(commandKeymap([{ ...rename, disabled: true }], () => false).size).toBe(0) -}) - -test.each([true, false])("resolveKeybindOption leaves the key to a skipping command's target: %p", (inside) => { - const rename = { id: "session.rename", title: "Rename session", skip: () => inside } - const focus = { id: "input.focus", title: "Focus input" } - const event = new KeyboardEvent("keydown") - - expect(resolveKeybindOption([rename], event)).toBe(inside ? undefined : rename) - expect(resolveKeybindOption([rename, focus], event)).toBe(inside ? focus : rename) -}) - describe("command keybinds", () => { test("parseKeybind handles aliases, multiple combos, and disabled bindings", () => { const keybinds = parseKeybind("control+option+k, mod+shift+comma") diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index 7c916ee63a0..0b9e73091ba 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -4,15 +4,15 @@ import { type Accessor, batch, createEffect, createMemo, createSignal, onCleanup import { createStore, produce, reconcile } from "solid-js/store" import { Predicate, Schema } from "effect" import { Persistence } from "@/runtime/persistence/schema" -import { makeEventListener } from "@solid-primitives/event-listener" import { useLanguage } from "@/runtime/i18n/language" import { useSettings } from "@/settings/model" import { keybindRenames } from "@/settings/keybinds/migration" import en from "@/runtime/i18n/en" import { Persist, persisted } from "@/runtime/persistence/storage" import { INITIAL_KEYBIND_SUSPEND_STATE, selectKeybindsSuspended, transitionKeybindSuspend } from "./suspend-machine" +import { createAppKeymap, IS_MAC, keyFromKeyboardEvent, registerCommandLayers } from "./keymap" -const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) +export { keyFromKeyboardEvent } const PALETTE_ID = "command.palette" @@ -50,51 +50,6 @@ function actionId(id: string) { return id.slice(SUGGESTED_PREFIX.length) } -function normalizeKey(key: string) { - if (key === ",") return "comma" - - if (key === "+") return "plus" - - if (key === " ") return "space" - - return key.toLowerCase() -} - -export function keyFromKeyboardEvent(event: KeyboardEvent) { - const key = normalizeKey(physicalKey(event)) - - if (!event.altKey || /^[a-z0-9]$/.test(key)) return key - - if (!event.code.startsWith("Key") || event.code.length !== 4) return key - - return event.code.slice(3).toLowerCase() -} - -// ⇧[ types { and ⌥. types ≥ on US layouts. Keep ASCII layout mappings; non-ASCII falls back to the physical key. -function physicalKey(event: Pick) { - if (event.key === "{" || event.key === "}") return event.key === "{" ? "[" : "]" - - if (!/^[^\x00-\x7f]$/u.test(event.key)) return event.key - - if (event.code === "BracketLeft") return "[" - - if (event.code === "BracketRight") return "]" - - if (event.code === "Period") return "." - - return event.key -} - -function signature(key: string, ctrl: boolean, meta: boolean, shift: boolean, alt: boolean) { - const mask = (ctrl ? 1 : 0) | (meta ? 2 : 0) | (shift ? 4 : 0) | (alt ? 8 : 0) - - return `${key}:${mask}` -} - -function signatureFromEvent(event: KeyboardEvent) { - return signature(keyFromKeyboardEvent(event), event.ctrlKey, event.metaKey, event.shiftKey, event.altKey) -} - type KeybindConfig = string export interface Keybind { @@ -134,6 +89,8 @@ export interface CommandOption { hidden?: boolean /** The keybind also fires while a text field has focus. */ editable?: boolean + /** The keybind fires only while focus is inside this element, ahead of keybinds without one. */ + target?: () => HTMLElement | undefined when?: (event: KeyboardEvent) => boolean /** The keybind leaves this event to its target, as if the command had no keybind. */ skip?: (event: KeyboardEvent) => boolean @@ -149,37 +106,6 @@ export function commandPaletteOptions(options: CommandOption[]) { ) } -/** Maps each keybind signature to its commands. A user's own binding comes before a default on the same keys. */ -export function commandKeymap(options: CommandOption[], custom: (id: string) => boolean) { - const map = new Map() - - for (const option of options) { - if (option.id.startsWith(SUGGESTED_PREFIX)) continue - - if (option.disabled) continue - - if (!option.keybind) continue - - const keybinds = parseKeybind(option.keybind) - - for (const kb of keybinds) { - if (!kb.key) continue - const sig = signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt) - const existing = map.get(sig) ?? [] - - map.set(sig, custom(actionId(option.id)) ? [option, ...existing] : [...existing, option]) - } - } - - return map -} - -export function resolveKeybindOption(candidates: CommandOption[] | undefined, event: KeyboardEvent) { - const live = candidates?.filter((option) => !option.skip?.(event)) - - return live?.find((option) => option.when?.(event)) ?? live?.find((option) => !option.when) -} - export type CommandSource = "palette" | "keybind" | "slash" const CommandCatalogItem = Persistence.struct({ @@ -398,8 +324,9 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const [catalog, setCatalog, _, catalogReady] = persisted(Persist.global("command.catalog.v1"), CommandCatalog, {}) const bind = (id: string, def: KeybindConfig | undefined, follows?: string) => { - const custom = settings.keybinds.get(actionId(id)) ?? (follows ? settings.keybinds.get(follows) : undefined) - const config = custom ?? def + const base = actionId(id) + const custom = settings.keybinds.get(base) ?? (follows ? settings.keybinds.get(follows) : undefined) + const config = custom ?? (base === PALETTE_ID ? DEFAULT_PALETTE_KEYBIND : def) if (!config || config === "none") return @@ -467,6 +394,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const resolved = registered().map((opt) => ({ ...opt, keybind: bind(opt.id, opt.keybind, opt.follows), + editable: opt.editable || opt.id === PALETTE_ID, })) const suggested = resolved.filter((x) => x.suggested && !x.disabled) @@ -483,15 +411,26 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const suspended = () => selectKeybindsSuspended(suspendState()) - const palette = createMemo(() => { - const config = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND - const keybinds = parseKeybind(config) + const app = createAppKeymap({ blocked: () => suspended() || !!dialog.active, editable: isEditableTarget }) - return new Set(keybinds.map((kb) => signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt))) + onCleanup(app.destroy) + + createEffect(() => { + const bound = options().filter((option) => !option.id.startsWith(SUGGESTED_PREFIX) && !option.disabled) + + // The palette's keys come first, so they win over any other command on the same keys. + onCleanup( + registerCommandLayers( + app.keymap, + [ + ...bound.filter((option) => option.id === PALETTE_ID), + ...bound.filter((option) => option.id !== PALETTE_ID), + ], + (id) => settings.keybinds.get(id) !== undefined, + ), + ) }) - const keymap = createMemo(() => commandKeymap(options(), (id) => settings.keybinds.get(id) !== undefined)) - const optionMap = createMemo(() => { const map = new Map() @@ -513,40 +452,6 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex run(PALETTE_ID, "palette") } - const handleKeyDown = (event: KeyboardEvent) => { - if (suspended() || dialog.active) return - - const sig = signatureFromEvent(event) - const isPalette = palette().has(sig) - const option = resolveKeybindOption(keymap().get(sig), event) - const modified = event.ctrlKey || event.metaKey || event.altKey - const isTab = event.key === "Tab" - - if (isEditableTarget(event.target) && !isPalette && !option?.editable && !modified && !isTab) return - - if (isPalette) { - event.preventDefault() - event.stopPropagation() - showPalette() - - return - } - - if (!option) return - - // A command that returns false declines the key, which goes on to its target. - const result = option.onSelect?.("keybind") - - if (result === false) return - event.preventDefault() - event.stopPropagation() - void result - } - - onMount(() => { - makeEventListener(document, "keydown", handleKeyDown, { capture: true }) - }) - function register(cb: () => CommandOption[]): void function register(key: string, cb: () => CommandOption[]): void function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) { @@ -570,7 +475,6 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex } const keybindConfig = (id: string) => { - if (id === PALETTE_ID) return settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND const base = actionId(id) return ( diff --git a/packages/app/src/shell/commands/keymap.test.ts b/packages/app/src/shell/commands/keymap.test.ts new file mode 100644 index 00000000000..15c3cc934e3 --- /dev/null +++ b/packages/app/src/shell/commands/keymap.test.ts @@ -0,0 +1,159 @@ +import { afterEach, expect, test } from "bun:test" +import type { CommandOption } from "./command" +import { createAppKeymap, registerCommandLayers } from "./keymap" + +const cleanup: (() => void)[] = [] + +afterEach(() => { + cleanup.splice(0).forEach((dispose) => dispose()) + document.body.replaceChildren() +}) + +function setup(options: CommandOption[], input?: { custom?: string[]; blocked?: () => boolean }) { + const app = createAppKeymap({ + blocked: input?.blocked ?? (() => false), + editable: (target) => target instanceof HTMLElement && target.isContentEditable, + }) + + const layers = registerCommandLayers(app.keymap, options, (id) => input?.custom?.includes(id) ?? false) + + cleanup.push(() => { + layers() + app.destroy() + }) + + return app +} + +function press(target: HTMLElement, init: KeyboardEventInit) { + const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }) + target.dispatchEvent(event) + + return event +} + +function editor() { + const element = document.createElement("div") + element.contentEditable = "true" + document.body.append(element) + element.focus() + + return element +} + +function command(id: string, keybind: string, ran: string[], extra?: Partial): CommandOption { + return { id, title: id, keybind, onSelect: () => void ran.push(id), ...extra } +} + +// happy-dom never reports a Mac platform, so mod is Ctrl here. +test("a command with a when wins only in its context, then a user's binding, then the first registered", () => { + const ran: string[] = [] + const inside = { value: true } + setup( + [ + command("tab.close", "mod+w", ran), + command("file.close", "mod+w", ran), + command("terminal.close", "mod+w", ran, { when: () => inside.value }), + ], + { custom: ["file.close"] }, + ) + + press(document.body, { key: "w", ctrlKey: true }) + inside.value = false + press(document.body, { key: "w", ctrlKey: true }) + + expect(ran).toEqual(["terminal.close", "file.close"]) +}) + +test("a declining command passes the key to the next command, and finally to the focused element", () => { + const ran: string[] = [] + const skip = { value: true } + setup([ + command("session.rename", "ctrl+r", ran, { skip: () => skip.value }), + command("plugin.run", "ctrl+r", ran, { onSelect: () => (ran.push("plugin.run"), false) }), + ]) + + const declined = press(document.body, { key: "r", ctrlKey: true }) + skip.value = false + const handled = press(document.body, { key: "r", ctrlKey: true }) + + expect(ran).toEqual(["plugin.run", "session.rename"]) + expect(declined.defaultPrevented).toBe(false) + expect(handled.defaultPrevented).toBe(true) +}) + +test("a key that types a character fires in a text field only for an editable command", () => { + const ran: string[] = [] + setup([ + command("review.next", "j", ran), + command("prompt.stop", "escape", ran, { editable: true }), + command("model.choose", "mod+'", ran), + ]) + const field = editor() + + const typed = press(field, { key: "j" }) + press(field, { key: "Escape" }) + press(field, { key: "'", ctrlKey: true }) + field.blur() + press(document.body, { key: "j" }) + + expect(typed.defaultPrevented).toBe(false) + expect(ran).toEqual(["prompt.stop", "model.choose", "review.next"]) +}) + +test("a focus target's command wins inside the target and is absent outside it", () => { + const ran: string[] = [] + const field = editor() + const outside = document.createElement("button") + document.body.append(outside) + setup([ + command("dialog.close", "escape", ran, { editable: true }), + command("prompt.stop", "escape", ran, { editable: true, target: () => field }), + ]) + + press(field, { key: "Escape" }) + outside.focus() + press(outside, { key: "Escape" }) + + expect(ran).toEqual(["prompt.stop", "dialog.close"]) +}) + +test.each([ + { name: "composing", init: { key: "Escape", isComposing: true } }, + { name: "Safari's composition Enter", init: { key: "Escape", keyCode: 229 } }, +])("keys are left to the IME while it composes: $name", (row) => { + const ran: string[] = [] + setup([command("prompt.stop", "escape", ran, { editable: true })]) + + const event = press(editor(), row.init) + + expect(event.defaultPrevented).toBe(false) + expect(ran).toEqual([]) +}) + +test("keys are left alone while keybinds are blocked", () => { + const ran: string[] = [] + const blocked = { value: true } + setup([command("palette", "mod+k", ran)], { blocked: () => blocked.value }) + + press(document.body, { key: "k", ctrlKey: true }) + blocked.value = false + press(document.body, { key: "k", ctrlKey: true }) + + expect(ran).toEqual(["palette"]) +}) + +test.each([ + { keybind: "mod+alt+.", init: { key: "≥", code: "Period", ctrlKey: true, altKey: true } }, + { keybind: "mod+shift+[", init: { key: "{", code: "BracketLeft", ctrlKey: true, shiftKey: true } }, + { keybind: "alt+arrowup", init: { key: "ArrowUp", altKey: true } }, + { keybind: "mod+comma", init: { key: ",", ctrlKey: true } }, + { keybind: "shift+enter", init: { key: "Enter", shiftKey: true } }, +])("$keybind matches the key the layout types", (row) => { + const ran: string[] = [] + setup([command("run", row.keybind, ran)]) + + press(document.body, row.init) + + expect(ran).toEqual(["run"]) +}) diff --git a/packages/app/src/shell/commands/keymap.ts b/packages/app/src/shell/commands/keymap.ts new file mode 100644 index 00000000000..c8efe7ec954 --- /dev/null +++ b/packages/app/src/shell/commands/keymap.ts @@ -0,0 +1,257 @@ +import { Keymap, type KeymapHost } from "@opentui/keymap" +import { registerDefaultBindingParser } from "@opentui/keymap/addons" +import { createHtmlKeymapHost, type HtmlKeymapEvent } from "@opentui/keymap/html" +import type { CommandOption } from "./command" + +export const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) + +export type AppKeymap = Keymap + +/** + * The keymap behind every command keybind. It reads keys in the capture phase on the document root, before the + * focused element sees them. + */ +export function createAppKeymap(input: { blocked: () => boolean; editable: (target: EventTarget | null) => boolean }) { + const host = createAppKeymapHost(document.documentElement, input.blocked) + const keymap: AppKeymap = new Keymap(host.host) + // Every binding is written by `keymapKey`: one `+`-joined combo. + keymap.prependBindingParser((ctx) => { + if (ctx.index !== 0) return + + return { + parts: [ctx.parseObjectKey(strokeInput(ctx.input.trim()), { display: ctx.input })], + nextIndex: ctx.input.length, + } + }) + registerDefaultBindingParser(keymap) + keymap.prependEventMatchResolver((event, ctx) => { + const original = event.originalEvent + + if (!original) return + + const name = keymapKeyName(keyFromKeyboardEvent(original)) + const alias = KEY_ALIASES.get(name) + + const stroke = { + name, + ctrl: original.ctrlKey, + shift: original.shiftKey, + meta: original.altKey, + super: original.metaKey, + } + + return (alias ? [name, alias] : [name]).flatMap((name) => [ + ctx.resolveKey({ ...stroke, name }), + // `shift+/` types `?`, so `?` binds the symbol whichever modifier the layout needs. + ...(stroke.shift && name.length === 1 && !/^[a-z0-9]$/.test(name) + ? [ctx.resolveKey({ ...stroke, name, shift: false })] + : []), + ]) + }) + // A binding whose key types a character stays out of text fields, so typing in them is never taken. + keymap.registerBindingFields({ + outsideText(value, ctx) { + if (value === true) ctx.activeWhen(() => !input.editable(document.activeElement)) + }, + }) + + return { keymap, destroy: host.destroy } +} + +/** + * Registers the keybinds of `options`: one global layer, plus one layer per focus target, which wins over the global + * one while focus is inside it. On the same keys a command with a `when` comes first, then a user's own binding, then + * the order given. A command declines a key by returning false from `onSelect`, or through `when` and `skip`; the key + * then goes to the next command, and finally to the focused element. + */ +export function registerCommandLayers(keymap: AppKeymap, options: CommandOption[], custom: (id: string) => boolean) { + const layers = new Map() + + options + .map((option, index) => ({ option, index, rank: (option.when ? 2 : 0) + (custom(option.id) ? 1 : 0) })) + .sort((a, b) => b.rank - a.rank || a.index - b.index) + .forEach(({ option }) => { + if (!option.keybind) return + const target = option.target?.() + + if (option.target && !target) return + layers.set(target, [...(layers.get(target) ?? []), option]) + }) + + const disposers = Array.from(layers, ([target, options]) => + keymap.registerLayer({ + target, + priority: target ? 1 : 0, + commands: options.map((option) => ({ + name: option.id, + run(ctx) { + const event = ctx.event.originalEvent + + if (event && option.skip?.(event)) return false + + if (event && option.when && !option.when(event)) return false + + return option.onSelect?.("keybind") !== false + }, + })), + bindings: options.flatMap((option) => + option + .keybind!.split(",") + .map((combo) => combo.trim()) + .filter((combo) => combo && combo !== "none") + .map((combo) => { + const key = keymapKey(combo) + + return { key, cmd: option.id, outsideText: !option.editable && typesCharacter(keymap, key) } + }), + ), + }), + ) + + return () => disposers.forEach((dispose) => dispose()) +} + +/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`) into the keymap's. */ +export function keymapKey(combo: string) { + return combo + .trim() + .split("+") + .map((part) => { + const lower = part.toLowerCase() + + if (lower === "mod") return IS_MAC ? "super" : "ctrl" + + if (lower === "meta" || lower === "cmd" || lower === "command") return "super" + + return MODIFIER_PARTS.has(lower) ? lower : keymapKeyName(lower) + }) + .join("+") +} + +// One stroke as `keymapKey` writes it, such as `super+shift+[`. +function strokeInput(stroke: string) { + const parts = stroke.split("+") + const has = (...names: string[]) => parts.some((part) => names.includes(part)) + + return { + name: parts.findLast((part) => !MODIFIER_PARTS.has(part)) ?? parts.at(-1)!, + ctrl: has("ctrl", "control"), + shift: has("shift"), + meta: has("alt", "option"), + super: has("super"), + hyper: has("hyper") || undefined, + } +} + +/** Whether a keymap key types a character, so it should stay out of text fields. */ +export function typesCharacter(keymap: AppKeymap, key: string) { + const first = keymap.parseKeySequence(key)[0]?.stroke + + if (!first) return false + + return !first.ctrl && !first.meta && !first.super && first.name !== "tab" +} + +export function keyFromKeyboardEvent(event: KeyboardEvent) { + const key = normalizeKey(physicalKey(event)) + + if (!event.altKey || /^[a-z0-9]$/.test(key)) return key + + if (!event.code.startsWith("Key") || event.code.length !== 4) return key + + return event.code.slice(3).toLowerCase() +} + +const MODIFIER_PARTS = new Set(["ctrl", "control", "shift", "alt", "option", "super", "hyper"]) + +const KEY_NAMES = new Map([ + ["arrowup", "up"], + ["arrowdown", "down"], + ["arrowleft", "left"], + ["arrowright", "right"], + ["esc", "escape"], + ["enter", "return"], +]) + +// The app writes these keys by name and the keymap parser reads both forms, so events resolve to each. +const KEY_ALIASES = new Map([ + ["comma", ","], + ["plus", "+"], +]) + +function keymapKeyName(key: string) { + return KEY_NAMES.get(key) ?? key +} + +function normalizeKey(key: string) { + if (key === ",") return "comma" + + if (key === "+") return "plus" + + if (key === " ") return "space" + + return key.toLowerCase() +} + +// ⇧[ types { and ⌥. types ≥ on US layouts. Keep ASCII layout mappings; non-ASCII falls back to the physical key. +function physicalKey(event: Pick) { + if (event.key === "{" || event.key === "}") return event.key === "{" ? "[" : "]" + + if (!/^[^\x00-\x7f]$/u.test(event.key)) return event.key + + if (event.code === "BracketLeft") return "[" + + if (event.code === "BracketRight") return "]" + + if (event.code === "Period") return "." + + return event.key +} + +// The HTML host, except that it drops keys while an IME composes or while command keybinds are blocked, and that +// its owner can destroy it, which disposes the keymap. +function createAppKeymapHost(root: HTMLElement, blocked: () => boolean) { + const host = createHtmlKeymapHost(root) + const destroyed = new Set<() => void>() + const state = { destroyed: false } + + const keymapHost: KeymapHost = { + metadata: host.metadata, + rootTarget: host.rootTarget, + get isDestroyed() { + return state.destroyed + }, + onDestroy(listener) { + destroyed.add(listener) + + return () => destroyed.delete(listener) + }, + getFocusedTarget: () => host.getFocusedTarget(), + getParentTarget: (target) => host.getParentTarget(target), + isTargetDestroyed: (target) => host.isTargetDestroyed(target), + onKeyPress: (listener) => + host.onKeyPress((event) => { + const original = event.originalEvent + + // Escape, Enter and Tab confirm or cancel IME candidates; Safari can report them as keyCode 229. + if (original && (original.isComposing || original.keyCode === 229)) return + + if (blocked()) return + + listener(event) + }), + onKeyRelease: (listener) => host.onKeyRelease(listener), + onFocusChange: (listener) => host.onFocusChange(listener), + onTargetDestroy: (target, listener) => host.onTargetDestroy(target, listener), + createCommandEvent: () => host.createCommandEvent(), + } + + return { + host: keymapHost, + destroy() { + if (state.destroyed) return + state.destroyed = true + destroyed.forEach((listener) => listener()) + }, + } +} diff --git a/packages/app/test-browser/composer-ime.test.ts b/packages/app/test-browser/composer-ime.test.ts index 02c5c3ebbb1..4cd2c3da848 100644 --- a/packages/app/test-browser/composer-ime.test.ts +++ b/packages/app/test-browser/composer-ime.test.ts @@ -5,18 +5,15 @@ import { createComposerEditor } from "../src/composer/editor/interaction" import type { ComposerPersistedState } from "../src/composer/types" test.each([ - { key: "Escape", isComposing: true, keyCode: 27, list: false, stops: 0, selections: 0, prevented: false }, - { key: "Escape", isComposing: false, keyCode: 229, list: false, stops: 0, selections: 0, prevented: false }, - { key: "Escape", isComposing: false, keyCode: 27, list: false, stops: 1, selections: 0, prevented: true }, - { key: "Tab", isComposing: true, keyCode: 9, list: true, stops: 0, selections: 0, prevented: false }, - { key: "Tab", isComposing: false, keyCode: 229, list: true, stops: 0, selections: 0, prevented: false }, - { key: "Enter", isComposing: false, keyCode: 229, list: true, stops: 0, selections: 0, prevented: false }, - { key: "Tab", isComposing: false, keyCode: 9, list: true, stops: 0, selections: 1, prevented: true }, + { key: "Tab", isComposing: true, keyCode: 9, selections: 0, prevented: false }, + { key: "Tab", isComposing: false, keyCode: 229, selections: 0, prevented: false }, + { key: "Enter", isComposing: false, keyCode: 229, selections: 0, prevented: false }, + { key: "Tab", isComposing: false, keyCode: 9, selections: 1, prevented: true }, ])("IME key ownership: $key, composing=$isComposing, keyCode=$keyCode", (row) => { const value = createRoot((dispose) => { const store = createStore({ prompt: [], context: { items: [] } }) - const [calls, setCalls] = createStore({ stops: 0, selections: 0 }) + const [calls, setCalls] = createStore({ selections: 0 }) const editor = createComposerEditor({ store, @@ -26,10 +23,9 @@ test.each([ onSuggestionSelect: () => () => setCalls("selections", (count) => count + 1), view: { submit: { - working: () => true, stopping: () => false, onSubmit() {}, - onStop: () => setCalls("stops", (count) => count + 1), + onStop() {}, }, }, }) @@ -38,12 +34,10 @@ test.each([ }) try { - if (row.list) { - value.editor.openCommands() - value.editor.dispatch({ type: "popover.results", ids: ["review"] }) - expect(value.editor.state.popover.type).toBe("command-inline") - expect(value.editor.suggestions().map((item) => item.id)).toEqual(["review"]) - } + value.editor.openCommands() + value.editor.dispatch({ type: "popover.results", ids: ["review"] }) + expect(value.editor.state.popover.type).toBe("command-inline") + expect(value.editor.suggestions().map((item) => item.id)).toEqual(["review"]) const event = new KeyboardEvent("keydown", { key: row.key, @@ -54,11 +48,10 @@ test.each([ // happy-dom does not initialize the legacy keyCode field from KeyboardEventInit. Object.defineProperty(event, "keyCode", { value: row.keyCode }) expect(value.editor.onKeyDown(event)).toBe(true) - expect(value.calls.stops).toBe(row.stops) expect(value.calls.selections).toBe(row.selections) expect(event.defaultPrevented).toBe(row.prevented) - if (row.list && !row.selections) expect(value.editor.state.popover.type).toBe("command-inline") + if (!row.selections) expect(value.editor.state.popover.type).toBe("command-inline") } finally { value.dispose() }