Skip to content

Modern Docker Management, Designed for Everyone

13.2 KB
Raw Blame
import type { ApplicationTheme } from '#lib/types/settings.js';

const APPLICATION_THEME_VALUES = [
	'default',
	'graphite',
	'carbon',
	'ocean',
	'amber',
	'github',
	'nord',
	'everforest',
	'rosepine'
] as const satisfies readonly ApplicationTheme[];

export type ApplicationThemeOption = {
	value: ApplicationTheme;
	preview: {
		light: {
			background: string;
			sidebar: string;
			card: string;
			border: string;
			foreground: string;
			primary: string;
		};
		dark: {
			background: string;
			sidebar: string;
			card: string;
			border: string;
			foreground: string;
			primary: string;
		};
	};
};

export const APPLICATION_THEME_OPTIONS: readonly ApplicationThemeOption[] = [
	{
		value: 'default',
		preview: {
			light: {
				background: '#fafafa',
				sidebar: '#f3f4f6',
				card: '#ffffff',
				border: '#d4d4d8',
				foreground: '#18181b',
				primary: '#8b5cf6'
			},
			dark: {
				background: '#24262b',
				sidebar: '#1c1f24',
				card: '#31343a',
				border: '#4a4f58',
				foreground: '#f5f7fa',
				primary: '#a855f7'
			}
		}
	},
	{
		value: 'graphite',
		preview: {
			light: {
				background: '#eef1f5',
				sidebar: '#dfe5ec',
				card: '#f8fafc',
				border: '#cbd5e1',
				foreground: '#0f172a',
				primary: '#5b6ee1'
			},
			dark: {
				background: '#2d3139',
				sidebar: '#252932',
				card: '#343944',
				border: '#4d5664',
				foreground: '#edf2f7',
				primary: '#8ea0ff'
			}
		}
	},
	{
		value: 'carbon',
		preview: {
			light: {
				background: '#F4F4F4',
				sidebar: '#EBEBEC',
				card: '#FCFCFC',
				border: '#D4D4D8',
				foreground: '#1C1C1E',
				primary: '#4A6FA5'
			},
			dark: {
				background: '#0B0B0B',
				sidebar: '#131315',
				card: '#1C1C1F',
				border: '#46464B',
				foreground: '#D8D8D8',
				primary: '#6B91D1'
			}
		}
	},
	{
		value: 'ocean',
		preview: {
			light: {
				background: '#EAF0FF',
				sidebar: '#DDE5FA',
				card: '#F8FAFF',
				border: '#B9C6E8',
				foreground: '#1E2A45',
				primary: '#3B5CB5'
			},
			dark: {
				background: '#10121B',
				sidebar: '#151A2C',
				card: '#1D2338',
				border: '#474C5E',
				foreground: '#CFD2E4',
				primary: '#83ABFF'
			}
		}
	},
	{
		value: 'amber',
		preview: {
			light: {
				background: '#f9f1e6',
				sidebar: '#efe0cd',
				card: '#fffaf3',
				border: '#ddc2a0',
				foreground: '#3f2a12',
				primary: '#c67620'
			},
			dark: {
				background: '#3b2d1f',
				sidebar: '#2f2419',
				card: '#473626',
				border: '#7a5b3d',
				foreground: '#f7ead7',
				primary: '#e0a255'
			}
		}
	},
	{
		value: 'github',
		preview: {
			light: {
				background: '#f6f8fa',
				sidebar: '#eff2f5',
				card: '#ffffff',
				border: '#d0d7de',
				foreground: '#1f2328',
				primary: '#0969da'
			},
			dark: {
				background: '#161b22',
				sidebar: '#0d1117',
				card: '#21262d',
				border: '#30363d',
				foreground: '#e6edf3',
				primary: '#2f81f7'
			}
		}
	},
	{
		value: 'nord',
		preview: {
			light: {
				background: '#eceff4',
				sidebar: '#e5e9f0',
				card: '#f8fafc',
				border: '#c5cedc',
				foreground: '#2e3440',
				primary: '#5e81ac'
			},
			dark: {
				background: '#2b313c',
				sidebar: '#242933',
				card: '#353c49',
				border: '#4c566a',
				foreground: '#eceff4',
				primary: '#88c0d0'
			}
		}
	},
	{
		value: 'everforest',
		preview: {
			light: {
				background: '#f2efdf',
				sidebar: '#e7e2cc',
				card: '#fbf8ee',
				border: '#cdbf9f',
				foreground: '#374145',
				primary: '#6f894e'
			},
			dark: {
				background: '#2d3530',
				sidebar: '#252b28',
				card: '#343f39',
				border: '#56635f',
				foreground: '#e6e2cc',
				primary: '#a7c080'
			}
		}
	},
	{
		value: 'rosepine',
		preview: {
			light: {
				background: '#faf4ed',
				sidebar: '#f2e9e1',
				card: '#fffaf5',
				border: '#dfd1c5',
				foreground: '#575279',
				primary: '#b4637a'
			},
			dark: {
				background: '#191724',
				sidebar: '#16141f',
				card: '#26233a',
				border: '#403d52',
				foreground: '#e0def4',
				primary: '#c4a7e7'
			}
		}
	}
] as const;

const APP_THEME_ATTRIBUTE = 'data-app-theme';
const OLED_CLASS = 'oled';
const DARK_CLASS = 'dark';
const OLED_THEME_COLOR = '#000000';
const DEFAULT_ACCENT_COLOR = 'oklch(0.606 0.25 292.717)';

let htmlClassObserver: MutationObserver | null = null;

// Mirrors the appearance state onto localStorage so the blocking inline script
// in app.html can restore it before first paint (see app.html) — without this
// the SPA shell paints the default light theme until hydration + API calls finish.
const APPEARANCE_CACHE_KEY = 'arcane-appearance';

type AppearanceCache = {
	appTheme?: ApplicationTheme | null;
	oled?: boolean;
	accent?: { primary: string; primaryForeground: string; ring: string } | null;
	fontSize?: number | null;
	noBlur?: boolean;
	reduceEffects?: boolean;
};

function updateAppearanceCache(partial: AppearanceCache): void {
	if (typeof localStorage === 'undefined') {
		return;
	}

	try {
		const stored = JSON.parse(localStorage.getItem(APPEARANCE_CACHE_KEY) ?? '{}') as { v?: AppearanceCache };
		const v: AppearanceCache = { ...stored.v, ...partial };

		// Pre-compute the exact attribute, class list, and inline style the inline
		// script applies, so it stays a dumb three-line replay of this cache.
		const attr = v.appTheme ?? '';
		const cls = [v.oled && OLED_CLASS, v.noBlur && 'no-blur', v.reduceEffects && 'reduce-effects'].filter(Boolean).join(' ');
		const css = [
			...(v.accent
				? [
						`--primary: ${v.accent.primary}`,
						`--primary-foreground: ${v.accent.primaryForeground}`,
						`--ring: ${v.accent.ring}`,
						`--sidebar-ring: ${v.accent.ring}`
					]
				: []),
			...(v.fontSize ? [`font-size: ${v.fontSize}px`] : [])
		].join('; ');

		localStorage.setItem(APPEARANCE_CACHE_KEY, JSON.stringify({ v, attr, cls, css }));
	} catch {
		// localStorage unavailable (private browsing) or corrupted cache — the
		// inline script degrades to the default theme, nothing else breaks.
	}
}

const appearanceState = $state({ theme: 'default' as ApplicationTheme, accent: 'default' });

const THEME_LOGO_PRIMARIES = Object.fromEntries(
	APPLICATION_THEME_OPTIONS.map((option) => [
		option.value,
		{ light: option.preview.light.primary, dark: option.preview.dark.primary }
	])
) as Record<ApplicationTheme, { light: string; dark: string }>;

export function resolveThemePrimary(isDarkMode: boolean): string {
	if (appearanceState.theme === 'default') {
		return DEFAULT_ACCENT_COLOR;
	}

	const primaries = THEME_LOGO_PRIMARIES[appearanceState.theme];
	return isDarkMode ? primaries.dark : primaries.light;
}

export function resolveLogoColor(isDarkMode: boolean): string {
	if (appearanceState.accent !== 'default' && appearanceState.accent !== 'theme') {
		return appearanceState.accent;
	}

	return resolveThemePrimary(isDarkMode);
}

export function resolveApplicationTheme(value?: string | null): ApplicationTheme {
	if (!value) {
		return 'default';
	}

	return APPLICATION_THEME_VALUES.includes(value as ApplicationTheme) ? (value as ApplicationTheme) : 'default';
}

export function applyApplicationTheme(themeValue?: string | null): void {
	const theme = resolveApplicationTheme(themeValue);
	appearanceState.theme = theme;

	if (typeof document === 'undefined') {
		return;
	}

	ensureThemeColorSyncObserver();

	if (theme === 'default') {
		document.documentElement.removeAttribute(APP_THEME_ATTRIBUTE);
	} else {
		document.documentElement.setAttribute(APP_THEME_ATTRIBUTE, theme);
	}

	updateAppearanceCache({ appTheme: theme === 'default' ? null : theme });

	syncBrowserThemeColor();
}

function isDefaultApplicationTheme(root: HTMLElement): boolean {
	const appTheme = root.getAttribute(APP_THEME_ATTRIBUTE);
	return !appTheme || appTheme === 'default';
}

function ensureThemeColorSyncObserver(): void {
	if (typeof document === 'undefined' || htmlClassObserver) {
		return;
	}

	htmlClassObserver = new MutationObserver(() => {
		syncBrowserThemeColor();
	});

	htmlClassObserver.observe(document.documentElement, {
		attributes: true,
		attributeFilter: ['class', APP_THEME_ATTRIBUTE]
	});
}

function syncBrowserThemeColor(): void {
	if (typeof document === 'undefined') {
		return;
	}

	const root = document.documentElement;
	const isDarkMode = root.classList.contains(DARK_CLASS);
	const activeMeta = document.querySelector<HTMLMetaElement>(
		`meta[name="theme-color"][media="(prefers-color-scheme: ${isDarkMode ? 'dark' : 'light'})"]`
	);

	if (!activeMeta) {
		return;
	}

	if (isDarkMode && root.classList.contains(OLED_CLASS) && isDefaultApplicationTheme(root)) {
		activeMeta.content = OLED_THEME_COLOR;
		return;
	}

	const background = getComputedStyle(root).getPropertyValue('--background').trim();

	if (background) {
		activeMeta.content = background;
	}
}

export function applyAccentColor(accentValue: string) {
	// The 'theme' sentinel means "inherit the application theme" and behaves
	// exactly like 'default' (no override). It is normalized here so invalid
	// CSS can never reach the custom-accent branch below.
	const normalizedAccent = accentValue === 'theme' ? 'default' : accentValue;
	const resolvedAccent = normalizedAccent === 'default' ? DEFAULT_ACCENT_COLOR : normalizedAccent;
	appearanceState.accent = normalizedAccent;

	if (typeof document === 'undefined') {
		return;
	}

	if (normalizedAccent === 'default') {
		document.documentElement.style.removeProperty('--primary');
		document.documentElement.style.removeProperty('--primary-foreground');
		document.documentElement.style.removeProperty('--ring');
		document.documentElement.style.removeProperty('--sidebar-ring');
		updateAppearanceCache({ accent: null });
		return;
	}

	document.documentElement.style.setProperty('--primary', resolvedAccent);

	const foregroundColor = getContrastingForeground(resolvedAccent);
	document.documentElement.style.setProperty('--primary-foreground', foregroundColor);

	const ringColor = `color-mix(in srgb, ${resolvedAccent} 50%, transparent)`;
	document.documentElement.style.setProperty('--ring', ringColor);
	document.documentElement.style.setProperty('--sidebar-ring', ringColor);

	updateAppearanceCache({ accent: { primary: resolvedAccent, primaryForeground: foregroundColor, ring: ringColor } });
}

function getContrastingForeground(color: string): string {
	const brightness = getColorBrightness(color);
	return brightness < 0.55 ? 'oklch(0.98 0 0)' : 'oklch(0.09 0 0)';
}

function getColorBrightness(color: string): number {
	const tempElement = document.createElement('div');
	tempElement.style.color = color;
	document.body.appendChild(tempElement);

	const computedColor = window.getComputedStyle(tempElement).color;
	document.body.removeChild(tempElement);

	const rgbMatch = computedColor.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
	if (!rgbMatch) {
		return 0.5;
	}

	const r = Number.parseInt(rgbMatch[1] ?? '0', 10);
	const g = Number.parseInt(rgbMatch[2] ?? '0', 10);
	const b = Number.parseInt(rgbMatch[3] ?? '0', 10);

	const sR = r / 255;
	const sG = g / 255;
	const sB = b / 255;

	const rLinear = sR <= 0.03928 ? sR / 12.92 : Math.pow((sR + 0.055) / 1.055, 2.4);
	const gLinear = sG <= 0.03928 ? sG / 12.92 : Math.pow((sG + 0.055) / 1.055, 2.4);
	const bLinear = sB <= 0.03928 ? sB / 12.92 : Math.pow((sB + 0.055) / 1.055, 2.4);

	return 0.2126 * rLinear + 0.7152 * gLinear + 0.0722 * bLinear;
}

export function applyOledMode(enabled: boolean): void {
	if (typeof document === 'undefined') {
		return;
	}

	if (enabled) {
		document.documentElement.classList.add(OLED_CLASS);
	} else {
		document.documentElement.classList.remove(OLED_CLASS);
	}

	updateAppearanceCache({ oled: enabled });

	syncBrowserThemeColor();
}

const NO_BLUR_CLASS = 'no-blur';
const REDUCE_EFFECTS_CLASS = 'reduce-effects';

/**
 * Toggle glass / backdrop-blur effects. When disabled, the `no-blur` class on
 * <html> drives layout.css to strip every backdrop-filter and make glass surfaces
 * opaque — the main lever for cutting GPU usage on Firefox-based browsers.
 */
export function applyGlassEffects(enabled: boolean): void {
	if (typeof document === 'undefined') {
		return;
	}

	document.documentElement.classList.toggle(NO_BLUR_CLASS, !enabled);
	updateAppearanceCache({ noBlur: !enabled });
}

/**
 * Toggle decorative, always-on interface animations (ambient login shimmer,
 * loading-bar glow, pulse indicators). When disabled we add a `reduce-effects`
 * class to <html> and layout.css halts those animations.
 */
export function applyInterfaceAnimations(enabled: boolean): void {
	if (typeof document === 'undefined') {
		return;
	}

	document.documentElement.classList.toggle(REDUCE_EFFECTS_CLASS, !enabled);
	updateAppearanceCache({ reduceEffects: !enabled });
}

export const FONT_SIZE_MIN = 12;
export const FONT_SIZE_MAX = 20;
export const FONT_SIZE_DEFAULT = 14; // matches `html { font-size: 14px }` in layout.css

/**
 * Apply the user's preferred root font size. The UI is sized in `rem` off the
 * root element, so this scales text and spacing together (a whole-UI zoom). At
 * the default size we remove the inline override so the CSS rule wins.
 */
export function applyFontSize(px?: number | null): void {
	if (typeof document === 'undefined') {
		return;
	}

	const root = document.documentElement;

	if (px == null || px === FONT_SIZE_DEFAULT) {
		root.style.removeProperty('font-size');
		updateAppearanceCache({ fontSize: null });
		return;
	}

	const clamped = Math.min(FONT_SIZE_MAX, Math.max(FONT_SIZE_MIN, Math.round(px)));
	root.style.fontSize = `${clamped}px`;
	updateAppearanceCache({ fontSize: clamped });
}