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

editorPreferences.ts

140 lines4.3 KB

1import {
2 AuthOrchestrationOperateScope,
3 EDITORS,
4 EditorId,
5 EnvironmentAuthorizationError,
6 EnvironmentId,
7} from "@t3tools/contracts";
8import {
9 mapAtomCommandResult,
10 type AtomCommandFailure,
11 type AtomCommandResult,
12} from "@t3tools/client-runtime/state/runtime";
13import * as Cause from "effect/Cause";
14import * as Schema from "effect/Schema";
15import { AsyncResult } from "effect/reactivity";
16import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
17import { shellEnvironment } from "./state/shell";
18import { useAtomCommand } from "./state/use-atom-command";
19import { readEnvironmentScope } from "./state/session";
20​
21const LAST_EDITOR_KEY = "t3code:last-editor";
22​
23export class PreferredEditorEnvironmentRequiredError extends Schema.TaggedError<PreferredEditorEnvironmentRequiredError>()(
24 "PreferredEditorEnvironmentRequiredError",
25 {
26 targetPath: Schema.String,
27 },
28) {
29 override get message(): string {
30 return `Cannot open ${this.targetPath} because no environment is selected.`;
31 }
33​
34export class PreferredEditorUnavailableError extends Schema.TaggedError<PreferredEditorUnavailableError>()(
35 "PreferredEditorUnavailableError",
36 {
37 environmentId: EnvironmentId,
38 targetPath: Schema.String,
39 availableEditorIds: Schema.Array(EditorId),
40 },
41) {
42 override get message(): string {
43 return `No available editor can open ${this.targetPath} in environment ${this.environmentId}.`;
44 }
46​
47export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {
48 const [lastEditor, setLastEditor] = useLocalStorage(LAST_EDITOR_KEY, null, EditorId);
49​
50 const effectiveEditor =
51 lastEditor && availableEditors.includes(lastEditor)
52 ? lastEditor
53 : (EDITORS.find((editor) => availableEditors.includes(editor.id))?.id ?? null);
54​
55 return [effectiveEditor, setLastEditor] as const;
57​
58function resolveAndPersistPreferredEditor(availableEditors: readonly EditorId[]): EditorId | null {
59 const availableEditorIds = new Set(availableEditors);
60 let stored: EditorId | null = null;
61 try {
62 stored = getLocalStorageItem(LAST_EDITOR_KEY, EditorId);
63 } catch (error) {
64 console.warn("Could not read the preferred editor.", error);
65 }
66 if (stored && availableEditorIds.has(stored)) return stored;
67 const editor = EDITORS.find((editor) => availableEditorIds.has(editor.id))?.id ?? null;
68 if (editor) {
69 try {
70 setLocalStorageItem(LAST_EDITOR_KEY, editor, EditorId);
71 } catch (error) {
72 console.warn("Could not save the preferred editor.", error);
73 }
74 }
75 return editor ?? null;
77​
78export function useOpenInPreferredEditor(
79 environmentId: EnvironmentId | null,
80 availableEditors: readonly EditorId[],
81 projectRoot?: string,
82) {
83 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
84 reportFailure: false,
85 });
86 type OpenInEditorError = AtomCommandFailure<Awaited<ReturnType<typeof openInEditor>>>;
87​
88 return async (
89 targetPath: string,
90 ): Promise<
91 AtomCommandResult<
92 EditorId,
93 | OpenInEditorError
94 | PreferredEditorEnvironmentRequiredError
95 | PreferredEditorUnavailableError
96 | EnvironmentAuthorizationError
97 >
98 > => {
99 if (environmentId === null) {
100 return AsyncResult.failure(
101 Cause.fail(
102 new PreferredEditorEnvironmentRequiredError({
103 targetPath,
104 }),
105 ),
106 );
107 }
108 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
109 return AsyncResult.failure(
110 Cause.fail(
111 new EnvironmentAuthorizationError({
112 requiredScope: AuthOrchestrationOperateScope,
113 message: "This connection cannot open an editor on this environment.",
114 }),
115 ),
116 );
117 }
118 const editor = resolveAndPersistPreferredEditor(availableEditors);
119 if (!editor) {
120 return AsyncResult.failure(
121 Cause.fail(
122 new PreferredEditorUnavailableError({
123 environmentId,
124 targetPath,
125 availableEditorIds: availableEditors,
126 }),
127 ),
128 );
129 }
130 const result = await openInEditor({
131 environmentId,
132 input: {
133 cwd: targetPath,
134 editor,
135 ...(projectRoot ? { projectRoot } : {}),
136 },
137 });
138 return mapAtomCommandResult(result, () => editor);
139 };