Files
t3code/apps/web/src/editorPreferences.ts
b96308fc5a Prepare datamodel for multi-environment (#1765)
Co-authored-by: justsomelegs <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-04-09 02:05:20 +00:00

36 lines
1.5 KiB
TypeScript

import { EDITORS, EditorId, LocalApi } from "@t3tools/contracts";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
import { useMemo } from "react";
const LAST_EDITOR_KEY = "t3code:last-editor";
export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {
const [lastEditor, setLastEditor] = useLocalStorage(LAST_EDITOR_KEY, null, EditorId);
const effectiveEditor = useMemo(() => {
if (lastEditor && availableEditors.includes(lastEditor)) return lastEditor;
return EDITORS.find((editor) => availableEditors.includes(editor.id))?.id ?? null;
}, [lastEditor, availableEditors]);
return [effectiveEditor, setLastEditor] as const;
}
export function resolveAndPersistPreferredEditor(
availableEditors: readonly EditorId[],
): EditorId | null {
const availableEditorIds = new Set(availableEditors);
const stored = getLocalStorageItem(LAST_EDITOR_KEY, EditorId);
if (stored && availableEditorIds.has(stored)) return stored;
const editor = EDITORS.find((editor) => availableEditorIds.has(editor.id))?.id ?? null;
if (editor) setLocalStorageItem(LAST_EDITOR_KEY, editor, EditorId);
return editor ?? null;
}
export async function openInPreferredEditor(api: LocalApi, targetPath: string): Promise<EditorId> {
const { availableEditors } = await api.server.getConfig();
const editor = resolveAndPersistPreferredEditor(availableEditors);
if (!editor) throw new Error("No available editors found.");
await api.shell.openInEditor(targetPath, editor);
return editor;
}