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

HtmlRenderDialog.test.tsx

203 lines6.9 KB

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