Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2import { page, userEvent } from "vite-plus/test/browser";
3
4import type { ReactNode } from "react";
5
6import { act, render } from "../../../test/render";
7import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
8import { ThemeEditorPanel } from "./ThemeEditorPanel";
9
10function dragHeader(panel: HTMLElement, toX: number, toY: number) {
11 const header = panel.querySelector<HTMLElement>("h2")!.closest<HTMLElement>(".cursor-grab")!;
12 const rect = panel.getBoundingClientRect();
13 const start = { clientX: rect.left + 40, clientY: rect.top + 10 };
14 const init = { bubbles: true, button: 0, pointerId: 1 };
15 header.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...start }));
16 header.dispatchEvent(
17 new PointerEvent("pointermove", { ...init, clientX: toX + 40, clientY: toY + 10 }),
18 );
19 header.dispatchEvent(new PointerEvent("pointerup", init));
20}
21
22function dragResizeHandle(panel: HTMLElement, byX: number) {
23 const handle = panel.querySelector<HTMLElement>(".cursor-se-resize")!;
24 const rect = handle.getBoundingClientRect();
25 const init = { bubbles: true, button: 0, pointerId: 2 };
26 const start = { clientX: rect.left + 4, clientY: rect.top + 4 };
27 handle.dispatchEvent(new PointerEvent("pointerdown", { ...init, ...start }));
28 handle.dispatchEvent(
29 new PointerEvent("pointermove", {
30 ...init,
31 clientX: start.clientX + byX,
32 clientY: start.clientY,
33 }),
34 );
35 handle.dispatchEvent(new PointerEvent("pointerup", init));
36}
37
38function pointerAt(target: HTMLElement, type: string, xFraction: number) {
39 const rect = target.getBoundingClientRect();
40 target.dispatchEvent(
41 new PointerEvent(type, {
42 bubbles: true,
43 button: 0,
44 pointerId: 3,
45 clientX: rect.left + rect.width * xFraction,
46 clientY: rect.top + rect.height / 2,
47 }),
48 );
49}
50
51async function renderPanel(appContent?: ReactNode) {
52 await page.viewport(1280, 900);
53 await using stack = new AsyncDisposableStack();
54 // Synthetic pointer ids are not active pointers, so the browser would reject capture.
55 stack.use(vi.spyOn(HTMLElement.prototype, "setPointerCapture").mockImplementation(() => {}));
56 // Tailwind is not loaded here; give the panel its fixed, card-sized box.
57 const style = document.head.appendChild(document.createElement("style"));
58 style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";
59 stack.defer(() => style.remove());
60 const screen = stack.use(
61 await render(
62 <>
63 {appContent}
64 <ThemeEditorPanel
65 open
66 onOpenChange={() => {}}
67 onSaved={() => true}
68 editingTheme={null}
69 initialAppearance="dark"
70 restoreTheme={() => {}}
71 />
72 </>,
73 ),
74 );
75 const panel = screen.getByRole("dialog", { name: "Create theme" });
76 await expect.element(panel).toBeVisible();
77 const owned = stack.move();
78 return {
79 panel: panel.element() as HTMLElement,
80 [Symbol.asyncDispose]: () => owned.disposeAsync(),
81 };
82}
83
84// The editor floats beside the Settings dialog, whose Esc handler sits on the document.
85async function renderBesideSettings() {
86 const onSettingsOpenChange = vi.fn();
87 const onEditorOpenChange = vi.fn();
88 await using stack = new AsyncDisposableStack();
89 stack.use(
90 await render(
91 <>
92 <Dialog onOpenChange={onSettingsOpenChange} open>
93 <DialogPopup>
94 <DialogTitle>Settings</DialogTitle>
95 </DialogPopup>
96 </Dialog>
97 <ThemeEditorPanel
98 open
99 onOpenChange={onEditorOpenChange}
100 onSaved={() => true}
101 editingTheme={null}
102 initialAppearance="light"
103 restoreTheme={() => {}}
104 />
105 </>,
106 ),
107 );
108 // Settings moves focus in on a later frame; landing after the test focuses the editor, it steals it.
109 await expect.element(page.getByRole("button", { name: "Close" })).toHaveFocus();
110 const screen = stack.move();
111 return {
112 onSettingsOpenChange,
113 onEditorOpenChange,
114 [Symbol.asyncDispose]: () => screen.disposeAsync(),
115 };
116}
117
118const IME_ESCAPE_229 = { key: "Escape", keyCode: 229, bubbles: true, cancelable: true };
119
120async function pressImeEscapes(target: HTMLElement) {
121 // The bare 229 goes first, before a compositionend opens Base UI's own composition window.
122 for (const { compositionEnd, ...composition } of [
123 { key: "Escape", isComposing: false, keyCode: 229, compositionEnd: false },
124 { key: "Escape", isComposing: true, keyCode: 27, compositionEnd: false },
125 // Safari ends the composition just before the Escape keydown.
126 { key: "Escape", isComposing: false, keyCode: 229, compositionEnd: true },
127 ]) {
128 const keydown = new KeyboardEvent("keydown", {
129 ...composition,
130 bubbles: true,
131 cancelable: true,
132 });
133 await act(() => {
134 if (compositionEnd)
135 target.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
136 target.dispatchEvent(keydown);
137 });
138 expect(keydown.defaultPrevented).toBe(false);
139 }
140}
141
142// The modal Settings dialog marks the editor inert, hiding it from role queries and pointer input.
143async function editorElement(selector: string) {
144 const query = () => document.querySelector<HTMLElement>(`[data-theme-editor-panel] ${selector}`);
145 await expect.poll(query).toBeTruthy();
146 return query()!;
147}
148
149describe("ThemeEditorPanel", () => {
150 it("keeps its left edge when resized after the window shrank", async () => {
151 await using view = await renderPanel();
152 dragHeader(view.panel, 700, 40);
153 await expect.poll(() => view.panel.style.left).toBe("700px");
154
155 await page.viewport(600, 900);
156 await expect.poll(() => Number.parseFloat(view.panel.style.left)).toBeLessThan(600);
157 const clampedLeft = view.panel.style.left;
158
159 dragResizeHandle(view.panel, -100);
160 await expect.poll(() => view.panel.style.width).not.toBe("");
161 expect(view.panel.style.left).toBe(clampedLeft);
162 });
163
164 it("returns to where the user left it when the window shrinks and grows back", async () => {
165 await page.viewport(1280, 900);
166 // Synthetic pointer ids are not active pointers, so the browser would reject capture.
167 using _capture = vi
168 .spyOn(HTMLElement.prototype, "setPointerCapture")
169 .mockImplementation(() => {});
170 // Tailwind is not loaded here; give the panel its fixed, card-sized box.
171 const style = document.head.appendChild(document.createElement("style"));
172 style.textContent = "[data-theme-editor-panel]{position:fixed;width:400px;height:300px}";
173 using _style = { [Symbol.dispose]: () => style.remove() };
174 await using screen = await render(
175 <ThemeEditorPanel
176 open
177 onOpenChange={() => {}}
178 onSaved={() => true}
179 editingTheme={null}
180 initialAppearance="dark"
181 restoreTheme={() => {}}
182 />,
183 );
184 const panel = screen.getByRole("dialog", { name: "Create theme" });
185 await expect.element(panel).toBeVisible();
186
187 dragHeader(panel.element() as HTMLElement, 700, 40);
188 await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");
189
190 await page.viewport(600, 900);
191 await expect
192 .poll(() => Number.parseFloat((panel.element() as HTMLElement).style.left))
193 .toBeLessThan(600);
194
195 await page.viewport(1280, 900);
196 await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px");
197 });
198
199 it("restores the colors from before the picker opened when Escape closes it", async () => {
200 await using _view = await renderPanel();
201 const hex = page.getByRole("textbox", { name: "Accent hex value" });
202 const original = (hex.element() as HTMLInputElement).value;
203 await userEvent.click(page.getByRole("button", { name: "Choose Accent color" }));
204 const hue = page.getByRole("slider", { name: "Accent hue" });
205 await expect.element(hue).toBeInTheDocument();
206 const hueSlider = hue.element() as HTMLElement;
207
208 await act(async () => {
209 pointerAt(hueSlider, "pointerdown", 0.5);
210 pointerAt(hueSlider, "pointerup", 0.5);
211 });
212 await expect.element(hex).not.toHaveValue(original);
213 const edited = (hex.element() as HTMLInputElement).value;
214
215 const pickerHex = page.getByRole("textbox", { name: "Accent picker hex value" });
216 await act(() =>
217 pickerHex.element().dispatchEvent(new KeyboardEvent("keydown", IME_ESCAPE_229)),
218 );
219 await expect.element(hue).toBeInTheDocument();
220 expect((hex.element() as HTMLInputElement).value).toBe(edited);
221
222 await act(async () => {
223 pointerAt(hueSlider, "pointerdown", 0.25);
224 hueSlider.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Escape" }));
225 // The drag keeps going while the picker animates out.
226 pointerAt(hueSlider, "pointermove", 0.75);
227 pointerAt(hueSlider, "pointerup", 0.75);
228 });
229 expect((hex.element() as HTMLInputElement).value).toBe(original);
230 });
231
232 it("keeps the typed text while backspacing the background hex past valid shorthand", async () => {
233 await using _view = await renderPanel();
234 const hex = page.getByRole("textbox", { name: "Background hex value" });
235 await userEvent.fill(hex, "#222222");
236 await expect.element(hex).toHaveValue("#222222");
237
238 // Four- and three-digit prefixes are valid shorthand; the guided palette must not rewrite them.
239 for (const expected of ["#22222", "#2222", "#222", "#22", "#2", "#", ""]) {
240 await userEvent.keyboard("{Backspace}");
241 await expect.element(hex).toHaveValue(expected);
242 }
243
244 await userEvent.keyboard("#3366cc");
245 await expect.element(hex).toHaveValue("#3366cc");
246 await act(async () => (hex.element() as HTMLInputElement).blur());
247 await expect.element(hex).toHaveValue("#3366cc");
248 });
249
250 it("commits a typed shorthand hex when inspecting an advanced color switches modes", async () => {
251 await using _view = await renderPanel(<div className="bg-sidebar" data-testid="app-sidebar" />);
252 await userEvent.click(page.getByRole("button", { name: "Inspect app colors" }));
253 await userEvent.fill(page.getByRole("textbox", { name: "Background hex value" }), "#abc");
254
255 // Inspect mode cancels the pointerdown, so the hex field keeps focus while it unmounts.
256 const sidebar = page.getByTestId("app-sidebar").element() as HTMLElement;
257 await act(async () => pointerAt(sidebar, "pointerdown", 0.5));
258
259 await expect
260 .element(page.getByRole("switch", { name: "Use advanced theme colors" }))
261 .toBeChecked();
262 await expect
263 .element(page.getByRole("textbox", { name: "Background hex value" }))
264 .toHaveValue("#aabbcc");
265 });
266
267 it("closes on Escape without closing Settings", async () => {
268 await using view = await renderBesideSettings();
269 const input = await editorElement("input");
270 input.focus();
271 await pressImeEscapes(input);
272 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
273 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
274
275 await userEvent.keyboard("{Escape}");
276
277 expect(view.onEditorOpenChange).toHaveBeenCalledWith(false);
278 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
279 });
280
281 it("leaves inspection on Escape without closing the editor or Settings", async () => {
282 await using view = await renderBesideSettings();
283 (await editorElement('[aria-label="Inspect app colors"]')).click();
284 await editorElement('[aria-label="Cancel inspecting app colors"]');
285 await pressImeEscapes(await editorElement("input"));
286 await editorElement('[aria-label="Cancel inspecting app colors"]');
287 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
288 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
289
290 await userEvent.keyboard("{Escape}");
291
292 await editorElement('[aria-label="Inspect app colors"]');
293 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
294 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
295 });
296
297 it("closes on a second Escape from the Custom CSS editor without closing Settings", async () => {
298 await using view = await renderBesideSettings();
299 await editorElement("button[aria-expanded]");
300 const cssToggle = Array.from(
301 document.querySelectorAll<HTMLButtonElement>(
302 "[data-theme-editor-panel] button[aria-expanded]",
303 ),
304 ).find((button) => button.textContent?.includes("Custom CSS"));
305 expect(cssToggle).toBeDefined();
306 cssToggle!.click();
307
308 const editor = await editorElement('textarea[aria-label="Custom CSS"]');
309 editor.focus();
310 const imeEscape = new KeyboardEvent("keydown", IME_ESCAPE_229);
311 await act(() => editor.dispatchEvent(imeEscape));
312 expect(imeEscape.defaultPrevented).toBe(false);
313 await userEvent.keyboard("{Escape}");
314 editor.dispatchEvent(
315 new KeyboardEvent("keydown", {
316 bubbles: true,
317 cancelable: true,
318 key: "Escape",
319 repeat: true,
320 }),
321 );
322
323 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
324 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
325
326 await userEvent.keyboard("{Escape}");
327
328 expect(view.onEditorOpenChange).toHaveBeenCalledWith(false);
329 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
330 });
331
332 it("clears the advanced color filter on Escape before closing on a second Escape", async () => {
333 await using view = await renderBesideSettings();
334 (await editorElement('[aria-label="Use advanced theme colors"]')).click();
335
336 const filter = (await editorElement('input[aria-label="Filter colors"]')) as HTMLInputElement;
337 filter.focus();
338 await userEvent.keyboard("accent");
339 await expect.poll(() => filter.value).toBe("accent");
340
341 await userEvent.keyboard("{Escape}");
342 await expect.poll(() => filter.value).toBe("");
343 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
344 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
345
346 await act(async () => {
347 filter.dispatchEvent(
348 new KeyboardEvent("keydown", {
349 bubbles: true,
350 cancelable: true,
351 key: "Escape",
352 repeat: true,
353 }),
354 );
355 });
356 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
357 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
358
359 await userEvent.keyboard("{Escape}");
360 expect(view.onEditorOpenChange).toHaveBeenCalledWith(false);
361 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
362 });
363
364 it("keeps the color filter on an IME Escape", async () => {
365 await using view = await renderBesideSettings();
366 (await editorElement('[aria-label="Use advanced theme colors"]')).click();
367
368 const filter = (await editorElement('input[aria-label="Filter colors"]')) as HTMLInputElement;
369 filter.focus();
370 await userEvent.keyboard("accent");
371 await expect.poll(() => filter.value).toBe("accent");
372
373 await pressImeEscapes(filter);
374 expect(filter.value).toBe("accent");
375 expect(view.onEditorOpenChange).not.toHaveBeenCalled();
376 expect(view.onSettingsOpenChange).not.toHaveBeenCalled();
377 });
378});