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

openFileInPreview.ts

160 lines5.4 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 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 {
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 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 }
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 // Read before any await: a side chat pane that unmounts meanwhile drops its host mapping.
65 const threadRef = rightPanelHostRef(input.threadRef);
66 const defaults = await resolveBrowserDefaults().catch(
67 (cause: unknown) => new BrowserSettingsReadError({ cause }),
68 );
69 if (defaults instanceof BrowserSettingsReadError) {
70 return AsyncResult.failure(Cause.fail(defaults));
71 }
72 const runtime = previewRuntimeFor(threadRef.environmentId);
73 const previousActiveTabId = readThreadPreviewState(threadRef).activeTabId;
74 // The server changes the active tab, not panel selection; selection changes come from the user.
75 const selectedSurface = () =>
76 selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.id ??
77 null;
78 const surfaceBeforeOpen = selectedSurface();
79 const result = await input.openPreview({
80 environmentId: threadRef.environmentId,
81 input: {
82 threadId: threadRef.threadId,
83 url: input.url,
84 viewport: defaults.viewport,
85 profileId: input.profileId ?? defaults.profileId,
86 ...(runtime === undefined ? {} : { runtime }),
87 },
88 });
89 return mapAtomCommandResult(result, (snapshot) => {
90 rememberPreviewUrl(threadRef, input.url);
91 if (input.background) {
92 updatePreviewServerSnapshot(threadRef, snapshot);
93 // Restore focus unless the user picked a tab while opening this one.
94 if (
95 previousActiveTabId &&
96 readThreadPreviewState(threadRef).activeTabId === snapshot.tabId &&
97 selectedSurface() === surfaceBeforeOpen
98 ) {
99 setActivePreviewTab(threadRef, previousActiveTabId);
100 }
101 return;
102 }
103 applyPreviewServerSnapshot(threadRef, snapshot);
104 useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);
105 });
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 hostRef = rightPanelHostRef(input.threadRef);
134 const insideWorkspace =
135 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
136 const assetResult = await input.createAssetUrl({
137 environmentId: input.threadRef.environmentId,
138 input: {
139 resource: {
140 _tag: insideWorkspace ? "workspace-file" : "media-file",
141 threadId: input.threadRef.threadId,
142 path: input.filePath,
143 },
144 },
145 });
146 if (assetResult._tag === "Failure") {
147 return AsyncResult.failure(assetResult.cause);
148 }
149 const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
150 if (assetUrl === null) {
151 return AsyncResult.failure(
152 Cause.die(new Error("The environment returned an invalid asset URL.")),
153 );
154 }
155 return openUrlInPreview({
156 threadRef: hostRef,
157 url: assetUrl,
158 openPreview: input.openPreview,
159 });