command.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import { createSimpleContext } from "@opencode-ai/ui/context"
  2. import { useDialog } from "@opencode-ai/ui/context/dialog"
  3. import { type Accessor, createEffect, createMemo, onCleanup, onMount } from "solid-js"
  4. import { createStore } from "solid-js/store"
  5. import { makeEventListener } from "@solid-primitives/event-listener"
  6. import { useLanguage } from "@/context/language"
  7. import { useSettings } from "@/context/settings"
  8. import { dict as en } from "@/i18n/en"
  9. import { Persist, persisted } from "@/utils/persist"
  10. const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
  11. const PALETTE_ID = "command.palette"
  12. export const DEFAULT_PALETTE_KEYBIND = "mod+k,mod+shift+p"
  13. const SUGGESTED_PREFIX = "suggested."
  14. const EDITABLE_KEYBIND_IDS = new Set(["terminal.toggle", "terminal.new", "file.attach"])
  15. type KeyLabel =
  16. | "common.key.ctrl"
  17. | "common.key.alt"
  18. | "common.key.shift"
  19. | "common.key.meta"
  20. | "common.key.space"
  21. | "common.key.backspace"
  22. | "common.key.enter"
  23. | "common.key.tab"
  24. | "common.key.delete"
  25. | "common.key.home"
  26. | "common.key.end"
  27. | "common.key.pageUp"
  28. | "common.key.pageDown"
  29. | "common.key.insert"
  30. | "common.key.esc"
  31. function keyText(key: KeyLabel, t?: (key: KeyLabel) => string) {
  32. return t ? t(key) : en[key]
  33. }
  34. function actionId(id: string) {
  35. if (!id.startsWith(SUGGESTED_PREFIX)) return id
  36. return id.slice(SUGGESTED_PREFIX.length)
  37. }
  38. function normalizeKey(key: string) {
  39. if (key === ",") return "comma"
  40. if (key === "+") return "plus"
  41. if (key === " ") return "space"
  42. return key.toLowerCase()
  43. }
  44. function signature(key: string, ctrl: boolean, meta: boolean, shift: boolean, alt: boolean) {
  45. const mask = (ctrl ? 1 : 0) | (meta ? 2 : 0) | (shift ? 4 : 0) | (alt ? 8 : 0)
  46. return `${key}:${mask}`
  47. }
  48. function signatureFromEvent(event: KeyboardEvent) {
  49. return signature(normalizeKey(event.key), event.ctrlKey, event.metaKey, event.shiftKey, event.altKey)
  50. }
  51. function isAllowedEditableKeybind(id: string | undefined) {
  52. if (!id) return false
  53. return EDITABLE_KEYBIND_IDS.has(actionId(id))
  54. }
  55. export type KeybindConfig = string
  56. export interface Keybind {
  57. key: string
  58. ctrl: boolean
  59. meta: boolean
  60. shift: boolean
  61. alt: boolean
  62. }
  63. export interface CommandOption {
  64. id: string
  65. title: string
  66. description?: string
  67. category?: string
  68. keybind?: KeybindConfig
  69. slash?: string
  70. suggested?: boolean
  71. disabled?: boolean
  72. hidden?: boolean
  73. when?: (event: KeyboardEvent) => boolean
  74. onSelect?: (source?: "palette" | "keybind" | "slash") => void
  75. onHighlight?: () => (() => void) | void
  76. }
  77. export function commandPaletteOptions(options: CommandOption[]) {
  78. return options.filter(
  79. (option) =>
  80. !option.disabled && !option.hidden && !option.id.startsWith(SUGGESTED_PREFIX) && option.id !== "file.open",
  81. )
  82. }
  83. export function resolveKeybindOption(candidates: CommandOption[] | undefined, event: KeyboardEvent) {
  84. return candidates?.find((option) => option.when?.(event)) ?? candidates?.find((option) => !option.when)
  85. }
  86. type CommandSource = "palette" | "keybind" | "slash"
  87. export type CommandCatalogItem = {
  88. title: string
  89. description?: string
  90. category?: string
  91. keybind?: KeybindConfig
  92. slash?: string
  93. hidden?: boolean
  94. }
  95. export type CommandRegistration = {
  96. key?: string
  97. options: Accessor<CommandOption[]>
  98. }
  99. export function addCommandRegistration(registrations: CommandRegistration[], entry: CommandRegistration) {
  100. return [entry, ...registrations]
  101. }
  102. export function activeCommandRegistrations(registrations: CommandRegistration[]) {
  103. const keys = new Set<string>()
  104. return registrations.filter((entry) => {
  105. if (entry.key === undefined) return true
  106. if (keys.has(entry.key)) return false
  107. keys.add(entry.key)
  108. return true
  109. })
  110. }
  111. export function parseKeybind(config: string): Keybind[] {
  112. if (!config || config === "none") return []
  113. return config.split(",").map((combo) => {
  114. const parts = combo.trim().toLowerCase().split("+")
  115. const keybind: Keybind = {
  116. key: "",
  117. ctrl: false,
  118. meta: false,
  119. shift: false,
  120. alt: false,
  121. }
  122. for (const part of parts) {
  123. switch (part) {
  124. case "ctrl":
  125. case "control":
  126. keybind.ctrl = true
  127. break
  128. case "meta":
  129. case "cmd":
  130. case "command":
  131. keybind.meta = true
  132. break
  133. case "mod":
  134. if (IS_MAC) keybind.meta = true
  135. else keybind.ctrl = true
  136. break
  137. case "alt":
  138. case "option":
  139. keybind.alt = true
  140. break
  141. case "shift":
  142. keybind.shift = true
  143. break
  144. default:
  145. keybind.key = part
  146. break
  147. }
  148. }
  149. return keybind
  150. })
  151. }
  152. export function matchKeybind(keybinds: Keybind[], event: KeyboardEvent): boolean {
  153. const eventKey = normalizeKey(event.key)
  154. for (const kb of keybinds) {
  155. const keyMatch = kb.key === eventKey
  156. const ctrlMatch = kb.ctrl === (event.ctrlKey || false)
  157. const metaMatch = kb.meta === (event.metaKey || false)
  158. const shiftMatch = kb.shift === (event.shiftKey || false)
  159. const altMatch = kb.alt === (event.altKey || false)
  160. if (keyMatch && ctrlMatch && metaMatch && shiftMatch && altMatch) {
  161. return true
  162. }
  163. }
  164. return false
  165. }
  166. function displayKeybindParts(kb: Keybind, t?: (key: KeyLabel) => string) {
  167. const parts: string[] = []
  168. if (kb.ctrl) parts.push(IS_MAC ? "⌃" : keyText("common.key.ctrl", t))
  169. if (kb.alt) parts.push(IS_MAC ? "⌥" : keyText("common.key.alt", t))
  170. if (kb.shift) parts.push(IS_MAC ? "⇧" : keyText("common.key.shift", t))
  171. if (kb.meta) parts.push(IS_MAC ? "⌘" : keyText("common.key.meta", t))
  172. if (!kb.key) return parts
  173. const keys: Record<string, string> = {
  174. arrowup: "↑",
  175. arrowdown: "↓",
  176. arrowleft: "←",
  177. arrowright: "→",
  178. comma: ",",
  179. plus: "+",
  180. }
  181. const named: Record<string, KeyLabel> = {
  182. backspace: "common.key.backspace",
  183. delete: "common.key.delete",
  184. end: "common.key.end",
  185. enter: "common.key.enter",
  186. esc: "common.key.esc",
  187. escape: "common.key.esc",
  188. home: "common.key.home",
  189. insert: "common.key.insert",
  190. pagedown: "common.key.pageDown",
  191. pageup: "common.key.pageUp",
  192. space: "common.key.space",
  193. tab: "common.key.tab",
  194. }
  195. const key = kb.key.toLowerCase()
  196. const displayKey =
  197. keys[key] ??
  198. (named[key]
  199. ? keyText(named[key], t)
  200. : key.length === 1
  201. ? key.toUpperCase()
  202. : key.charAt(0).toUpperCase() + key.slice(1))
  203. parts.push(displayKey)
  204. return parts
  205. }
  206. export function formatKeybindParts(config: string, t?: (key: KeyLabel) => string): string[] {
  207. if (!config || config === "none") return []
  208. const keybind = parseKeybind(config)[0]
  209. return keybind ? displayKeybindParts(keybind, t) : []
  210. }
  211. export function formatKeybind(config: string, t?: (key: KeyLabel) => string): string {
  212. const parts = formatKeybindParts(config, t)
  213. if (parts.length === 0) return ""
  214. return IS_MAC ? parts.join("") : parts.join("+")
  215. }
  216. // KeybindV2 takes an array instead of a string
  217. export function formatKeybindKeys(config: string, t?: (key: KeyLabel) => string): string[] {
  218. return formatKeybindParts(config, t)
  219. }
  220. function isEditableTarget(target: EventTarget | null) {
  221. if (!(target instanceof HTMLElement)) return false
  222. if (target.isContentEditable) return true
  223. if (target.closest("[contenteditable='true']")) return true
  224. if (target.closest("input, textarea, select")) return true
  225. return false
  226. }
  227. export const { use: useCommand, provider: CommandProvider } = createSimpleContext({
  228. name: "Command",
  229. init: () => {
  230. const dialog = useDialog()
  231. const settings = useSettings()
  232. const language = useLanguage()
  233. const [store, setStore] = createStore({
  234. registrations: [] as CommandRegistration[],
  235. suspendCount: 0,
  236. })
  237. const warnedDuplicates = new Set<string>()
  238. type CommandCatalog = Record<string, CommandCatalogItem>
  239. const [catalog, setCatalog, _, catalogReady] = persisted(
  240. Persist.global("command.catalog.v1"),
  241. createStore<CommandCatalog>({}),
  242. )
  243. const bind = (id: string, def: KeybindConfig | undefined) => {
  244. const custom = settings.keybinds.get(actionId(id))
  245. const config = custom ?? def
  246. if (!config || config === "none") return
  247. return config
  248. }
  249. const registered = createMemo(() => {
  250. const seen = new Set<string>()
  251. const all: CommandOption[] = []
  252. for (const reg of activeCommandRegistrations(store.registrations)) {
  253. for (const opt of reg.options()) {
  254. if (seen.has(opt.id)) {
  255. if (import.meta.env.DEV && !warnedDuplicates.has(opt.id)) {
  256. warnedDuplicates.add(opt.id)
  257. console.warn(`[command] duplicate command id "${opt.id}" registered; keeping first entry`)
  258. }
  259. continue
  260. }
  261. seen.add(opt.id)
  262. all.push(opt)
  263. }
  264. }
  265. return all
  266. })
  267. createEffect(() => {
  268. if (!catalogReady()) return
  269. setCatalog(
  270. registered().reduce((acc, opt) => {
  271. const id = actionId(opt.id)
  272. if (opt.title)
  273. acc[id] = {
  274. title: opt.title,
  275. description: opt.description,
  276. category: opt.category,
  277. keybind: opt.keybind,
  278. slash: opt.slash,
  279. }
  280. return acc
  281. }, {} as CommandCatalog),
  282. )
  283. })
  284. const catalogOptions = createMemo(() => Object.entries(catalog).map(([id, meta]) => ({ id, ...meta })))
  285. const options = createMemo(() => {
  286. const resolved = registered().map((opt) => ({
  287. ...opt,
  288. keybind: bind(opt.id, opt.keybind),
  289. }))
  290. const suggested = resolved.filter((x) => x.suggested && !x.disabled)
  291. return [
  292. ...suggested.map((x) => ({
  293. ...x,
  294. id: SUGGESTED_PREFIX + x.id,
  295. category: language.t("command.category.suggested"),
  296. })),
  297. ...resolved,
  298. ]
  299. })
  300. const suspended = () => store.suspendCount > 0
  301. const palette = createMemo(() => {
  302. const config = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
  303. const keybinds = parseKeybind(config)
  304. return new Set(keybinds.map((kb) => signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt)))
  305. })
  306. const keymap = createMemo(() => {
  307. const map = new Map<string, CommandOption[]>()
  308. for (const option of options()) {
  309. if (option.id.startsWith(SUGGESTED_PREFIX)) continue
  310. if (option.disabled) continue
  311. if (!option.keybind) continue
  312. const keybinds = parseKeybind(option.keybind)
  313. for (const kb of keybinds) {
  314. if (!kb.key) continue
  315. const sig = signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt)
  316. const existing = map.get(sig)
  317. if (existing) {
  318. existing.push(option)
  319. continue
  320. }
  321. map.set(sig, [option])
  322. }
  323. }
  324. return map
  325. })
  326. const optionMap = createMemo(() => {
  327. const map = new Map<string, CommandOption>()
  328. for (const option of options()) {
  329. map.set(option.id, option)
  330. map.set(actionId(option.id), option)
  331. }
  332. return map
  333. })
  334. const run = (id: string, source?: CommandSource) => {
  335. const option = optionMap().get(id)
  336. option?.onSelect?.(source)
  337. }
  338. const showPalette = () => {
  339. run(PALETTE_ID, "palette")
  340. }
  341. const handleKeyDown = (event: KeyboardEvent) => {
  342. if (suspended() || dialog.active) return
  343. const sig = signatureFromEvent(event)
  344. const isPalette = palette().has(sig)
  345. const option = resolveKeybindOption(keymap().get(sig), event)
  346. const modified = event.ctrlKey || event.metaKey || event.altKey
  347. const isTab = event.key === "Tab"
  348. if (isEditableTarget(event.target) && !isPalette && !isAllowedEditableKeybind(option?.id) && !modified && !isTab)
  349. return
  350. if (isPalette) {
  351. event.preventDefault()
  352. event.stopPropagation()
  353. showPalette()
  354. return
  355. }
  356. if (!option) return
  357. event.preventDefault()
  358. event.stopPropagation()
  359. option.onSelect?.("keybind")
  360. }
  361. onMount(() => {
  362. makeEventListener(document, "keydown", handleKeyDown, { capture: true })
  363. })
  364. function register(cb: () => CommandOption[]): void
  365. function register(key: string, cb: () => CommandOption[]): void
  366. function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) {
  367. const id = typeof key === "string" ? key : undefined
  368. const next = typeof key === "function" ? key : cb
  369. if (!next) return
  370. const options = createMemo(next)
  371. const entry: CommandRegistration = {
  372. key: id,
  373. options,
  374. }
  375. setStore("registrations", (arr) => addCommandRegistration(arr, entry))
  376. onCleanup(() => {
  377. setStore("registrations", (arr) => arr.filter((x) => x !== entry))
  378. })
  379. }
  380. const keybindConfig = (id: string) => {
  381. if (id === PALETTE_ID) return settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
  382. const base = actionId(id)
  383. return options().find((x) => actionId(x.id) === base)?.keybind ?? bind(base, catalog[base]?.keybind)
  384. }
  385. return {
  386. register,
  387. trigger(id: string, source?: CommandSource) {
  388. run(id, source)
  389. },
  390. keybind(id: string) {
  391. const config = keybindConfig(id)
  392. if (!config) return ""
  393. return formatKeybind(config, language.t)
  394. },
  395. keybindParts(id: string) {
  396. const config = keybindConfig(id)
  397. return config ? formatKeybindParts(config, language.t) : []
  398. },
  399. show: showPalette,
  400. keybinds(enabled: boolean) {
  401. setStore("suspendCount", (count) => Math.max(0, count + (enabled ? -1 : 1)))
  402. },
  403. suspended,
  404. get catalog() {
  405. return catalogOptions()
  406. },
  407. get options() {
  408. return options()
  409. },
  410. }
  411. },
  412. })