From acca4c34d93beb2f490ab6702b061082cf0961ab Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Tue, 17 Nov 2026 16:00:08 +0800 Subject: [PATCH 1/4] feat(app): dispatch command shortcuts through @opentui/keymap --- bun.lock | 1 + packages/app/package.json | 1 + .../app/src/composer/editor/interaction.ts | 19 +- packages/app/src/composer/model.ts | 22 +- 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 ++++++++++++++++++ 9 files changed, 478 insertions(+), 159 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 c34eb189eaca..01aad3f8b355 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/package.json b/packages/app/package.json index 6b76d843204f..08fe999299d0 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 41a149a0dedc..538134d862d1 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -108,6 +108,10 @@ export function createComposerEditor(input: { onQuoteComment?: (item: Extract, comment: string) => void quoteComment?: QuoteCommentController onEditor?: (element: HTMLElement) => void + /** The key attaches files, as the `file.attach` command's keybind. Defaults to Mod+U. */ + attachKey?: (event: KeyboardEvent) => boolean + /** The key stops a running session, as the `prompt.stop` command's keybind. Defaults to Escape and Ctrl+G. */ + stopKey?: (event: KeyboardEvent) => boolean onSuggestionSelect?: (item: ComposerSuggestion) => (() => void) | void view: ComposerEditorView attachments?: ComposerAttachmentConfig @@ -474,12 +478,12 @@ export function createComposerEditor(input: { flushFocus() + // The command keymap attaches first in the app; this covers the editor when it runs on its own, as in a story. if ( mode() === "normal" && - (event.metaKey || event.ctrlKey) && - !event.altKey && - !event.shiftKey && - event.key.toLowerCase() === "u" + (input.attachKey + ? input.attachKey(event) + : (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "u") ) { event.preventDefault() attach() @@ -537,10 +541,13 @@ export function createComposerEditor(input: { return true } + // As with attaching, the `prompt.stop` command stops first in the app. 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") + (input.stopKey + ? input.stopKey(event) + : (event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && event.key.toLowerCase() === "g") || + event.key === "Escape") if (stop) { event.preventDefault() diff --git a/packages/app/src/composer/model.ts b/packages/app/src/composer/model.ts index c4c4a931c7c9..719a8b2ac300 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,9 +460,12 @@ 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) }, + attachKey: (event) => command.matches("file.attach", event), + stopKey: (event) => command.matches("prompt.stop", event), onSuggestionSelect(item) { if (item.kind !== "command") return const selected = slashCommands().find((entry) => entry.id === item.id) @@ -607,6 +613,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 d81f8692518a..adc3979480d2 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 72ddf29c6e15..aee190e37faa 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 7c916ee63a0e..0b9e73091ba9 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,14 +411,25 @@ 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) - const keymap = createMemo(() => commandKeymap(options(), (id) => settings.keybinds.get(id) !== undefined)) + 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 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 000000000000..15c3cc934e3b --- /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 000000000000..c8efe7ec954d --- /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()) + }, + } +} From c1378f07f38abb16ae9e5a76453f3cd5586db8be Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Tue, 17 Nov 2026 16:00:16 +0800 Subject: [PATCH 2/4] feat(app): support key chords in shortcuts --- packages/app/src/app.tsx | 2 + packages/app/src/runtime/i18n/en.ts | 1 + .../app/src/settings/keybinds/keybinds.tsx | 238 +++++++++++------- .../app/src/settings/keybinds/machine.test.ts | 82 ++++-- packages/app/src/settings/keybinds/machine.ts | 76 ++++-- packages/app/src/settings/model.tsx | 1 + .../app/src/shell/commands/command.test.ts | 6 + packages/app/src/shell/commands/command.tsx | 130 +++++++--- .../app/src/shell/commands/key-sequence.tsx | 38 +++ .../app/src/shell/commands/keymap.test.ts | 43 ++++ packages/app/src/shell/commands/keymap.ts | 52 ++-- .../test-browser/settings-keybinds.test.ts | 30 ++- 12 files changed, 503 insertions(+), 196 deletions(-) create mode 100644 packages/app/src/shell/commands/key-sequence.tsx diff --git a/packages/app/src/app.tsx b/packages/app/src/app.tsx index 78083534acfa..8b2133c63afb 100644 --- a/packages/app/src/app.tsx +++ b/packages/app/src/app.tsx @@ -12,6 +12,7 @@ import { type Component, createRenderEffect, ErrorBoundary, type JSX, type Paren import { Dynamic } from "solid-js/web" import { CommandProvider } from "@/shell/commands/command" import { DesktopCommands } from "@/shell/commands/desktop" +import { KeySequenceHint } from "@/shell/commands/key-sequence" import { ProjectIconsProvider } from "@/shell/layout/project-icons" import { GlobalProvider } from "@/runtime/server/runtime" import { LanguageProvider, UiI18nBridge, type Locale } from "@/runtime/i18n/language" @@ -105,6 +106,7 @@ export function AppInterface(props: { {rootProps.children} + diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index adc3979480d2..790b9f365312 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -1234,6 +1234,7 @@ export const dict = { "settings.shortcuts.unassigned": "Unassigned", "settings.shortcuts.pressKeys": "Press keys", "settings.shortcuts.unbind": "Unbind", + "settings.shortcuts.addKey": "Add a key", "settings.shortcuts.search.placeholder": "Search shortcuts", "settings.shortcuts.group.general": "General", diff --git a/packages/app/src/settings/keybinds/keybinds.tsx b/packages/app/src/settings/keybinds/keybinds.tsx index 999903381434..e742bbbac7d3 100644 --- a/packages/app/src/settings/keybinds/keybinds.tsx +++ b/packages/app/src/settings/keybinds/keybinds.tsx @@ -2,6 +2,8 @@ import { For, Show, createEffect, createMemo, createSignal, onCleanup, untrack } import { createStore } from "solid-js/store" import { makeEventListener } from "@solid-primitives/event-listener" import { Button } from "@opencode/ui/button" +import { Icon } from "@opencode/ui/icon" +import { IconButton } from "@opencode/ui/icon-button" import { showToast } from "@/shell/notifications/toast" import fuzzysort from "fuzzysort" import { Predicate } from "effect" @@ -13,6 +15,7 @@ import { useCommand, type CommandSection, } from "@/shell/commands/command" +import { chordStrokes } from "@/shell/commands/keymap" import { useLanguage } from "@/runtime/i18n/language" import { usePluginHost } from "@/runtime/plugin/host" import { useSettings } from "@/settings/model" @@ -21,7 +24,10 @@ import { SettingsSearchEmpty } from "@/settings/search-empty" import { SettingsSearchField } from "@/settings/search-field" import { INITIAL_KEYBIND_CAPTURE_STATE, + MAX_CHORD_STROKES, + selectCapturePrefix, selectCapturingKeybind, + selectExtendableKeybind, transitionKeybindCapture, type KeybindCaptureEffect, type KeybindCaptureEvent, @@ -134,28 +140,30 @@ function isEditableTarget(target: EventTarget | null) { ) } -function signatures(config: string | undefined) { - if (!config) return [] - const sigs: string[] = [] +// Each combo of a keybind as its strokes' signatures. +function chords(config: string | undefined) { + if (!config || config === "none") return [] - for (const kb of parseKeybind(config)) { - const parts: string[] = [] - - if (kb.ctrl) parts.push("ctrl") - - if (kb.alt) parts.push("alt") + return config + .split(",") + .map((combo) => chordStrokes(combo).map(signature)) + .filter((chord) => chord.length > 0) +} - if (kb.shift) parts.push("shift") +function signature(stroke: string) { + const kb = parseKeybind(stroke)[0] - if (kb.meta) parts.push("meta") + if (!kb) return stroke - if (kb.key) parts.push(kb.key) + return [kb.ctrl && "ctrl", kb.alt && "alt", kb.shift && "shift", kb.meta && "meta", kb.key].filter(Boolean).join("+") +} - if (parts.length === 0) continue - sigs.push(parts.join("+")) - } +// Two chords clash when one starts the other: the shorter one would run before the longer could finish. +function clashes(a: readonly string[], b: readonly string[]) { + const shorter = a.length <= b.length ? a : b + const longer = shorter === a ? b : a - return sigs + return shorter.every((stroke, index) => longer[index] === stroke) } function listFor( @@ -258,14 +266,16 @@ function filteredFor( return out } +// What the recording driver holds between effects: the release of the shortcut suspension. +type CaptureDriver = { release?: () => void } + export function createKeybindSettingsController( input: { command: Pick /** The ids of the installed GUI plugins; remembered commands of any other plugin are not listed. */ plugins?: () => ReadonlySet settings: { - current: { keybinds?: KeybindMap } - keybinds: Pick + keybinds: Pick } target?: Document notify?: (toast: { title: string; description: string }) => void @@ -275,7 +285,7 @@ export function createKeybindSettingsController( language: Pick = useLanguage(), ) { const [captureState, setCaptureState] = createSignal(INITIAL_KEYBIND_CAPTURE_STATE) - const overrides = createMemo(() => input.settings.current.keybinds ?? {}) + const overrides = createMemo(() => input.settings.keybinds.all()) const list = createMemo(() => { language.locale() @@ -300,28 +310,23 @@ export function createKeybindSettingsController( return input.command.catalog.find((item) => item.id === id)?.keybind } - const used = createMemo(() => { - const value = new Map() - - for (const id of list().keys()) { - for (const signature of signatures(effective(id))) { - const items = value.get(signature) + const used = createMemo(() => + Array.from(list().keys()).flatMap((id) => chords(effective(id)).map((chord) => ({ id, title: title(id), chord }))), + ) - if (items) { - items.push({ id, title: title(id) }) - continue - } + // The commands a chord would clash with, other than the one being recorded. + const conflicts = (keybind: string, id: string) => { + const chord = chords(keybind)[0] - value.set(signature, [{ id, title: title(id) }]) - } - } + if (!chord) return [] - return value - }) + return [...new Set(used().flatMap((item) => (item.id !== id && clashes(chord, item.chord) ? [item.title] : [])))] + } const notify = input.notify ?? ((toast: { title: string; description: string }) => showToast(toast)) const pageActive = () => input.active?.() ?? true - let release: (() => void) | undefined + + const driver: CaptureDriver = {} const dispatch = (event: KeybindCaptureEvent) => untrack(() => { @@ -332,17 +337,25 @@ export function createKeybindSettingsController( next.effects.forEach(run) }) + const conflictsFor = (keybind: string) => { + const id = selectCapturingKeybind(untrack(captureState)) + + if (!id) return [] + + return conflicts(keybind, id) + } + function run(effect: KeybindCaptureEffect) { if (effect.type === "keybinds.suspend") { - release?.() - release = input.command.suspend() + driver.release?.() + driver.release = input.command.suspend() return } if (effect.type === "keybinds.resume") { - release?.() - release = undefined + driver.release?.() + driver.release = undefined return } @@ -380,35 +393,23 @@ export function createKeybindSettingsController( event.preventDefault() event.stopPropagation() event.stopImmediatePropagation() - dispatch({ type: "key.pressed", input: recordedKey(event, id) }) + dispatch({ type: "key.pressed", input: recordedKey(event) }) } - const recordedKey = (event: KeyboardEvent, id: string): RecordedKeyInput => { - if (event.key === "Escape") return { kind: "escape" } + const recordedKey = (event: KeyboardEvent): RecordedKeyInput => { + const plain = !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey - const clear = - (event.key === "Backspace" || event.key === "Delete") && - !event.ctrlKey && - !event.metaKey && - !event.altKey && - !event.shiftKey - - if (clear) return { kind: "clear" } + if (event.key === "Escape") return { kind: "escape" } - const keybind = recordKeybind(event) + if ((event.key === "Backspace" || event.key === "Delete") && plain) return { kind: "backspace" } - if (!keybind) return { kind: "modifier-only" } + const stroke = recordKeybind(event) - const conflicts = new Map() + if (!stroke) return { kind: "modifier-only" } - for (const signature of signatures(keybind)) { - for (const item of used().get(signature) ?? []) { - if (item.id === id) continue - conflicts.set(item.id, item.title) - } - } + const prefix = selectCapturePrefix(untrack(captureState)) - return { kind: "combo", keybind, conflictTitles: [...conflicts.values()] } + return { kind: "stroke", stroke, conflictTitles: conflictsFor(prefix ? `${prefix} ${stroke}` : stroke) } } const target = input.target ?? (typeof document !== "undefined" ? document : undefined) @@ -430,16 +431,30 @@ export function createKeybindSettingsController( createEffect(() => dispatch({ type: "catalog.synced", ids: new Set(list().keys()) })) onCleanup(() => dispatch({ type: "disposed" })) + const format = (config: string | undefined) => formatKeybind(config ?? "", language.t) + + const firstCombo = (id: string) => { + const config = effective(id) + + return config && config !== "none" ? (config.split(",")[0]?.trim() ?? "") : "" + } + return { catalog: { groups: GROUPS, - filtered: (query: string) => - filteredFor(query, list(), grouped(), (id) => formatKeybind(effective(id) ?? "", language.t)), + filtered: (query: string) => filteredFor(query, list(), grouped(), (id) => format(effective(id))), title, - keybind: (id: string) => formatKeybind(effective(id) ?? "", language.t), + keybind: (id: string) => format(effective(id)), }, capture: { active: () => selectCapturingKeybind(captureState()), + /** The keys the key being recorded adds to, formatted. */ + prefix: () => format(selectCapturePrefix(captureState())), + /** Whether the row offers + to add a key to its shortcut: it was just saved and has room for another. */ + extendable: (id: string) => + selectExtendableKeybind(captureState()) === id && chordStrokes(firstCombo(id)).length < MAX_CHORD_STROKES, + extend: (id: string) => + dispatch({ type: "capture.extended", id, chord: firstCombo(id), pageActive: pageActive() }), toggle: (id: string) => dispatch({ type: "capture.toggled", id, pageActive: pageActive() }), unbind: (id: string) => dispatch({ type: "unbind.clicked", id }), }, @@ -471,7 +486,10 @@ export function SettingsKeybinds(props: { active?: boolean }) { title={controller.catalog.title} keybind={controller.catalog.keybind} active={controller.capture.active()} + prefix={controller.capture.prefix()} + extendable={controller.capture.extendable} onCapture={controller.capture.toggle} + onExtend={controller.capture.extend} onUnbind={controller.capture.unbind} hasOverrides={controller.settings.hasOverrides()} onReset={controller.settings.reset} @@ -486,7 +504,10 @@ function SettingsKeybindsView(props: { title: (id: string) => string keybind: (id: string) => string active: string | null + prefix: string + extendable: (id: string) => boolean onCapture: (id: string) => void + onExtend: (id: string) => void onUnbind: (id: string) => void hasOverrides: boolean onReset: () => void @@ -524,42 +545,32 @@ function SettingsKeybindsView(props: {

{language.t(groupKey[group])}

- {(id) => { - const binding = () => props.keybind(id) - - return ( -
- {props.title(id)} -
- - - - -
+ variant="ghost-muted" + icon={} + aria-label={language.t("settings.shortcuts.addKey")} + data-action="settings-shortcut-add-key" + onClick={() => props.onExtend(id)} + /> +
- ) - }} +
+ )} @@ -576,3 +587,38 @@ function SettingsKeybindsView(props: { ) } + +// A shortcut and the button that records it, with Unbind while recording one that is set. +function ShortcutButton(props: { + id: string + binding: string + active: string | null + prefix: string + onCapture: (id: string) => void + onUnbind: (id: string) => void +}) { + const language = useLanguage() + const recording = () => props.active === props.id + + return ( +
+ + + + +
+ ) +} diff --git a/packages/app/src/settings/keybinds/machine.test.ts b/packages/app/src/settings/keybinds/machine.test.ts index 13dd9772ada1..ae2080c2200a 100644 --- a/packages/app/src/settings/keybinds/machine.test.ts +++ b/packages/app/src/settings/keybinds/machine.test.ts @@ -1,7 +1,9 @@ import { describe, expect, test } from "bun:test" import { INITIAL_KEYBIND_CAPTURE_STATE, + selectCapturePrefix, selectCapturingKeybind, + selectExtendableKeybind, transitionKeybindCapture, type KeybindCaptureEffect, type KeybindCaptureEvent, @@ -17,6 +19,20 @@ function replay(events: KeybindCaptureEvent[], state = INITIAL_KEYBIND_CAPTURE_S const capture = (id: string, pageActive = true): KeybindCaptureEvent => ({ type: "capture.toggled", id, pageActive }) +const press = (stroke: string, conflictTitles: string[] = []): KeybindCaptureEvent => ({ + type: "key.pressed", + input: { kind: "stroke", stroke, conflictTitles }, +}) + +const extend = (id: string, chord: string): KeybindCaptureEvent => ({ + type: "capture.extended", + id, + chord, + pageActive: true, +}) + +const backspace: KeybindCaptureEvent = { type: "key.pressed", input: { kind: "backspace" } } + describe("keybind capture machine", () => { test("moving the recording to another row keeps shortcuts suspended", () => { const first = replay([capture("session.alpha")]) @@ -52,30 +68,54 @@ describe("keybind capture machine", () => { ]) }) - test("a conflicting combination keeps recording; a free one binds and resumes", () => { - const capturing = replay([capture("session.beta")]).state + test("a key saves at once, and + adds the next key to the saved shortcut", () => { + const saved = replay([capture("session.beta"), press("mod+k")]) - const conflict = transitionKeybindCapture(capturing, { - type: "key.pressed", - input: { kind: "combo", keybind: "mod+a", conflictTitles: ["Alpha"] }, - }) + expect(saved.effects).toEqual([ + { type: "binding.set", id: "session.beta", value: "mod+k" }, + { type: "keybinds.resume" }, + ]) + expect(selectExtendableKeybind(saved.state)).toBe("session.beta") - expect(conflict.state).toBe(capturing) - expect(conflict.effects).toEqual([{ type: "notify.conflict", keybind: "mod+a", conflictTitles: ["Alpha"] }]) + const extending = replay([extend("session.beta", "mod+k")], saved.state) + expect(extending.effects).toEqual([{ type: "keybinds.suspend" }]) + expect(replay([press("mod+c")], extending.state).effects).toEqual([ + { type: "binding.set", id: "session.beta", value: "mod+k mod+c" }, + { type: "keybinds.resume" }, + ]) - expect( - transitionKeybindCapture(capturing, { - type: "key.pressed", - input: { kind: "combo", keybind: "mod+x", conflictTitles: [] }, - }).effects, - ).toEqual([{ type: "binding.set", id: "session.beta", value: "mod+x" }, { type: "keybinds.resume" }]) - expect(transitionKeybindCapture(capturing, { type: "key.pressed", input: { kind: "modifier-only" } }).state).toBe( - capturing, - ) - expect(transitionKeybindCapture(capturing, { type: "key.pressed", input: { kind: "clear" } }).effects).toEqual([ + // Recording another row, or unbinding, takes the + away. + expect(selectExtendableKeybind(replay([capture("session.alpha")], saved.state).state)).toBeUndefined() + expect(selectExtendableKeybind(replay([{ type: "unbind.clicked", id: "x" }], saved.state).state)).toBeUndefined() + }) + + test("a clashing key keeps recording the same chord", () => { + const extending = replay([extend("session.beta", "mod+k")]).state + const clash = transitionKeybindCapture(extending, press("mod+c", ["Alpha"])) + + expect(clash.state).toBe(extending) + expect(selectCapturePrefix(clash.state)).toBe("mod+k") + expect(clash.effects).toEqual([{ type: "notify.conflict", keybind: "mod+k mod+c", conflictTitles: ["Alpha"] }]) + }) + + test("Backspace drops the key being added, and with nothing before it removes the shortcut", () => { + const dropped = replay([extend("session.beta", "mod+k"), backspace]) + expect(selectCapturingKeybind(dropped.state)).toBe("session.beta") + expect(selectCapturePrefix(dropped.state)).toBe("") + expect(dropped.effects).toEqual([]) + + expect(replay([capture("session.beta"), backspace]).effects).toEqual([ { type: "binding.set", id: "session.beta", value: "none" }, { type: "keybinds.resume" }, ]) + }) + + test("modifier-only keys are ignored and Escape stops recording", () => { + const capturing = replay([capture("session.beta")]).state + + expect(transitionKeybindCapture(capturing, { type: "key.pressed", input: { kind: "modifier-only" } }).state).toBe( + capturing, + ) expect(transitionKeybindCapture(capturing, { type: "key.pressed", input: { kind: "escape" } }).effects).toEqual([ { type: "keybinds.resume" }, ]) @@ -95,8 +135,8 @@ describe("keybind capture machine", () => { test("disposal resumes shortcuts once and ignores later keys", () => { const disposed = replay([capture("session.alpha"), { type: "disposed" }]) expect(disposed.effects).toEqual([{ type: "keybinds.resume" }]) - expect(transitionKeybindCapture(disposed.state, { type: "key.pressed", input: { kind: "escape" } }).effects).toEqual( - [], - ) + expect( + transitionKeybindCapture(disposed.state, { type: "key.pressed", input: { kind: "escape" } }).effects, + ).toEqual([]) }) }) diff --git a/packages/app/src/settings/keybinds/machine.ts b/packages/app/src/settings/keybinds/machine.ts index 5eee32ffa8a8..6305d25acd92 100644 --- a/packages/app/src/settings/keybinds/machine.ts +++ b/packages/app/src/settings/keybinds/machine.ts @@ -1,19 +1,28 @@ -/** A key pressed while recording, classified by the driver. */ +/** A command chord takes at most this many strokes; its row offers no + past that. */ +export const MAX_CHORD_STROKES = 4 + +/** A key pressed while recording, classified by the driver; a stroke carries the commands its chord would clash with. */ export type RecordedKeyInput = | { readonly kind: "escape" } - | { readonly kind: "clear" } + | { readonly kind: "backspace" } | { readonly kind: "modifier-only" } - | { readonly kind: "combo"; readonly keybind: string; readonly conflictTitles: readonly string[] } + | { readonly kind: "stroke"; readonly stroke: string; readonly conflictTitles: readonly string[] } -/** Recording a shortcut. Global shortcuts stay suspended exactly while a command is `capturing`. */ +/** + * Recording a shortcut. Global shortcuts stay suspended exactly while `capturing`. Each pressed key saves the chord + * at once: `prefix` holds the strokes it extends, from +. `idle.recent` is the row just saved, + * which offers + to add a key. + */ export type KeybindCaptureState = - | { readonly status: "idle" } - | { readonly status: "capturing"; readonly id: string } + | { readonly status: "idle"; readonly recent?: string } + | { readonly status: "capturing"; readonly id: string; readonly prefix: readonly string[] } | { readonly status: "disposed" } export type KeybindCaptureEvent = /** `pageActive`: whether the Shortcuts page shows; a hidden page never starts recording. */ | { readonly type: "capture.toggled"; readonly id: string; readonly pageActive: boolean } + /** + on a row: the next key is added to `chord`, the row's current shortcut. */ + | { readonly type: "capture.extended"; readonly id: string; readonly chord: string; readonly pageActive: boolean } /** Focus moved into a text field, such as a search box: typing there is not a shortcut. */ | { readonly type: "capture.cancelled" } | { readonly type: "unbind.clicked"; readonly id: string } @@ -42,6 +51,10 @@ const DISPOSED: KeybindCaptureState = Object.freeze({ status: "disposed" }) const NONE: readonly KeybindCaptureEffect[] = Object.freeze([]) +const NO_STROKES: readonly string[] = Object.freeze([]) + +const SUSPEND: KeybindCaptureEffect = Object.freeze({ type: "keybinds.suspend" }) + const RESUME: KeybindCaptureEffect = Object.freeze({ type: "keybinds.resume" }) export function transitionKeybindCapture( @@ -56,21 +69,26 @@ export function transitionKeybindCapture( if (event.type === "disposed") return { state: DISPOSED, effects: stop } if (event.type === "unbind.clicked") - return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: [{ type: "binding.set", id: event.id, value: "none" }, ...stop] } + return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: [...unbind(event.id), ...stop] } if (event.type === "reset.clicked") - return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: [...stop, { type: "bindings.reset" }, { type: "notify.reset" }] } + return { + state: INITIAL_KEYBIND_CAPTURE_STATE, + effects: [...stop, { type: "bindings.reset" }, { type: "notify.reset" }], + } + + if (event.type === "capture.toggled" || event.type === "capture.extended") { + const prefix = event.type === "capture.extended" ? event.chord.split(" ").filter(Boolean) : NO_STROKES - if (event.type === "capture.toggled") { if (!capturing) { if (!event.pageActive) return { state, effects: NONE } - return { state: { status: "capturing", id: event.id }, effects: [{ type: "keybinds.suspend" }] } + return { state: { status: "capturing", id: event.id, prefix }, effects: [SUSPEND] } } - // Moving to another row keeps shortcuts suspended instead of resuming them for a moment. - if (state.id !== event.id && event.pageActive) - return { state: { status: "capturing", id: event.id }, effects: NONE } + // Moving to another row, or extending one, keeps shortcuts suspended instead of resuming them for a moment. + if ((state.id !== event.id || event.type === "capture.extended") && event.pageActive) + return { state: { status: "capturing", id: event.id, prefix }, effects: NONE } return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: stop } } @@ -92,18 +110,40 @@ export function transitionKeybindCapture( if (input.kind === "escape") return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: stop } - if (input.kind === "clear") - return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: [{ type: "binding.set", id: state.id, value: "none" }, RESUME] } + // With nothing before it, Backspace removes the shortcut; otherwise it drops the key being added. + if (input.kind === "backspace") { + if (state.prefix.length === 0) + return { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: [...unbind(state.id), RESUME] } + + return { state: { ...state, prefix: state.prefix.slice(0, -1) }, effects: NONE } + } + + const keybind = [...state.prefix, input.stroke].join(" ") + // A clashing key keeps recording, so the next press tries again. if (input.conflictTitles.length > 0) - return { state, effects: [{ type: "notify.conflict", keybind: input.keybind, conflictTitles: input.conflictTitles }] } + return { state, effects: [{ type: "notify.conflict", keybind, conflictTitles: input.conflictTitles }] } return { - state: INITIAL_KEYBIND_CAPTURE_STATE, - effects: [{ type: "binding.set", id: state.id, value: input.keybind }, RESUME], + state: { status: "idle", recent: state.id }, + effects: [{ type: "binding.set", id: state.id, value: keybind }, RESUME], } } export function selectCapturingKeybind(state: KeybindCaptureState) { return state.status === "capturing" ? state.id : null } + +/** The strokes the key being recorded adds to, as a keybind such as `mod+k`. */ +export function selectCapturePrefix(state: KeybindCaptureState) { + return state.status === "capturing" ? state.prefix.join(" ") : "" +} + +/** The row that offers + to add a key: the one just saved. */ +export function selectExtendableKeybind(state: KeybindCaptureState) { + return state.status === "idle" ? state.recent : undefined +} + +function unbind(id: string): readonly KeybindCaptureEffect[] { + return [{ type: "binding.set", id, value: "none" }] +} diff --git a/packages/app/src/settings/model.tsx b/packages/app/src/settings/model.tsx index 01b89173c793..7ebd4d8eec28 100644 --- a/packages/app/src/settings/model.tsx +++ b/packages/app/src/settings/model.tsx @@ -502,6 +502,7 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont }, }, keybinds: { + all: () => store.keybinds ?? {}, get: (action: string) => store.keybinds?.[action], set(action: string, keybind: string) { setStore("keybinds", action, keybind) diff --git a/packages/app/src/shell/commands/command.test.ts b/packages/app/src/shell/commands/command.test.ts index aee190e37faa..56fa2c0f0e64 100644 --- a/packages/app/src/shell/commands/command.test.ts +++ b/packages/app/src/shell/commands/command.test.ts @@ -6,6 +6,7 @@ import { commandPaletteOptions, CommandCatalog, formatKeybind, + formatKeybindParts, matchKeybind, parseKeybind, type CommandOption, @@ -109,4 +110,9 @@ describe("command keybinds", () => { expect(formatKeybind("mod+k,mod+p")).toContain("K") expect(formatKeybind("mod+k,mod+p")).not.toContain("P") }) + + test("formatKeybind shows a chord stroke by stroke", () => { + expect(formatKeybind("g i")).toBe("G I") + expect(formatKeybindParts("g s")).toEqual(["G", "S"]) + }) }) diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index 0b9e73091ba9..fb60e0c77b3b 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -10,7 +10,8 @@ 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" +import { chordStrokes, createAppKeymap, IS_MAC, keyFromKeyboardEvent, registerCommandLayers } from "./keymap" +import type { ActiveKey, KeySequencePart } from "@opentui/keymap" export { keyFromKeyboardEvent } @@ -166,50 +167,56 @@ function placeAfterSlash(options: CommandOption[]) { }) } +/** The single-stroke combos of a keybind; chords such as `mod+k mod+c` are left out. */ export function parseKeybind(config: string): Keybind[] { if (!config || config === "none") return [] - return config.split(",").map((combo) => { - const parts = combo.trim().toLowerCase().split("+") + return config + .split(",") + .filter((combo) => chordStrokes(combo).length === 1) + .map(parseStroke) +} - const keybind: Keybind = { - key: "", - ctrl: false, - meta: false, - shift: false, - alt: false, - } +function parseStroke(combo: string): Keybind { + const parts = combo.trim().toLowerCase().split("+") - for (const part of parts) { - switch (part) { - case "ctrl": - case "control": - keybind.ctrl = true - break - case "meta": - case "cmd": - case "command": - keybind.meta = true - break - case "mod": - if (IS_MAC) keybind.meta = true - else keybind.ctrl = true - break - case "alt": - case "option": - keybind.alt = true - break - case "shift": - keybind.shift = true - break - default: - keybind.key = part - break - } + const keybind: Keybind = { + key: "", + ctrl: false, + meta: false, + shift: false, + alt: false, + } + + for (const part of parts) { + switch (part) { + case "ctrl": + case "control": + keybind.ctrl = true + break + case "meta": + case "cmd": + case "command": + keybind.meta = true + break + case "mod": + if (IS_MAC) keybind.meta = true + else keybind.ctrl = true + break + case "alt": + case "option": + keybind.alt = true + break + case "shift": + keybind.shift = true + break + default: + keybind.key = part + break } + } - return keybind - }) + return keybind } export function matchKeybind(keybinds: Keybind[], event: KeyboardEvent): boolean { @@ -248,6 +255,10 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) { ["arrowdown", "↓"], ["arrowleft", "←"], ["arrowright", "→"], + ["up", "↑"], + ["down", "↓"], + ["left", "←"], + ["right", "→"], ["comma", ","], ["plus", "+"], ]) @@ -263,6 +274,7 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) { ["insert", "common.key.insert"], ["pagedown", "common.key.pageDown"], ["pageup", "common.key.pageUp"], + ["return", "common.key.enter"], ["space", "common.key.space"], ["tab", "common.key.tab"], ]) @@ -279,18 +291,29 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) { return parts } +/** + * The first combo of a keybind as keycap labels. A single stroke gives one label per key (⌘, K); a chord gives one + * label per stroke (⌘K, ⌘C). + */ export function formatKeybindParts(config: string, t?: (key: KeyLabel) => string): string[] { if (!config || config === "none") return [] - const keybind = parseKeybind(config)[0] + const strokes = chordStrokes(config.split(",")[0] ?? "") + + if (strokes.length === 1) return displayKeybindParts(parseStroke(strokes[0]!), t) - return keybind ? displayKeybindParts(keybind, t) : [] + return strokes.map((stroke) => joinParts(displayKeybindParts(parseStroke(stroke), t))) } export function formatKeybind(config: string, t?: (key: KeyLabel) => string): string { + const strokes = chordStrokes(config && config !== "none" ? (config.split(",")[0] ?? "") : "") const parts = formatKeybindParts(config, t) - if (parts.length === 0) return "" + if (strokes.length > 1) return parts.join(" ") + return joinParts(parts) +} + +function joinParts(parts: string[]) { return IS_MAC ? parts.join("") : parts.join("+") } @@ -413,8 +436,19 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const app = createAppKeymap({ blocked: () => suspended() || !!dialog.active, editable: isEditableTarget }) + const [pending, setPending] = createStore<{ sequence: readonly KeySequencePart[]; next: readonly ActiveKey[] }>({ + sequence: [], + next: [], + }) + onCleanup(app.destroy) + onCleanup( + app.keymap.on("pendingSequence", (sequence) => + setPending({ sequence, next: sequence.length ? app.keymap.getActiveKeys() : [] }), + ), + ) + createEffect(() => { const bound = options().filter((option) => !option.id.startsWith(SUGGESTED_PREFIX) && !option.disabled) @@ -500,6 +534,20 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex return config ? formatKeybindParts(config, language.t) : [] }, + /** The key sequence in progress, and the keys that can continue it. */ + pending, + /** Formats one stroke of a pending key sequence. */ + strokeParts(part: Pick) { + const stroke = part.stroke + + return displayKeybindParts( + { key: stroke.name, ctrl: stroke.ctrl, meta: stroke.super, shift: stroke.shift, alt: stroke.meta }, + language.t, + ) + }, + title(id: string) { + return optionMap().get(id)?.title + }, /** The event matches the command's effective keybind (user override or default). */ matches(id: string, event: KeyboardEvent) { const config = keybindConfig(id) diff --git a/packages/app/src/shell/commands/key-sequence.tsx b/packages/app/src/shell/commands/key-sequence.tsx new file mode 100644 index 000000000000..d30cf5526086 --- /dev/null +++ b/packages/app/src/shell/commands/key-sequence.tsx @@ -0,0 +1,38 @@ +import { For, Show } from "solid-js" +import { Portal } from "solid-js/web" +import { Predicate } from "effect" +import type { ActiveKey } from "@opentui/keymap" +import { Keybind } from "@opencode/ui/keybind" +import { useCommand } from "@/shell/commands/command" + +/** While a chord is in progress, lists the keys that continue it and what each runs. */ +export function KeySequenceHint() { + const command = useCommand() + + const label = (key: ActiveKey) => + Predicate.isString(key.command) ? (command.title(key.command) ?? key.command) : undefined + + return ( + 0}> + +
+ command.strokeParts(part))} variant="neutral" /> +
+ + {(key) => ( + <> + + {key.continues ? "…" : (label(key) ?? "")} + + )} + +
+
+
+
+ ) +} diff --git a/packages/app/src/shell/commands/keymap.test.ts b/packages/app/src/shell/commands/keymap.test.ts index 15c3cc934e3b..edfe7d2d0c1b 100644 --- a/packages/app/src/shell/commands/keymap.test.ts +++ b/packages/app/src/shell/commands/keymap.test.ts @@ -118,6 +118,49 @@ test("a focus target's command wins inside the target and is absent outside it", expect(ran).toEqual(["prompt.stop", "dialog.close"]) }) +test("chords run from any focus when their first key has a modifier, and only outside text fields otherwise", () => { + const ran: string[] = [] + setup([command("comment.toggle", "mod+k mod+c", ran), command("inbox.go", "g i", ran)]) + const field = editor() + + press(field, { key: "k", ctrlKey: true }) + press(field, { key: "c", ctrlKey: true }) + const typed = press(field, { key: "g" }) + press(field, { key: "i" }) + field.blur() + press(document.body, { key: "g" }) + press(document.body, { key: "i" }) + + expect(typed.defaultPrevented).toBe(false) + expect(ran).toEqual(["comment.toggle", "inbox.go"]) +}) + +test("Escape cancels a pending chord without running a command, and Backspace takes back its last key", () => { + const ran: string[] = [] + + const app = setup([ + command("tab.new", "ctrl+x t", ran), + command("tab.close", "ctrl+x w", ran), + command("prompt.stop", "escape", ran, { editable: true }), + ]) + + press(document.body, { key: "x", ctrlKey: true }) + expect( + app.keymap + .getActiveKeys() + .map((key) => String(key.command)) + .sort(), + ).toEqual(["tab.close", "tab.new"]) + press(document.body, { key: "Escape" }) + press(document.body, { key: "t" }) + expect(ran).toEqual([]) + expect(app.keymap.getPendingSequence()).toHaveLength(0) + + press(document.body, { key: "x", ctrlKey: true }) + press(document.body, { key: "Backspace" }) + expect(app.keymap.getPendingSequence()).toHaveLength(0) +}) + test.each([ { name: "composing", init: { key: "Escape", isComposing: true } }, { name: "Safari's composition Enter", init: { key: "Escape", keyCode: 229 } }, diff --git a/packages/app/src/shell/commands/keymap.ts b/packages/app/src/shell/commands/keymap.ts index c8efe7ec954d..c57f9efb89c1 100644 --- a/packages/app/src/shell/commands/keymap.ts +++ b/packages/app/src/shell/commands/keymap.ts @@ -1,5 +1,9 @@ import { Keymap, type KeymapHost } from "@opentui/keymap" -import { registerDefaultBindingParser } from "@opentui/keymap/addons" +import { + registerBackspacePopsPendingSequence, + registerDefaultBindingParser, + registerEscapeClearsPendingSequence, +} from "@opentui/keymap/addons" import { createHtmlKeymapHost, type HtmlKeymapEvent } from "@opentui/keymap/html" import type { CommandOption } from "./command" @@ -7,6 +11,11 @@ export const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad export type AppKeymap = Keymap +/** Splits one combo of a keybind into its chord strokes: `mod+k mod+c` into two. */ +export function chordStrokes(combo: string) { + return combo.trim().split(/\s+/).filter(Boolean) +} + /** * The keymap behind every command keybind. It reads keys in the capture phase on the document root, before the * focused element sees them. @@ -14,12 +23,12 @@ export type AppKeymap = Keymap 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. + // Every binding is written by `keymapKey`: strokes separated by spaces, each a `+`-joined combo. keymap.prependBindingParser((ctx) => { if (ctx.index !== 0) return return { - parts: [ctx.parseObjectKey(strokeInput(ctx.input.trim()), { display: ctx.input })], + parts: chordStrokes(ctx.input).map((stroke) => ctx.parseObjectKey(strokeInput(stroke), { display: stroke })), nextIndex: ctx.input.length, } }) @@ -48,12 +57,14 @@ export function createAppKeymap(input: { blocked: () => boolean; editable: (targ : []), ]) }) - // A binding whose key types a character stays out of text fields, so typing in them is never taken. + // A binding whose first key types a character stays out of text fields, so typing never starts a sequence. keymap.registerBindingFields({ outsideText(value, ctx) { if (value === true) ctx.activeWhen(() => !input.editable(document.activeElement)) }, }) + registerEscapeClearsPendingSequence(keymap) + registerBackspacePopsPendingSequence(keymap) return { keymap, destroy: host.destroy } } @@ -111,21 +122,24 @@ export function registerCommandLayers(keymap: AppKeymap, options: CommandOption[ return () => disposers.forEach((dispose) => dispose()) } -/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`) into the keymap's. */ +/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`, `mod+k mod+c`) 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("+") + return chordStrokes(combo) + .map((stroke) => + stroke + .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("+"), + ) + .join(" ") } // One stroke as `keymapKey` writes it, such as `super+shift+[`. @@ -143,7 +157,7 @@ function strokeInput(stroke: string) { } } -/** Whether a keymap key types a character, so it should stay out of text fields. */ +/** Whether the first key of a keymap sequence 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 diff --git a/packages/app/test-browser/settings-keybinds.test.ts b/packages/app/test-browser/settings-keybinds.test.ts index 6c864ada99a6..e56781362040 100644 --- a/packages/app/test-browser/settings-keybinds.test.ts +++ b/packages/app/test-browser/settings-keybinds.test.ts @@ -16,6 +16,7 @@ function setup(overrides: Record = {}, plugins?: ReadonlySet = {}, plugins?: ReadonlySet plugins), settings: { - current: { keybinds: overrides }, keybinds: { + all: () => overrides, get: (id) => overrides[id], set: (id, value) => { overrides[id] = value @@ -73,6 +74,10 @@ function modKey(key: string) { return new KeyboardEvent("keydown", { key, ctrlKey: !mac, metaKey: mac, bubbles: true, cancelable: true }) } +function key(key: string, init?: KeyboardEventInit) { + return new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }) +} + describe("keybind settings controller", () => { test("derives the catalog, effective bindings, and filtered groups", () => { const state = setup({ "session.beta": "alt+k" }) @@ -117,6 +122,29 @@ describe("keybind settings controller", () => { expect(state.changes).toEqual([["session.beta", "mod+x"]]) }) + test("+ adds a key to the saved shortcut, and a chord may not start or be started by another", () => { + const state = setup() + + state.controller.capture.toggle("session.beta") + document.dispatchEvent(modKey("k")) + expect(state.notifications.map((toast) => toast.description)).toEqual([expect.stringContaining("Chord")]) + + document.dispatchEvent(modKey("j")) + expect(state.changes).toEqual([["session.beta", "mod+j"]]) + expect(state.controller.capture.extendable("session.beta")).toBe(true) + expect(state.controller.capture.extendable("session.alpha")).toBe(false) + + state.controller.capture.extend("session.beta") + expect(state.controller.capture.prefix()).not.toBe("") + document.dispatchEvent(modKey("c")) + expect(state.changes).toEqual([ + ["session.beta", "mod+j"], + ["session.beta", "mod+j mod+c"], + ]) + + state.dispose() + }) + test("moving the recording between rows keeps shortcuts suspended, and hiding the page resumes them", () => { const [active, setActive] = createSignal(true) const state = setup({}, undefined, active) From ffc6b6c67f3809b1f597381cceda5ffb9cc91ada Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Tue, 17 Nov 2026 16:01:08 +0800 Subject: [PATCH 3/4] feat(app): add a leader key for shortcut chords --- packages/app/src/runtime/i18n/en.ts | 4 + .../app/src/settings/keybinds/keybinds.tsx | 85 +++++++++++++++++-- .../app/src/settings/keybinds/machine.test.ts | 21 +++++ packages/app/src/settings/keybinds/machine.ts | 29 +++++-- packages/app/src/settings/model.test.ts | 5 ++ packages/app/src/settings/model.tsx | 13 +++ .../app/src/shell/commands/command.test.ts | 6 +- packages/app/src/shell/commands/command.tsx | 41 +++++++-- .../app/src/shell/commands/key-sequence.tsx | 2 +- .../app/src/shell/commands/keymap.test.ts | 51 ++++++++++- packages/app/src/shell/commands/keymap.ts | 78 +++++++++++++---- .../test-browser/settings-keybinds.test.ts | 42 ++++++++- 12 files changed, 335 insertions(+), 42 deletions(-) diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index 790b9f365312..3977372081e4 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -106,6 +106,7 @@ export const dict = { "command.prompt.mode.normal": "Prompt", "command.prompt.mode.toggle": "Toggle shell mode", "command.prompt.stop": "Stop session", + "command.keymap.leader": "Leader key", "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", @@ -789,6 +790,7 @@ export const dict = { "common.edit": "Edit", "common.loadMore": "Load more", "common.key.esc": "ESC", + "common.key.leader": "Leader", "common.key.ctrl": "Ctrl", "common.key.alt": "Alt", "common.key.shift": "Shift", @@ -1234,7 +1236,9 @@ export const dict = { "settings.shortcuts.unassigned": "Unassigned", "settings.shortcuts.pressKeys": "Press keys", "settings.shortcuts.unbind": "Unbind", + "settings.shortcuts.insertLeader": "Add leader", "settings.shortcuts.addKey": "Add a key", + "settings.shortcuts.leader.description": "Starts shortcuts that begin with Leader. Not set by default.", "settings.shortcuts.search.placeholder": "Search shortcuts", "settings.shortcuts.group.general": "General", diff --git a/packages/app/src/settings/keybinds/keybinds.tsx b/packages/app/src/settings/keybinds/keybinds.tsx index e742bbbac7d3..12ef8497302a 100644 --- a/packages/app/src/settings/keybinds/keybinds.tsx +++ b/packages/app/src/settings/keybinds/keybinds.tsx @@ -15,15 +15,17 @@ import { useCommand, type CommandSection, } from "@/shell/commands/command" -import { chordStrokes } from "@/shell/commands/keymap" +import { chordStrokes, LEADER, validChord } from "@/shell/commands/keymap" import { useLanguage } from "@/runtime/i18n/language" import { usePluginHost } from "@/runtime/plugin/host" import { useSettings } from "@/settings/model" +import { SettingsRow } from "@/settings/row" import { SettingsList } from "@/settings/list" import { SettingsSearchEmpty } from "@/settings/search-empty" import { SettingsSearchField } from "@/settings/search-field" import { INITIAL_KEYBIND_CAPTURE_STATE, + LEADER_SLOT, MAX_CHORD_STROKES, selectCapturePrefix, selectCapturingKeybind, @@ -140,14 +142,20 @@ function isEditableTarget(target: EventTarget | null) { ) } -// Each combo of a keybind as its strokes' signatures. -function chords(config: string | undefined) { +// Each combo of a keybind as its strokes' signatures, with `` spelled as the leader key when one is set. +function chords(config: string | undefined, leader: string | undefined) { if (!config || config === "none") return [] return config .split(",") - .map((combo) => chordStrokes(combo).map(signature)) - .filter((chord) => chord.length > 0) + .filter(validChord) + .map((combo) => + chordStrokes(combo).flatMap((stroke) => { + if (stroke.toLowerCase() !== LEADER) return [signature(stroke)] + + return [leader ? signature(leader) : LEADER] + }), + ) } function signature(stroke: string) { @@ -276,6 +284,7 @@ export function createKeybindSettingsController( plugins?: () => ReadonlySet settings: { keybinds: Pick + keymap: Pick } target?: Document notify?: (toast: { title: string; description: string }) => void @@ -286,6 +295,7 @@ export function createKeybindSettingsController( ) { const [captureState, setCaptureState] = createSignal(INITIAL_KEYBIND_CAPTURE_STATE) const overrides = createMemo(() => input.settings.keybinds.all()) + const leader = () => input.settings.keymap.leader() const list = createMemo(() => { language.locale() @@ -311,18 +321,33 @@ export function createKeybindSettingsController( } const used = createMemo(() => - Array.from(list().keys()).flatMap((id) => chords(effective(id)).map((chord) => ({ id, title: title(id), chord }))), + Array.from(list().keys()).flatMap((id) => + chords(effective(id), leader()).map((chord) => ({ id, title: title(id), chord })), + ), ) // The commands a chord would clash with, other than the one being recorded. const conflicts = (keybind: string, id: string) => { - const chord = chords(keybind)[0] + const chord = chords(keybind, leader())[0] if (!chord) return [] return [...new Set(used().flatMap((item) => (item.id !== id && clashes(chord, item.chord) ? [item.title] : [])))] } + // A leader key clashes with every shortcut that starts with that key, apart from the leader's own chords. + const leaderConflicts = (stroke: string) => { + const key = signature(stroke) + + return [ + ...new Set( + Array.from(list().keys()).flatMap((id) => + chords(effective(id), undefined).some((chord) => chord[0] === key) ? [title(id)] : [], + ), + ), + ] + } + const notify = input.notify ?? ((toast: { title: string; description: string }) => showToast(toast)) const pageActive = () => input.active?.() ?? true @@ -342,7 +367,7 @@ export function createKeybindSettingsController( if (!id) return [] - return conflicts(keybind, id) + return id === LEADER_SLOT ? leaderConflicts(keybind) : conflicts(keybind, id) } function run(effect: KeybindCaptureEffect) { @@ -362,6 +387,8 @@ export function createKeybindSettingsController( if (effect.type === "binding.set") return input.settings.keybinds.set(effect.id, effect.value) + if (effect.type === "leader.set") return input.settings.keymap.setLeader(effect.value) + if (effect.type === "bindings.reset") return input.settings.keybinds.resetAll() if (effect.type === "notify.reset") { @@ -457,6 +484,11 @@ export function createKeybindSettingsController( dispatch({ type: "capture.extended", id, chord: firstCombo(id), pageActive: pageActive() }), toggle: (id: string) => dispatch({ type: "capture.toggled", id, pageActive: pageActive() }), unbind: (id: string) => dispatch({ type: "unbind.clicked", id }), + insertLeader: () => dispatch({ type: "leader.inserted" }), + }, + leader: { + keybind: () => format(leader()), + set: () => !!leader(), }, settings: { hasOverrides: () => Object.values(overrides()).some(Predicate.isString), @@ -481,6 +513,7 @@ export function SettingsKeybinds(props: { active?: boolean }) { return ( @@ -499,6 +534,7 @@ export function SettingsKeybinds(props: { active?: boolean }) { function SettingsKeybindsView(props: { visible?: boolean + leader: string groups: KeybindGroup[] filtered: (query: string) => Map title: (id: string) => string @@ -506,9 +542,11 @@ function SettingsKeybindsView(props: { active: string | null prefix: string extendable: (id: string) => boolean + canInsertLeader: boolean onCapture: (id: string) => void onExtend: (id: string) => void onUnbind: (id: string) => void + onInsertLeader: () => void hasOverrides: boolean onReset: () => void }) { @@ -538,6 +576,25 @@ function SettingsKeybindsView(props: {
+ +
+ + + + + +
+
{(group) => ( 0}> @@ -549,6 +606,18 @@ function SettingsKeybindsView(props: {
{props.title(id)}
+ + + { { type: "binding.set", id: "session.beta", value: "none" }, { type: "keybinds.resume" }, ]) + expect(replay([capture(LEADER_SLOT), backspace]).effects).toEqual([ + { type: "leader.set", value: undefined }, + { type: "keybinds.resume" }, + ]) + }) + + test("the leader starts only a command's chord, and the leader slot saves one stroke", () => { + const leader = replay([capture("session.beta"), { type: "leader.inserted" }]) + expect(selectCapturePrefix(leader.state)).toBe("") + expect(selectCapturePrefix(replay([{ type: "leader.inserted" }], leader.state).state)).toBe("") + expect(replay([press("n")], leader.state).effects[0]).toEqual({ + type: "binding.set", + id: "session.beta", + value: " n", + }) + expect(selectCapturePrefix(replay([capture(LEADER_SLOT), { type: "leader.inserted" }]).state)).toBe("") + + const set = replay([capture(LEADER_SLOT), press("ctrl+x")]) + expect(set.effects).toEqual([{ type: "leader.set", value: "ctrl+x" }, { type: "keybinds.resume" }]) + expect(selectExtendableKeybind(set.state)).toBeUndefined() }) test("modifier-only keys are ignored and Escape stops recording", () => { diff --git a/packages/app/src/settings/keybinds/machine.ts b/packages/app/src/settings/keybinds/machine.ts index 6305d25acd92..119d11e7da14 100644 --- a/packages/app/src/settings/keybinds/machine.ts +++ b/packages/app/src/settings/keybinds/machine.ts @@ -1,3 +1,6 @@ +/** The recording slot of the leader key, which records one stroke instead of a command's chord. */ +export const LEADER_SLOT = "keymap.leader" + /** A command chord takes at most this many strokes; its row offers no + past that. */ export const MAX_CHORD_STROKES = 4 @@ -10,7 +13,7 @@ export type RecordedKeyInput = /** * Recording a shortcut. Global shortcuts stay suspended exactly while `capturing`. Each pressed key saves the chord - * at once: `prefix` holds the strokes it extends, from +. `idle.recent` is the row just saved, + * at once: `prefix` holds the strokes it extends, from + or the Leader button. `idle.recent` is the row just saved, * which offers + to add a key. */ export type KeybindCaptureState = @@ -28,6 +31,8 @@ export type KeybindCaptureEvent = | { readonly type: "unbind.clicked"; readonly id: string } | { readonly type: "reset.clicked" } | { readonly type: "key.pressed"; readonly input: RecordedKeyInput } + /** Starts the chord with the leader key; only a command's recording with nothing before it takes it. */ + | { readonly type: "leader.inserted" } | { readonly type: "page.synced"; readonly active: boolean } | { readonly type: "catalog.synced"; readonly ids: ReadonlySet } | { readonly type: "disposed" } @@ -36,6 +41,7 @@ export type KeybindCaptureEffect = | { readonly type: "keybinds.suspend" } | { readonly type: "keybinds.resume" } | { readonly type: "binding.set"; readonly id: string; readonly value: string } + | { readonly type: "leader.set"; readonly value: string | undefined } | { readonly type: "bindings.reset" } | { readonly type: "notify.conflict"; readonly keybind: string; readonly conflictTitles: readonly string[] } | { readonly type: "notify.reset" } @@ -102,7 +108,15 @@ export function transitionKeybindCapture( // A plugin removed while its command was recording. if (event.type === "catalog.synced") - return event.ids.has(state.id) ? { state, effects: NONE } : { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: stop } + return event.ids.has(state.id) || state.id === LEADER_SLOT + ? { state, effects: NONE } + : { state: INITIAL_KEYBIND_CAPTURE_STATE, effects: stop } + + if (event.type === "leader.inserted") { + if (state.id === LEADER_SLOT || state.prefix.length > 0) return { state, effects: NONE } + + return { state: { ...state, prefix: [""] }, effects: NONE } + } const input = event.input @@ -125,8 +139,13 @@ export function transitionKeybindCapture( return { state, effects: [{ type: "notify.conflict", keybind, conflictTitles: input.conflictTitles }] } return { - state: { status: "idle", recent: state.id }, - effects: [{ type: "binding.set", id: state.id, value: keybind }, RESUME], + state: state.id === LEADER_SLOT ? INITIAL_KEYBIND_CAPTURE_STATE : { status: "idle", recent: state.id }, + effects: [ + state.id === LEADER_SLOT + ? { type: "leader.set", value: input.stroke } + : { type: "binding.set", id: state.id, value: keybind }, + RESUME, + ], } } @@ -145,5 +164,5 @@ export function selectExtendableKeybind(state: KeybindCaptureState) { } function unbind(id: string): readonly KeybindCaptureEffect[] { - return [{ type: "binding.set", id, value: "none" }] + return [id === LEADER_SLOT ? { type: "leader.set", value: undefined } : { type: "binding.set", id, value: "none" }] } diff --git a/packages/app/src/settings/model.test.ts b/packages/app/src/settings/model.test.ts index f1c90dae3e98..a727ed02ff77 100644 --- a/packages/app/src/settings/model.test.ts +++ b/packages/app/src/settings/model.test.ts @@ -206,6 +206,11 @@ describe("settings schema", () => { }, ) + test("keeps a valid leader key and drops an invalid one", () => { + expect(decode({ keymap: { leader: "ctrl+x" } }).keymap).toEqual({ leader: "ctrl+x" }) + expect(decode({ keymap: { leader: 7 } }).keymap).toEqual({}) + }) + test("does not silently repair invalid values during encoding", () => { expect(() => Schema.encodeUnknownSync(settingsSchema)({ ...decode({}), appearance: { fontSize: "large" } }), diff --git a/packages/app/src/settings/model.tsx b/packages/app/src/settings/model.tsx index 7ebd4d8eec28..86ebf644a6c1 100644 --- a/packages/app/src/settings/model.tsx +++ b/packages/app/src/settings/model.tsx @@ -191,6 +191,11 @@ const soundsSchema = Persistence.struct({ interfaceEnabled: Schema.optional(Schema.Boolean), }) +const keymapSchema = Persistence.struct({ + // The key that starts `` chords. Unset by default. + leader: Persistence.optional(Schema.String), +}) + export const settingsSchema = Persistence.struct({ general: generalSchema, // Owned by the details plugin, which copies it out once; kept so settings rewrites cannot drop it first. @@ -199,6 +204,7 @@ export const settingsSchema = Persistence.struct({ ), appearance: appearanceSchema, keybinds: Persistence.record(Schema.String.pipe(Schema.catchDecoding(() => Effect.succeed(Option.none())))), + keymap: Persistence.optional(keymapSchema), permissions: permissionsSchema, workspaces: workspacesSchema, notifications: notificationsSchema, @@ -520,6 +526,13 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont setStore("keybinds", reconcile({})) }, }, + keymap: { + /** The leader key, if one is set. */ + leader: () => store.keymap?.leader, + setLeader(leader: string | undefined) { + setStore("keymap", { leader }) + }, + }, permissions: { autoApproveDefault, setAutoApproveDefault(value: boolean) { diff --git a/packages/app/src/shell/commands/command.test.ts b/packages/app/src/shell/commands/command.test.ts index 56fa2c0f0e64..8cb1dd8b592b 100644 --- a/packages/app/src/shell/commands/command.test.ts +++ b/packages/app/src/shell/commands/command.test.ts @@ -111,8 +111,10 @@ describe("command keybinds", () => { expect(formatKeybind("mod+k,mod+p")).not.toContain("P") }) - test("formatKeybind shows a chord stroke by stroke", () => { + test("formatKeybind shows a chord stroke by stroke, and the leader as Leader rather than its key", () => { + expect(formatKeybind(" n")).toBe("Leader N") + expect(formatKeybind("n")).toBe("Leader N") + expect(formatKeybindParts(" g s")).toEqual(["Leader", "G", "S"]) expect(formatKeybind("g i")).toBe("G I") - expect(formatKeybindParts("g s")).toEqual(["G", "S"]) }) }) diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index fb60e0c77b3b..640f4a7c87bb 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -10,7 +10,15 @@ 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 { chordStrokes, createAppKeymap, IS_MAC, keyFromKeyboardEvent, registerCommandLayers } from "./keymap" +import { + chordStrokes, + createAppKeymap, + IS_MAC, + keyFromKeyboardEvent, + LEADER, + registerAppLeader, + registerCommandLayers, +} from "./keymap" import type { ActiveKey, KeySequencePart } from "@opentui/keymap" export { keyFromKeyboardEvent } @@ -40,6 +48,7 @@ type KeyLabel = | "common.key.pageDown" | "common.key.insert" | "common.key.esc" + | "common.key.leader" function keyText(key: KeyLabel, t?: (key: KeyLabel) => string) { return t ? t(key) : en[key] @@ -293,22 +302,27 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) { /** * The first combo of a keybind as keycap labels. A single stroke gives one label per key (⌘, K); a chord gives one - * label per stroke (⌘K, ⌘C). + * label per stroke (⌘K, ⌘C). `` shows as Leader rather than the key it stands for, which can change. */ export function formatKeybindParts(config: string, t?: (key: KeyLabel) => string): string[] { if (!config || config === "none") return [] const strokes = chordStrokes(config.split(",")[0] ?? "") - if (strokes.length === 1) return displayKeybindParts(parseStroke(strokes[0]!), t) + if (strokes.length === 1 && strokes[0]!.toLowerCase() !== LEADER) + return displayKeybindParts(parseStroke(strokes[0]!), t) - return strokes.map((stroke) => joinParts(displayKeybindParts(parseStroke(stroke), t))) + return strokes.map((stroke) => + stroke.toLowerCase() === LEADER + ? keyText("common.key.leader", t) + : joinParts(displayKeybindParts(parseStroke(stroke), t)), + ) } export function formatKeybind(config: string, t?: (key: KeyLabel) => string): string { const strokes = chordStrokes(config && config !== "none" ? (config.split(",")[0] ?? "") : "") const parts = formatKeybindParts(config, t) - if (strokes.length > 1) return parts.join(" ") + if (strokes.length > 1 || strokes[0]?.toLowerCase() === LEADER) return parts.join(" ") return joinParts(parts) } @@ -346,6 +360,8 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex const [catalog, setCatalog, _, catalogReady] = persisted(Persist.global("command.catalog.v1"), CommandCatalog, {}) + const leader = settings.keymap.leader + const bind = (id: string, def: KeybindConfig | undefined, follows?: string) => { const base = actionId(id) const custom = settings.keybinds.get(base) ?? (follows ? settings.keybinds.get(follows) : undefined) @@ -449,6 +465,14 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex ), ) + createEffect(() => { + const trigger = leader() + + if (!trigger) return + + onCleanup(registerAppLeader(app.keymap, trigger)) + }) + createEffect(() => { const bound = options().filter((option) => !option.id.startsWith(SUGGESTED_PREFIX) && !option.disabled) @@ -461,6 +485,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex ...bound.filter((option) => option.id !== PALETTE_ID), ], (id) => settings.keybinds.get(id) !== undefined, + !!leader(), ), ) }) @@ -536,10 +561,12 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex }, /** The key sequence in progress, and the keys that can continue it. */ pending, - /** Formats one stroke of a pending key sequence. */ - strokeParts(part: Pick) { + /** Formats one stroke of a pending key sequence; the leader shows as Leader, as in shortcut labels. */ + strokeParts(part: Pick) { const stroke = part.stroke + if (part.tokenName === "leader") return [language.t("common.key.leader")] + return displayKeybindParts( { key: stroke.name, ctrl: stroke.ctrl, meta: stroke.super, shift: stroke.shift, alt: stroke.meta }, language.t, diff --git a/packages/app/src/shell/commands/key-sequence.tsx b/packages/app/src/shell/commands/key-sequence.tsx index d30cf5526086..14189c0dd177 100644 --- a/packages/app/src/shell/commands/key-sequence.tsx +++ b/packages/app/src/shell/commands/key-sequence.tsx @@ -5,7 +5,7 @@ import type { ActiveKey } from "@opentui/keymap" import { Keybind } from "@opencode/ui/keybind" import { useCommand } from "@/shell/commands/command" -/** While a chord is in progress, lists the keys that continue it and what each runs. */ +/** While a key sequence such as a leader is in progress, lists the keys that continue it and what each runs. */ export function KeySequenceHint() { const command = useCommand() diff --git a/packages/app/src/shell/commands/keymap.test.ts b/packages/app/src/shell/commands/keymap.test.ts index edfe7d2d0c1b..db6b4de69627 100644 --- a/packages/app/src/shell/commands/keymap.test.ts +++ b/packages/app/src/shell/commands/keymap.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, test } from "bun:test" import type { CommandOption } from "./command" -import { createAppKeymap, registerCommandLayers } from "./keymap" +import { createAppKeymap, registerAppLeader, registerCommandLayers } from "./keymap" const cleanup: (() => void)[] = [] @@ -9,16 +9,24 @@ afterEach(() => { document.body.replaceChildren() }) -function setup(options: CommandOption[], input?: { custom?: string[]; blocked?: () => boolean }) { +function setup(options: CommandOption[], input?: { custom?: string[]; leader?: 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) + const leader = input?.leader ? registerAppLeader(app.keymap, input.leader) : undefined + + const layers = registerCommandLayers( + app.keymap, + options, + (id) => input?.custom?.includes(id) ?? false, + !!input?.leader, + ) cleanup.push(() => { layers() + leader?.() app.destroy() }) @@ -118,6 +126,28 @@ test("a focus target's command wins inside the target and is absent outside it", expect(ran).toEqual(["prompt.stop", "dialog.close"]) }) +test("a leader sequence runs from a text field, and the leader alone types nothing", () => { + const ran: string[] = [] + + const app = setup([command("tab.new", "mod+t, t", ran), command("settings.open", " comma", ran)], { + leader: "ctrl+x", + }) + + const field = editor() + const leader = press(field, { key: "x", ctrlKey: true }) + const next = app.keymap.getActiveKeys().map((key) => String(key.command)) + + expect(app.keymap.getPendingSequence()).toHaveLength(1) + expect(next.sort()).toEqual(["settings.open", "tab.new"]) + press(field, { key: "t" }) + press(field, { key: "x", ctrlKey: true }) + press(field, { key: "," }) + + expect(leader.defaultPrevented).toBe(true) + expect(ran).toEqual(["tab.new", "settings.open"]) + expect(app.keymap.getPendingSequence()).toHaveLength(0) +}) + test("chords run from any focus when their first key has a modifier, and only outside text fields otherwise", () => { const ran: string[] = [] setup([command("comment.toggle", "mod+k mod+c", ran), command("inbox.go", "g i", ran)]) @@ -135,6 +165,21 @@ test("chords run from any focus when their first key has a modifier, and only ou expect(ran).toEqual(["comment.toggle", "inbox.go"]) }) +test.each([ + { name: "without a leader key", keybind: " t", leader: undefined }, + { name: "with the leader after the first key", keybind: "g ", leader: "ctrl+x" }, +])("a leader chord does nothing $name", (row) => { + const ran: string[] = [] + const app = setup([command("tab.new", row.keybind, ran)], { leader: row.leader }) + + press(document.body, { key: "x", ctrlKey: true }) + press(document.body, { key: "g" }) + press(document.body, { key: "t" }) + + expect(ran).toEqual([]) + expect(app.keymap.getPendingSequence()).toHaveLength(0) +}) + test("Escape cancels a pending chord without running a command, and Backspace takes back its last key", () => { const ran: string[] = [] diff --git a/packages/app/src/shell/commands/keymap.ts b/packages/app/src/shell/commands/keymap.ts index c57f9efb89c1..20e9c344f08d 100644 --- a/packages/app/src/shell/commands/keymap.ts +++ b/packages/app/src/shell/commands/keymap.ts @@ -3,6 +3,7 @@ import { registerBackspacePopsPendingSequence, registerDefaultBindingParser, registerEscapeClearsPendingSequence, + registerTimedLeader, } from "@opentui/keymap/addons" import { createHtmlKeymapHost, type HtmlKeymapEvent } from "@opentui/keymap/html" import type { CommandOption } from "./command" @@ -11,9 +12,28 @@ export const IS_MAC = typeof navigator !== "undefined" && /(Mac|iPod|iPhone|iPad export type AppKeymap = Keymap -/** Splits one combo of a keybind into its chord strokes: `mod+k mod+c` into two. */ +/** Stands for the leader key. It may only start a chord: ` g s`. */ +export const LEADER = "" + +const LEADER_TIMEOUT_MS = 2000 + +/** + * Splits one combo of a keybind into its chord strokes: `mod+k mod+c` into two, ` n` into the leader and `n`. + * `n` without a space is accepted too. + */ export function chordStrokes(combo: string) { - return combo.trim().split(/\s+/).filter(Boolean) + return combo + .trim() + .replace(/^(?=\S)/i, `${LEADER} `) + .split(/\s+/) + .filter(Boolean) +} + +/** Whether a combo is a chord the keymap accepts: no empty strokes, and `` only as its first stroke. */ +export function validChord(combo: string) { + const strokes = chordStrokes(combo) + + return strokes.length > 0 && strokes.every((stroke, index) => (stroke.toLowerCase() === LEADER ? index === 0 : true)) } /** @@ -26,10 +46,25 @@ export function createAppKeymap(input: { blocked: () => boolean; editable: (targ // Every binding is written by `keymapKey`: strokes separated by spaces, each a `+`-joined combo. keymap.prependBindingParser((ctx) => { if (ctx.index !== 0) return + const leader = ctx.tokens.get("leader") + + const parts = ctx.input + .trim() + .split(/\s+/) + .map((stroke) => + stroke === LEADER + ? leader + ? ctx.parseObjectKey(leader.stroke, { display: LEADER, match: leader.match, tokenName: "leader" }) + : undefined + : ctx.parseObjectKey(strokeInput(stroke), { display: stroke }), + ) + + if (parts.some((part) => !part)) return { parts: [], nextIndex: ctx.input.length, unknownTokens: ["leader"] } return { - parts: chordStrokes(ctx.input).map((stroke) => ctx.parseObjectKey(strokeInput(stroke), { display: stroke })), + parts: parts.filter((part) => part !== undefined), nextIndex: ctx.input.length, + usedTokens: ctx.input.includes(LEADER) ? ["leader"] : [], } }) registerDefaultBindingParser(keymap) @@ -75,7 +110,12 @@ export function createAppKeymap(input: { blocked: () => boolean; editable: (targ * 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) { +export function registerCommandLayers( + keymap: AppKeymap, + options: CommandOption[], + custom: (id: string) => boolean, + leader: boolean, +) { const layers = new Map() options @@ -109,7 +149,9 @@ export function registerCommandLayers(keymap: AppKeymap, options: CommandOption[ option .keybind!.split(",") .map((combo) => combo.trim()) - .filter((combo) => combo && combo !== "none") + .filter((combo) => combo && combo !== "none" && validChord(combo)) + // Without a leader key the `` chords stay listed but do nothing. + .filter((combo) => leader || chordStrokes(combo)[0]?.toLowerCase() !== LEADER) .map((combo) => { const key = keymapKey(combo) @@ -122,22 +164,28 @@ export function registerCommandLayers(keymap: AppKeymap, options: CommandOption[ return () => disposers.forEach((dispose) => dispose()) } -/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`, `mod+k mod+c`) into the keymap's. */ +export function registerAppLeader(keymap: AppKeymap, trigger: string) { + return registerTimedLeader(keymap, { trigger: keymapKey(trigger), timeoutMs: LEADER_TIMEOUT_MS }) +} + +/** Translates one combo of the app's keybind syntax (`mod+shift+arrowup`, ` g s`) into the keymap's. */ export function keymapKey(combo: string) { return chordStrokes(combo) .map((stroke) => - stroke - .split("+") - .map((part) => { - const lower = part.toLowerCase() + stroke.toLowerCase() === LEADER + ? LEADER + : stroke + .split("+") + .map((part) => { + const lower = part.toLowerCase() - if (lower === "mod") return IS_MAC ? "super" : "ctrl" + if (lower === "mod") return IS_MAC ? "super" : "ctrl" - if (lower === "meta" || lower === "cmd" || lower === "command") return "super" + if (lower === "meta" || lower === "cmd" || lower === "command") return "super" - return MODIFIER_PARTS.has(lower) ? lower : keymapKeyName(lower) - }) - .join("+"), + return MODIFIER_PARTS.has(lower) ? lower : keymapKeyName(lower) + }) + .join("+"), ) .join(" ") } diff --git a/packages/app/test-browser/settings-keybinds.test.ts b/packages/app/test-browser/settings-keybinds.test.ts index e56781362040..de0a8d1cb40e 100644 --- a/packages/app/test-browser/settings-keybinds.test.ts +++ b/packages/app/test-browser/settings-keybinds.test.ts @@ -2,8 +2,14 @@ import { describe, expect, test } from "bun:test" import { createRoot, createSignal } from "solid-js" import { createKeybindSettingsController } from "../src/settings/keybinds/keybinds" -function setup(overrides: Record = {}, plugins?: ReadonlySet, active?: () => boolean) { +function setup( + overrides: Record = {}, + plugins?: ReadonlySet, + active?: () => boolean, + initialLeader?: string, +) { const changes: [string, string][] = [] + const [leader, setLeader] = createSignal(initialLeader) const suppression: boolean[] = [] const notifications: { title: string; description?: string }[] = [] let resets = 0 @@ -17,6 +23,7 @@ function setup(overrides: Record = {}, plugins?: ReadonlySet n" }, { id: "acme.open", plugin: "acme", title: "Open Acme", section: "session" }, ], options: [], @@ -28,6 +35,7 @@ function setup(overrides: Record = {}, plugins?: ReadonlySet plugins), settings: { + keymap: { leader, setLeader }, keybinds: { all: () => overrides, get: (id) => overrides[id], @@ -64,6 +72,7 @@ function setup(overrides: Record = {}, plugins?: ReadonlySet resets, + leader, dispose, } } @@ -145,6 +154,37 @@ describe("keybind settings controller", () => { state.dispose() }) + test("records the leader key, and rejects one that starts another shortcut", () => { + const state = setup() + + state.controller.capture.toggle("keymap.leader") + document.dispatchEvent(modKey("a")) + expect(state.leader()).toBeUndefined() + expect(state.notifications.map((toast) => toast.description)).toEqual([expect.stringContaining("Alpha")]) + + document.dispatchEvent(key("x", { ctrlKey: true })) + expect(state.leader()).toBe(/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "ctrl+x" : "mod+x") + expect(state.controller.capture.active()).toBeNull() + + state.dispose() + }) + + test("a leader chord starts with the leader, and clashes with shortcuts on the leader's key", () => { + const state = setup({}, undefined, undefined, "alt+x") + + expect(state.controller.catalog.keybind("session.next")).toBe("common.key.leader N") + + state.controller.capture.toggle("session.beta") + state.controller.capture.insertLeader() + document.dispatchEvent(key("n")) + expect(state.notifications.map((toast) => toast.description)).toEqual([expect.stringContaining("Next")]) + + document.dispatchEvent(key("m")) + expect(state.changes).toEqual([["session.beta", " m"]]) + + state.dispose() + }) + test("moving the recording between rows keeps shortcuts suspended, and hiding the page resumes them", () => { const [active, setActive] = createSignal(true) const state = setup({}, undefined, active) From 5c3ae7db454c5443189effd37819c8e78911fa5c Mon Sep 17 00:00:00 2001 From: Brendan Allan Date: Tue, 17 Nov 2026 16:32:35 +0800 Subject: [PATCH 4/4] refactor(app): leave composer attach and stop keys to the command keymap --- packages/app/component-tests/composer.spec.ts | 3 +- .../app/src/composer/editor/interaction.ts | 32 ------------------- packages/app/src/composer/model.ts | 2 -- .../app/test-browser/composer-ime.test.ts | 29 +++++++---------- 4 files changed, 13 insertions(+), 53 deletions(-) diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index 974cd7824979..3fb3fde481d1 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/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index 538134d862d1..bc73927b3d94 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -108,10 +108,6 @@ export function createComposerEditor(input: { onQuoteComment?: (item: Extract, comment: string) => void quoteComment?: QuoteCommentController onEditor?: (element: HTMLElement) => void - /** The key attaches files, as the `file.attach` command's keybind. Defaults to Mod+U. */ - attachKey?: (event: KeyboardEvent) => boolean - /** The key stops a running session, as the `prompt.stop` command's keybind. Defaults to Escape and Ctrl+G. */ - stopKey?: (event: KeyboardEvent) => boolean onSuggestionSelect?: (item: ComposerSuggestion) => (() => void) | void view: ComposerEditorView attachments?: ComposerAttachmentConfig @@ -478,19 +474,6 @@ export function createComposerEditor(input: { flushFocus() - // The command keymap attaches first in the app; this covers the editor when it runs on its own, as in a story. - if ( - mode() === "normal" && - (input.attachKey - ? input.attachKey(event) - : (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()) @@ -541,21 +524,6 @@ export function createComposerEditor(input: { return true } - // As with attaching, the `prompt.stop` command stops first in the app. - const stop = - (input.view.submit.working?.() || input.view.submit.held?.()) && - (input.stopKey - ? input.stopKey(event) - : (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 719a8b2ac300..9520c38c73b7 100644 --- a/packages/app/src/composer/model.ts +++ b/packages/app/src/composer/model.ts @@ -464,8 +464,6 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? if (adapter.kind === "active-session") adapter.setEditor(editor) }, - attachKey: (event) => command.matches("file.attach", event), - stopKey: (event) => command.matches("prompt.stop", event), onSuggestionSelect(item) { if (item.kind !== "command") return const selected = slashCommands().find((entry) => entry.id === item.id) diff --git a/packages/app/test-browser/composer-ime.test.ts b/packages/app/test-browser/composer-ime.test.ts index 02c5c3ebbb1c..4cd2c3da8480 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() }