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

themeBackground.ts

122 lines4.4 KB

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