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

PreviewView.browser.test.tsx

346 lines12.7 KB

1import {
2 BUILT_IN_BROWSER_PROFILES,
3 DEFAULT_BROWSER_PROFILE_ID,
4 DEFAULT_PREVIEW_APPEARANCE,
5 DEFAULT_PREVIEW_ZOOM_FACTOR,
6 EnvironmentId,
7 FILL_PREVIEW_VIEWPORT,
8 ThreadId,
9} from "@t3tools/contracts";
10import { type ComponentProps } from "react";
11import { describe, expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13​
14import "~/index.css";
15import { act, render } from "../../../test/render";
16​
17import type { PreviewableServer } from "./useDiscoveredLocalServers";
18​
19const mocks = vi.hoisted(() => ({
20 navigate: vi.fn(async (_tabId: string, _url: string): Promise<void> => undefined),
21 rememberPreviewUrl: vi.fn(),
22 readPreparedConnection: vi.fn(() => ({ httpBaseUrl: "http://172.25.85.75:3773" })),
23 readEnvironmentScope: vi.fn((_environmentId?: unknown, _scope?: unknown) => true),
24 setAnnotationSendEnabled: vi.fn(async (_tabId: string, _enabled: boolean): Promise<void> => {}),
25 cancelPickElement: vi.fn(async (_tabId: string) => undefined),
26 openPictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
27 closePictureInPicture: vi.fn(async (_tabId: string): Promise<void> => undefined),
28 pickElement: vi.fn(),
29 addPreviewAnnotation: vi.fn(),
30 addImage: vi.fn(),
31 pictureInPicture: false,
32 showEmptyState: false,
33 loading: false,
34 nativeServerTab: false,
35 serverEpoch: null as string | null,
36 servers: [] as PreviewableServer[],
37 recordingTabIds: new Set<string>(),
38 recordingRuntimeTabId: null as string | null,
39 recordVisitForThread: vi.fn(),
40}));
41​
42const STUB_BROWSER_DEFAULTS = {
43 viewport: FILL_PREVIEW_VIEWPORT,
44 zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
45 appearance: DEFAULT_PREVIEW_APPEARANCE,
46 autoShowFloatingPreview: true,
47 profiles: BUILT_IN_BROWSER_PROFILES,
48 profileId: DEFAULT_BROWSER_PROFILE_ID,
49};
50​
51// The desktop bridge only exists inside Electron; the view reads it once at import.
52vi.mock(import("./previewBridge"), async (original) => ({
53 ...(await original()),
54 previewBridge: {
55 navigate: mocks.navigate,
56 pickElement: mocks.pickElement,
57 annotationVoice: { onEvent: () => () => {}, update: async () => {} },
58 setAnnotationSendEnabled: mocks.setAnnotationSendEnabled,
59 cancelPickElement: mocks.cancelPickElement,
60 refresh: vi.fn(async () => undefined),
61 goBack: vi.fn(async () => undefined),
62 goForward: vi.fn(async () => undefined),
63 hardReload: vi.fn(async () => undefined),
64 openDevTools: vi.fn(async () => undefined),
65 setColorScheme: vi.fn(async () => undefined),
66 zoomIn: vi.fn(async () => undefined),
67 zoomOut: vi.fn(async () => undefined),
68 resetZoom: vi.fn(async () => undefined),
69 clearCookies: vi.fn(async () => undefined),
70 clearCache: vi.fn(async () => undefined),
71 pictureInPicture: {
72 open: mocks.openPictureInPicture,
73 close: mocks.closePictureInPicture,
74 },
75 } as never,
76}));
77vi.mock(import("~/browserHistoryStore"), async (original) => ({
78 ...(await original()),
79 recordVisitForThread: mocks.recordVisitForThread,
80}));
81vi.mock(import("~/state/session"), async (original) => ({
82 ...(await original()),
83 readPreparedConnection: mocks.readPreparedConnection as never,
84 readEnvironmentScope: mocks.readEnvironmentScope,
85 useEnvironmentScope: mocks.readEnvironmentScope,
86}));
87vi.mock(import("~/browser/browserDefaults"), async (original) => ({
88 ...(await original()),
89 useBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
90 getBrowserDefaults: () => STUB_BROWSER_DEFAULTS,
91}));
92vi.mock(import("~/previewStateStore"), async (original) => ({
93 ...(await original()),
94 rememberPreviewUrl: mocks.rememberPreviewUrl,
95 useThreadPreviewState: (() => ({
96 activeTabId: "tab-1",
97 serverEpoch: mocks.serverEpoch,
98 desktopByTabId: {
99 "tab-1": {
100 hasWebContents: true,
101 canGoBack: false,
102 canGoForward: false,
103 loading: mocks.loading,
104 zoomFactor: 1,
105 pictureInPicture: mocks.pictureInPicture,
106 colorScheme: "system",
107 audioMuted: false,
108 audible: false,
109 controller: "none",
110 },
111 },
112 recentlySeenUrls: [],
113 sessions: mocks.showEmptyState
114 ? {}
115 : {
116 "tab-1": {
117 threadId: "thread-1",
118 tabId: "tab-1",
119 runtime: mocks.nativeServerTab ? "server" : "desktop",
120 navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" },
121 canGoBack: false,
122 canGoForward: false,
123 updatedAt: "2026-07-13T00:00:00.000Z",
124 },
125 },
126 })) as never,
127}));
128vi.mock(import("~/state/environments"), async (original) => ({
129 ...(await original()),
130 useEnvironment: (() => ({ label: "WSL" })) as never,
131 useEnvironmentHttpBaseUrl: () => "http://172.25.85.75:3773",
132 usePrimaryEnvironmentId: () => null,
133}));
134vi.mock(import("~/browser/browserRecording"), async (original) => ({
135 ...(await original()),
136 findActiveBrowserRecordingRuntimeTabId: () => mocks.recordingRuntimeTabId,
137 useActiveBrowserRecordingTabIds: () => mocks.recordingTabIds,
138}));
139vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
140 ...(await original()),
141 useDiscoveredLocalServers: () => mocks.servers,
142}));
143vi.mock(import("./usePreviewSession"), async (original) => ({
144 ...(await original()),
145 usePreviewSession: () => {},
146}));
147​
148vi.mock(import("~/browser/previewRuntime"), async (original) => ({
149 ...(await original()),
150 useRendersServerTabNatively: () => mocks.nativeServerTab,
151}));
152​
153vi.mock(import("~/browser/browserViewportActions"), { spy: true });
154​
155import { useComposerDraftStore } from "~/composerDraftStore";
156import { useBrowserPointerStore } from "~/browser/browserPointerStore";
157import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
158import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
159import { dispatchPreviewAction } from "./previewActionBus";
160import { PreviewView } from "./PreviewView";
161import { ToastProvider } from "~/components/ui/toast";
162​
163const TEST_THREAD_REF = {
164 environmentId: EnvironmentId.make("environment-1"),
165 threadId: ThreadId.make("thread-1"),
166} as const;
167const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
168​
169function view(onSendAnnotation?: ComponentProps<typeof PreviewView>["onSendAnnotation"]) {
170 return (
171 <PreviewView
172 threadRef={TEST_THREAD_REF}
173 tabId="tab-1"
174 visible
175 {...(onSendAnnotation ? { onSendAnnotation } : {})}
176 />
177 );
179​
180function annotation(id: string, screenshot: unknown = null) {
181 return {
182 id,
183 pageUrl: "https://example.com/dashboard",
184 pageTitle: "Dashboard",
185 comment: "Tighten this spacing",
186 elements: [],
187 regions: [],
188 strokes: [],
189 styleChanges: [],
190 screenshot,
191 createdAt: "2026-07-27T00:00:00.000Z",
192 };
194​
195// The mocked modules and stores are shared by the whole file, so every test starts by
196// resetting them.
197function setup() {
198 vi.clearAllMocks();
199 mocks.readEnvironmentScope.mockReset().mockReturnValue(true);
200 mocks.setAnnotationSendEnabled.mockReset().mockResolvedValue(undefined);
201 mocks.pickElement.mockReset();
202 mocks.pictureInPicture = false;
203 mocks.showEmptyState = false;
204 mocks.loading = false;
205 mocks.nativeServerTab = false;
206 mocks.serverEpoch = null;
207 mocks.servers = [];
208 mocks.recordingTabIds = new Set();
209 mocks.recordingRuntimeTabId = null;
210 useComposerDraftStore.setState({
211 addPreviewAnnotation: mocks.addPreviewAnnotation,
212 addImage: mocks.addImage,
213 });
214 usePreviewMiniPlayerStore.setState({ byThreadKey: {} });
215 useBrowserPointerStore.setState({ byTabId: {} });
217​
218describe("PreviewView", () => {
219 it.each(["mailto:alice@example.com", "http://"])(
220 "reports rejected address %s without navigating or recording it",
221 async (address) => {
222 setup();
223 await using _screen = await render(<ToastProvider timeout={0}>{view()}</ToastProvider>);
224 const input = page.getByPlaceholder("Search or enter URL");
225 await input.fill(address);
226 await userEvent.keyboard("{Enter}");
227​
228 await expect.element(page.getByText("Could not open this address")).toBeVisible();
229 await expect.element(page.getByText("Enter an http or https URL.")).toBeVisible();
230 expect(mocks.navigate).not.toHaveBeenCalled();
231 expect(mocks.recordVisitForThread).not.toHaveBeenCalled();
232 await userEvent.click(page.getByRole("button", { name: "Dismiss notification" }));
233 },
234 );
235​
236 it("retains the annotation locally when its own environment loses access during capture", async () => {
237 setup();
238 const picked = annotation("annotation-revoked");
239 const onSendAnnotation = vi.fn();
240 let submitPick: (() => void) | undefined;
241 mocks.pickElement.mockImplementationOnce(
242 () =>
243 new Promise((resolve) => {
244 submitPick = () => resolve({ annotation: picked, submission: "send" });
245 }),
246 );
247 await using screen = await render(view(onSendAnnotation));
248 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
249 await vi.waitFor(() => expect(submitPick).toBeDefined());
250 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
251​
252 mocks.readEnvironmentScope.mockImplementation(
253 (environmentId?: unknown) => environmentId !== TEST_THREAD_REF.environmentId,
254 );
255 await screen.rerender(view(onSendAnnotation));
256 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, false);
257 await act(async () => submitPick!());
258 await vi.waitFor(() =>
259 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, picked),
260 );
261 expect(onSendAnnotation).not.toHaveBeenCalled();
262​
263 mocks.readEnvironmentScope.mockReturnValue(true);
264 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
265 await screen.rerender(view(onSendAnnotation));
266 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
267 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(picked, null));
268 expect(mocks.setAnnotationSendEnabled).toHaveBeenLastCalledWith(TEST_RUNTIME_TAB_ID, true);
269 });
270​
271 it("still sends annotation text when the picked element's crop is malformed", async () => {
272 setup();
273 const picked = annotation("annotation-2", {
274 dataUrl: "data:image/png;base64,%%%",
275 width: 10,
276 height: 10,
277 cropRect: { x: 0, y: 0, width: 10, height: 10 },
278 });
279 const onSendAnnotation = vi.fn();
280 mocks.pickElement.mockResolvedValue({ annotation: picked, submission: "send" });
281 await using _screen = await render(view(onSendAnnotation));
282 await userEvent.click(page.getByRole("button", { name: "Annotate preview" }));
283​
284 const sent = { ...picked, screenshot: null };
285 await vi.waitFor(() => expect(onSendAnnotation).toHaveBeenCalledWith(sent, null));
286 expect(mocks.addPreviewAnnotation).toHaveBeenCalledWith(TEST_THREAD_REF, sent);
287 expect(mocks.addImage).not.toHaveBeenCalled();
288 });
289​
290 it("focuses and selects the address from forwarded desktop actions only while visible", async () => {
291 setup();
292 using stack = new DisposableStack();
293 const previousBridge = window.desktopBridge;
294 stack.defer(() => {
295 if (previousBridge) window.desktopBridge = previousBridge;
296 else delete window.desktopBridge;
297 });
298 const listeners = new Set<(action: string) => void>();
299 window.desktopBridge = {
300 getWindowZoomFactor: () => 1,
301 onMenuAction: (listener: (action: string) => void) => {
302 listeners.add(listener);
303 return () => {
304 listeners.delete(listener);
305 };
306 },
307 } as NonNullable<typeof window.desktopBridge>;
308 await using screen = await render(view());
309 const address = page.getByRole("textbox");
310 const input = address.element() as HTMLInputElement;
311 const forward = () =>
312 act(() => {
313 listeners.forEach((listener) => listener("preview.focusUrl"));
314 });
315​
316 await forward();
317 await expect.element(address).toHaveFocus();
318 expect(input.selectionStart).toBe(0);
319 expect(input.selectionEnd).toBe(input.value.length);
320 await act(() => input.blur());
321 await forward();
322 await expect.element(address).toHaveFocus();
323​
324 await act(() => input.blur());
325 await screen.rerender(
326 <PreviewView threadRef={TEST_THREAD_REF} tabId="tab-1" visible={false} />,
327 );
328 await forward();
329 await expect.element(address).not.toHaveFocus();
330 expect(listeners.size).toBe(0);
331 });
332​
333 it("focuses the address bar each time the focus-url shortcut fires", async () => {
334 setup();
335 await using _screen = await render(view());
336 const address = page.getByRole("textbox");
337​
338 act(() => dispatchPreviewAction("focus-url"));
339 await expect.element(address).toHaveFocus();
340​
341 (address.element() as HTMLInputElement).blur();
342 await expect.element(address).not.toHaveFocus();
343 act(() => dispatchPreviewAction("focus-url"));
344 await expect.element(address).toHaveFocus();
345 });
346});