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

browserViewportActions.ts

110 lines3.7 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​
16const 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​
28/** Serializes UI and automation mutations per tab so rollback cannot overtake a newer resize. */
29const queueBrowserViewportMutation = <A>(
30 tabId: string,
31 start: () => Promise<A>,
32): {
33 readonly started: Promise<{ readonly operation: Promise<A> }>;
34 readonly execution: Promise<A>;
35} => {
36 const previous = commitTails.get(tabId) ?? Promise.resolve();
37 const started = previous
38 .catch(() => undefined)
39 .then(() => ({
40 operation: Promise.resolve().then(start),
41 }));
42 const execution = started.then(({ operation }) => operation);
43 const tail = execution.then(() => undefined);
44 commitTails.set(tabId, tail);
45 const clear = () => {
46 if (commitTails.get(tabId) === tail) commitTails.delete(tabId);
47 };
48 void tail.then(clear, clear);
49 return { started, execution };
50};
51​
52const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
53 let timeoutId: ReturnType<typeof setTimeout> | undefined;
54 const timeout = new Promise<never>((_resolve, reject) => {
55 timeoutId = setTimeout(
56 () => reject(new BrowserViewportCommitTimeoutError(tabId)),
57 BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
58 );
59 });
60 return Promise.race([operation, timeout]).finally(() => {
61 if (timeoutId !== undefined) clearTimeout(timeoutId);
62 });
63};
64​
65async function resizeBrowserViewport(
66 target: BrowserViewportTarget,
67 viewport: PreviewViewportSetting,
68): Promise<void> {
69 const result = await runAtomCommand(
70 appAtomRegistry,
71 previewEnvironment.resize,
72 {
73 environmentId: target.threadRef.environmentId,
74 input: { threadId: target.threadRef.threadId, tabId: target.tabId, viewport },
75 },
76 { label: "preview viewport resize" },
77 );
78 if (result._tag === "Failure") {
79 const error = squashAtomCommandFailure(result);
80 toastManager.add({
81 type: "error",
82 title: "Unable to resize browser viewport",
83 description: error instanceof Error ? error.message : "An error occurred.",
84 });
85 throw error;
86 }
87 updatePreviewServerSnapshot(target.threadRef, result.value);
89​
90/**
91 * Runs `operation` after every earlier commit for the runtime tab. The
92 * caller-facing timeout starts only once it reaches the front of the queue,
93 * while the queue itself waits for the real operation.
94 */
95export function queueBrowserViewportCommit(
96 runtimeTabId: string,
97 operation: () => Promise<void>,
98): Promise<void> {
99 const { started } = queueBrowserViewportMutation(runtimeTabId, operation);
100 return started.then(({ operation: running }) => runHandlerWithTimeout(runtimeTabId, running));
102​
103export function commitBrowserViewportChange(
104 target: BrowserViewportTarget,
105 setting: PreviewViewportSetting,
106): Promise<void> {
107 return queueBrowserViewportCommit(target.runtimeTabId, () =>
108 resizeBrowserViewport(target, setting),
109 );