Open History to see the last commit
1import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
2import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3import type { EnvironmentId } from "@t3tools/contracts";
4
5import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
6import { assetEnvironment } from "./state/assets";
7import { themeEnvironmentIdAtom } from "./state/primaryEnvironment";
8import { themeServerEnvironmentThemesAtom } from "./state/server";
9import { environmentSession } from "./state/session";
10import { getCustomThemes } from "./themePalette";
11
12const THEME_BACKGROUND_VARIABLE = "--theme-background-image";
13const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000];
14
15let shownKey: string | null = null;
16let loading: AbortController | null = null;
17let objectUrl: string | null = null;
18
19function show(nextUrl: string | null): void {
20 const root = document.documentElement;
21 if (nextUrl === null) root.style.removeProperty(THEME_BACKGROUND_VARIABLE);
22 else root.style.setProperty(THEME_BACKGROUND_VARIABLE, `url("${nextUrl}")`);
23 if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
24 objectUrl = nextUrl;
25}
26
27async function loadBackground(
28 environmentId: EnvironmentId,
29 themeId: string,
30 signal: AbortSignal,
31): Promise<string | null> {
32 const minted = await executeAtomQuery(
33 appAtomRegistry,
34 assetEnvironment.createUrl({
35 environmentId,
36 input: { resource: { _tag: "environment-theme-background", themeId } },
37 }),
38 { label: "theme background", reportFailure: false, refresh: true, signal },
39 );
40 const connection = appAtomRegistry.get(
41 environmentSession.preparedConnectionValueAtom(environmentId),
42 );
43 if (minted._tag !== "Success" || connection._tag === "None") return null;
44 const url = resolveAssetUrl(connection.value.httpBaseUrl, minted.value.relativeUrl);
45 if (url === null) return null;
46 const response = await fetch(url, { signal });
47 if (!response.ok) return null;
48 const image = await response.blob();
49 return image.type.startsWith("image/") ? URL.createObjectURL(image) : null;
50}
51
52/**
53 * Sets `--theme-background-image` to the image published beside `themeId`, or clears it.
54 * The image is copied into a blob URL once per revision, so the signed URL may expire.
55 */
56export function applyThemeBackground(themeId: string | undefined): void {
57 if (typeof document === "undefined") return;
58 const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom);
59 // A saved theme wins its id over a published one, so the published image is not its.
60 const revision =
61 themeId === undefined || getCustomThemes().some((theme) => theme.id === themeId)
62 ? undefined
63 : appAtomRegistry.get(themeServerEnvironmentThemesAtom)?.find((theme) => theme.id === themeId)
64 ?.background;
65 const key =
66 environmentId === null || themeId === undefined || revision === undefined
67 ? null
68 : JSON.stringify([environmentId, themeId, revision]);
69 if (key === shownKey) return;
70 shownKey = key;
71 loading?.abort();
72 loading = null;
73 // The previous image must not show under the next theme while it loads.
74 show(null);
75 if (environmentId === null || themeId === undefined || key === null) return;
76 const controller = new AbortController();
77 loading = controller;
78 let retries = 0;
79 const failed = () => {
80 if (controller.signal.aborted) return;
81 const delay = RETRY_DELAYS_MS[retries++];
82 if (delay !== undefined) {
83 // Transient HTTP failures may never produce a browser online event.
84 const timer = setTimeout(load, delay);
85 controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
86 return;
87 }
88 loading = null;
89 // Lets the next repaint or `online` event try again.
90 shownKey = null;
91 };
92 const load = () => {
93 loadBackground(environmentId, themeId, controller.signal).then((url) => {
94 if (controller.signal.aborted) {
95 if (url !== null) URL.revokeObjectURL(url);
96 return;
97 }
98 if (url === null) failed();
99 else {
100 loading = null;
101 show(url);
102 }
103 }, failed);
104 };
105 load();
106}
107
108/**
109 * A new image revision does not change the palette, so it does not repaint the theme.
110 * Coming back online retries a download that failed; a shown image is left alone.
111 */
112export function startThemeBackground(): () => void {
113 const reapply = () => applyThemeBackground(document.documentElement.dataset.themeId);
114 const unsubscribe = subscribeAtomChanges(themeServerEnvironmentThemesAtom, reapply);
115 window.addEventListener("online", reapply);
116 return () => {
117 unsubscribe();
118 window.removeEventListener("online", reapply);
119 loading?.abort();
120 loading = null;
121 shownKey = null;
122 show(null);
123 };
124}