Add custom theme support
This commit is contained in:
1 parent
641aacf346
commit
86a3906a9d
9 files changed
+369
-20
No files matched your search
Generated
+9
-2
@@ -44,6 +44,7 @@
|
||||
"immer": "^9.0.21",
|
||||
"is-hotkey": "^0.2.0",
|
||||
"jotai": "^2.18.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"linkify-react": "^4.3.2",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"matrix-js-sdk": "^38.4.0",
|
||||
@@ -79,6 +80,7 @@
|
||||
"@types/chroma-js": "^3.1.2",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/is-hotkey": "^0.1.10",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "24.10.13",
|
||||
"@types/prismjs": "^1.26.6",
|
||||
"@types/react": "^18.3.28",
|
||||
@@ -5797,6 +5799,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/js-yaml": {
|
||||
"version": "4.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",
|
||||
"integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
@@ -7259,7 +7268,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/aria-query": {
|
||||
@@ -10532,7 +10540,6 @@
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
"immer": "^9.0.21",
|
||||
"is-hotkey": "^0.2.0",
|
||||
"jotai": "^2.18.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"linkify-react": "^4.3.2",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"matrix-js-sdk": "^38.4.0",
|
||||
@@ -93,6 +94,7 @@
|
||||
"@types/chroma-js": "^3.1.2",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/is-hotkey": "^0.1.10",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "24.10.13",
|
||||
"@types/prismjs": "^1.26.6",
|
||||
"@types/react": "^18.3.28",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import React from 'react';
|
||||
import { Box, Button, Icon, IconButton, Icons, Text, color } from 'folds';
|
||||
import { SequenceCard } from '../../../components/sequence-card';
|
||||
import { SettingTile } from '../../../components/setting-tile';
|
||||
import { SequenceCardStyle } from '../styles.css';
|
||||
import { useCustomThemes } from '../../../hooks/useCustomThemes';
|
||||
|
||||
export function CustomThemeManager() {
|
||||
const { customThemes, error, fileInputRef, triggerUpload, handleFileChange, deleteTheme } =
|
||||
useCustomThemes();
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Box alignItems="Center" gap="200">
|
||||
<Text size="L400">Custom Themes</Text>
|
||||
<IconButton size="300" variant="Surface" radii="300" onClick={triggerUpload}>
|
||||
<Icon size="200" src={Icons.Plus} />
|
||||
</IconButton>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".yml,.yaml"
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</Box>
|
||||
{error && (
|
||||
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
||||
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||
{error}
|
||||
</Text>
|
||||
</SequenceCard>
|
||||
)}
|
||||
{customThemes.map((theme) => (
|
||||
<SequenceCard
|
||||
key={theme.id}
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
>
|
||||
<SettingTile
|
||||
title={theme.name}
|
||||
description={theme.kind === 'light' ? 'Light theme' : 'Dark theme'}
|
||||
after={
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
onClick={() => deleteTheme(theme.id)}
|
||||
>
|
||||
<Text size="B300">Delete</Text>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
} from '$hooks/useTheme';
|
||||
import { stopPropagation } from '$appUtils/keyboard';
|
||||
import { SequenceCardStyle } from '../styles.css';
|
||||
import { CustomThemeManager } from './CustomThemeManager';
|
||||
|
||||
type ThemeSelectorProps = {
|
||||
themeNames: Record<string, string>;
|
||||
@@ -336,6 +337,7 @@ export function Appearance() {
|
||||
return (
|
||||
<Box direction="Column" gap="700">
|
||||
<ThemeSettings />
|
||||
<CustomThemeManager />
|
||||
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Visual Tweaks</Text>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { ChangeEventHandler, useCallback, useRef, useState } from 'react';
|
||||
import { useAtom } from 'jotai';
|
||||
import { customThemesAtom } from '../state/customThemes';
|
||||
import {
|
||||
CustomThemeData,
|
||||
parseCustomThemeYaml,
|
||||
removeCustomThemeStyle,
|
||||
} from '../utils/customTheme';
|
||||
|
||||
export function useCustomThemes() {
|
||||
const [customThemes, setCustomThemes] = useAtom(customThemesAtom);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const triggerUpload = useCallback(() => {
|
||||
fileInputRef.current?.click();
|
||||
}, []);
|
||||
|
||||
const handleFileChange: ChangeEventHandler<HTMLInputElement> = useCallback(
|
||||
(evt) => {
|
||||
setError(undefined);
|
||||
const file = evt.target.files?.[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
try {
|
||||
const themeData = parseCustomThemeYaml(reader.result as string);
|
||||
setCustomThemes([...customThemes, themeData]);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to parse theme file');
|
||||
}
|
||||
};
|
||||
reader.readAsText(file);
|
||||
evt.target.value = '';
|
||||
},
|
||||
[customThemes, setCustomThemes]
|
||||
);
|
||||
|
||||
const deleteTheme = useCallback(
|
||||
(id: string) => {
|
||||
const theme = customThemes.find((t: CustomThemeData) => t.id === id);
|
||||
if (theme) removeCustomThemeStyle(theme);
|
||||
setCustomThemes(customThemes.filter((t: CustomThemeData) => t.id !== id));
|
||||
},
|
||||
[customThemes, setCustomThemes]
|
||||
);
|
||||
|
||||
return {
|
||||
customThemes,
|
||||
error,
|
||||
fileInputRef,
|
||||
triggerUpload,
|
||||
handleFileChange,
|
||||
deleteTheme,
|
||||
};
|
||||
}
|
||||
+39
-17
@@ -10,6 +10,9 @@ import {
|
||||
} from '../../colors.css';
|
||||
import { settingsAtom } from '../state/settings';
|
||||
import { useSetting } from '../state/hooks/settings';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { customThemesAtom } from '../state/customThemes';
|
||||
import { CustomThemeData, injectCustomThemeStyle } from '../utils/customTheme';
|
||||
|
||||
export enum ThemeKind {
|
||||
Light = 'light',
|
||||
@@ -54,27 +57,46 @@ export const CinnyDarkTheme: Theme = {
|
||||
classNames: ['cinny-dark-theme', cinnyDarkTheme, onDarkFontWeight, 'prism-dark'],
|
||||
};
|
||||
|
||||
export const useThemes = (): Theme[] => {
|
||||
const themes: Theme[] = useMemo(
|
||||
() => [LightTheme, SilverTheme, DarkTheme, ButterTheme, RosePineTheme, CinnyDarkTheme],
|
||||
[]
|
||||
);
|
||||
const BUILTIN_THEMES: Theme[] = [LightTheme, SilverTheme, DarkTheme, ButterTheme, RosePineTheme];
|
||||
|
||||
return themes;
|
||||
const BUILTIN_THEME_NAMES: Record<string, string> = {
|
||||
[LightTheme.id]: 'Light',
|
||||
[SilverTheme.id]: 'Silver',
|
||||
[DarkTheme.id]: 'Dark',
|
||||
[ButterTheme.id]: 'Butter',
|
||||
[RosePineTheme.id]: 'Rose Pine',
|
||||
};
|
||||
|
||||
export const useThemeNames = (): Record<string, string> =>
|
||||
useMemo(
|
||||
() => ({
|
||||
[LightTheme.id]: 'Light',
|
||||
[SilverTheme.id]: 'Silver',
|
||||
[DarkTheme.id]: 'Dark',
|
||||
[ButterTheme.id]: 'Butter',
|
||||
[CinnyDarkTheme.id]: 'Cinny Dark',
|
||||
[RosePineTheme.id]: 'Rose Pine',
|
||||
}),
|
||||
[]
|
||||
function customThemeDataToTheme(data: CustomThemeData): Theme {
|
||||
const className = injectCustomThemeStyle(data);
|
||||
const fontWeight = data.kind === ThemeKind.Light ? onLightFontWeight : onDarkFontWeight;
|
||||
const prism = data.kind === ThemeKind.Light ? 'prism-light' : 'prism-dark';
|
||||
return {
|
||||
id: data.id,
|
||||
kind: data.kind,
|
||||
classNames: [className, fontWeight, prism],
|
||||
};
|
||||
}
|
||||
|
||||
export const useThemes = (): Theme[] => {
|
||||
const customThemes = useAtomValue(customThemesAtom);
|
||||
return useMemo(
|
||||
() => [...BUILTIN_THEMES, ...customThemes.map(customThemeDataToTheme)],
|
||||
[customThemes]
|
||||
);
|
||||
};
|
||||
|
||||
export const useThemeNames = (): Record<string, string> => {
|
||||
const customThemes = useAtomValue(customThemesAtom);
|
||||
return useMemo(() => {
|
||||
const names: Record<string, string> = { ...BUILTIN_THEME_NAMES };
|
||||
customThemes.forEach((t) => {
|
||||
names[t.id] = t.name;
|
||||
});
|
||||
return names;
|
||||
}, [customThemes]);
|
||||
};
|
||||
|
||||
|
||||
export const useSystemThemeKind = (): ThemeKind => {
|
||||
const darkModeQueryList = useMemo(() => window.matchMedia('(prefers-color-scheme: dark)'), []);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { ReactNode, useEffect } from 'react';
|
||||
import { configClass, varsClass } from 'folds';
|
||||
import { color, configClass, varsClass } from 'folds';
|
||||
import {
|
||||
DarkTheme,
|
||||
LightTheme,
|
||||
@@ -11,6 +11,13 @@ import {
|
||||
import { useSetting } from '../state/hooks/settings';
|
||||
import { settingsAtom } from '../state/settings';
|
||||
|
||||
const BG_VAR_NAME = color.Background.Container.replace(/^var\((.+)\)$/, '$1');
|
||||
|
||||
function syncHtmlBackground(): void {
|
||||
const bg = getComputedStyle(document.body).getPropertyValue(BG_VAR_NAME).trim();
|
||||
document.documentElement.style.setProperty('--pwa-canvas-bg', bg || '#ffffff');
|
||||
}
|
||||
|
||||
export function UnAuthRouteThemeManager() {
|
||||
const systemThemeKind = useSystemThemeKind();
|
||||
|
||||
@@ -23,6 +30,7 @@ export function UnAuthRouteThemeManager() {
|
||||
if (systemThemeKind === ThemeKind.Light) {
|
||||
document.body.classList.add(...LightTheme.classNames);
|
||||
}
|
||||
syncHtmlBackground();
|
||||
}, [systemThemeKind]);
|
||||
|
||||
return null;
|
||||
@@ -37,6 +45,7 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) {
|
||||
document.body.classList.add(configClass, varsClass);
|
||||
|
||||
document.body.classList.add(...activeTheme.classNames);
|
||||
syncHtmlBackground();
|
||||
|
||||
if (monochromeMode) {
|
||||
document.body.style.filter = 'grayscale(1)';
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { atom } from 'jotai';
|
||||
import { CustomThemeData } from '../utils/customTheme';
|
||||
|
||||
const STORAGE_KEY = 'custom-themes';
|
||||
|
||||
export const getCustomThemes = (): CustomThemeData[] => {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return [];
|
||||
return JSON.parse(raw) as CustomThemeData[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const setCustomThemes = (themes: CustomThemeData[]) => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(themes));
|
||||
};
|
||||
|
||||
const baseCustomThemes = atom<CustomThemeData[]>(getCustomThemes());
|
||||
|
||||
export const customThemesAtom = atom<CustomThemeData[], [CustomThemeData[]], undefined>(
|
||||
(get) => get(baseCustomThemes),
|
||||
(_get, set, update) => {
|
||||
set(baseCustomThemes, update);
|
||||
setCustomThemes(update);
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,163 @@
|
||||
import { load } from 'js-yaml';
|
||||
import { color } from 'folds';
|
||||
import { ThemeKind } from '../hooks/useTheme';
|
||||
|
||||
export interface CustomThemeData {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: ThemeKind;
|
||||
colors: ThemeColorData;
|
||||
}
|
||||
|
||||
interface ColorGroup5 {
|
||||
Container: string;
|
||||
ContainerHover: string;
|
||||
ContainerActive: string;
|
||||
ContainerLine: string;
|
||||
OnContainer: string;
|
||||
}
|
||||
|
||||
interface ColorGroup10 extends ColorGroup5 {
|
||||
Main: string;
|
||||
MainHover: string;
|
||||
MainActive: string;
|
||||
MainLine: string;
|
||||
OnMain: string;
|
||||
}
|
||||
|
||||
interface OtherGroup {
|
||||
FocusRing: string;
|
||||
Shadow: string;
|
||||
Overlay: string;
|
||||
}
|
||||
|
||||
export interface ThemeColorData {
|
||||
Background: ColorGroup5;
|
||||
Surface: ColorGroup5;
|
||||
SurfaceVariant: ColorGroup5;
|
||||
Primary: ColorGroup10;
|
||||
Secondary: ColorGroup10;
|
||||
Success: ColorGroup10;
|
||||
Warning: ColorGroup10;
|
||||
Critical: ColorGroup10;
|
||||
Other: OtherGroup;
|
||||
}
|
||||
|
||||
const COLOR_GROUP_5_KEYS: (keyof ColorGroup5)[] = [
|
||||
'Container',
|
||||
'ContainerHover',
|
||||
'ContainerActive',
|
||||
'ContainerLine',
|
||||
'OnContainer',
|
||||
];
|
||||
|
||||
const COLOR_GROUP_10_KEYS: (keyof ColorGroup10)[] = [
|
||||
'Main',
|
||||
'MainHover',
|
||||
'MainActive',
|
||||
'MainLine',
|
||||
'OnMain',
|
||||
...COLOR_GROUP_5_KEYS,
|
||||
];
|
||||
|
||||
const OTHER_KEYS: (keyof OtherGroup)[] = ['FocusRing', 'Shadow', 'Overlay'];
|
||||
|
||||
function isObject(val: unknown): val is Record<string, unknown> {
|
||||
return typeof val === 'object' && val !== null && !Array.isArray(val);
|
||||
}
|
||||
|
||||
function hasStringKeys(obj: Record<string, unknown>, keys: string[]): boolean {
|
||||
return keys.every((k) => typeof obj[k] === 'string');
|
||||
}
|
||||
|
||||
function validateColorData(data: unknown): data is ThemeColorData {
|
||||
if (!isObject(data)) return false;
|
||||
const groups5: (keyof ThemeColorData)[] = ['Background', 'Surface', 'SurfaceVariant'];
|
||||
const groups10: (keyof ThemeColorData)[] = [
|
||||
'Primary',
|
||||
'Secondary',
|
||||
'Success',
|
||||
'Warning',
|
||||
'Critical',
|
||||
];
|
||||
|
||||
for (const g of groups5) {
|
||||
if (!isObject(data[g])) return false;
|
||||
if (!hasStringKeys(data[g] as Record<string, unknown>, COLOR_GROUP_5_KEYS)) return false;
|
||||
}
|
||||
for (const g of groups10) {
|
||||
if (!isObject(data[g])) return false;
|
||||
if (!hasStringKeys(data[g] as Record<string, unknown>, COLOR_GROUP_10_KEYS)) return false;
|
||||
}
|
||||
if (!isObject(data.Other)) return false;
|
||||
if (!hasStringKeys(data.Other as Record<string, unknown>, OTHER_KEYS)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function parseCustomThemeYaml(yamlStr: string): CustomThemeData {
|
||||
const raw = load(yamlStr);
|
||||
if (!isObject(raw)) throw new Error('Invalid theme file: root must be an object');
|
||||
if (typeof raw.name !== 'string' || raw.name.trim() === '')
|
||||
throw new Error('Invalid theme file: "name" is required');
|
||||
if (raw.kind !== 'light' && raw.kind !== 'dark')
|
||||
throw new Error('Invalid theme file: "kind" must be "light" or "dark"');
|
||||
if (!validateColorData(raw.colors))
|
||||
throw new Error('Invalid theme file: "colors" section is missing or incomplete');
|
||||
|
||||
return {
|
||||
id: `custom-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
name: raw.name as string,
|
||||
kind: raw.kind as ThemeKind,
|
||||
colors: raw.colors as ThemeColorData,
|
||||
};
|
||||
}
|
||||
|
||||
function extractVarName(cssVar: string): string {
|
||||
const match = cssVar.match(/^var\((.+)\)$/);
|
||||
return match ? match[1] : cssVar;
|
||||
}
|
||||
|
||||
function buildCssVarMap(): Record<string, Record<string, string>> {
|
||||
const map: Record<string, Record<string, string>> = {};
|
||||
for (const [groupName, group] of Object.entries(color)) {
|
||||
map[groupName] = {};
|
||||
for (const [key, val] of Object.entries(group as Record<string, string>)) {
|
||||
map[groupName][key] = extractVarName(val);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
const cssVarMap = buildCssVarMap();
|
||||
|
||||
export function injectCustomThemeStyle(themeData: CustomThemeData): string {
|
||||
const className = `custom-theme-${themeData.id}`;
|
||||
const existing = document.getElementById(className);
|
||||
if (existing) return className;
|
||||
|
||||
const lines: string[] = [];
|
||||
for (const [groupName, group] of Object.entries(themeData.colors)) {
|
||||
const varGroup = cssVarMap[groupName];
|
||||
if (!varGroup) continue;
|
||||
for (const [key, value] of Object.entries(group as Record<string, string>)) {
|
||||
const varName = varGroup[key];
|
||||
if (varName) lines.push(`${varName}:${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
const style = document.createElement('style');
|
||||
style.id = className;
|
||||
style.textContent = `.${className}{${lines.join(';')}}`;
|
||||
document.head.appendChild(style);
|
||||
return className;
|
||||
}
|
||||
|
||||
export function removeCustomThemeStyle(themeData: CustomThemeData): void {
|
||||
const className = `custom-theme-${themeData.id}`;
|
||||
document.getElementById(className)?.remove();
|
||||
}
|
||||
|
||||
export function injectAllCustomThemeStyles(themes: CustomThemeData[]): void {
|
||||
themes.forEach(injectCustomThemeStyle);
|
||||
}
|
||||
Reference in new issue
Block a user