Open History to see the last commit
1import type { PreviewViewportSetting } from "@t3tools/contracts";
2
3type BrowserViewportHandler = (setting: PreviewViewportSetting) => Promise<void>;
4
5export const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;
6
7class BrowserViewportCommitTimeoutError extends Error {
8 override readonly name = "BrowserViewportCommitTimeoutError";
9
10 constructor(readonly tabId: string) {
11 super(`Timed out committing the browser viewport for tab ${tabId}`);
12 }
13}
14
15const handlers = new Map<string, BrowserViewportHandler>();
16const commitTails = new Map<string, Promise<void>>();
17
18const queueBrowserViewportMutation = <A>(
19 tabId: string,
20 start: () => Promise<A>,
21): {
22 readonly started: Promise<{ readonly operation: Promise<A> }>;
23 readonly execution: Promise<A>;
24} => {
25 const previous = commitTails.get(tabId) ?? Promise.resolve();
26 const started = previous
27 .catch(() => undefined)
28 .then(() => ({
29 operation: Promise.resolve().then(start),
30 }));
31 const execution = started.then(({ operation }) => operation);
32 const tail = execution.then(() => undefined);
33 commitTails.set(tabId, tail);
34 const clear = () => {
35 if (commitTails.get(tabId) === tail) commitTails.delete(tabId);
36 };
37 void tail.then(clear, clear);
38 return { started, execution };
39};
40
41/** Serializes UI and automation mutations per tab so rollback cannot overtake a newer resize. */
42export function runBrowserViewportMutation<A>(
43 tabId: string,
44 mutation: () => Promise<A>,
45): Promise<A> {
46 return queueBrowserViewportMutation(tabId, mutation).execution;
47}
48
49const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
50 let timeoutId: ReturnType<typeof setTimeout> | undefined;
51 const timeout = new Promise<never>((_resolve, reject) => {
52 timeoutId = setTimeout(
53 () => reject(new BrowserViewportCommitTimeoutError(tabId)),
54 BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
55 );
56 });
57 return Promise.race([operation, timeout]).finally(() => {
58 if (timeoutId !== undefined) clearTimeout(timeoutId);
59 });
60};
61
62export function subscribeBrowserViewportChange(
63 tabId: string,
64 handler: BrowserViewportHandler,
65): () => void {
66 handlers.set(tabId, handler);
67 return () => {
68 if (handlers.get(tabId) === handler) handlers.delete(tabId);
69 };
70}
71
72export function commitBrowserViewportChange(
73 tabId: string,
74 setting: PreviewViewportSetting,
75): Promise<void> {
76 const { started } = queueBrowserViewportMutation(tabId, () => {
77 const handler = handlers.get(tabId);
78 return handler
79 ? handler(setting)
80 : Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
81 });
82 // Queue until the handler finishes; start the caller timeout only when its turn begins.
83 const result = started.then(({ operation }) => runHandlerWithTimeout(tabId, operation));
84 return result;
85}