Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { withPreviewAutomationFocus } from "./previewAutomationFocus";
4
5class MockHTMLElement {
6 isConnected = true;
7 readonly focus = vi.fn((_options?: FocusOptions) => {
8 setActiveElement(this);
9 });
10}
11
12const setActiveElement = (activeElement: MockHTMLElement | null): void => {
13 (globalThis.document as unknown as { activeElement: MockHTMLElement | null }).activeElement =
14 activeElement;
15};
16
17afterEach(() => {
18 vi.unstubAllGlobals();
19});
20
21const setupDocument = (activeElement: MockHTMLElement | null, focused = true) => {
22 const body = new MockHTMLElement();
23 const documentElement = new MockHTMLElement();
24 let documentFocused = focused;
25 const documentListeners = new Map<string, Set<(event: Event) => void>>();
26 const windowListeners = new Map<string, Set<() => void>>();
27 vi.stubGlobal("HTMLElement", MockHTMLElement);
28 vi.stubGlobal("document", {
29 activeElement,
30 body,
31 documentElement,
32 hasFocus: () => documentFocused,
33 addEventListener: (type: string, listener: (event: Event) => void) => {
34 const listeners = documentListeners.get(type) ?? new Set();
35 listeners.add(listener);
36 documentListeners.set(type, listeners);
37 },
38 removeEventListener: (type: string, listener: (event: Event) => void) => {
39 documentListeners.get(type)?.delete(listener);
40 },
41 });
42 vi.stubGlobal("window", {
43 addEventListener: (type: string, listener: () => void) => {
44 const listeners = windowListeners.get(type) ?? new Set();
45 listeners.add(listener);
46 windowListeners.set(type, listeners);
47 },
48 removeEventListener: (type: string, listener: () => void) => {
49 windowListeners.get(type)?.delete(listener);
50 },
51 });
52 return {
53 body,
54 setDocumentFocused: (value: boolean) => {
55 documentFocused = value;
56 },
57 dispatchDocument: (type: string, target: MockHTMLElement, isTrusted = true) => {
58 for (const listener of documentListeners.get(type) ?? []) {
59 listener({ target, isTrusted } as unknown as Event);
60 }
61 },
62 dispatchWindow: (type: string) => {
63 for (const listener of windowListeners.get(type) ?? []) listener();
64 },
65 };
66};
67
68describe("withPreviewAutomationFocus", () => {
69 it("restores focus when automation leaves a connected host control focused", async () => {
70 const composer = new MockHTMLElement();
71 const hostButton = new MockHTMLElement();
72 const { dispatchDocument, dispatchWindow } = setupDocument(composer);
73
74 const result = await withPreviewAutomationFocus(async () => {
75 // Native guest focus briefly transfers the renderer window away and back.
76 dispatchWindow("blur");
77 dispatchWindow("focus");
78 setActiveElement(hostButton);
79 dispatchDocument("focusin", hostButton, false);
80 return "pressed";
81 });
82
83 expect(result).toBe("pressed");
84 expect(composer.focus).toHaveBeenCalledWith({ preventScroll: true });
85 expect(globalThis.document.activeElement).toBe(composer);
86 });
87
88 it("preserves newer DOM focus while the bridge operation is pending", async () => {
89 const composer = new MockHTMLElement();
90 const newerControl = new MockHTMLElement();
91 const { body, dispatchDocument } = setupDocument(composer);
92 let finish!: () => void;
93 let started!: () => void;
94 const operationStarted = new Promise<void>((resolve) => {
95 started = resolve;
96 });
97
98 const pending = withPreviewAutomationFocus(async () => {
99 setActiveElement(body);
100 started();
101 await new Promise<void>((resolve) => {
102 finish = resolve;
103 });
104 });
105
106 await operationStarted;
107 setActiveElement(newerControl);
108 // This models a newer programmatic or user focus event in the host.
109 dispatchDocument("focusin", newerControl);
110 finish();
111 await pending;
112
113 expect(composer.focus).not.toHaveBeenCalled();
114 expect(globalThis.document.activeElement).toBe(newerControl);
115 });
116
117 it("does not restore a detached prior element", async () => {
118 const detachedComposer = new MockHTMLElement();
119 const { body } = setupDocument(detachedComposer);
120 await withPreviewAutomationFocus(async () => {
121 detachedComposer.isConnected = false;
122 setActiveElement(body);
123 });
124 expect(detachedComposer.focus).not.toHaveBeenCalled();
125 });
126
127 it("does not restore when the document is unfocused at invocation", async () => {
128 const unfocusedComposer = new MockHTMLElement();
129 const unfocused = setupDocument(unfocusedComposer, false);
130 setActiveElement(unfocusedComposer);
131 await withPreviewAutomationFocus(async () => {
132 setActiveElement(unfocused.body);
133 });
134 expect(unfocusedComposer.focus).not.toHaveBeenCalled();
135 });
136
137 it("does not restore when the document loses focus during the operation", async () => {
138 const composer = new MockHTMLElement();
139 const { body, setDocumentFocused } = setupDocument(composer);
140 await withPreviewAutomationFocus(async () => {
141 setActiveElement(body);
142 setDocumentFocused(false);
143 });
144 expect(composer.focus).not.toHaveBeenCalled();
145 });
146
147 it.each(["pointerdown", "keydown"] as const)(
148 "preserves user focus after a native transfer and %s",
149 async (userEvent) => {
150 const composer = new MockHTMLElement();
151 const hostButton = new MockHTMLElement();
152 const { dispatchDocument, dispatchWindow } = setupDocument(composer);
153
154 await withPreviewAutomationFocus(async () => {
155 dispatchWindow("blur");
156 dispatchWindow("focus");
157 dispatchDocument(userEvent, hostButton);
158 setActiveElement(hostButton);
159 dispatchDocument("focusin", hostButton);
160 });
161
162 expect(composer.focus).not.toHaveBeenCalled();
163 expect(globalThis.document.activeElement).toBe(hostButton);
164 },
165 );
166
167 it("does not mask the operation rejection when restoration fails", async () => {
168 const composer = new MockHTMLElement();
169 const { body } = setupDocument(composer);
170 const error = new Error("press failed");
171 composer.focus.mockImplementation(() => {
172 throw new Error("focus failed");
173 });
174
175 await expect(
176 withPreviewAutomationFocus(async () => {
177 setActiveElement(body);
178 throw error;
179 }),
180 ).rejects.toBe(error);
181 });
182
183 it("does not mask the operation result when restoration fails", async () => {
184 const composer = new MockHTMLElement();
185 const { body } = setupDocument(composer);
186 composer.focus.mockImplementation(() => {
187 throw new Error("focus failed");
188 });
189
190 await expect(
191 withPreviewAutomationFocus(async () => {
192 setActiveElement(body);
193 return "pressed";
194 }),
195 ).resolves.toBe("pressed");
196 });
197
198 it("does not let an older overlapping operation reclaim focus", async () => {
199 const composer = new MockHTMLElement();
200 const { body } = setupDocument(composer);
201 let finish!: () => void;
202 let firstStarted!: () => void;
203 const firstIsStarted = new Promise<void>((resolve) => {
204 firstStarted = resolve;
205 });
206
207 const first = withPreviewAutomationFocus(async () => {
208 setActiveElement(body);
209 firstStarted();
210 await new Promise<void>((resolve) => {
211 finish = resolve;
212 });
213 });
214 await firstIsStarted;
215
216 const second = withPreviewAutomationFocus(async () => {
217 setActiveElement(body);
218 });
219
220 await second;
221 expect(composer.focus).not.toHaveBeenCalled();
222 finish();
223 await first;
224 expect(composer.focus).not.toHaveBeenCalled();
225 });
226});