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

openFileInPreview.ts

164 lines5.7 KB

1import type {
2 AssetCreateUrlResult,
3 AssetResource,
4 EnvironmentId,
5 PreviewOpenInput,
6 PreviewSessionSnapshot,
7 ScopedThreadRef,
8} from "@t3tools/contracts";
9import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
10import {
11 type AtomCommandResult,
12 mapAtomCommandResult,
13} from "@t3tools/client-runtime/state/runtime";
14import * as Cause from "effect/Cause";
15import * as Schema from "effect/Schema";
16import { AsyncResult } from "effect/reactivity";
17​
18import { resolveAssetUrl } from "~/assets/assetUrls";
19import { isPreviewAvailableFor, previewRuntimeFor } from "~/browser/previewRuntime";
20import {
21 applyPreviewServerSnapshot,
22 readThreadPreviewState,
23 rememberPreviewUrl,
24 setActivePreviewTab,
25 updatePreviewServerSnapshot,
26} from "~/previewStateStore";
27import {
28 rightPanelHostRef,
29 selectSelectedRightPanelSurface,
30 useRightPanelStore,
31} from "~/rightPanelStore";
32​
33import { resolveBrowserDefaults } from "./browserDefaults";
34​
35export const isBrowserPreviewFile = (path: string): boolean =>
36 /\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
37​
38export class BrowserPreviewUnavailableError extends Schema.TaggedError<BrowserPreviewUnavailableError>()(
39 "BrowserPreviewUnavailableError",
40 { message: Schema.String },
41) {}
42​
43export class BrowserSettingsReadError extends Schema.TaggedError<BrowserSettingsReadError>()(
44 "BrowserSettingsReadError",
45 { cause: Schema.Defect() },
46) {
47 override get message(): string {
48 return "Saved browser settings could not be loaded.";
49 }
51​
52export const isBrowserSettingsReadError = Schema.is(BrowserSettingsReadError);
53​
54export type OpenPreviewMutation<E = unknown> = (input: {
55 readonly environmentId: EnvironmentId;
56 readonly input: PreviewOpenInput;
57}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
58​
59export async function openUrlInPreview<E>(input: {
60 readonly threadRef: ScopedThreadRef;
61 readonly url: string;
62 readonly openPreview: OpenPreviewMutation<E>;
63 readonly profileId?: PreviewOpenInput["profileId"];
64 readonly background?: boolean;
65}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
66 // Read before any await: a side chat pane that unmounts meanwhile drops its host mapping.
67 const threadRef = rightPanelHostRef(input.threadRef);
68 const defaults = await resolveBrowserDefaults().catch(
69 (cause: unknown) => new BrowserSettingsReadError({ cause }),
70 );
71 if (isBrowserSettingsReadError(defaults)) {
72 return AsyncResult.failure(Cause.fail(defaults));
73 }
74 const runtime = previewRuntimeFor(threadRef.environmentId);
75 const previousActiveTabId = readThreadPreviewState(threadRef).activeTabId;
76 // The server changes the active tab, not panel selection; selection changes come from the user.
77 const selectedSurface = () =>
78 selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.id ??
79 null;
80 const surfaceBeforeOpen = selectedSurface();
81 const result = await input.openPreview({
82 environmentId: threadRef.environmentId,
83 input: {
84 threadId: threadRef.threadId,
85 url: input.url,
86 viewport: defaults.viewport,
87 profileId: input.profileId ?? defaults.profileId,
88 ...(runtime === undefined
89 ? {}
90 : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }),
91 },
92 });
93 return mapAtomCommandResult(result, (snapshot) => {
94 rememberPreviewUrl(threadRef, input.url);
95 if (input.background) {
96 updatePreviewServerSnapshot(threadRef, snapshot);
97 // Restore focus unless the user picked a tab while opening this one.
98 if (
99 previousActiveTabId &&
100 readThreadPreviewState(threadRef).activeTabId === snapshot.tabId &&
101 selectedSurface() === surfaceBeforeOpen
102 ) {
103 setActivePreviewTab(threadRef, previousActiveTabId);
104 }
105 return;
106 }
107 applyPreviewServerSnapshot(threadRef, snapshot);
108 useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);
109 });
111​
112export async function openFileInPreview<AssetError, PreviewError>(input: {
113 readonly threadRef: ScopedThreadRef;
114 readonly filePath: string;
115 readonly workspaceRoot: string | undefined;
116 readonly httpBaseUrl: string;
117 readonly createAssetUrl: (input: {
118 readonly environmentId: EnvironmentId;
119 readonly input: { readonly resource: AssetResource };
120 }) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
121 readonly openPreview: OpenPreviewMutation<PreviewError>;
122}): Promise<
123 AtomCommandResult<
124 void,
125 AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserSettingsReadError
126 >
127> {
128 if (!isPreviewAvailableFor(input.threadRef.environmentId)) {
129 return AsyncResult.failure(
130 Cause.fail(
131 new BrowserPreviewUnavailableError({
132 message: "The integrated browser is unavailable in this runtime.",
133 }),
134 ),
135 );
136 }
137 const hostRef = rightPanelHostRef(input.threadRef);
138 const insideWorkspace =
139 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
140 const assetResult = await input.createAssetUrl({
141 environmentId: input.threadRef.environmentId,
142 input: {
143 resource: {
144 _tag: insideWorkspace ? "workspace-file" : "media-file",
145 threadId: input.threadRef.threadId,
146 path: input.filePath,
147 },
148 },
149 });
150 if (assetResult._tag === "Failure") {
151 return AsyncResult.failure(assetResult.cause);
152 }
153 const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
154 if (assetUrl === null) {
155 return AsyncResult.failure(
156 Cause.die(new Error("The environment returned an invalid asset URL.")),
157 );
158 }
159 return openUrlInPreview({
160 threadRef: hostRef,
161 url: assetUrl,
162 openPreview: input.openPreview,
163 });