@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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