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