Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";
3import { describe, expect, it, vi } from "vite-plus/test";
4
5const query = vi.hoisted(() => vi.fn());
6vi.mock(
7 import("@t3tools/client-runtime/state/runtime"),
8 () =>
9 ({
10 executeAtomQuery: query,
11 }) as never,
12);
13vi.mock(import("./state/primaryEnvironment"), async () => {
14 const { Atom } = await import("effect/reactivity");
15 return { localEnvironmentIdAtom: Atom.make(EnvironmentId.make("host")) } as never;
16});
17vi.mock(import("./state/server"), async () => {
18 const { Atom } = await import("effect/reactivity");
19 return {
20 themeServerEnvironmentThemesAtom: Atom.make([{ id: "nightfall", background: "revision-1" }]),
21 } as never;
22});
23vi.mock(import("./state/session"), async () => {
24 const { Atom } = await import("effect/reactivity");
25 return {
26 environmentSession: {
27 preparedConnectionValueAtom: Atom.family(() =>
28 Atom.make({ _tag: "Some", value: { httpBaseUrl: "https://example.com/" } }),
29 ),
30 },
31 } as never;
32});
33vi.mock(
34 import("./state/assets"),
35 () =>
36 ({
37 assetEnvironment: { createUrl: vi.fn() },
38 }) as never,
39);
40
41import { applyThemeBackground, startThemeBackground } from "./themeBackground";
42import {
43 applyThemeColorPreview,
44 CUSTOM_THEMES_STORAGE_KEY,
45 getThemeDefinition,
46 invalidateCustomThemes,
47 THEME_PREVIEW_ID,
48} from "./themePalette";
49
50const BACKGROUND = "--theme-background-image";
51const image = new Blob(["image"], { type: "image/png" });
52const offline = () => Promise.reject(new TypeError("Failed to fetch"));
53const loaded = async () => ({ ok: true, blob: async () => image });
54
55function setup(storage: Record<string, string> = {}) {
56 vi.useFakeTimers();
57 const properties = new Map<string, string>();
58 const browser = Object.assign(new EventTarget(), {
59 localStorage: { getItem: (key: string) => storage[key] ?? null },
60 });
61 vi.stubGlobal("window", browser);
62 invalidateCustomThemes();
63 vi.stubGlobal("document", {
64 documentElement: {
65 dataset: { themeId: "nightfall" },
66 classList: { toggle: () => false },
67 style: {
68 setProperty: (name: string, value: string) => properties.set(name, value),
69 removeProperty: (name: string) => properties.delete(name),
70 },
71 },
72 });
73 query.mockResolvedValue({ _tag: "Success", value: { relativeUrl: "/background.png" } });
74 const fetchBackground = vi.fn<() => Promise<unknown>>(offline);
75 vi.stubGlobal("fetch", fetchBackground);
76 const stop = startThemeBackground();
77 return {
78 properties,
79 browser,
80 fetchBackground,
81 stop,
82 [Symbol.dispose]() {
83 stop();
84 applyThemeBackground(undefined);
85 vi.unstubAllGlobals();
86 invalidateCustomThemes();
87 vi.useRealTimers();
88 },
89 };
90}
91
92describe("theme backgrounds", () => {
93 it("retries a failed download after 1, 2, 4 and 8 seconds", async () => {
94 using t = setup();
95 t.fetchBackground
96 .mockImplementationOnce(async () => new Response(null, { status: 503 }))
97 .mockImplementationOnce(offline)
98 .mockImplementationOnce(offline)
99 .mockImplementationOnce(offline)
100 .mockImplementation(loaded);
101
102 applyThemeBackground("nightfall");
103 await vi.advanceTimersByTimeAsync(0);
104 for (const [delay, attempts] of [
105 [1_000, 1],
106 [2_000, 2],
107 [4_000, 3],
108 [8_000, 4],
109 ] as const) {
110 await vi.advanceTimersByTimeAsync(delay - 1);
111 expect(t.fetchBackground).toHaveBeenCalledTimes(attempts);
112 expect(t.properties.has(BACKGROUND)).toBe(false);
113 await vi.advanceTimersByTimeAsync(1);
114 }
115 expect(t.fetchBackground).toHaveBeenCalledTimes(5);
116 expect(t.properties.get(BACKGROUND)).toMatch(/^url\("blob:/);
117 });
118
119 it("loads the background once when the browser comes back online after retries stop", async () => {
120 using t = setup();
121 applyThemeBackground("nightfall");
122 await vi.advanceTimersByTimeAsync(30_000);
123 expect(t.fetchBackground).toHaveBeenCalledTimes(5);
124 expect(t.properties.has(BACKGROUND)).toBe(false);
125
126 t.fetchBackground.mockImplementation(loaded);
127 t.browser.dispatchEvent(new Event("online"));
128 await vi.advanceTimersByTimeAsync(0);
129 expect(t.properties.get(BACKGROUND)).toMatch(/^url\("blob:/);
130
131 t.browser.dispatchEvent(new Event("online"));
132 await vi.advanceTimersByTimeAsync(30_000);
133 expect(t.fetchBackground).toHaveBeenCalledTimes(6);
134 });
135
136 it("keeps the shown background under a draft preview when the browser comes back online", async () => {
137 using t = setup();
138 t.fetchBackground.mockImplementation(loaded);
139 applyThemeBackground("nightfall");
140 await vi.advanceTimersByTimeAsync(0);
141 const shown = t.properties.get(BACKGROUND);
142 expect(shown).toMatch(/^url\("blob:/);
143
144 document.documentElement.dataset.themeId = THEME_PREVIEW_ID;
145 t.browser.dispatchEvent(new Event("online"));
146 await vi.advanceTimersByTimeAsync(0);
147 expect(t.properties.get(BACKGROUND)).toBe(shown);
148 });
149
150 it("shows no background under a draft of a theme without one", async () => {
151 using t = setup();
152 t.fetchBackground.mockImplementation(loaded);
153 applyThemeBackground("nightfall");
154 await vi.advanceTimersByTimeAsync(0);
155 expect(t.properties.get(BACKGROUND)).toMatch(/^url\("blob:/);
156
157 const [plain] = BUILT_IN_THEMES;
158 applyThemeColorPreview(plain!.colors, plain!.appearance, plain!.syntax);
159 await vi.advanceTimersByTimeAsync(0);
160 expect(t.properties.has(BACKGROUND)).toBe(false);
161 });
162
163 it.each(["theme change", "disposal"])("stops retrying after %s", async (reason) => {
164 using t = setup();
165 applyThemeBackground("nightfall");
166 await vi.advanceTimersByTimeAsync(0);
167 if (reason === "theme change") applyThemeBackground(undefined);
168 else t.stop();
169 await vi.advanceTimersByTimeAsync(30_000);
170 expect(t.fetchBackground).toHaveBeenCalledTimes(1);
171 });
172
173 it("shows no published background when a saved theme shares its id", async () => {
174 using t = setup({
175 [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
176 {
177 id: "nightfall",
178 label: "Nightfall",
179 appearance: "dark",
180 colors: { canvas: "#162327", accent: "#cc3344" },
181 },
182 ]),
183 });
184 t.fetchBackground.mockImplementation(loaded);
185 expect(getThemeDefinition("nightfall")?.colors.accent).toBeDefined();
186 applyThemeBackground("nightfall");
187 await vi.advanceTimersByTimeAsync(0);
188 expect(t.fetchBackground).not.toHaveBeenCalled();
189 expect(t.properties.has(BACKGROUND)).toBe(false);
190 });
191});