Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type {
3 DesktopPreviewBridge,
4 DesktopPreviewWebviewConfig,
5 EnvironmentId,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Option from "effect/Option";
9import * as Schema from "effect/Schema";
10import { AsyncResult, Atom } from "effect/unstable/reactivity";
11
12import { previewBridge } from "~/components/preview/previewBridge";
13
14const PREVIEW_CONFIG_STALE_TIME_MS = 5 * 60_000;
15const PREVIEW_CONFIG_IDLE_TTL_MS = 10 * 60_000;
16
17export class PreviewWebviewBridgeUnavailableError extends Schema.TaggedErrorClass<PreviewWebviewBridgeUnavailableError>()(
18 "PreviewWebviewBridgeUnavailableError",
19 { environmentId: Schema.String },
20) {
21 override get message(): string {
22 return `Desktop preview configuration is unavailable for environment "${this.environmentId}".`;
23 }
24}
25
26export class PreviewWebviewConfigLoadError extends Schema.TaggedErrorClass<PreviewWebviewConfigLoadError>()(
27 "PreviewWebviewConfigLoadError",
28 {
29 environmentId: Schema.String,
30 cause: Schema.Defect(),
31 },
32) {
33 override get message(): string {
34 return `Failed to load desktop preview configuration for environment "${this.environmentId}".`;
35 }
36}
37
38export const PreviewWebviewConfigError = Schema.Union([
39 PreviewWebviewBridgeUnavailableError,
40 PreviewWebviewConfigLoadError,
41]);
42export type PreviewWebviewConfigError = typeof PreviewWebviewConfigError.Type;
43
44type PreviewConfigBridge = Pick<DesktopPreviewBridge, "getPreviewConfig">;
45
46export const loadPreviewWebviewConfig = (
47 environmentId: EnvironmentId,
48 bridge: PreviewConfigBridge | null = previewBridge,
49): Effect.Effect<DesktopPreviewWebviewConfig, PreviewWebviewConfigError> => {
50 if (bridge === null) {
51 return Effect.fail(new PreviewWebviewBridgeUnavailableError({ environmentId }));
52 }
53
54 return Effect.tryPromise({
55 try: () => bridge.getPreviewConfig(environmentId),
56 catch: (cause) => new PreviewWebviewConfigLoadError({ environmentId, cause }),
57 });
58};
59
60const previewWebviewConfigAtom = Atom.family((environmentId: EnvironmentId) =>
61 Atom.make(loadPreviewWebviewConfig(environmentId)).pipe(
62 Atom.swr({
63 staleTime: PREVIEW_CONFIG_STALE_TIME_MS,
64 revalidateOnMount: true,
65 }),
66 Atom.setIdleTTL(PREVIEW_CONFIG_IDLE_TTL_MS),
67 Atom.withLabel(`preview:webview-config:${environmentId}`),
68 ),
69);
70
71export function usePreviewWebviewConfig(
72 environmentId: EnvironmentId,
73): DesktopPreviewWebviewConfig | null {
74 const result = useAtomValue(previewWebviewConfigAtom(environmentId));
75 return Option.getOrNull(AsyncResult.value(result));
76}