diff --git a/package-lock.json b/package-lock.json index 351a7880..bf29eebd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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" diff --git a/package.json b/package.json index e7326695..ebb1f118 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/app/features/settings/cosmetics/CustomThemeManager.tsx b/src/app/features/settings/cosmetics/CustomThemeManager.tsx new file mode 100644 index 00000000..669e1d14 --- /dev/null +++ b/src/app/features/settings/cosmetics/CustomThemeManager.tsx @@ -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 ( + + + Custom Themes + + + + + + {error && ( + + + {error} + + + )} + {customThemes.map((theme) => ( + + deleteTheme(theme.id)} + > + Delete + + } + /> + + ))} + + ); +} \ No newline at end of file diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index ae1a1118..8fefdb9e 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -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; @@ -336,6 +337,7 @@ export function Appearance() { return ( + Visual Tweaks diff --git a/src/app/hooks/useCustomThemes.ts b/src/app/hooks/useCustomThemes.ts new file mode 100644 index 00000000..8c216216 --- /dev/null +++ b/src/app/hooks/useCustomThemes.ts @@ -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(null); + const [error, setError] = useState(); + + const triggerUpload = useCallback(() => { + fileInputRef.current?.click(); + }, []); + + const handleFileChange: ChangeEventHandler = 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, + }; +} \ No newline at end of file diff --git a/src/app/hooks/useTheme.ts b/src/app/hooks/useTheme.ts index 8d5660a1..49973fa2 100644 --- a/src/app/hooks/useTheme.ts +++ b/src/app/hooks/useTheme.ts @@ -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 = { + [LightTheme.id]: 'Light', + [SilverTheme.id]: 'Silver', + [DarkTheme.id]: 'Dark', + [ButterTheme.id]: 'Butter', + [RosePineTheme.id]: 'Rose Pine', }; -export const useThemeNames = (): Record => - 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 => { + const customThemes = useAtomValue(customThemesAtom); + return useMemo(() => { + const names: Record = { ...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)'), []); diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index 69d50cdb..f2009f6f 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -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)'; diff --git a/src/app/state/customThemes.ts b/src/app/state/customThemes.ts new file mode 100644 index 00000000..369fe817 --- /dev/null +++ b/src/app/state/customThemes.ts @@ -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(getCustomThemes()); + +export const customThemesAtom = atom( + (get) => get(baseCustomThemes), + (_get, set, update) => { + set(baseCustomThemes, update); + setCustomThemes(update); + } +); \ No newline at end of file diff --git a/src/app/utils/customTheme.ts b/src/app/utils/customTheme.ts new file mode 100644 index 00000000..8e4ee0b1 --- /dev/null +++ b/src/app/utils/customTheme.ts @@ -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 { + return typeof val === 'object' && val !== null && !Array.isArray(val); +} + +function hasStringKeys(obj: Record, 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, COLOR_GROUP_5_KEYS)) return false; + } + for (const g of groups10) { + if (!isObject(data[g])) return false; + if (!hasStringKeys(data[g] as Record, COLOR_GROUP_10_KEYS)) return false; + } + if (!isObject(data.Other)) return false; + if (!hasStringKeys(data.Other as Record, 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> { + const map: Record> = {}; + for (const [groupName, group] of Object.entries(color)) { + map[groupName] = {}; + for (const [key, val] of Object.entries(group as Record)) { + 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)) { + 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); +} \ No newline at end of file