From 39f7f06568efb5317caac5032272980aec00dfbe Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 2 Apr 2026 11:36:50 -0500 Subject: [PATCH] chat preview embeds --- src/app/components/RenderMessageContent.tsx | 40 +- src/app/components/theme/ThemePreviewCard.tsx | 231 +++++++++ .../url-preview/ThemePreviewUrlCard.tsx | 439 +++++++++++++++++ src/app/components/url-preview/index.ts | 1 + .../cosmetics/ThemeCatalogSettings.tsx | 447 ++++++++++-------- src/app/state/settings.ts | 1 + 6 files changed, 958 insertions(+), 201 deletions(-) create mode 100644 src/app/components/theme/ThemePreviewCard.tsx create mode 100644 src/app/components/url-preview/ThemePreviewUrlCard.tsx diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index cc07d5082..8208051e3 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -3,6 +3,7 @@ import { MsgType } from '$types/matrix-sdk'; import { parseSettingsLink } from '$features/settings/settingsLink'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { testMatrixTo } from '$plugins/matrix-to'; +import { useClientConfig } from '$hooks/useClientConfig'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom, CaptionPosition } from '$state/settings'; import { HTMLReactParserOptions } from 'html-react-parser'; @@ -29,7 +30,13 @@ import { UnsupportedContent, VideoContent, } from './message'; -import { UrlPreviewCard, UrlPreviewHolder, ClientPreview, youtubeUrl } from './url-preview'; +import { + UrlPreviewCard, + UrlPreviewHolder, + ClientPreview, + ThemePreviewUrlCard, + youtubeUrl, +} from './url-preview'; import { Image, MediaControl, PersistedVolumeVideo } from './media'; import { ImageViewer } from './image-viewer'; import { PdfViewer } from './Pdf-viewer'; @@ -82,6 +89,9 @@ function RenderMessageContentInternal({ const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); const [captionPosition] = useSetting(settingsAtom, 'captionPosition'); + const [themeChatAny] = useSetting(settingsAtom, 'themeChatPreviewAnyUrl'); + const [themeChatApprovedOnly] = useSetting(settingsAtom, 'themeChatPreviewApprovedCatalogOnly'); + const clientConfig = useClientConfig(); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const captionPositionMap = { [CaptionPosition.Above]: 'column-reverse', @@ -110,6 +120,18 @@ function RenderMessageContentInternal({ ); if (filteredUrls.length === 0) return undefined; + const themePreviewUrls = themeChatAny + ? filteredUrls.filter((u) => /\.preview\.sable\.css(\?|#|$)/i.test(u)) + : []; + const approvedPrefixes = clientConfig.themeCatalogApprovedHostPrefixes ?? []; + const themeAllowed = (u: string) => { + if (!/^https:\/\//i.test(u)) return false; + if (!themeChatApprovedOnly) return true; + if (approvedPrefixes.length === 0) return false; + return approvedPrefixes.some((p) => u.startsWith(p)); + }; + const themeToRender = themePreviewUrls.filter(themeAllowed); + const analyzed = filteredUrls.map((url) => ({ url, type: getMediaType(url), @@ -120,7 +142,11 @@ function RenderMessageContentInternal({ return ( + {themeToRender.map((url) => ( + + ))} {toRender.map(({ url, type }) => { + if (themeToRender.includes(url)) return null; if (type) { return ; } @@ -135,9 +161,17 @@ function RenderMessageContentInternal({ ); }, - [ts, clientUrlPreview, settingsLinkBaseUrl, urlPreview] + [ + ts, + clientUrlPreview, + settingsLinkBaseUrl, + urlPreview, + themeChatAny, + themeChatApprovedOnly, + clientConfig.themeCatalogApprovedHostPrefixes, + ] ); - const messageUrlsPreview = urlPreview ? renderUrlsPreview : undefined; + const messageUrlsPreview = urlPreview || themeChatAny ? renderUrlsPreview : undefined; const renderCaption = () => { const hasCaption = content.body && content.body.trim().length > 0; diff --git a/src/app/components/theme/ThemePreviewCard.tsx b/src/app/components/theme/ThemePreviewCard.tsx new file mode 100644 index 000000000..21004c23a --- /dev/null +++ b/src/app/components/theme/ThemePreviewCard.tsx @@ -0,0 +1,231 @@ +import { type ReactNode, useCallback, useMemo } from 'react'; +import { Box, Button, Icon, IconButton, Icons, Text, toRem, config } from 'folds'; + +import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { copyToClipboard } from '$utils/dom'; +import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../../theme/previewCss'; + +export type ThemePreviewCardProps = { + title: string; + subtitle?: ReactNode; + previewCssText: string; + scopeSlug: string; + copyText?: string; + isFavorited?: boolean; + onToggleFavorite?: () => void | Promise; + + systemTheme: boolean; + onApplyLight?: () => void | Promise; + onApplyDark?: () => void | Promise; + onApplyManual?: () => void | Promise; + isAppliedLight?: boolean; + isAppliedDark?: boolean; + isAppliedManual?: boolean; + + onRevert?: () => void; + canRevert?: boolean; +}; + +function safeSlug(input: string): string { + return (input || 'theme').replace(/[^a-zA-Z0-9_-]/g, '-') || 'theme'; +} + +export function ThemePreviewCard({ + title, + subtitle, + previewCssText, + scopeSlug, + copyText, + isFavorited, + onToggleFavorite, + systemTheme, + onApplyLight, + onApplyDark, + onApplyManual, + isAppliedLight, + isAppliedDark, + isAppliedManual, + onRevert, + canRevert, +}: ThemePreviewCardProps) { + const [copied, setCopied] = useTimeoutToggle(); + + const scopeClass = useMemo(() => `sable-theme-preview--${safeSlug(scopeSlug)}`, [scopeSlug]); + + const styleBlock = useMemo(() => { + const vars = extractSafePreviewCustomProperties(previewCssText); + return buildPreviewStyleBlock(vars, scopeClass); + }, [previewCssText, scopeClass]); + + const handleCopy = useCallback(async () => { + if (!copyText) return; + if (await copyToClipboard(copyText)) setCopied(); + }, [copyText, setCopied]); + + return ( + + + + {title} + {subtitle && ( + + {subtitle} + + )} + + + + {copyText && ( + { + handleCopy().catch(() => undefined); + }} + > + + + )} + + {typeof isFavorited === 'boolean' && onToggleFavorite && ( + { + Promise.resolve(onToggleFavorite()).catch(() => undefined); + }} + > + + + )} + + + + {styleBlock ? ( + <> + + + + Sample text + + + + Primary + + + Surface + + + + + ) : ( + + No preview tokens + + )} + + + {systemTheme ? ( + <> + {onApplyLight && ( + + )} + {onApplyDark && ( + + )} + + ) : ( + onApplyManual && ( + + ) + )} + + {onRevert && ( + + )} + + + ); +} diff --git a/src/app/components/url-preview/ThemePreviewUrlCard.tsx b/src/app/components/url-preview/ThemePreviewUrlCard.tsx new file mode 100644 index 000000000..03bd67276 --- /dev/null +++ b/src/app/components/url-preview/ThemePreviewUrlCard.tsx @@ -0,0 +1,439 @@ +import { useCallback, useMemo, useRef, useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { Box, Text } from 'folds'; +import { useStore } from 'jotai/react'; + +import { useClientConfig } from '$hooks/useClientConfig'; +import { ThemeKind } from '$hooks/useTheme'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom, type Settings, type ThemeRemoteFavorite } from '$state/settings'; +import { + extractFullThemeUrlFromPreview, + parseSableThemeMetadata, + type SableThemeContrast, +} from '../../theme/metadata'; +import { putCachedThemeCss } from '../../theme/cache'; +import { ThemePreviewCard } from '../theme/ThemePreviewCard'; + +function isHttps(url: string): boolean { + return /^https:\/\//i.test(url); +} + +function isPreviewThemeUrl(url: string): boolean { + return /\.preview\.sable\.css(\?|#|$)/i.test(url); +} + +function isApprovedByPrefix(url: string, prefixes: string[] | undefined): boolean { + if (!prefixes || prefixes.length === 0) return true; + return prefixes.some((p) => url.startsWith(p)); +} + +function fullUrlFromPreviewUrl(previewUrl: string, metaFull?: string): string | undefined { + if (metaFull && isHttps(metaFull)) return metaFull; + if (!/\.preview\.sable\.css(\?|#|$)/i.test(previewUrl)) return undefined; + return previewUrl.replace(/\.preview\.sable\.css(\?|#|$)/i, '.sable.css$1'); +} + +function basenameFromUrl(url: string): string { + const tail = url.split('/').pop() ?? url; + return tail.replace(/\.preview\.sable\.css(\?|#|$)/i, '').replace(/\.sable\.css(\?|#|$)/i, ''); +} + +function baseLabel(url: string): string { + try { + const u = new URL(url); + return u.hostname; + } catch { + return 'Unofficial theme'; + } +} + +export function ThemePreviewUrlCard({ url }: { url: string }) { + const clientConfig = useClientConfig(); + const store = useStore(); + const [chatAny] = useSetting(settingsAtom, 'themeChatPreviewAnyUrl'); + const [chatApprovedOnly] = useSetting(settingsAtom, 'themeChatPreviewApprovedCatalogOnly'); + const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites'); + const [systemTheme] = useSetting(settingsAtom, 'useSystemTheme'); + const [manualRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl'); + const [lightRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl'); + const [darkRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl'); + + const allowed = useMemo(() => { + if (!chatAny) return false; + if (!isHttps(url) || !isPreviewThemeUrl(url)) return false; + if (chatApprovedOnly) { + return isApprovedByPrefix(url, clientConfig.themeCatalogApprovedHostPrefixes); + } + return true; + }, [chatAny, chatApprovedOnly, clientConfig.themeCatalogApprovedHostPrefixes, url]); + + const isOfficial = useMemo( + () => isApprovedByPrefix(url, clientConfig.themeCatalogApprovedHostPrefixes), + [clientConfig.themeCatalogApprovedHostPrefixes, url] + ); + + const previewQuery = useQuery({ + queryKey: ['theme-preview-embed', url], + enabled: allowed, + staleTime: 10 * 60_000, + queryFn: async () => { + const res = await fetch(url, { mode: 'cors' }); + if (!res.ok) throw new Error(`theme preview fetch failed: ${res.status}`); + const previewText = await res.text(); + const meta = parseSableThemeMetadata(previewText); + const fullFromMeta = extractFullThemeUrlFromPreview(previewText); + const fullUrl = fullUrlFromPreviewUrl(url, fullFromMeta); + const kind = meta.kind ?? ThemeKind.Light; + const displayName = meta.name?.trim() || basenameFromUrl(url); + const author = meta.author?.trim() || undefined; + const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; + const tags = meta.tags ?? []; + return { previewText, fullUrl, kind, displayName, author, contrast, tags }; + }, + }); + + const patchSettings = useCallback( + (partial: Partial) => { + const next = { ...store.get(settingsAtom), ...partial }; + store.set(settingsAtom, next); + }, + [store] + ); + + const revertRef = useRef | null>(null); + const lastAutoSavedUrlRef = useRef(null); + const [canRevert, setCanRevert] = useState(false); + const [favoriteTouched, setFavoriteTouched] = useState(false); + + /** True when this embed's theme is active (survives remount when scrolling away). */ + const appliedHere = useMemo(() => { + const u = previewQuery.data?.fullUrl; + if (!u) return false; + if (systemTheme) { + return lightRemoteFullUrl === u || darkRemoteFullUrl === u; + } + return manualRemoteFullUrl === u; + }, [ + previewQuery.data?.fullUrl, + systemTheme, + lightRemoteFullUrl, + darkRemoteFullUrl, + manualRemoteFullUrl, + ]); + + const canRevertUi = useMemo(() => canRevert || appliedHere, [canRevert, appliedHere]); + + const isFav = useMemo( + () => favorites.some((f) => f.fullUrl === previewQuery.data?.fullUrl), + [favorites, previewQuery.data?.fullUrl] + ); + + const pruneFavorites = useCallback( + (nextFavorites: ThemeRemoteFavorite[], nextActive: string[]) => { + const active = new Set(nextActive); + return nextFavorites.filter((f) => f.pinned === true || active.has(f.fullUrl)); + }, + [] + ); + + const toggleFavorite = useCallback(async () => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + + const existing = favorites.find((f) => f.fullUrl === fullUrl); + if (existing) { + setFavoriteTouched(false); + const cleared: Partial = {}; + if (lightRemoteFullUrl === fullUrl) { + cleared.themeRemoteLightFullUrl = undefined; + cleared.themeRemoteLightKind = undefined; + } + if (darkRemoteFullUrl === fullUrl) { + cleared.themeRemoteDarkFullUrl = undefined; + cleared.themeRemoteDarkKind = undefined; + } + if (manualRemoteFullUrl === fullUrl) { + cleared.themeRemoteManualFullUrl = undefined; + cleared.themeRemoteManualKind = undefined; + } + + const nextFavs = favorites.filter((f) => f.fullUrl !== fullUrl); + const nextActive = [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl] + .filter((u): u is string => Boolean(u && u.trim().length > 0)) + .filter((u) => u !== fullUrl); + patchSettings({ ...cleared, themeRemoteFavorites: pruneFavorites(nextFavs, nextActive) }); + return; + } + + setFavoriteTouched(true); + const res = await fetch(fullUrl, { mode: 'cors' }); + if (!res.ok) return; + const cssText = await res.text(); + await putCachedThemeCss(fullUrl, cssText); + + const next: ThemeRemoteFavorite = { + fullUrl, + displayName: previewQuery.data.displayName, + basename: basenameFromUrl(fullUrl), + kind: previewQuery.data.kind === ThemeKind.Dark ? 'dark' : 'light', + pinned: true, + }; + + patchSettings({ themeRemoteFavorites: [...favorites, next] }); + }, [ + darkRemoteFullUrl, + favorites, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + previewQuery.data, + pruneFavorites, + ]); + + const applyManual = useCallback(() => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + const kind = previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ themeRemoteManualFullUrl: fullUrl, themeRemoteManualKind: kind }); + }, [patchSettings, previewQuery.data]); + + const applyLightSlot = useCallback(() => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + const kind = previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ themeRemoteLightFullUrl: fullUrl, themeRemoteLightKind: kind }); + }, [patchSettings, previewQuery.data]); + + const applyDarkSlot = useCallback(() => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + const kind = previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ themeRemoteDarkFullUrl: fullUrl, themeRemoteDarkKind: kind }); + }, [patchSettings, previewQuery.data]); + + const ensureFavorited = useCallback(async (): Promise => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return false; + if (favorites.some((f) => f.fullUrl === fullUrl)) return false; + + const res = await fetch(fullUrl, { mode: 'cors' }); + if (!res.ok) return false; + const cssText = await res.text(); + await putCachedThemeCss(fullUrl, cssText); + + const next: ThemeRemoteFavorite = { + fullUrl, + displayName: previewQuery.data!.displayName, + basename: basenameFromUrl(fullUrl), + kind: previewQuery.data!.kind === ThemeKind.Dark ? 'dark' : 'light', + pinned: false, + }; + + patchSettings({ themeRemoteFavorites: [...favorites, next] }); + return true; + }, [favorites, patchSettings, previewQuery.data]); + + const snapshotAnd = useCallback( + async (fn: () => void, nextApplied: Partial) => { + const current = store.get(settingsAtom); + if ( + nextApplied.themeRemoteManualFullUrl && + current.themeRemoteManualFullUrl === nextApplied.themeRemoteManualFullUrl + ) { + return; + } + if ( + nextApplied.themeRemoteLightFullUrl && + current.themeRemoteLightFullUrl === nextApplied.themeRemoteLightFullUrl + ) { + return; + } + if ( + nextApplied.themeRemoteDarkFullUrl && + current.themeRemoteDarkFullUrl === nextApplied.themeRemoteDarkFullUrl + ) { + return; + } + revertRef.current = { + themeId: current.themeId, + themeRemoteManualFullUrl: current.themeRemoteManualFullUrl, + themeRemoteManualKind: current.themeRemoteManualKind, + themeRemoteLightFullUrl: current.themeRemoteLightFullUrl, + themeRemoteLightKind: current.themeRemoteLightKind, + themeRemoteDarkFullUrl: current.themeRemoteDarkFullUrl, + themeRemoteDarkKind: current.themeRemoteDarkKind, + } satisfies Partial; + setCanRevert(true); + + if (!favoriteTouched) { + const added = await ensureFavorited(); + lastAutoSavedUrlRef.current = added ? (previewQuery.data?.fullUrl ?? null) : null; + } else { + lastAutoSavedUrlRef.current = null; + } + + fn(); + + const nextActive = [ + nextApplied.themeRemoteManualFullUrl ?? manualRemoteFullUrl, + nextApplied.themeRemoteLightFullUrl ?? lightRemoteFullUrl, + nextApplied.themeRemoteDarkFullUrl ?? darkRemoteFullUrl, + ].filter((u): u is string => Boolean(u && u.trim().length > 0)); + + patchSettings({ + themeRemoteFavorites: pruneFavorites( + store.get(settingsAtom).themeRemoteFavorites, + nextActive + ), + }); + }, + [ + ensureFavorited, + favoriteTouched, + lightRemoteFullUrl, + darkRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + previewQuery.data?.fullUrl, + pruneFavorites, + store, + ] + ); + + const revert = useCallback(() => { + const syncFavoritesAfterRevert = (removeAutoSavedFullUrl: string | null) => { + const after = store.get(settingsAtom); + let favs = after.themeRemoteFavorites; + if (removeAutoSavedFullUrl) { + favs = favs.filter((f) => f.fullUrl !== removeAutoSavedFullUrl); + } + const nextActive = [ + after.themeRemoteManualFullUrl, + after.themeRemoteLightFullUrl, + after.themeRemoteDarkFullUrl, + ].filter((u): u is string => Boolean(u && u.trim().length > 0)); + patchSettings({ + themeRemoteFavorites: pruneFavorites(favs, nextActive), + }); + }; + + const snap = revertRef.current; + if (snap) { + patchSettings(snap); + syncFavoritesAfterRevert(lastAutoSavedUrlRef.current); + + revertRef.current = null; + lastAutoSavedUrlRef.current = null; + setCanRevert(false); + return; + } + + const u = previewQuery.data?.fullUrl; + if (!u) return; + const partial: Partial = {}; + if (lightRemoteFullUrl === u) { + partial.themeRemoteLightFullUrl = undefined; + partial.themeRemoteLightKind = undefined; + } + if (darkRemoteFullUrl === u) { + partial.themeRemoteDarkFullUrl = undefined; + partial.themeRemoteDarkKind = undefined; + } + if (manualRemoteFullUrl === u) { + partial.themeRemoteManualFullUrl = undefined; + partial.themeRemoteManualKind = undefined; + partial.themeId = previewQuery.data?.kind === ThemeKind.Dark ? 'dark-theme' : 'light-theme'; + } + if (Object.keys(partial).length === 0) return; + patchSettings(partial); + syncFavoritesAfterRevert(null); + }, [ + darkRemoteFullUrl, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + previewQuery.data?.fullUrl, + previewQuery.data?.kind, + pruneFavorites, + store, + ]); + + if (!allowed) return null; + + const title = previewQuery.data?.displayName ?? 'Theme preview'; + let kindLabel = 'Theme'; + if (previewQuery.data?.kind === ThemeKind.Dark) kindLabel = 'Dark'; + else if (previewQuery.data?.kind === ThemeKind.Light) kindLabel = 'Light'; + const contrastLabel = previewQuery.data?.contrast ? `${previewQuery.data.contrast} contrast` : ''; + const authorLabel = previewQuery.data?.author ? `by ${previewQuery.data.author}` : ''; + const tagsLabel = + previewQuery.data?.tags && previewQuery.data.tags.length > 0 + ? previewQuery.data.tags.join(', ') + : ''; + const sourceLabel = isOfficial ? 'Official theme' : baseLabel(url); + const subtitleLine1 = [kindLabel, contrastLabel].filter(Boolean).join(' · '); + const subtitleLine2 = [authorLabel, tagsLabel].filter(Boolean).join(' · '); + const subtitleLine3 = sourceLabel; + const subtitle = ( + <> + {subtitleLine1} + {subtitleLine2 ? ( + <> +
+ {subtitleLine2} + + ) : null} +
+ {subtitleLine3} + + ); + const fullUrl = previewQuery.data?.fullUrl; + + return ( + + toggleFavorite() : undefined} + systemTheme={systemTheme} + onApplyLight={ + systemTheme && fullUrl + ? () => snapshotAnd(() => applyLightSlot(), { themeRemoteLightFullUrl: fullUrl }) + : undefined + } + onApplyDark={ + systemTheme && fullUrl + ? () => snapshotAnd(() => applyDarkSlot(), { themeRemoteDarkFullUrl: fullUrl }) + : undefined + } + onApplyManual={ + !systemTheme && fullUrl + ? () => snapshotAnd(() => applyManual(), { themeRemoteManualFullUrl: fullUrl }) + : undefined + } + isAppliedLight={fullUrl ? lightRemoteFullUrl === fullUrl : false} + isAppliedDark={fullUrl ? darkRemoteFullUrl === fullUrl : false} + isAppliedManual={fullUrl ? manualRemoteFullUrl === fullUrl : false} + canRevert={canRevertUi} + onRevert={revert} + /> + {previewQuery.isPending && ( + + Loading preview… + + )} + + ); +} diff --git a/src/app/components/url-preview/index.ts b/src/app/components/url-preview/index.ts index ccf60be87..d146abd3d 100644 --- a/src/app/components/url-preview/index.ts +++ b/src/app/components/url-preview/index.ts @@ -1,3 +1,4 @@ export * from './UrlPreview'; export * from './UrlPreviewCard'; export * from './ClientPreview'; +export * from './ThemePreviewUrlCard'; diff --git a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx index fbde6b5b2..41ef54f21 100644 --- a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx +++ b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx @@ -1,19 +1,6 @@ import { type ChangeEventHandler, useCallback, useMemo, useState } from 'react'; import { useQuery } from '@tanstack/react-query'; -import { - Box, - Button, - Chip, - config, - Icon, - IconButton, - Icons, - Input, - Spinner, - Switch, - Text, - toRem, -} from 'folds'; +import { Box, Button, Chip, Input, Spinner, Switch, Text, toRem } from 'folds'; import { useStore } from 'jotai/react'; import { useClientConfig } from '$hooks/useClientConfig'; @@ -24,12 +11,9 @@ import { settingsAtom, type Settings, type ThemeRemoteFavorite } from '$state/se import { SequenceCardStyle } from '$features/settings/styles.css'; import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; +import { ThemePreviewCard } from '$components/theme/ThemePreviewCard'; import { putCachedThemeCss } from '../../../theme/cache'; import { listThemePairsFromCatalog, type ThemePair } from '../../../theme/catalog'; -import { - buildPreviewStyleBlock, - extractSafePreviewCustomProperties, -} from '../../../theme/previewCss'; import { extractFullThemeUrlFromPreview, parseSableThemeMetadata, @@ -49,8 +33,10 @@ export type CatalogPreviewRow = ThemePair & { }; export type LocalPreviewRow = ThemeRemoteFavorite & { + previewUrl: string; previewText: string; displayName: string; + author?: string; contrast: SableThemeContrast; tags: string[]; }; @@ -71,66 +57,6 @@ export function usePatchSettings() { ); } -function ThemePreviewMini({ scopeClass, styleBlock }: { scopeClass: string; styleBlock: string }) { - if (!styleBlock) { - return ( - - No preview tokens - - ); - } - return ( - <> - - - - Sample text - - - - Primary - - - Surface - - - - - ); -} - export type ThemeCatalogSettingsMode = 'full' | 'local' | 'chat' | 'remote'; export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSettingsMode }) { @@ -160,6 +86,42 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet const onSearchChange: ChangeEventHandler = (e) => setSearch(e.target.value); + const activeUrls = useMemo( + () => + [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl].filter((u): u is string => + Boolean(u && u.trim().length > 0) + ), + [darkRemoteFullUrl, lightRemoteFullUrl, manualRemoteFullUrl] + ); + + const pruneFavorites = useCallback( + (nextFavorites: ThemeRemoteFavorite[], nextActiveUrls: string[]) => { + const active = new Set(nextActiveUrls); + return nextFavorites.filter((f) => f.pinned === true || active.has(f.fullUrl)); + }, + [] + ); + + const clearAssignmentsIfMatch = useCallback( + (fullUrl: string) => { + const partial: Partial = {}; + if (lightRemoteFullUrl === fullUrl) { + partial.themeRemoteLightFullUrl = undefined; + partial.themeRemoteLightKind = undefined; + } + if (darkRemoteFullUrl === fullUrl) { + partial.themeRemoteDarkFullUrl = undefined; + partial.themeRemoteDarkKind = undefined; + } + if (manualRemoteFullUrl === fullUrl) { + partial.themeRemoteManualFullUrl = undefined; + partial.themeRemoteManualKind = undefined; + } + return partial; + }, + [darkRemoteFullUrl, lightRemoteFullUrl, manualRemoteFullUrl] + ); + const pairsQuery = useQuery({ queryKey: ['theme-catalog-pairs', catalogBase], queryFn: () => listThemePairsFromCatalog(catalogBase), @@ -239,8 +201,10 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; return { ...fav, + previewUrl, previewText, displayName, + author: meta.author?.trim() || undefined, contrast, tags: meta.tags ?? [], }; @@ -256,11 +220,25 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet const removeFavorite = useCallback( (fullUrl: string) => { + const nextFavorites = favorites.filter((f) => f.fullUrl !== fullUrl); + const cleared = clearAssignmentsIfMatch(fullUrl); + const nextActive = [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl] + .filter((u): u is string => Boolean(u && u.trim().length > 0)) + .filter((u) => u !== fullUrl); patchSettings({ - themeRemoteFavorites: favorites.filter((f) => f.fullUrl !== fullUrl), + ...cleared, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), }); }, - [favorites, patchSettings] + [ + clearAssignmentsIfMatch, + darkRemoteFullUrl, + favorites, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + pruneFavorites, + ] ); const applyFavoriteToLight = useCallback( @@ -347,8 +325,12 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet async (row: CatalogPreviewRow) => { const existing = favorites.find((f: ThemeRemoteFavorite) => f.fullUrl === row.fullInstallUrl); if (existing) { + const nextFavorites = favorites.filter((f) => f.fullUrl !== row.fullInstallUrl); + const cleared = clearAssignmentsIfMatch(row.fullInstallUrl); + const nextActive = activeUrls.filter((u) => u !== row.fullInstallUrl); patchSettings({ - themeRemoteFavorites: favorites.filter((f) => f.fullUrl !== row.fullInstallUrl), + ...cleared, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), }); return; } @@ -360,12 +342,125 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet displayName: row.displayName, basename: row.basename, kind, + pinned: true, }; patchSettings({ themeRemoteFavorites: [...favorites, next], }); }, - [favorites, patchSettings, prefetchFull] + [activeUrls, clearAssignmentsIfMatch, favorites, patchSettings, prefetchFull, pruneFavorites] + ); + + const installFromCatalogLight = useCallback( + async (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const nextActive = Array.from( + new Set( + [manualRemoteFullUrl, darkRemoteFullUrl, row.fullInstallUrl].filter(Boolean) as string[] + ) + ); + + let nextFavorites = favorites; + const existing = favorites.find((f) => f.fullUrl === row.fullInstallUrl); + if (!existing) { + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + nextFavorites = [ + ...favorites, + { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: false, + }, + ]; + } + + patchSettings({ + themeRemoteLightFullUrl: row.fullInstallUrl, + themeRemoteLightKind: kind, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [darkRemoteFullUrl, favorites, manualRemoteFullUrl, patchSettings, prefetchFull, pruneFavorites] + ); + + const installFromCatalogDark = useCallback( + async (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const nextActive = Array.from( + new Set( + [manualRemoteFullUrl, lightRemoteFullUrl, row.fullInstallUrl].filter(Boolean) as string[] + ) + ); + + let nextFavorites = favorites; + const existing = favorites.find((f) => f.fullUrl === row.fullInstallUrl); + if (!existing) { + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + nextFavorites = [ + ...favorites, + { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: false, + }, + ]; + } + + patchSettings({ + themeRemoteDarkFullUrl: row.fullInstallUrl, + themeRemoteDarkKind: kind, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [ + favorites, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + prefetchFull, + pruneFavorites, + ] + ); + + const installFromCatalogManual = useCallback( + async (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const nextActive = Array.from( + new Set( + [lightRemoteFullUrl, darkRemoteFullUrl, row.fullInstallUrl].filter(Boolean) as string[] + ) + ); + + let nextFavorites = favorites; + const existing = favorites.find((f) => f.fullUrl === row.fullInstallUrl); + if (!existing) { + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + nextFavorites = [ + ...favorites, + { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: false, + }, + ]; + } + + patchSettings({ + themeRemoteManualFullUrl: row.fullInstallUrl, + themeRemoteManualKind: kind, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [darkRemoteFullUrl, favorites, lightRemoteFullUrl, patchSettings, prefetchFull, pruneFavorites] ); const clearRemote = useCallback(() => { @@ -505,52 +600,48 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet }} > {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'; const isFav = favorites.some((f) => f.fullUrl === row.fullInstallUrl); + const line1 = `${kindLabel} · ${row.contrast} contrast`; + const line2 = `${row.author ? `by ${row.author}` : ''}${ + row.tags.length > 0 + ? `${row.author ? ' · ' : ''}${row.tags.join(', ')}` + : '' + }`.trim(); + const subtitle = ( + <> + {line1} + {line2 ? ( + <> +
+ {line2} + + ) : null} + + ); return ( - - - - {row.displayName} - - {kindLabel} · {row.contrast} contrast - {row.author ? ` · by ${row.author}` : ''} - {row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''} - - - { - toggleFavorite(row).catch(() => undefined); - }} - > - - - - - + title={row.displayName} + subtitle={subtitle} + previewCssText={row.previewText} + scopeSlug={`catalog-${slug}`} + copyText={row.previewUrl} + isFavorited={isFav} + onToggleFavorite={() => toggleFavorite(row)} + systemTheme={systemTheme} + onApplyLight={ + systemTheme ? () => installFromCatalogLight(row) : undefined + } + onApplyDark={systemTheme ? () => installFromCatalogDark(row) : undefined} + onApplyManual={ + !systemTheme ? () => installFromCatalogManual(row) : undefined + } + isAppliedLight={lightRemoteFullUrl === row.fullInstallUrl} + isAppliedDark={darkRemoteFullUrl === row.fullInstallUrl} + isAppliedManual={manualRemoteFullUrl === row.fullInstallUrl} + /> ); })} @@ -661,85 +752,45 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet }} > {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; - + const line1 = `${kindLabel} · ${row.contrast} contrast`; + const line2 = `${row.author ? `by ${row.author}` : ''}${ + row.tags.length > 0 + ? `${row.author ? ' · ' : ''}${row.tags.join(', ')}` + : '' + }`.trim(); + const subtitle = ( + <> + {line1} + {line2 ? ( + <> +
+ {line2} + + ) : null} + + ); return ( - - - - {row.displayName} - - {kindLabel} · {row.contrast} contrast - {row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''} - - - - removeFavorite(row.fullUrl)} - > - - - - - - - {systemTheme ? ( - - - - - ) : ( - - )} - + title={row.displayName} + subtitle={subtitle} + previewCssText={row.previewText} + scopeSlug={`local-${slug}`} + copyText={row.previewUrl} + isFavorited + onToggleFavorite={() => removeFavorite(row.fullUrl)} + systemTheme={systemTheme} + onApplyLight={systemTheme ? () => applyFavoriteToLight(row) : undefined} + onApplyDark={systemTheme ? () => applyFavoriteToDark(row) : undefined} + onApplyManual={ + !systemTheme ? () => applyFavoriteToManual(row) : undefined + } + isAppliedLight={lightRemoteFullUrl === row.fullUrl} + isAppliedDark={darkRemoteFullUrl === row.fullUrl} + isAppliedManual={manualRemoteFullUrl === row.fullUrl} + /> ); })} diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 85523ab69..7de6f34d5 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -28,6 +28,7 @@ export type ThemeRemoteFavorite = { displayName: string; basename: string; kind: 'light' | 'dark'; + pinned?: boolean; }; export interface Settings {