support theme file uploads

This commit is contained in:
7w1 committed 2026-07-14 23:01:47 -05:00
1 parent e4f194bed4
commit 2ba185145d
6 files changed
+625 -7

No files matched your search

@@ -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}
@@ -649,7 +649,7 @@ export function MAudio({
}
type RenderFileContentProps = {
body: string;
fileName: string;
info: IFileInfo & IThumbnailContent;
mimeType: string;
url: string;
@@ -680,7 +680,7 @@ export function MFile({ content, renderFileContent, outlined }: MFileProps) {
<AttachmentBox>
<AttachmentContent>
{renderFileContent({
body: content.body ?? content.filename ?? 'File',
fileName: content.filename ?? content.body ?? 'File',
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 { 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 { 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 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));
}
function pruneTweakFavorites(
favorites: ThemeRemoteTweakFavorite[],
enabledUrls: string[]
): ThemeRemoteTweakFavorite[] {
const enabled = new Set(enabledUrls);
return favorites.filter((favorite) => favorite.pinned === true || enabled.has(favorite.fullUrl));
}
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: pruneTweakFavorites(
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: pruneTweakFavorites(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>
</Box>
<Box direction="Row" gap="100" alignItems="Center" shrink="No">
<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}
scopeSlug={`upload-${data.basename}`}
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';
+180
View File
@@ -37,6 +37,61 @@ export type ProcessedThemeImport =
}
| { ok: false; error: string };
export type ProcessedUploadedSableCss =
| {
ok: true;
role: 'theme';
fullUrl?: string;
previewCssForCard: 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 +329,128 @@ 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,
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,
displayName,
basename,
kind: metaKindToLd(meta),
importedLocal: true,
previewOnly: false,
};
}