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

editorPreferences.ts

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