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

themeBackground.test.ts

160 lines5.2 KB

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