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

usePreviewSession.ts

83 lines2.9 KB

1"use client";
2​
3import { useAtomValue } from "@effect/atom-react";
4import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
5import type { ScopedThreadRef } from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7import { AsyncResult, Atom } from "effect/unstable/reactivity";
8​
9import {
10 applyPreviewServerEvent,
11 readThreadPreviewState,
12 reconcilePreviewServerSessions,
13} from "~/previewStateStore";
14import { previewEnvironment } from "~/state/preview";
15​
16class PreviewSessionThreadKeyParseError extends Schema.TaggedErrorClass<PreviewSessionThreadKeyParseError>()(
17 "PreviewSessionThreadKeyParseError",
18 { threadKey: Schema.String },
19) {
20 override get message(): string {
21 return `Invalid scoped preview thread key: ${this.threadKey}`;
22 }
24​
25const previewSessionSyncAtom = Atom.family((threadKey: string) => {
26 const threadRef = parseScopedThreadKey(threadKey);
27 if (threadRef === null) {
28 throw new PreviewSessionThreadKeyParseError({ threadKey });
29 }
30​
31 const sessionsAtom = previewEnvironment.list({
32 environmentId: threadRef.environmentId,
33 input: { threadId: threadRef.threadId },
34 });
35 const eventsAtom = previewEnvironment.events({
36 environmentId: threadRef.environmentId,
37 input: {},
38 });
39​
40 return Atom.make((get) => {
41 let disposed = false;
42 let eventsVersion = 0;
43​
44 const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
45 if (!AsyncResult.isSuccess(result)) return;
46 reconcilePreviewServerSessions(threadRef, result.value);
47 };
48​
49 const applyLatestEvent = (result: Atom.Type<typeof eventsAtom>) => {
50 if (!AsyncResult.isSuccess(result) || result.value.threadId !== threadRef.threadId) return;
51 const currentEpoch = readThreadPreviewState(threadRef).serverEpoch;
52 if (currentEpoch !== null && currentEpoch !== result.value.serverEpoch) {
53 get.refresh(sessionsAtom);
54 return;
55 }
56 applyPreviewServerEvent(threadRef, result.value);
57 };
58​
59 get.addFinalizer(() => {
60 disposed = true;
61 });
62 const initialEvent = get.once(eventsAtom);
63 get.subscribe(sessionsAtom, (result) => {
64 reconcileSessions(result);
65 });
66 get.subscribe(eventsAtom, (result) => {
67 eventsVersion += 1;
68 applyLatestEvent(result);
69 });
70 queueMicrotask(() => {
71 if (disposed) return;
72 // The cached list can predate an automation-created tab. Keep the local
73 // snapshot visible until an authoritative refresh arrives instead of
74 // reconciling against a stale empty result when the panel first mounts.
75 get.refresh(sessionsAtom);
76 if (eventsVersion === 0) applyLatestEvent(initialEvent);
77 });
78 }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));
79});
80​
81export function usePreviewSession(threadRef: ScopedThreadRef): void {
82 useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef)));