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

usePreviewSession.ts

120 lines4.0 KB

1"use client";
2​
3import { useAtomValue } from "@effect/atom-react";
4import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
5import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
6import type { ScopedThreadRef } from "@t3tools/contracts";
7import * as Schema from "effect/Schema";
8import { AsyncResult, Atom } from "effect/unstable/reactivity";
9​
10import {
11 applyPreviewServerEvent,
12 applyPreviewServerSnapshot,
13 readThreadPreviewState,
14 reconcilePreviewServerSessions,
15} from "~/previewStateStore";
16import { previewEnvironment } from "~/state/preview";
17​
18class PreviewSessionThreadKeyParseError extends Schema.TaggedErrorClass<PreviewSessionThreadKeyParseError>()(
19 "PreviewSessionThreadKeyParseError",
20 { threadKey: Schema.String },
21) {
22 override get message(): string {
23 return `Invalid scoped preview thread key: ${this.threadKey}`;
24 }
26​
27const previewSessionSyncAtom = Atom.family((threadKey: string) => {
28 const threadRef = parseScopedThreadKey(threadKey);
29 if (threadRef === null) {
30 throw new PreviewSessionThreadKeyParseError({ threadKey });
31 }
32​
33 const sessionsAtom = previewEnvironment.list({
34 environmentId: threadRef.environmentId,
35 input: { threadId: threadRef.threadId },
36 });
37 const eventsAtom = previewEnvironment.events({
38 environmentId: threadRef.environmentId,
39 input: {},
40 });
41​
42 return Atom.make((get) => {
43 let disposed = false;
44 let recoveryId = 0;
45 let recoveringUrl: string | null = null;
46 let sessionsVersion = 0;
47 let eventsVersion = 0;
48​
49 const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
50 if (!AsyncResult.isSuccess(result)) return;
51 if (result.value.sessions.length > 0) {
52 recoveringUrl = null;
53 recoveryId += 1;
54 reconcilePreviewServerSessions(threadRef, result.value.sessions);
55 return;
56 }
57​
58 const localSnapshot = readThreadPreviewState(threadRef).snapshot;
59 const recoverableUrl =
60 localSnapshot && localSnapshot.navStatus._tag !== "Idle"
61 ? localSnapshot.navStatus.url
62 : null;
63 if (!recoverableUrl) {
64 applyPreviewServerSnapshot(threadRef, null);
65 return;
66 }
67 if (recoveringUrl === recoverableUrl) return;
68​
69 recoveringUrl = recoverableUrl;
70 const currentRecoveryId = ++recoveryId;
71 void runAtomCommand(
72 get.registry,
73 previewEnvironment.open,
74 {
75 environmentId: threadRef.environmentId,
76 input: { threadId: threadRef.threadId, url: recoverableUrl },
77 },
78 { reportDefect: false, reportFailure: false },
79 ).then((openResult) => {
80 if (disposed || currentRecoveryId !== recoveryId) return;
81 recoveringUrl = null;
82 if (openResult._tag === "Failure") return;
83 applyPreviewServerSnapshot(threadRef, openResult.value);
84 get.refresh(sessionsAtom);
85 });
86 };
87​
88 const applyLatestEvent = (result: Atom.Type<typeof eventsAtom>) => {
89 if (!AsyncResult.isSuccess(result) || result.value.threadId !== threadRef.threadId) return;
90 applyPreviewServerEvent(threadRef, result.value);
91 if (result.value.type === "opened" || result.value.type === "closed") {
92 get.refresh(sessionsAtom);
93 }
94 };
95​
96 get.addFinalizer(() => {
97 disposed = true;
98 recoveryId += 1;
99 });
100 const initialSessions = get.once(sessionsAtom);
101 const initialEvent = get.once(eventsAtom);
102 get.subscribe(sessionsAtom, (result) => {
103 sessionsVersion += 1;
104 reconcileSessions(result);
105 });
106 get.subscribe(eventsAtom, (result) => {
107 eventsVersion += 1;
108 applyLatestEvent(result);
109 });
110 queueMicrotask(() => {
111 if (disposed) return;
112 if (sessionsVersion === 0) reconcileSessions(initialSessions);
113 if (eventsVersion === 0) applyLatestEvent(initialEvent);
114 });
115 }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));
116});
117​
118export function usePreviewSession(threadRef: ScopedThreadRef): void {
119 useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef)));