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

editorPreferences.ts

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