Open History to see the last commit
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 Data from "effect/Data";
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 { selectSelectedRightPanelSurface, useRightPanelStore } from "~/rightPanelStore";
28
29import {
30 browserDefaultOpenProfileId,
31 browserDefaultOpenViewport,
32 resolveBrowserDefaults,
33} from "./browserDefaults";
34
35export const isBrowserPreviewFile = (path: string): boolean =>
36 /\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
37
38export class BrowserPreviewUnavailableError extends Data.TaggedError(
39 "BrowserPreviewUnavailableError",
40)<{
41 readonly message: string;
42}> {}
43
44export class BrowserSettingsReadError extends Data.TaggedError("BrowserSettingsReadError")<{
45 readonly cause: unknown;
46}> {
47 override get message(): string {
48 return "Saved browser settings could not be loaded.";
49 }
50}
51
52export type OpenPreviewMutation<E = unknown> = (input: {
53 readonly environmentId: EnvironmentId;
54 readonly input: PreviewOpenInput;
55}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
56
57export async function openUrlInPreview<E>(input: {
58 readonly threadRef: ScopedThreadRef;
59 readonly url: string;
60 readonly openPreview: OpenPreviewMutation<E>;
61 readonly profileId?: PreviewOpenInput["profileId"];
62 readonly background?: boolean;
63}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
64 const defaults = await resolveBrowserDefaults().catch(
65 (cause: unknown) => new BrowserSettingsReadError({ cause }),
66 );
67 if (defaults instanceof BrowserSettingsReadError) {
68 return AsyncResult.failure(Cause.fail(defaults));
69 }
70 const runtime = previewRuntimeFor(input.threadRef.environmentId);
71 const previousActiveTabId = readThreadPreviewState(input.threadRef).activeTabId;
72 // The server's "opened" event switches the preview tab but not the panel's
73 // selection, so a changed selection means the user picked a tab themselves.
74 const selectedSurface = () =>
75 selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, input.threadRef)
76 ?.id ?? null;
77 const surfaceBeforeOpen = selectedSurface();
78 const result = await input.openPreview({
79 environmentId: input.threadRef.environmentId,
80 input: {
81 threadId: input.threadRef.threadId,
82 url: input.url,
83 viewport: browserDefaultOpenViewport(defaults),
84 profileId: input.profileId ?? browserDefaultOpenProfileId(defaults),
85 ...(runtime === undefined ? {} : { runtime }),
86 },
87 });
88 return mapAtomCommandResult(result, (snapshot) => {
89 rememberPreviewUrl(input.threadRef, input.url);
90 if (input.background) {
91 updatePreviewServerSnapshot(input.threadRef, snapshot);
92 // The server's "opened" event activates the new tab; hand focus back,
93 // unless the user picked a tab, this one included, while the open was in flight.
94 if (
95 previousActiveTabId &&
96 readThreadPreviewState(input.threadRef).activeTabId === snapshot.tabId &&
97 selectedSurface() === surfaceBeforeOpen
98 ) {
99 setActivePreviewTab(input.threadRef, previousActiveTabId);
100 }
101 return;
102 }
103 applyPreviewServerSnapshot(input.threadRef, snapshot);
104 useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
105 });
106}
107
108export async function openFileInPreview<AssetError, PreviewError>(input: {
109 readonly threadRef: ScopedThreadRef;
110 readonly filePath: string;
111 readonly workspaceRoot: string | undefined;
112 readonly httpBaseUrl: string;
113 readonly createAssetUrl: (input: {
114 readonly environmentId: EnvironmentId;
115 readonly input: { readonly resource: AssetResource };
116 }) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
117 readonly openPreview: OpenPreviewMutation<PreviewError>;
118}): Promise<
119 AtomCommandResult<
120 void,
121 AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserSettingsReadError
122 >
123> {
124 if (!isPreviewAvailableFor(input.threadRef.environmentId)) {
125 return AsyncResult.failure(
126 Cause.fail(
127 new BrowserPreviewUnavailableError({
128 message: "The integrated browser is unavailable in this runtime.",
129 }),
130 ),
131 );
132 }
133 const insideWorkspace =
134 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
135 const assetResult = await input.createAssetUrl({
136 environmentId: input.threadRef.environmentId,
137 input: {
138 resource: {
139 _tag: insideWorkspace ? "workspace-file" : "media-file",
140 threadId: input.threadRef.threadId,
141 path: input.filePath,
142 },
143 },
144 });
145 if (assetResult._tag === "Failure") {
146 return AsyncResult.failure(assetResult.cause);
147 }
148 const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
149 if (assetUrl === null) {
150 return AsyncResult.failure(
151 Cause.die(new Error("The environment returned an invalid asset URL.")),
152 );
153 }
154 return openUrlInPreview({
155 threadRef: input.threadRef,
156 url: assetUrl,
157 openPreview: input.openPreview,
158 });
159}