()
| 22 | } |
| 23 | |
| 24 | function init() { |
| 25 | const [registrations, setRegistrations] = createSignal<Accessor<CommandOption[]>[]>([]) |
| 26 | const [suspendCount, setSuspendCount] = createSignal(0) |
| 27 | const dialog = useDialog() |
| 28 | const keybind = useKeybind() |
| 29 | const options = createMemo(() => { |
| 30 | const all = registrations().flatMap((x) => x()) |
| 31 | const suggested = all.filter((x) => x.suggested) |
| 32 | return [ |
| 33 | ...suggested.map((x) => ({ |
| 34 | ...x, |
| 35 | category: "Suggested", |
| 36 | value: "suggested." + x.value, |
| 37 | })), |
| 38 | ...all, |
| 39 | ].map((x) => ({ |
| 40 | ...x, |
| 41 | footer: x.keybind ? keybind.print(x.keybind) : undefined, |
| 42 | })) |
| 43 | }) |
| 44 | const suspended = () => suspendCount() > 0 |
| 45 | |
| 46 | useKeyboard((evt) => { |
| 47 | if (suspended()) return |
| 48 | if (dialog.stack.length > 0) return |
| 49 | if (evt.defaultPrevented) return |
| 50 | for (const option of options()) { |
| 51 | if (option.keybind && keybind.match(option.keybind, evt)) { |
| 52 | evt.preventDefault() |
| 53 | option.onSelect?.(dialog) |
| 54 | return |
| 55 | } |
| 56 | } |
| 57 | }) |
| 58 | |
| 59 | const result = { |
| 60 | trigger(name: string, source?: "prompt") { |
| 61 | for (const option of options()) { |
| 62 | if (option.value === name) { |
| 63 | option.onSelect?.(dialog, source) |
| 64 | return |
| 65 | } |
| 66 | } |
| 67 | }, |
| 68 | keybinds(enabled: boolean) { |
| 69 | setSuspendCount((count) => count + (enabled ? -1 : 1)) |
| 70 | }, |
| 71 | suspended, |
| 72 | show() { |
| 73 | dialog.replace(() => <DialogCommand options={options()} />) |
| 74 | }, |
| 75 | register(cb: () => CommandOption[]) { |
| 76 | const results = createMemo(cb) |
| 77 | setRegistrations((arr) => [results, ...arr]) |
| 78 | onCleanup(() => { |
| 79 | setRegistrations((arr) => arr.filter((x) => x !== results)) |
| 80 | }) |
| 81 | }, |
no test coverage detected