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

openFileInPreview.ts

36 lines1.4 KB

1import type { ScopedThreadRef } from "@t3tools/contracts";
2​
3import { readEnvironmentApi } from "~/environmentApi";
4import { resolveAssetUrl } from "~/assets/assetUrls";
5import { isPreviewSupportedInRuntime, usePreviewStateStore } from "~/previewStateStore";
6import { useRightPanelStore } from "~/rightPanelStore";
7​
8export const isBrowserPreviewFile = (path: string): boolean =>
9 /\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
10​
11export async function openUrlInPreview(threadRef: ScopedThreadRef, url: string): Promise<void> {
12 const api = readEnvironmentApi(threadRef.environmentId);
13 if (!api) {
14 throw new Error("Environment is not connected.");
15 }
16​
17 const snapshot = await api.preview.open({ threadId: threadRef.threadId, url });
18 usePreviewStateStore.getState().applyServerSnapshot(threadRef, snapshot);
19 usePreviewStateStore.getState().rememberUrl(threadRef, url);
20 useRightPanelStore.getState().openBrowser(threadRef, snapshot.tabId);
22​
23export async function openFileInPreview(
24 threadRef: ScopedThreadRef,
25 filePath: string,
26): Promise<void> {
27 if (!isPreviewSupportedInRuntime()) {
28 throw new Error("The integrated browser is unavailable in this runtime.");
29 }
30 const asset = await resolveAssetUrl(threadRef.environmentId, {
31 _tag: "workspace-file",
32 threadId: threadRef.threadId,
33 path: filePath,
34 });
35 await openUrlInPreview(threadRef, asset.url);