Skip to content

Commit 35d45ac

Browse files
authored
fix(app): match shortcuts on non-Latin keyboard layouts
Fixes anomalyco#55676.
1 parent 81200db commit 35d45ac

4 files changed

Lines changed: 198 additions & 18 deletions

File tree

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Relative command import is deliberate: Storybook aliases @/shell/commands/command to a no-op.
2+
import { DialogProvider } from "@opencode/ui/context/dialog"
3+
import { render } from "solid-js/web"
4+
import { PlatformProvider } from "../src/runtime/platform/platform"
5+
import { LanguageProvider } from "../src/runtime/i18n/language"
6+
import { SettingsProvider, useSettings } from "../src/settings/model"
7+
import { CommandProvider, useCommand } from "../src/shell/commands/command"
8+
9+
export async function mountCommands() {
10+
const element = document.createElement("div")
11+
document.body.append(element)
12+
const selected: string[] = []
13+
let settings: ReturnType<typeof useSettings> | undefined
14+
15+
function Probe() {
16+
const commands = useCommand()
17+
settings = useSettings()
18+
settings.keybinds.set("command.palette", "ctrl+k")
19+
commands.register("layout-fixture", () => [
20+
{ id: "find", title: "Find", keybind: "ctrl+f", onSelect: () => void selected.push("find") },
21+
{ id: "custom", title: "Custom", keybind: "none", onSelect: () => void selected.push("custom") },
22+
{ id: "command.palette", title: "Palette", onSelect: () => void selected.push("palette") },
23+
])
24+
25+
return null
26+
}
27+
28+
const dispose = render(
29+
() => (
30+
<PlatformProvider value={{ platform: "web", openExternal() {}, restart: async () => {}, notify: async () => {} }}>
31+
<LanguageProvider locale="en">
32+
<SettingsProvider>
33+
<DialogProvider>
34+
<CommandProvider>
35+
<Probe />
36+
</CommandProvider>
37+
</DialogProvider>
38+
</SettingsProvider>
39+
</LanguageProvider>
40+
</PlatformProvider>
41+
),
42+
element,
43+
)
44+
45+
await Promise.resolve()
46+
47+
return {
48+
selected,
49+
set(action: string, bind: string) {
50+
settings!.keybinds.set(action, bind)
51+
},
52+
send(input: KeyboardEventInit) {
53+
const event = new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...input })
54+
element.dispatchEvent(event)
55+
56+
return event.defaultPrevented
57+
},
58+
dispose() {
59+
dispose()
60+
element.remove()
61+
},
62+
}
63+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Uses the real CommandProvider, global document listener and Settings keybind overrides.
2+
import { expect, sourceURL, story } from "../../storybook/playwright/story"
3+
4+
const fixture = sourceURL(new URL("./command-keybinds.fixture.tsx", import.meta.url))
5+
6+
story(
7+
"non-Latin fallback dispatches commands and palette while exact custom bindings take priority",
8+
async ({ mount, page }) => {
9+
await mount("ui-line-comment--editor")
10+
11+
const result = await page.evaluate(async (fixture) => {
12+
const { mountCommands } = await import(fixture)
13+
const host = await mountCommands()
14+
15+
try {
16+
const prevented = [host.send({ key: "а", code: "KeyF", ctrlKey: true })]
17+
host.set("custom", "ctrl+а")
18+
prevented.push(host.send({ key: "а", code: "KeyF", ctrlKey: true }))
19+
host.set("custom", "ctrl+л")
20+
prevented.push(host.send({ key: "л", code: "KeyK", ctrlKey: true }))
21+
host.set("custom", "none")
22+
prevented.push(host.send({ key: "л", code: "KeyK", ctrlKey: true }))
23+
host.set("custom", "ctrl+k")
24+
host.set("command.palette", "ctrl+л")
25+
prevented.push(host.send({ key: "л", code: "KeyK", ctrlKey: true }))
26+
27+
return { selected: host.selected, prevented }
28+
} finally {
29+
host.dispose()
30+
}
31+
}, fixture)
32+
33+
expect(result.selected).toEqual(["find", "custom", "custom", "palette", "palette"])
34+
expect(result.prevented).toEqual([true, true, true, true, true])
35+
},
36+
)

‎packages/app/src/shell/commands/command.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,44 @@ describe("command keybinds", () => {
9292
{ config: "mod+alt+[", event: { key: "[", metaKey: true, altKey: true }, match: false },
9393
// macOS Option turns L into ¬; the physical key still matches.
9494
{ config: "meta+alt+l", event: { key: "¬", code: "KeyL", metaKey: true, altKey: true }, match: true },
95+
{ config: "ctrl+f", event: { key: "а", code: "KeyF", ctrlKey: true }, match: true },
96+
{ config: "meta+f", event: { key: "а", code: "KeyF", metaKey: true }, match: true },
97+
{ config: "ctrl+shift+f", event: { key: "А", code: "KeyF", ctrlKey: true, shiftKey: true }, match: true },
98+
{ config: "ctrl+g", event: { key: "γ", code: "KeyG", ctrlKey: true }, match: true },
99+
{ config: "ctrl+e", event: { key: "ק", code: "KeyE", ctrlKey: true }, match: true },
100+
{ config: "ctrl+comma", event: { key: "б", code: "Comma", ctrlKey: true }, match: true },
101+
{ config: "ctrl+.", event: { key: "ю", code: "Period", ctrlKey: true }, match: true },
102+
{ config: "ctrl+;", event: { key: "ж", code: "Semicolon", ctrlKey: true }, match: true },
103+
{ config: "ctrl+'", event: { key: "э", code: "Quote", ctrlKey: true }, match: true },
104+
{ config: "ctrl+[", event: { key: "х", code: "BracketLeft", ctrlKey: true }, match: true },
105+
{ config: "ctrl+]", event: { key: "ъ", code: "BracketRight", ctrlKey: true }, match: true },
106+
{ config: "ctrl+\\", event: { key: "む", code: "Backslash", ctrlKey: true }, match: true },
107+
{ config: "ctrl+/", event: { key: "め", code: "Slash", ctrlKey: true }, match: true },
108+
{ config: "ctrl+`", event: { key: "ё", code: "Backquote", ctrlKey: true }, match: true },
109+
{ config: "ctrl+а", event: { key: "а", code: "KeyF", ctrlKey: true }, match: true },
110+
{ config: "а", event: { key: "а", code: "KeyF" }, match: true },
111+
{ config: "f", event: { key: "а", code: "KeyF" }, match: false },
112+
{ config: "shift+f", event: { key: "А", code: "KeyF", shiftKey: true }, match: false },
113+
{ config: "ctrl+a", event: { key: "a", code: "KeyQ", ctrlKey: true }, match: true },
114+
{ config: "ctrl+q", event: { key: "a", code: "KeyQ", ctrlKey: true }, match: false },
115+
{ config: "ctrl+e", event: { key: "é", code: "KeyE", ctrlKey: true }, match: false },
116+
{ config: "ctrl+f", event: { key: "а", code: "KeyF", metaKey: true }, match: false },
117+
{ config: "ctrl+f", event: { key: "а", code: "KeyF", ctrlKey: true, shiftKey: true }, match: false },
118+
{ config: "ctrl+f", event: { key: "а", code: "KeyF", ctrlKey: true, isComposing: true }, match: false },
119+
{ config: "ctrl+f", event: { key: "Dead", code: "KeyF", ctrlKey: true }, match: false },
120+
{ config: "ctrl+f", event: { key: "Unidentified", code: "KeyF", ctrlKey: true }, match: false },
121+
{ config: "ctrl+alt+[", event: { key: "х", code: "BracketLeft", ctrlKey: true, altKey: true }, match: false },
122+
{
123+
config: "ctrl+[",
124+
event: { key: "х", code: "BracketLeft", ctrlKey: true, modifierAltGraph: true },
125+
match: false,
126+
},
95127
])("matchKeybind $config with $event.key is $match", (row) => {
96-
expect(matchKeybind(parseKeybind(row.config), new KeyboardEvent("keydown", row.event))).toBe(row.match)
128+
const event = new KeyboardEvent("keydown", row.event)
129+
130+
// happy-dom does not implement modifierAltGraph.
131+
if ("modifierAltGraph" in row.event) event.getModifierState = (key) => key === "AltGraph"
132+
expect(matchKeybind(parseKeybind(row.config), event)).toBe(row.match)
97133
})
98134

99135
// IS_MAC is fixed when the module loads, so each assertion accepts either platform's symbols.

‎packages/app/src/shell/commands/command.tsx‎

Lines changed: 62 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { keybindRenames } from "@/settings/keybinds/migration"
1111
import en from "@/runtime/i18n/en"
1212
import { Persist, persisted } from "@/runtime/persistence/storage"
1313

14+
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- navigator is absent during server-side rendering.
1415
const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
1516

1617
const PALETTE_ID = "command.palette"
@@ -66,14 +67,50 @@ export function keyFromKeyboardEvent(event: KeyboardEvent) {
6667
return event.code.slice(3).toLowerCase()
6768
}
6869

70+
function keybindKeysFromKeyboardEvent(event: KeyboardEvent) {
71+
const key = keyFromKeyboardEvent(event)
72+
73+
if (
74+
(!event.ctrlKey && !event.metaKey) ||
75+
event.altKey ||
76+
event.isComposing ||
77+
event.getModifierState("AltGraph") ||
78+
!/^[^\p{ASCII}\p{Script=Latin}]$/u.test(event.key)
79+
)
80+
return [key]
81+
82+
// Keep literal bindings first, then try the physical position on non-Latin layouts.
83+
if (/^Key[A-Z]$/.test(event.code)) return [key, event.code.slice(3).toLowerCase()]
84+
85+
const punctuation = new Map([
86+
["Comma", "comma"],
87+
["Period", "."],
88+
["Semicolon", ";"],
89+
["Quote", "'"],
90+
["BracketLeft", "["],
91+
["BracketRight", "]"],
92+
["Backslash", "\\"],
93+
["Slash", "/"],
94+
["Backquote", "`"],
95+
["Minus", "-"],
96+
["Equal", "="],
97+
])
98+
99+
const physical = punctuation.get(event.code)
100+
101+
return physical ? [key, physical] : [key]
102+
}
103+
69104
function signature(key: string, ctrl: boolean, meta: boolean, shift: boolean, alt: boolean) {
70105
const mask = (ctrl ? 1 : 0) | (meta ? 2 : 0) | (shift ? 4 : 0) | (alt ? 8 : 0)
71106

72107
return `${key}:${mask}`
73108
}
74109

75-
function signatureFromEvent(event: KeyboardEvent) {
76-
return signature(keyFromKeyboardEvent(event), event.ctrlKey, event.metaKey, event.shiftKey, event.altKey)
110+
function signaturesFromEvent(event: KeyboardEvent) {
111+
return keybindKeysFromKeyboardEvent(event).map((key) =>
112+
signature(key, event.ctrlKey, event.metaKey, event.shiftKey, event.altKey),
113+
)
77114
}
78115

79116
export type KeybindConfig = string
@@ -232,10 +269,10 @@ export function parseKeybind(config: string): Keybind[] {
232269
}
233270

234271
export function matchKeybind(keybinds: Keybind[], event: KeyboardEvent): boolean {
235-
const eventKey = keyFromKeyboardEvent(event)
272+
const eventKeys = keybindKeysFromKeyboardEvent(event)
236273

237274
for (const kb of keybinds) {
238-
const keyMatch = kb.key === eventKey
275+
const keyMatch = eventKeys.includes(kb.key)
239276
const ctrlMatch = kb.ctrl === (event.ctrlKey || false)
240277
const metaMatch = kb.meta === (event.metaKey || false)
241278
const shiftMatch = kb.shift === (event.shiftKey || false)
@@ -262,6 +299,7 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) {
262299

263300
if (!kb.key) return parts
264301

302+
// oxlint-disable-next-line anti-slop/no-known-value-widening -- Parsed keybind strings index this display dictionary.
265303
const keys: Record<string, string> = {
266304
arrowup: "↑",
267305
arrowdown: "↓",
@@ -271,6 +309,7 @@ function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) {
271309
plus: "+",
272310
}
273311

312+
// oxlint-disable-next-line anti-slop/no-known-value-widening -- Parsed keybind strings index this display dictionary.
274313
const named: Record<string, KeyLabel> = {
275314
backspace: "common.key.backspace",
276315
delete: "common.key.delete",
@@ -335,6 +374,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
335374
const settings = useSettings()
336375
const language = useLanguage()
337376

377+
// SAFETY: register populates this initially empty list exclusively with CommandRegistration entries.
338378
const [store, setStore] = createStore({
339379
registrations: [] as CommandRegistration[],
340380
suspendCount: 0,
@@ -488,26 +528,29 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
488528
const handleKeyDown = (event: KeyboardEvent) => {
489529
if (suspended() || dialog.active) return
490530

491-
const sig = signatureFromEvent(event)
492-
const isPalette = palette().has(sig)
493-
const option = resolveKeybindOption(keymap().get(sig), event)
494-
const modified = event.ctrlKey || event.metaKey || event.altKey
495-
const isTab = event.key === "Tab"
531+
for (const sig of signaturesFromEvent(event)) {
532+
const isPalette = palette().has(sig)
533+
const option = resolveKeybindOption(keymap().get(sig), event)
534+
const modified = event.ctrlKey || event.metaKey || event.altKey
535+
const isTab = event.key === "Tab"
496536

497-
if (isEditableTarget(event.target) && !isPalette && !option?.editable && !modified && !isTab) return
537+
if (isEditableTarget(event.target) && !isPalette && !option?.editable && !modified && !isTab) return
498538

499-
if (isPalette) {
539+
if (isPalette) {
540+
event.preventDefault()
541+
event.stopPropagation()
542+
showPalette()
543+
544+
return
545+
}
546+
547+
if (!option) continue
500548
event.preventDefault()
501549
event.stopPropagation()
502-
showPalette()
550+
void option.onSelect?.("keybind")
503551

504552
return
505553
}
506-
507-
if (!option) return
508-
event.preventDefault()
509-
event.stopPropagation()
510-
void option.onSelect?.("keybind")
511554
}
512555

513556
onMount(() => {
@@ -517,7 +560,9 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
517560
function register(cb: () => CommandOption[]): void
518561
function register(key: string, cb: () => CommandOption[]): void
519562
function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) {
563+
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Discriminates the public register overloads.
520564
const id = typeof key === "string" ? key : undefined
565+
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Discriminates the public register overloads.
521566
const next = typeof key === "function" ? key : cb
522567

523568
if (!next) return

0 commit comments

Comments
 (0)