command.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. const DEFAULT_PALETTE_KEYBIND = "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. onSelect?: (source?: "palette" | "keybind" | "slash") => void
  73. onHighlight?: () => (() => void) | void
  74. }
  75. type CommandSource = "palette" | "keybind" | "slash"
  76. export type CommandCatalogItem = {
  77. title: string
  78. description?: string
  79. category?: string
  80. keybind?: KeybindConfig
  81. slash?: string
  82. }
  83. export type CommandRegistration = {
  84. key?: string
  85. options: Accessor<CommandOption[]>
  86. }
  87. export function upsertCommandRegistration(registrations: CommandRegistration[], entry: CommandRegistration) {
  88. if (entry.key === undefined) return [entry, ...registrations]
  89. return [entry, ...registrations.filter((x) => x.key !== entry.key)]
  90. }
  91. export function parseKeybind(config: string): Keybind[] {
  92. if (!config || config === "none") return []
  93. return config.split(",").map((combo) => {
  94. const parts = combo.trim().toLowerCase().split("+")
  95. const keybind: Keybind = {
  96. key: "",
  97. ctrl: false,
  98. meta: false,
  99. shift: false,
  100. alt: false,
  101. }
  102. for (const part of parts) {
  103. switch (part) {
  104. case "ctrl":
  105. case "control":
  106. keybind.ctrl = true
  107. break
  108. case "meta":
  109. case "cmd":
  110. case "command":
  111. keybind.meta = true
  112. break
  113. case "mod":
  114. if (IS_MAC) keybind.meta = true
  115. else keybind.ctrl = true
  116. break
  117. case "alt":
  118. case "option":
  119. keybind.alt = true
  120. break
  121. case "shift":
  122. keybind.shift = true
  123. break
  124. default:
  125. keybind.key = part
  126. break
  127. }
  128. }
  129. return keybind
  130. })
  131. }
  132. export function matchKeybind(keybinds: Keybind[], event: KeyboardEvent): boolean {
  133. const eventKey = normalizeKey(event.key)
  134. for (const kb of keybinds) {
  135. const keyMatch = kb.key === eventKey
  136. const ctrlMatch = kb.ctrl === (event.ctrlKey || false)
  137. const metaMatch = kb.meta === (event.metaKey || false)
  138. const shiftMatch = kb.shift === (event.shiftKey || false)
  139. const altMatch = kb.alt === (event.altKey || false)
  140. if (keyMatch && ctrlMatch && metaMatch && shiftMatch && altMatch) {
  141. return true
  142. }
  143. }
  144. return false
  145. }
  146. export function formatKeybind(config: string, t?: (key: KeyLabel) => string): string {
  147. if (!config || config === "none") return ""
  148. const keybinds = parseKeybind(config)
  149. if (keybinds.length === 0) return ""
  150. const kb = keybinds[0]
  151. const parts: string[] = []
  152. if (kb.ctrl) parts.push(IS_MAC ? "⌃" : keyText("common.key.ctrl", t))
  153. if (kb.alt) parts.push(IS_MAC ? "⌥" : keyText("common.key.alt", t))
  154. if (kb.shift) parts.push(IS_MAC ? "⇧" : keyText("common.key.shift", t))
  155. if (kb.meta) parts.push(IS_MAC ? "⌘" : keyText("common.key.meta", t))
  156. if (kb.key) {
  157. const keys: Record<string, string> = {
  158. arrowup: "↑",
  159. arrowdown: "↓",
  160. arrowleft: "←",
  161. arrowright: "→",
  162. comma: ",",
  163. plus: "+",
  164. }
  165. const named: Record<string, KeyLabel> = {
  166. backspace: "common.key.backspace",
  167. delete: "common.key.delete",
  168. end: "common.key.end",
  169. enter: "common.key.enter",
  170. esc: "common.key.esc",
  171. escape: "common.key.esc",
  172. home: "common.key.home",
  173. insert: "common.key.insert",
  174. pagedown: "common.key.pageDown",
  175. pageup: "common.key.pageUp",
  176. space: "common.key.space",
  177. tab: "common.key.tab",
  178. }
  179. const key = kb.key.toLowerCase()
  180. const displayKey =
  181. keys[key] ??
  182. (named[key]
  183. ? keyText(named[key], t)
  184. : key.length === 1
  185. ? key.toUpperCase()
  186. : key.charAt(0).toUpperCase() + key.slice(1))
  187. parts.push(displayKey)
  188. }
  189. return IS_MAC ? parts.join("") : parts.join("+")
  190. }
  191. function isEditableTarget(target: EventTarget | null) {
  192. if (!(target instanceof HTMLElement)) return false
  193. if (target.isContentEditable) return true
  194. if (target.closest("[contenteditable='true']")) return true
  195. if (target.closest("input, textarea, select")) return true
  196. return false
  197. }
  198. export const { use: useCommand, provider: CommandProvider } = createSimpleContext({
  199. name: "Command",
  200. init: () => {
  201. const dialog = useDialog()
  202. const settings = useSettings()
  203. const language = useLanguage()
  204. const [store, setStore] = createStore({
  205. registrations: [] as CommandRegistration[],
  206. suspendCount: 0,
  207. })
  208. const warnedDuplicates = new Set<string>()
  209. type CommandCatalog = Record<string, CommandCatalogItem>
  210. const [catalog, setCatalog, _, catalogReady] = persisted(
  211. Persist.global("command.catalog.v1"),
  212. createStore<CommandCatalog>({}),
  213. )
  214. const bind = (id: string, def: KeybindConfig | undefined) => {
  215. const custom = settings.keybinds.get(actionId(id))
  216. const config = custom ?? def
  217. if (!config || config === "none") return
  218. return config
  219. }
  220. const registered = createMemo(() => {
  221. const seen = new Set<string>()
  222. const all: CommandOption[] = []
  223. for (const reg of store.registrations) {
  224. for (const opt of reg.options()) {
  225. if (seen.has(opt.id)) {
  226. if (import.meta.env.DEV && !warnedDuplicates.has(opt.id)) {
  227. warnedDuplicates.add(opt.id)
  228. console.warn(`[command] duplicate command id "${opt.id}" registered; keeping first entry`)
  229. }
  230. continue
  231. }
  232. seen.add(opt.id)
  233. all.push(opt)
  234. }
  235. }
  236. return all
  237. })
  238. createEffect(() => {
  239. if (!catalogReady()) return
  240. setCatalog(
  241. registered().reduce((acc, opt) => {
  242. const id = actionId(opt.id)
  243. acc[id] = {
  244. title: opt.title,
  245. description: opt.description,
  246. category: opt.category,
  247. keybind: opt.keybind,
  248. slash: opt.slash,
  249. }
  250. return acc
  251. }, {} as CommandCatalog),
  252. )
  253. })
  254. const catalogOptions = createMemo(() => Object.entries(catalog).map(([id, meta]) => ({ id, ...meta })))
  255. const options = createMemo(() => {
  256. const resolved = registered().map((opt) => ({
  257. ...opt,
  258. keybind: bind(opt.id, opt.keybind),
  259. }))
  260. const suggested = resolved.filter((x) => x.suggested && !x.disabled)
  261. return [
  262. ...suggested.map((x) => ({
  263. ...x,
  264. id: SUGGESTED_PREFIX + x.id,
  265. category: language.t("command.category.suggested"),
  266. })),
  267. ...resolved,
  268. ]
  269. })
  270. const suspended = () => store.suspendCount > 0
  271. const palette = createMemo(() => {
  272. const config = settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND
  273. const keybinds = parseKeybind(config)
  274. return new Set(keybinds.map((kb) => signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt)))
  275. })
  276. const keymap = createMemo(() => {
  277. const map = new Map<string, CommandOption>()
  278. for (const option of options()) {
  279. if (option.id.startsWith(SUGGESTED_PREFIX)) continue
  280. if (option.disabled) continue
  281. if (!option.keybind) continue
  282. const keybinds = parseKeybind(option.keybind)
  283. for (const kb of keybinds) {
  284. if (!kb.key) continue
  285. const sig = signature(kb.key, kb.ctrl, kb.meta, kb.shift, kb.alt)
  286. if (map.has(sig)) continue
  287. map.set(sig, option)
  288. }
  289. }
  290. return map
  291. })
  292. const optionMap = createMemo(() => {
  293. const map = new Map<string, CommandOption>()
  294. for (const option of options()) {
  295. map.set(option.id, option)
  296. map.set(actionId(option.id), option)
  297. }
  298. return map
  299. })
  300. const run = (id: string, source?: CommandSource) => {
  301. const option = optionMap().get(id)
  302. option?.onSelect?.(source)
  303. }
  304. const showPalette = () => {
  305. run("file.open", "palette")
  306. }
  307. const handleKeyDown = (event: KeyboardEvent) => {
  308. if (suspended() || dialog.active) return
  309. const sig = signatureFromEvent(event)
  310. const isPalette = palette().has(sig)
  311. const option = keymap().get(sig)
  312. const modified = event.ctrlKey || event.metaKey || event.altKey
  313. const isTab = event.key === "Tab"
  314. if (isEditableTarget(event.target) && !isPalette && !isAllowedEditableKeybind(option?.id) && !modified && !isTab)
  315. return
  316. if (isPalette) {
  317. event.preventDefault()
  318. showPalette()
  319. return
  320. }
  321. if (!option) return
  322. event.preventDefault()
  323. option.onSelect?.("keybind")
  324. }
  325. onMount(() => {
  326. makeEventListener(document, "keydown", handleKeyDown)
  327. })
  328. function register(cb: () => CommandOption[]): void
  329. function register(key: string, cb: () => CommandOption[]): void
  330. function register(key: string | (() => CommandOption[]), cb?: () => CommandOption[]) {
  331. const id = typeof key === "string" ? key : undefined
  332. const next = typeof key === "function" ? key : cb
  333. if (!next) return
  334. const options = createMemo(next)
  335. const entry: CommandRegistration = {
  336. key: id,
  337. options,
  338. }
  339. setStore("registrations", (arr) => upsertCommandRegistration(arr, entry))
  340. onCleanup(() => {
  341. setStore("registrations", (arr) => arr.filter((x) => x !== entry))
  342. })
  343. }
  344. return {
  345. register,
  346. trigger(id: string, source?: CommandSource) {
  347. run(id, source)
  348. },
  349. keybind(id: string) {
  350. if (id === PALETTE_ID) {
  351. return formatKeybind(settings.keybinds.get(PALETTE_ID) ?? DEFAULT_PALETTE_KEYBIND, language.t)
  352. }
  353. const base = actionId(id)
  354. const option = options().find((x) => actionId(x.id) === base)
  355. if (option?.keybind) return formatKeybind(option.keybind, language.t)
  356. const meta = catalog[base]
  357. const config = bind(base, meta?.keybind)
  358. if (!config) return ""
  359. return formatKeybind(config, language.t)
  360. },
  361. show: showPalette,
  362. keybinds(enabled: boolean) {
  363. setStore("suspendCount", (count) => Math.max(0, count + (enabled ? -1 : 1)))
  364. },
  365. suspended,
  366. get catalog() {
  367. return catalogOptions()
  368. },
  369. get options() {
  370. return options()
  371. },
  372. }
  373. },
  374. })