diff --git a/src/app/components/RenderMessageContent.test.tsx b/src/app/components/RenderMessageContent.test.tsx index 666beab50..5ce02d13d 100644 --- a/src/app/components/RenderMessageContent.test.tsx +++ b/src/app/components/RenderMessageContent.test.tsx @@ -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 }) => ( +
{body}
+ ), +})); + +vi.mock('$hooks/useMediaAuthentication', () => ({ + useMediaAuthentication: () => false, +})); + vi.mock('./url-preview', () => ({ UrlPreviewHolder: ({ children }: { children: React.ReactNode }) => (
{children}
@@ -30,6 +41,23 @@ function renderMessage(body: string) { ); } +function renderFileMessage(content: Record) { + return render( + + + content as never} + htmlReactParserOptions={{}} + linkifyOpts={{}} + /> + + + ); +} + 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'); + }); }); diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 57c607eac..5c5538a96 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -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( & { msgtype: MsgType.File }} - renderFileContent={({ body, mimeType, info, encInfo, url }) => ( + renderFileContent={({ fileName, mimeType, info, encInfo, url }) => ( ( ( )} > - + {themeChatSableWidgets && isSableCssAttachmentFileName(fileName) && ( + + )} + )} outlined={outlineAttachment} diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index eb686aa07..692c7462e 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -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) { {renderFileContent({ - body: content.body ?? content.filename ?? 'File', + fileName: content.filename ?? content.body ?? 'File', info: fileInfo ?? {}, mimeType: fileInfo?.mimetype ?? FALLBACK_MIMETYPE, url: mxcUrl, diff --git a/src/app/components/message/content/UploadedSableCssContent.tsx b/src/app/components/message/content/UploadedSableCssContent.tsx new file mode 100644 index 000000000..dcecd3099 --- /dev/null +++ b/src/app/components/message/content/UploadedSableCssContent.tsx @@ -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; + +function pruneThemeFavorites( + favorites: ThemeRemoteFavorite[], + activeUrls: Array +): 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 }) { + 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 ( + + + + {data.displayName} + + {description || 'Uploaded tweak'} + + + + + {sizedIcon(Star, '200', { filled: isFavorite })} + + + + + {styleBlock && ( + <> + + + + Sample text + + + + )} + + ); +} + +function UploadedThemeCard({ data }: { data: Extract }) { + 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 = {}; + 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 = { + 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 ( + 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 => { + 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' ? ( + + ) : ( + + ); + } + + return ( + + + {loadState.status === AsyncStatus.Error && ( + + {loadState.error instanceof Error ? loadState.error.message : 'Failed to load theme CSS.'} + + )} + + ); +} diff --git a/src/app/components/message/content/index.ts b/src/app/components/message/content/index.ts index 6a31ed7ee..ca28c2005 100644 --- a/src/app/components/message/content/index.ts +++ b/src/app/components/message/content/index.ts @@ -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'; diff --git a/src/app/theme/processThemeImport.ts b/src/app/theme/processThemeImport.ts index eabcf3ad7..7e26d0f4b 100644 --- a/src/app/theme/processThemeImport.ts +++ b/src/app/theme/processThemeImport.ts @@ -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 { + 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 { + 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, + }; +}