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

editorPreferences.ts

43 lines2.0 KB

1import { EDITORS, EditorId, LocalApi } from "@workbench/contracts";
2import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
3import { useMemo } from "react";
4​
5const LAST_EDITOR_KEY = "workbench:last-editor";
6// back-compat read for migration; remove in next major.
7const LEGACY_LAST_EDITOR_KEY = "t3code:last-editor";
8​
9export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {
10 const [lastEditor, setLastEditor] = useLocalStorage(LAST_EDITOR_KEY, null, EditorId);
11 // back-compat read for migration; remove in next major.
12 const legacyLastEditor = useLocalStorage(LEGACY_LAST_EDITOR_KEY, null, EditorId)[0];
13​
14 const effectiveEditor = useMemo(() => {
15 const candidate = lastEditor ?? legacyLastEditor;
16 if (candidate && availableEditors.includes(candidate)) return candidate;
17 return EDITORS.find((editor) => availableEditors.includes(editor.id))?.id ?? null;
18 }, [lastEditor, legacyLastEditor, availableEditors]);
19​
20 return [effectiveEditor, setLastEditor] as const;
22​
23export function resolveAndPersistPreferredEditor(
24 availableEditors: readonly EditorId[],
25): EditorId | null {
26 const availableEditorIds = new Set(availableEditors);
27 const stored =
28 getLocalStorageItem(LAST_EDITOR_KEY, EditorId) ??
29 // back-compat read for migration; remove in next major.
30 getLocalStorageItem(LEGACY_LAST_EDITOR_KEY, EditorId);
31 if (stored && availableEditorIds.has(stored)) return stored;
32 const editor = EDITORS.find((editor) => availableEditorIds.has(editor.id))?.id ?? null;
33 if (editor) setLocalStorageItem(LAST_EDITOR_KEY, editor, EditorId);
34 return editor ?? null;
36​
37export async function openInPreferredEditor(api: LocalApi, targetPath: string): Promise<EditorId> {
38 const { availableEditors } = await api.server.getConfig();
39 const editor = resolveAndPersistPreferredEditor(availableEditors);
40 if (!editor) throw new Error("No available editors found.");
41 await api.shell.openInEditor(targetPath, editor);
42 return editor;