Open History to see the last commit
1import { EDITORS, EditorId, LocalApi } from "@t3tools/contracts";
2import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
3import { useMemo } from "react";
4
5const LAST_EDITOR_KEY = "t3code:last-editor";
6
7export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {
8 const [lastEditor, setLastEditor] = useLocalStorage(LAST_EDITOR_KEY, null, EditorId);
9
10 const effectiveEditor = useMemo(() => {
11 if (lastEditor && availableEditors.includes(lastEditor)) return lastEditor;
12 return EDITORS.find((editor) => availableEditors.includes(editor.id))?.id ?? null;
13 }, [lastEditor, availableEditors]);
14
15 return [effectiveEditor, setLastEditor] as const;
16}
17
18export function resolveAndPersistPreferredEditor(
19 availableEditors: readonly EditorId[],
20): EditorId | null {
21 const availableEditorIds = new Set(availableEditors);
22 const stored = getLocalStorageItem(LAST_EDITOR_KEY, EditorId);
23 if (stored && availableEditorIds.has(stored)) return stored;
24 const editor = EDITORS.find((editor) => availableEditorIds.has(editor.id))?.id ?? null;
25 if (editor) setLocalStorageItem(LAST_EDITOR_KEY, editor, EditorId);
26 return editor ?? null;
27}
28
29export async function openInPreferredEditor(api: LocalApi, targetPath: string): Promise<EditorId> {
30 const { availableEditors } = await api.server.getConfig();
31 const editor = resolveAndPersistPreferredEditor(availableEditors);
32 if (!editor) throw new Error("No available editors found.");
33 await api.shell.openInEditor(targetPath, editor);
34 return editor;
35}