diff --git a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx new file mode 100644 index 000000000..94f183ad7 --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx @@ -0,0 +1,479 @@ +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 { 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 { SequenceCardStyle } from '$features/settings/styles.css'; +import { SequenceCard } from '$components/sequence-card'; +import { SettingTile } from '$components/setting-tile'; +import { putCachedThemeCss } from '../../../theme/cache'; +import { listThemePairsFromCatalog, type ThemePair } from '../../../theme/catalog'; +import { + buildPreviewStyleBlock, + extractSafePreviewCustomProperties, +} from '../../../theme/previewCss'; +import { + extractFullThemeUrlFromPreview, + parseSableThemeMetadata, + type SableThemeContrast, +} from '../../../theme/metadata'; + +const DEFAULT_CATALOG_BASE = 'https://raw.githubusercontent.com/SableClient/themes/main/'; + +export type CatalogPreviewRow = ThemePair & { + previewText: string; + displayName: string; + kind: ThemeKind; + contrast: SableThemeContrast; + tags: string[]; + fullInstallUrl: string; +}; + +function usePatchSettings() { + const store = useStore(); + return useCallback( + (partial: Partial) => { + const next = { ...store.get(settingsAtom), ...partial }; + store.set(settingsAtom, next); + }, + [store] + ); +} + +function ThemePreviewMini({ scopeClass, styleBlock }: { scopeClass: string; styleBlock: string }) { + if (!styleBlock) { + return ( + + No preview tokens + + ); + } + return ( + <> + + + + Sample text + + + + Primary + + + Surface + + + + + ); +} + +export function ThemeCatalogSettings() { + 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 [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'); + const [contrastFilter, setContrastFilter] = useState<'all' | SableThemeContrast>('all'); + + const onSearchChange: ChangeEventHandler = (e) => setSearch(e.target.value); + + const pairsQuery = useQuery({ + queryKey: ['theme-catalog-pairs', catalogBase], + queryFn: () => listThemePairsFromCatalog(catalogBase), + enabled: catalogEnabled, + staleTime: 5 * 60_000, + }); + + const previewsQuery = useQuery({ + queryKey: [ + 'theme-catalog-previews', + catalogBase, + pairsQuery.data?.map((p) => p.previewUrl).join('|') ?? '', + ], + queryFn: async (): Promise => { + const pairs = pairsQuery.data ?? []; + const rows = await Promise.all( + pairs.map(async (pair) => { + const res = await fetch(pair.previewUrl, { mode: 'cors' }); + const previewText = res.ok ? await res.text() : ''; + const meta = parseSableThemeMetadata(previewText); + const fullFromMeta = extractFullThemeUrlFromPreview(previewText); + const fullInstallUrl = + fullFromMeta && /^https:\/\//i.test(fullFromMeta) ? fullFromMeta : pair.fullUrl; + const kind = meta.kind ?? ThemeKind.Light; + const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; + return { + ...pair, + previewText, + displayName: meta.name?.trim() || pair.basename, + kind, + contrast, + tags: meta.tags ?? [], + fullInstallUrl, + }; + }) + ); + return rows; + }, + enabled: catalogEnabled && Boolean(pairsQuery.data?.length), + staleTime: 10 * 60_000, + }); + + const filteredRows = useMemo(() => { + const rows = previewsQuery.data ?? []; + const q = search.trim().toLowerCase(); + return rows.filter((row) => { + if (kindFilter !== 'all') { + const want = kindFilter === 'dark' ? ThemeKind.Dark : ThemeKind.Light; + if (row.kind !== want) return false; + } + if (contrastFilter !== 'all' && row.contrast !== contrastFilter) return false; + if (q) { + const hay = `${row.displayName} ${row.basename} ${row.tags.join(' ')}`.toLowerCase(); + if (!hay.includes(q)) return false; + } + return true; + }); + }, [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 installManual = useCallback( + (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ + themeRemoteManualFullUrl: row.fullInstallUrl, + themeRemoteManualKind: kind, + }); + 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] + ); + + const clearRemote = useCallback(() => { + patchSettings({ + themeRemoteManualFullUrl: undefined, + themeRemoteManualKind: undefined, + themeRemoteLightFullUrl: undefined, + themeRemoteLightKind: undefined, + themeRemoteDarkFullUrl: undefined, + themeRemoteDarkKind: undefined, + }); + }, [patchSettings]); + + return ( + + Theme catalog + + + } + /> + + + + } + /> + + + + + } + /> + + + {catalogEnabled && ( + <> + + + + {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 + + } + /> + + + {pairsQuery.isSuccess && pairsQuery.data.length > 0 && ( + + {previewsQuery.isPending && ( + + + Loading previews… + + )} + + {previewsQuery.isSuccess && ( + <> + + + Kind: + {(['all', 'light', 'dark'] as const).map((k) => ( + setKindFilter(k)} + > + {k === 'all' ? 'All' : k} + + ))} + Contrast: + {(['all', 'low', 'high'] as const).map((c) => ( + setContrastFilter(c)} + > + {c === 'all' ? 'All' : c} + + ))} + + + + {filteredRows.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 === ThemeKind.Dark ? 'Dark' : 'Light'; + return ( + + {row.displayName} + + {kindLabel} · {row.contrast} contrast + {row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''} + + + {systemTheme ? ( + + + + + ) : ( + + )} + + ); + })} + + + {filteredRows.length === 0 && ( + + No themes match filters. + + )} + + )} + + )} + + )} + + ); +} diff --git a/src/app/features/settings/cosmetics/Themes.tsx b/src/app/features/settings/cosmetics/Themes.tsx index 77e692265..4852d3d3c 100644 --- a/src/app/features/settings/cosmetics/Themes.tsx +++ b/src/app/features/settings/cosmetics/Themes.tsx @@ -24,6 +24,7 @@ import { 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) => ({ @@ -385,6 +386,8 @@ function ThemeSettings() { after={} /> + + ); }