diff --git a/config.json b/config.json index 0767b7837..02ed78536 100644 --- a/config.json +++ b/config.json @@ -16,9 +16,7 @@ "settingsLinkBaseUrl": "https://app.sable.moe", "themeCatalogBaseUrl": "https://raw.githubusercontent.com/SableClient/themes/main/", - "themeCatalogApprovedHostPrefixes": [ - "https://raw.githubusercontent.com/SableClient/themes/" - ], + "themeCatalogApprovedHostPrefixes": ["https://raw.githubusercontent.com/SableClient/themes/"], "slidingSync": { "enabled": true diff --git a/src/app/features/settings/cosmetics/Cosmetics.tsx b/src/app/features/settings/cosmetics/Cosmetics.tsx index 3d50d886e..234d81af4 100644 --- a/src/app/features/settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/settings/cosmetics/Cosmetics.tsx @@ -258,17 +258,23 @@ type CosmeticsProps = { }; export function Cosmetics({ requestBack, requestClose }: CosmeticsProps) { + const [themeBrowserOpen, setThemeBrowserOpen] = useState(false); + return ( - - - - - + + {!themeBrowserOpen && ( + <> + + + + + + )} diff --git a/src/app/features/settings/cosmetics/ThemeAppearanceSection.tsx b/src/app/features/settings/cosmetics/ThemeAppearanceSection.tsx new file mode 100644 index 000000000..7e82de9df --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeAppearanceSection.tsx @@ -0,0 +1,249 @@ +import { useCallback, useEffect, useState } from 'react'; +import { Box, Button, Switch, Text } from 'folds'; + +import { SettingMenuSelector } from '$components/setting-menu-selector'; +import { SequenceCard } from '$components/sequence-card'; +import { SettingTile } from '$components/setting-tile'; +import { DarkTheme, LightTheme, Theme, ThemeKind, useThemeNames, useThemes } from '$hooks/useTheme'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { SequenceCardStyle } from '$features/settings/styles.css'; +import { useStore } from 'jotai/react'; + +import { useThemeCatalogOnboardingGate } from './ThemeCatalogOnboarding'; +import { ThemeCatalogSettings, usePatchSettings } from './ThemeCatalogSettings'; + +function makeThemeOptions(themes: Theme[], themeNames: Record) { + return themes.map((theme) => ({ + value: theme.id, + label: themeNames[theme.id] ?? theme.id, + })); +} + +function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) { + const themes = useThemes(); + const themeNames = useThemeNames(); + const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId'); + + const themeOptions = makeThemeOptions(themes, themeNames); + const selectedThemeId = + themeOptions.find((theme) => theme.value === themeId)?.value ?? LightTheme.id; + + return ( + + ); +} + +function SystemThemePreferences() { + const themeNames = useThemeNames(); + const themes = useThemes(); + const [lightThemeId, setLightThemeId] = useSetting(settingsAtom, 'lightThemeId'); + const [darkThemeId, setDarkThemeId] = useSetting(settingsAtom, 'darkThemeId'); + + const lightThemes = themes.filter((theme) => theme.kind === ThemeKind.Light); + const darkThemes = themes.filter((theme) => theme.kind === ThemeKind.Dark); + const lightThemeOptions = makeThemeOptions(lightThemes, themeNames); + const darkThemeOptions = makeThemeOptions(darkThemes, themeNames); + + const selectedLightThemeId = + lightThemeOptions.find((theme) => theme.value === lightThemeId)?.value ?? LightTheme.id; + const selectedDarkThemeId = + darkThemeOptions.find((theme) => theme.value === darkThemeId)?.value ?? DarkTheme.id; + + return ( + + + } + /> + + } + /> + + ); +} + +function ClassicThemeSection({ onBrowseCatalog }: { onBrowseCatalog: () => void }) { + const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); + + return ( + + + } + /> + {systemTheme && } + + + + } + /> + + + + + Browse catalog… + + } + /> + + + ); +} + +function RemoteCatalogThemeSection({ + onBrowseOpenChange, +}: { + onBrowseOpenChange?: (open: boolean) => void; +}) { + const [browseOpen, setBrowseOpen] = useState(false); + const setBrowseOpenSafe = (open: boolean) => { + setBrowseOpen(open); + onBrowseOpenChange?.(open); + }; + + useEffect(() => { + onBrowseOpenChange?.(browseOpen); + }, [browseOpen, onBrowseOpenChange]); + + return ( + + {!browseOpen ? ( + <> + + + + setBrowseOpenSafe(true)} + > + Browse themes + + } + /> + + + + + ) : ( + <> + + setBrowseOpenSafe(false)} + > + Back + + } + /> + + + + + )} + + ); +} + +export function ThemeAppearanceSection({ + onBrowseOpenChange, +}: { + onBrowseOpenChange?: (open: boolean) => void; +} = {}) { + const store = useStore(); + const [onboardingDone] = useSetting(settingsAtom, 'themeCatalogOnboardingDone'); + const [catalogEnabled] = useSetting(settingsAtom, 'themeRemoteCatalogEnabled'); + + useEffect(() => { + if (!catalogEnabled) onBrowseOpenChange?.(false); + }, [catalogEnabled, onBrowseOpenChange]); + + const completeOnboarding = useCallback( + (enabled: boolean) => { + const next = { ...store.get(settingsAtom), themeCatalogOnboardingDone: true }; + next.themeRemoteCatalogEnabled = enabled; + store.set(settingsAtom, next); + }, + [store] + ); + + const { dialog } = useThemeCatalogOnboardingGate(onboardingDone, completeOnboarding); + + const patchSettings = usePatchSettings(); + const enableCatalog = useCallback(() => { + patchSettings({ themeRemoteCatalogEnabled: true, themeCatalogOnboardingDone: true }); + }, [patchSettings]); + + return ( + + Theme + {dialog} + {catalogEnabled ? ( + + ) : ( + + )} + + ); +} diff --git a/src/app/features/settings/cosmetics/ThemeCatalogOnboarding.tsx b/src/app/features/settings/cosmetics/ThemeCatalogOnboarding.tsx new file mode 100644 index 000000000..568bc266e --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeCatalogOnboarding.tsx @@ -0,0 +1,104 @@ +import { useCallback, useEffect, useState } from 'react'; +import FocusTrap from 'focus-trap-react'; +import { + Box, + Button, + config, + Dialog, + Header, + Icon, + IconButton, + Icons, + Overlay, + OverlayBackdrop, + OverlayCenter, + Text, +} from 'folds'; + +import { stopPropagation } from '$utils/keyboard'; + +type ThemeCatalogOnboardingProps = { + open: boolean; + onEnable: () => void; + onDecline: () => void; +}; + +export function ThemeCatalogOnboarding({ open, onEnable, onDecline }: ThemeCatalogOnboardingProps) { + return ( + }> + + + +
+ + Remote themes + + + + +
+ + + Load themes from the official Sable theme catalog on GitHub? You can browse + previews, save favorites locally, and sync them with light and dark mode. If you + choose not to, you can keep using the built-in Light and Dark themes only. + + + + + + +
+
+
+
+ ); +} + +export function useThemeCatalogOnboardingGate( + onboardingDone: boolean, + onComplete: (enabled: boolean) => void +) { + const [open, setOpen] = useState(false); + + useEffect(() => { + if (!onboardingDone) { + setOpen(true); + } + }, [onboardingDone]); + + const handleEnable = useCallback(() => { + setOpen(false); + onComplete(true); + }, [onComplete]); + + const handleDecline = useCallback(() => { + setOpen(false); + onComplete(false); + }, [onComplete]); + + return { + open, + dialog: ( + + ), + }; +} diff --git a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx index 94f183ad7..fbde6b5b2 100644 --- a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx +++ b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx @@ -1,13 +1,26 @@ import { type ChangeEventHandler, useCallback, useMemo, useState } from 'react'; import { useQuery } from '@tanstack/react-query'; -import { Box, Button, Chip, config, Input, Spinner, Switch, Text, toRem } from 'folds'; +import { + Box, + Button, + Chip, + config, + Icon, + IconButton, + Icons, + Input, + Spinner, + Switch, + Text, + toRem, +} from 'folds'; import { useStore } from 'jotai/react'; import { useClientConfig } from '$hooks/useClientConfig'; import { ThemeKind } from '$hooks/useTheme'; import { trimTrailingSlash } from '$utils/common'; import { useSetting } from '$state/hooks/settings'; -import { settingsAtom, type Settings } from '$state/settings'; +import { settingsAtom, type Settings, type ThemeRemoteFavorite } from '$state/settings'; import { SequenceCardStyle } from '$features/settings/styles.css'; import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; @@ -28,13 +41,26 @@ const DEFAULT_CATALOG_BASE = 'https://raw.githubusercontent.com/SableClient/them export type CatalogPreviewRow = ThemePair & { previewText: string; displayName: string; + author?: string; kind: ThemeKind; contrast: SableThemeContrast; tags: string[]; fullInstallUrl: string; }; -function usePatchSettings() { +export type LocalPreviewRow = ThemeRemoteFavorite & { + previewText: string; + displayName: string; + contrast: SableThemeContrast; + tags: string[]; +}; + +function previewUrlFromFullThemeUrl(fullUrl: string): string | undefined { + if (!/\.sable\.css$/i.test(fullUrl)) return undefined; + return fullUrl.replace(/\.sable\.css$/i, '.preview.sable.css'); +} + +export function usePatchSettings() { const store = useStore(); return useCallback( (partial: Partial) => { @@ -105,19 +131,28 @@ function ThemePreviewMini({ scopeClass, styleBlock }: { scopeClass: string; styl ); } -export function ThemeCatalogSettings() { +export type ThemeCatalogSettingsMode = 'full' | 'local' | 'chat' | 'remote'; + +export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSettingsMode }) { const clientConfig = useClientConfig(); const patchSettings = usePatchSettings(); const configBase = clientConfig.themeCatalogBaseUrl?.trim(); const catalogBase = `${trimTrailingSlash(configBase && configBase.length > 0 ? configBase : DEFAULT_CATALOG_BASE)}/`; - const [catalogEnabled, setCatalogEnabled] = useSetting(settingsAtom, 'themeRemoteCatalogEnabled'); + const isRemoteMode = mode === 'remote' || mode === 'full'; + const isChatMode = mode === 'chat' || mode === 'full'; + const isLocalMode = mode === 'local' || mode === 'full'; + + const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites'); + const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); + const [manualRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl'); + const [lightRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl'); + const [darkRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl'); const [chatAny, setChatAny] = useSetting(settingsAtom, 'themeChatPreviewAnyUrl'); const [chatApprovedOnly, setChatApprovedOnly] = useSetting( settingsAtom, 'themeChatPreviewApprovedCatalogOnly' ); - const [systemTheme] = useSetting(settingsAtom, 'useSystemTheme'); const [search, setSearch] = useState(''); const [kindFilter, setKindFilter] = useState<'all' | 'light' | 'dark'>('all'); @@ -128,7 +163,7 @@ export function ThemeCatalogSettings() { const pairsQuery = useQuery({ queryKey: ['theme-catalog-pairs', catalogBase], queryFn: () => listThemePairsFromCatalog(catalogBase), - enabled: catalogEnabled, + enabled: isRemoteMode, staleTime: 5 * 60_000, }); @@ -154,6 +189,7 @@ export function ThemeCatalogSettings() { ...pair, previewText, displayName: meta.name?.trim() || pair.basename, + author: meta.author?.trim() || undefined, kind, contrast, tags: meta.tags ?? [], @@ -163,7 +199,7 @@ export function ThemeCatalogSettings() { ); return rows; }, - enabled: catalogEnabled && Boolean(pairsQuery.data?.length), + enabled: isRemoteMode && Boolean(pairsQuery.data?.length), staleTime: 10 * 60_000, }); @@ -184,54 +220,152 @@ export function ThemeCatalogSettings() { }); }, [previewsQuery.data, search, kindFilter, contrastFilter]); - const prefetchFull = useCallback((url: string) => { - const run = async () => { - try { - const res = await fetch(url, { mode: 'cors' }); - if (!res.ok) return; - const text = await res.text(); - await putCachedThemeCss(url, text); - } catch { - /* ignore */ - } - }; - run(); + const localPreviewsQuery = useQuery({ + queryKey: ['theme-local-previews', favorites.map((f) => f.fullUrl).join('|')], + enabled: isLocalMode && favorites.length > 0, + staleTime: 10 * 60_000, + queryFn: async (): Promise => { + const rows = await Promise.all( + favorites.map(async (fav) => { + const previewUrl = previewUrlFromFullThemeUrl(fav.fullUrl); + if (!previewUrl) return undefined; + + try { + const res = await fetch(previewUrl, { mode: 'cors' }); + if (!res.ok) return undefined; + const previewText = await res.text(); + const meta = parseSableThemeMetadata(previewText); + const displayName = meta.name?.trim() || fav.displayName || fav.basename; + const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; + return { + ...fav, + previewText, + displayName, + contrast, + tags: meta.tags ?? [], + }; + } catch { + return undefined; + } + }) + ); + + return rows.filter((r): r is LocalPreviewRow => Boolean(r)); + }, + }); + + const removeFavorite = useCallback( + (fullUrl: string) => { + patchSettings({ + themeRemoteFavorites: favorites.filter((f) => f.fullUrl !== fullUrl), + }); + }, + [favorites, patchSettings] + ); + + const applyFavoriteToLight = useCallback( + (row: LocalPreviewRow) => { + patchSettings({ + themeRemoteLightFullUrl: row.fullUrl, + themeRemoteLightKind: row.kind, + }); + }, + [patchSettings] + ); + + const applyFavoriteToDark = useCallback( + (row: LocalPreviewRow) => { + patchSettings({ + themeRemoteDarkFullUrl: row.fullUrl, + themeRemoteDarkKind: row.kind, + }); + }, + [patchSettings] + ); + + const applyFavoriteToManual = useCallback( + (row: LocalPreviewRow) => { + patchSettings({ + themeRemoteManualFullUrl: row.fullUrl, + themeRemoteManualKind: row.kind, + }); + }, + [patchSettings] + ); + + const useBuiltinForLightSlot = useCallback( + () => + patchSettings({ + themeRemoteLightFullUrl: undefined, + themeRemoteLightKind: undefined, + }), + [patchSettings] + ); + + const useBuiltinForDarkSlot = useCallback( + () => + patchSettings({ + themeRemoteDarkFullUrl: undefined, + themeRemoteDarkKind: undefined, + }), + [patchSettings] + ); + + const useBuiltinForManualLight = useCallback( + () => + patchSettings({ + themeRemoteManualFullUrl: undefined, + themeRemoteManualKind: undefined, + themeId: 'light-theme', + }), + [patchSettings] + ); + + const useBuiltinForManualDark = useCallback( + () => + patchSettings({ + themeRemoteManualFullUrl: undefined, + themeRemoteManualKind: undefined, + themeId: 'dark-theme', + }), + [patchSettings] + ); + + const prefetchFull = useCallback(async (url: string): Promise => { + try { + const res = await fetch(url, { mode: 'cors' }); + if (!res.ok) return false; + const text = await res.text(); + await putCachedThemeCss(url, text); + return true; + } catch { + return false; + } }, []); - const installManual = useCallback( - (row: CatalogPreviewRow) => { + const toggleFavorite = useCallback( + async (row: CatalogPreviewRow) => { + const existing = favorites.find((f: ThemeRemoteFavorite) => f.fullUrl === row.fullInstallUrl); + if (existing) { + patchSettings({ + themeRemoteFavorites: favorites.filter((f) => f.fullUrl !== row.fullInstallUrl), + }); + return; + } + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const next: ThemeRemoteFavorite = { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + }; patchSettings({ - themeRemoteManualFullUrl: row.fullInstallUrl, - themeRemoteManualKind: kind, + themeRemoteFavorites: [...favorites, next], }); - prefetchFull(row.fullInstallUrl); }, - [patchSettings, prefetchFull] - ); - - const installLightSlot = useCallback( - (row: CatalogPreviewRow) => { - const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; - patchSettings({ - themeRemoteLightFullUrl: row.fullInstallUrl, - themeRemoteLightKind: kind, - }); - prefetchFull(row.fullInstallUrl); - }, - [patchSettings, prefetchFull] - ); - - const installDarkSlot = useCallback( - (row: CatalogPreviewRow) => { - const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; - patchSettings({ - themeRemoteDarkFullUrl: row.fullInstallUrl, - themeRemoteDarkKind: kind, - }); - prefetchFull(row.fullInstallUrl); - }, - [patchSettings, prefetchFull] + [favorites, patchSettings, prefetchFull] ); const clearRemote = useCallback(() => { @@ -247,84 +381,22 @@ export function ThemeCatalogSettings() { return ( - Theme catalog - - - } - /> - - - - } - /> - - - - - } - /> - - - {catalogEnabled && ( + {isChatMode && ( <> + Chat previews + - - - {configBase && configBase.length > 0 - ? 'Catalog URL (from config): ' - : 'Catalog URL (default; set themeCatalogBaseUrl in config to override): '} - {catalogBase} - - {pairsQuery.isPending && ( - - - Loading catalog… - - )} - {pairsQuery.isError && ( - - {pairsQuery.error?.message ?? 'Failed to load catalog'} - - )} - {pairsQuery.isSuccess && pairsQuery.data.length === 0 && ( - - No paired theme files found (expect *.preview.sable.css + matching *.sable.css). - - )} - + } + /> - Clear - + } /> + + )} + + {isRemoteMode && ( + <> + Browse catalog + + {(pairsQuery.isPending || pairsQuery.isError) && ( + + + {pairsQuery.isPending && ( + + + Loading catalog… + + )} + {pairsQuery.isError && ( + + {pairsQuery.error?.message ?? 'Failed to load catalog'} + + )} + + + )} {pairsQuery.isSuccess && pairsQuery.data.length > 0 && ( f.fullUrl === row.fullInstallUrl); return ( - {row.displayName} - - {kindLabel} · {row.contrast} contrast - {row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''} - - - {systemTheme ? ( - - - + + + {row.displayName} + + {kindLabel} · {row.contrast} contrast + {row.author ? ` · by ${row.author}` : ''} + {row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''} + - ) : ( - - )} + + + + ); })} @@ -474,6 +566,189 @@ export function ThemeCatalogSettings() { )} )} + + {isLocalMode && ( + <> + + } + /> + + {systemTheme ? ( + + + + + ) : ( + + + + + )} + + + + + Clear + + } + /> + + + + {localPreviewsQuery.isPending && ( + + + Loading local previews… + + )} + + {favorites.length === 0 && ( + + No saved themes yet. Star themes in the catalog to download them locally. + + )} + + {localPreviewsQuery.isSuccess && favorites.length > 0 && ( + <> + {localPreviewsQuery.data.length === 0 ? ( + + Could not load local previews. If this happens, the theme preview file may be + missing or not paired as `*.preview.sable.css`. + + ) : ( + + {localPreviewsQuery.data.map((row) => { + const vars = extractSafePreviewCustomProperties(row.previewText); + const slug = row.basename.replace(/[^a-zA-Z0-9_-]/g, '-') || 'theme'; + const scopeClass = `sable-theme-preview--${slug}`; + const styleBlock = buildPreviewStyleBlock(vars, scopeClass); + + const kindLabel = row.kind === 'dark' ? 'Dark' : 'Light'; + const isLightSelected = lightRemoteFullUrl === row.fullUrl; + const isDarkSelected = darkRemoteFullUrl === row.fullUrl; + const isManualSelected = manualRemoteFullUrl === row.fullUrl; + + return ( + + + + {row.displayName} + + {kindLabel} · {row.contrast} contrast + {row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''} + + + + removeFavorite(row.fullUrl)} + > + + + + + + + {systemTheme ? ( + + + + + ) : ( + + )} + + ); + })} + + )} + + )} + + + )} ); } diff --git a/src/app/features/settings/cosmetics/Themes.test.tsx b/src/app/features/settings/cosmetics/Themes.test.tsx index ba621537d..991518e57 100644 --- a/src/app/features/settings/cosmetics/Themes.test.tsx +++ b/src/app/features/settings/cosmetics/Themes.test.tsx @@ -6,6 +6,9 @@ import { Appearance } from './Themes'; type SettingsShape = { themeId?: string; useSystemTheme: boolean; + themeCatalogOnboardingDone: boolean; + themeRemoteCatalogEnabled: boolean; + themeRemoteFavorites: unknown[]; lightThemeId?: string; darkThemeId?: string; useSystemArboriumTheme: boolean; @@ -61,6 +64,9 @@ beforeEach(() => { currentSettings = { themeId: 'silver-theme', useSystemTheme: true, + themeCatalogOnboardingDone: true, + themeRemoteCatalogEnabled: false, + themeRemoteFavorites: [], lightThemeId: 'cinny-light-theme', darkThemeId: 'black-theme', useSystemArboriumTheme: true, @@ -94,22 +100,24 @@ const getFirstEnabledButton = (name: string) => screen.getAllByRole('button', { name }).find((node) => !node.hasAttribute('disabled')); describe('Appearance settings', () => { - it('renders Theme, Code Block Theme, and Visual Tweaks as separate sections', () => { + it('renders Theme, Display, Code Block Theme, and Visual Tweaks as separate sections', () => { render(); const themeHeading = screen.getByText('Theme'); + const displayHeading = screen.getByText('Display'); const codeBlockThemeHeading = screen.getByText('Code Block Theme'); const visualTweaksHeading = screen.getByText('Visual Tweaks'); - expect(themeHeading.compareDocumentPosition(codeBlockThemeHeading)).toBe( + expect(themeHeading.compareDocumentPosition(displayHeading)).toBe( + Node.DOCUMENT_POSITION_FOLLOWING + ); + expect(displayHeading.compareDocumentPosition(codeBlockThemeHeading)).toBe( Node.DOCUMENT_POSITION_FOLLOWING ); expect(codeBlockThemeHeading.compareDocumentPosition(visualTweaksHeading)).toBe( Node.DOCUMENT_POSITION_FOLLOWING ); - expect(screen.getByRole('button', { name: 'Silver' })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Cinny Light' })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Black' })).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: 'Light' }).length).toBeGreaterThan(0); expect(screen.getByRole('button', { name: 'GitHub Light' })).toBeInTheDocument(); expect(screen.getAllByRole('button', { name: 'Dracula' })).toHaveLength(2); expect(screen.getAllByRole('button', { name: 'Dracula' }).at(-1)).toBeDisabled(); @@ -124,7 +132,7 @@ describe('Appearance settings', () => { render(); - fireEvent.click(screen.getByRole('button', { name: 'Silver' })); + fireEvent.click(screen.getAllByRole('button', { name: 'Light' }).at(-1)!); clickLatestButton('Dark'); fireEvent.click(screen.getByRole('button', { name: 'Dracula' })); @@ -134,19 +142,6 @@ describe('Appearance settings', () => { expect(getSetter('arboriumThemeId')).toHaveBeenCalledWith('ayu-light'); }); - it('updates the system theme settings when the chip selectors change', () => { - render(); - - fireEvent.click(screen.getByRole('button', { name: 'Cinny Light' })); - clickLatestButton('Silver'); - - fireEvent.click(screen.getByRole('button', { name: 'Black' })); - clickLatestButton('Dark'); - - expect(getSetter('lightThemeId')).toHaveBeenCalledWith('silver-theme'); - expect(getSetter('darkThemeId')).toHaveBeenCalledWith('dark-theme'); - }); - it('updates the system code block theme settings when the chip selectors change', () => { render(); @@ -169,7 +164,7 @@ describe('Appearance settings', () => { render(); - expect(screen.getByRole('button', { name: 'Light' })).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: 'Light' }).length).toBeGreaterThan(0); }); it('falls back to the active code block system theme when the stored manual theme id is invalid', () => { @@ -194,7 +189,7 @@ describe('Appearance settings', () => { render(); - expect(screen.getByRole('button', { name: 'Light' })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Dark' })).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: 'Light' }).length).toBeGreaterThan(0); + expect(screen.getAllByRole('button', { name: 'Dark' }).length).toBeGreaterThan(0); }); }); diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 4852d3d3c..5e4ec7dfa 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -11,27 +11,11 @@ import { getArboriumThemeLabel, getArboriumThemeOptions, } from '$plugins/arborium'; -import { - DarkTheme, - LightTheme, - Theme, - ThemeKind, - useActiveTheme, - useSystemThemeKind, - useThemeNames, - useThemes, -} from '$hooks/useTheme'; +import { ThemeKind, useActiveTheme } from '$hooks/useTheme'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { SequenceCardStyle } from '$features/settings/styles.css'; -import { ThemeCatalogSettings } from './ThemeCatalogSettings'; - -function makeThemeOptions(themes: Theme[], themeNames: Record) { - return themes.map((theme) => ({ - value: theme.id, - label: themeNames[theme.id] ?? theme.id, - })); -} +import { ThemeAppearanceSection } from './ThemeAppearanceSection'; function makeArboriumThemeOptions(kind?: 'light' | 'dark') { const themes = kind @@ -70,86 +54,6 @@ function ThemeTrigger({ ); } -function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) { - const themes = useThemes(); - const themeNames = useThemeNames(); - const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId'); - - const themeOptions = makeThemeOptions(themes, themeNames); - const selectedThemeId = - themeOptions.find((theme) => theme.value === themeId)?.value ?? LightTheme.id; - - return ( - - ); -} - -function SystemThemePreferences() { - const themeKind = useSystemThemeKind(); - const themeNames = useThemeNames(); - const themes = useThemes(); - const [lightThemeId, setLightThemeId] = useSetting(settingsAtom, 'lightThemeId'); - const [darkThemeId, setDarkThemeId] = useSetting(settingsAtom, 'darkThemeId'); - - const lightThemes = themes.filter((theme) => theme.kind === ThemeKind.Light); - const darkThemes = themes.filter((theme) => theme.kind === ThemeKind.Dark); - const lightThemeOptions = makeThemeOptions(lightThemes, themeNames); - const darkThemeOptions = makeThemeOptions(darkThemes, themeNames); - - const selectedLightThemeId = - lightThemeOptions.find((theme) => theme.value === lightThemeId)?.value ?? LightTheme.id; - const selectedDarkThemeId = - darkThemeOptions.find((theme) => theme.value === darkThemeId)?.value ?? DarkTheme.id; - - return ( - - ( - - )} - /> - } - /> - ( - - )} - /> - } - /> - - ); -} - function SelectCodeBlockTheme({ disabled }: Readonly<{ disabled?: boolean }>) { const activeTheme = useActiveTheme(); const [arboriumThemeId, setArboriumThemeId] = useSetting(settingsAtom, 'arboriumThemeId'); @@ -281,8 +185,7 @@ function CodeBlockThemeSettings() { ); } -function ThemeSettings() { - const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); +function ThemeVisualPreferences() { const [saturation, setSaturation] = useSetting(settingsAtom, 'saturationLevel'); const [underlineLinks, setUnderlineLinks] = useSetting(settingsAtom, 'underlineLinks'); const [reducedMotion, setReducedMotion] = useSetting(settingsAtom, 'reducedMotion'); @@ -292,31 +195,7 @@ function ThemeSettings() { return ( - Theme - - - } - /> - {systemTheme && } - - - - } - /> - + Display } /> - - ); } @@ -482,49 +359,66 @@ function PageZoomInput() { ); } -export function Appearance() { +export function Appearance({ + onThemeBrowserOpenChange, +}: { + onThemeBrowserOpenChange?: (open: boolean) => void; +} = {}) { const [twitterEmoji, setTwitterEmoji] = useSetting(settingsAtom, 'twitterEmoji'); const [showEasterEggs, setShowEasterEggs] = useSetting(settingsAtom, 'showEasterEggs'); + const [themeBrowserOpen, setThemeBrowserOpen] = useState(false); return ( - - + { + setThemeBrowserOpen(open); + onThemeBrowserOpenChange?.(open); + }} + /> + {!themeBrowserOpen && ( + <> + + - - Visual Tweaks + + Visual Tweaks - - } - /> - + + } + /> + - - } - /> - + + + } + /> + - - } /> - + + } /> + - - } - /> - - + + } + /> + + + + )} ); } diff --git a/src/app/hooks/useTheme.ts b/src/app/hooks/useTheme.ts index b9c988d14..b339ee065 100755 --- a/src/app/hooks/useTheme.ts +++ b/src/app/hooks/useTheme.ts @@ -21,10 +21,7 @@ export const REMOTE_THEME_ID = 'sable-remote-theme'; const isHttpsThemeUrl = (u: string | undefined): u is string => Boolean(u && /^https:\/\//i.test(u.trim())); -function parseRemoteKind( - value: 'light' | 'dark' | undefined, - fallback: ThemeKind -): ThemeKind { +function parseRemoteKind(value: 'light' | 'dark' | undefined, fallback: ThemeKind): ThemeKind { if (value === 'dark') return ThemeKind.Dark; if (value === 'light') return ThemeKind.Light; return fallback; @@ -32,8 +29,7 @@ function parseRemoteKind( function makeRemoteTheme(url: string, kind: ThemeKind): Theme { const fw = kind === ThemeKind.Dark ? onDarkFontWeight : onLightFontWeight; - const kindClass = - kind === ThemeKind.Dark ? 'sable-remote-kind-dark' : 'sable-remote-kind-light'; + const kindClass = kind === ThemeKind.Dark ? 'sable-remote-kind-dark' : 'sable-remote-kind-light'; const legacyCssTheme = kind === ThemeKind.Dark ? 'dark-theme' : 'light-theme'; const veTheme = kind === ThemeKind.Dark ? darkTheme : lightTheme; return { @@ -107,16 +103,8 @@ export const useActiveTheme = (): Theme => { if (!systemTheme) { if (isHttpsThemeUrl(manualRemoteUrl)) { - const inferred = - themeId === 'dark-theme' - ? ThemeKind.Dark - : themeId === 'light-theme' - ? ThemeKind.Light - : ThemeKind.Light; - return makeRemoteTheme( - manualRemoteUrl, - parseRemoteKind(manualRemoteKind, inferred) - ); + const inferred = themeId === 'dark-theme' ? ThemeKind.Dark : ThemeKind.Light; + return makeRemoteTheme(manualRemoteUrl, parseRemoteKind(manualRemoteKind, inferred)); } return themes.find((theme) => theme.id === themeId) ?? LightTheme; } diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index fd89d42cc..a8fd95ec0 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -8,10 +8,10 @@ import { useActiveTheme, useSystemThemeKind, } from '$hooks/useTheme'; -import { getCachedThemeCss, putCachedThemeCss } from '../theme/cache'; import { ArboriumThemeBridge } from '$plugins/arborium'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; +import { getCachedThemeCss, putCachedThemeCss } from '../theme/cache'; const REMOTE_STYLE_ID = 'sable-remote-theme-style'; @@ -84,28 +84,27 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) { useEffect(() => { const url = activeTheme.remoteFullUrl?.trim(); - if (!url) { - document.getElementById(REMOTE_STYLE_ID)?.remove(); - return; - } - let cancelled = false; - (async () => { - const text = await loadRemoteThemeCssText(url); - if (cancelled) return; - if (!text) { - document.getElementById(REMOTE_STYLE_ID)?.remove(); - return; - } - let node = document.getElementById(REMOTE_STYLE_ID) as HTMLStyleElement | null; - if (!node) { - node = document.createElement('style'); - node.id = REMOTE_STYLE_ID; - document.head.appendChild(node); - } - node.textContent = text; - })(); + if (url) { + (async () => { + const text = await loadRemoteThemeCssText(url); + if (cancelled) return; + if (!text) { + document.getElementById(REMOTE_STYLE_ID)?.remove(); + return; + } + let node = document.getElementById(REMOTE_STYLE_ID) as HTMLStyleElement | null; + if (!node) { + node = document.createElement('style'); + node.id = REMOTE_STYLE_ID; + document.head.appendChild(node); + } + node.textContent = text; + })(); + } else { + document.getElementById(REMOTE_STYLE_ID)?.remove(); + } return () => { cancelled = true; diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index c1a5448e9..85523ab69 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -23,6 +23,13 @@ export enum CaptionPosition { } export type JumboEmojiSize = 'none' | 'extraSmall' | 'small' | 'normal' | 'large' | 'extraLarge'; +export type ThemeRemoteFavorite = { + fullUrl: string; + displayName: string; + basename: string; + kind: 'light' | 'dark'; +}; + export interface Settings { themeId?: string; useSystemTheme: boolean; @@ -111,9 +118,6 @@ export interface Settings { alwaysShowCallButton: boolean; faviconForMentionsOnly: boolean; highlightMentions: boolean; - /** - * whether to enable pk compat - */ pkCompat: boolean; pmpProxying: boolean; mentionInReplies: boolean; @@ -123,13 +127,14 @@ export interface Settings { renderAnimals: boolean; // theme catalog + themeCatalogOnboardingDone: boolean; + themeRemoteFavorites: ThemeRemoteFavorite[]; themeRemoteCatalogEnabled: boolean; themeChatPreviewAnyUrl: boolean; themeChatPreviewApprovedCatalogOnly: boolean; themeRemoteManualFullUrl?: string; themeRemoteLightFullUrl?: string; themeRemoteDarkFullUrl?: string; - /** for Arborium / UI kind **/ themeRemoteManualKind?: 'light' | 'dark'; themeRemoteLightKind?: 'light' | 'dark'; themeRemoteDarkKind?: 'light' | 'dark'; @@ -233,6 +238,8 @@ const defaultSettings: Settings = { renderAnimals: true, // theme catalog + themeCatalogOnboardingDone: false, + themeRemoteFavorites: [], themeRemoteCatalogEnabled: false, themeChatPreviewAnyUrl: false, themeChatPreviewApprovedCatalogOnly: false, @@ -258,10 +265,19 @@ export const getSettings = () => { } delete parsed.monochromeMode; - return { + const merged = { ...defaultSettings, ...(parsed as Settings), }; + + if (merged.themeCatalogOnboardingDone === undefined) { + merged.themeCatalogOnboardingDone = merged.themeRemoteCatalogEnabled === true; + } + if (!merged.themeRemoteFavorites) { + merged.themeRemoteFavorites = []; + } + + return merged; }; export const setSettings = (settings: Settings) => { diff --git a/src/app/theme/catalog.test.ts b/src/app/theme/catalog.test.ts index c5998962f..baf116422 100644 --- a/src/app/theme/catalog.test.ts +++ b/src/app/theme/catalog.test.ts @@ -16,13 +16,15 @@ describe('listThemePairsFromCatalog', () => { name: 'rose-pine.preview.sable.css', path: 'rose-pine.preview.sable.css', type: 'file', - download_url: 'https://raw.githubusercontent.com/SableClient/themes/main/rose-pine.preview.sable.css', + download_url: + 'https://raw.githubusercontent.com/SableClient/themes/main/rose-pine.preview.sable.css', }, { name: 'rose-pine.sable.css', path: 'rose-pine.sable.css', type: 'file', - download_url: 'https://raw.githubusercontent.com/SableClient/themes/main/rose-pine.sable.css', + download_url: + 'https://raw.githubusercontent.com/SableClient/themes/main/rose-pine.sable.css', }, { name: 'README.md', diff --git a/src/app/theme/catalog.ts b/src/app/theme/catalog.ts index 44efaf558..831fefa23 100644 --- a/src/app/theme/catalog.ts +++ b/src/app/theme/catalog.ts @@ -16,28 +16,6 @@ export type ThemePair = { const PREVIEW_SUFFIX = '.preview.sable.css'; const FULL_SUFFIX = '.sable.css'; -export async function listThemePairsFromCatalog(baseUrl: string): Promise { - const parts = parseGithubRawBaseUrl(baseUrl); - if (!parts) return []; - const items = await fetchGithubContents(parts); - const previewFiles = items.filter( - (i) => i.type === 'file' && i.name.endsWith(PREVIEW_SUFFIX) - ); - const pairs: ThemePair[] = []; - for (const p of previewFiles) { - const basename = p.name.slice(0, -PREVIEW_SUFFIX.length); - const fullName = `${basename}${FULL_SUFFIX}`; - const full = items.find((i) => i.type === 'file' && i.name === fullName); - if (!full?.download_url) continue; - pairs.push({ - basename, - previewUrl: rawFileUrl(parts, p.name), - fullUrl: full.download_url, - }); - } - return pairs; -} - /** Path segments for GET /repos/.../contents/{path} */ function directoryPathToApiSegment(directoryPath: string): string { if (!directoryPath) return ''; @@ -61,3 +39,24 @@ async function fetchGithubContents(parts: GithubRawParts): Promise { + const parts = parseGithubRawBaseUrl(baseUrl); + if (!parts) return []; + const items = await fetchGithubContents(parts); + const previewFiles = items.filter((i) => i.type === 'file' && i.name.endsWith(PREVIEW_SUFFIX)); + const pairs: ThemePair[] = previewFiles + .map((p) => { + const basename = p.name.slice(0, -PREVIEW_SUFFIX.length); + const fullName = `${basename}${FULL_SUFFIX}`; + const full = items.find((i) => i.type === 'file' && i.name === fullName); + if (!full?.download_url) return null; + return { + basename, + previewUrl: rawFileUrl(parts, p.name), + fullUrl: full.download_url, + }; + }) + .filter((pair): pair is ThemePair => pair !== null); + return pairs; +} diff --git a/src/app/theme/githubRaw.ts b/src/app/theme/githubRaw.ts index 978e3bd20..224b67ff4 100644 --- a/src/app/theme/githubRaw.ts +++ b/src/app/theme/githubRaw.ts @@ -9,8 +9,7 @@ export type GithubRawParts = { directoryPath: string; }; -const RAW_RE = - /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)(?:\/(.*))?$/; +const RAW_RE = /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)(?:\/(.*))?$/; export function parseGithubRawBaseUrl(baseUrl: string): GithubRawParts | null { const trimmed = baseUrl.trim().replace(/\/+$/, ''); diff --git a/src/app/theme/index.ts b/src/app/theme/index.ts deleted file mode 100644 index 59c11d7a8..000000000 --- a/src/app/theme/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from './cache'; -export * from './catalog'; -export * from './githubRaw'; -export * from './legacyThemeMap'; -export * from './metadata'; -export * from './previewCss'; -export * from './themeUrlGuards'; diff --git a/src/app/theme/legacyThemeMap.ts b/src/app/theme/legacyThemeMap.ts deleted file mode 100644 index 824e0083e..000000000 --- a/src/app/theme/legacyThemeMap.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Map legacy theme ids to catalog basenames (SableClient/themes repo filenames without suffix) for migration. - */ -export const LEGACY_THEME_TO_BASENAME: Record = { - 'silver-theme': 'silver', - 'cinny-light-theme': 'cinny-light', - 'cinny-silver-theme': 'cinny-silver', - 'dark-theme': 'dark', - 'light-theme': 'light', - 'butter-theme': 'butter', - 'rose-pine-theme': 'rose-pine', - 'cinny-dark-theme': 'cinny-dark', - 'gruvdark-theme': 'gruvdark', - 'accord-theme': 'accord', - 'black-theme': 'black', -}; - -export const LEGACY_THEME_IDS = Object.keys(LEGACY_THEME_TO_BASENAME); - -export function isLegacyBuiltinThemeId(id: string | undefined): boolean { - if (!id) return false; - return id !== 'light-theme' && id !== 'dark-theme' && id in LEGACY_THEME_TO_BASENAME; -} diff --git a/src/app/theme/metadata.ts b/src/app/theme/metadata.ts index e297c2896..a4feeba07 100644 --- a/src/app/theme/metadata.ts +++ b/src/app/theme/metadata.ts @@ -15,6 +15,14 @@ export type SableThemeMetadata = { const META_START = '@sable-theme'; +function extractFirstBlockComment(cssText: string): string { + const start = cssText.indexOf('/*'); + if (start === -1) return ''; + const end = cssText.indexOf('*/', start + 2); + if (end === -1) return ''; + return cssText.slice(start + 2, end); +} + /** * First block comment must contain @sable-theme and key: value lines. */ @@ -24,54 +32,53 @@ export function parseSableThemeMetadata(cssText: string): Partial l.replace(/^\s*\*?\s?/, '').trim()); const out: Partial = {}; - for (const line of lines) { - if (line.startsWith('@') || line === '---' || line === '') continue; - const idx = line.indexOf(':'); - if (idx === -1) continue; - const key = line.slice(0, idx).trim().toLowerCase(); - const value = line.slice(idx + 1).trim(); - switch (key) { - case 'id': - out.id = value; - break; - case 'name': - out.name = value; - break; - case 'author': - out.author = value; - break; - case 'kind': - out.kind = value === 'dark' ? ThemeKind.Dark : ThemeKind.Light; - break; - case 'contrast': - out.contrast = value === 'high' ? 'high' : 'low'; - break; - case 'tags': - out.tags = value.split(',').map((t) => t.trim()).filter(Boolean); - break; - case 'legacyids': - case 'legacy_ids': - out.legacyIds = value.split(',').map((t) => t.trim()).filter(Boolean); - break; - case 'fullthemeurl': - case 'full_theme_url': - out.fullThemeUrl = value; - break; - default: - break; - } - } + lines + .filter((line) => !(line.startsWith('@') || line === '---' || line === '')) + .filter((line) => line.indexOf(':') !== -1) + .forEach((line) => { + const idx = line.indexOf(':'); + const key = line.slice(0, idx).trim().toLowerCase(); + const value = line.slice(idx + 1).trim(); + switch (key) { + case 'id': + out.id = value; + break; + case 'name': + out.name = value; + break; + case 'author': + out.author = value; + break; + case 'kind': + out.kind = value === 'dark' ? ThemeKind.Dark : ThemeKind.Light; + break; + case 'contrast': + out.contrast = value === 'high' ? 'high' : 'low'; + break; + case 'tags': + out.tags = value + .split(',') + .map((t) => t.trim()) + .filter(Boolean); + break; + case 'legacyids': + case 'legacy_ids': + out.legacyIds = value + .split(',') + .map((t) => t.trim()) + .filter(Boolean); + break; + case 'fullthemeurl': + case 'full_theme_url': + out.fullThemeUrl = value; + break; + default: + break; + } + }); return out; } -function extractFirstBlockComment(cssText: string): string { - const start = cssText.indexOf('/*'); - if (start === -1) return ''; - const end = cssText.indexOf('*/', start + 2); - if (end === -1) return ''; - return cssText.slice(start + 2, end); -} - export function extractFullThemeUrlFromPreview(cssText: string): string | undefined { const meta = parseSableThemeMetadata(cssText); if (meta.fullThemeUrl && /^https:\/\//i.test(meta.fullThemeUrl)) { diff --git a/src/app/theme/previewCss.ts b/src/app/theme/previewCss.ts index 79f33bd8f..83c77fc46 100644 --- a/src/app/theme/previewCss.ts +++ b/src/app/theme/previewCss.ts @@ -10,17 +10,19 @@ const DANGEROUS_VALUE = /url\s*\(|@import|expression\s*\(|javascript:|\\0|