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

openFileInPreview.ts

162 lines5.6 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 ? {} : { runtime }),
89 },
90 });
91 return mapAtomCommandResult(result, (snapshot) => {
92 rememberPreviewUrl(threadRef, input.url);
93 if (input.background) {
94 updatePreviewServerSnapshot(threadRef, snapshot);
95 // Restore focus unless the user picked a tab while opening this one.
96 if (
97 previousActiveTabId &&
98 readThreadPreviewState(threadRef).activeTabId === snapshot.tabId &&
99 selectedSurface() === surfaceBeforeOpen
100 ) {
101 setActivePreviewTab(threadRef, previousActiveTabId);
102 }
103 return;
104 }
105 applyPreviewServerSnapshot(threadRef, snapshot);
106 useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);
107 });
109​
110export async function openFileInPreview<AssetError, PreviewError>(input: {
111 readonly threadRef: ScopedThreadRef;
112 readonly filePath: string;
113 readonly workspaceRoot: string | undefined;
114 readonly httpBaseUrl: string;
115 readonly createAssetUrl: (input: {
116 readonly environmentId: EnvironmentId;
117 readonly input: { readonly resource: AssetResource };
118 }) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
119 readonly openPreview: OpenPreviewMutation<PreviewError>;
120}): Promise<
121 AtomCommandResult<
122 void,
123 AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserSettingsReadError
124 >
125> {
126 if (!isPreviewAvailableFor(input.threadRef.environmentId)) {
127 return AsyncResult.failure(
128 Cause.fail(
129 new BrowserPreviewUnavailableError({
130 message: "The integrated browser is unavailable in this runtime.",
131 }),
132 ),
133 );
134 }
135 const hostRef = rightPanelHostRef(input.threadRef);
136 const insideWorkspace =
137 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
138 const assetResult = await input.createAssetUrl({
139 environmentId: input.threadRef.environmentId,
140 input: {
141 resource: {
142 _tag: insideWorkspace ? "workspace-file" : "media-file",
143 threadId: input.threadRef.threadId,
144 path: input.filePath,
145 },
146 },
147 });
148 if (assetResult._tag === "Failure") {
149 return AsyncResult.failure(assetResult.cause);
150 }
151 const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
152 if (assetUrl === null) {
153 return AsyncResult.failure(
154 Cause.die(new Error("The environment returned an invalid asset URL.")),
155 );
156 }
157 return openUrlInPreview({
158 threadRef: hostRef,
159 url: assetUrl,
160 openPreview: input.openPreview,
161 });