Open History to see the last commit
1import type { ClientSettings } from "@t3tools/contracts";
2import { StrictMode } from "react";
3import { describe, expect, it, vi } from "vite-plus/test";
4import { page, userEvent } from "vite-plus/test/browser";
5
6import { act, render } from "../../../test/render";
7import {
8 __resetClientSettingsPersistenceForTests,
9 updateClientSettings,
10} from "../../hooks/useSettings";
11import { I18nProvider } from "../../i18n/I18nProvider";
12import { startI18n, whenLocaleReady } from "../../i18n/runtime";
13import { ensureLocalApi } from "../../localApi";
14import {
15 CUSTOM_THEMES_STORAGE_KEY,
16 getCustomThemes,
17 installCustomTheme,
18 invalidateCustomThemes,
19 parseThemeFile,
20 themeColorToHex,
21 THEME_FILE_VERSION,
22} from "../../themePalette";
23import { importOpenVsxThemeExtension, type OpenVsxThemeExtension } from "../../openVsxThemes";
24import { AppRouteModal } from "../AppRouteModal";
25import { SharedTooltipProvider } from "../ui/shared-tooltip";
26import { ThemeImportDialog } from "./ThemeImportDialog";
27import { ThemeLibrary } from "./ThemeSettings";
28import { useThemeEditorStore } from "./themeEditorStore";
29
30const searchOpenVsxThemes = vi.hoisted(() => vi.fn());
31
32vi.mock("../chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null }));
33vi.mock("../../hooks/useEnvironmentTheme", () => ({ useEnvironmentThemeDefinitions: () => [] }));
34vi.mock("../../openVsxThemes", () => ({
35 searchOpenVsxThemes,
36 importOpenVsxThemeExtension: vi.fn(),
37}));
38
39const extension: OpenVsxThemeExtension = {
40 id: "acme.nightfall",
41 collectionId: "acme.nightfall",
42 name: "Nightfall",
43 publisher: "acme",
44 description: "A dark theme",
45 downloadCount: 10,
46 iconUrl: null,
47 sourceUrl: null,
48 manifestUrl: "https://example.test/manifest",
49 sha256Url: "https://example.test/sha256",
50 vsixUrl: "https://example.test/vsix",
51 version: "1.0.0",
52 license: "MIT",
53};
54
55describe("ThemeImportDialog", () => {
56 // StrictMode replays ref attach/detach on mount, which must not end the session.
57 it("searches Open VSX under StrictMode", async () => {
58 searchOpenVsxThemes.mockReset();
59 searchOpenVsxThemes.mockResolvedValue([extension]);
60 await using _screen = await render(
61 <StrictMode>
62 <ThemeImportDialog
63 open
64 onOpenChange={() => {}}
65 onImported={() => true}
66 onImportedMany={() => {}}
67 />
68 </StrictMode>,
69 );
70
71 // One input event: keystrokes more than the search debounce apart would search a prefix first.
72 await userEvent.fill(page.getByLabelText("Search Open VSX themes"), "night");
73
74 await expect.element(page.getByRole("heading", { name: "Nightfall" })).toBeVisible();
75 expect(searchOpenVsxThemes).toHaveBeenCalledWith(
76 "night",
77 expect.objectContaining({ sortBy: "downloadCount" }),
78 );
79 });
80
81 it("shows the singular label for one download", async () => {
82 searchOpenVsxThemes.mockReset();
83 searchOpenVsxThemes.mockResolvedValue([{ ...extension, downloadCount: 1 }]);
84 await using _screen = await render(
85 <ThemeImportDialog
86 open
87 onOpenChange={() => {}}
88 onImported={() => true}
89 onImportedMany={() => {}}
90 />,
91 );
92
93 await userEvent.fill(page.getByRole("searchbox"), "night");
94
95 await expect.element(page.getByText("acme · 1 download", { exact: true })).toBeVisible();
96 });
97
98 it("reformats the shown download count when the app language changes", async () => {
99 searchOpenVsxThemes.mockReset();
100 searchOpenVsxThemes.mockResolvedValue([{ ...extension, downloadCount: 1_200_000 }]);
101 const { persistence } = ensureLocalApi();
102 let savedSettings: ClientSettings | null = null;
103 using _readSettings = vi
104 .spyOn(persistence, "getClientSettings")
105 .mockImplementation(async () => savedSettings);
106 using _writeSettings = vi
107 .spyOn(persistence, "setClientSettings")
108 .mockImplementation(async (settings) => {
109 savedSettings = settings;
110 });
111 __resetClientSettingsPersistenceForTests();
112 const setLanguage = async (language: string) => {
113 await act(async () => {
114 await updateClientSettings({ language });
115 await whenLocaleReady();
116 });
117 };
118
119 try {
120 startI18n();
121 await setLanguage("en");
122 await using _screen = await render(
123 <I18nProvider>
124 <ThemeImportDialog
125 open
126 onOpenChange={() => {}}
127 onImported={() => true}
128 onImportedMany={() => {}}
129 />
130 </I18nProvider>,
131 { locale: false },
132 );
133 await userEvent.fill(page.getByRole("searchbox"), "night");
134 await expect.element(page.getByText("acme · 1.2M downloads", { exact: true })).toBeVisible();
135
136 await setLanguage("ru");
137 await expect.element(page.getByText(/^acme · Скачиваний: 1,2\s+млн$/)).toBeVisible();
138 } finally {
139 await setLanguage("en");
140 __resetClientSettingsPersistenceForTests();
141 }
142 });
143
144 it("clears the search on Escape before closing the dialog", async () => {
145 searchOpenVsxThemes.mockReset();
146 searchOpenVsxThemes.mockResolvedValue([]);
147 const onOpenChange = vi.fn();
148 await using _screen = await render(
149 <ThemeImportDialog
150 open
151 onOpenChange={onOpenChange}
152 onImported={() => true}
153 onImportedMany={() => {}}
154 />,
155 );
156 const search = page.getByRole("searchbox", { name: "Search Open VSX themes" });
157 await expect.element(search).toHaveAttribute("type", "text");
158 await userEvent.fill(search, "nord");
159 await userEvent.keyboard("{Escape}");
160 await expect.element(search).toHaveValue("");
161 search.element().dispatchEvent(
162 new KeyboardEvent("keydown", {
163 bubbles: true,
164 cancelable: true,
165 key: "Escape",
166 repeat: true,
167 }),
168 );
169 expect(onOpenChange).not.toHaveBeenCalled();
170
171 await userEvent.keyboard("{Escape}");
172 expect(onOpenChange).toHaveBeenCalledWith(false);
173 });
174
175 it("clears a stale import error when Theme JSON is edited", async () => {
176 await using _screen = await render(
177 <ThemeImportDialog
178 open
179 onOpenChange={() => {}}
180 onImported={() => true}
181 onImportedMany={() => {}}
182 />,
183 );
184 const editor = page.getByRole("textbox", { name: "Theme JSON" });
185 await userEvent.fill(editor, "{");
186 await page.getByRole("button", { name: "Add theme", exact: true }).click();
187 await expect.element(page.getByRole("alert")).toBeVisible();
188
189 await userEvent.fill(editor, "{}");
190 await expect.element(page.getByRole("alert")).not.toBeInTheDocument();
191 });
192});
193
194const theme = (name: string, accent = "#3b82f6", css?: string) => ({
195 version: THEME_FILE_VERSION,
196 name,
197 appearance: "dark",
198 colors: { accent },
199 ...(css ? { css } : {}),
200});
201
202const themeFile = (name: string, accent?: string, css?: string) =>
203 new File([JSON.stringify(theme(name, accent, css))], `${name}.json`, {
204 type: "application/json",
205 });
206
207const DUSK_CSS = ".chat-header { height: 3rem; }";
208
209it.each(["Update existing", "Keep both"])(
210 "keeps batch failures visible after %s",
211 async (choice) => {
212 using _themes = {
213 [Symbol.dispose]() {
214 window.localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
215 invalidateCustomThemes();
216 },
217 };
218 installCustomTheme(parseThemeFile(theme("Dusk")));
219 const onOpenChange = vi.fn();
220 await using _screen = await render(
221 <ThemeImportDialog
222 open
223 onOpenChange={onOpenChange}
224 onImported={() => true}
225 onImportedMany={() => {}}
226 />,
227 );
228 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
229 await userEvent.upload(input, [
230 themeFile("Dawn"),
231 themeFile("Dusk", "#f97316", DUSK_CSS),
232 new File(["{"], "broken.json", { type: "application/json" }),
233 ]);
234
235 await expect.element(page.getByText("Already installed")).toBeVisible();
236 await expect.element(page.getByText(/^broken\.json:/)).toBeVisible();
237 expect(getCustomThemes().map((theme) => theme.label)).toContain("Dawn");
238 await page.getByRole("button", { name: choice }).click();
239 invalidateCustomThemes();
240 const label = choice === "Update existing" ? "Dusk" : "Dusk (1)";
241 expect(getCustomThemes().find((theme) => theme.label === label)).toMatchObject({
242 colors: parseThemeFile(theme("Dusk", "#f97316")).colors,
243 css: DUSK_CSS,
244 });
245 await expect.element(page.getByText(/^broken\.json:/)).toBeVisible();
246 expect(onOpenChange).not.toHaveBeenCalledWith(false);
247 },
248);
249
250it("does not name a kept batch copy after an earlier single file", async () => {
251 using _themes = isolateThemes();
252 installCustomTheme(parseThemeFile(theme("Dusk")));
253 await using _screen = await render(
254 <ThemeImportDialog
255 open
256 onOpenChange={() => {}}
257 onImported={() => true}
258 onImportedMany={() => {}}
259 />,
260 );
261 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
262 await userEvent.upload(input, themeFile("Unrelated"));
263 await expect.element(page.getByText("Unrelated.json")).toBeVisible();
264 await userEvent.upload(input, [themeFile("Dawn"), themeFile("Dusk", "#f97316")]);
265 await expect.element(page.getByText("Already installed")).toBeVisible();
266 await page.getByRole("button", { name: "Keep both" }).click();
267
268 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["Dusk", "Dawn", "Dusk (1)"]);
269});
270
271function isolateThemes() {
272 const previous = localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
273 localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
274 invalidateCustomThemes();
275 return {
276 [Symbol.dispose]() {
277 if (previous === null) localStorage.removeItem(CUSTOM_THEMES_STORAGE_KEY);
278 else localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, previous);
279 invalidateCustomThemes();
280 },
281 };
282}
283
284it("keeps a numbered copy when the theme name expands in its ID", async () => {
285 using _themes = isolateThemes();
286 const name = "İstanbul İncisi İzmir İskenderun İnegöl İpsala";
287 const original = installCustomTheme(parseThemeFile(theme(name)));
288 const updated = theme(name, "#f97316");
289 await using _screen = await render(
290 <ThemeImportDialog
291 open
292 onOpenChange={() => {}}
293 onImported={() => true}
294 onImportedMany={() => {}}
295 />,
296 );
297
298 await userEvent.fill(page.getByRole("textbox", { name: "Theme JSON" }), JSON.stringify(updated));
299 await page.getByRole("button", { name: "Add theme", exact: true }).click();
300 await expect.element(page.getByText("Already installed")).toBeVisible();
301 await page.getByRole("button", { name: "Keep both" }).click();
302
303 const themes = getCustomThemes();
304 expect(themes).toHaveLength(2);
305 expect(themes.find(({ id }) => id === original.id)).toEqual(original);
306 expect(themes.find(({ id }) => id !== original.id)).toMatchObject({
307 label: "İstanbul İncisi İzmir İskenderun İnegöl İ (1)",
308 colors: parseThemeFile(updated).colors,
309 });
310});
311
312it.each([
313 [
314 "a different theme label",
315 theme("Dusk"),
316 theme("Dusk", "#f97316"),
317 `${"a".repeat(47)}🌙.json`,
318 "a".repeat(47),
319 ],
320 [
321 "the same label after truncating",
322 { ...theme("a".repeat(47)), id: "custom-id" },
323 { ...theme("a".repeat(47), "#f97316"), id: "custom-id" },
324 `${"a".repeat(47)}🌙.json`,
325 `${"a".repeat(44)} (1)`,
326 ],
327 [
328 "the same label after truncating at a space",
329 { ...theme("a".repeat(46)), id: "custom-id" },
330 { ...theme("a".repeat(46), "#f97316"), id: "custom-id" },
331 `${"a".repeat(46)} 🌙.json`,
332 `${"a".repeat(44)} (1)`,
333 ],
334 [
335 "a flag emoji crossing the limit",
336 theme("Dusk"),
337 theme("Dusk", "#f97316"),
338 `${"b".repeat(46)}🇺🇸.json`,
339 "b".repeat(46),
340 ],
341 [
342 "an oversized first grapheme cluster",
343 theme("Dusk"),
344 theme("Dusk", "#f97316"),
345 `e${"\u0301".repeat(50)}.json`,
346 "Dusk (1)",
347 ],
348 ["a reserved theme ID", theme("Dusk"), theme("Dusk", "#336699"), "dark.json", "Dusk (1)"],
349])(
350 "names a kept copy after its file (%s)",
351 async (_caseName, installed, imported, fileName, expectedLabel) => {
352 using _themes = isolateThemes();
353 const original = installCustomTheme(parseThemeFile(installed));
354 const json = JSON.stringify(imported);
355 await using _screen = await render(
356 <ThemeImportDialog
357 open
358 onOpenChange={() => {}}
359 onImported={() => true}
360 onImportedMany={() => {}}
361 />,
362 );
363 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
364 await userEvent.upload(input, new File([json], fileName, { type: "application/json" }));
365 await expect.element(page.getByRole("textbox", { name: "Theme JSON" })).toHaveValue(json);
366 await page.getByRole("button", { name: "Add theme", exact: true }).click();
367 await expect.element(page.getByText("Already installed")).toBeVisible();
368 await page.getByRole("button", { name: "Keep both" }).click();
369
370 expect(getCustomThemes().find(({ id }) => id !== original.id)?.label).toBe(expectedLabel);
371 },
372);
373
374it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => {
375 using _themes = isolateThemes();
376 await using _screen = await render(
377 <ThemeImportDialog
378 open
379 onOpenChange={() => {}}
380 onImported={() => true}
381 onImportedMany={() => {}}
382 />,
383 );
384 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
385 await userEvent.upload(
386 input,
387 new File(["x".repeat(1_048_100)], "huge.json", { type: "application/json" }),
388 );
389
390 await expect
391 .element(page.getByText(/^That file is/))
392 .toHaveTextContent(
393 "That file is 1.00 MB. Theme files are only a few KB, so this one was not read (limit 256 KB).",
394 );
395});
396
397it("names an oversized file in a batch import in the UI language", async () => {
398 using _themes = isolateThemes();
399 await using _screen = await render(
400 <ThemeImportDialog
401 open
402 onOpenChange={() => {}}
403 onImported={() => true}
404 onImportedMany={() => {}}
405 />,
406 { locale: "de" },
407 );
408 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
409 await userEvent.upload(input, [
410 themeFile("Dawn"),
411 new File(["x".repeat(1_048_100)], "huge.json", { type: "application/json" }),
412 ]);
413
414 await expect
415 .element(page.getByRole("alert"))
416 .toHaveTextContent(
417 "huge.json: Diese Datei ist 1.00 MB groß. Design-Dateien haben nur wenige KB, daher wurde sie nicht gelesen (Limit 256 KB).",
418 );
419});
420
421it("names a duplicated theme in the UI language", async () => {
422 using _locale = {
423 [Symbol.dispose]() {
424 useThemeEditorStore.getState().closeThemeEditor();
425 },
426 };
427 await using _screen = await render(
428 <SharedTooltipProvider>
429 <ThemeLibrary
430 appearanceMode="dark"
431 customThemes={[]}
432 initialAppearance="dark"
433 isImportOpen={false}
434 onImportOpenChange={() => {}}
435 refreshTheme={() => {}}
436 setAppearanceMode={() => true}
437 setTheme={() => true}
438 setThemeHalf={() => true}
439 theme="dark"
440 themeHalves={null}
441 />
442 </SharedTooltipProvider>,
443 { locale: "de" },
444 );
445
446 await page.getByRole("button", { name: "T3 Code duplizieren" }).click();
447
448 expect(useThemeEditorStore.getState().session?.seedName).toBe("T3 Code Kopie");
449});
450
451it.each(["failed read", "batch install"])(
452 "keeps the oversized replacement warning after a superseded %s",
453 async (earlierImport) => {
454 using _themes = isolateThemes();
455 await using _screen = await render(
456 <ThemeImportDialog
457 open
458 onOpenChange={() => {}}
459 onImported={() => true}
460 onImportedMany={() => {}}
461 />,
462 );
463 const earlierRead = Promise.withResolvers<string>();
464 const readStarted = Promise.withResolvers<void>();
465 const earlierFile = Object.assign(themeFile("Dusk"), {
466 text() {
467 readStarted.resolve();
468 return earlierRead.promise;
469 },
470 });
471 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
472 const files = new DataTransfer();
473 if (earlierImport === "batch install") files.items.add(themeFile("Dawn"));
474 files.items.add(earlierFile);
475 await act(async () => {
476 input.files = files.files;
477 input.dispatchEvent(new Event("change", { bubbles: true }));
478 await readStarted.promise;
479 });
480 await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled();
481 await userEvent.upload(
482 input,
483 new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }),
484 );
485 const warning = page.getByText(/^That file is/);
486 await expect.element(warning).toBeVisible();
487
488 await act(async () => {
489 if (earlierImport === "batch install") {
490 earlierRead.resolve(JSON.stringify(theme("Dusk")));
491 } else {
492 earlierRead.reject(new Error("Could not read Dusk"));
493 }
494 await earlierRead.promise.catch(() => {});
495 });
496
497 expect(getCustomThemes().map((theme) => theme.label)).toEqual([]);
498 expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/);
499 await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled();
500 },
501);
502
503function themeJsonc(name: string, background: string) {
504 return `{
505 // VS Code themes use JSONC even with a .json extension.
506 "name": "${name}",
507 "colors": {
508 "editor.background": "${background}",
509 },
510 "tokenColors": [],
511 }`;
512}
513
514describe("ThemeImportDialog JSONC imports", () => {
515 it.each(["paste", "file"])("imports a VS Code JSONC theme from %s", async (source) => {
516 using _themes = isolateThemes();
517 await using _screen = await render(
518 <ThemeImportDialog
519 open
520 onOpenChange={() => {}}
521 onImported={() => true}
522 onImportedMany={() => {}}
523 />,
524 );
525 const json = themeJsonc("JSONC Night", "#002b36");
526 if (source === "paste") {
527 await page.getByRole("textbox", { name: "Theme JSON" }).fill(json);
528 } else {
529 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
530 await userEvent.upload(input, new File([json], "night.json", { type: "application/json" }));
531 await expect.element(page.getByRole("textbox", { name: "Theme JSON" })).toHaveValue(json);
532 }
533 await page.getByRole("button", { name: "Add theme", exact: true }).click();
534
535 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night"]);
536 expect(themeColorToHex(getCustomThemes()[0]!.colors.canvas)).toBe("#002b36");
537 });
538
539 it("refuses pasted multibyte JSON over the byte limit", async () => {
540 using _themes = isolateThemes();
541 await using _screen = await render(
542 <ThemeImportDialog
543 open
544 onOpenChange={() => {}}
545 onImported={() => true}
546 onImportedMany={() => {}}
547 />,
548 );
549 const json = JSON.stringify({
550 version: 1,
551 name: "Dusk",
552 appearance: "dark",
553 colors: { accent: "#336699" },
554 notes: "語".repeat(90_000),
555 });
556 await page.getByRole("textbox", { name: "Theme JSON" }).fill(json);
557 await page.getByRole("button", { name: "Add theme", exact: true }).click();
558
559 await expect
560 .element(page.getByRole("alert"))
561 .toHaveTextContent(
562 "That file is 264 KB. Theme files are only a few KB, so this one was not read (limit 256 KB).",
563 );
564 expect(getCustomThemes()).toEqual([]);
565 });
566
567 it("imports each VS Code JSONC theme in a file batch", async () => {
568 using _themes = isolateThemes();
569 await using _screen = await render(
570 <ThemeImportDialog
571 open
572 onOpenChange={() => {}}
573 onImported={() => true}
574 onImportedMany={() => {}}
575 />,
576 );
577 const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
578 await userEvent.upload(input, [
579 new File([themeJsonc("JSONC Night", "#002b36")], "night.json", {
580 type: "application/json",
581 }),
582 new File([themeJsonc("JSONC Day", "#fdf6e3")], "day.json", {
583 type: "application/json",
584 }),
585 ]);
586
587 await vi.waitFor(() => {
588 expect(getCustomThemes().map((theme) => theme.label)).toEqual(["JSONC Night", "JSONC Day"]);
589 });
590 expect(getCustomThemes().map((theme) => themeColorToHex(theme.colors.canvas))).toEqual([
591 "#002b36",
592 "#fdf6e3",
593 ]);
594 });
595});
596
597it("does not install a pending community theme after leaving Appearance", async () => {
598 using _themes = isolateThemes();
599 searchOpenVsxThemes.mockReset();
600 searchOpenVsxThemes.mockResolvedValue([extension]);
601 const download = Promise.withResolvers<ReturnType<typeof parseThemeFile>[]>();
602 vi.mocked(importOpenVsxThemeExtension).mockReset();
603 vi.mocked(importOpenVsxThemeExtension).mockReturnValue(download.promise);
604 await using screen = await render(
605 <ThemeImportDialog
606 open
607 onOpenChange={() => {}}
608 onImported={() => true}
609 onImportedMany={() => {}}
610 />,
611 );
612 await userEvent.fill(page.getByLabelText("Search Open VSX themes"), "night");
613 await page.getByRole("button", { name: "Install Nightfall" }).click();
614 await screen.unmount();
615 await act(async () => {
616 download.resolve([
617 {
618 ...parseThemeFile(theme("Nightfall")),
619 collection: { id: extension.collectionId, label: extension.name },
620 },
621 ]);
622 await download.promise;
623 });
624 expect(
625 getCustomThemes(),
626 "expect leaving Appearance to cancel its pending theme installation",
627 ).toEqual([]);
628});
629
630it("closes an open theme variant radial picker on Escape before closing Settings", async () => {
631 const collection = { id: "acme.cat", label: "Catppuccin" };
632 const customThemes = [
633 {
634 ...parseThemeFile({
635 version: THEME_FILE_VERSION,
636 name: "Catppuccin Latte",
637 appearance: "light",
638 colors: { accent: "#3b82f6" },
639 }),
640 collection,
641 },
642 { ...parseThemeFile(theme("Catppuccin Mocha")), collection },
643 { ...parseThemeFile(theme("Catppuccin Frappe", "#f97316")), collection },
644 ];
645 const renderSettings = (key: string) => (
646 <SharedTooltipProvider>
647 <AppRouteModal key={key} label="Settings">
648 <ThemeLibrary
649 appearanceMode="dark"
650 customThemes={customThemes}
651 initialAppearance="dark"
652 isImportOpen={false}
653 onImportOpenChange={() => {}}
654 refreshTheme={() => {}}
655 setAppearanceMode={() => true}
656 setTheme={() => true}
657 setThemeHalf={() => true}
658 theme="dark"
659 themeHalves={null}
660 />
661 </AppRouteModal>
662 </SharedTooltipProvider>
663 );
664
665 await using screen = await render(renderSettings("multi"), { router: "/settings/appearance" });
666 const settings = page.getByRole("dialog", { name: "Settings" });
667 await expect.element(settings).toHaveFocus();
668
669 const darkPicker = page.getByRole("button", {
670 name: "Choose dark variant, 2 options, currently Mocha",
671 });
672 const mochaOption = page.getByRole("button", { name: "Use Mocha for dark mode" });
673 (darkPicker.element() as HTMLElement).focus();
674 await expect.element(mochaOption).toHaveStyle({ opacity: "1", pointerEvents: "auto" });
675
676 await userEvent.keyboard("{Escape}");
677 await expect.element(mochaOption).toHaveStyle({ opacity: "0", pointerEvents: "none" });
678 await expect.element(darkPicker).toHaveFocus();
679 await expect.element(settings).toHaveAttribute("data-open");
680
681 await userEvent.tab();
682 await expect.element(mochaOption).toHaveFocus();
683 await expect.element(mochaOption).toHaveStyle({ opacity: "1", pointerEvents: "auto" });
684
685 await userEvent.keyboard("{Escape}");
686 await expect.element(mochaOption).toHaveStyle({ opacity: "0", pointerEvents: "none" });
687 await expect.element(darkPicker).toHaveFocus();
688 await expect.element(settings).toHaveAttribute("data-open");
689
690 await userEvent.keyboard("{Escape}");
691 await expect.element(settings).not.toBeInTheDocument();
692
693 await screen.rerender(renderSettings("single"));
694 await expect.element(settings).toHaveFocus();
695
696 const lightVariant = page.getByRole("button", { name: "Use light variant, currently Latte" });
697 (lightVariant.element() as HTMLElement).focus();
698 await userEvent.keyboard("{Escape}");
699 await expect.element(settings).not.toBeInTheDocument();
700});