Merge remote-tracking branch 'origin/dev' into sliding-sync-stablization

This commit is contained in:
7w1 committed 2026-07-16 13:38:46 -05:00
commit 7c29062403
35 files changed
+2029 -487

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
Use attachment filenames instead of captions when downloading files and harden unsafe download names.
@@ -0,0 +1,5 @@
---
default: patch
---
Fix the new messages divider staying at the room-open position instead of re-anchoring at the last read when the window loses focus.
@@ -0,0 +1,5 @@
---
default: patch
---
Fix redacted messages rendering as "Unsupported message (no body)" instead of "Message deleted" with sliding sync.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Display redacted state events (membership, room name/topic/avatar, pins and other state events) as a "deleted" tombstone in the timeline instead of rendering them with empty/redacted content or hiding them, so the reply-to of a redaction highlights the redacted event.
@@ -0,0 +1,5 @@
---
default: patch
---
Add uploaded Sable CSS theme loading, automatic catalog updates, and a cleaner theme browser with full CSS viewing.
+5
View File
@@ -0,0 +1,5 @@
---
default: minor
---
Show the unread mention count in the page title.
+2 -1
View File
@@ -29,6 +29,7 @@ import {
} from '$components/icons/phosphor';
import FocusTrap from 'focus-trap-react';
import FileSaver from 'file-saver';
import { getDownloadFilename } from '$utils/download';
import { AsyncStatus } from '$hooks/useAsyncCallback';
import { useImageGestures } from '$hooks/useImageGestures';
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '$plugins/pdfjs-dist';
@@ -90,7 +91,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
}, [docState, pageNo, zoom]);
const handleDownload = () => {
FileSaver.saveAs(src, name);
FileSaver.saveAs(src, getDownloadFilename(name, undefined, 'document.pdf'));
};
const handleJumpSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
@@ -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}
@@ -37,16 +37,18 @@ import { CheckerboardIcon, CopyIcon, DownloadIcon } from '@phosphor-icons/react'
import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '$utils/keyboard';
import { copyImageToClipboard } from '$utils/dom';
import { getDownloadFilename } from '$utils/download';
export type ImageViewerProps = {
alt: string;
filename?: string;
src: string;
requestClose: () => void;
info?: IImageInfo;
};
export const ImageViewer = as<'div', ImageViewerProps>(
({ className, alt, src, requestClose, info, ...props }, ref) => {
({ className, alt, filename, src, requestClose, info, ...props }, ref) => {
const zoomInputRef = useRef<HTMLInputElement>(null);
const [pixelatedImageRendering] = useSetting(settingsAtom, 'pixelatedImageRendering');
@@ -98,7 +100,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
const handleDownload = async () => {
const fileContent = await downloadMedia(src);
FileSaver.saveAs(fileContent, alt);
FileSaver.saveAs(fileContent, getDownloadFilename(filename, alt, 'image'));
};
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
+2 -1
View File
@@ -9,6 +9,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
import { getDownloadFilename } from '$utils/download';
const badgeStyles = { maxWidth: toRem(100) };
@@ -31,7 +32,7 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow
: await downloadMedia(mediaUrl);
const fileURL = URL.createObjectURL(fileContent);
FileSaver.saveAs(fileURL, filename);
FileSaver.saveAs(fileURL, getDownloadFilename(filename));
return fileURL;
}, [mx, url, useAuthentication, mimeType, encInfo, filename])
);
@@ -37,6 +37,7 @@ import { unwrapForwardedContent } from './modals/MessageForward';
import { LINKINPUTREGEX } from '$components/editor';
import { MATRIX_TO_BASE } from '$plugins/matrix-to';
import { copyToClipboard } from '$utils/dom';
import { getAttachmentFilename } from '$utils/download';
import { MapContainer, Marker, TileLayer } from 'react-leaflet';
import type { LatLngExpression } from 'leaflet';
import 'leaflet/dist/leaflet.css';
@@ -447,6 +448,7 @@ export function MImage({ content, renderImageContent, outlined, fitParent }: MIm
// this garbage is for portrait images, we cap the width so the card doesn't exceed the bounds of the image
const displayWidth = imgH > imgW ? Math.round(MAX_SIZE * (imgW / imgH)) : MAX_SIZE;
const height = scaleYDimension(imgInfo?.w || 400, displayWidth, imgInfo?.h || 400);
const filename = getAttachmentFilename(content.filename, content.body, 'Image');
return (
<Attachment
@@ -468,6 +470,7 @@ export function MImage({ content, renderImageContent, outlined, fitParent }: MIm
>
{renderImageContent({
body: content.body || content.filename || 'Image',
filename,
info: imgInfo,
mimeType: imgInfo?.mimetype,
url: mxcUrl,
@@ -511,7 +514,7 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
const displayWidth = Math.min(videoInfo.w || 400, 400);
const height = Math.min(scaleYDimension(videoInfo.w || 400, 400, videoInfo.h || 400), 400);
const filename = content.filename ?? content.body ?? 'Video';
const filename = getAttachmentFilename(content.filename, content.body, 'Video');
return (
<Attachment
@@ -611,7 +614,7 @@ export function MAudio({
return <BrokenContent body={content.body ?? content.filename} />;
}
const filename = content.filename ?? content.body ?? 'Audio';
const filename = getAttachmentFilename(content.filename, content.body, 'Audio');
const durationMs = getAudioDurationMs(content, audioInfo);
const resolvedInfo =
durationMs !== undefined ? { ...audioInfo, duration: durationMs } : audioInfo;
@@ -649,7 +652,7 @@ export function MAudio({
}
type RenderFileContentProps = {
body: string;
fileName: string;
info: IFileInfo & IThumbnailContent;
mimeType: string;
url: string;
@@ -669,18 +672,17 @@ export function MFile({ content, renderFileContent, outlined }: MFileProps) {
return <BrokenContent body={content.body ?? content.filename} />;
}
const filename = getAttachmentFilename(content.filename, content.body, 'File');
return (
<Attachment outlined={outlined} style={{ width: toRem(400), height: 'auto' }}>
<AttachmentHeader>
<FileHeader
body={content.filename ?? content.body ?? 'Unnamed File'}
mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE}
/>
<FileHeader body={filename} mimeType={fileInfo?.mimetype ?? FALLBACK_MIMETYPE} />
</AttachmentHeader>
<AttachmentBox>
<AttachmentContent>
{renderFileContent({
body: content.body ?? content.filename ?? 'File',
fileName: filename,
info: fileInfo ?? {},
mimeType: fileInfo?.mimetype ?? FALLBACK_MIMETYPE,
url: mxcUrl,
@@ -31,6 +31,7 @@ import { stopPropagation } from '$utils/keyboard';
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { ModalWide } from '$styles/Modal.css';
import { getDownloadFilename } from '$utils/download';
const renderErrorButton = (retry: () => void, text: string) => (
<TooltipProvider
@@ -257,7 +258,7 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
: await downloadMedia(mediaUrl);
const fileURL = URL.createObjectURL(fileContent);
FileSaver.saveAs(fileURL, body);
FileSaver.saveAs(fileURL, getDownloadFilename(body));
return fileURL;
}, [mx, url, useAuthentication, mimeType, encInfo, body])
);
@@ -272,7 +273,7 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
size="400"
onClick={() =>
downloadState.status === AsyncStatus.Success
? FileSaver.saveAs(downloadState.data, body)
? FileSaver.saveAs(downloadState.data, getDownloadFilename(body))
: download()
}
disabled={downloadState.status === AsyncStatus.Loading}
@@ -70,6 +70,7 @@ function thumbnailDimsForMaxEdge(
type RenderViewerProps = {
src: string;
alt: string;
filename?: string;
requestClose: () => void;
info?: IImageInfo;
};
@@ -84,6 +85,7 @@ type RenderImageProps = {
};
export type ImageContentProps = {
body?: string;
filename?: string;
mimeType?: string;
url: string;
info?: IImageInfo;
@@ -104,6 +106,7 @@ export const ImageContent = as<'div', ImageContentProps>(
className,
style,
body,
filename,
mimeType,
url,
info,
@@ -270,6 +273,7 @@ export const ImageContent = as<'div', ImageContentProps>(
{renderViewer({
src: viewerFullSrc ?? srcState.data,
alt: body ?? '',
filename,
requestClose: () => setViewer(false),
info: info,
})}
@@ -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 ? (
+10 -2
View File
@@ -832,9 +832,17 @@ export function RoomTimeline({
useDocumentFocusChange(
useCallback(
(inFocus) => {
if (inFocus && atBottomState) tryAutoMarkAsRead();
if (inFocus) {
if (atBottomState) tryAutoMarkAsRead();
return;
}
// Re-anchor the divider at the last read when tabbing out while caught up.
if (atBottomState && timelineSync.liveTimelineLinked) {
readUptoEventIdRef.current = undefined;
setUnreadInfo(undefined);
}
},
[tryAutoMarkAsRead, atBottomState]
[tryAutoMarkAsRead, atBottomState, timelineSync.liveTimelineLinked, setUnreadInfo]
)
);
@@ -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',
@@ -562,6 +562,7 @@ export function useTimelineEventRenderer({
const baseContent = mEvent.getContent() || {};
const safeContent =
Object.keys(baseContent).length > 0 ? baseContent : mEvent.getOriginalContent();
const isContentEmpty = Object.keys(safeContent).length === 0;
const getContent = (() => editedNewContent ?? safeContent) as GetContentCallback;
@@ -669,7 +670,7 @@ export function useTimelineEventRenderer({
hour24Clock={hour24Clock}
dateFormatString={dateFormatString}
>
{mEvent.isRedacted() ? (
{mEvent.isRedacted() || isContentEmpty ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<RenderMessageContent
@@ -1039,6 +1040,7 @@ export function useTimelineEventRenderer({
const baseContent = mEvent.getContent() || {};
const safeContent =
Object.keys(baseContent).length > 0 ? baseContent : mEvent.getOriginalContent();
const isContentEmpty = Object.keys(safeContent).length === 0;
const getContent = (() => editedNewContent ?? safeContent) as GetContentCallback;
@@ -1146,7 +1148,7 @@ export function useTimelineEventRenderer({
hour24Clock={hour24Clock}
dateFormatString={dateFormatString}
>
{mEvent.isRedacted() ? (
{mEvent.isRedacted() || isContentEmpty ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<RenderMessageContent
@@ -1176,9 +1178,10 @@ export function useTimelineEventRenderer({
if (membershipChanged && hideMembershipEvents) return null;
if (!membershipChanged && hideNickAvatarEvents) return null;
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const parsed = parseMemberEvent(mEvent);
const parsed = isRedacted ? null : parseMemberEvent(mEvent);
const timeJSX = (
<Time
@@ -1257,19 +1260,24 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={parsed.icon}
icon={parsed?.icon ?? timelineIcon(Trash)}
content={
<Text size="T300" priority="300">
<Box direction="Row" style={{ flexWrap: 'wrap', columnGap: toRem(6) }}>
{parsed.body}
</Box>
</Text>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Text size="T300" priority="300">
<Box direction="Row" style={{ flexWrap: 'wrap', columnGap: toRem(6) }}>
{parsed?.body}
</Box>
</Text>
)
}
/>
</Message>
);
},
[EventType.RoomName]: (mEventId, mEvent, item, timelineSet, collapse) => {
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const senderId = mEvent.getSender() ?? '';
@@ -1351,20 +1359,25 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={timelineIcon(Hash)}
icon={isRedacted ? timelineIcon(Trash) : timelineIcon(Hash)}
content={
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{t('Organisms.RoomCommon.changed_room_name')}
</Text>
</Box>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{t('Organisms.RoomCommon.changed_room_name')}
</Text>
</Box>
)
}
/>
</Message>
);
},
[EventType.RoomTopic]: (mEventId, mEvent, item, timelineSet, collapse) => {
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const senderId = mEvent.getSender() ?? '';
@@ -1447,20 +1460,25 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={timelineIcon(Hash)}
icon={isRedacted ? timelineIcon(Trash) : timelineIcon(Hash)}
content={
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{' changed room topic'}
</Text>
</Box>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{' changed room topic'}
</Text>
</Box>
)
}
/>
</Message>
);
},
[EventType.RoomAvatar]: (mEventId, mEvent, item, timelineSet, collapse) => {
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const senderId = mEvent.getSender() ?? '';
@@ -1543,20 +1561,25 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={timelineIcon(Hash)}
icon={isRedacted ? timelineIcon(Trash) : timelineIcon(Hash)}
content={
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{' changed room avatar'}
</Text>
</Box>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{' changed room avatar'}
</Text>
</Box>
)
}
/>
</Message>
);
},
[EventType.GroupCallMemberPrefix]: (mEventId, mEvent, item, timelineSet, collapse) => {
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const senderId = mEvent.getSender() ?? '';
@@ -1646,14 +1669,24 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={callJoined ? timelineIcon(Phone) : timelineIcon(PhoneDisconnect)}
icon={
isRedacted
? timelineIcon(Trash)
: callJoined
? timelineIcon(Phone)
: timelineIcon(PhoneDisconnect)
}
content={
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{callJoined ? ' joined the call' : ' ended the call'}
</Text>
</Box>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{callJoined ? ' joined the call' : ' ended the call'}
</Text>
</Box>
)
}
/>
</Message>
@@ -1988,6 +2021,7 @@ export function useTimelineEventRenderer({
},
[EventType.RoomPinnedEvents]: (mEventId, mEvent, item, timelineSet, collapse) => {
if (!hiddenEventOther) return null;
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const senderId = mEvent.getSender() ?? '';
@@ -2081,39 +2115,43 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={timelineIcon(PushPin)}
icon={isRedacted ? timelineIcon(Trash) : timelineIcon(PushPin)}
content={
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{(pinsAdded?.length > 0 &&
`pinned ${pinsAdded.length} message${pinsAdded.length > 1 ? 's' : ''}`) ||
''}
{(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && ` and `) || ''}
{(pinsRemoved?.length > 0 &&
`unpinned ${pinsRemoved.length} message${
pinsRemoved.length > 1 ? 's' : ''
}`) ||
''}
{((!pinsAdded || pinsAdded.length <= 0) &&
(!pinsRemoved || pinsRemoved.length <= 0) &&
`has not changed the pins`) ||
`:`}
</Text>
{pinPreviewIds.length > 0 &&
pinPreviewIds
.slice(0, 4)
.map((x: string) => (
<Reply
key={x}
style={{ opacity: '80%' }}
room={room}
replyEventId={x}
onClick={handleOpenReply}
replyIcon={<>{menuIcon(pinnedSet.has(x) ? PushPin : PushPinSlash)}</>}
/>
))}
</Box>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{(pinsAdded?.length > 0 &&
`pinned ${pinsAdded.length} message${pinsAdded.length > 1 ? 's' : ''}`) ||
''}
{(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && ` and `) || ''}
{(pinsRemoved?.length > 0 &&
`unpinned ${pinsRemoved.length} message${
pinsRemoved.length > 1 ? 's' : ''
}`) ||
''}
{((!pinsAdded || pinsAdded.length <= 0) &&
(!pinsRemoved || pinsRemoved.length <= 0) &&
`has not changed the pins`) ||
`:`}
</Text>
{pinPreviewIds.length > 0 &&
pinPreviewIds
.slice(0, 4)
.map((x: string) => (
<Reply
key={x}
style={{ opacity: '80%' }}
room={room}
replyEventId={x}
onClick={handleOpenReply}
replyIcon={<>{menuIcon(pinnedSet.has(x) ? PushPin : PushPinSlash)}</>}
/>
))}
</Box>
)
}
/>
</Message>
@@ -2122,6 +2160,7 @@ export function useTimelineEventRenderer({
},
(mEventId, mEvent, item, timelineSet, collapse) => {
if (!hiddenEventOther) return null;
const isRedacted = mEvent.isRedacted();
const highlighted = focusItem?.index === item && focusItem.highlight;
const marked = activeReplyId === mEventId && !suppressMark;
const senderId = mEvent.getSender() ?? '';
@@ -2203,16 +2242,20 @@ export function useTimelineEventRenderer({
<EventContent
messageLayout={messageLayout}
time={timeJSX}
icon={timelineIcon(Code)}
icon={isRedacted ? timelineIcon(Trash) : timelineIcon(Code)}
content={
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{' sent '}
<code className={customHtmlCss.Code}>{mEvent.getType()}</code>
{' state event'}
</Text>
</Box>
isRedacted ? (
<RedactedContent reason={mEvent.getUnsigned().redacted_because?.content.reason} />
) : (
<Box grow="Yes" direction="Column">
<Text size="T300" priority="300">
<DecoratedUser userId={senderId} userName={senderName} room={room} />
{' sent '}
<code className={customHtmlCss.Code}>{mEvent.getType()}</code>
{' state event'}
</Text>
</Box>
)
}
/>
</Message>
+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>
</>
);
}
+37 -17
View File
@@ -39,7 +39,7 @@ import {
isDMRoom,
isNotificationEvent,
} from '$utils/room';
import { NotificationType } from '$types/matrix/room';
import { NotificationType, type RoomToUnread } from '$types/matrix/room';
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
import { useSelectedRoom } from '$hooks/router/useSelectedRoom';
import { useInboxNotificationsSelected } from '$hooks/router/useInbox';
@@ -107,6 +107,40 @@ function PageZoomFeature() {
return null;
}
// Sum only leaf rooms (from === null); space entries aggregate their children
// and would double-count.
function getUnreadTotals(roomToUnread: RoomToUnread) {
let total = 0;
let highlightTotal = 0;
let notification = false;
let highlight = false;
roomToUnread.forEach((unread) => {
if (unread.from === null) {
total += unread.total;
highlightTotal += unread.highlight;
}
if (unread.total > 0) {
notification = true;
}
if (unread.highlight > 0) {
highlight = true;
}
});
return { total, highlightTotal, notification, highlight };
}
// Show the mention count in the tab title.
function PageTitleUpdater() {
const roomToUnread = useAtomValue(roomToUnreadAtom);
useEffect(() => {
const { highlightTotal } = getUnreadTotals(roomToUnread);
document.title = highlightTotal > 0 ? `(${highlightTotal}) Sable Client` : 'Sable Client';
}, [roomToUnread]);
return null;
}
function FaviconUpdater() {
const roomToUnread = useAtomValue(roomToUnreadAtom);
const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
@@ -114,22 +148,7 @@ function FaviconUpdater() {
const registration = useAtomValue(registrationAtom);
useEffect(() => {
let notification = false;
let highlight = false;
let total = 0;
let highlightTotal = 0;
roomToUnread.forEach((unread) => {
if (unread.from === null) {
total += unread.total;
highlightTotal += unread.highlight;
}
if (unread.total > 0) {
notification = true;
}
if (unread.highlight > 0) {
highlight = true;
}
});
const { total, highlightTotal, notification, highlight } = getUnreadTotals(roomToUnread);
if (highlight) {
setFavicon(LogoHighlightSVG);
@@ -907,6 +926,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
<PageZoomFeature />
<PrivacyBlurFeature />
<FaviconUpdater />
<PageTitleUpdater />
<InviteNotifications />
<MessageNotifications />
<BackgroundNotifications />
+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';
}
+46
View File
@@ -0,0 +1,46 @@
const INVALID_FILENAME_CHARS = /[<>:"/\\|?*]/g;
const CONTROL_CHARS = /\p{Cc}/gu;
const BIDI_CONTROL_CHARS = /[\u202a-\u202e\u2066-\u2069]/g;
const WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
const MAX_FILENAME_LENGTH = 255;
const nonEmptyString = (value: unknown): string | undefined => {
if (typeof value !== 'string') return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
};
export const getAttachmentFilename = (
filename: unknown,
body: unknown,
fallback = 'download'
): string => nonEmptyString(filename) ?? nonEmptyString(body) ?? fallback;
export const sanitizeDownloadFilename = (filename: string, fallback = 'download'): string => {
let safeName = filename
.replace(INVALID_FILENAME_CHARS, '_')
.replace(CONTROL_CHARS, '_')
.replace(BIDI_CONTROL_CHARS, '')
.trim()
.replace(/[. ]+$/g, '');
if (!safeName || safeName === '.' || safeName === '..') safeName = fallback;
if (WINDOWS_RESERVED_NAME.test(safeName)) safeName = `_${safeName}`;
if (safeName.length > MAX_FILENAME_LENGTH) {
const extensionStart = safeName.lastIndexOf('.');
const extension = extensionStart > 0 ? safeName.slice(extensionStart) : '';
const extensionLength = Math.min(extension.length, 32);
safeName = `${safeName.slice(0, MAX_FILENAME_LENGTH - extensionLength)}${extension.slice(
-extensionLength
)}`;
}
return safeName;
};
export const getDownloadFilename = (
filename: unknown,
body?: unknown,
fallback = 'download'
): string => sanitizeDownloadFilename(getAttachmentFilename(filename, body, fallback), fallback);