Open History to see the last commit
1import type { PreviewViewportSetting } from "@v12/contracts";
2
3type BrowserViewportHandler = (setting: PreviewViewportSetting) => Promise<void>;
4
5export const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;
6
7export class 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 runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
19 let timeoutId: ReturnType<typeof setTimeout> | undefined;
20 const timeout = new Promise<never>((_resolve, reject) => {
21 timeoutId = setTimeout(
22 () => reject(new BrowserViewportCommitTimeoutError(tabId)),
23 BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
24 );
25 });
26 return Promise.race([operation, timeout]).finally(() => {
27 if (timeoutId !== undefined) clearTimeout(timeoutId);
28 });
29};
30
31export function subscribeBrowserViewportChange(
32 tabId: string,
33 handler: BrowserViewportHandler,
34): () => void {
35 handlers.set(tabId, handler);
36 return () => {
37 if (handlers.get(tabId) === handler) handlers.delete(tabId);
38 };
39}
40
41export function commitBrowserViewportChange(
42 tabId: string,
43 setting: PreviewViewportSetting,
44): Promise<void> {
45 const previous = commitTails.get(tabId) ?? Promise.resolve();
46 const started = previous
47 .catch(() => undefined)
48 .then(() => {
49 const handler = handlers.get(tabId);
50 const operation = handler
51 ? Promise.resolve().then(() => handler(setting))
52 : Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
53 return { operation };
54 });
55 // The queue follows the real handler lifetime, not the caller-facing timeout.
56 // A slow commit therefore cannot time out, release the queue, and overwrite a
57 // newer viewport after that newer request has already completed.
58 const execution = started.then(({ operation }) => operation);
59 const result = started.then(({ operation }) => runHandlerWithTimeout(tabId, operation));
60 commitTails.set(tabId, execution);
61 const clear = () => {
62 if (commitTails.get(tabId) === execution) commitTails.delete(tabId);
63 };
64 void execution.then(clear, clear);
65 return result;
66}