Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenInPickerShortcut.ts

58 lines1.9 KB

1import type { EditorId, EnvironmentId, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2import { useEffect } from "react";
3​
4import { usePreferredEditor } from "../../editorPreferences";
5import { editorLabelForPlatform } from "../../editorLabels";
6import { isOpenFavoriteEditorShortcut } from "../../keybindings";
7import { announce } from "../../lib/announce";
8import { useRemoteOpenState } from "../../remoteOpen";
9import { shellEnvironment } from "../../state/shell";
10import { useAtomCommand } from "../../state/use-atom-command";
11​
12export function useOpenFavoriteEditorShortcut({
13 enabled,
14 environmentId,
15 keybindings,
16 availableEditors,
17 openInCwd,
18}: {
19 enabled: boolean;
20 environmentId: EnvironmentId;
21 keybindings: ResolvedKeybindingsConfig;
22 availableEditors: ReadonlyArray<EditorId>;
23 openInCwd: string | null;
24}) {
25 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
26 const [preferredEditor] = usePreferredEditor(availableEditors);
27 const remote = useRemoteOpenState(environmentId);
28​
29 useEffect(() => {
30 if (!enabled || remote.mode !== "local-exec") return;
31 const handler = (event: globalThis.KeyboardEvent) => {
32 if (event.defaultPrevented || !isOpenFavoriteEditorShortcut(event, keybindings)) return;
33 if (!openInCwd || !preferredEditor) return;
34​
35 event.preventDefault();
36 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
37 void openInEditorMutation({
38 environmentId,
39 input: {
40 cwd: openInCwd,
41 editor: preferredEditor,
42 },
43 }).then((result) => {
44 if (result._tag === "Success") announce(`Opened in ${label}`);
45 });
46 };
47 window.addEventListener("keydown", handler);
48 return () => window.removeEventListener("keydown", handler);
49 }, [
50 enabled,
51 environmentId,
52 keybindings,
53 openInCwd,
54 openInEditorMutation,
55 preferredEditor,
56 remote.mode,
57 ]);