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

openFileInPreview.ts

165 lines5.7 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";
34import { msg } from "gt-react";
35import { m } from "~/i18n/messages";
36​
37export const isBrowserPreviewFile = (path: string): boolean => /\.(?:html?|pdf)$/i.test(path);
38​
39export class BrowserPreviewUnavailableError extends Schema.TaggedError<BrowserPreviewUnavailableError>()(
40 "BrowserPreviewUnavailableError",
41 { message: Schema.String },
42) {}
43​
44export class BrowserSettingsReadError extends Schema.TaggedError<BrowserSettingsReadError>()(
45 "BrowserSettingsReadError",
46 { cause: Schema.Defect() },
47) {
48 override get message(): string {
49 return m(msg("Saved browser settings could not be loaded."));
50 }
52​
53export const isBrowserSettingsReadError = Schema.is(BrowserSettingsReadError);
54​
55export type OpenPreviewMutation<E = unknown> = (input: {
56 readonly environmentId: EnvironmentId;
57 readonly input: PreviewOpenInput;
58}) => Promise<AtomCommandResult<PreviewSessionSnapshot, E>>;
59​
60export async function openUrlInPreview<E>(input: {
61 readonly threadRef: ScopedThreadRef;
62 readonly url: string;
63 readonly openPreview: OpenPreviewMutation<E>;
64 readonly profileId?: PreviewOpenInput["profileId"];
65 readonly background?: boolean;
66}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
67 // Read before any await: a side chat pane that unmounts meanwhile drops its host mapping.
68 const threadRef = rightPanelHostRef(input.threadRef);
69 const defaults = await resolveBrowserDefaults().catch(
70 (cause: unknown) => new BrowserSettingsReadError({ cause }),
71 );
72 if (isBrowserSettingsReadError(defaults)) {
73 return AsyncResult.failure(Cause.fail(defaults));
74 }
75 const runtime = previewRuntimeFor(threadRef.environmentId);
76 const previousActiveTabId = readThreadPreviewState(threadRef).activeTabId;
77 // The server changes the active tab, not panel selection; selection changes come from the user.
78 const selectedSurface = () =>
79 selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, threadRef)?.id ??
80 null;
81 const surfaceBeforeOpen = selectedSurface();
82 const result = await input.openPreview({
83 environmentId: threadRef.environmentId,
84 input: {
85 threadId: threadRef.threadId,
86 url: input.url,
87 viewport: defaults.viewport,
88 profileId: input.profileId ?? defaults.profileId,
89 ...(runtime === undefined
90 ? {}
91 : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }),
92 },
93 });
94 return mapAtomCommandResult(result, (snapshot) => {
95 rememberPreviewUrl(threadRef, input.url);
96 if (input.background) {
97 updatePreviewServerSnapshot(threadRef, snapshot);
98 // Restore focus unless the user picked a tab while opening this one.
99 if (
100 previousActiveTabId &&
101 readThreadPreviewState(threadRef).activeTabId === snapshot.tabId &&
102 selectedSurface() === surfaceBeforeOpen
103 ) {
104 setActivePreviewTab(threadRef, previousActiveTabId);
105 }
106 return;
107 }
108 applyPreviewServerSnapshot(threadRef, snapshot);
109 useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);
110 });
112​
113export async function openFileInPreview<AssetError, PreviewError>(input: {
114 readonly threadRef: ScopedThreadRef;
115 readonly filePath: string;
116 readonly workspaceRoot: string | undefined;
117 readonly httpBaseUrl: string;
118 readonly createAssetUrl: (input: {
119 readonly environmentId: EnvironmentId;
120 readonly input: { readonly resource: AssetResource };
121 }) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
122 readonly openPreview: OpenPreviewMutation<PreviewError>;
123}): Promise<
124 AtomCommandResult<
125 void,
126 AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserSettingsReadError
127 >
128> {
129 if (!isPreviewAvailableFor(input.threadRef.environmentId)) {
130 return AsyncResult.failure(
131 Cause.fail(
132 new BrowserPreviewUnavailableError({
133 message: m(msg("The integrated browser is unavailable in this runtime.")),
134 }),
135 ),
136 );
137 }
138 const hostRef = rightPanelHostRef(input.threadRef);
139 const insideWorkspace =
140 mediaFileReference(input.filePath, input.workspaceRoot).relativePath !== undefined;
141 const assetResult = await input.createAssetUrl({
142 environmentId: input.threadRef.environmentId,
143 input: {
144 resource: {
145 _tag: insideWorkspace ? "workspace-file" : "media-file",
146 threadId: input.threadRef.threadId,
147 path: input.filePath,
148 },
149 },
150 });
151 if (assetResult._tag === "Failure") {
152 return AsyncResult.failure(assetResult.cause);
153 }
154 const assetUrl = resolveAssetUrl(input.httpBaseUrl, assetResult.value.relativeUrl);
155 if (assetUrl === null) {
156 return AsyncResult.failure(
157 Cause.die(new Error("The environment returned an invalid asset URL.")),
158 );
159 }
160 return openUrlInPreview({
161 threadRef: hostRef,
162 url: assetUrl,
163 openPreview: input.openPreview,
164 });