chat preview embeds

This commit is contained in:
7w1 committed 2026-04-02 11:36:50 -05:00
1 parent 310be03972
commit 39f7f06568
6 files changed
+958 -201

No files matched your search

+37 -3
View File
@@ -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 (
<UrlPreviewHolder>
{themeToRender.map((url) => (
<ThemePreviewUrlCard key={`theme:${url}`} url={url} />
))}
{toRender.map(({ url, type }) => {
if (themeToRender.includes(url)) return null;
if (type) {
return <UrlPreviewCard key={url} url={url} ts={ts} mediaType={type} />;
}
@@ -135,9 +161,17 @@ function RenderMessageContentInternal({
</UrlPreviewHolder>
);
},
[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;
@@ -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<void>;
systemTheme: boolean;
onApplyLight?: () => void | Promise<void>;
onApplyDark?: () => void | Promise<void>;
onApplyManual?: () => void | Promise<void>;
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 (
<Box
direction="Column"
gap="300"
style={{
padding: toRem(12),
borderRadius: config.radii.R300,
border: `${toRem(1)} solid var(--sable-surface-container-line)`,
background: 'var(--sable-surface-container)',
width: '100%',
maxWidth: '100%',
}}
>
<Box direction="Row" alignItems="Start" justifyContent="SpaceBetween" gap="200">
<Box direction="Column" gap="100" grow="Yes">
<Text size="H6">{title}</Text>
{subtitle && (
<Text size="T200" priority="300" style={{ wordBreak: 'break-word' }}>
{subtitle}
</Text>
)}
</Box>
<Box direction="Row" gap="100" alignItems="Center" shrink="No">
{copyText && (
<IconButton
size="300"
variant="Secondary"
radii="300"
aria-label={copied ? 'Copied theme link' : 'Copy theme link'}
onClick={() => {
handleCopy().catch(() => undefined);
}}
>
<Icon size="200" src={copied ? Icons.Check : Icons.Link} />
</IconButton>
)}
{typeof isFavorited === 'boolean' && onToggleFavorite && (
<IconButton
size="300"
variant={isFavorited ? 'Primary' : 'Secondary'}
radii="300"
aria-label={isFavorited ? 'Remove from saved' : 'Save theme'}
onClick={() => {
Promise.resolve(onToggleFavorite()).catch(() => undefined);
}}
>
<Icon size="200" src={Icons.Star} filled={isFavorited} />
</IconButton>
)}
</Box>
</Box>
{styleBlock ? (
<>
<style>{styleBlock}</style>
<Box
className={scopeClass}
direction="Column"
gap="200"
style={{
padding: toRem(12),
borderRadius: config.radii.R300,
background: 'var(--sable-bg-container)',
border: `${toRem(1)} solid var(--sable-surface-container-line)`,
}}
>
<Text size="T300" style={{ color: 'var(--sable-bg-on-container)' }}>
Sample text
</Text>
<Box direction="Row" gap="200" wrap="Wrap">
<span
style={{
display: 'inline-flex',
alignItems: 'center',
padding: `${toRem(6)} ${toRem(12)}`,
borderRadius: config.radii.Pill,
background: 'var(--sable-primary-main)',
color: 'var(--sable-primary-on-main)',
fontSize: toRem(12),
fontWeight: 500,
}}
>
Primary
</span>
<span
style={{
display: 'inline-flex',
alignItems: 'center',
padding: `${toRem(6)} ${toRem(12)}`,
borderRadius: config.radii.Pill,
background: 'var(--sable-surface-container)',
color: 'var(--sable-surface-on-container)',
fontSize: toRem(12),
}}
>
Surface
</span>
</Box>
</Box>
</>
) : (
<Text size="T300" priority="300">
No preview tokens
</Text>
)}
<Box direction="Row" gap="200" wrap="Wrap" alignItems="Center" style={{ width: '100%' }}>
{systemTheme ? (
<>
{onApplyLight && (
<Button
variant={isAppliedLight ? 'Primary' : 'Secondary'}
size="300"
radii="300"
style={{ flex: '1 1 0' }}
disabled={Boolean(isAppliedLight)}
onClick={() => Promise.resolve(onApplyLight()).catch(() => undefined)}
>
<Text size="B300">Use when OS light</Text>
</Button>
)}
{onApplyDark && (
<Button
variant={isAppliedDark ? 'Primary' : 'Secondary'}
size="300"
radii="300"
style={{ flex: '1 1 0' }}
disabled={Boolean(isAppliedDark)}
onClick={() => Promise.resolve(onApplyDark()).catch(() => undefined)}
>
<Text size="B300">Use when OS dark</Text>
</Button>
)}
</>
) : (
onApplyManual && (
<Button
variant={isAppliedManual ? 'Primary' : 'Secondary'}
size="300"
radii="300"
style={{ flex: onRevert ? '1 1 0' : undefined, width: onRevert ? undefined : '100%' }}
disabled={Boolean(isAppliedManual)}
onClick={() => Promise.resolve(onApplyManual()).catch(() => undefined)}
>
<Text size="B300">Use theme</Text>
</Button>
)
)}
{onRevert && (
<Button
variant="Secondary"
size="300"
radii="300"
disabled={!canRevert}
style={{ flex: '1 1 0' }}
onClick={onRevert}
>
<Text size="B300">Revert</Text>
</Button>
)}
</Box>
</Box>
);
}
@@ -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<Settings>) => {
const next = { ...store.get(settingsAtom), ...partial };
store.set(settingsAtom, next);
},
[store]
);
const revertRef = useRef<Partial<Settings> | null>(null);
const lastAutoSavedUrlRef = useRef<string | null>(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<Settings> = {};
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<boolean> => {
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<Settings>) => {
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<Settings>;
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<Settings> = {};
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 ? (
<>
<br />
{subtitleLine2}
</>
) : null}
<br />
{subtitleLine3}
</>
);
const fullUrl = previewQuery.data?.fullUrl;
return (
<Box
style={{
width: '400px',
maxWidth: '100%',
flexShrink: 0,
boxSizing: 'border-box',
}}
>
<ThemePreviewCard
title={title}
subtitle={subtitle}
previewCssText={previewQuery.data?.previewText ?? ''}
scopeSlug={`chat-${basenameFromUrl(url)}`}
copyText={url}
isFavorited={fullUrl ? isFav : false}
onToggleFavorite={fullUrl ? () => 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 && (
<Text size="T200" priority="300">
Loading preview…
</Text>
)}
</Box>
);
}
+1
View File
@@ -1,3 +1,4 @@
export * from './UrlPreview';
export * from './UrlPreviewCard';
export * from './ClientPreview';
export * from './ThemePreviewUrlCard';
@@ -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 (
<Text size="T300" priority="300">
No preview tokens
</Text>
);
}
return (
<>
<style>{styleBlock}</style>
<Box
className={scopeClass}
direction="Column"
gap="300"
style={{
padding: toRem(12),
borderRadius: config.radii.R300,
background: 'var(--sable-bg-container)',
border: `${toRem(1)} solid var(--sable-surface-container-line)`,
minHeight: toRem(88),
}}
>
<Text size="T300" style={{ color: 'var(--sable-bg-on-container)' }}>
Sample text
</Text>
<Box direction="Row" gap="200" wrap="Wrap">
<span
style={{
display: 'inline-flex',
alignItems: 'center',
padding: `${toRem(4)} ${toRem(10)}`,
borderRadius: config.radii.Pill,
background: 'var(--sable-primary-main)',
color: 'var(--sable-primary-on-main)',
fontSize: toRem(12),
fontWeight: 500,
}}
>
Primary
</span>
<span
style={{
display: 'inline-flex',
alignItems: 'center',
padding: `${toRem(4)} ${toRem(10)}`,
borderRadius: config.radii.Pill,
background: 'var(--sable-surface-container)',
color: 'var(--sable-surface-on-container)',
fontSize: toRem(12),
}}
>
Surface
</span>
</Box>
</Box>
</>
);
}
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<HTMLInputElement> = (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<Settings> = {};
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 ? (
<>
<br />
{line2}
</>
) : null}
</>
);
return (
<Box
<ThemePreviewCard
key={row.basename}
direction="Column"
gap="300"
style={{
padding: toRem(12),
borderRadius: config.radii.R300,
border: `${toRem(1)} solid var(--sable-surface-container-line)`,
background: 'var(--sable-surface-container)',
}}
>
<Box
direction="Row"
alignItems="Start"
justifyContent="SpaceBetween"
gap="200"
>
<Box direction="Column" gap="100" grow="Yes">
<Text size="H6">{row.displayName}</Text>
<Text size="T200" priority="300">
{kindLabel} · {row.contrast} contrast
{row.author ? ` · by ${row.author}` : ''}
{row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''}
</Text>
</Box>
<IconButton
size="300"
variant={isFav ? 'Primary' : 'Secondary'}
radii="300"
aria-label={isFav ? 'Remove from saved' : 'Save theme'}
onClick={() => {
toggleFavorite(row).catch(() => undefined);
}}
>
<Icon size="200" src={Icons.Star} filled={isFav} />
</IconButton>
</Box>
<ThemePreviewMini scopeClass={scopeClass} styleBlock={styleBlock} />
</Box>
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}
/>
);
})}
</Box>
@@ -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 ? (
<>
<br />
{line2}
</>
) : null}
</>
);
return (
<Box
<ThemePreviewCard
key={row.fullUrl}
direction="Column"
gap="300"
style={{
padding: toRem(12),
borderRadius: config.radii.R300,
border: `${toRem(1)} solid var(--sable-surface-container-line)`,
background: 'var(--sable-surface-container)',
}}
>
<Box
direction="Row"
alignItems="Start"
justifyContent="SpaceBetween"
gap="200"
>
<Box direction="Column" gap="100" grow="Yes">
<Text size="H6">{row.displayName}</Text>
<Text size="T200" priority="300">
{kindLabel} · {row.contrast} contrast
{row.tags.length > 0 ? ` · ${row.tags.join(', ')}` : ''}
</Text>
</Box>
<IconButton
size="300"
variant="Secondary"
radii="300"
aria-label="Remove from saved"
onClick={() => removeFavorite(row.fullUrl)}
>
<Icon size="200" src={Icons.Star} filled />
</IconButton>
</Box>
<ThemePreviewMini scopeClass={scopeClass} styleBlock={styleBlock} />
{systemTheme ? (
<Box direction="Column" gap="200">
<Button
variant={isLightSelected ? 'Primary' : 'Secondary'}
size="300"
radii="300"
onClick={() => applyFavoriteToLight(row)}
>
<Text size="B300">Use when OS light</Text>
</Button>
<Button
variant={isDarkSelected ? 'Primary' : 'Secondary'}
size="300"
radii="300"
onClick={() => applyFavoriteToDark(row)}
>
<Text size="B300">Use when OS dark</Text>
</Button>
</Box>
) : (
<Button
variant={isManualSelected ? 'Primary' : 'Secondary'}
size="300"
radii="300"
onClick={() => applyFavoriteToManual(row)}
>
<Text size="B300">Use theme</Text>
</Button>
)}
</Box>
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}
/>
);
})}
</Box>
+1
View File
@@ -28,6 +28,7 @@ export type ThemeRemoteFavorite = {
displayName: string;
basename: string;
kind: 'light' | 'dark';
pinned?: boolean;
};
export interface Settings {