| 1 | import type { EditorId, EnvironmentId, ResolvedKeybindingsConfig } from "@t3tools/contracts"; |
| 2 | import { useEffect } from "react"; |
| 3 | |
| 4 | import { usePreferredEditor } from "../../editorPreferences"; |
| 5 | import { isOpenFavoriteEditorShortcut } from "../../keybindings"; |
| 6 | import { shellEnvironment } from "../../state/shell"; |
| 7 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 8 | |
| 9 | export function useOpenFavoriteEditorShortcut({ |
| 10 | enabled, |
| 11 | environmentId, |
| 12 | keybindings, |
| 13 | availableEditors, |
| 14 | openInCwd, |
| 15 | }: { |
| 16 | enabled: boolean; |
| 17 | environmentId: EnvironmentId; |
| 18 | keybindings: ResolvedKeybindingsConfig; |
| 19 | availableEditors: ReadonlyArray<EditorId>; |
| 20 | openInCwd: string | null; |
| 21 | }) { |
| 22 | const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor"); |
| 23 | const [preferredEditor] = usePreferredEditor(availableEditors); |
| 24 | |
| 25 | useEffect(() => { |
| 26 | if (!enabled) return; |
| 27 | const handler = (event: globalThis.KeyboardEvent) => { |
| 28 | if (!isOpenFavoriteEditorShortcut(event, keybindings)) return; |
| 29 | if (!openInCwd || !preferredEditor) return; |
| 30 | |
| 31 | event.preventDefault(); |
| 32 | void openInEditorMutation({ |
| 33 | environmentId, |
| 34 | input: { |
| 35 | cwd: openInCwd, |
| 36 | editor: preferredEditor, |
| 37 | }, |
| 38 | }); |
| 39 | }; |
| 40 | window.addEventListener("keydown", handler); |
| 41 | return () => window.removeEventListener("keydown", handler); |
| 42 | }, [enabled, environmentId, keybindings, openInCwd, openInEditorMutation, preferredEditor]); |
| 43 | } |