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

PreviewView.browser.test.tsx

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