Open History to see the last commit
1import { appAtomRegistry } from "../rpc/atomRegistry";
2import { localEnvironmentIdAtom } from "../state/primaryEnvironment";
3import { themeServerSettingsAtom } from "../state/server";
4import { getThemeDefinition, singleAppearanceOf, subscribeToCustomThemes } from "../themePalette";
5import { getThemeSnapshot, setAppearanceMode, setTheme } from "./useTheme";
6
7const APPLIED_DEFAULT_THEME_STORAGE_PREFIX = "t3code:default-theme-applied:v2:";
8const APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX = "t3code:default-appearance-applied:v1:";
9
10/** Include set time so reasserting the same theme still applies. */
11export function defaultThemeGeneration(theme: string, setAt: string): string {
12 return setAt.length > 0 ? `${theme}@${setAt}` : theme;
13}
14
15export function defaultThemeToApply(input: {
16 readonly environmentId: string | null;
17 readonly defaultTheme: string;
18 readonly defaultThemeSetAt: string;
19 readonly appliedGeneration: string | null;
20 readonly resolves: boolean;
21}): string | null {
22 // Empty with a set time means the stock theme was set; with none, no theme was.
23 if (input.environmentId === null) return null;
24 if (input.defaultTheme.length === 0 && input.defaultThemeSetAt.length === 0) return null;
25 const generation = defaultThemeGeneration(input.defaultTheme, input.defaultThemeSetAt);
26 if (input.appliedGeneration === generation) return null;
27 // The setting and the palette it names arrive independently, so an id that
28 // does not resolve yet is not a failure -- adoption re-checks when the
29 // published set changes.
30 if (!input.resolves) return null;
31 return generation;
32}
33
34/** A single-appearance theme sets its own mode unless a mode was set with it or after it. */
35export function themeSetsOwnMode(input: {
36 readonly defaultThemeSetAt: string;
37 readonly defaultAppearance: string;
38 readonly defaultAppearanceSetAt: string;
39}): boolean {
40 // ISO timestamps from one server compare correctly as strings.
41 return input.defaultAppearance === "" || input.defaultAppearanceSetAt < input.defaultThemeSetAt;
42}
43
44function readAppliedGeneration(storageKey: string): string | null {
45 if (typeof window === "undefined") return null;
46 try {
47 return window.localStorage.getItem(storageKey);
48 } catch {
49 return null;
50 }
51}
52
53function writeAppliedGeneration(storageKey: string, generation: string): boolean {
54 try {
55 window.localStorage.setItem(storageKey, generation);
56 return true;
57 } catch {
58 return false;
59 }
60}
61
62function adoptDefaultTheme(): void {
63 if (typeof window === "undefined") return;
64 const environmentId = appAtomRegistry.get(localEnvironmentIdAtom);
65 if (environmentId === null) return;
66 const settings = appAtomRegistry.get(themeServerSettingsAtom);
67 const { defaultTheme, defaultThemeSetAt } = settings;
68 const definition = getThemeDefinition(defaultTheme);
69 const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;
70 const generation = defaultThemeToApply({
71 environmentId,
72 defaultTheme,
73 defaultThemeSetAt,
74 appliedGeneration: readAppliedGeneration(storageKey),
75 resolves: definition !== null || defaultTheme === "",
76 });
77 if (generation === null) return;
78 if (definition === null) {
79 // The stock theme keeps the client's own light, dark, or system mode.
80 if (setTheme(getThemeSnapshot().appearanceMode)) writeAppliedGeneration(storageKey, generation);
81 return;
82 }
83
84 // A single-appearance theme needs both preference and appearance writes to take effect.
85 if (!setTheme(defaultTheme)) return;
86 const half = singleAppearanceOf(definition);
87 // Only record adoption after both writes succeed, so an appearance failure remains retryable.
88 if (half !== null && themeSetsOwnMode(settings) && !setAppearanceMode(half)) return;
89 writeAppliedGeneration(storageKey, generation);
90}
91
92/** Like the theme, the environment's mode applies once per set, then local choices win. */
93function adoptDefaultAppearance(): boolean {
94 if (typeof window === "undefined") return true;
95 const environmentId = appAtomRegistry.get(localEnvironmentIdAtom);
96 const { defaultAppearance, defaultAppearanceSetAt } =
97 appAtomRegistry.get(themeServerSettingsAtom);
98 const storageKey = `${APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX}${environmentId}`;
99 const generation = defaultThemeToApply({
100 environmentId,
101 defaultTheme: defaultAppearance,
102 defaultThemeSetAt: defaultAppearanceSetAt,
103 appliedGeneration: readAppliedGeneration(storageKey),
104 resolves: true,
105 });
106 if (generation === null || defaultAppearance === "") return true;
107 return setAppearanceMode(defaultAppearance) && writeAppliedGeneration(storageKey, generation);
108}
109
110function adoptDefaults(): void {
111 // Mode first, so a newer single-appearance theme can still set its own mode
112 // and the stock theme keeps the adopted mode rather than the one before it.
113 if (!adoptDefaultAppearance()) return;
114 adoptDefaultTheme();
115}
116
117/**
118 * Applies the theme environment's default theme once per generation. Start it after the
119 * environment theme sync so a first-run client adopting the environment's own theme finds it
120 * already in the library; it re-checks when published or custom palettes change, so a theme
121 * that resolves late still applies.
122 */
123export function startDefaultThemeAdoption(): () => void {
124 const unsubscribes = [
125 appAtomRegistry.subscribe(localEnvironmentIdAtom, adoptDefaults),
126 appAtomRegistry.subscribe(themeServerSettingsAtom, adoptDefaults),
127 subscribeToCustomThemes(adoptDefaults),
128 ];
129 adoptDefaults();
130 return () => {
131 for (const unsubscribe of unsubscribes) unsubscribe();
132 };
133}