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

HtmlRenderDialog.browser.test.tsx

201 lines6.9 KB

1import { act } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4import { page, userEvent } from "vite-plus/test/browser";
5import { htmlRenderTheme, HTML_RENDER_DEFAULT_FONTS } from "@t3tools/shared/htmlRender";
6import { T3_CODE_DARK_THEME_COLORS } from "@t3tools/shared/themePalettes";
7import { EnvironmentId, ThreadId } from "@t3tools/contracts";
8​
9import "~/index.css";
10​
11import { HtmlRenderDialog } from "./HtmlRenderDialog";
12import { HtmlRenderFrame } from "./HtmlRenderFrame";
13​
14const { cachedUrl, refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({
15 cachedUrl: { lifeMs: 60 * 60_000 },
16 refresh: vi.fn(),
17 showError: vi.fn(),
18 openLink: vi.fn(),
19 openChangeRequestLink: vi.fn(),
20}));
21vi.mock(import("~/browser/useOpenLink"), async (original) => ({
22 ...(await original()),
23 useOpenLink: () => openLink,
24}));
25vi.mock(import("~/lib/openPullRequestLink"), async (original) => ({
26 ...(await original()),
27 useOpenChangeRequestLink: () => openChangeRequestLink,
28}));
29vi.mock(import("~/assets/assetUrls"), async (original) => ({
30 ...(await original()),
31 useAssetUrlState: () => ({
32 _tag: "Success",
33 url: "https://environment.test/original.html",
34 expiresAt: Date.now() + cachedUrl.lifeMs,
35 }),
36 useAssetUrlRefresh: () => refresh,
37}));
38vi.mock(import("../ui/toast"), async (original) => {
39 const actual = await original();
40 return { ...actual, toastManager: { ...actual.toastManager, add: showError } };
41});
42vi.mock(import("~/hooks/useHtmlRenderTheme"), async (original) => ({
43 ...(await original()),
44 useHtmlRenderTheme: () =>
45 htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark", HTML_RENDER_DEFAULT_FONTS),
46}));
47​
48let root: Root;
49let container: HTMLDivElement;
50const onClose = vi.fn();
51​
52beforeEach(async () => {
53 refresh.mockReset();
54 cachedUrl.lifeMs = 60 * 60_000;
55 openLink.mockReset().mockResolvedValue(undefined);
56 openChangeRequestLink.mockReset().mockReturnValue(false);
57 showError.mockClear();
58 onClose.mockClear();
59 container = document.createElement("div");
60 document.body.append(container);
61 root = createRoot(container);
62 await act(() =>
63 root.render(
64 <HtmlRenderDialog
65 src="https://environment.test/page.html"
66 title="Diagram"
67 onClose={onClose}
68 />,
69 ),
70 );
71});
72​
73afterEach(async () => {
74 await act(() => root.unmount());
75 container.remove();
76});
77​
78function button(label: string) {
79 return page.getByRole("button", { name: label, exact: true });
81​
82// A trusted click, so the page also gets the user activation the link handler requires.
83async function click(label: string) {
84 await button(label).click();
86​
87it("zooms the loaded page within bounds and resets without reloading it", async () => {
88 const frame = document.querySelector("iframe")!;
89 const src = frame.src;
90 for (let step = 0; step < 4; step += 1) await click("Zoom in");
91 await expect.element(button("Zoom in")).toBeDisabled();
92 expect(frame.parentElement!.style.getPropertyValue("zoom")).toBe("2");
93 for (let step = 0; step < 6; step += 1) await click("Zoom out");
94 await expect.element(button("Zoom out")).toBeDisabled();
95 expect(frame.parentElement!.style.getPropertyValue("zoom")).toBe("0.5");
96 await click("Reset zoom");
97 expect(frame.parentElement!.style.getPropertyValue("zoom")).toBe("1");
98 expect(document.querySelector("iframe")).toBe(frame);
99 expect(frame.src).toBe(src);
100 expect(frame.getAttribute("sandbox")).toBe("allow-scripts allow-forms");
101});
102​
103it("closes with the close button or Escape", async () => {
104 await click("Close");
105 expect(onClose).toHaveBeenCalledOnce();
106 onClose.mockClear();
107 await userEvent.keyboard("{Escape}");
108 expect(onClose).toHaveBeenCalledOnce();
109});
110​
111async function renderInline() {
112 // Async so a URL minted at mount lands inside act.
113 await act(async () =>
114 root.render(
115 <HtmlRenderFrame
116 environmentId={EnvironmentId.make("environment")}
117 htmlRender={{ attachmentId: "html", title: "Diagram", height: 400 }}
118 threadRef={{
119 environmentId: EnvironmentId.make("environment"),
120 threadId: ThreadId.make("thread"),
121 }}
122 />,
123 ),
124 );
126​
127it("offers only full screen and opens with the inline URL while keeping the inline page loaded", async () => {
128 await renderInline();
129 expect(document.querySelector('[aria-label="Open in panel"]')).toBeNull();
130 const inlineFrame = document.querySelector("iframe")!;
131 const originalSrc = inlineFrame.src;
132 const expandButton = document.querySelector<HTMLButtonElement>(
133 '[aria-label="Open full screen"]',
134 )!;
135 expandButton.focus();
136 await click("Open full screen");
137 expect(refresh).not.toHaveBeenCalled();
138 expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(
139 "https://environment.test/original.html#",
140 );
141 expect(inlineFrame.src).toBe(originalSrc);
142 await click("Close");
143 expect(document.querySelector('[role="dialog"]')).toBeNull();
144 expect(document.querySelector("iframe")).toBe(inlineFrame);
145 expect(document.activeElement).toBe(expandButton);
146});
147​
148async function renderInlineNearExpiry() {
149 cachedUrl.lifeMs = 60_000;
150 refresh.mockResolvedValueOnce("https://environment.test/inline.html");
151 await renderInline();
152 expect(refresh).toHaveBeenCalledOnce();
154​
155it("opens full screen with a fresh URL when the inline one is near expiry", async () => {
156 await renderInlineNearExpiry();
157 refresh.mockResolvedValue("https://environment.test/renewed.html");
158 await click("Open full screen");
159 expect(refresh).toHaveBeenCalledTimes(2);
160 expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain(
161 "https://environment.test/renewed.html#",
162 );
163});
164​
165it("routes links from the expanded page through its thread", async () => {
166 await renderInline();
167 openChangeRequestLink.mockReturnValue(true);
168 await click("Open full screen");
169 const frame = document.querySelector<HTMLIFrameElement>('[role="dialog"] iframe')!;
170 frame.focus();
171 const url = "https://github.com/pingdotgg/t3code/pull/17561";
172 await act(() => {
173 window.dispatchEvent(
174 new MessageEvent("message", {
175 source: frame.contentWindow,
176 data: { jsonrpc: "2.0", id: "link", method: "ui/open-link", params: { url } },
177 }),
178 );
179 });
180 expect(openChangeRequestLink).toHaveBeenCalledWith(
181 expect.objectContaining({ metaKey: false, ctrlKey: false }),
182 url,
183 undefined,
184 EnvironmentId.make("environment"),
185 );
186 expect(openLink).not.toHaveBeenCalled();
187});
188​
189it.each([null, new Error("Disconnected")])(
190 "reports an unavailable URL instead of opening a blank page: %s",
191 async (failure) => {
192 await renderInlineNearExpiry();
193 if (failure === null) refresh.mockResolvedValue(null);
194 else refresh.mockRejectedValue(failure);
195 await click("Open full screen");
196 expect(document.querySelector('[role="dialog"]')).toBeNull();
197 expect(showError).toHaveBeenCalledWith(
198 expect.objectContaining({ type: "error", title: "Page unavailable" }),
199 );
200 },
201);