mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 09:01:17 -08:00
warning banner and rendering for 3rd party themes and migration system and i forgot to commit earlier
This commit is contained in:
14 files changed
+464
-52
No files matched your search
@@ -3,7 +3,6 @@ import { MsgType } from '$types/matrix-sdk';
|
||||
import { parseSettingsLink } from '$features/settings/settingsLink';
|
||||
import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl';
|
||||
import { testMatrixTo } from '$plugins/matrix-to';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom, CaptionPosition } from '$state/settings';
|
||||
import { HTMLReactParserOptions } from 'html-react-parser';
|
||||
@@ -90,8 +89,6 @@ function RenderMessageContentInternal({
|
||||
const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs');
|
||||
const [captionPosition] = useSetting(settingsAtom, 'captionPosition');
|
||||
const [themeChatAny] = useSetting(settingsAtom, 'themeChatPreviewAnyUrl');
|
||||
const [themeChatApprovedOnly] = useSetting(settingsAtom, 'themeChatPreviewApprovedCatalogOnly');
|
||||
const clientConfig = useClientConfig();
|
||||
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
|
||||
const captionPositionMap = {
|
||||
[CaptionPosition.Above]: 'column-reverse',
|
||||
@@ -123,14 +120,7 @@ function RenderMessageContentInternal({
|
||||
const themePreviewUrls = themeChatAny
|
||||
? filteredUrls.filter((u) => /\.preview\.sable\.css(\?|#|$)/i.test(u))
|
||||
: [];
|
||||
const approvedPrefixes = clientConfig.themeCatalogApprovedHostPrefixes ?? [];
|
||||
const themeAllowed = (u: string) => {
|
||||
if (!/^https:\/\//i.test(u)) return false;
|
||||
if (!themeChatApprovedOnly) return true;
|
||||
if (approvedPrefixes.length === 0) return false;
|
||||
return approvedPrefixes.some((p) => u.startsWith(p));
|
||||
};
|
||||
const themeToRender = themePreviewUrls.filter(themeAllowed);
|
||||
const themeToRender = themePreviewUrls.filter((u) => /^https:\/\//i.test(u));
|
||||
|
||||
const analyzed = filteredUrls.map((url) => ({
|
||||
url,
|
||||
@@ -161,15 +151,7 @@ function RenderMessageContentInternal({
|
||||
</UrlPreviewHolder>
|
||||
);
|
||||
},
|
||||
[
|
||||
ts,
|
||||
clientUrlPreview,
|
||||
settingsLinkBaseUrl,
|
||||
urlPreview,
|
||||
themeChatAny,
|
||||
themeChatApprovedOnly,
|
||||
clientConfig.themeCatalogApprovedHostPrefixes,
|
||||
]
|
||||
[ts, clientUrlPreview, settingsLinkBaseUrl, urlPreview, themeChatAny]
|
||||
);
|
||||
const messageUrlsPreview = urlPreview || themeChatAny ? renderUrlsPreview : undefined;
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
config,
|
||||
Dialog,
|
||||
Header,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Overlay,
|
||||
OverlayBackdrop,
|
||||
OverlayCenter,
|
||||
Text,
|
||||
} from 'folds';
|
||||
import { useStore } from 'jotai/react';
|
||||
|
||||
import { useOptionalClientConfig } from '$hooks/useClientConfig';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { trimTrailingSlash } from '$utils/common';
|
||||
import { defaultSettings, settingsAtom } from '$state/settings';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
|
||||
import { usePatchSettings } from '$features/settings/cosmetics/ThemeCatalogSettings';
|
||||
import { needsLegacyThemeMigration } from '../../theme/legacyToCatalogMap';
|
||||
import { DEFAULT_THEME_CATALOG_BASE, runLegacyThemeMigration } from '../../theme/migrateLegacyThemes';
|
||||
|
||||
export function ThemeMigrationBanner() {
|
||||
const store = useStore();
|
||||
const [themeMigrationDismissed] = useSetting(settingsAtom, 'themeMigrationDismissed');
|
||||
const [themeId] = useSetting(settingsAtom, 'themeId');
|
||||
const [lightThemeId] = useSetting(settingsAtom, 'lightThemeId');
|
||||
const [darkThemeId] = useSetting(settingsAtom, 'darkThemeId');
|
||||
const patchSettings = usePatchSettings();
|
||||
const clientConfig = useOptionalClientConfig();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
needsLegacyThemeMigration({
|
||||
...defaultSettings,
|
||||
themeMigrationDismissed: themeMigrationDismissed ?? false,
|
||||
themeId,
|
||||
lightThemeId,
|
||||
darkThemeId,
|
||||
}),
|
||||
[themeMigrationDismissed, themeId, lightThemeId, darkThemeId]
|
||||
);
|
||||
|
||||
const catalogBase = trimTrailingSlash(
|
||||
clientConfig?.themeCatalogBaseUrl?.trim() || DEFAULT_THEME_CATALOG_BASE
|
||||
);
|
||||
|
||||
const dismiss = useCallback(() => {
|
||||
patchSettings({ themeMigrationDismissed: true });
|
||||
}, [patchSettings]);
|
||||
|
||||
const dismissSafe = useCallback(() => {
|
||||
if (busy) return;
|
||||
dismiss();
|
||||
}, [busy, dismiss]);
|
||||
|
||||
const migrate = useCallback(async () => {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const current = store.get(settingsAtom);
|
||||
const result = await runLegacyThemeMigration(current, catalogBase);
|
||||
if (!result.ok) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
patchSettings(result.partial);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [catalogBase, patchSettings, store]);
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
return (
|
||||
<Overlay open backdrop={<OverlayBackdrop />}>
|
||||
<OverlayCenter>
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: false,
|
||||
onDeactivate: dismissSafe,
|
||||
clickOutsideDeactivates: false,
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
<Dialog variant="Surface" aria-labelledby="theme-migration-title">
|
||||
<Header
|
||||
style={{
|
||||
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||
borderBottomWidth: config.borderWidth.B300,
|
||||
}}
|
||||
variant="Surface"
|
||||
size="500"
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text id="theme-migration-title" size="H4">
|
||||
Update your theme selection
|
||||
</Text>
|
||||
</Box>
|
||||
<IconButton
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={dismissSafe}
|
||||
disabled={busy}
|
||||
aria-label="Close"
|
||||
>
|
||||
<Icon src={Icons.Cross} size="100" />
|
||||
</IconButton>
|
||||
</Header>
|
||||
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
|
||||
<Text priority="400">
|
||||
Older bundled color themes are no longer included in the app. Migrate to the same
|
||||
looks from the official catalog (downloaded and cached on this device), or dismiss
|
||||
this reminder.
|
||||
</Text>
|
||||
{error && (
|
||||
<Text size="T300" priority="400" style={{ color: 'var(--sable-error)' }}>
|
||||
{error}
|
||||
</Text>
|
||||
)}
|
||||
<Box direction="Column" gap="200">
|
||||
<Button variant="Primary" fill="Solid" onClick={migrate} disabled={busy}>
|
||||
<Text size="B400">{busy ? 'Migrating…' : 'Migrate'}</Text>
|
||||
</Button>
|
||||
<Button variant="Secondary" fill="Soft" onClick={dismissSafe} disabled={busy}>
|
||||
<Text size="B400">Not now</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Dialog>
|
||||
</FocusTrap>
|
||||
</OverlayCenter>
|
||||
</Overlay>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../.
|
||||
export type ThemePreviewCardProps = {
|
||||
title: string;
|
||||
subtitle?: ReactNode;
|
||||
beforePreview?: ReactNode;
|
||||
previewCssText: string;
|
||||
scopeSlug: string;
|
||||
copyText?: string;
|
||||
@@ -33,6 +34,7 @@ function safeSlug(input: string): string {
|
||||
export function ThemePreviewCard({
|
||||
title,
|
||||
subtitle,
|
||||
beforePreview,
|
||||
previewCssText,
|
||||
scopeSlug,
|
||||
copyText,
|
||||
@@ -116,6 +118,8 @@ export function ThemePreviewCard({
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{beforePreview}
|
||||
|
||||
{styleBlock ? (
|
||||
<>
|
||||
<style>{styleBlock}</style>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '../../theme/metadata';
|
||||
import { putCachedThemeCss } from '../../theme/cache';
|
||||
import { ThemePreviewCard } from '../theme/ThemePreviewCard';
|
||||
import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner';
|
||||
|
||||
function isHttps(url: string): boolean {
|
||||
return /^https:\/\//i.test(url);
|
||||
@@ -52,7 +53,6 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
|
||||
const clientConfig = useClientConfig();
|
||||
const store = useStore();
|
||||
const [chatAny] = useSetting(settingsAtom, 'themeChatPreviewAnyUrl');
|
||||
const [chatApprovedOnly] = useSetting(settingsAtom, 'themeChatPreviewApprovedCatalogOnly');
|
||||
const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites');
|
||||
const [systemTheme] = useSetting(settingsAtom, 'useSystemTheme');
|
||||
const [manualRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl');
|
||||
@@ -61,18 +61,19 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
|
||||
|
||||
const allowed = useMemo(() => {
|
||||
if (!chatAny) return false;
|
||||
if (!isHttps(url) || !isPreviewThemeUrl(url)) return false;
|
||||
if (chatApprovedOnly) {
|
||||
return isApprovedByPrefix(url, clientConfig.themeCatalogApprovedHostPrefixes);
|
||||
}
|
||||
return true;
|
||||
}, [chatAny, chatApprovedOnly, clientConfig.themeCatalogApprovedHostPrefixes, url]);
|
||||
return isHttps(url) && isPreviewThemeUrl(url);
|
||||
}, [chatAny, url]);
|
||||
|
||||
const isOfficial = useMemo(
|
||||
() => isApprovedByPrefix(url, clientConfig.themeCatalogApprovedHostPrefixes),
|
||||
[clientConfig.themeCatalogApprovedHostPrefixes, url]
|
||||
);
|
||||
|
||||
const showThirdPartyBanner = useMemo(() => {
|
||||
const p = clientConfig.themeCatalogApprovedHostPrefixes;
|
||||
return Boolean(p && p.length > 0 && !isApprovedByPrefix(url, p));
|
||||
}, [clientConfig.themeCatalogApprovedHostPrefixes, url]);
|
||||
|
||||
const previewQuery = useQuery({
|
||||
queryKey: ['theme-preview-embed', url],
|
||||
enabled: allowed,
|
||||
@@ -174,9 +175,9 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
|
||||
|
||||
const next: ThemeRemoteFavorite = {
|
||||
fullUrl,
|
||||
displayName: previewQuery.data.displayName,
|
||||
displayName: previewQuery.data?.displayName ?? basenameFromUrl(fullUrl),
|
||||
basename: basenameFromUrl(fullUrl),
|
||||
kind: previewQuery.data.kind === ThemeKind.Dark ? 'dark' : 'light',
|
||||
kind: previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light',
|
||||
pinned: true,
|
||||
};
|
||||
|
||||
@@ -402,6 +403,9 @@ export function ThemePreviewUrlCard({ url }: { url: string }) {
|
||||
<ThemePreviewCard
|
||||
title={title}
|
||||
subtitle={subtitle}
|
||||
beforePreview={
|
||||
showThirdPartyBanner ? <ThemeThirdPartyBanner hostLabel={baseLabel(url)} /> : undefined
|
||||
}
|
||||
previewCssText={previewQuery.data?.previewText ?? ''}
|
||||
scopeSlug={`chat-${basenameFromUrl(url)}`}
|
||||
copyText={url}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Box, Icon, Icons, Text, toRem, config } from 'folds';
|
||||
|
||||
type ThemeThirdPartyBannerProps = {
|
||||
hostLabel: string;
|
||||
};
|
||||
|
||||
export function ThemeThirdPartyBanner({ hostLabel }: ThemeThirdPartyBannerProps) {
|
||||
return (
|
||||
<Box
|
||||
direction="Column"
|
||||
gap="200"
|
||||
style={{
|
||||
padding: toRem(10),
|
||||
borderRadius: config.radii.R300,
|
||||
background: 'var(--sable-warn-container)',
|
||||
border: `${toRem(1)} solid var(--sable-warn-container-line)`,
|
||||
color: 'var(--sable-warn-on-container)',
|
||||
}}
|
||||
>
|
||||
<Box direction="Row" gap="200" alignItems="Start">
|
||||
<Icon src={Icons.Warning} size="100" filled />
|
||||
<Box direction="Column" gap="100" grow="Yes" style={{ minWidth: 0 }}>
|
||||
<Text size="T300" style={{ fontWeight: 600 }}>
|
||||
Third-party theme
|
||||
</Text>
|
||||
<Text size="T200" priority="300" style={{ wordBreak: 'break-word' }}>
|
||||
This preview is hosted on {hostLabel}, outside the Sable catalog allowlist. Saving or
|
||||
applying installs full theme CSS from that host—only use themes you trust.
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -2,3 +2,4 @@ export * from './UrlPreview';
|
||||
export * from './UrlPreviewCard';
|
||||
export * from './ClientPreview';
|
||||
export * from './ThemePreviewUrlCard';
|
||||
export * from './ThemeThirdPartyBanner';
|
||||
@@ -75,10 +75,6 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet
|
||||
const [lightRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl');
|
||||
const [darkRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl');
|
||||
const [chatAny, setChatAny] = useSetting(settingsAtom, 'themeChatPreviewAnyUrl');
|
||||
const [chatApprovedOnly, setChatApprovedOnly] = useSetting(
|
||||
settingsAtom,
|
||||
'themeChatPreviewApprovedCatalogOnly'
|
||||
);
|
||||
|
||||
const [search, setSearch] = useState('');
|
||||
const [kindFilter, setKindFilter] = useState<'all' | 'light' | 'dark'>('all');
|
||||
@@ -487,28 +483,12 @@ export function ThemeCatalogSettings({ mode = 'full' }: { mode?: ThemeCatalogSet
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Chat: theme previews from any HTTPS URL"
|
||||
title="Theme previews from any URL"
|
||||
focusId="theme-chat-preview-any"
|
||||
description="When enabled, messages linking to .preview.sable.css may fetch and show a small preview (parsed for safety)."
|
||||
description="When enabled, messages linking to .preview.sable.css may fetch and show a preview (parsed for safety). Installing these third-party themes is not necessarily safe."
|
||||
after={<Switch variant="Primary" value={chatAny} onChange={setChatAny} />}
|
||||
/>
|
||||
</SequenceCard>
|
||||
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Chat: only approved catalog URLs"
|
||||
focusId="theme-chat-preview-approved"
|
||||
description="Restricts chat theme embeds to URLs under approved prefixes from config."
|
||||
after={
|
||||
<Switch variant="Primary" value={chatApprovedOnly} onChange={setChatApprovedOnly} />
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ type SettingsShape = {
|
||||
themeId?: string;
|
||||
useSystemTheme: boolean;
|
||||
themeCatalogOnboardingDone: boolean;
|
||||
themeMigrationDismissed: boolean;
|
||||
themeRemoteCatalogEnabled: boolean;
|
||||
themeRemoteFavorites: unknown[];
|
||||
lightThemeId?: string;
|
||||
@@ -65,6 +66,7 @@ beforeEach(() => {
|
||||
themeId: 'silver-theme',
|
||||
useSystemTheme: true,
|
||||
themeCatalogOnboardingDone: true,
|
||||
themeMigrationDismissed: true,
|
||||
themeRemoteCatalogEnabled: false,
|
||||
themeRemoteFavorites: [],
|
||||
lightThemeId: 'cinny-light-theme',
|
||||
|
||||
@@ -58,6 +58,10 @@ export function useClientConfig(): ClientConfig {
|
||||
return config;
|
||||
}
|
||||
|
||||
export function useOptionalClientConfig(): ClientConfig | null {
|
||||
return useContext(ClientConfigContext);
|
||||
}
|
||||
|
||||
export const clientDefaultServer = (clientConfig: ClientConfig): string =>
|
||||
clientConfig.homeserverList?.[clientConfig.defaultHomeserver ?? 0] ?? 'matrix.org';
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ import { createDebugLogger } from '$utils/debugLogger';
|
||||
import { useSlidingSyncActiveRoom } from '$hooks/useSlidingSyncActiveRoom';
|
||||
import { getSlidingSyncManager } from '$client/initMatrix';
|
||||
import { NotificationBanner } from '$components/notification-banner';
|
||||
import { ThemeMigrationBanner } from '$components/theme/ThemeMigrationBanner';
|
||||
import { TelemetryConsentBanner } from '$components/telemetry-consent';
|
||||
import { useCallSignaling } from '$hooks/useCallSignaling';
|
||||
import { getBlobCacheStats } from '$hooks/useBlobCache';
|
||||
@@ -861,6 +862,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
|
||||
<HandleDecryptPushEvent />
|
||||
<NotificationBanner />
|
||||
<TelemetryConsentBanner />
|
||||
<ThemeMigrationBanner />
|
||||
<SlidingSyncActiveRoomSubscriber />
|
||||
<PresenceFeature />
|
||||
<SentryRoomContextFeature />
|
||||
|
||||
@@ -139,9 +139,10 @@ export interface Settings {
|
||||
themeRemoteManualKind?: 'light' | 'dark';
|
||||
themeRemoteLightKind?: 'light' | 'dark';
|
||||
themeRemoteDarkKind?: 'light' | 'dark';
|
||||
themeMigrationDismissed: boolean;
|
||||
}
|
||||
|
||||
const defaultSettings: Settings = {
|
||||
export const defaultSettings: Settings = {
|
||||
themeId: undefined,
|
||||
useSystemTheme: true,
|
||||
lightThemeId: undefined,
|
||||
@@ -250,6 +251,7 @@ const defaultSettings: Settings = {
|
||||
themeRemoteManualKind: undefined,
|
||||
themeRemoteLightKind: undefined,
|
||||
themeRemoteDarkKind: undefined,
|
||||
themeMigrationDismissed: false,
|
||||
};
|
||||
|
||||
export const getSettings = () => {
|
||||
@@ -277,6 +279,9 @@ export const getSettings = () => {
|
||||
if (!merged.themeRemoteFavorites) {
|
||||
merged.themeRemoteFavorites = [];
|
||||
}
|
||||
if (merged.themeMigrationDismissed === undefined) {
|
||||
merged.themeMigrationDismissed = false;
|
||||
}
|
||||
|
||||
return merged;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { defaultSettings } from '$state/settings';
|
||||
|
||||
import {
|
||||
catalogFullUrlForBasename,
|
||||
inferLegacyKindFromBasename,
|
||||
isLegacyThemeId,
|
||||
legacyThemeIdToBasename,
|
||||
needsLegacyThemeMigration,
|
||||
} from './legacyToCatalogMap';
|
||||
|
||||
describe('legacyToCatalogMap', () => {
|
||||
it('treats only light-theme and dark-theme as non-legacy', () => {
|
||||
expect(isLegacyThemeId(undefined)).toBe(false);
|
||||
expect(isLegacyThemeId('light-theme')).toBe(false);
|
||||
expect(isLegacyThemeId('dark-theme')).toBe(false);
|
||||
expect(isLegacyThemeId('silver-theme')).toBe(true);
|
||||
});
|
||||
|
||||
it('maps legacy id to basename', () => {
|
||||
expect(legacyThemeIdToBasename('silver-theme')).toBe('silver');
|
||||
expect(legacyThemeIdToBasename('cinny-light-theme')).toBe('cinny-light');
|
||||
});
|
||||
|
||||
it('builds catalog full URL', () => {
|
||||
expect(catalogFullUrlForBasename('silver', 'https://example.com/themes')).toBe(
|
||||
'https://example.com/themes/silver.sable.css'
|
||||
);
|
||||
});
|
||||
|
||||
it('infers kind from basename when metadata missing', () => {
|
||||
expect(inferLegacyKindFromBasename('silver')).toBe('light');
|
||||
expect(inferLegacyKindFromBasename('black')).toBe('dark');
|
||||
});
|
||||
|
||||
it('needs migration when dismissed is false and a slot is legacy', () => {
|
||||
expect(
|
||||
needsLegacyThemeMigration({
|
||||
...defaultSettings,
|
||||
themeMigrationDismissed: false,
|
||||
themeId: 'silver-theme',
|
||||
})
|
||||
).toBe(true);
|
||||
expect(
|
||||
needsLegacyThemeMigration({
|
||||
...defaultSettings,
|
||||
themeMigrationDismissed: true,
|
||||
themeId: 'silver-theme',
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { REMOTE_THEME_ID } from '$hooks/useTheme';
|
||||
import type { Settings } from '$state/settings';
|
||||
import { trimTrailingSlash } from '$utils/common';
|
||||
|
||||
export const BUILTIN_THEME_IDS = new Set(['light-theme', 'dark-theme']);
|
||||
|
||||
export function isLegacyThemeId(themeId: string | undefined): boolean {
|
||||
if (!themeId || themeId.trim() === '') return false;
|
||||
if (BUILTIN_THEME_IDS.has(themeId)) return false;
|
||||
if (themeId === REMOTE_THEME_ID) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function legacyThemeIdToBasename(legacyId: string): string {
|
||||
return legacyId.endsWith('-theme') ? legacyId.slice(0, -'-theme'.length) : legacyId;
|
||||
}
|
||||
|
||||
const DARK_BASENAMES = new Set([
|
||||
'dark',
|
||||
'black',
|
||||
'cinny-dark',
|
||||
'gruvdark',
|
||||
'accord',
|
||||
'butter',
|
||||
'rose-pine',
|
||||
]);
|
||||
|
||||
export function inferLegacyKindFromBasename(basename: string): 'light' | 'dark' {
|
||||
return DARK_BASENAMES.has(basename) ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
export function catalogFullUrlForBasename(basename: string, catalogBase: string): string {
|
||||
const base = trimTrailingSlash(catalogBase);
|
||||
return `${base}/${basename}.sable.css`;
|
||||
}
|
||||
|
||||
export function needsLegacyThemeMigration(settings: Settings): boolean {
|
||||
if (settings.themeMigrationDismissed) return false;
|
||||
return (
|
||||
isLegacyThemeId(settings.themeId) ||
|
||||
isLegacyThemeId(settings.lightThemeId) ||
|
||||
isLegacyThemeId(settings.darkThemeId)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { ThemeKind } from '$hooks/useTheme';
|
||||
import type { Settings, ThemeRemoteFavorite } from '$state/settings';
|
||||
import { trimTrailingSlash } from '$utils/common';
|
||||
|
||||
import { putCachedThemeCss } from './cache';
|
||||
import {
|
||||
catalogFullUrlForBasename,
|
||||
inferLegacyKindFromBasename,
|
||||
isLegacyThemeId,
|
||||
legacyThemeIdToBasename,
|
||||
} from './legacyToCatalogMap';
|
||||
import { parseSableThemeMetadata } from './metadata';
|
||||
|
||||
export const DEFAULT_THEME_CATALOG_BASE =
|
||||
'https://raw.githubusercontent.com/SableClient/themes/main';
|
||||
|
||||
type FetchOk = {
|
||||
kind: 'light' | 'dark';
|
||||
displayName: string;
|
||||
basename: string;
|
||||
};
|
||||
|
||||
async function fetchAndCacheTheme(
|
||||
url: string
|
||||
): Promise<{ ok: true; data: FetchOk } | { ok: false; error: string }> {
|
||||
try {
|
||||
const res = await fetch(url, { mode: 'cors' });
|
||||
if (!res.ok) return { ok: false, error: `Could not download theme (${res.status}).` };
|
||||
const text = await res.text();
|
||||
await putCachedThemeCss(url, text);
|
||||
const meta = parseSableThemeMetadata(text);
|
||||
const basenameFromUrl =
|
||||
url
|
||||
.replace(/\.sable\.css$/i, '')
|
||||
.split('/')
|
||||
.pop() ?? 'theme';
|
||||
const basename = meta.id?.trim() || basenameFromUrl;
|
||||
let kind: 'light' | 'dark';
|
||||
if (meta.kind === ThemeKind.Dark) kind = 'dark';
|
||||
else if (meta.kind === ThemeKind.Light) kind = 'light';
|
||||
else kind = inferLegacyKindFromBasename(basename);
|
||||
const displayName = meta.name?.trim() || basename;
|
||||
return { ok: true, data: { kind, displayName, basename } };
|
||||
} catch {
|
||||
return { ok: false, error: 'Network error while downloading theme.' };
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCatalogBase(catalogBase: string): string {
|
||||
return trimTrailingSlash(catalogBase.length > 0 ? catalogBase : DEFAULT_THEME_CATALOG_BASE);
|
||||
}
|
||||
|
||||
type Assign = 'manual' | 'light' | 'dark';
|
||||
|
||||
export async function runLegacyThemeMigration(
|
||||
settings: Settings,
|
||||
catalogBase: string
|
||||
): Promise<{ ok: true; partial: Partial<Settings> } | { ok: false; error: string }> {
|
||||
const base = normalizeCatalogBase(catalogBase);
|
||||
|
||||
const partial: Partial<Settings> = {
|
||||
themeMigrationDismissed: true,
|
||||
themeRemoteCatalogEnabled: true,
|
||||
themeCatalogOnboardingDone: true,
|
||||
};
|
||||
|
||||
const tasks: { legacyId: string; url: string; assign: Assign }[] = [];
|
||||
|
||||
if (!settings.useSystemTheme && isLegacyThemeId(settings.themeId)) {
|
||||
const id = settings.themeId!;
|
||||
tasks.push({
|
||||
legacyId: id,
|
||||
url: catalogFullUrlForBasename(legacyThemeIdToBasename(id), base),
|
||||
assign: 'manual',
|
||||
});
|
||||
}
|
||||
|
||||
if (isLegacyThemeId(settings.lightThemeId)) {
|
||||
const id = settings.lightThemeId!;
|
||||
tasks.push({
|
||||
legacyId: id,
|
||||
url: catalogFullUrlForBasename(legacyThemeIdToBasename(id), base),
|
||||
assign: 'light',
|
||||
});
|
||||
}
|
||||
|
||||
if (isLegacyThemeId(settings.darkThemeId)) {
|
||||
const id = settings.darkThemeId!;
|
||||
tasks.push({
|
||||
legacyId: id,
|
||||
url: catalogFullUrlForBasename(legacyThemeIdToBasename(id), base),
|
||||
assign: 'dark',
|
||||
});
|
||||
}
|
||||
|
||||
if (tasks.length === 0) {
|
||||
if (settings.useSystemTheme && isLegacyThemeId(settings.themeId)) {
|
||||
partial.themeId = 'light-theme';
|
||||
}
|
||||
return { ok: true, partial };
|
||||
}
|
||||
|
||||
const urlToFetched = new Map<string, FetchOk>();
|
||||
const uniqueUrls = [...new Set(tasks.map((t) => t.url))];
|
||||
|
||||
const fetchResults = await Promise.all(uniqueUrls.map((url) => fetchAndCacheTheme(url)));
|
||||
const failed = fetchResults.find((r): r is { ok: false; error: string } => !r.ok);
|
||||
if (failed) return failed;
|
||||
|
||||
uniqueUrls.forEach((url, i) => {
|
||||
const r = fetchResults[i];
|
||||
if (r.ok) urlToFetched.set(url, r.data);
|
||||
});
|
||||
|
||||
tasks.forEach((task) => {
|
||||
const data = urlToFetched.get(task.url)!;
|
||||
|
||||
if (task.assign === 'manual') {
|
||||
partial.themeRemoteManualFullUrl = task.url;
|
||||
partial.themeRemoteManualKind = data.kind;
|
||||
partial.themeId = data.kind === 'dark' ? 'dark-theme' : 'light-theme';
|
||||
} else if (task.assign === 'light') {
|
||||
partial.themeRemoteLightFullUrl = task.url;
|
||||
partial.themeRemoteLightKind = data.kind;
|
||||
partial.lightThemeId = 'light-theme';
|
||||
} else {
|
||||
partial.themeRemoteDarkFullUrl = task.url;
|
||||
partial.themeRemoteDarkKind = data.kind;
|
||||
partial.darkThemeId = 'dark-theme';
|
||||
}
|
||||
});
|
||||
|
||||
if (settings.useSystemTheme && isLegacyThemeId(settings.themeId)) {
|
||||
partial.themeId = 'light-theme';
|
||||
}
|
||||
|
||||
const existing: ThemeRemoteFavorite[] = [...(settings.themeRemoteFavorites ?? [])];
|
||||
const byUrl = new Map(existing.map((f) => [f.fullUrl, f]));
|
||||
tasks.forEach((task) => {
|
||||
const data = urlToFetched.get(task.url)!;
|
||||
if (!byUrl.has(task.url)) {
|
||||
byUrl.set(task.url, {
|
||||
fullUrl: task.url,
|
||||
displayName: data.displayName,
|
||||
basename: data.basename,
|
||||
kind: data.kind,
|
||||
pinned: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
partial.themeRemoteFavorites = [...byUrl.values()];
|
||||
|
||||
return { ok: true, partial };
|
||||
}
|
||||
Reference in new issue
Block a user