settings-keybinds.tsx 14 KB

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