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

browserViewportActions.ts

117 lines3.9 KB

1import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
3​
4import { toastManager } from "~/components/ui/toast";
5import { updatePreviewServerSnapshot } from "~/previewStateStore";
6import { appAtomRegistry } from "~/rpc/atomRegistry";
7import { previewEnvironment } from "~/state/preview";
8​
9/** One browser tab as both the server (thread + tab id) and this window's runtime know it. */
10export interface BrowserViewportTarget {
11 readonly threadRef: ScopedThreadRef;
12 readonly tabId: string;
13 readonly runtimeTabId: string;
15​
16export const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;
17​
18class BrowserViewportCommitTimeoutError extends Error {
19 override readonly name = "BrowserViewportCommitTimeoutError";
20​
21 constructor(readonly tabId: string) {
22 super(`Timed out committing the browser viewport for tab ${tabId}`);
23 }
25​
26const commitTails = new Map<string, Promise<void>>();
27​
28const queueBrowserViewportMutation = <A>(
29 tabId: string,
30 start: () => Promise<A>,
31): {
32 readonly started: Promise<{ readonly operation: Promise<A> }>;
33 readonly execution: Promise<A>;
34} => {
35 const previous = commitTails.get(tabId) ?? Promise.resolve();
36 const started = previous
37 .catch(() => undefined)
38 .then(() => ({
39 operation: Promise.resolve().then(start),
40 }));
41 const execution = started.then(({ operation }) => operation);
42 const tail = execution.then(() => undefined);
43 commitTails.set(tabId, tail);
44 const clear = () => {
45 if (commitTails.get(tabId) === tail) commitTails.delete(tabId);
46 };
47 void tail.then(clear, clear);
48 return { started, execution };
49};
50​
51/** Serializes UI and automation mutations per tab so rollback cannot overtake a newer resize. */
52export function runBrowserViewportMutation<A>(
53 tabId: string,
54 mutation: () => Promise<A>,
55): Promise<A> {
56 return queueBrowserViewportMutation(tabId, mutation).execution;
58​
59const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
60 let timeoutId: ReturnType<typeof setTimeout> | undefined;
61 const timeout = new Promise<never>((_resolve, reject) => {
62 timeoutId = setTimeout(
63 () => reject(new BrowserViewportCommitTimeoutError(tabId)),
64 BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
65 );
66 });
67 return Promise.race([operation, timeout]).finally(() => {
68 if (timeoutId !== undefined) clearTimeout(timeoutId);
69 });
70};
71​
72async function resizeBrowserViewport(
73 target: BrowserViewportTarget,
74 viewport: PreviewViewportSetting,
75): Promise<void> {
76 const result = await runAtomCommand(
77 appAtomRegistry,
78 previewEnvironment.resize,
79 {
80 environmentId: target.threadRef.environmentId,
81 input: { threadId: target.threadRef.threadId, tabId: target.tabId, viewport },
82 },
83 { label: "preview viewport resize" },
84 );
85 if (result._tag === "Failure") {
86 const error = squashAtomCommandFailure(result);
87 toastManager.add({
88 type: "error",
89 title: "Unable to resize browser viewport",
90 description: error instanceof Error ? error.message : "An error occurred.",
91 });
92 throw error;
93 }
94 updatePreviewServerSnapshot(target.threadRef, result.value);
96​
97/**
98 * Runs `operation` after every earlier commit for the runtime tab. The
99 * caller-facing timeout starts only once it reaches the front of the queue,
100 * while the queue itself waits for the real operation.
101 */
102export function queueBrowserViewportCommit(
103 runtimeTabId: string,
104 operation: () => Promise<void>,
105): Promise<void> {
106 const { started } = queueBrowserViewportMutation(runtimeTabId, operation);
107 return started.then(({ operation: running }) => runHandlerWithTimeout(runtimeTabId, running));
109​
110export function commitBrowserViewportChange(
111 target: BrowserViewportTarget,
112 setting: PreviewViewportSetting,
113): Promise<void> {
114 return queueBrowserViewportCommit(target.runtimeTabId, () =>
115 resizeBrowserViewport(target, setting),
116 );