Theme system improvements (#1087)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #774 
Adds pages for tweaks/themes browsing
Adds some simple catalog auto updating based on hashes
Adds the ability to load themes from uploaded `.sable.css` files in
rooms

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [x] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->

Tests were AI generated
This commit is contained in:
7w1 authored and GitHub committed 2026-07-16 12:18:22 -05:00
commit b07f7a60d9
21 files changed
+1767 -378

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
Add uploaded Sable CSS theme loading, automatic catalog updates, and a cleaner theme browser with full CSS viewing.
@@ -2,8 +2,19 @@ import { render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MsgType } from '$types/matrix-sdk';
import { ClientConfigProvider } from '$hooks/useClientConfig';
import { MatrixClientProvider } from '$hooks/useMatrixClient';
import { RenderMessageContent } from './RenderMessageContent';
vi.mock('./message/content/UploadedSableCssContent', () => ({
UploadedSableCssContent: ({ body }: { body: string }) => (
<div data-testid="uploaded-sable-css">{body}</div>
),
}));
vi.mock('$hooks/useMediaAuthentication', () => ({
useMediaAuthentication: () => false,
}));
vi.mock('./url-preview', () => ({
UrlPreviewHolder: ({ children }: { children: React.ReactNode }) => (
<div data-testid="url-preview-holder">{children}</div>
@@ -30,6 +41,23 @@ function renderMessage(body: string) {
);
}
function renderFileMessage(content: Record<string, unknown>) {
return render(
<ClientConfigProvider value={{}}>
<MatrixClientProvider value={{} as never}>
<RenderMessageContent
displayName="Alice"
msgType={MsgType.File}
ts={0}
getContent={() => content as never}
htmlReactParserOptions={{}}
linkifyOpts={{}}
/>
</MatrixClientProvider>
</ClientConfigProvider>
);
}
beforeEach(() => {
vi.stubGlobal('location', { origin: 'https://app.example' } as Location);
});
@@ -92,4 +120,16 @@ describe('RenderMessageContent', () => {
expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument();
expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com)');
});
it('detects an uploaded Sable theme by filename when the body is a caption', () => {
renderFileMessage({
msgtype: MsgType.File,
body: 'A theme you might like',
filename: 'amethyst.sable.css',
url: 'mxc://example/amethyst',
info: { mimetype: 'text/css', size: 1024 },
});
expect(screen.getByTestId('uploaded-sable-css')).toHaveTextContent('amethyst.sable.css');
});
});
+22 -5
View File
@@ -31,6 +31,7 @@ import {
RenderBody,
ThumbnailContent,
UnsupportedContent,
UploadedSableCssContent,
VideoContent,
} from './message';
import {
@@ -42,6 +43,7 @@ import {
youtubeUrl,
} from './url-preview';
import { isHttpsFullSableCssUrl } from '../theme/previewUrls';
import { isSableCssAttachmentFileName } from '../theme/processThemeImport';
import { Image, MediaControl, PersistedVolumeVideo } from './media';
import { ImageViewer } from './image-viewer';
import { PdfViewer } from './Pdf-viewer';
@@ -278,13 +280,13 @@ function RenderMessageContentInternal({
renderCaptionedAttachment(
<MFile
content={content as Record<string, never> & { msgtype: MsgType.File }}
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
renderFileContent={({ fileName, mimeType, info, encInfo, url }) => (
<FileContent
body={body}
body={fileName}
mimeType={mimeType}
renderAsPdfFile={() => (
<ReadPdfFile
body={body}
body={fileName}
mimeType={mimeType}
url={url}
encInfo={encInfo}
@@ -293,7 +295,7 @@ function RenderMessageContentInternal({
)}
renderAsTextFile={() => (
<ReadTextFile
body={body}
body={fileName}
mimeType={mimeType}
url={url}
encInfo={encInfo}
@@ -301,7 +303,22 @@ function RenderMessageContentInternal({
/>
)}
>
<DownloadFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} info={info} />
{themeChatSableWidgets && isSableCssAttachmentFileName(fileName) && (
<UploadedSableCssContent
body={fileName}
mimeType={mimeType}
url={url}
encInfo={encInfo}
size={info.size}
/>
)}
<DownloadFile
body={fileName}
mimeType={mimeType}
url={url}
encInfo={encInfo}
info={info}
/>
</FileContent>
)}
outlined={outlineAttachment}
@@ -652,7 +652,7 @@ export function MAudio({
}
type RenderFileContentProps = {
body: string;
fileName: string;
info: IFileInfo & IThumbnailContent;
mimeType: string;
url: string;
@@ -682,7 +682,7 @@ export function MFile({ content, renderFileContent, outlined }: MFileProps) {
<AttachmentBox>
<AttachmentContent>
{renderFileContent({
body: filename,
fileName: filename,
info: fileInfo ?? {},
mimeType: fileInfo?.mimetype ?? FALLBACK_MIMETYPE,
url: mxcUrl,
@@ -0,0 +1,380 @@
import { useCallback, useMemo } from 'react';
import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Box, Button, IconButton, Spinner, Switch, Text, config, toRem } from 'folds';
import { Star, sizedIcon } from '$components/icons/phosphor';
import { ThemePreviewCard } from '$components/theme/ThemePreviewCard';
import { CssViewerButton } from '$components/theme/CssViewerButton';
import { usePatchSettings } from '$features/settings/cosmetics/themeSettingsPatch';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { useClientConfig } from '$hooks/useClientConfig';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { useSetting } from '$state/hooks/settings';
import {
settingsAtom,
type Settings,
type ThemeRemoteFavorite,
type ThemeRemoteTweakFavorite,
} from '$state/settings';
import {
processUploadedSableCssAttachment,
type ProcessedUploadedSableCss,
} from '../../../theme/processThemeImport';
import { isThirdPartyThemeUrl } from '../../../theme/themeApproval';
import {
buildPreviewStyleBlock,
extractSafePreviewCustomProperties,
} from '../../../theme/previewCss';
import {
pruneThemeFavorites,
pruneThemeTweakFavorites,
themeSourceLabel,
} from '../../../theme/themeLibrary';
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
export const MAX_SABLE_CSS_ATTACHMENT_BYTES = 1024 * 1024;
type UploadedSableCssContentProps = {
body: string;
mimeType: string;
url: string;
size?: number;
encInfo?: EncryptedAttachmentInfo;
};
type SuccessfulUpload = Extract<ProcessedUploadedSableCss, { ok: true }>;
function UploadedTweakCard({ data }: { data: Extract<SuccessfulUpload, { role: 'tweak' }> }) {
const patchSettings = usePatchSettings();
const [favorites] = useSetting(settingsAtom, 'themeRemoteTweakFavorites');
const [enabledUrls] = useSetting(settingsAtom, 'themeRemoteEnabledTweakFullUrls');
const isFavorite = favorites.some((favorite) => favorite.fullUrl === data.fullUrl);
const isEnabled = enabledUrls.includes(data.fullUrl);
const scopeClass = useMemo(
() => `sable-uploaded-tweak--${data.basename.replace(/[^a-zA-Z0-9_-]/g, '-')}`,
[data.basename]
);
const styleBlock = useMemo(
() => buildPreviewStyleBlock(extractSafePreviewCustomProperties(data.cssText), scopeClass),
[data.cssText, scopeClass]
);
const makeFavorite = useCallback(
(pinned: boolean): ThemeRemoteTweakFavorite[] => {
const existing = favorites.find((favorite) => favorite.fullUrl === data.fullUrl);
if (existing) {
return favorites.map((favorite) =>
favorite.fullUrl === data.fullUrl && pinned ? { ...favorite, pinned: true } : favorite
);
}
return [
...favorites,
{
fullUrl: data.fullUrl,
displayName: data.displayName,
basename: data.basename,
pinned,
importedLocal: true,
},
];
},
[data, favorites]
);
const toggleFavorite = useCallback(() => {
if (isFavorite) {
const nextEnabled = enabledUrls.filter((url) => url !== data.fullUrl);
patchSettings({
themeRemoteEnabledTweakFullUrls: nextEnabled,
themeRemoteTweakFavorites: pruneThemeTweakFavorites(
favorites.filter((favorite) => favorite.fullUrl !== data.fullUrl),
nextEnabled
),
});
return;
}
patchSettings({ themeRemoteTweakFavorites: makeFavorite(true) });
}, [data.fullUrl, enabledUrls, favorites, isFavorite, makeFavorite, patchSettings]);
const setEnabled = useCallback(
(enabled: boolean) => {
const nextEnabled = enabled
? Array.from(new Set([...enabledUrls, data.fullUrl]))
: enabledUrls.filter((url) => url !== data.fullUrl);
patchSettings({
themeRemoteEnabledTweakFullUrls: nextEnabled,
themeRemoteTweakFavorites: pruneThemeTweakFavorites(makeFavorite(false), nextEnabled),
});
},
[data.fullUrl, enabledUrls, makeFavorite, patchSettings]
);
const description = [
data.description,
data.author ? `by ${data.author}` : undefined,
data.tags.length > 0 ? data.tags.join(', ') : undefined,
]
.filter(Boolean)
.join(' · ');
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)',
}}
>
<Box direction="Row" gap="200" alignItems="Start" justifyContent="SpaceBetween">
<Box direction="Column" gap="100" grow="Yes">
<Text size="H6">{data.displayName}</Text>
<Text size="T200" priority="300">
{description || 'Uploaded tweak'}
</Text>
<Text size="T200" priority="300">
Source: Uploaded file
</Text>
</Box>
<Box direction="Row" gap="100" alignItems="Center" shrink="No">
<CssViewerButton
title={`${data.displayName} — CSS`}
cssText={data.cssText}
ariaLabel="View tweak CSS"
/>
<IconButton
size="300"
variant={isFavorite ? 'Primary' : 'Secondary'}
fill="Soft"
outlined
radii="300"
aria-label={isFavorite ? 'Remove tweak from saved' : 'Save tweak'}
onClick={toggleFavorite}
>
{sizedIcon(Star, '200', { filled: isFavorite })}
</IconButton>
<Switch variant="Primary" value={isEnabled} onChange={setEnabled} />
</Box>
</Box>
{styleBlock && (
<>
<style>{styleBlock}</style>
<Box
className={scopeClass}
style={{
padding: toRem(12),
borderRadius: config.radii.R300,
background: 'var(--sable-bg-container)',
}}
>
<Text size="T300" style={{ color: 'var(--sable-bg-on-container)' }}>
Sample text
</Text>
</Box>
</>
)}
</Box>
);
}
function UploadedThemeCard({ data }: { data: Extract<SuccessfulUpload, { role: 'theme' }> }) {
const clientConfig = useClientConfig();
const patchSettings = usePatchSettings();
const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites');
const [systemTheme] = useSetting(settingsAtom, 'useSystemTheme');
const [manualUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl');
const [lightUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl');
const [darkUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl');
const fullUrl = data.fullUrl;
const isFavorite = fullUrl ? favorites.some((favorite) => favorite.fullUrl === fullUrl) : false;
const ensureFavorite = useCallback(
(pinned: boolean): ThemeRemoteFavorite[] => {
if (!fullUrl) return favorites;
const existing = favorites.find((favorite) => favorite.fullUrl === fullUrl);
if (existing) {
return favorites.map((favorite) =>
favorite.fullUrl === fullUrl && pinned ? { ...favorite, pinned: true } : favorite
);
}
return [
...favorites,
{
fullUrl,
displayName: data.displayName,
basename: data.basename,
kind: data.kind,
pinned,
importedLocal: data.importedLocal,
},
];
},
[data, favorites, fullUrl]
);
const toggleFavorite = useCallback(() => {
if (!fullUrl) return;
if (!isFavorite) {
patchSettings({ themeRemoteFavorites: ensureFavorite(true) });
return;
}
const partial: Partial<Settings> = {};
if (manualUrl === fullUrl) {
partial.themeRemoteManualFullUrl = undefined;
partial.themeRemoteManualKind = undefined;
}
if (lightUrl === fullUrl) {
partial.themeRemoteLightFullUrl = undefined;
partial.themeRemoteLightKind = undefined;
}
if (darkUrl === fullUrl) {
partial.themeRemoteDarkFullUrl = undefined;
partial.themeRemoteDarkKind = undefined;
}
patchSettings({
...partial,
themeRemoteFavorites: pruneThemeFavorites(
favorites.filter((favorite) => favorite.fullUrl !== fullUrl),
[
manualUrl === fullUrl ? undefined : manualUrl,
lightUrl === fullUrl ? undefined : lightUrl,
darkUrl === fullUrl ? undefined : darkUrl,
]
),
});
}, [darkUrl, ensureFavorite, favorites, fullUrl, isFavorite, lightUrl, manualUrl, patchSettings]);
const apply = useCallback(
(slot: 'manual' | 'light' | 'dark') => {
if (!fullUrl) return;
const partial: Partial<Settings> = {
themeRemoteFavorites: pruneThemeFavorites(ensureFavorite(false), [
slot === 'manual' ? fullUrl : manualUrl,
slot === 'light' ? fullUrl : lightUrl,
slot === 'dark' ? fullUrl : darkUrl,
]),
};
if (slot === 'manual') {
partial.themeRemoteManualFullUrl = fullUrl;
partial.themeRemoteManualKind = data.kind;
} else if (slot === 'light') {
partial.themeRemoteLightFullUrl = fullUrl;
partial.themeRemoteLightKind = data.kind;
} else {
partial.themeRemoteDarkFullUrl = fullUrl;
partial.themeRemoteDarkKind = data.kind;
}
patchSettings(partial);
},
[darkUrl, data.kind, ensureFavorite, fullUrl, lightUrl, manualUrl, patchSettings]
);
const kindLabel = data.kind === 'dark' ? 'Dark' : 'Light';
const subtitle = data.previewOnly
? `${kindLabel} · Uploaded preview only — no reachable full theme was provided.`
: `${kindLabel} · ${data.importedLocal ? 'Uploaded theme' : 'Uploaded preview'}`;
return (
<ThemePreviewCard
title={data.displayName}
subtitle={subtitle}
previewCssText={data.previewCssForCard}
fullCssText={data.fullCssForCard}
scopeSlug={`upload-${data.basename}`}
sourceLabel={themeSourceLabel({ importedLocal: data.importedLocal, url: data.fullUrl })}
thirdParty={
fullUrl !== undefined &&
!data.importedLocal &&
isThirdPartyThemeUrl(fullUrl, clientConfig.themeCatalogApprovedHostPrefixes)
}
isFavorited={fullUrl ? isFavorite : undefined}
onToggleFavorite={fullUrl ? toggleFavorite : undefined}
systemTheme={systemTheme}
onApplyLight={systemTheme && fullUrl ? () => apply('light') : undefined}
onApplyDark={systemTheme && fullUrl ? () => apply('dark') : undefined}
onApplyManual={!systemTheme && fullUrl ? () => apply('manual') : undefined}
isAppliedLight={Boolean(fullUrl && lightUrl === fullUrl)}
isAppliedDark={Boolean(fullUrl && darkUrl === fullUrl)}
isAppliedManual={Boolean(fullUrl && manualUrl === fullUrl)}
/>
);
}
export function UploadedSableCssContent({
body,
mimeType,
url,
size,
encInfo,
}: UploadedSableCssContentProps) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const [loadState, load] = useAsyncCallback(
useCallback(async (): Promise<SuccessfulUpload> => {
if (typeof size === 'number' && size > MAX_SABLE_CSS_ATTACHMENT_BYTES) {
throw new Error('Theme CSS attachments must be 1 MiB or smaller.');
}
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication);
if (!mediaUrl) throw new Error('Invalid media URL.');
const blob = encInfo
? await downloadEncryptedMedia(mediaUrl, (encrypted) =>
decryptFile(encrypted, mimeType, encInfo)
)
: await downloadMedia(mediaUrl);
if (blob.size > MAX_SABLE_CSS_ATTACHMENT_BYTES) {
throw new Error('Theme CSS attachments must be 1 MiB or smaller.');
}
const result = await processUploadedSableCssAttachment(
await blob.text(),
body,
`${url}\n${JSON.stringify(encInfo ?? null)}`
);
if (!result.ok) throw new Error(result.error);
return result;
}, [body, encInfo, mimeType, mx, size, url, useAuthentication])
);
if (loadState.status === AsyncStatus.Success) {
return loadState.data.role === 'theme' ? (
<UploadedThemeCard data={loadState.data} />
) : (
<UploadedTweakCard data={loadState.data} />
);
}
return (
<Box direction="Column" gap="200">
<Button
variant={loadState.status === AsyncStatus.Error ? 'Critical' : 'Secondary'}
fill="Soft"
outlined
radii="300"
size="400"
disabled={loadState.status === AsyncStatus.Loading}
before={
loadState.status === AsyncStatus.Loading ? (
<Spinner fill="Soft" size="100" variant="Secondary" />
) : undefined
}
onClick={() => load()}
>
<Text size="B400">
{loadState.status === AsyncStatus.Loading
? 'Loading theme preview…'
: loadState.status === AsyncStatus.Error
? 'Retry theme preview'
: 'Load theme preview'}
</Text>
</Button>
{loadState.status === AsyncStatus.Error && (
<Text size="T200" style={{ color: 'var(--sable-error)' }}>
{loadState.error instanceof Error ? loadState.error.message : 'Failed to load theme CSS.'}
</Text>
)}
</Box>
);
}
@@ -3,5 +3,6 @@ export * from './ImageContent';
export * from './VideoContent';
export * from './AudioContent';
export * from './FileContent';
export * from './UploadedSableCssContent';
export * from './FallbackContent';
export * from './EventContent';
@@ -0,0 +1,83 @@
import { useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter } from 'folds';
import { Code, sizedIcon } from '$components/icons/phosphor';
import { TextViewer } from '$components/text-viewer';
import { ModalWide } from '$styles/Modal.css';
import { stopPropagation } from '$utils/keyboard';
type CssViewerButtonProps = {
title: string;
cssText?: string;
loadCssText?: () => Promise<string>;
ariaLabel: string;
};
export function CssViewerButton({ title, cssText, loadCssText, ariaLabel }: CssViewerButtonProps) {
const [open, setOpen] = useState(false);
const [loadedCssText, setLoadedCssText] = useState('');
const [loading, setLoading] = useState(false);
const viewerText = cssText?.trim() ? cssText : loadedCssText;
if (!cssText?.trim() && !loadCssText) return null;
const handleOpen = async () => {
if (viewerText) {
setOpen(true);
return;
}
if (!loadCssText || loading) return;
setLoading(true);
try {
const loaded = await loadCssText();
if (!loaded.trim()) return;
setLoadedCssText(loaded);
setOpen(true);
} finally {
setLoading(false);
}
};
return (
<>
<IconButton
size="300"
variant="Secondary"
fill="Soft"
outlined
radii="300"
aria-label={ariaLabel}
disabled={loading}
onClick={() => {
handleOpen().catch(() => undefined);
}}
>
{sizedIcon(Code, '200')}
</IconButton>
{open && (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setOpen(false),
clickOutsideDeactivates: true,
escapeDeactivates: stopPropagation,
}}
>
<Modal className={ModalWide} size="500">
<TextViewer
name={title}
text={viewerText}
langName="css"
requestClose={() => setOpen(false)}
/>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
)}
</>
);
}
@@ -5,13 +5,17 @@ import { Check, Download, Link, Star, Warning, sizedIcon } from '$components/ico
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
import { copyToClipboard } from '$utils/dom';
import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../../theme/previewCss';
import { CssViewerButton } from './CssViewerButton';
export type ThemePreviewCardProps = {
title: string;
subtitle?: ReactNode;
beforePreview?: ReactNode;
previewCssText: string;
fullCssText?: string;
loadFullCssText?: () => Promise<string>;
scopeSlug: string;
sourceLabel?: string;
copyText?: string;
isFavorited?: boolean;
onToggleFavorite?: () => void | Promise<void>;
@@ -40,7 +44,10 @@ export function ThemePreviewCard({
subtitle,
beforePreview,
previewCssText,
fullCssText,
loadFullCssText,
scopeSlug,
sourceLabel,
copyText,
isFavorited,
onToggleFavorite,
@@ -119,9 +126,20 @@ export function ThemePreviewCard({
{subtitle}
</Text>
)}
{sourceLabel && (
<Text size="T200" priority="300">
Source: {sourceLabel}
</Text>
)}
</Box>
<Box direction="Row" gap="100" alignItems="Center" shrink="No">
<CssViewerButton
title={`${title} — CSS`}
cssText={fullCssText}
loadCssText={loadFullCssText}
ariaLabel="View theme CSS"
/>
{copyText && (
<IconButton
size="300"
@@ -13,12 +13,13 @@ import {
parseSableThemeMetadata,
type SableThemeContrast,
} from '../../theme/metadata';
import { putCachedThemeCss } from '../../theme/cache';
import { getCachedThemeCss, putCachedThemeCss } from '../../theme/cache';
import { fullUrlFromPreviewUrl } from '../../theme/previewUrls';
import { isApprovedCatalogHostUrl } from '../../theme/themeApproval';
import { ThemePreviewCard } from '../theme/ThemePreviewCard';
import { SableChatPreviewPlaceholder } from './SableChatPreviewPlaceholder';
import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner';
import { pruneThemeFavorites, themeUrlHostLabel } from '../../theme/themeLibrary';
function isHttps(url: string): boolean {
return /^https:\/\//i.test(url);
@@ -33,15 +34,6 @@ function basenameFromUrl(url: string): string {
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();
@@ -138,14 +130,6 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
[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;
@@ -173,7 +157,10 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
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) });
patchSettings({
...cleared,
themeRemoteFavorites: pruneThemeFavorites(nextFavs, nextActive),
});
return;
}
@@ -205,7 +192,6 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
manualRemoteFullUrl,
patchSettings,
previewQuery.data,
pruneFavorites,
]);
const applyManual = useCallback(() => {
@@ -304,7 +290,7 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
].filter((u): u is string => Boolean(u && u.trim().length > 0));
patchSettings({
themeRemoteFavorites: pruneFavorites(
themeRemoteFavorites: pruneThemeFavorites(
store.get(settingsAtom).themeRemoteFavorites,
nextActive
),
@@ -318,7 +304,6 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
manualRemoteFullUrl,
patchSettings,
previewQuery.data?.fullUrl,
pruneFavorites,
store,
]
);
@@ -336,7 +321,7 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
after.themeRemoteDarkFullUrl,
].filter((u): u is string => Boolean(u && u.trim().length > 0));
patchSettings({
themeRemoteFavorites: pruneFavorites(favs, nextActive),
themeRemoteFavorites: pruneThemeFavorites(favs, nextActive),
});
};
@@ -377,7 +362,6 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
patchSettings,
previewQuery.data?.fullUrl,
previewQuery.data?.kind,
pruneFavorites,
store,
]);
@@ -388,7 +372,7 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
<SableChatPreviewPlaceholder
kind="theme"
url={url}
hostLabel={baseLabel(url)}
hostLabel={themeUrlHostLabel(url, 'Unofficial theme')}
isApprovedHost={isOfficial}
onLoadPreview={() => {
setUserTriggeredLoad(true);
@@ -407,10 +391,9 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
previewQuery.data?.tags && previewQuery.data.tags.length > 0
? previewQuery.data.tags.join(', ')
: '';
const sourceLabel = isOfficial ? 'Official theme' : baseLabel(url);
const sourceLabel = isOfficial ? 'Official catalog' : themeUrlHostLabel(url, 'Unofficial theme');
const subtitleLine1 = [kindLabel, contrastLabel].filter(Boolean).join(' · ');
const subtitleLine2 = [authorLabel, tagsLabel].filter(Boolean).join(' · ');
const subtitleLine3 = sourceLabel;
const subtitle = (
<>
{subtitleLine1}
@@ -420,11 +403,19 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
{subtitleLine2}
</>
) : null}
<br />
{subtitleLine3}
</>
);
const fullUrl = previewQuery.data?.fullUrl;
const loadFullCssText = async (): Promise<string> => {
if (!fullUrl) throw new Error('Full theme URL is unavailable.');
const cached = await getCachedThemeCss(fullUrl);
if (cached) return cached;
const response = await fetch(fullUrl, { mode: 'cors' });
if (!response.ok) throw new Error(`Theme CSS fetch failed: ${response.status}`);
const text = await response.text();
await putCachedThemeCss(fullUrl, text);
return text;
};
return (
<Box
@@ -441,10 +432,14 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
title={title}
subtitle={subtitle}
beforePreview={
showThirdPartyBanner ? <ThemeThirdPartyBanner hostLabel={baseLabel(url)} /> : undefined
showThirdPartyBanner ? (
<ThemeThirdPartyBanner hostLabel={themeUrlHostLabel(url, 'Unofficial theme')} />
) : undefined
}
previewCssText={previewQuery.data?.previewText ?? ''}
loadFullCssText={fullUrl ? loadFullCssText : undefined}
scopeSlug={`chat-${basenameFromUrl(url)}`}
sourceLabel={sourceLabel}
copyText={url}
isFavorited={fullUrl ? isFav : false}
onToggleFavorite={fullUrl ? () => toggleFavorite() : undefined}
@@ -26,28 +26,14 @@ import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../.
import { isApprovedCatalogHostUrl, isThirdPartyThemeUrl } from '../../theme/themeApproval';
import { SableChatPreviewPlaceholder } from './SableChatPreviewPlaceholder';
import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner';
function baseLabel(url: string): string {
try {
return new URL(url).hostname;
} catch {
return 'Unofficial tweak';
}
}
import { CssViewerButton } from '../theme/CssViewerButton';
import { pruneThemeTweakFavorites, themeUrlHostLabel } from '../../theme/themeLibrary';
function basenameFromFullSableUrl(url: string): string {
const tail = url.split('/').pop() ?? url;
return tail.replace(/\.sable\.css(\?.*)?$/i, '') || 'tweak';
}
function pruneTweakFavorites(
nextFavorites: ThemeRemoteTweakFavorite[],
nextEnabledUrls: string[]
): ThemeRemoteTweakFavorite[] {
const enabled = new Set(nextEnabledUrls);
return nextFavorites.filter((f) => f.pinned === true || enabled.has(f.fullUrl));
}
function safeSlug(input: string): string {
return (input || 'tweak').replace(/[^a-zA-Z0-9_-]/g, '-') || 'tweak';
}
@@ -150,7 +136,7 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
const nextFavs = tweakFavorites.filter((f) => f.fullUrl !== url);
const nextEnabled = enabledTweakFullUrls.filter((u) => u !== url);
patchSettings({
themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled),
themeRemoteTweakFavorites: pruneThemeTweakFavorites(nextFavs, nextEnabled),
themeRemoteEnabledTweakFullUrls: nextEnabled,
});
return;
@@ -164,7 +150,7 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
pinned: true,
};
patchSettings({
themeRemoteTweakFavorites: pruneTweakFavorites(
themeRemoteTweakFavorites: pruneThemeTweakFavorites(
[...tweakFavorites, next],
enabledTweakFullUrls
),
@@ -191,7 +177,7 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
}
patchSettings({
themeRemoteEnabledTweakFullUrls: nextEnabled,
themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled),
themeRemoteTweakFavorites: pruneThemeTweakFavorites(nextFavs, nextEnabled),
});
} else {
const nextEnabled = enabledTweakFullUrls.filter((u) => u !== url);
@@ -210,7 +196,7 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
<SableChatPreviewPlaceholder
kind="tweak"
url={url}
hostLabel={baseLabel(url)}
hostLabel={themeUrlHostLabel(url, 'Unofficial tweak')}
isApprovedHost={isOfficial}
onLoadPreview={() => {
setUserTriggeredLoad(true);
@@ -253,7 +239,7 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
data.tags.length > 0 ? data.tags.join(', ') : '',
].filter(Boolean);
const descLine = descParts.join(' · ');
const sourceLabel = isOfficial ? 'Official catalog' : baseLabel(url);
const sourceLabel = isOfficial ? 'Official catalog' : themeUrlHostLabel(url, 'Unofficial tweak');
return (
<Box
@@ -310,6 +296,11 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
</Box>
<Box direction="Row" gap="100" alignItems="Center" shrink="No">
<CssViewerButton
title={`${data.displayName} — CSS`}
cssText={data.cssText}
ariaLabel="View tweak CSS"
/>
<IconButton
size="300"
variant="Secondary"
@@ -347,7 +338,10 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
</Box>
{showThirdPartyBanner ? (
<ThemeThirdPartyBanner kind="tweak" hostLabel={baseLabel(url)} />
<ThemeThirdPartyBanner
kind="tweak"
hostLabel={themeUrlHostLabel(url, 'Unofficial tweak')}
/>
) : undefined}
{styleBlock ? (
@@ -0,0 +1,15 @@
import { style } from '@vanilla-extract/css';
import { toRem } from 'folds';
export const themeCardGrid = style({
display: 'grid',
gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
gap: toRem(16),
width: '100%',
maxWidth: toRem(760),
'@media': {
[`screen and (max-width: ${toRem(700)})`]: {
gridTemplateColumns: 'minmax(0, 1fr)',
},
},
});
File diff suppressed because it is too large. Load diff
@@ -31,6 +31,7 @@ import {
processPastedOrUploadedCss,
type ProcessedThemeImport,
} from '../../../theme/processThemeImport';
import { pruneThemeFavorites, pruneThemeTweakFavorites } from '../../../theme/themeLibrary';
import { usePatchSettings } from './themeSettingsPatch';
@@ -64,22 +65,6 @@ export function ThemeImportModal({ open, onClose }: ThemeImportModalProps) {
[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 pruneTweakFavorites = useCallback(
(nextFavorites: ThemeRemoteTweakFavorite[], nextEnabledUrls: string[]) => {
const enabled = new Set(nextEnabledUrls);
return nextFavorites.filter((f) => f.pinned === true || enabled.has(f.fullUrl));
},
[]
);
useEffect(() => {
if (!open) {
setImportUrl('');
@@ -116,7 +101,10 @@ export function ThemeImportModal({ open, onClose }: ThemeImportModalProps) {
? [...enabledTweakFullUrls]
: [...enabledTweakFullUrls, r.fullUrl];
patchSettings({
themeRemoteTweakFavorites: pruneTweakFavorites([...tweakFavorites, next], nextEnabled),
themeRemoteTweakFavorites: pruneThemeTweakFavorites(
[...tweakFavorites, next],
nextEnabled
),
themeRemoteEnabledTweakFullUrls: nextEnabled,
});
onClose();
@@ -142,20 +130,11 @@ export function ThemeImportModal({ open, onClose }: ThemeImportModalProps) {
)
);
patchSettings({
themeRemoteFavorites: pruneFavorites([...favorites, next], nextActive),
themeRemoteFavorites: pruneThemeFavorites([...favorites, next], nextActive),
});
onClose();
},
[
activeUrls,
enabledTweakFullUrls,
favorites,
onClose,
patchSettings,
pruneFavorites,
pruneTweakFavorites,
tweakFavorites,
]
[activeUrls, enabledTweakFullUrls, favorites, onClose, patchSettings, tweakFavorites]
);
const onImportFileChange: ChangeEventHandler<HTMLInputElement> = (e) => {
@@ -128,7 +128,6 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
'catalog-themes',
'catalog-tweaks',
'theme-browse-remote',
'theme-catalog-clear-remote',
'theme-chat-sable-widgets',
'theme-chat-auto-approved',
'theme-chat-auto-any',
+46 -1
View File
@@ -1,6 +1,6 @@
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render } from '@testing-library/react';
import { render, waitFor } from '@testing-library/react';
import { ThemeKind, type Theme } from '$hooks/useTheme';
import { AuthRouteThemeManager, UnAuthRouteThemeManager } from './ThemeManager';
@@ -18,6 +18,8 @@ let activeTheme: Theme = {
kind: ThemeKind.Light,
classNames: ['test-light-theme'],
};
let cachedCss = '';
let cacheUpdateListener: ((update: { url: string; contentHash: string }) => void) | undefined;
type ThemeContextProviderProps = {
value: Theme;
@@ -59,6 +61,21 @@ vi.mock('$plugins/arborium', () => ({
kind === ThemeKind.Dark ? <>{children}</> : <>{children}</>,
}));
vi.mock('../theme/cache', () => ({
getCachedThemeCss: vi.fn<(url: string) => Promise<string | undefined>>(async () =>
cachedCss ? cachedCss : undefined
),
putCachedThemeCss: vi.fn<(url: string, cssText: string) => Promise<void>>(async () => undefined),
subscribeThemeCacheUpdates: vi.fn<
(listener: (update: { url: string; contentHash: string }) => void) => () => void
>((listener: (update: { url: string; contentHash: string }) => void) => {
cacheUpdateListener = listener;
return () => {
cacheUpdateListener = undefined;
};
}),
}));
beforeEach(() => {
systemThemeKind = ThemeKind.Light;
activeTheme = {
@@ -70,6 +87,8 @@ beforeEach(() => {
settings.underlineLinks = false;
settings.reducedMotion = false;
settings.themeRemoteEnabledTweakFullUrls = [];
cachedCss = '';
cacheUpdateListener = undefined;
document.body.className = '';
document.body.style.filter = '';
});
@@ -105,4 +124,30 @@ describe('ThemeManager', () => {
expect(document.body).toHaveClass('test-dark-theme');
expect(document.body).not.toHaveClass('test-light-theme');
});
it('reloads active CSS when the cached content changes without a URL change', async () => {
const themeUrl = 'https://catalog.example/theme.sable.css';
cachedCss = 'body { --sable-primary-main: red; }';
activeTheme = {
id: 'test-remote',
kind: ThemeKind.Dark,
classNames: ['test-dark-theme'],
remoteFullUrl: themeUrl,
};
render(
<AuthRouteThemeManager>
<div>child</div>
</AuthRouteThemeManager>
);
await waitFor(() =>
expect(document.getElementById('sable-remote-theme-style')).toHaveTextContent('red')
);
cachedCss = 'body { --sable-primary-main: blue; }';
cacheUpdateListener?.({ url: themeUrl, contentHash: 'new-hash' });
await waitFor(() =>
expect(document.getElementById('sable-remote-theme-style')).toHaveTextContent('blue')
);
});
});
+100 -9
View File
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react';
import { useEffect } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { configClass, varsClass } from 'folds';
import {
DarkTheme,
@@ -12,8 +12,14 @@ import {
import { ArboriumThemeBridge } from '$plugins/arborium';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { getCachedThemeCss, putCachedThemeCss } from '../theme/cache';
import { useOptionalClientConfig } from '$hooks/useClientConfig';
import { getCachedThemeCss, putCachedThemeCss, subscribeThemeCacheUpdates } from '../theme/cache';
import { isLocalImportBundledUrl } from '../theme/localImportUrls';
import { themeCatalogListingBaseUrl } from '../theme/catalogDefaults';
import {
THEME_CATALOG_AUTO_UPDATE_INTERVAL_MS,
updateInstalledCatalogPackages,
} from '../theme/catalogUpdater';
const REMOTE_STYLE_ID = 'sable-remote-theme-style';
const REMOTE_TWEAKS_STYLE_ID = 'sable-remote-tweaks-style';
@@ -39,6 +45,74 @@ async function loadRemoteThemeCssText(url: string): Promise<string | undefined>
return text;
}
function CatalogThemeAutoUpdater() {
const clientConfig = useOptionalClientConfig();
const [catalogEnabled] = useSetting(settingsAtom, 'themeRemoteCatalogEnabled');
const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites');
const [tweakFavorites] = useSetting(settingsAtom, 'themeRemoteTweakFavorites');
const [manualUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl');
const [lightUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl');
const [darkUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl');
const [enabledTweakUrls] = useSetting(settingsAtom, 'themeRemoteEnabledTweakFullUrls');
const inFlightRef = useRef<Promise<unknown> | null>(null);
const installedThemeUrls = useMemo(
() =>
Array.from(
new Set(
[
...(favorites ?? []).map((favorite) => favorite.fullUrl),
manualUrl,
lightUrl,
darkUrl,
].filter((url): url is string => Boolean(url))
)
),
[darkUrl, favorites, lightUrl, manualUrl]
);
const installedTweakUrls = useMemo(
() =>
Array.from(
new Set([
...(tweakFavorites ?? []).map((favorite) => favorite.fullUrl),
...(enabledTweakUrls ?? []),
])
),
[enabledTweakUrls, tweakFavorites]
);
const checkForUpdates = useCallback(() => {
if (!catalogEnabled || !clientConfig || inFlightRef.current) return;
if (installedThemeUrls.length === 0 && installedTweakUrls.length === 0) return;
const task = updateInstalledCatalogPackages({
catalogBase: themeCatalogListingBaseUrl(clientConfig.themeCatalogBaseUrl?.trim()),
manifestUrl: clientConfig.themeCatalogManifestUrl?.trim() || undefined,
installedThemeUrls,
installedTweakUrls,
maxAgeMs: THEME_CATALOG_AUTO_UPDATE_INTERVAL_MS,
})
.catch(() => undefined)
.finally(() => {
if (inFlightRef.current === task) inFlightRef.current = null;
});
inFlightRef.current = task;
}, [catalogEnabled, clientConfig, installedThemeUrls, installedTweakUrls]);
useEffect(() => {
checkForUpdates();
}, [checkForUpdates]);
useEffect(() => {
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') checkForUpdates();
};
document.addEventListener('visibilitychange', onVisibilityChange);
return () => document.removeEventListener('visibilitychange', onVisibilityChange);
}, [checkForUpdates]);
return null;
}
export function UnAuthRouteThemeManager() {
const systemThemeKind = useSystemThemeKind();
@@ -94,7 +168,7 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) {
let cancelled = false;
if (url) {
(async () => {
const applyThemeCss = async () => {
const text = await loadRemoteThemeCssText(url);
if (cancelled) return;
if (!text) {
@@ -108,7 +182,15 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) {
document.head.appendChild(node);
}
node.textContent = text;
})();
};
applyThemeCss().catch(() => undefined);
const unsubscribe = subscribeThemeCacheUpdates((update) => {
if (update.url === url) applyThemeCss().catch(() => undefined);
});
return () => {
cancelled = true;
unsubscribe();
};
} else {
document.getElementById(REMOTE_STYLE_ID)?.remove();
}
@@ -127,7 +209,7 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) {
return undefined;
}
(async () => {
const applyTweakCss = async () => {
const texts = await Promise.all(urls.map((url) => loadRemoteThemeCssText(url.trim())));
if (cancelled) return;
const chunks = texts.filter((text): text is string => Boolean(text));
@@ -138,16 +220,25 @@ export function AuthRouteThemeManager({ children }: { children: ReactNode }) {
document.head.appendChild(node);
}
node.textContent = chunks.join('\n\n');
})();
};
applyTweakCss().catch(() => undefined);
const activeUrls = new Set(urls.map((url) => url.trim()));
const unsubscribe = subscribeThemeCacheUpdates((update) => {
if (activeUrls.has(update.url)) applyTweakCss().catch(() => undefined);
});
return () => {
cancelled = true;
unsubscribe();
};
}, [enabledTweakUrls]);
return (
<ArboriumThemeBridge kind={activeTheme.kind}>
<ThemeContextProvider value={activeTheme}>{children}</ThemeContextProvider>
</ArboriumThemeBridge>
<>
<CatalogThemeAutoUpdater />
<ArboriumThemeBridge kind={activeTheme.kind}>
<ThemeContextProvider value={activeTheme}>{children}</ThemeContextProvider>
</ArboriumThemeBridge>
</>
);
}
+217 -8
View File
@@ -1,40 +1,115 @@
const DB_NAME = 'sable-theme-cache';
const DB_VERSION = 1;
const STORE = 'themes';
const UPDATE_CHANNEL = 'sable-theme-cache-updates';
export type CachedThemeEntry = {
url: string;
cssText: string;
cachedAt: number;
checkedAt?: number;
contentHash?: string;
etag?: string;
lastModified?: string;
};
export type ThemeCacheRevalidationResult =
| { status: 'updated'; url: string; previousHash?: string; contentHash: string }
| { status: 'unchanged'; url: string; contentHash: string }
| { status: 'skipped'; url: string; contentHash?: string }
| { status: 'failed'; url: string; error: string };
export type ThemeCacheUpdate = {
url: string;
contentHash: string;
};
export type ThemeCacheStats = {
entries: number;
localEntries: number;
remoteEntries: number;
totalBytes: number;
localBytes: number;
remoteBytes: number;
lastCheckedAt?: number;
};
const updateListeners = new Set<(update: ThemeCacheUpdate) => void>();
let updateChannel: BroadcastChannel | undefined;
function isThemeCacheUpdate(value: unknown): value is ThemeCacheUpdate {
if (!value || typeof value !== 'object') return false;
const update = value as Record<string, unknown>;
return typeof update.url === 'string' && typeof update.contentHash === 'string';
}
function getUpdateChannel(): BroadcastChannel | undefined {
if (typeof BroadcastChannel === 'undefined') return undefined;
if (!updateChannel) {
updateChannel = new BroadcastChannel(UPDATE_CHANNEL);
updateChannel.addEventListener('message', (event: MessageEvent<unknown>) => {
const update = event.data;
if (!isThemeCacheUpdate(update)) return;
updateListeners.forEach((listener) => listener(update));
});
}
return updateChannel;
}
function notifyThemeCacheUpdated(update: ThemeCacheUpdate): void {
updateListeners.forEach((listener) => listener(update));
getUpdateChannel()?.postMessage(update);
}
export function subscribeThemeCacheUpdates(
listener: (update: ThemeCacheUpdate) => void
): () => void {
updateListeners.add(listener);
getUpdateChannel();
return () => updateListeners.delete(listener);
}
function openDb(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.addEventListener('error', () => reject(req.error));
req.addEventListener('success', () => resolve(req.result));
req.addEventListener('upgradeneeded', () => {
req.result.createObjectStore(STORE, { keyPath: 'url' });
if (!req.result.objectStoreNames.contains(STORE)) {
req.result.createObjectStore(STORE, { keyPath: 'url' });
}
});
});
}
export async function getCachedThemeCss(url: string): Promise<string | undefined> {
export async function hashThemeCss(cssText: string): Promise<string> {
try {
const bytes = new TextEncoder().encode(cssText);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(
''
);
} catch {
let hash = 0x811c9dc5;
for (let i = 0; i < cssText.length; i += 1) {
hash = Math.imul(hash ^ cssText.charCodeAt(i), 0x01000193);
}
return `fnv1a-${(hash >>> 0).toString(16).padStart(8, '0')}`;
}
}
export async function getCachedThemeEntry(url: string): Promise<CachedThemeEntry | undefined> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readonly');
const req = tx.objectStore(STORE).get(url);
req.addEventListener('error', () => reject(req.error));
req.addEventListener('success', () => {
const row = req.result as CachedThemeEntry | undefined;
resolve(row?.cssText);
});
req.addEventListener('success', () => resolve(req.result as CachedThemeEntry | undefined));
});
}
export async function putCachedThemeCss(url: string, cssText: string): Promise<void> {
async function writeCachedThemeEntry(entry: CachedThemeEntry): Promise<void> {
const db = await openDb();
const entry: CachedThemeEntry = { url, cssText, cachedAt: Date.now() };
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).put(entry);
@@ -43,6 +118,83 @@ export async function putCachedThemeCss(url: string, cssText: string): Promise<v
});
}
export async function getCachedThemeCss(url: string): Promise<string | undefined> {
return (await getCachedThemeEntry(url))?.cssText;
}
export async function putCachedThemeCss(url: string, cssText: string): Promise<void> {
const [existing, contentHash] = await Promise.all([
getCachedThemeEntry(url),
hashThemeCss(cssText),
]);
const now = Date.now();
await writeCachedThemeEntry({
...existing,
url,
cssText,
cachedAt: now,
checkedAt: now,
contentHash,
etag: undefined,
lastModified: undefined,
});
if (existing && existing.contentHash !== contentHash) {
notifyThemeCacheUpdated({ url, contentHash });
}
}
export async function revalidateCachedThemeCss(
url: string,
maxAgeMs = 0
): Promise<ThemeCacheRevalidationResult> {
try {
const existing = await getCachedThemeEntry(url);
const lastCheck = existing?.checkedAt ?? existing?.cachedAt ?? 0;
if (maxAgeMs > 0 && Date.now() - lastCheck < maxAgeMs) {
return { status: 'skipped', url, contentHash: existing?.contentHash };
}
const response = await fetch(url, { mode: 'cors', cache: 'no-cache' });
if (!response.ok) {
return { status: 'failed', url, error: `Theme update check failed (${response.status}).` };
}
const cssText = await response.text();
const contentHash = await hashThemeCss(cssText);
const previousHash =
existing?.contentHash ?? (existing ? await hashThemeCss(existing.cssText) : undefined);
const now = Date.now();
if (existing && previousHash === contentHash) {
await writeCachedThemeEntry({
...existing,
checkedAt: now,
contentHash,
etag: response.headers.get('etag') ?? existing.etag,
lastModified: response.headers.get('last-modified') ?? existing.lastModified,
});
return { status: 'unchanged', url, contentHash };
}
await writeCachedThemeEntry({
url,
cssText,
cachedAt: now,
checkedAt: now,
contentHash,
etag: response.headers.get('etag') ?? undefined,
lastModified: response.headers.get('last-modified') ?? undefined,
});
notifyThemeCacheUpdated({ url, contentHash });
return { status: 'updated', url, previousHash, contentHash };
} catch (error) {
return {
status: 'failed',
url,
error: error instanceof Error ? error.message : 'Theme update check failed.',
};
}
}
export async function clearThemeCache(): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
@@ -52,3 +204,60 @@ export async function clearThemeCache(): Promise<void> {
tx.addEventListener('error', () => reject(tx.error));
});
}
export async function getThemeCacheStats(): Promise<ThemeCacheStats> {
const db = await openDb();
const entries = await new Promise<CachedThemeEntry[]>((resolve, reject) => {
const tx = db.transaction(STORE, 'readonly');
const req = tx.objectStore(STORE).getAll();
req.addEventListener('error', () => reject(req.error));
req.addEventListener('success', () => resolve(req.result as CachedThemeEntry[]));
});
const stats: ThemeCacheStats = {
entries: entries.length,
localEntries: 0,
remoteEntries: 0,
totalBytes: 0,
localBytes: 0,
remoteBytes: 0,
};
entries.forEach((entry) => {
const bytes = new TextEncoder().encode(entry.cssText).byteLength;
const local = entry.url.startsWith('sable-import://');
stats.totalBytes += bytes;
if (local) {
stats.localEntries += 1;
stats.localBytes += bytes;
} else {
stats.remoteEntries += 1;
stats.remoteBytes += bytes;
const checkedAt = entry.checkedAt ?? entry.cachedAt;
if (!stats.lastCheckedAt || checkedAt > stats.lastCheckedAt) stats.lastCheckedAt = checkedAt;
}
});
return stats;
}
/** Clears only refetchable network CSS. Uploaded local theme packages are preserved. */
export async function clearRemoteThemeCache(): Promise<number> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
const store = tx.objectStore(STORE);
const req = store.openCursor();
let removed = 0;
req.addEventListener('error', () => reject(req.error));
req.addEventListener('success', () => {
const cursor = req.result;
if (!cursor) return;
const entry = cursor.value as CachedThemeEntry;
if (!entry.url.startsWith('sable-import://')) {
cursor.delete();
removed += 1;
}
cursor.continue();
});
tx.addEventListener('complete', () => resolve(removed));
tx.addEventListener('error', () => reject(tx.error));
});
}
+57
View File
@@ -0,0 +1,57 @@
import { revalidateCachedThemeCss, type ThemeCacheRevalidationResult } from './cache';
import { fetchThemeCatalogBundle } from './catalog';
export const THEME_CATALOG_AUTO_UPDATE_INTERVAL_MS = 6 * 60 * 60_000;
const lastCatalogChecks = new Map<string, number>();
export type CatalogUpdateSummary = {
checked: number;
updated: number;
unchanged: number;
skipped: number;
failed: number;
results: ThemeCacheRevalidationResult[];
};
export type UpdateInstalledCatalogPackagesOptions = {
catalogBase: string;
manifestUrl?: string;
installedThemeUrls: string[];
installedTweakUrls: string[];
maxAgeMs?: number;
};
export async function updateInstalledCatalogPackages({
catalogBase,
manifestUrl,
installedThemeUrls,
installedTweakUrls,
maxAgeMs = THEME_CATALOG_AUTO_UPDATE_INTERVAL_MS,
}: UpdateInstalledCatalogPackagesOptions): Promise<CatalogUpdateSummary> {
const catalogCheckKey = `${catalogBase}\n${manifestUrl ?? ''}`;
const previousCatalogCheck = lastCatalogChecks.get(catalogCheckKey) ?? 0;
if (maxAgeMs > 0 && Date.now() - previousCatalogCheck < maxAgeMs) {
return { checked: 0, updated: 0, unchanged: 0, skipped: 0, failed: 0, results: [] };
}
const bundle = await fetchThemeCatalogBundle(catalogBase, { manifestUrl });
const catalogThemeUrls = new Set(bundle.themes.map((theme) => theme.fullUrl));
lastCatalogChecks.set(catalogCheckKey, Date.now());
const catalogTweakUrls = new Set(bundle.tweaks.map((tweak) => tweak.fullUrl));
const installed = new Set([
...installedThemeUrls.filter((url) => catalogThemeUrls.has(url)),
...installedTweakUrls.filter((url) => catalogTweakUrls.has(url)),
]);
const results = await Promise.all(
Array.from(installed, (url) => revalidateCachedThemeCss(url, maxAgeMs))
);
return {
checked: results.filter((result) => result.status !== 'skipped').length,
updated: results.filter((result) => result.status === 'updated').length,
unchanged: results.filter((result) => result.status === 'unchanged').length,
skipped: results.filter((result) => result.status === 'skipped').length,
failed: results.filter((result) => result.status === 'failed').length,
results,
};
}
+183
View File
@@ -37,6 +37,62 @@ export type ProcessedThemeImport =
}
| { ok: false; error: string };
export type ProcessedUploadedSableCss =
| {
ok: true;
role: 'theme';
fullUrl?: string;
previewCssForCard: string;
fullCssForCard?: string;
displayName: string;
basename: string;
kind: 'light' | 'dark';
importedLocal: boolean;
previewOnly: boolean;
}
| {
ok: true;
role: 'tweak';
fullUrl: string;
cssText: string;
displayName: string;
basename: string;
description?: string;
author?: string;
tags: string[];
importedLocal: true;
}
| { ok: false; error: string };
export function isSableCssAttachmentFileName(fileName: string): boolean {
return /\.sable\.css$/i.test(fileName);
}
function fallbackStableId(sourceKey: string): string {
let first = 0x811c9dc5;
let second = 0x9e3779b9;
for (let i = 0; i < sourceKey.length; i += 1) {
const code = sourceKey.charCodeAt(i);
first = Math.imul(first ^ code, 0x01000193);
second = Math.imul(second ^ code, 0x85ebca6b);
}
return `${(first >>> 0).toString(16).padStart(8, '0')}${(second >>> 0)
.toString(16)
.padStart(8, '0')}`;
}
async function stableImportId(sourceKey: string): Promise<string> {
try {
const bytes = new TextEncoder().encode(sourceKey);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0'))
.join('')
.slice(0, 32);
} catch {
return fallbackStableId(sourceKey);
}
}
function basenameFromHttpsUrl(url: string): string {
try {
const u = new URL(url);
@@ -274,3 +330,130 @@ export async function processPastedOrUploadedCss(
importedLocal: true,
};
}
/** Process a Matrix file attachment without treating a preview-only file as a full theme. */
export async function processUploadedSableCssAttachment(
cssText: string,
fileName: string,
sourceKey: string
): Promise<ProcessedUploadedSableCss> {
const trimmed = cssText.trim();
if (!trimmed) return { ok: false, error: 'The uploaded CSS file is empty.' };
const packageKind = getSableCssPackageKind(trimmed);
if (packageKind === 'unknown') {
return {
ok: false,
error: 'This file does not contain @sable-theme or @sable-tweak metadata.',
};
}
const stableId = await stableImportId(sourceKey);
if (packageKind === 'tweak') {
const meta = parseSableTweakMetadata(trimmed);
const basename = tweakBasename(meta, fileName);
const fullUrl = localImportTweakFullUrl(stableId);
await putCachedThemeCss(fullUrl, trimmed);
return {
ok: true,
role: 'tweak',
fullUrl,
cssText: trimmed,
displayName: meta.name?.trim() || basename,
basename,
description: meta.description?.trim() || undefined,
author: meta.author?.trim() || undefined,
tags: meta.tags ?? [],
importedLocal: true,
};
}
const meta = parseSableThemeMetadata(trimmed);
const fileBasename = fileName
.replace(/\.preview\.sable\.css$/i, '')
.replace(/\.sable\.css$/i, '');
const displayName = meta.name?.trim() || fileBasename || 'Uploaded theme';
const basename =
meta.id?.trim() ||
displayName.replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-|-$/g, '') ||
'uploaded';
const isPreviewFile = /\.preview\.sable\.css$/i.test(fileName);
if (isPreviewFile) {
const fullUrl = extractFullThemeUrlFromPreview(trimmed);
if (!fullUrl) {
return {
ok: true,
role: 'theme',
previewCssForCard: trimmed,
displayName,
basename,
kind: metaKindToLd(meta),
importedLocal: false,
previewOnly: true,
};
}
try {
const response = await fetch(fullUrl, { mode: 'cors' });
if (!response.ok) {
return {
ok: true,
role: 'theme',
previewCssForCard: trimmed,
displayName,
basename,
kind: metaKindToLd(meta),
importedLocal: false,
previewOnly: true,
};
}
const fullCss = await response.text();
if (getSableCssPackageKind(fullCss) === 'tweak') {
return { ok: false, error: 'The preview file points to a tweak instead of a full theme.' };
}
await putCachedThemeCss(fullUrl, fullCss);
return {
ok: true,
role: 'theme',
fullUrl,
previewCssForCard: trimmed,
fullCssForCard: fullCss,
displayName,
basename,
kind: metaKindToLd(meta),
importedLocal: false,
previewOnly: false,
};
} catch {
return {
ok: true,
role: 'theme',
previewCssForCard: trimmed,
displayName,
basename,
kind: metaKindToLd(meta),
importedLocal: false,
previewOnly: true,
};
}
}
const fullUrl = localImportFullUrl(stableId);
const previewUrl = localImportPreviewUrl(stableId);
await putCachedThemeCss(fullUrl, trimmed);
await putCachedThemeCss(previewUrl, trimmed);
return {
ok: true,
role: 'theme',
fullUrl,
previewCssForCard: trimmed,
fullCssForCard: trimmed,
displayName,
basename,
kind: metaKindToLd(meta),
importedLocal: true,
previewOnly: false,
};
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest';
import {
pruneThemeFavorites,
pruneThemeTweakFavorites,
themeSourceLabel,
themeUrlHostLabel,
} from './themeLibrary';
describe('themeLibrary', () => {
it('keeps pinned and active theme records', () => {
const favorites = [
{ fullUrl: 'active', displayName: 'Active', basename: 'active', kind: 'dark' as const },
{
fullUrl: 'pinned',
displayName: 'Pinned',
basename: 'pinned',
kind: 'light' as const,
pinned: true,
},
{ fullUrl: 'unused', displayName: 'Unused', basename: 'unused', kind: 'dark' as const },
];
expect(pruneThemeFavorites(favorites, ['active']).map((item) => item.fullUrl)).toEqual([
'active',
'pinned',
]);
});
it('keeps pinned and enabled tweak records', () => {
const favorites = [
{ fullUrl: 'enabled', displayName: 'Enabled', basename: 'enabled' },
{ fullUrl: 'pinned', displayName: 'Pinned', basename: 'pinned', pinned: true },
{ fullUrl: 'unused', displayName: 'Unused', basename: 'unused' },
];
expect(pruneThemeTweakFavorites(favorites, ['enabled']).map((item) => item.fullUrl)).toEqual([
'enabled',
'pinned',
]);
});
it('provides consistent source labels', () => {
expect(themeSourceLabel({ importedLocal: true })).toBe('Uploaded file');
expect(themeSourceLabel({ official: true })).toBe('Official catalog');
expect(themeSourceLabel({ url: 'https://themes.example/night.sable.css' })).toBe(
'themes.example'
);
expect(themeUrlHostLabel('not a URL', 'Unknown')).toBe('Unknown');
});
});
+40
View File
@@ -0,0 +1,40 @@
import type { ThemeRemoteFavorite, ThemeRemoteTweakFavorite } from '$state/settings';
export function pruneThemeFavorites(
favorites: ThemeRemoteFavorite[],
activeUrls: Array<string | undefined>
): ThemeRemoteFavorite[] {
const active = new Set(activeUrls.filter((url): url is string => Boolean(url)));
return favorites.filter((favorite) => favorite.pinned === true || active.has(favorite.fullUrl));
}
export function pruneThemeTweakFavorites(
favorites: ThemeRemoteTweakFavorite[],
enabledUrls: string[]
): ThemeRemoteTweakFavorite[] {
const enabled = new Set(enabledUrls);
return favorites.filter((favorite) => favorite.pinned === true || enabled.has(favorite.fullUrl));
}
export function themeUrlHostLabel(url: string, fallback = 'Third-party source'): string {
try {
return new URL(url).hostname;
} catch {
return fallback;
}
}
export function themeSourceLabel({
importedLocal,
official,
url,
}: {
importedLocal?: boolean;
official?: boolean;
url?: string;
}): string {
if (importedLocal) return 'Uploaded file';
if (official) return 'Official catalog';
if (url) return themeUrlHostLabel(url);
return 'Local theme';
}