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

useHtmlRenderTheme.ts

65 lines2.3 KB

1import { HTML_RENDER_DEFAULT_FONTS, htmlRenderTheme } from "@t3tools/shared/htmlRender";
2import { useAtomMount } from "@effect/atom-react";
3import type { ScopedThreadRef } from "@t3tools/contracts";
4import { useSyncExternalStore } from "react";
5​
6import { appearanceFontStack } from "../appearanceFonts";
7import { useServerConfigs } from "../state/entities";
8import { previewEnvironment } from "../state/preview";
9import {
10 getStandardThemeColors,
11 getThemeColorsForMode,
12 getThemeDefinition,
13 resolveThemeHalf,
14 subscribeToCustomThemes,
15 themeColorToHex,
16 type ThemeAppearance,
17 type ThemeHalves,
18 type ThemePreference,
19} from "../themePalette";
20import { useClientSettings } from "./useSettings";
21import { useTheme } from "./useTheme";
22​
23function resolveActiveThemeColors(
24 theme: ThemePreference,
25 halves: ThemeHalves | null,
26 appearance: ThemeAppearance,
27) {
28 const definition = getThemeDefinition(resolveThemeHalf(theme, halves, appearance));
29 return definition === null
30 ? getStandardThemeColors(appearance)
31 : (getThemeColorsForMode(definition, appearance) ?? definition.colors);
33​
34export function useHtmlRenderTheme() {
35 const { theme, resolvedTheme, themeHalves } = useTheme();
36 // Custom and published palettes can be edited in place, under an unchanged preference.
37 const colors = useSyncExternalStore(
38 subscribeToCustomThemes,
39 () => resolveActiveThemeColors(theme, themeHalves, resolvedTheme),
40 () => getStandardThemeColors(resolvedTheme),
41 );
42 const sans = useClientSettings((settings) => settings.fontFamilySans);
43 const mono = useClientSettings((settings) => settings.fontFamilyCode);
44 return htmlRenderTheme(
45 Object.fromEntries(
46 Object.entries(colors).map(([role, color]) => [role, themeColorToHex(color) ?? color]),
47 ) as typeof colors,
48 resolvedTheme,
49 {
50 sans: appearanceFontStack(sans, HTML_RENDER_DEFAULT_FONTS.sans),
51 mono: appearanceFontStack(mono, HTML_RENDER_DEFAULT_FONTS.mono),
52 },
53 );
55​
56export function useThreadHtmlPreviewTheme(threadRef: ScopedThreadRef) {
57 const theme = useHtmlRenderTheme();
58 const config = useServerConfigs().get(threadRef.environmentId);
59 useAtomMount(
60 previewEnvironment.htmlPreviewTheme(
61 config?.environment.capabilities.htmlPreviewTheme === true ? threadRef : null,
62 theme,
63 ),
64 );