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/unstable/reactivity";
17
18import { resolveAssetUrl } from "~/assets/assetUrls";
19import {
20 applyPreviewServerSnapshot,
21 isPreviewSupportedInRuntime,
22 rememberPreviewUrl,
23} from "~/previewStateStore";
24import { useRightPanelStore } from "~/rightPanelStore";
25
26import {
27 browserDefaultOpenProfileId,
28 browserDefaultOpenViewport,
29 resolveBrowserDefaults,
30} from "./browserDefaults";
31
32export const isBrowserPreviewFile = (path: string): boolean =>
33 /\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
34
35export class BrowserPreviewUnavailableError extends Data.TaggedError(
36 "BrowserPreviewUnavailableError",
37)<{
38 readonly message: string;
39}> {}
40
41export class BrowserSettingsReadError extends Data.TaggedError("BrowserSettingsReadError")<{
42 readonly cause: unknown;
43}> {
44 override get message(): string {
45 return "Saved browser settings could not be loaded.";
46 }
47}
48
49export type OpenPreviewMutation<E = unknown> = (input: {
50 readonly environmentId: EnvironmentId;
51 readonly input: PreviewOpenInput;
52}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
53
54export async function openUrlInPreview<E>(input: {
55 readonly threadRef: ScopedThreadRef;
56 readonly url: string;
57 readonly openPreview: OpenPreviewMutation<E>;
58}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
59 const defaults = await resolveBrowserDefaults().catch(
60 (cause: unknown) => new BrowserSettingsReadError({ cause }),
61 );
62 if (defaults instanceof BrowserSettingsReadError) {
63 return AsyncResult.failure(Cause.fail(defaults));
64 }
65 const result = await input.openPreview({
66 environmentId: input.threadRef.environmentId,
67 input: {
68 threadId: input.threadRef.threadId,
69 url: input.url,
70 // Built here rather than via `openPreviewSession` because this path
71 // maps the result differently, so the configured defaults have to be
72 // applied explicitly or file/link opens would ignore them.
73 viewport: browserDefaultOpenViewport(defaults),
74 profileId: browserDefaultOpenProfileId(defaults),
75 },
76 });
77 return mapAtomCommandResult(result, (snapshot) => {
78 applyPreviewServerSnapshot(input.threadRef, snapshot);
79 rememberPreviewUrl(input.threadRef, input.url);
80 useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
81 });
82}
83
84/**
85 * Opens a browser document in the integrated browser. Inside the workspace the
86 * page may load sibling assets; a file outside it is served on its own.
87 */
88export async function openFileInPreview<AssetError, PreviewError>(input: {
89 readonly threadRef: ScopedThreadRef;
90 readonly filePath: string;
91 readonly workspaceRoot: string | undefined;
92 readonly httpBaseUrl: string;
93 readonly createAssetUrl: (input: {
94 readonly environmentId: EnvironmentId;
95 readonly input: { readonly resource: AssetResource };
96 }) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
97 readonly openPreview: OpenPreviewMutation<PreviewError>;
98}): Promise<
99 AtomCommandResult<
100 void,
101 AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserSettingsReadError
102 >
103> {
104 if (!isPreviewSupportedInRuntime()) {
105 return AsyncResult.failure(
106 Cause.fail(
107 new BrowserPreviewUnavailableError({
108 message: "The integrated browser is unavailable in this runtime.",
109 }),
110 ),
111 );
112 }
113 const insideWorkspace =
114 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
115 const assetResult = await input.createAssetUrl({
116 environmentId: input.threadRef.environmentId,
117 input: {
118 resource: {
119 _tag: insideWorkspace ? "workspace-file" : "media-file",
120 threadId: input.threadRef.threadId,
121 path: input.filePath,
122 },
123 },
124 });
125 if (assetResult._tag === "Failure") {
126 return AsyncResult.failure(assetResult.cause);
127 }
128 const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
129 if (assetUrl === null) {
130 return AsyncResult.failure(
131 Cause.die(new Error("The environment returned an invalid asset URL.")),
132 );
133 }
134 return openUrlInPreview({
135 threadRef: input.threadRef,
136 url: assetUrl,
137 openPreview: input.openPreview,
138 });
139}