summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/context/command.tsx
blob: efd83bec8613c6ace47bd8b42676dde213124b8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import { createMemo, createSignal, onCleanup, onMount, Show, type Accessor } from "solid-js"
import { createSimpleContext } from "@opencode-ai/ui/context"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { Dialog } from "@opencode-ai/ui/dialog"
import { List } from "@opencode-ai/ui/list"

const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)

export type KeybindConfig = string

export interface Keybind {
  key: string
  ctrl: boolean
  meta: boolean
  shift: boolean
  alt: boolean
}

export interface CommandOption {
  id: string
  title: string
  description?: string
  category?: string
  keybind?: KeybindConfig
  slash?: string
  suggested?: boolean
  disabled?: boolean
  onSelect?: (source?: "palette" | "keybind" | "slash") => void
  onHighlight?: () => (() => void) | void
}

export function parseKeybind(config: string): Keybind[] {
  if (!config || config === "none") return []

  return config.split(",").map((combo) => {
    const parts = combo.trim().toLowerCase().split("+")
    const keybind: Keybind = {
      key: "",
      ctrl: false,
      meta: false,
      shift: false,
      alt: false,
    }

    for (const part of parts) {
      switch (part) {
        case "ctrl":
        case "control":
          keybind.ctrl = true
          break
        case "meta":
        case "cmd":
        case "command":
          keybind.meta = true
          break
        case "mod":
          if (IS_MAC) keybind.meta = true
          else keybind.ctrl = true
          break
        case "alt":
        case "option":
          keybind.alt = true
          break
        case "shift":
          keybind.shift = true
          break
        default:
          keybind.key = part
          break
      }
    }

    return keybind
  })
}

export function matchKeybind(keybinds: Keybind[], event: KeyboardEvent): boolean {
  const eventKey = event.key.toLowerCase()

  for (const kb of keybinds) {
    const keyMatch = kb.key === eventKey
    const ctrlMatch = kb.ctrl === (event.ctrlKey || false)
    const metaMatch = kb.meta === (event.metaKey || false)
    const shiftMatch = kb.shift === (event.shiftKey || false)
    const altMatch = kb.alt === (event.altKey || false)

    if (keyMatch && ctrlMatch && metaMatch && shiftMatch && altMatch) {
      return true
    }
  }

  return false
}

export function formatKeybind(config: string): string {
  if (!config || config === "none") return ""

  const keybinds = parseKeybind(config)
  if (keybinds.length === 0) return ""

  const kb = keybinds[0]
  const parts: string[] = []

  if (kb.ctrl) parts.push(IS_MAC ? "⌃" : "Ctrl")
  if (kb.alt) parts.push(IS_MAC ? "⌥" : "Alt")
  if (kb.shift) parts.push(IS_MAC ? "⇧" : "Shift")
  if (kb.meta) parts.push(IS_MAC ? "⌘" : "Meta")

  if (kb.key) {
    const displayKey = kb.key.length === 1 ? kb.key.toUpperCase() : kb.key.charAt(0).toUpperCase() + kb.key.slice(1)
    parts.push(displayKey)
  }

  return IS_MAC ? parts.join("") : parts.join("+")
}

function DialogCommand(props: { options: CommandOption[] }) {
  const dialog = useDialog()
  let cleanup: (() => void) | void
  let committed = false

  const handleMove = (option: CommandOption | undefined) => {
    cleanup?.()
    cleanup = option?.onHighlight?.()
  }

  const handleSelect = (option: CommandOption | undefined) => {
    if (option) {
      committed = true
      cleanup = undefined
      dialog.close()
      option.onSelect?.("palette")
    }
  }

  onCleanup(() => {
    if (!committed) {
      cleanup?.()
    }
  })

  return (
    <Dialog title="Commands">
      <List
        search={{ placeholder: "Search commands", autofocus: true }}
        emptyMessage="No commands found"
        items={() => props.options.filter((x) => !x.id.startsWith("suggested.") || !x.disabled)}
        key={(x) => x?.id}
        filterKeys={["title", "description", "category"]}
        groupBy={(x) => x.category ?? ""}
        onMove={handleMove}
        onSelect={handleSelect}
      >
        {(option) => (
          <div class="w-full flex items-center justify-between gap-4">
            <div class="flex items-center gap-2 min-w-0">
              <span class="text-14-regular text-text-strong whitespace-nowrap">{option.title}</span>
              <Show when={option.description}>
                <span class="text-14-regular text-text-weak truncate">{option.description}</span>
              </Show>
            </div>
            <Show when={option.keybind}>
              <span class="text-12-regular text-text-subtle shrink-0">{formatKeybind(option.keybind!)}</span>
            </Show>
          </div>
        )}
      </List>
    </Dialog>
  )
}

export const { use: useCommand, provider: CommandProvider } = createSimpleContext({
  name: "Command",
  init: () => {
    const [registrations, setRegistrations] = createSignal<Accessor<CommandOption[]>[]>([])
    const [suspendCount, setSuspendCount] = createSignal(0)
    const dialog = useDialog()

    const options = createMemo(() => {
      const all = registrations().flatMap((x) => x())
      const suggested = all.filter((x) => x.suggested && !x.disabled)
      return [
        ...suggested.map((x) => ({
          ...x,
          id: "suggested." + x.id,
          category: "Suggested",
        })),
        ...all,
      ]
    })

    const suspended = () => suspendCount() > 0

    const showPalette = () => {
      if (!dialog.active) {
        dialog.show(() => <DialogCommand options={options().filter((x) => !x.disabled)} />)
      }
    }

    const handleKeyDown = (event: KeyboardEvent) => {
      if (suspended()) return

      const paletteKeybinds = parseKeybind("mod+shift+p")
      if (matchKeybind(paletteKeybinds, event)) {
        event.preventDefault()
        showPalette()
        return
      }

      for (const option of options()) {
        if (option.disabled) continue
        if (!option.keybind) continue

        const keybinds = parseKeybind(option.keybind)
        if (matchKeybind(keybinds, event)) {
          event.preventDefault()
          option.onSelect?.("keybind")
          return
        }
      }
    }

    onMount(() => {
      document.addEventListener("keydown", handleKeyDown)
    })

    onCleanup(() => {
      document.removeEventListener("keydown", handleKeyDown)
    })

    return {
      register(cb: () => CommandOption[]) {
        const results = createMemo(cb)
        setRegistrations((arr) => [results, ...arr])
        onCleanup(() => {
          setRegistrations((arr) => arr.filter((x) => x !== results))
        })
      },
      trigger(id: string, source?: "palette" | "keybind" | "slash") {
        for (const option of options()) {
          if (option.id === id || option.id === "suggested." + id) {
            option.onSelect?.(source)
            return
          }
        }
      },
      keybind(id: string) {
        const option = options().find((x) => x.id === id || x.id === "suggested." + id)
        if (!option?.keybind) return ""
        return formatKeybind(option.keybind)
      },
      show: showPalette,
      keybinds(enabled: boolean) {
        setSuspendCount((count) => count + (enabled ? -1 : 1))
      },
      suspended,
      get options() {
        return options()
      },
    }
  },
})