settings-keybinds.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import { Component, For, Show, createMemo, onCleanup, onMount } from "solid-js"
  2. import { createStore } from "solid-js/store"
  3. import { makeEventListener } from "@solid-primitives/event-listener"
  4. import { Button } from "@opencode-ai/ui/button"
  5. import { Icon } from "@opencode-ai/ui/icon"
  6. import { IconButton } from "@opencode-ai/ui/icon-button"
  7. import { TextField } from "@opencode-ai/ui/text-field"
  8. import { showToast } from "@opencode-ai/ui/toast"
  9. import fuzzysort from "fuzzysort"
  10. import { formatKeybind, parseKeybind, useCommand } from "@/context/command"
  11. import { useLanguage } from "@/context/language"
  12. import { useSettings } from "@/context/settings"
  13. import { SettingsList } from "./settings-list"
  14. const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
  15. const PALETTE_ID = "command.palette"
  16. const DEFAULT_PALETTE_KEYBIND = "mod+shift+p"
  17. type KeybindGroup = "General" | "Session" | "Navigation" | "Model and agent" | "Terminal" | "Prompt"
  18. type KeybindMeta = {
  19. title: string
  20. group: KeybindGroup
  21. }
  22. type KeybindMap = Record<string, string | undefined>
  23. type CommandContext = ReturnType<typeof useCommand>
  24. const GROUPS: KeybindGroup[] = ["General", "Session", "Navigation", "Model and agent", "Terminal", "Prompt"]
  25. type GroupKey =
  26. | "settings.shortcuts.group.general"
  27. | "settings.shortcuts.group.session"
  28. | "settings.shortcuts.group.navigation"
  29. | "settings.shortcuts.group.modelAndAgent"
  30. | "settings.shortcuts.group.terminal"
  31. | "settings.shortcuts.group.prompt"
  32. const groupKey: Record<KeybindGroup, GroupKey> = {
  33. General: "settings.shortcuts.group.general",
  34. Session: "settings.shortcuts.group.session",
  35. Navigation: "settings.shortcuts.group.navigation",
  36. "Model and agent": "settings.shortcuts.group.modelAndAgent",
  37. Terminal: "settings.shortcuts.group.terminal",
  38. Prompt: "settings.shortcuts.group.prompt",
  39. }
  40. function groupFor(id: string): KeybindGroup {
  41. if (id === PALETTE_ID) return "General"
  42. if (id.startsWith("terminal.")) return "Terminal"
  43. if (id.startsWith("model.") || id.startsWith("agent.") || id.startsWith("mcp.")) return "Model and agent"
  44. if (id.startsWith("file.") || id.startsWith("fileTree.")) return "Navigation"
  45. if (id.startsWith("prompt.")) return "Prompt"
  46. if (
  47. id.startsWith("session.") ||
  48. id.startsWith("message.") ||
  49. id.startsWith("permissions.") ||
  50. id.startsWith("steps.") ||
  51. id.startsWith("review.")
  52. )
  53. return "Session"
  54. return "General"
  55. }
  56. function isModifier(key: string) {
  57. return key === "Shift" || key === "Control" || key === "Alt" || key === "Meta"
  58. }
  59. function normalizeKey(key: string) {
  60. if (key === ",") return "comma"
  61. if (key === "+") return "plus"
  62. if (key === " ") return "space"
  63. return key.toLowerCase()
  64. }
  65. function recordKeybind(event: KeyboardEvent) {
  66. if (isModifier(event.key)) return
  67. const parts: string[] = []
  68. const mod = IS_MAC ? event.metaKey : event.ctrlKey
  69. if (mod) parts.push("mod")
  70. if (IS_MAC && event.ctrlKey) parts.push("ctrl")
  71. if (!IS_MAC && event.metaKey) parts.push("meta")
  72. if (event.altKey) parts.push("alt")
  73. if (event.shiftKey) parts.push("shift")
  74. const key = normalizeKey(event.key)
  75. if (!key) return
  76. parts.push(key)
  77. return parts.join("+")
  78. }
  79. function signatures(config: string | undefined) {
  80. if (!config) return []
  81. const sigs: string[] = []
  82. for (const kb of parseKeybind(config)) {
  83. const parts: string[] = []
  84. if (kb.ctrl) parts.push("ctrl")
  85. if (kb.alt) parts.push("alt")
  86. if (kb.shift) parts.push("shift")
  87. if (kb.meta) parts.push("meta")
  88. if (kb.key) parts.push(kb.key)
  89. if (parts.length === 0) continue
  90. sigs.push(parts.join("+"))
  91. }
  92. return sigs
  93. }
  94. function keybinds(value: unknown): KeybindMap {
  95. if (!value || typeof value !== "object" || Array.isArray(value)) return {}
  96. return value as KeybindMap
  97. }
  98. function listFor(command: CommandContext, map: KeybindMap, palette: string) {
  99. const out = new Map<string, KeybindMeta>()
  100. out.set(PALETTE_ID, { title: palette, group: "General" })
  101. for (const opt of command.catalog) {
  102. if (opt.id.startsWith("suggested.")) continue
  103. out.set(opt.id, { title: opt.title, group: groupFor(opt.id) })
  104. }
  105. for (const opt of command.options) {
  106. if (opt.id.startsWith("suggested.")) continue
  107. out.set(opt.id, { title: opt.title, group: groupFor(opt.id) })
  108. }
  109. for (const [id, value] of Object.entries(map)) {
  110. if (typeof value !== "string") continue
  111. if (out.has(id)) continue
  112. out.set(id, { title: id, group: groupFor(id) })
  113. }
  114. return out
  115. }
  116. function groupedFor(list: Map<string, KeybindMeta>) {
  117. const out = new Map<KeybindGroup, string[]>()
  118. for (const group of GROUPS) out.set(group, [])
  119. for (const [id, item] of list) {
  120. const ids = out.get(item.group)
  121. if (!ids) continue
  122. ids.push(id)
  123. }
  124. for (const group of GROUPS) {
  125. const ids = out.get(group)
  126. if (!ids) continue
  127. ids.sort((a, b) => (list.get(a)?.title ?? "").localeCompare(list.get(b)?.title ?? ""))
  128. }
  129. return out
  130. }
  131. function filteredFor(
  132. query: string,
  133. list: Map<string, KeybindMeta>,
  134. grouped: Map<KeybindGroup, string[]>,
  135. keybind: (id: string) => string,
  136. ) {
  137. const value = query.toLowerCase().trim()
  138. if (!value) return grouped
  139. const out = new Map<KeybindGroup, string[]>()
  140. for (const group of GROUPS) out.set(group, [])
  141. const items = Array.from(list.entries()).map(([id, meta]) => ({
  142. id,
  143. title: meta.title,
  144. group: meta.group,
  145. keybind: keybind(id),
  146. }))
  147. const results = fuzzysort.go(value, items, {
  148. keys: ["title", "keybind"],
  149. threshold: -10000,
  150. })
  151. for (const result of results) {
  152. const ids = out.get(result.obj.group)
  153. if (!ids) continue
  154. ids.push(result.obj.id)
  155. }
  156. return out
  157. }
  158. function useKeyCapture(input: {
  159. active: () => string | null
  160. stop: () => void
  161. set: (id: string, keybind: string) => void
  162. used: () => Map<string, { id: string; title: string }[]>
  163. language: ReturnType<typeof useLanguage>
  164. }) {
  165. onMount(() => {
  166. const handle = (event: KeyboardEvent) => {
  167. const id = input.active()
  168. if (!id) return
  169. event.preventDefault()
  170. event.stopPropagation()
  171. event.stopImmediatePropagation()
  172. if (event.key === "Escape") {
  173. input.stop()
  174. return
  175. }
  176. const clear =
  177. (event.key === "Backspace" || event.key === "Delete") &&
  178. !event.ctrlKey &&
  179. !event.metaKey &&
  180. !event.altKey &&
  181. !event.shiftKey
  182. if (clear) {
  183. input.set(id, "none")
  184. input.stop()
  185. return
  186. }
  187. const next = recordKeybind(event)
  188. if (!next) return
  189. const conflicts = new Map<string, string>()
  190. for (const sig of signatures(next)) {
  191. for (const item of input.used().get(sig) ?? []) {
  192. if (item.id === id) continue
  193. conflicts.set(item.id, item.title)
  194. }
  195. }
  196. if (conflicts.size > 0) {
  197. showToast({
  198. title: input.language.t("settings.shortcuts.conflict.title"),
  199. description: input.language.t("settings.shortcuts.conflict.description", {
  200. keybind: formatKeybind(next, input.language.t),
  201. titles: [...conflicts.values()].join(", "),
  202. }),
  203. })
  204. return
  205. }
  206. input.set(id, next)
  207. input.stop()
  208. }
  209. makeEventListener(document, "keydown", handle, { capture: true })
  210. })
  211. }
  212. export const SettingsKeybinds: Component = () => {
  213. const command = useCommand()
  214. const language = useLanguage()
  215. const settings = useSettings()
  216. const [store, setStore] = createStore({
  217. active: null as string | null,
  218. filter: "",
  219. })
  220. const stop = () => {
  221. if (!store.active) return
  222. setStore("active", null)
  223. command.keybinds(true)
  224. }
  225. const start = (id: string) => {
  226. if (store.active === id) {
  227. stop()
  228. return
  229. }
  230. if (store.active) stop()
  231. setStore("active", id)
  232. command.keybinds(false)
  233. }
  234. const map = createMemo(() => keybinds(settings.current.keybinds))
  235. const hasOverrides = createMemo(() => Object.values(map()).some((x) => typeof x === "string"))
  236. const resetAll = () => {
  237. stop()
  238. settings.keybinds.resetAll()
  239. showToast({
  240. title: language.t("settings.shortcuts.reset.toast.title"),
  241. description: language.t("settings.shortcuts.reset.toast.description"),
  242. })
  243. }
  244. const list = createMemo(() => {
  245. language.locale()
  246. return listFor(command, map(), language.t("command.palette"))
  247. })
  248. const title = (id: string) => list().get(id)?.title ?? ""
  249. const grouped = createMemo(() => groupedFor(list()))
  250. const filtered = createMemo(() => {
  251. return filteredFor(store.filter, list(), grouped(), (id) => command.keybind(id) || "")
  252. })
  253. const hasResults = createMemo(() => {
  254. for (const group of GROUPS) {
  255. const ids = filtered().get(group) ?? []
  256. if (ids.length > 0) return true
  257. }
  258. return false
  259. })
  260. const used = createMemo(() => {
  261. const map = new Map<string, { id: string; title: string }[]>()
  262. const add = (key: string, value: { id: string; title: string }) => {
  263. const list = map.get(key)
  264. if (!list) {
  265. map.set(key, [value])
  266. return
  267. }
  268. list.push(value)
  269. }
  270. const palette = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
  271. for (const sig of signatures(palette)) {
  272. add(sig, { id: PALETTE_ID, title: title(PALETTE_ID) })
  273. }
  274. const valueFor = (id: string) => {
  275. const custom = settings.keybinds.get(id)
  276. if (typeof custom === "string") return custom
  277. const live = command.options.find((x) => x.id === id)
  278. if (live?.keybind) return live.keybind
  279. const meta = command.catalog.find((x) => x.id === id)
  280. return meta?.keybind
  281. }
  282. for (const id of list().keys()) {
  283. if (id === PALETTE_ID) continue
  284. for (const sig of signatures(valueFor(id))) {
  285. add(sig, { id, title: title(id) })
  286. }
  287. }
  288. return map
  289. })
  290. const setKeybind = (id: string, keybind: string) => settings.keybinds.set(id, keybind)
  291. useKeyCapture({
  292. active: () => store.active,
  293. stop,
  294. set: setKeybind,
  295. used,
  296. language,
  297. })
  298. onCleanup(() => {
  299. if (store.active) command.keybinds(true)
  300. })
  301. return (
  302. <div class="flex flex-col h-full overflow-y-auto no-scrollbar px-4 pb-10 sm:px-10 sm:pb-10">
  303. <div class="sticky top-0 z-10 bg-[linear-gradient(to_bottom,var(--surface-stronger-non-alpha)_calc(100%_-_24px),transparent)]">
  304. <div class="flex flex-col gap-4 pt-6 pb-6 max-w-[720px]">
  305. <div class="flex items-center justify-between gap-4">
  306. <h2 class="text-16-medium text-text-strong">{language.t("settings.shortcuts.title")}</h2>
  307. <Button size="small" variant="secondary" onClick={resetAll} disabled={!hasOverrides()}>
  308. {language.t("settings.shortcuts.reset.button")}
  309. </Button>
  310. </div>
  311. <div class="flex items-center gap-2 px-3 h-9 rounded-lg bg-surface-base">
  312. <Icon name="magnifying-glass" class="text-icon-weak-base flex-shrink-0" />
  313. <TextField
  314. variant="ghost"
  315. type="text"
  316. value={store.filter}
  317. onChange={(v) => setStore("filter", v)}
  318. placeholder={language.t("settings.shortcuts.search.placeholder")}
  319. spellcheck={false}
  320. autocorrect="off"
  321. autocomplete="off"
  322. autocapitalize="off"
  323. class="flex-1"
  324. />
  325. <Show when={store.filter}>
  326. <IconButton icon="circle-x" variant="ghost" onClick={() => setStore("filter", "")} />
  327. </Show>
  328. </div>
  329. </div>
  330. </div>
  331. <div class="flex flex-col gap-8 max-w-[720px]">
  332. <For each={GROUPS}>
  333. {(group) => (
  334. <Show when={(filtered().get(group) ?? []).length > 0}>
  335. <div class="flex flex-col gap-1">
  336. <h3 class="text-14-medium text-text-strong pb-2">{language.t(groupKey[group])}</h3>
  337. <SettingsList>
  338. <For each={filtered().get(group) ?? []}>
  339. {(id) => (
  340. <div class="flex items-center justify-between gap-4 py-3 border-b border-border-weak-base last:border-none">
  341. <span class="text-14-regular text-text-strong">{title(id)}</span>
  342. <button
  343. type="button"
  344. data-keybind-id={id}
  345. classList={{
  346. "h-8 px-3 rounded-md text-12-regular": true,
  347. "bg-surface-base text-text-subtle hover:bg-surface-raised-base-hover active:bg-surface-raised-base-active":
  348. store.active !== id,
  349. "border border-border-weak-base bg-surface-inset-base text-text-weak": store.active === id,
  350. }}
  351. onClick={() => start(id)}
  352. >
  353. <Show
  354. when={store.active === id}
  355. fallback={command.keybind(id) || language.t("settings.shortcuts.unassigned")}
  356. >
  357. {language.t("settings.shortcuts.pressKeys")}
  358. </Show>
  359. </button>
  360. </div>
  361. )}
  362. </For>
  363. </SettingsList>
  364. </div>
  365. </Show>
  366. )}
  367. </For>
  368. <Show when={store.filter && !hasResults()}>
  369. <div class="flex flex-col items-center justify-center py-12 text-center">
  370. <span class="text-14-regular text-text-weak">{language.t("settings.shortcuts.search.empty")}</span>
  371. <Show when={store.filter}>
  372. <span class="text-14-regular text-text-strong mt-1">"{store.filter}"</span>
  373. </Show>
  374. </div>
  375. </Show>
  376. </div>
  377. </div>
  378. )
  379. }