From 95acfc139daee6de1256030a161b377424dca135 Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 26 Aug 2026 17:29:53 +0930 Subject: [PATCH 1/7] feat(themes): theme layout and rearrangements --- .../components/store/ThemeCard.svelte | 19 +- .../components/store/ThemeGrid.svelte | 15 +- .../components/store/ThemeModal.svelte | 102 ++++++++-- .../components/themes/ThemeSelector.svelte | 174 +++++++++++++----- src/interface/pages/settings.svelte | 39 ++-- src/interface/pages/settings/theme.svelte | 6 +- src/interface/pages/store.svelte | 16 ++ src/interface/utils/themeListFilters.test.ts | 68 +++++++ src/interface/utils/themeListFilters.ts | 16 ++ src/seqta/utils/settingsNavigation.ts | 2 +- 10 files changed, 356 insertions(+), 101 deletions(-) create mode 100644 src/interface/utils/themeListFilters.test.ts create mode 100644 src/interface/utils/themeListFilters.ts diff --git a/src/interface/components/store/ThemeCard.svelte b/src/interface/components/store/ThemeCard.svelte index bae0d58d..37b0ab3f 100644 --- a/src/interface/components/store/ThemeCard.svelte +++ b/src/interface/components/store/ThemeCard.svelte @@ -4,9 +4,10 @@ masterGridDisplayDownloadCount, gridCardPreviewImageUrls, } from '@/interface/utils/themeStoreFlavours' + import { isStoreThemeInstalled } from '@/interface/utils/themeListFilters' import emblaCarouselSvelte from 'embla-carousel-svelte'; import Autoplay from 'embla-carousel-autoplay'; - let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows } = $props<{ + let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows, installedThemeIds = [] } = $props<{ theme: Theme; onClick: () => void; toggleFavorite: (theme: Theme) => void; @@ -14,6 +15,7 @@ onRequestSignIn?: () => void; /** Raw API themes (includes hidden slaves) for aggregated master download totals */ allStoreThemeRows?: Theme[]; + installedThemeIds?: string[]; }>(); const displayDownloadCount = $derived( @@ -47,6 +49,8 @@ ]; }); + const isInstalled = $derived(isStoreThemeInstalled(theme, installedThemeIds)); + function handleCardClick(e: MouseEvent) { if ((e.target as HTMLElement).closest('[data-theme-favorite]')) return; onClick(); @@ -85,6 +89,19 @@ {/if} + {#if isInstalled} +
+ + + + + Installed + +
+ {/if} +{/if} + + + + {:else} +{/if} + + + + {:else} +{:else} + +{/if} - - + {#if listMode === 'custom'} +

+ No custom themes yet +

+

+ Create your own theme or follow our guide to get started. +

+
+ +
+ {:else if listMode === 'downloaded'} +

+ No downloaded themes +

+

+ Browse the theme store to find and install themes. +

+
+ +
+ {:else} +

+ No themes installed +

+

+ Install a theme from the store or create one of your own. +

+
+ + +
+ {/if} {/if} - {#if showNavigation && themes && themes.themes.length > 0} + {#if themes && ((showNavigation && visibleThemes.length > 0) || (listMode === 'custom' && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
- + {#if listMode === 'custom'} + - + +
+
{'\uecb3'}
+
+ Got a Theme Idea? +

Transform it into a stunning theme!

+
+
+
+ {:else if listMode === 'downloaded'} + + {:else} + + + + {/if} {/if} diff --git a/src/interface/pages/settings.svelte b/src/interface/pages/settings.svelte index 103709a3..6045e8b3 100644 --- a/src/interface/pages/settings.svelte +++ b/src/interface/pages/settings.svelte @@ -39,7 +39,7 @@ } from "@/utils/githubReleaseUpdate"; type PageId = "settings" | "themes" | "backgrounds"; type StoreTab = "themes" | "backgrounds"; - type ThemeView = "theme-settings" | "theme-store"; + type ThemeView = "theme-settings" | "theme-store" | "create-theme"; type BackgroundView = "background-settings" | "background-store"; type NavItem = { @@ -94,8 +94,8 @@ label: "Themes", items: [ { id: "theme-store", label: "Store" }, - { id: "theme-settings", label: "Theme settings" }, - { id: "create-theme", label: "Create theme" }, + { id: "theme-settings", label: "Downloaded themes" }, + { id: "create-theme", label: "Custom themes" }, ], }, ]; @@ -142,11 +142,21 @@ ); const sectionTitle = $derived.by(() => { - if (activePage === "themes") return "Themes"; + if (activePage === "themes") { + if (activeThemeView === "theme-settings") return "Downloaded themes"; + if (activeThemeView === "create-theme") return "Custom themes"; + return "Themes"; + } if (activePage === "backgrounds") return "Backgrounds"; return [...userNav, ...appNav].find((item) => item.id === activeSection)?.label ?? "Settings"; }); + const activeThemeListMode = $derived.by(() => { + if (activeThemeView === "create-theme") return "custom" as const; + if (activeThemeView === "theme-settings") return "downloaded" as const; + return "all" as const; + }); + const isStoreView = $derived( (activePage === "themes" && activeThemeView === "theme-store") || (activePage === "backgrounds" && activeBackgroundView === "background-store"), @@ -256,11 +266,7 @@ } if (activePage === "themes") { - if (id === "create-theme") { - void openThemeCreator(); - } else { - activeThemeView = id as ThemeView; - } + activeThemeView = id as ThemeView; return; } @@ -272,18 +278,17 @@ } }; - const openThemeCreator = async () => { - const { OpenThemeCreator } = await import("@/plugins/built-in/themes/ThemeCreator"); - OpenThemeCreator(); - closeExtensionPopup(); - }; - const applyDestination = (destination: SettingsDestination) => { activePage = destination.page; if (destination.page === "settings" && destination.section) { activeSection = destination.section; } else if (destination.page === "themes" && destination.view) { - activeThemeView = destination.view === "store" ? "theme-store" : "theme-settings"; + activeThemeView = + destination.view === "store" + ? "theme-store" + : destination.view === "custom" + ? "create-theme" + : "theme-settings"; } else if (destination.page === "backgrounds" && destination.view) { activeBackgroundView = destination.view === "store" ? "background-store" : "background-settings"; } @@ -467,7 +472,7 @@ /> {/if} {:else if activePage === "themes"} - + {:else} {/if} diff --git a/src/interface/pages/settings/theme.svelte b/src/interface/pages/settings/theme.svelte index 74be1d73..fc54f727 100644 --- a/src/interface/pages/settings/theme.svelte +++ b/src/interface/pages/settings/theme.svelte @@ -2,9 +2,11 @@ import BackgroundSelector from "@/interface/components/themes/BackgroundSelector.svelte" import ThemeSelector from "@/interface/components/themes/ThemeSelector.svelte" import { standalone } from "@/interface/utils/standalone.svelte" + import type { ThemeListMode } from "@/interface/utils/themeListFilters" - let { section = "all" } = $props<{ + let { section = "all", listMode = "all" } = $props<{ section?: "all" | "themes" | "backgrounds"; + listMode?: ThemeListMode; }>(); // backgrounds @@ -41,7 +43,7 @@ {/if} {#if showThemes} - + {/if} {:else} diff --git a/src/interface/pages/store.svelte b/src/interface/pages/store.svelte index 6713d253..3c2531b0 100644 --- a/src/interface/pages/store.svelte +++ b/src/interface/pages/store.svelte @@ -53,6 +53,7 @@ let loading = $state(true); let displayTheme = $state(null); let currentThemes = $state([]); + let selectedThemeId = $state(''); let error = $state(null); let fetchAttempt = $state(0); @@ -74,6 +75,7 @@ const fetchCurrentThemes = async () => { const themes = await themeManager.getAvailableThemes(); currentThemes = themes.filter(theme => theme !== null).map(theme => theme.id); + selectedThemeId = themeManager.getSelectedThemeId() || ''; }; const setDisplayTheme = (theme: Theme | null) => { @@ -174,6 +176,7 @@ // On mount onMount(async () => { window.addEventListener('bsplus:highlight-theme', onHighlightThemeEvent); + themeUpdates.addListener(fetchCurrentThemes); await fetchThemes(); await fetchCurrentThemes(); @@ -183,6 +186,7 @@ return () => { window.removeEventListener('bsplus:highlight-theme', onHighlightThemeEvent); + themeUpdates.removeListener(fetchCurrentThemes); }; }); @@ -219,6 +223,13 @@ await fetchCurrentThemes(); } + async function applyThemeFromStore(themeId: string) { + await themeManager.setTheme(themeId); + selectedThemeId = themeId; + themeUpdates.triggerUpdate(); + void browser.runtime.sendMessage({ type: 'cloudSettingsRequestDebouncedUpload' }).catch(() => {}); + } + $effect(() => { loadBackground(); selectedBackground @@ -287,6 +298,7 @@ {toggleFavorite} isLoggedIn={cloudLoggedIn} onRequestSignIn={() => (showSignInOverlay = true)} + installedThemeIds={currentThemes} /> {#if displayTheme} @@ -300,6 +312,7 @@ {toggleFavorite} isLoggedIn={cloudLoggedIn} onRequestSignIn={() => (showSignInOverlay = true)} + {selectedThemeId} onInstall={async (themeId: string) => { if (displayTheme) await installThemeFromStore(themeId, displayTheme); }} @@ -307,6 +320,9 @@ console.debug('deleting theme', themeId); await removeThemeFromStore(themeId); }} + onApply={async (themeId: string) => { + await applyThemeFromStore(themeId); + }} /> {/if} {:else if activeTab === 'backgrounds'} diff --git a/src/interface/utils/themeListFilters.test.ts b/src/interface/utils/themeListFilters.test.ts new file mode 100644 index 00000000..1167b79d --- /dev/null +++ b/src/interface/utils/themeListFilters.test.ts @@ -0,0 +1,68 @@ +import type { CustomTheme } from '@/types/CustomThemes'; +import type { Theme } from '@/interface/types/Theme'; +import { filterThemesByMode, isStoreThemeInstalled } from './themeListFilters'; + +function makeCustomTheme(overrides: Partial & Pick): CustomTheme { + return { + description: '', + defaultColour: '#000000', + CanChangeColour: true, + allowBackgrounds: true, + CustomCSS: '', + CustomImages: [], + coverImage: null, + isEditable: false, + hideThemeName: false, + ...overrides, + }; +} + +function makeStoreTheme(overrides: Partial & Pick): Theme { + return { + description: '', + coverImage: '', + ...overrides, + }; +} + +describe('filterThemesByMode', () => { + const downloaded = makeCustomTheme({ id: 'store-1', name: 'Store Theme', isEditable: false }); + const custom = makeCustomTheme({ id: 'custom-1', name: 'Custom Theme', isEditable: true }); + + it('returns all themes in all mode', () => { + expect(filterThemesByMode([downloaded, custom], 'all')).toEqual([downloaded, custom]); + }); + + it('returns only non-editable themes in downloaded mode', () => { + expect(filterThemesByMode([downloaded, custom], 'downloaded')).toEqual([downloaded]); + }); + + it('returns only editable themes in custom mode', () => { + expect(filterThemesByMode([downloaded, custom], 'custom')).toEqual([custom]); + }); +}); + +describe('isStoreThemeInstalled', () => { + it('returns true when master id is installed', () => { + const theme = makeStoreTheme({ id: 'master-1', name: 'Master' }); + expect(isStoreThemeInstalled(theme, ['master-1'])).toBe(true); + }); + + it('returns true when a flavour id is installed', () => { + const theme = makeStoreTheme({ + id: 'master-1', + name: 'Master', + flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#000', cover_image: '' }], + }); + expect(isStoreThemeInstalled(theme, ['flavour-1'])).toBe(true); + }); + + it('returns false when neither master nor flavours are installed', () => { + const theme = makeStoreTheme({ + id: 'master-1', + name: 'Master', + flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#000', cover_image: '' }], + }); + expect(isStoreThemeInstalled(theme, ['other-theme'])).toBe(false); + }); +}); diff --git a/src/interface/utils/themeListFilters.ts b/src/interface/utils/themeListFilters.ts new file mode 100644 index 00000000..1ff72799 --- /dev/null +++ b/src/interface/utils/themeListFilters.ts @@ -0,0 +1,16 @@ +import type { CustomTheme } from '@/types/CustomThemes'; +import type { Theme } from '@/interface/types/Theme'; + +export type ThemeListMode = 'downloaded' | 'custom' | 'all'; + +export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): CustomTheme[] { + if (mode === 'all') return themes; + if (mode === 'custom') return themes.filter((theme) => theme.isEditable === true); + return themes.filter((theme) => theme.isEditable !== true); +} + +export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean { + const installed = new Set(installedIds); + if (installed.has(theme.id)) return true; + return (theme.flavours ?? []).some((flavour) => installed.has(flavour.id)); +} diff --git a/src/seqta/utils/settingsNavigation.ts b/src/seqta/utils/settingsNavigation.ts index 8290d9ab..9094bd09 100644 --- a/src/seqta/utils/settingsNavigation.ts +++ b/src/seqta/utils/settingsNavigation.ts @@ -1,6 +1,6 @@ export type SettingsDestination = | { page: "settings"; section?: string } - | { page: "themes" | "backgrounds"; view?: "settings" | "store" }; + | { page: "themes" | "backgrounds"; view?: "settings" | "store" | "custom" }; export const SETTINGS_NAVIGATION_EVENT = "bsplus:navigate-settings"; From 1ce95f64e9ac2905b18a241d7c816b2928a8f2ab Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 26 Aug 2026 18:01:16 +0930 Subject: [PATCH 2/7] feat(themes): various UI/UX tweaks --- .../components/SkeletonLoader.svelte | 7 +++- src/interface/components/store/Header.svelte | 2 +- .../components/store/ThemeModal.svelte | 42 +++++++++++++------ .../components/themes/ThemeSelector.svelte | 32 +++++++------- src/interface/pages/settings/theme.svelte | 18 ++++---- src/interface/pages/store.svelte | 5 +++ src/interface/utils/themeListFilters.test.ts | 40 +++++++++++++++++- src/interface/utils/themeListFilters.ts | 37 ++++++++++++++++ src/test/mocks/color.ts | 21 ++++++++-- 9 files changed, 163 insertions(+), 41 deletions(-) diff --git a/src/interface/components/SkeletonLoader.svelte b/src/interface/components/SkeletonLoader.svelte index 17e23ade..ffe8cf51 100644 --- a/src/interface/components/SkeletonLoader.svelte +++ b/src/interface/components/SkeletonLoader.svelte @@ -1,5 +1,8 @@ -
+
diff --git a/src/interface/components/store/Header.svelte b/src/interface/components/store/Header.svelte index f0ec96ab..f8648f6b 100644 --- a/src/interface/components/store/Header.svelte +++ b/src/interface/components/store/Header.svelte @@ -71,7 +71,7 @@ role="tab" aria-selected={activePage === tab.id} onclick={() => setActivePage(tab.id)} - class="relative z-10 h-10 flex-1 whitespace-nowrap rounded-full px-4 text-base transition-colors duration-200 + class="relative z-10 h-10 flex-1 whitespace-nowrap rounded-full px-4 text-lg transition-colors duration-200 {activePage === tab.id ? 'font-semibold text-zinc-900 dark:text-white' : 'text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-white'}" diff --git a/src/interface/components/store/ThemeModal.svelte b/src/interface/components/store/ThemeModal.svelte index 838bdd20..c89e0414 100644 --- a/src/interface/components/store/ThemeModal.svelte +++ b/src/interface/components/store/ThemeModal.svelte @@ -9,6 +9,10 @@ flavourCarouselImageUrl, masterCarouselImageUrl, masterGridDisplayDownloadCount, } from '@/interface/utils/themeStoreFlavours' +import { +getThemeApplyButtonStyles, +resolveStoreVariantAccentColor, +} from '@/interface/utils/themeListFilters' let { theme, currentThemes, @@ -23,6 +27,7 @@ toggleFavorite, isLoggedIn, onRequestSignIn, selectedThemeId = '', +installedThemeColors = {}, } = $props<{ theme: Theme | null currentThemes: string[] @@ -38,7 +43,16 @@ toggleFavorite?: (theme: Theme) => void isLoggedIn?: boolean onRequestSignIn?: () => void selectedThemeId?: string +installedThemeColors?: Record }>() +function variantApplyStyles(variantId: string) { +if (!theme) { +return getThemeApplyButtonStyles(undefined) +} +return getThemeApplyButtonStyles( +resolveStoreVariantAccentColor(theme, variantId, installedThemeColors), +) +} const modalDisplayDownloadCount = $derived.by(() => { const t = theme if (!t) return 0 @@ -110,7 +124,7 @@ $effect(() => { if (displayTheme && modalElement) { animate( modalElement, -{ y: [500, 0], opacity: [0, 1] }, +{ y: [16, 0], opacity: [0, 1], scale: [0.98, 1] }, { type: 'spring', stiffness: 150, @@ -122,7 +136,7 @@ damping: 20, const hideModal = (relatedTheme = null) => { animate( modalElement, -{ y: [10, 500], opacity: [1, 0] }, +{ y: [0, 16], opacity: [1, 0], scale: [1, 0.98] }, { type: 'spring', stiffness: 150, @@ -170,7 +184,7 @@ else await runRemove(theme.id) }
{ if (e.target === e.currentTarget) hideModal() }} @@ -183,7 +197,7 @@ transition:fade
e.stopPropagation()} onkeydown={(e) => e.stopPropagation()} role="dialog" @@ -191,7 +205,7 @@ aria-modal="true" tabindex="-1" > {#if theme} -
+
@@ -383,7 +398,8 @@ class="relative w-full overflow-hidden rounded-2xl min-h-[9.5rem] sm:min-h-[11re type="button" onclick={(e) => { e.stopPropagation(); scrollHeroToFlavourIndex(flavourIdx); void runApply(f.id) }} disabled={installingId !== null} -class="px-3 py-1.5 text-sm font-semibold rounded-lg bg-emerald-500 text-white hover:bg-emerald-600 disabled:opacity-70" +style={variantApplyStyles(f.id).apply} +class="px-3 py-1.5 text-sm font-semibold rounded-lg hover:brightness-90 disabled:opacity-70" > Apply @@ -450,7 +466,8 @@ aria-label={theme.is_favorited ? 'Unfavorite' : 'Favorite'} @@ -459,7 +476,8 @@ Applied type="button" onclick={() => runApply(theme.id)} disabled={installingId !== null} -class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] text-white rounded-lg bg-emerald-600 hover:bg-emerald-700 transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 disabled:opacity-70" +style={variantApplyStyles(theme.id).apply} +class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] rounded-lg transition-all duration-200 hover:brightness-90 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-70" > {#if installingId === theme.id} @@ -500,11 +518,11 @@ class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] text-bla {/if}
{#if relatedThemes.length > 0} -
+

Related themes

-
+
{#each relatedThemes as relatedTheme (relatedTheme.id)}
-
+
{#if themes} {#each visibleThemes as theme (theme.id)} - -
-
{'\uecb3'}
-
- Got a Theme Idea? -

Transform it into a stunning theme!

-
-
+
+ {'\uecb3'} + View theme creation docs {:else if listMode === 'downloaded'} {/if} -
- +
+ {#if showThemes || showBackgrounds} +
+ +
+ {/if} {#if showBackgrounds} diff --git a/src/interface/pages/store.svelte b/src/interface/pages/store.svelte index 3c2531b0..5df465ca 100644 --- a/src/interface/pages/store.svelte +++ b/src/interface/pages/store.svelte @@ -54,6 +54,7 @@ let displayTheme = $state(null); let currentThemes = $state([]); let selectedThemeId = $state(''); + let installedThemeColors = $state>({}); let error = $state(null); let fetchAttempt = $state(0); @@ -76,6 +77,9 @@ const themes = await themeManager.getAvailableThemes(); currentThemes = themes.filter(theme => theme !== null).map(theme => theme.id); selectedThemeId = themeManager.getSelectedThemeId() || ''; + installedThemeColors = Object.fromEntries( + themes.filter((theme) => theme != null).map((theme) => [theme.id, theme.defaultColour]), + ); }; const setDisplayTheme = (theme: Theme | null) => { @@ -313,6 +317,7 @@ isLoggedIn={cloudLoggedIn} onRequestSignIn={() => (showSignInOverlay = true)} {selectedThemeId} + {installedThemeColors} onInstall={async (themeId: string) => { if (displayTheme) await installThemeFromStore(themeId, displayTheme); }} diff --git a/src/interface/utils/themeListFilters.test.ts b/src/interface/utils/themeListFilters.test.ts index 1167b79d..7cd6b603 100644 --- a/src/interface/utils/themeListFilters.test.ts +++ b/src/interface/utils/themeListFilters.test.ts @@ -1,6 +1,11 @@ import type { CustomTheme } from '@/types/CustomThemes'; import type { Theme } from '@/interface/types/Theme'; -import { filterThemesByMode, isStoreThemeInstalled } from './themeListFilters'; +import { + filterThemesByMode, + getThemeApplyButtonStyles, + isStoreThemeInstalled, + resolveStoreVariantAccentColor, +} from './themeListFilters'; function makeCustomTheme(overrides: Partial & Pick): CustomTheme { return { @@ -66,3 +71,36 @@ describe('isStoreThemeInstalled', () => { expect(isStoreThemeInstalled(theme, ['other-theme'])).toBe(false); }); }); + +describe('resolveStoreVariantAccentColor', () => { + it('prefers installed theme colour for the variant id', () => { + const theme = makeStoreTheme({ + id: 'master-1', + name: 'Master', + flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#111111', cover_image: '' }], + }); + expect(resolveStoreVariantAccentColor(theme, 'flavour-1', { 'flavour-1': '#ff0000' })).toBe('#ff0000'); + }); + + it('falls back to flavour accent when not installed locally', () => { + const theme = makeStoreTheme({ + id: 'master-1', + name: 'Master', + flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#112233', cover_image: '' }], + }); + expect(resolveStoreVariantAccentColor(theme, 'flavour-1')).toBe('#112233'); + }); +}); + +describe('getThemeApplyButtonStyles', () => { + it('uses the theme accent as the apply button background', () => { + const styles = getThemeApplyButtonStyles('#ff0000'); + expect(styles.apply).toContain('background-color: #FF0000'); + }); + + it('uses a muted version of the accent for the applied state', () => { + const styles = getThemeApplyButtonStyles('#ff0000'); + expect(styles.applied).toContain('background-color:'); + expect(styles.applied).toContain('color: #FF0000'); + }); +}); diff --git a/src/interface/utils/themeListFilters.ts b/src/interface/utils/themeListFilters.ts index 1ff72799..41e54e10 100644 --- a/src/interface/utils/themeListFilters.ts +++ b/src/interface/utils/themeListFilters.ts @@ -1,8 +1,11 @@ import type { CustomTheme } from '@/types/CustomThemes'; import type { Theme } from '@/interface/types/Theme'; +import { parseCssColor } from '@/seqta/ui/colors/parseCssColor'; export type ThemeListMode = 'downloaded' | 'custom' | 'all'; +const DEFAULT_THEME_ACCENT = 'rgba(0, 123, 255, 1)'; + export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): CustomTheme[] { if (mode === 'all') return themes; if (mode === 'custom') return themes.filter((theme) => theme.isEditable === true); @@ -14,3 +17,37 @@ export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boo if (installed.has(theme.id)) return true; return (theme.flavours ?? []).some((flavour) => installed.has(flavour.id)); } + +export function resolveStoreVariantAccentColor( + theme: Theme, + variantId: string, + installedThemeColors: Record = {}, +): string { + const installed = installedThemeColors[variantId]?.trim(); + if (installed) return installed; + + const flavour = theme.flavours?.find((entry) => entry.id === variantId); + if (flavour?.accent_color?.trim()) return flavour.accent_color.trim(); + + if (variantId === theme.id) { + const firstFlavourAccent = theme.flavours?.find((entry) => entry.accent_color?.trim())?.accent_color?.trim(); + if (firstFlavourAccent) return firstFlavourAccent; + } + + return DEFAULT_THEME_ACCENT; +} + +export type ThemeApplyButtonStyles = { + apply: string; + applied: string; +}; + +export function getThemeApplyButtonStyles(accentColor: string | undefined): ThemeApplyButtonStyles { + const parsed = parseCssColor(accentColor?.trim() || DEFAULT_THEME_ACCENT, DEFAULT_THEME_ACCENT); + const onAccent = parsed.lightness() >= 60 ? '#18181b' : '#ffffff'; + + return { + apply: `background-color: ${parsed.hex()}; color: ${onAccent};`, + applied: `background-color: ${parsed.alpha(0.18).string()}; color: ${parsed.hex()};`, + }; +} diff --git a/src/test/mocks/color.ts b/src/test/mocks/color.ts index 585602a5..e0b8c121 100644 --- a/src/test/mocks/color.ts +++ b/src/test/mocks/color.ts @@ -18,13 +18,28 @@ function toHexByte(value: number): string { } function createColor(channels: ColorChannels) { + const hex = () => + `#${toHexByte(channels.r)}${toHexByte(channels.g)}${toHexByte(channels.b)}`.toUpperCase(); + const color = { red: () => clampByte(channels.r), green: () => clampByte(channels.g), blue: () => clampByte(channels.b), - alpha: () => clampAlpha(channels.a), - hex: () => - `#${toHexByte(channels.r)}${toHexByte(channels.g)}${toHexByte(channels.b)}`, + hex, + lightness: () => { + const r = channels.r / 255; + const g = channels.g / 255; + const b = channels.b / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + return ((max + min) / 2) * 100; + }, + string: () => { + if (channels.a < 1) { + return `rgba(${clampByte(channels.r)}, ${clampByte(channels.g)}, ${clampByte(channels.b)}, ${clampAlpha(channels.a)})`; + } + return hex(); + }, }; return { From d980c01c810457d76838b6b77e9228e712e79b4b Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 26 Aug 2026 20:41:51 +0930 Subject: [PATCH 3/7] add custom user themes! --- src/background.ts | 8 + src/background/customThemesHandlers.ts | 287 +++++++ .../components/store/ThemeCard.svelte | 23 +- .../components/store/ThemeGrid.svelte | 3 + .../components/store/ThemeModal.svelte | 16 +- .../components/themes/ThemeSelector.svelte | 58 +- src/interface/pages/communityThemes.svelte | 806 ++++++++++++++++++ src/interface/pages/settings.svelte | 53 +- src/plugins/built-in/themes/theme-manager.ts | 54 ++ .../buildThemeUploadFormData.test.ts | 18 + .../customThemes/buildThemeUploadFormData.ts | 110 +++ src/seqta/utils/customThemes/client.test.ts | 37 + src/seqta/utils/customThemes/client.ts | 193 +++++ src/seqta/utils/customThemes/constants.ts | 12 + .../customThemes/formatThemeDate.test.ts | 14 + .../utils/customThemes/formatThemeDate.ts | 5 + .../customThemes/normalizeCustomTheme.test.ts | 37 + .../customThemes/normalizeCustomTheme.ts | 80 ++ .../utils/customThemes/parseApiEnvelope.ts | 21 + src/seqta/utils/customThemes/types.ts | 68 ++ .../utils/openCommunityThemeSubmit.test.ts | 27 + src/seqta/utils/openCommunityThemeSubmit.ts | 45 + src/seqta/utils/settingsNavigation.ts | 2 +- src/types/CustomThemes.ts | 2 + thedocsiwastalkingabout/custom-themes-api.md | 554 ++++++++++++ .../custom-themes-client-integration.md | 383 +++++++++ 26 files changed, 2876 insertions(+), 40 deletions(-) create mode 100644 src/background/customThemesHandlers.ts create mode 100644 src/interface/pages/communityThemes.svelte create mode 100644 src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts create mode 100644 src/seqta/utils/customThemes/buildThemeUploadFormData.ts create mode 100644 src/seqta/utils/customThemes/client.test.ts create mode 100644 src/seqta/utils/customThemes/client.ts create mode 100644 src/seqta/utils/customThemes/constants.ts create mode 100644 src/seqta/utils/customThemes/formatThemeDate.test.ts create mode 100644 src/seqta/utils/customThemes/formatThemeDate.ts create mode 100644 src/seqta/utils/customThemes/normalizeCustomTheme.test.ts create mode 100644 src/seqta/utils/customThemes/normalizeCustomTheme.ts create mode 100644 src/seqta/utils/customThemes/parseApiEnvelope.ts create mode 100644 src/seqta/utils/customThemes/types.ts create mode 100644 src/seqta/utils/openCommunityThemeSubmit.test.ts create mode 100644 src/seqta/utils/openCommunityThemeSubmit.ts create mode 100644 thedocsiwastalkingabout/custom-themes-api.md create mode 100644 thedocsiwastalkingabout/custom-themes-client-integration.md diff --git a/src/background.ts b/src/background.ts index e4110da5..fd2863fe 100644 --- a/src/background.ts +++ b/src/background.ts @@ -19,6 +19,7 @@ import { registerGoogleCalendarMessageHandlers, registerOutlookCalendarMessageHandlers, } from "./background/calendarBackground"; +import { createCustomThemesHandlers } from "./background/customThemesHandlers"; /** * Session-only dev-mode override of the content API base. @@ -478,7 +479,14 @@ function handleSetDevApiBase( return false; } +const customThemesHandlers = createCustomThemesHandlers({ + apiBase, + getAccessTokenFromStorage, + parseJsonResponse, +}); + const MESSAGE_HANDLERS: Record = { + ...customThemesHandlers, reloadTabs: () => reloadSeqtaPages(), setDevApiBase: handleSetDevApiBase, extensionPages: (req) => { diff --git a/src/background/customThemesHandlers.ts b/src/background/customThemesHandlers.ts new file mode 100644 index 00000000..12200d30 --- /dev/null +++ b/src/background/customThemesHandlers.ts @@ -0,0 +1,287 @@ +type MessageSender = { (response?: unknown): void }; + +type UploadFilePart = { + fieldName: string; + filename: string; + mimeType: string; + dataBase64: string; +}; + +type UploadPayload = { + themeZip?: UploadFilePart; + looseFiles?: UploadFilePart[]; + submissionNotes?: string; +}; + +function base64ToBlob(base64: string, mimeType: string): Blob { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return new Blob([bytes], { type: mimeType }); +} + +function buildFormDataFromPayload(payload: UploadPayload): FormData { + const form = new FormData(); + if (payload.themeZip) { + const part = payload.themeZip; + form.append( + part.fieldName, + base64ToBlob(part.dataBase64, part.mimeType), + part.filename, + ); + } + for (const part of payload.looseFiles ?? []) { + form.append( + part.fieldName, + base64ToBlob(part.dataBase64, part.mimeType), + part.filename, + ); + } + if (payload.submissionNotes?.trim()) { + form.append("submission_notes", payload.submissionNotes.trim()); + } + return form; +} + +export function createCustomThemesHandlers(deps: { + apiBase: () => string; + getAccessTokenFromStorage: () => Promise; + parseJsonResponse: (r: Response) => Promise; +}): Record boolean> { + async function customThemesJsonFetch( + path: string, + init: RequestInit = {}, + requireAuth = false, + ): Promise> { + const headers: Record = { + Accept: "application/json", + ...(init.headers as Record | undefined), + }; + if (requireAuth) { + const token = await deps.getAccessTokenFromStorage(); + if (!token) { + return { success: false, error: "Not authenticated", httpStatus: 401 }; + } + headers.Authorization = `Bearer ${token}`; + } + const r = await fetch(`${deps.apiBase()}${path}`, { + ...init, + headers, + cache: "no-store", + }); + const json = await deps.parseJsonResponse(r); + if (json && typeof json === "object") { + return { ...json, httpStatus: r.status }; + } + return { success: false, error: `HTTP ${r.status}`, httpStatus: r.status }; + } + + async function customThemesMultipartPost( + path: string, + payload: UploadPayload, + ): Promise> { + const token = await deps.getAccessTokenFromStorage(); + if (!token) { + return { success: false, error: "Not authenticated", httpStatus: 401 }; + } + const form = buildFormDataFromPayload(payload); + const r = await fetch(`${deps.apiBase()}${path}`, { + method: "POST", + headers: { Authorization: `Bearer ${token}` }, + body: form, + cache: "no-store", + }); + const json = await deps.parseJsonResponse(r); + if (json && typeof json === "object") { + return { ...json, httpStatus: r.status }; + } + return { success: false, error: `HTTP ${r.status}`, httpStatus: r.status }; + } + + function handleFetchCustomThemes(request: any, sendResponse: MessageSender): boolean { + void (async () => { + try { + const params = new URLSearchParams(); + params.set("type", "betterseqta"); + params.set("page", String(request.page ?? 1)); + params.set("limit", String(request.limit ?? 20)); + if (request.sort) params.set("sort", String(request.sort)); + const search = request.search?.trim(); + const path = search + ? `/api/custom-themes/search?${params}&q=${encodeURIComponent(search)}` + : `/api/custom-themes?${params}`; + sendResponse(await customThemesJsonFetch(path)); + } catch (err) { + console.error("[Background] fetchCustomThemes error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Fetch failed", + }); + } + })(); + return true; + } + + function handleFetchMyCustomThemes(request: any, sendResponse: MessageSender): boolean { + void (async () => { + try { + const params = new URLSearchParams(); + params.set("page", String(request.page ?? 1)); + params.set("limit", String(request.limit ?? 20)); + params.set("type", "betterseqta"); + if (request.status) params.set("status", String(request.status)); + sendResponse( + await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true), + ); + } catch (err) { + console.error("[Background] fetchMyCustomThemes error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Fetch failed", + }); + } + })(); + return true; + } + + function handleFetchMyCustomThemeDetail(request: any, sendResponse: MessageSender): boolean { + const { themeId } = request; + if (!themeId || typeof themeId !== "string") { + sendResponse({ success: false, error: "Missing themeId" }); + return false; + } + void (async () => { + try { + sendResponse( + await customThemesJsonFetch( + `/api/custom-themes/mine/${encodeURIComponent(themeId)}`, + {}, + true, + ), + ); + } catch (err) { + console.error("[Background] fetchMyCustomThemeDetail error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Fetch failed", + }); + } + })(); + return true; + } + + function handleSubmitCustomTheme(request: any, sendResponse: MessageSender): boolean { + const payload = request.payload as UploadPayload | undefined; + if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) { + sendResponse({ success: false, error: "Missing upload files" }); + return false; + } + void (async () => { + try { + sendResponse(await customThemesMultipartPost("/api/custom-themes/mine", payload!)); + } catch (err) { + console.error("[Background] submitCustomTheme error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Upload failed", + }); + } + })(); + return true; + } + + function handleReplaceCustomThemeFiles(request: any, sendResponse: MessageSender): boolean { + const { themeId, payload } = request; + if (!themeId || typeof themeId !== "string") { + sendResponse({ success: false, error: "Missing themeId" }); + return false; + } + if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) { + sendResponse({ success: false, error: "Missing upload files" }); + return false; + } + void (async () => { + try { + sendResponse( + await customThemesMultipartPost( + `/api/custom-themes/mine/${encodeURIComponent(themeId)}/files`, + payload, + ), + ); + } catch (err) { + console.error("[Background] replaceCustomThemeFiles error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Upload failed", + }); + } + })(); + return true; + } + + function handleUpdateCustomThemeMetadata(request: any, sendResponse: MessageSender): boolean { + const { themeId, body } = request; + if (!themeId || typeof themeId !== "string") { + sendResponse({ success: false, error: "Missing themeId" }); + return false; + } + void (async () => { + try { + sendResponse( + await customThemesJsonFetch( + `/api/custom-themes/mine/${encodeURIComponent(themeId)}`, + { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body ?? {}), + }, + true, + ), + ); + } catch (err) { + console.error("[Background] updateCustomThemeMetadata error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Update failed", + }); + } + })(); + return true; + } + + function handleDeleteCustomTheme(request: any, sendResponse: MessageSender): boolean { + const { themeId } = request; + if (!themeId || typeof themeId !== "string") { + sendResponse({ success: false, error: "Missing themeId" }); + return false; + } + void (async () => { + try { + sendResponse( + await customThemesJsonFetch( + `/api/custom-themes/mine/${encodeURIComponent(themeId)}`, + { method: "DELETE" }, + true, + ), + ); + } catch (err) { + console.error("[Background] deleteCustomTheme error:", err); + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Delete failed", + }); + } + })(); + return true; + } + + return { + fetchCustomThemes: handleFetchCustomThemes, + fetchMyCustomThemes: handleFetchMyCustomThemes, + fetchMyCustomThemeDetail: handleFetchMyCustomThemeDetail, + submitCustomTheme: handleSubmitCustomTheme, + replaceCustomThemeFiles: handleReplaceCustomThemeFiles, + updateCustomThemeMetadata: handleUpdateCustomThemeMetadata, + deleteCustomTheme: handleDeleteCustomTheme, + }; +} diff --git a/src/interface/components/store/ThemeCard.svelte b/src/interface/components/store/ThemeCard.svelte index 37b0ab3f..49c017e2 100644 --- a/src/interface/components/store/ThemeCard.svelte +++ b/src/interface/components/store/ThemeCard.svelte @@ -7,7 +7,7 @@ import { isStoreThemeInstalled } from '@/interface/utils/themeListFilters' import emblaCarouselSvelte from 'embla-carousel-svelte'; import Autoplay from 'embla-carousel-autoplay'; - let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows, installedThemeIds = [] } = $props<{ + let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows, installedThemeIds = [], variant = 'official' } = $props<{ theme: Theme; onClick: () => void; toggleFavorite: (theme: Theme) => void; @@ -16,6 +16,7 @@ /** Raw API themes (includes hidden slaves) for aggregated master download totals */ allStoreThemeRows?: Theme[]; installedThemeIds?: string[]; + variant?: 'official' | 'community'; }>(); const displayDownloadCount = $derived( @@ -50,6 +51,8 @@ }); const isInstalled = $derived(isStoreThemeInstalled(theme, installedThemeIds)); + const isCommunity = $derived(variant === 'community'); + const showFavorites = $derived(!isCommunity); function handleCardClick(e: MouseEvent) { if ((e.target as HTMLElement).closest('[data-theme-favorite]')) return; @@ -76,8 +79,18 @@
- {#if theme.featured === true} + {#if isCommunity}
+ + Community + +
+ {/if} + {#if theme.featured === true} +
{/if} {#if isInstalled} -
+
{/if} + {#if showFavorites} + {/if}
{theme.name} {#if theme.author} @@ -142,12 +157,14 @@ {displayDownloadCount.toLocaleString()} + {#if showFavorites} {(theme.favorite_count ?? 0).toLocaleString()} + {/if}
{#if gridRotatorUrls.length === 0} diff --git a/src/interface/components/store/ThemeGrid.svelte b/src/interface/components/store/ThemeGrid.svelte index ced5ec25..180e8ef9 100644 --- a/src/interface/components/store/ThemeGrid.svelte +++ b/src/interface/components/store/ThemeGrid.svelte @@ -11,6 +11,7 @@ onRequestSignIn, allStoreThemeRows, installedThemeIds = [], + variant = 'official', } = $props<{ themes: Theme[]; searchTerm: string; @@ -21,6 +22,7 @@ /** Raw API list (includes `slave` rows) for master download aggregation */ allStoreThemeRows?: Theme[]; installedThemeIds?: string[]; + variant?: 'official' | 'community'; }>(); let filteredThemes = $derived(themes.filter((theme: Theme) => { @@ -42,6 +44,7 @@ {onRequestSignIn} {allStoreThemeRows} {installedThemeIds} + {variant} /> {/each} diff --git a/src/interface/components/store/ThemeModal.svelte b/src/interface/components/store/ThemeModal.svelte index c89e0414..46986eb6 100644 --- a/src/interface/components/store/ThemeModal.svelte +++ b/src/interface/components/store/ThemeModal.svelte @@ -28,6 +28,7 @@ isLoggedIn, onRequestSignIn, selectedThemeId = '', installedThemeColors = {}, +variant = 'official', } = $props<{ theme: Theme | null currentThemes: string[] @@ -44,7 +45,10 @@ isLoggedIn?: boolean onRequestSignIn?: () => void selectedThemeId?: string installedThemeColors?: Record +variant?: 'official' | 'community' }>() +const isCommunity = $derived(variant === 'community') +const showFavorites = $derived(!isCommunity) function variantApplyStyles(variantId: string) { if (!theme) { return getThemeApplyButtonStyles(undefined) @@ -220,6 +224,14 @@ aria-label="Close"

{theme.name}

+{#if isCommunity} + +Community + +{/if} {#if theme.featured === true} {modalDisplayDownloadCount.toLocaleString()} downloads +{#if showFavorites} {(theme.favorite_count ?? 0).toLocaleString()} favorites +{/if}
{#if heroSlides.length > 0} {#key theme?.id} @@ -446,7 +460,7 @@ title="Install {f.name}" {theme.description}

-{#if toggleFavorite && theme} +{#if showFavorites && toggleFavorite && theme} +
+
+ - - {'\uecb3'} - View theme creation docs - + + + View docs + +
+ + +
{:else if listMode === 'downloaded'} + +
+ {#if innerTab === "mine"} + + {/if} +
+

+ Community themes are user-submitted and moderated separately from the official theme store. +

+
+ +
+ {#if innerTab === "browse"} + {#if browseLoading} +
+ {#each Array(6) as _, i (i)} + + {/each} +
+ {:else if browseError} +
+

Couldn't load community themes

+

{browseError}

+ +
+ {:else} + (displayTheme = theme)} + toggleFavorite={() => {}} + isLoggedIn={false} + installedThemeIds={currentThemes} + variant="community" + /> + {#if displayTheme} + (displayTheme = t)} + {selectedThemeId} + {installedThemeColors} + variant="community" + onInstall={async (themeId) => { + if (displayTheme) await installCommunityTheme(themeId, displayTheme); + }} + onRemove={removeInstalledTheme} + onApply={applyInstalledTheme} + /> + {/if} + {/if} + {:else if !cloudLoggedIn} +
+

Sign in to manage your themes

+

+ Submit themes for review and track pending, approved, or rejected submissions. +

+ +
+ {:else} +
+ {#each ["", "pending", "approved", "rejected"] as status (status)} + + {/each} +
+ + {#if myLoading} +
+ {#each Array(4) as _, i (i)} + + {/each} +
+ {:else if myError} +

{myError}

+ {:else if myThemes.length === 0} +
+

No submissions yet.

+ +
+ {:else} +
    + {#each myThemes as theme (theme.id)} +
  • + +
  • + {/each} +
+ {/if} + {/if} +
+ + {#if showSignInOverlay} + (showSignInOverlay = false)} /> + {/if} + + {#if showSubmitModal} + + {/if} + + {#if detailTheme} + + {/if} +
diff --git a/src/interface/pages/settings.svelte b/src/interface/pages/settings.svelte index 6045e8b3..f022c166 100644 --- a/src/interface/pages/settings.svelte +++ b/src/interface/pages/settings.svelte @@ -3,6 +3,7 @@ import Shortcuts from "./settings/shortcuts.svelte"; import Theme from "./settings/theme.svelte"; import Store from "./store.svelte"; + import CommunityThemes from "./communityThemes.svelte"; import TabbedContainer from "../components/TabbedContainer.svelte"; import darkLogo from "@/resources/icons/betterseqta-dark-full.png"; import lightLogo from "@/resources/icons/betterseqta-light-full.png"; @@ -39,7 +40,7 @@ } from "@/utils/githubReleaseUpdate"; type PageId = "settings" | "themes" | "backgrounds"; type StoreTab = "themes" | "backgrounds"; - type ThemeView = "theme-settings" | "theme-store" | "create-theme"; + type ThemeView = "theme-settings" | "theme-store" | "community-themes" | "create-theme"; type BackgroundView = "background-settings" | "background-store"; type NavItem = { @@ -93,7 +94,8 @@ { label: "Themes", items: [ - { id: "theme-store", label: "Store" }, + { id: "theme-store", label: "Theme store" }, + { id: "community-themes", label: "Community themes" }, { id: "theme-settings", label: "Downloaded themes" }, { id: "create-theme", label: "Custom themes" }, ], @@ -145,6 +147,8 @@ if (activePage === "themes") { if (activeThemeView === "theme-settings") return "Downloaded themes"; if (activeThemeView === "create-theme") return "Custom themes"; + if (activeThemeView === "community-themes") return "Community themes"; + if (activeThemeView === "theme-store") return "Theme store"; return "Themes"; } if (activePage === "backgrounds") return "Backgrounds"; @@ -158,10 +162,15 @@ }); const isStoreView = $derived( - (activePage === "themes" && activeThemeView === "theme-store") || + (activePage === "themes" && + (activeThemeView === "theme-store" || activeThemeView === "community-themes")) || (activePage === "backgrounds" && activeBackgroundView === "background-store"), ); + const isOfficialStoreView = $derived( + activePage === "themes" && activeThemeView === "theme-store", + ); + const openGhRelease = () => { const url = ghReleaseUpdate?.url ?? "https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases"; @@ -286,9 +295,11 @@ activeThemeView = destination.view === "store" ? "theme-store" - : destination.view === "custom" - ? "create-theme" - : "theme-settings"; + : destination.view === "community" + ? "community-themes" + : destination.view === "custom" + ? "create-theme" + : "theme-settings"; } else if (destination.page === "backgrounds" && destination.view) { activeBackgroundView = destination.view === "store" ? "background-store" : "background-settings"; } @@ -365,7 +376,7 @@ activePage = page; if (page === "themes") activeThemeView = "theme-store"; }} - showStoreTools={isStoreView} + showStoreTools={isOfficialStoreView || activeThemeView === "community-themes"} onLogoClick={handleDevModeToggle} onClose={handleClose} /> @@ -438,18 +449,22 @@ {#if isStoreView}
- { - activePage = tab; - if (tab === "themes") activeThemeView = "theme-store"; - else activeBackgroundView = "background-store"; - }} - setSearchTerm={(term) => (storeSearchTerm = term)} - setBackgroundCategories={(categories) => (backgroundCategories = categories)} - /> + {#if activePage === "themes" && activeThemeView === "community-themes"} + (storeSearchTerm = term)} /> + {:else} + { + activePage = tab; + if (tab === "themes") activeThemeView = "theme-store"; + else activeBackgroundView = "background-store"; + }} + setSearchTerm={(term) => (storeSearchTerm = term)} + setBackgroundCategories={(categories) => (backgroundCategories = categories)} + /> + {/if}
{:else}
diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index 7955cc1c..ef25a197 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -57,6 +57,8 @@ type ThemeContent = { export type InstallThemeMeta = { fromStore: boolean; + /** Community custom-themes API install (distinct from official store). */ + fromCommunity?: boolean; /** Server list `updated_at` (Unix seconds); set when installing from store. */ serverUpdatedAtSec?: number; forceTheme?: boolean; @@ -582,6 +584,56 @@ export class ThemeManager { } } + /** + * Download and install an approved community theme from `/api/custom-themes`. + */ + public async downloadCommunityTheme(themeContent: { + id: string; + name?: string; + theme_json_url?: string; + updated_at?: number; + }): Promise { + try { + await this.downloadAndInstallCommunityTheme(themeContent); + } catch (error) { + console.error("[ThemeManager] Error downloading community theme:", error); + throw error; + } + } + + private async downloadAndInstallCommunityTheme(themeContent: { + id: string; + theme_json_url?: string; + updated_at?: number; + }): Promise { + verboseDebug("[ThemeManager] Downloading community theme:", themeContent.id); + if (!themeContent.id) { + throw new Error("Missing theme id"); + } + + let themeJsonUrl = themeContent.theme_json_url; + if (!themeJsonUrl) { + const downloadData = (await this.fetchFromUrl( + `${this.THEME_API_BASE}/custom-themes/${themeContent.id}/download`, + )) as { success?: boolean; data?: { theme_json_url: string } }; + if (!downloadData?.success || !downloadData?.data?.theme_json_url) { + throw new Error("Failed to get community theme download URL"); + } + themeJsonUrl = downloadData.data.theme_json_url; + } + + if (!isAllowedFetchUrl(themeJsonUrl)) { + throw new Error("Community theme download URL not allowed"); + } + + const themeData = (await this.fetchFromUrl(themeJsonUrl)) as ThemeContent; + await this.installTheme(themeData, { + fromStore: true, + fromCommunity: true, + serverUpdatedAtSec: themeContent.updated_at, + }); + } + /** * Fetch theme.json from the store and install (throws on failure). */ @@ -650,6 +702,7 @@ export class ThemeManager { } const fromStore = meta?.fromStore ?? false; + const fromCommunity = meta?.fromCommunity ?? false; const serverUpdatedAtSec = meta?.serverUpdatedAtSec; // Handle cover image (optional) @@ -701,6 +754,7 @@ export class ThemeManager { hideThemeName: themeData.hideThemeName ?? false, forceDark: themeData.forceDark, installedFromStore: fromStore, + installedFromCommunity: fromCommunity || undefined, userEdited: fromStore ? false : undefined, storeSyncedAtSec: fromStore && serverUpdatedAtSec != null diff --git a/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts b/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts new file mode 100644 index 00000000..0a37af53 --- /dev/null +++ b/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts @@ -0,0 +1,18 @@ +/** @jest-environment jsdom */ +import { mergeUploadPayload } from "./buildThemeUploadFormData"; + +describe("buildThemeUploadFormData", () => { + it("mergeUploadPayload attaches trimmed submission notes", () => { + const merged = mergeUploadPayload( + { themeZip: { fieldName: "theme_zip", filename: "t.zip", mimeType: "application/zip", dataBase64: "abc" } }, + " Please review ", + ); + expect(merged.submissionNotes).toBe("Please review"); + expect(merged.themeZip?.fieldName).toBe("theme_zip"); + }); + + it("mergeUploadPayload omits empty notes", () => { + const merged = mergeUploadPayload({ looseFiles: [] }, " "); + expect(merged.submissionNotes).toBeUndefined(); + }); +}); diff --git a/src/seqta/utils/customThemes/buildThemeUploadFormData.ts b/src/seqta/utils/customThemes/buildThemeUploadFormData.ts new file mode 100644 index 00000000..fc30ef9b --- /dev/null +++ b/src/seqta/utils/customThemes/buildThemeUploadFormData.ts @@ -0,0 +1,110 @@ +import type { LoadedCustomTheme } from "@/types/CustomThemes"; +import { blobToBase64Data } from "@/plugins/built-in/themes/themeImageUrl"; +import type { CustomThemeUploadFilePart, CustomThemeUploadPayload } from "./types"; + +/** Build serializable upload parts from a local custom theme (loose files, not ZIP). */ +export async function buildUploadPartsFromLocalTheme( + theme: LoadedCustomTheme, +): Promise { + const { + CustomImages = [], + coverImage, + webURL, + isEditable, + selectedColor, + allowBackgrounds, + installedFromStore, + storeSyncedAtSec, + userEdited, + installedFromCommunity, + ...themeBasics + } = theme; + + const finalImages = await Promise.all( + CustomImages.map(async (image) => ({ + id: image.id, + variableName: image.variableName, + data: await blobToBase64Data(image.blob), + })), + ); + + const coverImageBase64 = coverImage ? await blobToBase64Data(coverImage) : null; + + const themeJson = JSON.stringify({ + ...themeBasics, + images: finalImages, + coverImage: coverImageBase64, + }); + + const looseFiles: CustomThemeUploadFilePart[] = [ + { + fieldName: "theme.json", + filename: "theme.json", + mimeType: "application/json", + dataBase64: base64FromUtf8(themeJson), + }, + ]; + + if (coverImage) { + const coverBytes = await blobToBase64Data(coverImage); + looseFiles.push({ + fieldName: "images/banner.webp", + filename: "banner.webp", + mimeType: coverImage.type || "image/webp", + dataBase64: coverBytes, + }); + looseFiles.push({ + fieldName: "images/marquee.webp", + filename: "marquee.webp", + mimeType: coverImage.type || "image/webp", + dataBase64: coverBytes, + }); + } + + return { looseFiles }; +} + +/** Build upload payload from a user-selected ZIP file. */ +export async function buildUploadPartsFromZipFile(file: File): Promise { + const dataBase64 = await readFileAsBase64(file); + return { + themeZip: { + fieldName: "theme_zip", + filename: file.name || "theme.zip", + mimeType: file.type || "application/zip", + dataBase64, + }, + }; +} + +function base64FromUtf8(text: string): string { + const bytes = new TextEncoder().encode(text); + let binary = ""; + for (const b of bytes) binary += String.fromCharCode(b); + return btoa(binary); +} + +function readFileAsBase64(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + const result = reader.result; + if (typeof result !== "string") { + reject(new Error("Failed to read file")); + return; + } + const comma = result.indexOf(","); + resolve(comma >= 0 ? result.slice(comma + 1) : result); + }; + reader.onerror = () => reject(reader.error ?? new Error("Failed to read file")); + reader.readAsDataURL(file); + }); +} + +export function mergeUploadPayload( + base: CustomThemeUploadPayload, + submissionNotes?: string, +): CustomThemeUploadPayload { + const notes = submissionNotes?.trim(); + return notes ? { ...base, submissionNotes: notes } : base; +} diff --git a/src/seqta/utils/customThemes/client.test.ts b/src/seqta/utils/customThemes/client.test.ts new file mode 100644 index 00000000..d8e744b0 --- /dev/null +++ b/src/seqta/utils/customThemes/client.test.ts @@ -0,0 +1,37 @@ +import { + formatCustomThemeStatus, + statusBadgeClass, + canEditCustomTheme, +} from "./client"; +import { parseApiError, parseValidationErrors } from "./parseApiEnvelope"; + +describe("customThemes client helpers", () => { + it("formats status labels", () => { + expect(formatCustomThemeStatus("pending")).toBe("Pending review"); + expect(formatCustomThemeStatus("approved")).toBe("Approved"); + expect(formatCustomThemeStatus("rejected")).toBe("Rejected"); + }); + + it("returns badge classes per status", () => { + expect(statusBadgeClass("pending")).toContain("amber"); + expect(statusBadgeClass("approved")).toContain("emerald"); + expect(statusBadgeClass("rejected")).toContain("red"); + }); + + it("allows edit only for pending and rejected themes", () => { + expect(canEditCustomTheme({ id: "1", name: "A", description: "", coverImage: "", status: "pending" })).toBe(true); + expect(canEditCustomTheme({ id: "1", name: "A", description: "", coverImage: "", status: "rejected" })).toBe(true); + expect(canEditCustomTheme({ id: "1", name: "A", description: "", coverImage: "", status: "approved" })).toBe(false); + }); + + it("parses API envelope errors and validation details", () => { + expect(parseApiError({ code: "INVALID_THEME_STRUCTURE", message: "Bad theme" })).toBe("Bad theme"); + expect( + parseValidationErrors({ + code: "INVALID_THEME_STRUCTURE", + message: "Bad theme", + details: { errors: ["Missing CustomCSS", "Missing name"] }, + }), + ).toEqual(["Missing CustomCSS", "Missing name"]); + }); +}); diff --git a/src/seqta/utils/customThemes/client.ts b/src/seqta/utils/customThemes/client.ts new file mode 100644 index 00000000..0c432fba --- /dev/null +++ b/src/seqta/utils/customThemes/client.ts @@ -0,0 +1,193 @@ +import browser from "webextension-polyfill"; +import type { CustomThemeStatus } from "./constants"; +import { formatThemeDate } from "./formatThemeDate"; +import { normalizeCustomTheme } from "./normalizeCustomTheme"; +import { parseApiError, parseValidationErrors } from "./parseApiEnvelope"; +import type { + CustomThemeApiEnvelope, + CustomThemeDetailResponse, + CustomThemeListResponse, + CustomThemeOwner, + CustomThemeSubmitResponse, + CustomThemeUploadPayload, +} from "./types"; + +export class CustomThemeApiError extends Error { + constructor( + message: string, + readonly status: number, + readonly code?: string, + readonly validationErrors: string[] = [], + ) { + super(message); + this.name = "CustomThemeApiError"; + } +} + +const FETCH_TIMEOUT_MS = 25_000; + +function sendMessageWithTimeout(message: object): Promise { + return Promise.race([ + browser.runtime.sendMessage(message) as Promise, + new Promise((_, reject) => { + setTimeout( + () => + reject( + new Error( + "Community themes request timed out — reload the SEQTA page after updating the extension.", + ), + ), + FETCH_TIMEOUT_MS, + ); + }), + ]); +} + +function throwFromEnvelope( + envelope: CustomThemeApiEnvelope & { httpStatus?: number }, +): never { + const status = envelope.httpStatus ?? 0; + const errObj = + envelope.error && typeof envelope.error === "object" ? envelope.error : undefined; + const message = parseApiError(envelope.error); + const code = errObj?.code; + const validationErrors = parseValidationErrors(errObj); + throw new CustomThemeApiError(message, status, code, validationErrors); +} + +export function formatCustomThemeStatus(status: CustomThemeStatus | string | undefined): string { + const labels: Record = { + pending: "Pending review", + approved: "Approved", + rejected: "Rejected", + }; + return labels[status ?? ""] ?? (status ? String(status) : "Unknown"); +} + +export function statusBadgeClass(status: CustomThemeStatus | string | undefined): string { + switch (status) { + case "pending": + return "bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100"; + case "approved": + return "bg-emerald-100 text-emerald-900 dark:bg-emerald-950 dark:text-emerald-100"; + case "rejected": + return "bg-red-100 text-red-900 dark:bg-red-950 dark:text-red-100"; + default: + return "bg-zinc-100 text-zinc-800 dark:bg-zinc-800 dark:text-zinc-200"; + } +} + +export { formatThemeDate }; + +export async function fetchCommunityThemes(options?: { + page?: number; + limit?: number; + sort?: "popular" | "newest" | "name"; + search?: string; +}): Promise { + const res = await sendMessageWithTimeout< + CustomThemeApiEnvelope<{ themes?: unknown[]; pagination?: CustomThemeListResponse["pagination"] }> + >({ + type: "fetchCustomThemes", + page: options?.page ?? 1, + limit: options?.limit ?? 20, + sort: options?.sort ?? "popular", + search: options?.search, + }); + if (!res.success || !res.data?.themes) throwFromEnvelope(res); + return { + themes: res.data.themes + .map((row) => normalizeCustomTheme(row as Record)) + .filter((t) => t.id.length > 0), + pagination: res.data.pagination, + }; +} + +export async function fetchMyCustomThemes(options?: { + page?: number; + limit?: number; + status?: CustomThemeStatus; +}): Promise { + const res = await sendMessageWithTimeout< + CustomThemeApiEnvelope<{ themes?: unknown[]; pagination?: CustomThemeListResponse["pagination"] }> + >({ + type: "fetchMyCustomThemes", + page: options?.page ?? 1, + limit: options?.limit ?? 20, + status: options?.status, + }); + if (!res.success || !res.data?.themes) throwFromEnvelope(res); + return { + themes: res.data.themes + .map((row) => normalizeCustomTheme(row as Record)) + .filter((t) => t.id.length > 0), + pagination: res.data.pagination, + }; +} + +export async function fetchMyCustomThemeDetail(id: string): Promise { + const res = await sendMessageWithTimeout>({ + type: "fetchMyCustomThemeDetail", + themeId: id, + }); + if (!res.success || !res.data?.theme) throwFromEnvelope(res); + return { + theme: normalizeCustomTheme(res.data.theme as unknown as Record), + files: Array.isArray(res.data.files) ? res.data.files : [], + }; +} + +export async function submitCustomTheme( + payload: CustomThemeUploadPayload, +): Promise { + const res = await sendMessageWithTimeout>({ + type: "submitCustomTheme", + payload, + }); + if (!res.success || !res.data?.theme) throwFromEnvelope(res); + return { + theme: normalizeCustomTheme(res.data.theme as unknown as Record), + validation: res.data.validation, + }; +} + +export async function replaceCustomThemeFiles( + id: string, + payload: CustomThemeUploadPayload, +): Promise { + const res = await sendMessageWithTimeout>({ + type: "replaceCustomThemeFiles", + themeId: id, + payload, + }); + if (!res.success || !res.data?.theme) throwFromEnvelope(res); + return { + theme: normalizeCustomTheme(res.data.theme as unknown as Record), + validation: res.data.validation, + }; +} + +export async function updateCustomThemeMetadata( + id: string, + body: { name?: string; description?: string; submission_notes?: string }, +): Promise { + const res = await sendMessageWithTimeout>({ + type: "updateCustomThemeMetadata", + themeId: id, + body, + }); + if (!res.success || !res.data?.theme) throwFromEnvelope(res); + return normalizeCustomTheme(res.data.theme as Record); +} + +export async function deleteCustomTheme(id: string): Promise { + const res = await sendMessageWithTimeout>({ + type: "deleteCustomTheme", + themeId: id, + }); + if (!res.success) throwFromEnvelope(res); +} + +export function canEditCustomTheme(theme: CustomThemeOwner): boolean { + return theme.status === "pending" || theme.status === "rejected"; +} diff --git a/src/seqta/utils/customThemes/constants.ts b/src/seqta/utils/customThemes/constants.ts new file mode 100644 index 00000000..ff205461 --- /dev/null +++ b/src/seqta/utils/customThemes/constants.ts @@ -0,0 +1,12 @@ +export const CUSTOM_THEMES_BASE = "/api/custom-themes"; + +export const CUSTOM_THEME_STATUSES = ["pending", "approved", "rejected"] as const; +export type CustomThemeStatus = (typeof CUSTOM_THEME_STATUSES)[number]; + +export const PENDING_SUBMISSION_LIMIT = 5; +export const UPLOADS_PER_24H_LIMIT = 10; + +export const RATE_LIMIT_PENDING_MESSAGE = + "You can have at most 5 themes awaiting review. Wait for approval, rejection, or delete a pending submission."; +export const RATE_LIMIT_DAILY_MESSAGE = + "You can submit at most 10 new themes per 24 hours. Try again later."; diff --git a/src/seqta/utils/customThemes/formatThemeDate.test.ts b/src/seqta/utils/customThemes/formatThemeDate.test.ts new file mode 100644 index 00000000..e87afc92 --- /dev/null +++ b/src/seqta/utils/customThemes/formatThemeDate.test.ts @@ -0,0 +1,14 @@ +import { formatThemeDate } from "./formatThemeDate"; + +describe("formatThemeDate", () => { + it("formats Unix seconds as a locale date string", () => { + const formatted = formatThemeDate(1700000000); + expect(formatted).toMatch(/\d/); + expect(new Date(1700000000 * 1000).toLocaleDateString()).toBe(formatted); + }); + + it("returns em dash for missing values", () => { + expect(formatThemeDate(undefined)).toBe("—"); + expect(formatThemeDate(null)).toBe("—"); + }); +}); diff --git a/src/seqta/utils/customThemes/formatThemeDate.ts b/src/seqta/utils/customThemes/formatThemeDate.ts new file mode 100644 index 00000000..f7398a33 --- /dev/null +++ b/src/seqta/utils/customThemes/formatThemeDate.ts @@ -0,0 +1,5 @@ +/** Theme API timestamps are Unix seconds. */ +export function formatThemeDate(unixSeconds: number | null | undefined): string { + if (unixSeconds == null || !Number.isFinite(unixSeconds)) return "—"; + return new Date(unixSeconds * 1000).toLocaleDateString(); +} diff --git a/src/seqta/utils/customThemes/normalizeCustomTheme.test.ts b/src/seqta/utils/customThemes/normalizeCustomTheme.test.ts new file mode 100644 index 00000000..ef00e721 --- /dev/null +++ b/src/seqta/utils/customThemes/normalizeCustomTheme.test.ts @@ -0,0 +1,37 @@ +import { normalizeCustomTheme } from "./normalizeCustomTheme"; + +describe("normalizeCustomTheme", () => { + it("maps snake_case API fields and preserves Unix seconds", () => { + const theme = normalizeCustomTheme({ + id: "abc-123", + name: "Ocean Blue", + description: "A calm theme", + cover_image: "https://example.test/cover.webp", + theme_json_url: "https://example.test/theme.json", + download_count: 42, + created_at: 1700000000, + updated_at: 1700100000, + status: "pending", + submission_notes: "First try", + rejection_reason: null, + theme_type: "betterseqta", + author: "Alice", + }); + + expect(theme.id).toBe("abc-123"); + expect(theme.name).toBe("Ocean Blue"); + expect(theme.coverImage).toBe("https://example.test/cover.webp"); + expect(theme.theme_json_url).toBe("https://example.test/theme.json"); + expect(theme.download_count).toBe(42); + expect(theme.created_at).toBe(1700000000); + expect(theme.updated_at).toBe(1700100000); + expect(theme.status).toBe("pending"); + expect(theme.submission_notes).toBe("First try"); + expect(theme.theme_type).toBe("betterseqta"); + }); + + it("falls back to generated cover image URL when missing", () => { + const theme = normalizeCustomTheme({ id: "theme-1", name: "Test" }); + expect(theme.coverImage).toContain("/api/images/custom-themes/theme-1/images/banner.webp"); + }); +}); diff --git a/src/seqta/utils/customThemes/normalizeCustomTheme.ts b/src/seqta/utils/customThemes/normalizeCustomTheme.ts new file mode 100644 index 00000000..46634385 --- /dev/null +++ b/src/seqta/utils/customThemes/normalizeCustomTheme.ts @@ -0,0 +1,80 @@ +import type { CustomThemeOwner } from "./types"; + +function pickString(row: Record, ...keys: string[]): string { + for (const key of keys) { + const v = row[key]; + if (typeof v === "string" && v.length > 0) return v; + } + return ""; +} + +function pickOptionalString(row: Record, ...keys: string[]): string | undefined { + for (const key of keys) { + const v = row[key]; + if (typeof v === "string") return v; + } + return undefined; +} + +function pickNumber(row: Record, ...keys: string[]): number | undefined { + for (const key of keys) { + const v = row[key]; + if (typeof v === "number" && Number.isFinite(v)) return v; + } + return undefined; +} + +/** Normalize a custom-themes API row into a store-compatible Theme shape. */ +export function normalizeCustomTheme(row: Record): CustomThemeOwner { + const id = pickString(row, "id"); + const coverImage = + pickString(row, "coverImage", "cover_image") || + (id ? `https://betterseqta.org/api/images/custom-themes/${id}/images/banner.webp` : ""); + const marqueeImage = pickOptionalString(row, "marqueeImage", "marquee_image"); + + const tagsRaw = row.tags; + const tags = Array.isArray(tagsRaw) + ? tagsRaw.filter((t): t is string => typeof t === "string") + : undefined; + + const statusRaw = row.status; + const status = + statusRaw === "pending" || statusRaw === "approved" || statusRaw === "rejected" + ? statusRaw + : undefined; + + const themeTypeRaw = row.theme_type ?? row.themeType; + const theme_type = + themeTypeRaw === "betterseqta" || themeTypeRaw === "desqta" ? themeTypeRaw : undefined; + + return { + id, + name: pickString(row, "name") || "Untitled theme", + description: pickString(row, "description"), + coverImage, + marqueeImage, + theme_json_url: pickOptionalString(row, "theme_json_url", "themeJsonUrl"), + author: pickOptionalString(row, "author"), + download_count: pickNumber(row, "download_count", "downloadCount") ?? 0, + tags, + created_at: pickNumber(row, "created_at", "createdAt"), + updated_at: pickNumber(row, "updated_at", "updatedAt"), + published_at: pickNumber(row, "published_at", "publishedAt"), + slug: pickOptionalString(row, "slug"), + status, + theme_type, + submission_notes: + typeof row.submission_notes === "string" + ? row.submission_notes + : typeof row.submissionNotes === "string" + ? row.submissionNotes + : null, + rejection_reason: + typeof row.rejection_reason === "string" + ? row.rejection_reason + : typeof row.rejectionReason === "string" + ? row.rejectionReason + : null, + reviewed_at: pickNumber(row, "reviewed_at", "reviewedAt") ?? null, + }; +} diff --git a/src/seqta/utils/customThemes/parseApiEnvelope.ts b/src/seqta/utils/customThemes/parseApiEnvelope.ts new file mode 100644 index 00000000..86f7c7d4 --- /dev/null +++ b/src/seqta/utils/customThemes/parseApiEnvelope.ts @@ -0,0 +1,21 @@ +import type { CustomThemeApiEnvelope, CustomThemeApiError } from "./types"; + +export function parseApiError(error: CustomThemeApiEnvelope["error"]): string { + if (!error) return "Request failed"; + if (typeof error === "string") return error; + if (typeof error.message === "string" && error.message.length > 0) return error.message; + if (typeof error.code === "string") return error.code; + return "Request failed"; +} + +export function parseValidationErrors(error: CustomThemeApiError | null | undefined): string[] { + if (!error?.details?.errors || !Array.isArray(error.details.errors)) return []; + return error.details.errors.filter((e): e is string => typeof e === "string"); +} + +export function parseValidationWarnings( + validation: { warnings?: unknown[] } | undefined, +): string[] { + if (!validation?.warnings || !Array.isArray(validation.warnings)) return []; + return validation.warnings.filter((w): w is string => typeof w === "string"); +} diff --git a/src/seqta/utils/customThemes/types.ts b/src/seqta/utils/customThemes/types.ts new file mode 100644 index 00000000..0b10323a --- /dev/null +++ b/src/seqta/utils/customThemes/types.ts @@ -0,0 +1,68 @@ +import type { Theme } from "@/interface/types/Theme"; +import type { CustomThemeStatus } from "./constants"; + +export type CustomThemeApiError = { + code?: string; + message?: string; + details?: { errors?: string[]; warnings?: string[] }; +}; + +export type CustomThemeApiEnvelope = { + success: boolean; + data: T | null; + error: CustomThemeApiError | string | null; + meta?: { timestamp?: number; version?: string }; +}; + +export type CustomThemeOwner = Theme & { + slug?: string; + status?: CustomThemeStatus; + theme_type?: "betterseqta" | "desqta"; + submission_notes?: string | null; + rejection_reason?: string | null; + reviewed_at?: number | null; + published_at?: number | null; +}; + +export type CustomThemeFile = { + id: string; + file_path: string; + file_type: string; + file_size: number; + mime_type: string; + created_at: number; +}; + +export type CustomThemeUploadFilePart = { + fieldName: string; + filename: string; + mimeType: string; + /** Base64-encoded file bytes */ + dataBase64: string; +}; + +export type CustomThemeUploadPayload = { + themeZip?: CustomThemeUploadFilePart; + looseFiles?: CustomThemeUploadFilePart[]; + submissionNotes?: string; +}; + +export type CustomThemeListResponse = { + themes: CustomThemeOwner[]; + pagination?: { + page: number; + limit: number; + total: number; + total_pages: number; + }; +}; + +export type CustomThemeDetailResponse = { + theme: CustomThemeOwner; + files: CustomThemeFile[]; +}; + +export type CustomThemeSubmitResponse = { + theme: CustomThemeOwner; + validation?: { valid: boolean; warnings: string[]; errors: string[] }; +}; diff --git a/src/seqta/utils/openCommunityThemeSubmit.test.ts b/src/seqta/utils/openCommunityThemeSubmit.test.ts new file mode 100644 index 00000000..4dc5ac7f --- /dev/null +++ b/src/seqta/utils/openCommunityThemeSubmit.test.ts @@ -0,0 +1,27 @@ +/** @jest-environment jsdom */ + +import { + consumeOpenCommunityThemeSubmit, + requestOpenCommunityThemeSubmit, +} from "./openCommunityThemeSubmit"; + +describe("openCommunityThemeSubmit", () => { + beforeEach(() => { + sessionStorage.clear(); + while (consumeOpenCommunityThemeSubmit()) { + /* drain pending state */ + } + }); + + it("consumes the pending submit request once", () => { + requestOpenCommunityThemeSubmit(); + expect(consumeOpenCommunityThemeSubmit()).toBe(true); + expect(consumeOpenCommunityThemeSubmit()).toBe(false); + }); + + it("consumes a sessionStorage handoff once", () => { + sessionStorage.setItem("bsplus:open-community-theme-submit", "1"); + expect(consumeOpenCommunityThemeSubmit()).toBe(true); + expect(consumeOpenCommunityThemeSubmit()).toBe(false); + }); +}); diff --git a/src/seqta/utils/openCommunityThemeSubmit.ts b/src/seqta/utils/openCommunityThemeSubmit.ts new file mode 100644 index 00000000..ac05ae6a --- /dev/null +++ b/src/seqta/utils/openCommunityThemeSubmit.ts @@ -0,0 +1,45 @@ +/** + * Module-level handoff for "open Community themes → My themes → submit modal". + */ +const OPEN_COMMUNITY_SUBMIT_SESSION_KEY = "bsplus:open-community-theme-submit"; + +export const OPEN_COMMUNITY_SUBMIT_EVENT = "bsplus:open-community-submit"; + +let pendingOpenSubmit = false; + +export function requestOpenCommunityThemeSubmit(): void { + pendingOpenSubmit = true; + try { + sessionStorage.setItem(OPEN_COMMUNITY_SUBMIT_SESSION_KEY, "1"); + } catch { + /* ignore */ + } + window.dispatchEvent(new CustomEvent(OPEN_COMMUNITY_SUBMIT_EVENT)); +} + +export function consumeOpenCommunityThemeSubmit(): boolean { + let shouldOpen = pendingOpenSubmit; + pendingOpenSubmit = false; + + try { + if (sessionStorage.getItem(OPEN_COMMUNITY_SUBMIT_SESSION_KEY)) { + sessionStorage.removeItem(OPEN_COMMUNITY_SUBMIT_SESSION_KEY); + shouldOpen = true; + } + } catch { + /* ignore */ + } + + return shouldOpen; +} + +export async function openCommunityThemeSubmit(): Promise { + requestOpenCommunityThemeSubmit(); + const [{ requestSettingsDestination }, { openSettingsPopup }] = + await Promise.all([ + import("@/seqta/utils/settingsNavigation"), + import("@/seqta/utils/setupSettingsButton"), + ]); + requestSettingsDestination({ page: "themes", view: "community" }); + await openSettingsPopup(); +} diff --git a/src/seqta/utils/settingsNavigation.ts b/src/seqta/utils/settingsNavigation.ts index 9094bd09..afacdecb 100644 --- a/src/seqta/utils/settingsNavigation.ts +++ b/src/seqta/utils/settingsNavigation.ts @@ -1,6 +1,6 @@ export type SettingsDestination = | { page: "settings"; section?: string } - | { page: "themes" | "backgrounds"; view?: "settings" | "store" | "custom" }; + | { page: "themes" | "backgrounds"; view?: "settings" | "store" | "community" | "custom" }; export const SETTINGS_NAVIGATION_EVENT = "bsplus:navigate-settings"; diff --git a/src/types/CustomThemes.ts b/src/types/CustomThemes.ts index faa3006f..3eb2ff7a 100644 --- a/src/types/CustomThemes.ts +++ b/src/types/CustomThemes.ts @@ -20,6 +20,8 @@ export type CustomTheme = { forceDark?: boolean; /** True if installed from the BetterSEQTA theme store (not file import). */ installedFromStore?: boolean; + /** True if installed from the community custom-themes API. */ + installedFromCommunity?: boolean; /** Server `updated_at` (Unix seconds) when this copy was installed or last auto-updated. */ storeSyncedAtSec?: number; /** User saved edits in theme creator or popup; blocks store auto-update. */ diff --git a/thedocsiwastalkingabout/custom-themes-api.md b/thedocsiwastalkingabout/custom-themes-api.md new file mode 100644 index 00000000..9b606357 --- /dev/null +++ b/thedocsiwastalkingabout/custom-themes-api.md @@ -0,0 +1,554 @@ +# Custom User-Uploaded Themes API + +HTTP API for community-submitted BetterSEQTA and DesQTA themes. Submissions require Accounts authentication, pass admin moderation, and appear on public distribution endpoints once approved. + +**Base URL:** `https://betterseqta.org` +**Prefix:** `/api/custom-themes` + +This namespace is **separate** from the official theme marketplace at `/api/themes` and `/api/admin/themes`. Custom themes use an isolated D1 database (`USER_THEMES_DB`) and R2 prefix (`custom-themes/{id}/`). Official store data is unchanged. + +--- + +## Auth matrix + +| Actor | Routes | Auth | +|-------|--------|------| +| Public | `GET /api/custom-themes/*` (non-`/mine`) | None — **approved themes only** | +| User | `GET/POST/PUT/DELETE /api/custom-themes/mine/*` | Accounts session cookie or `Authorization: Bearer ` | +| Admin | `GET/POST /api/admin/custom-themes/*` | Staff session via `requireAdmin` (`admin_level >= 1`) | + +Bearer tokens are obtained via `POST /api/auth/extension/login` or OAuth web login. All authenticated routes call `/api/auth/me` with forwarded cookie/Bearer headers. + +--- + +## Response envelope + +Successful JSON responses follow: + +```json +{ + "success": true, + "data": { }, + "error": null, + "meta": { "timestamp": 1735123456789, "version": "1.0.0" } +} +``` + +Errors return `success: false`, `data: null`, and an `error` object: + +```json +{ + "success": false, + "data": null, + "error": { + "code": "INVALID_THEME_STRUCTURE", + "message": "BetterSEQTA theme validation failed", + "details": { "errors": ["..."], "warnings": [] } + }, + "meta": { "timestamp": 1735123456789, "version": "1.0.0" } +} +``` + +Validation failures from upload endpoints return **422** with the envelope above. Most other errors use Nitro/H3 `createError` with a plain `{ statusCode, statusMessage }` body. + +--- + +## Timestamps + +Theme fields `created_at`, `updated_at`, `published_at`, and `reviewed_at` are **Unix time in seconds** (integers). Use `value * 1000` for JavaScript `Date`. The `meta.timestamp` field in the response envelope is milliseconds. + +--- + +## Status lifecycle + +``` +pending ──(admin approve)──► approved ──(public list)──► visible + │ │ + │ └──(user delete)──► removed + │ + ├──(admin reject)──► rejected ──(user re-upload files)──► pending + │ + └──(user delete)──► removed +``` + +| Status | Public API | Owner `/mine` | Admin API | +|--------|------------|---------------|-----------| +| `pending` | Hidden | Visible | Visible | +| `approved` | Visible | Visible | Visible | +| `rejected` | Hidden | Visible (includes `rejection_reason`) | Visible | + +Approved themes cannot be edited in v1 — owners must delete and re-submit. + +--- + +## Rate limits and ownership + +| Rule | Limit | +|------|-------| +| Concurrent pending submissions per user | **5** | +| New uploads per 24 hours per user | **10** (count of `custom_themes` rows created in the last 24 hours for that user) | + +Re-uploading files on an existing theme (`POST …/mine/[id]/files`) does not create a new upload-log row and does not count toward the 24h limit. File replacement still checks the pending cap. + +- `author_id` is always set from the authenticated user; users cannot upload on behalf of others. +- Owners may view all their themes regardless of status. +- Owners may edit metadata or replace files only when status is `pending` or `rejected`. +- Owners may delete any own theme (removes D1 row + R2 assets). + +Exceeded limits return **429**. + +--- + +## D1 setup + +Custom themes use a dedicated Cloudflare D1 database bound as `USER_THEMES_DB` in `wrangler.toml`. + +**One-time production setup:** + +```bash +pnpm exec wrangler d1 create bsplus-user-themes-db +# Copy the database_id UUID into wrangler.toml (prod + env.dev) + +pnpm exec wrangler d1 execute bsplus-user-themes-db --remote --file=server/database/user-themes/schema.sql +``` + +**Local development:** + +```bash +pnpm exec wrangler d1 execute bsplus-user-themes-db --local --file=server/database/user-themes/schema.sql +pnpm cf:dev +``` + +Schema file: `server/database/user-themes/schema.sql` +Tables: `custom_themes`, `custom_theme_files` (`custom_theme_upload_log` exists for legacy deployments but is no longer written to) + +Theme assets are stored in the existing R2 `BUCKET` under keys like `custom-themes/{theme_id}/theme.json`. + +--- + +## Theme types + +Both BetterSEQTA and DesQTA themes are supported. Type is auto-detected from uploaded files. + +### BetterSEQTA + +Folder or ZIP containing `theme.json` with `id`, `name`, `description`, `CustomCSS`. Optional `images/banner.webp`, `images/marquee.webp`. + +### DesQTA + +ZIP with `theme-manifest.json` + `styles/`. Optional `preview.png`, `screenshot1.png`, etc. + +Multipart field names match the official admin upload: `theme_zip` or `theme_folder` (ZIP), plus optional loose files. Optional text field: `submission_notes`. + +--- + +## Public distribution (no auth) + +All public routes filter `status = 'approved'`. + +### `GET /api/custom-themes` + +Paginated list of approved custom themes. + +| Query | Default | Notes | +|-------|---------|-------| +| `page` | `1` | 1-based | +| `limit` | `20` | Max 100 | +| `type` | — | `betterseqta` or `desqta` | +| `search` | — | Matches name, description, author (alias: `q`) | +| `sort` | `popular` | `popular`, `newest`, `name` | + +**Response:** + +```json +{ + "success": true, + "data": { + "themes": [ + { + "id": "9a9786d1-b5fc-4a91-8c7a-f8bf7f7679ad", + "name": "My Theme", + "slug": "my-theme", + "version": "1.0.0", + "description": "...", + "author": "Alice", + "license": "MIT", + "category": "other", + "tags": [], + "theme_type": "betterseqta", + "download_count": 42, + "preview": { "thumbnail": "https://...", "screenshots": [] }, + "compatibility": { "min": null, "max": null }, + "created_at": 1700000000, + "updated_at": 1700100000, + "published_at": 1700050000, + "coverImage": "https://betterseqta.org/api/images/custom-themes/{id}/images/banner.webp", + "marqueeImage": "https://...", + "theme_json_url": "https://betterseqta.org/api/custom-themes/{id}/theme.json" + } + ], + "pagination": { + "page": 1, + "limit": 20, + "total": 1, + "total_pages": 1 + } + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +DesQTA list items include `preview_thumbnail_url`, `zip_download_url`, `file_size`, and `checksum` instead of BetterSEQTA image fields. + +### `GET /api/custom-themes/search` + +Same filters as the list endpoint; search term is passed as `q` instead of `search`. + +**Response:** Same shape as list, plus `"query": "search term"`. + +### `GET /api/custom-themes/[id]` + +Single approved theme detail. Same theme object shape as list items. + +| HTTP | When | +|------|------| +| 404 | Not found or not approved | + +### `GET /api/custom-themes/by-slug/[slug]` + +Lookup approved theme by URL slug. Response body matches `GET /api/custom-themes/[id]`. + +### `GET /api/custom-themes/[id]/theme.json` + +Returns raw `theme.json` for approved BetterSEQTA themes. Content-Type: `application/json`. No auth. + +| HTTP | When | +|------|------| +| 404 | Not found, not approved, or not `betterseqta` | + +### `GET /api/custom-themes/[id]/download` + +Increments `download_count` and returns download URLs. + +**BetterSEQTA response:** + +```json +{ + "success": true, + "data": { + "theme_json_url": "https://betterseqta.org/api/custom-themes/{id}/theme.json", + "download_count": 43 + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +**DesQTA response:** + +```json +{ + "success": true, + "data": { + "zip_download_url": "https://betterseqta.org/api/images/custom-themes/{id}/theme.zip", + "checksum": "sha256:...", + "file_size": 12345, + "download_count": 43 + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +--- + +## User management (auth required) + +### `POST /api/custom-themes/mine` + +Submit a new theme. Multipart upload; starts as `status: pending`. + +**Request:** `multipart/form-data` + +| Field | Required | Notes | +|-------|----------|-------| +| `theme_zip` or `theme_folder` | One of | `.zip` archive | +| Individual files | Alt. | Loose theme files with filenames as field names | +| `submission_notes` | No | Message for reviewers | + +**Success (201 implied, 200 in practice):** + +```json +{ + "success": true, + "data": { + "theme": { + "id": "...", + "name": "...", + "slug": "...", + "status": "pending", + "submission_notes": "Please review", + "rejection_reason": null, + "reviewed_at": null, + "...": "other public + owner fields" + }, + "validation": { "valid": true, "warnings": [], "errors": [] } + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +| HTTP | When | +|------|------| +| 401 | Not authenticated | +| 400 | No files / invalid multipart | +| 409 | Theme id conflict (BetterSEQTA `theme.json` id already used) | +| 422 | Validation failed (`INVALID_THEME_STRUCTURE`, `UNKNOWN_THEME_TYPE`) | +| 429 | Rate limit exceeded | + +**Example — BetterSEQTA ZIP:** + +```bash +curl -X POST 'https://betterseqta.org/api/custom-themes/mine' \ + -H 'Authorization: Bearer eyJ...' \ + -F 'theme_zip=@my-theme.zip' \ + -F 'submission_notes=First public release' +``` + +**Example — DesQTA folder files:** + +```bash +curl -X POST 'https://betterseqta.org/api/custom-themes/mine' \ + -H 'Authorization: Bearer eyJ...' \ + -F 'theme_zip=@desqta-theme.zip' +``` + +### `GET /api/custom-themes/mine` + +List caller's themes (all statuses unless filtered). + +| Query | Notes | +|-------|-------| +| `page`, `limit` | Pagination (default 1, 20; max 100) | +| `status` | `pending`, `approved`, or `rejected` | +| `type` | `betterseqta` or `desqta` | + +Owner view includes `status`, `submission_notes`, `rejection_reason`, `reviewed_at`. + +### `GET /api/custom-themes/mine/[id]` + +Own theme detail plus file manifest. + +```json +{ + "success": true, + "data": { + "theme": { "...": "owner shape with status and rejection_reason" }, + "files": [ + { + "id": "...", + "file_path": "theme.json", + "file_type": "theme_json", + "file_size": 1234, + "mime_type": "application/json", + "created_at": 1700000000 + } + ] + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +| HTTP | When | +|------|------| +| 403 | Not the owner | +| 404 | Theme not found | + +### `PUT /api/custom-themes/mine/[id]` + +Update metadata when status is `pending` or `rejected`. + +**Request body (JSON):** + +```json +{ + "name": "Updated Name", + "description": "Updated description", + "submission_notes": "Fixed contrast issues" +} +``` + +At least one field required. + +| HTTP | When | +|------|------| +| 409 | Theme is `approved` (not editable) | +| 403 | Not the owner | + +### `POST /api/custom-themes/mine/[id]/files` + +Replace theme files. Re-validates upload; resets `rejected` → `pending`. Same multipart fields as create. + +| HTTP | When | +|------|------| +| 409 | Theme is `approved` | +| 422 | Validation failed | +| 429 | Pending cap exceeded | + +```bash +curl -X POST 'https://betterseqta.org/api/custom-themes/mine/{id}/files' \ + -H 'Authorization: Bearer eyJ...' \ + -F 'theme_zip=@my-theme-v2.zip' +``` + +### `DELETE /api/custom-themes/mine/[id]` + +Delete own theme and all R2 assets. Allowed for any status. + +```json +{ + "success": true, + "data": { + "message": "Theme deleted successfully", + "id": "..." + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +--- + +## Admin moderation (admin required) + +**Admin UI:** [`/admin/custom-themes`](https://betterseqta.org/admin/custom-themes) — list pending submissions, review detail, approve/reject (requires `admin_level >= 1`). + +API routes (also used by the admin UI): + +### `GET /api/admin/custom-themes` + +List submissions for triage. + +| Query | Notes | +|-------|-------| +| `page`, `limit` | Pagination | +| `status` | Filter by status | +| `author_id` | Filter by submitter Accounts user ID | +| `search` | Name, description, author | +| `type` | `betterseqta` or `desqta` | +| `include_counts` | Optional. `1` / `true` adds `counts: { pending, approved, rejected }` | + +Returns owner-shaped theme objects (includes status, rejection fields). + +### `GET /api/admin/custom-themes/[id]` + +Full detail with file list (includes `r2_key`, `checksum`) and submitter info: + +```json +{ + "success": true, + "data": { + "theme": { "...": "owner shape" }, + "files": [ { "id": "...", "r2_key": "custom-themes/.../theme.json", "...": "..." } ], + "submitter": { "author_id": "...", "author": "Display Name" } + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +### `POST /api/admin/custom-themes/[id]/approve` + +Approve a submission. Sets `status = approved`, `published_at`, `reviewed_by`, `reviewed_at`; clears `rejection_reason`. + +```json +{ + "success": true, + "data": { + "message": "Custom theme approved successfully", + "id": "...", + "status": "approved" + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +```bash +curl -X POST 'https://betterseqta.org/api/admin/custom-themes/{id}/approve' \ + -H 'Cookie: auth_token=...' +``` + +### `POST /api/admin/custom-themes/[id]/reject` + +Reject a submission. Requires a reason. + +**Request body:** + +```json +{ + "reason": "CustomCSS contains invalid selectors and breaks the timetable layout." +} +``` + +**Response:** + +```json +{ + "success": true, + "data": { + "message": "Custom theme rejected", + "id": "...", + "status": "rejected", + "rejection_reason": "CustomCSS contains invalid selectors and breaks the timetable layout." + }, + "error": null, + "meta": { "timestamp": 0, "version": "1.0.0" } +} +``` + +| HTTP | When | +|------|------| +| 400 | Missing `reason` | + +--- + +## Distinction from official `/api/themes` + +| | Official marketplace | Custom themes | +|--|---------------------|---------------| +| Prefix | `/api/themes`, `/api/admin/themes` | `/api/custom-themes`, `/api/admin/custom-themes` | +| Database | Main `DB` (bsplus-db) | `USER_THEMES_DB` | +| R2 prefix | `themes/{id}/` | `custom-themes/{id}/` | +| Upload auth | Admin only | Any authenticated user | +| Initial status | Admin workflow | `pending` until approved | +| Features | Ratings, favorites, collections, spotlight | None in v1 | +| Public filter | Approved official themes | Approved custom themes only | + +Extensions and clients should use `/api/custom-themes?type=betterseqta` for community themes and `/api/themes?type=betterseqta` for curated official themes. + +--- + +## Error reference + +| HTTP | Typical cause | +|------|---------------| +| 400 | Missing ID, empty update body, missing rejection reason, bad multipart | +| 401 | Missing or invalid auth on `/mine` routes | +| 403 | Not owner; not admin | +| 404 | Theme not found or not visible at this access level | +| 409 | Approved theme edit attempt; BetterSEQTA id conflict | +| 422 | Theme structure / type validation failed | +| 429 | Pending cap (5) or 24h upload cap (10) exceeded | +| 500 | Unexpected server error | + +--- + +## Related docs + +- Official theme API: [`docs/extension-themes-api.md`](extension-themes-api.md) +- Extension auth: §7 in extension-themes-api.md (`POST /api/auth/extension/login`) +- Client integration handoff: [`docs/custom-themes-client-integration.md`](custom-themes-client-integration.md) diff --git a/thedocsiwastalkingabout/custom-themes-client-integration.md b/thedocsiwastalkingabout/custom-themes-client-integration.md new file mode 100644 index 00000000..3ab5f8d9 --- /dev/null +++ b/thedocsiwastalkingabout/custom-themes-client-integration.md @@ -0,0 +1,383 @@ +# Custom Themes — Client Integration Guide + +Handoff document for implementing user-uploaded theme UI on the **Accounts site** and **BetterSEQTA extension**. The server API is complete; this doc covers auth, UI flows, API sequences, and testing. + +**API reference:** [`docs/custom-themes-api.md`](custom-themes-api.md) +**Base URL:** `https://betterseqta.org` + +--- + +## Goals (client v1) + +Users with a BetterSEQTA Accounts login can: + +1. **Submit** a BetterSEQTA or DesQTA theme for review +2. **Track** submissions on a "My themes" page (pending / approved / rejected) +3. **See rejection reasons** and **re-upload** fixed files +4. **Edit metadata** (name, description, notes) while pending or rejected +5. **Delete** any own theme +6. **Browse and install** approved community themes (extension: BetterSEQTA type) + +**Out of scope for client v1:** + +- Admin moderation UI (available at `/admin/custom-themes` on betterseqta.org for staff) +- Editing approved themes (must delete and re-submit) +- Ratings, favorites, collections on custom themes +- Mixing custom and official themes in one admin upload flow + +--- + +## Authentication + +All `/api/custom-themes/mine/*` routes require a valid Accounts identity. + +### Extension + +1. `POST /api/auth/extension/login` with username + password +2. Store `access_token` from response +3. Send `Authorization: Bearer ` on every `/mine` request + +```bash +curl -X POST 'https://betterseqta.org/api/auth/extension/login' \ + -H 'Content-Type: application/json' \ + -d '{"username":"user","password":"secret"}' +``` + +Response: + +```json +{ + "access_token": "eyJ...", + "expires_in": 3600 +} +``` + +### Accounts website + +Use the existing OAuth web login flow. After login, the `auth_token` HttpOnly cookie is sent automatically on same-origin requests to `betterseqta.org`. No Bearer header required when calling from the website. + +Verify session: `GET /api/auth/me` → returns user object with `id`, `username`, etc. + +Public browse/install endpoints (`GET /api/custom-themes`, download, `theme.json`) require **no auth**. + +--- + +## UI flows + +### 1. Submit theme (wizard) + +**Screens:** file picker → optional notes → upload progress → success with link to detail. + +**Steps:** + +1. User selects ZIP or folder (BetterSEQTA: `theme.json` + optional images; DesQTA: manifest + styles). +2. Optional `submission_notes` textarea ("anything reviewers should know"). +3. `POST /api/custom-themes/mine` multipart upload. +4. On success, show theme id, slug, status badge **Pending**, link to "My themes". +5. On 422, display `error.details.errors` inline; show `warnings` as non-blocking hints. +6. On 429, explain limits (max 5 pending, 10 uploads per 24h). + +**Do not** expect the theme on public browse until admin approves. + +### 2. My themes list + +**Screen:** table or cards with status badges (`pending` yellow, `approved` green, `rejected` red). + +**API:** `GET /api/custom-themes/mine?page=1&limit=20` + +Optional filters: `?status=rejected`, `?type=betterseqta`. + +Show: name, type, status, `created_at` (format from Unix seconds), actions (view, edit, delete). + +### 3. Theme detail (owner) + +**API:** `GET /api/custom-themes/mine/[id]` + +Display full metadata, file list, `submission_notes`. + +**If `status === 'rejected'`:** +- Prominent `rejection_reason` banner +- CTA: "Upload revised files" → flow 4 +- Allow metadata edit via flow 5 + +**If `status === 'pending'`:** +- Show "Awaiting review" +- Allow metadata edit and file replace + +**If `status === 'approved'`:** +- Show public URL / slug +- Disable edit controls; only **Delete** (with confirmation) +- Link to public theme page if you build one + +### 4. Re-upload after rejection + +**When:** `status` is `pending` or `rejected` (file replace resets rejected → pending). + +**API:** `POST /api/custom-themes/mine/[id]/files` with same multipart shape as create. + +**UX:** +1. Confirm replacing files will reset review to pending. +2. Upload new ZIP. +3. Refresh detail; status should be `pending`, `rejection_reason` cleared server-side. + +### 5. Edit metadata + +**When:** `pending` or `rejected` only. + +**API:** `PUT /api/custom-themes/mine/[id]` + +```json +{ + "name": "Neumorphic Dark v2", + "description": "Fixed contrast on sidebar", + "submission_notes": "Addressed reviewer feedback" +} +``` + +409 if user tries to edit an approved theme — show message that they must delete and re-submit. + +### 6. Delete theme + +**When:** any status. + +**UX:** confirmation modal ("This cannot be undone"). + +**API:** `DELETE /api/custom-themes/mine/[id]` + +Remove from list on success. + +--- + +## Extension: browse and install community themes + +Community themes are **separate** from official `/api/themes`. Use the custom prefix. + +### List approved BetterSEQTA themes + +``` +GET /api/custom-themes?type=betterseqta&sort=popular&page=1&limit=20 +``` + +No auth. Parse `data.themes[]` — each item includes `theme_json_url`, `coverImage`, `marqueeImage`, `download_count`, timestamps in **Unix seconds**. + +### Install flow (BetterSEQTA) + +Same pattern as official themes, different URLs: + +1. User picks theme from community list (or deep link by id/slug). +2. `GET /api/custom-themes/{id}/download` — records download, returns `theme_json_url`. +3. `GET` the `theme_json_url` (or use URL from list/detail directly). +4. Apply `CustomCSS` and images per existing extension theme loader. + +**Optional:** `GET /api/custom-themes/by-slug/{slug}` for share links. + +**DesQTA community themes:** use `zip_download_url` from download endpoint or list item; install like official DesQTA ZIP flow. + +### Suggested extension UX + +- Separate tab or section: "Community themes" vs "Official themes" +- Badge: "Community" on custom theme cards +- Do not send Bearer token for public list/install unless you add authenticated features later + +--- + +## API call sequences (copy-paste examples) + +### Sequence A — First submission + +```http +POST /api/custom-themes/mine +Authorization: Bearer eyJ... +Content-Type: multipart/form-data + +theme_zip=@ocean-theme.zip +submission_notes=First submission +``` + +Response (abbreviated): + +```json +{ + "success": true, + "data": { + "theme": { + "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "name": "Ocean Blue", + "slug": "ocean-blue", + "status": "pending", + "theme_type": "betterseqta", + "created_at": 1700000000, + "updated_at": 1700000000, + "published_at": null, + "rejection_reason": null + }, + "validation": { "valid": true, "warnings": [], "errors": [] } + } +} +``` + +### Sequence B — Poll my pending themes + +```http +GET /api/custom-themes/mine?status=pending +Authorization: Bearer eyJ... +``` + +### Sequence C — Handle rejection + +After admin rejects (see testing), owner fetches detail: + +```http +GET /api/custom-themes/mine/a1b2c3d4-e5f6-7890-abcd-ef1234567890 +Authorization: Bearer eyJ... +``` + +Response includes: + +```json +{ + "data": { + "theme": { + "status": "rejected", + "rejection_reason": "Banner image must be WebP under 500 KB.", + "reviewed_at": 1700200000 + } + } +} +``` + +Re-upload: + +```http +POST /api/custom-themes/mine/a1b2c3d4-e5f6-7890-abcd-ef1234567890/files +Authorization: Bearer eyJ... +Content-Type: multipart/form-data + +theme_zip=@ocean-theme-fixed.zip +``` + +### Sequence D — Public install (extension, no auth) + +```http +GET /api/custom-themes?type=betterseqta&sort=newest&limit=10 +``` + +Pick id, then: + +```http +GET /api/custom-themes/a1b2c3d4-e5f6-7890-abcd-ef1234567890/download +``` + +```json +{ + "success": true, + "data": { + "theme_json_url": "https://betterseqta.org/api/custom-themes/a1b2c3d4-e5f6-7890-abcd-ef1234567890/theme.json", + "download_count": 1 + } +} +``` + +Fetch theme JSON and apply. + +--- + +## Error handling + +| HTTP | Code / body | Client action | +|------|-------------|---------------| +| 401 | Unauthorized | Prompt login; refresh token or re-auth | +| 403 | Forbidden - you do not own this theme | Hide action; return to list | +| 404 | Theme not found | Remove stale list item | +| 409 | Approved themes cannot be edited | Disable edit UI; offer delete + re-submit | +| 409 | Theme id already in use | Ask user to change `theme.json` id (BetterSEQTA) | +| 422 | `INVALID_THEME_STRUCTURE` | Show `error.details.errors` list | +| 422 | `UNKNOWN_THEME_TYPE` | Explain expected ZIP structure (link to docs) | +| 429 | Pending cap (5) | Block submit until a pending theme is approved/rejected/deleted | +| 429 | 10 uploads / 24h | Show retry later message | +| Network | — | Retry with backoff; preserve form state | + +Parse validation responses: + +```typescript +if (!response.success && response.error?.code === 'INVALID_THEME_STRUCTURE') { + const errors = response.error.details?.errors as string[] ?? []; + // render errors in upload UI +} +``` + +--- + +## Timestamp formatting + +All theme `created_at`, `updated_at`, `published_at`, `reviewed_at` values are **Unix seconds**. + +```typescript +function formatThemeDate(unixSeconds: number): string { + return new Date(unixSeconds * 1000).toLocaleDateString(); +} +``` + +Do not treat them as ISO strings or milliseconds. + +--- + +## Testing checklist + +Use `pnpm cf:dev` with local D1 schema applied (`wrangler d1 execute bsplus-user-themes-db --local --file=server/database/user-themes/schema.sql`). + +- [ ] **Auth:** extension login → `GET /api/custom-themes/mine` returns 200 +- [ ] **Submit BetterSEQTA:** valid ZIP → `status: pending` in response +- [ ] **Submit DesQTA:** valid manifest ZIP → `theme_type: desqta`, pending +- [ ] **Public list:** pending theme **not** in `GET /api/custom-themes` +- [ ] **Admin approve:** `POST /api/admin/custom-themes/{id}/approve` (admin cookie) +- [ ] **Public list:** approved theme **appears** in `GET /api/custom-themes` +- [ ] **Download:** `GET …/download` increments count; BetterSEQTA returns `theme_json_url` +- [ ] **theme.json:** `GET /api/custom-themes/{id}/theme.json` returns valid JSON +- [ ] **Reject:** admin reject with reason → owner sees `rejection_reason` on `GET …/mine/{id}` +- [ ] **Re-upload:** `POST …/mine/{id}/files` → status back to `pending`, reason cleared +- [ ] **Metadata edit:** `PUT …/mine/{id}` on pending/rejected works; on approved returns 409 +- [ ] **Delete:** `DELETE …/mine/{id}` removes theme; public list no longer shows it +- [ ] **Rate limits:** 6th concurrent pending or 11th upload in 24h returns 429 +- [ ] **Isolation:** official `GET /api/themes` unchanged; no custom themes mixed in + +### Admin API smoke test (no UI) + +```bash +# List pending (admin session) +curl 'https://betterseqta.org/api/admin/custom-themes?status=pending' -H 'Cookie: auth_token=...' + +# Approve +curl -X POST 'https://betterseqta.org/api/admin/custom-themes/{id}/approve' -H 'Cookie: auth_token=...' + +# Reject +curl -X POST 'https://betterseqta.org/api/admin/custom-themes/{id}/reject' \ + -H 'Cookie: auth_token=...' \ + -H 'Content-Type: application/json' \ + -d '{"reason":"Does not meet quality guidelines."}' +``` + +--- + +## Implementation notes for Accounts site + +- Place "My themes" under account settings or a dedicated `/account/themes` route. +- Reuse existing auth middleware / session handling; no new OAuth scopes. +- Upload component can mirror admin theme upload UI but POST to `/api/custom-themes/mine`. +- Show clear copy: community themes are moderated and separate from the official store. +- Slug is server-generated from name (conflicts get `-2`, `-3` suffix) — do not ask users for slug on create. + +--- + +## Implementation notes for extension + +- Add API module constants: `CUSTOM_THEMES_BASE = '/api/custom-themes'`. +- Cache public list with reasonable TTL; use `updated_at` for invalidation if needed. +- When applying theme JSON from custom endpoint, image URLs point at `/api/images/custom-themes/...` — existing image fetch should work. +- Keep official theme catalog on `/api/themes` unless product decision merges UI later (APIs remain separate). + +--- + +## Questions / server changes + +If the client needs additional fields or endpoints, extend [`docs/custom-themes-api.md`](custom-themes-api.md) and the Nitro handlers under `server/api/custom-themes/` — do not write to the official themes tables or main `DB`. From dc3b77f82b7b80be6ca9249899c450f9a422b6ac Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 26 Aug 2026 21:11:53 +0930 Subject: [PATCH 4/7] fix(settings): issues with new themes systems --- .../components/themes/ThemeSelector.svelte | 239 +++++++++++------- src/interface/pages/communityThemes.svelte | 6 +- src/interface/pages/themeCreator.svelte | 12 +- src/interface/utils/themeListFilters.test.ts | 94 ++++++- src/interface/utils/themeListFilters.ts | 34 ++- src/plugins/built-in/themes/theme-manager.ts | 16 +- src/seqta/ui/colors/Manager.ts | 5 +- .../syncTransparencyEffectsClass.test.ts | 20 ++ .../ui/colors/syncTransparencyEffectsClass.ts | 10 + .../utils/Closers/closeExtensionPopup.ts | 46 +++- src/seqta/utils/listeners/StorageChanges.ts | 8 +- .../utils/settingsPopupTransition.test.ts | 30 +++ src/seqta/utils/settingsPopupTransition.ts | 43 ++++ src/seqta/utils/setupSettingsButton.ts | 61 +++-- 14 files changed, 477 insertions(+), 147 deletions(-) create mode 100644 src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts create mode 100644 src/seqta/ui/colors/syncTransparencyEffectsClass.ts create mode 100644 src/seqta/utils/settingsPopupTransition.test.ts create mode 100644 src/seqta/utils/settingsPopupTransition.ts diff --git a/src/interface/components/themes/ThemeSelector.svelte b/src/interface/components/themes/ThemeSelector.svelte index 0dd6535a..0e278354 100644 --- a/src/interface/components/themes/ThemeSelector.svelte +++ b/src/interface/components/themes/ThemeSelector.svelte @@ -3,12 +3,12 @@ import { onDestroy, onMount } from 'svelte' import browser from 'webextension-polyfill' import { themeUpdates } from '@/interface/hooks/ThemeUpdates' - import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup' import { ThemeManager } from '@/plugins/built-in/themes/theme-manager' import { cloudAuth } from '@/seqta/utils/CloudAuth' import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte' import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte' - import { filterThemesByMode, type ThemeListMode } from '@/interface/utils/themeListFilters' + import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters' + import { closeExtensionPopup, SettingsClicked } from '@/seqta/utils/Closers/closeExtensionPopup' const themeManager = ThemeManager.getInstance(); @@ -19,7 +19,9 @@ listMode?: ThemeListMode; }>(); let isDragging = $state(false); + let dragDepth = $state(0); let tempTheme = $state(null); + let fileInput = $state(null); let favoriteStatus = $state>({}); let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn); let prevLoggedIn = $state(false); @@ -72,21 +74,33 @@ } } - const handleDragOver = (e: DragEvent) => { + const allowsFileImport = $derived(listMode === 'custom'); + + const handleDragEnter = (e: DragEvent) => { + if (!allowsFileImport) return; e.preventDefault(); + dragDepth += 1; isDragging = true; } - const handleDragLeave = () => { - isDragging = false; + const handleDragOver = (e: DragEvent) => { + if (!allowsFileImport) return; + e.preventDefault(); + if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; + isDragging = true; } - const handleDrop = async (e: DragEvent) => { + const handleDragLeave = (e: DragEvent) => { + if (!allowsFileImport) return; e.preventDefault(); - isDragging = false; - const file = e.dataTransfer?.files[0]; - if (!file) return; + dragDepth -= 1; + if (dragDepth <= 0) { + dragDepth = 0; + isDragging = false; + } + } + async function importThemeFromFile(file: File) { const reader = new FileReader(); reader.onload = async (event: ProgressEvent) => { try { @@ -103,6 +117,27 @@ reader.readAsText(file); } + const handleDrop = async (e: DragEvent) => { + if (!allowsFileImport) return; + e.preventDefault(); + dragDepth = 0; + isDragging = false; + const file = e.dataTransfer?.files[0]; + if (!file) return; + await importThemeFromFile(file); + } + + const handleFileInputChange = async (e: Event) => { + const input = e.currentTarget as HTMLInputElement; + const file = input.files?.[0]; + if (file) await importThemeFromFile(file); + input.value = ''; + } + + const triggerFileUpload = () => { + fileInput?.click(); + } + const fetchThemes = async () => { themes = { themes: await themeManager.getAvailableThemes(), @@ -139,20 +174,30 @@ const openThemeCreator = async (themeId?: string) => { const { OpenThemeCreator } = await import('@/plugins/built-in/themes/ThemeCreator') OpenThemeCreator(themeId) - closeExtensionPopup() + if (!SettingsClicked) closeExtensionPopup() } const openCommunitySubmit = async () => { + if (SettingsClicked) { + const [{ requestSettingsDestination }, { requestOpenCommunityThemeSubmit }] = + await Promise.all([ + import('@/seqta/utils/settingsNavigation'), + import('@/seqta/utils/openCommunityThemeSubmit'), + ]) + requestOpenCommunityThemeSubmit() + requestSettingsDestination({ page: 'themes', view: 'community' }) + return + } + const { openCommunityThemeSubmit } = await import('@/seqta/utils/openCommunityThemeSubmit') await openCommunityThemeSubmit() closeExtensionPopup() } const customThemeActionClass = - 'flex items-center justify-center gap-2 w-full rounded-xl transition bg-zinc-100 text-xl dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800' + 'flex h-12 items-center justify-center gap-2 w-full rounded-xl transition bg-zinc-100 text-xl dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800' - const customThemeActionCompactClass = - `${customThemeActionClass} h-full min-h-0` + const customThemeActionCompactClass = customThemeActionClass const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => { e.stopPropagation(); @@ -187,29 +232,51 @@ const useTwoColumnLayout = $derived(listMode === 'downloaded' || listMode === 'custom'); +{#snippet customThemeUploadZone()} + +{/snippet} +
-
-
-
-
- - - - - - - Import Theme -
+ {#if allowsFileImport} + void handleFileInputChange(e)} + /> + {/if} + + {#if allowsFileImport && isDragging} +
+
+ + Drop theme file to import
-
+ {/if} +
{#if themes} {#each visibleThemes as theme (theme.id)} @@ -230,38 +297,45 @@ {/if} {#if !isEditMode} -
handleToggleFavorite(theme, event)} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }} - role="button" - tabindex="-1" - title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'} - > - - - -
- {#if theme.isEditable} +
+ {#if !isLocalCustomTheme(theme)} +
handleToggleFavorite(theme, event)} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }} + role="button" + tabindex="-1" + title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'} + > + + + +
+ {/if} +
{ event.stopPropagation(); void openThemeCreator(theme.id) }} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }} + class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white/80" + onclick={(event) => { event.stopPropagation(); handleShareTheme(theme) }} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }} role="button" tabindex="-1" + title="Export theme" > - +
- {/if} -
{ event.stopPropagation(); handleShareTheme(theme) }} - onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }} - role="button" - tabindex="-1" - > - + {#if isLocalCustomTheme(theme)} +
{ event.stopPropagation(); void openThemeCreator(theme.id) }} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }} + role="button" + tabindex="-1" + title="Edit theme" + > + +
+ {/if}
{/if} @@ -297,17 +371,10 @@ No custom themes yet

- Create your own theme or follow our guide to get started. + Create your own theme, or follow our guide to get started.

-
- +
+ {@render customThemeUploadZone()}
{:else if listMode === 'downloaded'}

@@ -355,36 +422,38 @@

{/if} - {#if themes && ((showNavigation && visibleThemes.length > 0) || (listMode === 'custom' && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))} + {#if allowsFileImport && themes && visibleThemes.length > 0 && !tempTheme} + {@render customThemeUploadZone()} + {/if} + + {#if themes && (listMode === 'custom' || (showNavigation && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
{#if listMode === 'custom'} -
-
- +
+ - - - View docs - -
+ + + View docs + +
@@ -424,11 +430,5 @@ ] as SettingItem[] as setting} {@render settingItem(setting)} {/each} - -
\ No newline at end of file diff --git a/src/interface/utils/themeListFilters.test.ts b/src/interface/utils/themeListFilters.test.ts index 7cd6b603..e53cfc56 100644 --- a/src/interface/utils/themeListFilters.test.ts +++ b/src/interface/utils/themeListFilters.test.ts @@ -3,7 +3,10 @@ import type { Theme } from '@/interface/types/Theme'; import { filterThemesByMode, getThemeApplyButtonStyles, + isDownloadedTheme, + isLocalCustomTheme, isStoreThemeInstalled, + resolveLocalThemeInstallId, resolveStoreVariantAccentColor, } from './themeListFilters'; @@ -30,20 +33,97 @@ function makeStoreTheme(overrides: Partial & Pick): }; } +describe('isLocalCustomTheme', () => { + it('returns true for file imports and theme creator saves', () => { + expect(isLocalCustomTheme(makeCustomTheme({ id: 'a', name: 'A' }))).toBe(true); + expect( + isLocalCustomTheme( + makeCustomTheme({ id: 'b', name: 'B', installedFromStore: false }), + ), + ).toBe(true); + }); + + it('returns false for store and community installs', () => { + expect( + isLocalCustomTheme( + makeCustomTheme({ id: 's', name: 'S', installedFromStore: true }), + ), + ).toBe(false); + expect( + isLocalCustomTheme( + makeCustomTheme({ id: 'c', name: 'C', installedFromCommunity: true }), + ), + ).toBe(false); + }); +}); + +describe('resolveLocalThemeInstallId', () => { + it('keeps the id for store installs', () => { + expect(resolveLocalThemeInstallId('theme-1', null, true, false)).toBe('theme-1'); + }); + + it('generates a new id when a local import collides with a store copy', () => { + const nextId = resolveLocalThemeInstallId( + 'theme-1', + makeCustomTheme({ id: 'theme-1', name: 'Store', installedFromStore: true }), + false, + false, + ); + expect(nextId).not.toBe('theme-1'); + }); + + it('keeps the id when replacing an existing local copy', () => { + expect( + resolveLocalThemeInstallId( + 'theme-1', + makeCustomTheme({ id: 'theme-1', name: 'Local' }), + false, + false, + ), + ).toBe('theme-1'); + }); +}); + describe('filterThemesByMode', () => { - const downloaded = makeCustomTheme({ id: 'store-1', name: 'Store Theme', isEditable: false }); - const custom = makeCustomTheme({ id: 'custom-1', name: 'Custom Theme', isEditable: true }); + const storeTheme = makeCustomTheme({ + id: 'store-1', + name: 'Store Theme', + installedFromStore: true, + }); + const communityTheme = makeCustomTheme({ + id: 'community-1', + name: 'Community Theme', + installedFromCommunity: true, + }); + const localTheme = makeCustomTheme({ id: 'local-1', name: 'Local Theme' }); + const fileImport = makeCustomTheme({ + id: 'file-1', + name: 'Imported Theme', + installedFromStore: false, + isEditable: false, + }); it('returns all themes in all mode', () => { - expect(filterThemesByMode([downloaded, custom], 'all')).toEqual([downloaded, custom]); + expect(filterThemesByMode([storeTheme, localTheme], 'all')).toEqual([storeTheme, localTheme]); }); - it('returns only non-editable themes in downloaded mode', () => { - expect(filterThemesByMode([downloaded, custom], 'downloaded')).toEqual([downloaded]); + it('returns store and community themes in downloaded mode', () => { + expect( + filterThemesByMode([storeTheme, communityTheme, localTheme, fileImport], 'downloaded'), + ).toEqual([storeTheme, communityTheme]); }); - it('returns only editable themes in custom mode', () => { - expect(filterThemesByMode([downloaded, custom], 'custom')).toEqual([custom]); + it('returns local/file themes in custom mode', () => { + expect( + filterThemesByMode([storeTheme, communityTheme, localTheme, fileImport], 'custom'), + ).toEqual([localTheme, fileImport]); + }); + + it('isDownloadedTheme is the inverse of isLocalCustomTheme for known sources', () => { + expect(isDownloadedTheme(storeTheme)).toBe(true); + expect(isLocalCustomTheme(storeTheme)).toBe(false); + expect(isDownloadedTheme(localTheme)).toBe(false); + expect(isLocalCustomTheme(localTheme)).toBe(true); }); }); diff --git a/src/interface/utils/themeListFilters.ts b/src/interface/utils/themeListFilters.ts index 41e54e10..66666730 100644 --- a/src/interface/utils/themeListFilters.ts +++ b/src/interface/utils/themeListFilters.ts @@ -6,10 +6,40 @@ export type ThemeListMode = 'downloaded' | 'custom' | 'all'; const DEFAULT_THEME_ACCENT = 'rgba(0, 123, 255, 1)'; +/** Local themes: created in the editor or imported from a file (not store/community). */ +export function isLocalCustomTheme(theme: CustomTheme): boolean { + return theme.installedFromStore !== true && theme.installedFromCommunity !== true; +} + +/** Themes installed from the official store or community API. */ +export function isDownloadedTheme(theme: CustomTheme): boolean { + return theme.installedFromStore === true || theme.installedFromCommunity === true; +} + +/** + * When importing a local copy of a theme whose id already belongs to a store/community + * install, use a new id so both copies can coexist. + */ +export function resolveLocalThemeInstallId( + themeId: string, + existing: Pick | null, + fromStore: boolean, + fromCommunity: boolean, +): string { + if (fromStore || fromCommunity) return themeId; + if ( + existing && + (existing.installedFromStore === true || existing.installedFromCommunity === true) + ) { + return crypto.randomUUID(); + } + return themeId; +} + export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): CustomTheme[] { if (mode === 'all') return themes; - if (mode === 'custom') return themes.filter((theme) => theme.isEditable === true); - return themes.filter((theme) => theme.isEditable !== true); + if (mode === 'custom') return themes.filter(isLocalCustomTheme); + return themes.filter(isDownloadedTheme); } export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean { diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index ef25a197..a5c1a0c8 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -23,6 +23,7 @@ import { type ThemePageSyncInput, } from "@/seqta/utils/patchThemeImagesPageContext"; import { verboseDebug, verboseInfo } from "@/utils/verboseLog"; +import { resolveLocalThemeInstallId } from "@/interface/utils/themeListFilters"; import { clearThemeRuntime, injectThemeDom, @@ -704,6 +705,15 @@ export class ThemeManager { const fromStore = meta?.fromStore ?? false; const fromCommunity = meta?.fromCommunity ?? false; const serverUpdatedAtSec = meta?.serverUpdatedAtSec; + const isLocalInstall = !fromStore && !fromCommunity; + + const existingTheme = (await localforage.getItem(themeData.id)) as CustomTheme | null; + const themeId = resolveLocalThemeInstallId( + themeData.id, + existingTheme, + fromStore, + fromCommunity, + ); // Handle cover image (optional) let coverImageBlob = null; @@ -740,17 +750,17 @@ export class ThemeManager { .filter((img) => img !== null) ?? []; const theme: LoadedCustomTheme = { - id: themeData.id, + id: themeId, name: themeData.name, description: themeData.description || "", - webURL: themeData.id, + webURL: themeId, coverImage: coverImageBlob, CustomImages: images, CustomCSS: themeData.CustomCSS || "", defaultColour: themeData.defaultColour || "rgba(0, 123, 255, 1)", CanChangeColour: themeData.CanChangeColour ?? true, allowBackgrounds: true, - isEditable: false, + isEditable: isLocalInstall, hideThemeName: themeData.hideThemeName ?? false, forceDark: themeData.forceDark, installedFromStore: fromStore, diff --git a/src/seqta/ui/colors/Manager.ts b/src/seqta/ui/colors/Manager.ts index bb55220c..f0f1fbc0 100644 --- a/src/seqta/ui/colors/Manager.ts +++ b/src/seqta/ui/colors/Manager.ts @@ -6,6 +6,7 @@ import ColorLuminance from "./ColorLuminance"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { getAdaptiveColour } from "@/seqta/utils/adaptiveThemeColour"; import { getCustomThemeAdaptiveCssVariableBindings } from "@/seqta/ui/colors/customThemeAdaptiveBindings"; +import { syncTransparencyEffectsClass } from "@/seqta/ui/colors/syncTransparencyEffectsClass"; import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl"; import darkLogo from "@/resources/icons/betterseqta-light-full.png"; @@ -126,9 +127,7 @@ function getRepresentativeRgbChannels(s: string): { r: number; g: number; b: num } function applyColorsWith(selectedColor: string) { - if (settingsState.transparencyEffects) { - document.documentElement.classList.add("transparencyEffects"); - } + syncTransparencyEffectsClass(settingsState.transparencyEffects === true); // Common properties, always applied const commonProps = { diff --git a/src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts b/src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts new file mode 100644 index 00000000..fd8dd926 --- /dev/null +++ b/src/seqta/ui/colors/syncTransparencyEffectsClass.test.ts @@ -0,0 +1,20 @@ +/** @jest-environment jsdom */ + +import { syncTransparencyEffectsClass } from "./syncTransparencyEffectsClass"; + +describe("syncTransparencyEffectsClass", () => { + beforeEach(() => { + document.documentElement.classList.remove("transparencyEffects"); + }); + + it("adds the transparency class when enabled", () => { + syncTransparencyEffectsClass(true); + expect(document.documentElement.classList.contains("transparencyEffects")).toBe(true); + }); + + it("removes the transparency class when disabled", () => { + document.documentElement.classList.add("transparencyEffects"); + syncTransparencyEffectsClass(false); + expect(document.documentElement.classList.contains("transparencyEffects")).toBe(false); + }); +}); diff --git a/src/seqta/ui/colors/syncTransparencyEffectsClass.ts b/src/seqta/ui/colors/syncTransparencyEffectsClass.ts new file mode 100644 index 00000000..cf7c7138 --- /dev/null +++ b/src/seqta/ui/colors/syncTransparencyEffectsClass.ts @@ -0,0 +1,10 @@ +export function syncTransparencyEffectsClass( + enabled: boolean, + root: HTMLElement = document.documentElement, +): void { + if (enabled) { + root.classList.add("transparencyEffects"); + } else { + root.classList.remove("transparencyEffects"); + } +} diff --git a/src/seqta/utils/Closers/closeExtensionPopup.ts b/src/seqta/utils/Closers/closeExtensionPopup.ts index 20d67f22..d71e06f6 100644 --- a/src/seqta/utils/Closers/closeExtensionPopup.ts +++ b/src/seqta/utils/Closers/closeExtensionPopup.ts @@ -2,30 +2,48 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { animate } from "motion"; import { settingsPopup } from "@/seqta/utils/settingsPopup"; +import { + beginSettingsPopupTransition, + isCurrentSettingsPopupTransition, + resetSettingsPopupVisualState, + trackSettingsPopupAnimation, +} from "@/seqta/utils/settingsPopupTransition"; export let SettingsClicked = false; export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { - if (!extensionPopup) - extensionPopup = document.getElementById("ExtensionPopup")!; + const generation = beginSettingsPopupTransition(); + changeSettingsClicked(false); + + if (!extensionPopup) { + extensionPopup = document.getElementById("ExtensionPopup") ?? undefined; + } + if (!extensionPopup) return false; extensionPopup.classList.add("hide"); + resetSettingsPopupVisualState(extensionPopup); + if (settingsState.animations) { const panel = extensionPopup.shadowRoot?.querySelector( "[data-settings-panel]", ); - animate(1, 0, { - onUpdate: (progress) => { - extensionPopup.style.opacity = Math.max(0, progress).toString(); - }, - duration: 0.18, - ease: "easeIn", - }); + trackSettingsPopupAnimation( + animate(1, 0, { + onUpdate: (progress) => { + if (!isCurrentSettingsPopupTransition(generation)) return; + extensionPopup.style.opacity = Math.max(0, progress).toString(); + }, + duration: 0.18, + ease: "easeIn", + }), + ); if (panel) { - animate( - panel, - { scale: [1, 0], opacity: [1, 0] }, - { duration: 0.18, ease: "easeIn" }, + trackSettingsPopupAnimation( + animate( + panel, + { scale: [1, 0], opacity: [1, 0] }, + { duration: 0.18, ease: "easeIn" }, + ), ); } } else { @@ -33,7 +51,7 @@ export const closeExtensionPopup = (extensionPopup?: HTMLElement) => { } settingsPopup.triggerClose(); - return (SettingsClicked = false); + return false; }; export function changeSettingsClicked(newVal: boolean) { diff --git a/src/seqta/utils/listeners/StorageChanges.ts b/src/seqta/utils/listeners/StorageChanges.ts index 720601ff..7064632a 100644 --- a/src/seqta/utils/listeners/StorageChanges.ts +++ b/src/seqta/utils/listeners/StorageChanges.ts @@ -1,6 +1,6 @@ import { settingsState } from "./SettingsState"; import { updateAllColors } from "@/seqta/ui/colors/Manager"; -import { applySelectedFont } from "@/seqta/ui/fonts/Manager"; +import { syncTransparencyEffectsClass } from "@/seqta/ui/colors/syncTransparencyEffectsClass"; // Shortcuts rendering import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts"; @@ -85,10 +85,6 @@ export class StorageChangeHandler { } private handleTransparencyEffectsChange(newValue: boolean) { - if (newValue) { - document.documentElement.classList.add("transparencyEffects"); - } else { - document.documentElement.classList.remove("transparencyEffects"); - } + syncTransparencyEffectsClass(newValue === true); } } diff --git a/src/seqta/utils/settingsPopupTransition.test.ts b/src/seqta/utils/settingsPopupTransition.test.ts new file mode 100644 index 00000000..ae4dbaaf --- /dev/null +++ b/src/seqta/utils/settingsPopupTransition.test.ts @@ -0,0 +1,30 @@ +/** @jest-environment jsdom */ + +import { + beginSettingsPopupTransition, + isCurrentSettingsPopupTransition, + stopSettingsPopupAnimations, + trackSettingsPopupAnimation, +} from "./settingsPopupTransition"; + +describe("settingsPopupTransition", () => { + it("invalidates prior transitions when a new one begins", () => { + const first = beginSettingsPopupTransition(); + expect(isCurrentSettingsPopupTransition(first)).toBe(true); + + const second = beginSettingsPopupTransition(); + expect(isCurrentSettingsPopupTransition(first)).toBe(false); + expect(isCurrentSettingsPopupTransition(second)).toBe(true); + }); + + it("clears tracked animations when a new transition begins", () => { + const stop = jest.fn(); + stopSettingsPopupAnimations(); + + beginSettingsPopupTransition(); + trackSettingsPopupAnimation({ stop } as never); + + beginSettingsPopupTransition(); + expect(stop).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/seqta/utils/settingsPopupTransition.ts b/src/seqta/utils/settingsPopupTransition.ts new file mode 100644 index 00000000..b22bc07d --- /dev/null +++ b/src/seqta/utils/settingsPopupTransition.ts @@ -0,0 +1,43 @@ +import type { AnimationPlaybackControls } from "motion"; + +let popupTransitionGeneration = 0; +let activePopupAnimations: AnimationPlaybackControls[] = []; + +export function beginSettingsPopupTransition(): number { + popupTransitionGeneration += 1; + stopSettingsPopupAnimations(); + return popupTransitionGeneration; +} + +export function isCurrentSettingsPopupTransition(generation: number): boolean { + return generation === popupTransitionGeneration; +} + +export function trackSettingsPopupAnimation( + controls: AnimationPlaybackControls, +): void { + activePopupAnimations.push(controls); +} + +export function stopSettingsPopupAnimations(): void { + for (const animation of activePopupAnimations) { + try { + animation.stop(); + } catch { + /* ignore */ + } + } + activePopupAnimations = []; +} + +export function resetSettingsPopupVisualState(extensionPopup: HTMLElement): void { + extensionPopup.style.removeProperty("opacity"); + extensionPopup.style.removeProperty("transition"); + const panel = extensionPopup.shadowRoot?.querySelector( + "[data-settings-panel]", + ); + if (panel) { + panel.style.removeProperty("opacity"); + panel.style.removeProperty("scale"); + } +} diff --git a/src/seqta/utils/setupSettingsButton.ts b/src/seqta/utils/setupSettingsButton.ts index 0cabfee0..ca478f7d 100644 --- a/src/seqta/utils/setupSettingsButton.ts +++ b/src/seqta/utils/setupSettingsButton.ts @@ -7,6 +7,11 @@ import { animate } from "motion"; import { settingsState } from "./listeners/SettingsState"; import { renderSettingsIfNeeded } from "./Adders/AddExtensionSettings"; import { delay } from "./delay"; +import { + beginSettingsPopupTransition, + isCurrentSettingsPopupTransition, + trackSettingsPopupAnimation, +} from "./settingsPopupTransition"; export function setupSettingsButton() { const AddedSettings = document.getElementById("AddedSettings"); @@ -26,38 +31,60 @@ export function setupSettingsButton() { } export async function openSettingsPopup(): Promise { - if (SettingsClicked && document.getElementById("ExtensionPopup")) return; - - // Re-query each time — Engage SPA navigations can recreate the host. let extensionPopup = document.getElementById("ExtensionPopup"); + if ( + SettingsClicked && + extensionPopup && + !extensionPopup.classList.contains("hide") + ) { + return; + } + + const generation = beginSettingsPopupTransition(); + changeSettingsClicked(true); + if (!extensionPopup) { const { addExtensionSettings } = await import("./Adders/AddExtensionSettings"); addExtensionSettings(); extensionPopup = document.getElementById("ExtensionPopup"); } - if (!extensionPopup) return; + if (!extensionPopup) { + changeSettingsClicked(false); + return; + } await renderSettingsIfNeeded(); + if (!isCurrentSettingsPopupTransition(generation)) return; + await delay(30); + if (!isCurrentSettingsPopupTransition(generation)) return; extensionPopup.style.transform = "none"; + extensionPopup.classList.remove("hide"); + const panel = extensionPopup.shadowRoot?.querySelector( "[data-settings-panel]", ); if (settingsState.animations) { - animate(0, 1, { - onUpdate: (progress) => { - extensionPopup.style.opacity = progress.toString(); - }, - type: "spring", - stiffness: 280, - damping: 20, - }); + extensionPopup.style.opacity = "0"; + trackSettingsPopupAnimation( + animate(0, 1, { + onUpdate: (progress) => { + if (!isCurrentSettingsPopupTransition(generation)) return; + extensionPopup.style.opacity = progress.toString(); + }, + type: "spring", + stiffness: 280, + damping: 20, + }), + ); if (panel) { - animate( - panel, - { scale: [0, 1], opacity: [0, 1] }, - { type: "spring", stiffness: 330, damping: 30 }, + trackSettingsPopupAnimation( + animate( + panel, + { scale: [0, 1], opacity: [0, 1] }, + { type: "spring", stiffness: 330, damping: 30 }, + ), ); } } else { @@ -68,6 +95,4 @@ export async function openSettingsPopup(): Promise { panel.style.opacity = "1"; } } - extensionPopup.classList.remove("hide"); - changeSettingsClicked(true); } From b064f2df8f05f565fdbe6f87240d60bc084e49aa Mon Sep 17 00:00:00 2001 From: StroepWafel Date: Wed, 26 Aug 2026 21:32:32 +0930 Subject: [PATCH 5/7] fix(customthemessettings): box order --- .../components/themes/ThemeSelector.svelte | 34 ++++++++----------- src/interface/pages/communityThemes.svelte | 8 +++-- src/interface/pages/store.svelte | 8 +++-- src/interface/utils/themeListFilters.test.ts | 27 +++++++++++++++ src/interface/utils/themeListFilters.ts | 12 +++++++ 5 files changed, 63 insertions(+), 26 deletions(-) diff --git a/src/interface/components/themes/ThemeSelector.svelte b/src/interface/components/themes/ThemeSelector.svelte index 0e278354..dd8718f4 100644 --- a/src/interface/components/themes/ThemeSelector.svelte +++ b/src/interface/components/themes/ThemeSelector.svelte @@ -232,18 +232,6 @@ const useTwoColumnLayout = $derived(listMode === 'downloaded' || listMode === 'custom'); -{#snippet customThemeUploadZone()} - -{/snippet} -
+ {#if allowsFileImport} + + {/if} {#if themes} {#each visibleThemes as theme (theme.id)}
{/if} - {#if allowsFileImport && themes && visibleThemes.length > 0 && !tempTheme} - {@render customThemeUploadZone()} - {/if} - {#if themes && (listMode === 'custom' || (showNavigation && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
diff --git a/src/interface/pages/communityThemes.svelte b/src/interface/pages/communityThemes.svelte index 84d82826..1494df41 100644 --- a/src/interface/pages/communityThemes.svelte +++ b/src/interface/pages/communityThemes.svelte @@ -34,7 +34,7 @@ } from "@/seqta/utils/customThemes/buildThemeUploadFormData"; import type { CustomThemeOwner, CustomThemeFile } from "@/seqta/utils/customThemes/types"; import type { LoadedCustomTheme } from "@/types/CustomThemes"; - import { isLocalCustomTheme } from "@/interface/utils/themeListFilters"; + import { getCommunityInstalledThemeIds, isLocalCustomTheme } from "@/interface/utils/themeListFilters"; let { searchTerm, @@ -94,10 +94,12 @@ async function refreshInstalledThemes() { const themes = await themeManager.getAvailableThemes(); - currentThemes = themes.filter((t) => t !== null).map((t) => t.id); + currentThemes = getCommunityInstalledThemeIds(themes); selectedThemeId = themeManager.getSelectedThemeId() || ""; installedThemeColors = Object.fromEntries( - themes.filter((t) => t != null).map((t) => [t.id, t.defaultColour]), + themes + .filter((t) => t != null && t.installedFromCommunity === true) + .map((t) => [t.id, t.defaultColour]), ); } diff --git a/src/interface/pages/store.svelte b/src/interface/pages/store.svelte index 5df465ca..1ee39425 100644 --- a/src/interface/pages/store.svelte +++ b/src/interface/pages/store.svelte @@ -16,7 +16,7 @@ import Backgrounds from '../components/store/Backgrounds.svelte' import { cloudAuth } from '@/seqta/utils/CloudAuth' import SignInToFavoriteModal from '../components/SignInToFavoriteModal.svelte' - import { consumePendingHighlightThemeId } from '@/seqta/utils/openThemeStoreWithHighlight' + import { getStoreInstalledThemeIds } from '@/interface/utils/themeListFilters' const themeManager = ThemeManager.getInstance(); type StoreTab = 'themes' | 'backgrounds'; @@ -75,10 +75,12 @@ const fetchCurrentThemes = async () => { const themes = await themeManager.getAvailableThemes(); - currentThemes = themes.filter(theme => theme !== null).map(theme => theme.id); + currentThemes = getStoreInstalledThemeIds(themes); selectedThemeId = themeManager.getSelectedThemeId() || ''; installedThemeColors = Object.fromEntries( - themes.filter((theme) => theme != null).map((theme) => [theme.id, theme.defaultColour]), + themes + .filter((theme) => theme != null && theme.installedFromStore === true) + .map((theme) => [theme.id, theme.defaultColour]), ); }; diff --git a/src/interface/utils/themeListFilters.test.ts b/src/interface/utils/themeListFilters.test.ts index e53cfc56..d1389027 100644 --- a/src/interface/utils/themeListFilters.test.ts +++ b/src/interface/utils/themeListFilters.test.ts @@ -3,6 +3,8 @@ import type { Theme } from '@/interface/types/Theme'; import { filterThemesByMode, getThemeApplyButtonStyles, + getCommunityInstalledThemeIds, + getStoreInstalledThemeIds, isDownloadedTheme, isLocalCustomTheme, isStoreThemeInstalled, @@ -127,6 +129,31 @@ describe('filterThemesByMode', () => { }); }); +describe('getStoreInstalledThemeIds', () => { + it('returns only store-installed theme ids', () => { + const themes = [ + makeCustomTheme({ id: 'store-1', name: 'Store', installedFromStore: true }), + makeCustomTheme({ id: 'local-1', name: 'Local' }), + makeCustomTheme({ + id: 'same-as-store', + name: 'Imported copy', + installedFromStore: false, + }), + ]; + expect(getStoreInstalledThemeIds(themes)).toEqual(['store-1']); + }); +}); + +describe('getCommunityInstalledThemeIds', () => { + it('returns only community-installed theme ids', () => { + const themes = [ + makeCustomTheme({ id: 'community-1', name: 'Community', installedFromCommunity: true }), + makeCustomTheme({ id: 'local-1', name: 'Local' }), + ]; + expect(getCommunityInstalledThemeIds(themes)).toEqual(['community-1']); + }); +}); + describe('isStoreThemeInstalled', () => { it('returns true when master id is installed', () => { const theme = makeStoreTheme({ id: 'master-1', name: 'Master' }); diff --git a/src/interface/utils/themeListFilters.ts b/src/interface/utils/themeListFilters.ts index 66666730..d7b4d4ea 100644 --- a/src/interface/utils/themeListFilters.ts +++ b/src/interface/utils/themeListFilters.ts @@ -42,6 +42,18 @@ export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): return themes.filter(isDownloadedTheme); } +/** Installed theme ids from the official store only (excludes file imports / custom copies). */ +export function getStoreInstalledThemeIds(themes: CustomTheme[]): string[] { + return themes.filter((theme) => theme.installedFromStore === true).map((theme) => theme.id); +} + +/** Installed theme ids from the community API only (excludes file imports / custom copies). */ +export function getCommunityInstalledThemeIds(themes: CustomTheme[]): string[] { + return themes + .filter((theme) => theme.installedFromCommunity === true) + .map((theme) => theme.id); +} + export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean { const installed = new Set(installedIds); if (installed.has(theme.id)) return true; From e11358d7287f2da760601a4168495216fda67e81 Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Tue, 29 Sep 2026 10:49:49 +0930 Subject: [PATCH 6/7] feat: polish, enhance, cleanup and finilse theme builder for community themes --- src/background.ts | 9 +- src/background/customThemesHandlers.ts | 39 +- src/background/searchThemeStockPhotos.ts | 57 ++ src/css/injected.scss | 7 +- src/interface/components/Slider.svelte | 1 + .../communityThemes/BrowsePanel.svelte | 66 ++ .../communityThemes/ModalFrame.svelte | 38 + .../communityThemes/MyThemesPanel.svelte | 226 +++++ .../OwnerThemeDetailModal.svelte | 190 +++++ .../themes/ThemePlaceholderCover.svelte | 15 + .../components/themes/ThemeSelector.svelte | 62 +- .../hooks/communityThemesState.svelte.ts | 275 ++++++ .../hooks/themeBuilderPanel.svelte.ts | 13 + src/interface/index.ts | 2 + src/interface/pages/communityThemes.svelte | 798 +----------------- src/interface/pages/settings.svelte | 143 ++-- .../pages/settings/sections/advanced.svelte | 51 +- src/interface/pages/settings/theme.svelte | 13 + src/interface/pages/themeCreator.svelte | 463 ++++++++-- src/interface/utils/buildSimpleTheme.test.ts | 37 + src/interface/utils/buildSimpleTheme.ts | 11 + src/interface/utils/themeBuilderDraft.ts | 138 +++ src/interface/utils/themeCreatorMeta.ts | 104 +++ .../utils/themePlaceholderCover.test.ts | 17 + src/interface/utils/themePlaceholderCover.ts | 46 + src/plugins/built-in/themes/ThemeCreator.ts | 112 +-- src/plugins/built-in/themes/theme-manager.ts | 126 ++- .../built-in/themes/themeCreatorLayout.ts | 34 + .../themes/themeCreatorPersistence.ts | 24 + src/seqta/utils/DevApiBase.test.ts | 15 + src/seqta/utils/DevApiBase.ts | 57 +- src/seqta/utils/apiBasePolicy.ts | 14 + src/seqta/utils/customThemes/apiErrors.ts | 16 + src/seqta/utils/customThemes/client.test.ts | 28 +- src/seqta/utils/customThemes/client.ts | 47 +- .../utils/customThemes/parseApiEnvelope.ts | 92 +- .../utils/customThemes/submitLocalTheme.ts | 25 + src/seqta/utils/launchPageThemeBuilder.ts | 8 + .../utils/openCommunityThemeSubmit.test.ts | 7 + src/seqta/utils/openCommunityThemeSubmit.ts | 33 +- src/seqta/utils/searchThemeStockPhotos.ts | 25 + src/seqta/utils/themeImagePagePatch.js | 4 + src/types/CustomThemes.ts | 24 + 43 files changed, 2414 insertions(+), 1098 deletions(-) create mode 100644 src/background/searchThemeStockPhotos.ts create mode 100644 src/interface/components/communityThemes/BrowsePanel.svelte create mode 100644 src/interface/components/communityThemes/ModalFrame.svelte create mode 100644 src/interface/components/communityThemes/MyThemesPanel.svelte create mode 100644 src/interface/components/communityThemes/OwnerThemeDetailModal.svelte create mode 100644 src/interface/components/themes/ThemePlaceholderCover.svelte create mode 100644 src/interface/hooks/communityThemesState.svelte.ts create mode 100644 src/interface/hooks/themeBuilderPanel.svelte.ts create mode 100644 src/interface/utils/buildSimpleTheme.test.ts create mode 100644 src/interface/utils/buildSimpleTheme.ts create mode 100644 src/interface/utils/themeBuilderDraft.ts create mode 100644 src/interface/utils/themeCreatorMeta.ts create mode 100644 src/interface/utils/themePlaceholderCover.test.ts create mode 100644 src/interface/utils/themePlaceholderCover.ts create mode 100644 src/plugins/built-in/themes/themeCreatorLayout.ts create mode 100644 src/plugins/built-in/themes/themeCreatorPersistence.ts create mode 100644 src/seqta/utils/DevApiBase.test.ts create mode 100644 src/seqta/utils/apiBasePolicy.ts create mode 100644 src/seqta/utils/customThemes/apiErrors.ts create mode 100644 src/seqta/utils/customThemes/submitLocalTheme.ts create mode 100644 src/seqta/utils/launchPageThemeBuilder.ts create mode 100644 src/seqta/utils/searchThemeStockPhotos.ts diff --git a/src/background.ts b/src/background.ts index fd2863fe..4147de14 100644 --- a/src/background.ts +++ b/src/background.ts @@ -20,6 +20,7 @@ import { registerOutlookCalendarMessageHandlers, } from "./background/calendarBackground"; import { createCustomThemesHandlers } from "./background/customThemesHandlers"; +import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos"; /** * Session-only dev-mode override of the content API base. @@ -33,6 +34,8 @@ import { createCustomThemesHandlers } from "./background/customThemesHandlers"; const DEFAULT_API_BASE = "https://betterseqta.org"; let DEV_API_BASE: string | null = null; function apiBase(): string { + // Extension dev builds always hit production (see DevApiBase.ts). + if (import.meta.env.DEV) return DEFAULT_API_BASE; return DEV_API_BASE ?? DEFAULT_API_BASE; } @@ -470,6 +473,10 @@ function handleSetDevApiBase( sender?: browser.Runtime.MessageSender, ): boolean { if (!isTrustedSender(sender)) return false; + if (import.meta.env.DEV) { + DEV_API_BASE = null; + return false; + } const url = typeof request?.url === "string" ? request.url.trim() : null; if (url && /^https?:\/\//.test(url)) { DEV_API_BASE = url.replace(/\/$/, ""); @@ -482,11 +489,11 @@ function handleSetDevApiBase( const customThemesHandlers = createCustomThemesHandlers({ apiBase, getAccessTokenFromStorage, - parseJsonResponse, }); const MESSAGE_HANDLERS: Record = { ...customThemesHandlers, + searchThemeStockPhotos: handleSearchThemeStockPhotos, reloadTabs: () => reloadSeqtaPages(), setDevApiBase: handleSetDevApiBase, extensionPages: (req) => { diff --git a/src/background/customThemesHandlers.ts b/src/background/customThemesHandlers.ts index 12200d30..2b8b6fc3 100644 --- a/src/background/customThemesHandlers.ts +++ b/src/background/customThemesHandlers.ts @@ -1,3 +1,5 @@ +import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope"; + type MessageSender = { (response?: unknown): void }; type UploadFilePart = { @@ -46,8 +48,22 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData { export function createCustomThemesHandlers(deps: { apiBase: () => string; getAccessTokenFromStorage: () => Promise; - parseJsonResponse: (r: Response) => Promise; }): Record boolean> { + async function readCustomThemesResponse(r: Response): Promise> { + const text = await r.text(); + let body: unknown = {}; + try { + body = text ? JSON.parse(text) : {}; + } catch { + body = null; + } + const normalized = normalizeCustomThemeApiResponse(body, r.status, text); + if (!r.ok || normalized.success === false) { + console.error("[BetterSEQTA+ CustomThemes]", r.status, r.url, normalized); + } + return normalized; + } + async function customThemesJsonFetch( path: string, init: RequestInit = {}, @@ -64,16 +80,13 @@ export function createCustomThemesHandlers(deps: { } headers.Authorization = `Bearer ${token}`; } - const r = await fetch(`${deps.apiBase()}${path}`, { + const url = `${deps.apiBase()}${path}`; + const r = await fetch(url, { ...init, headers, cache: "no-store", }); - const json = await deps.parseJsonResponse(r); - if (json && typeof json === "object") { - return { ...json, httpStatus: r.status }; - } - return { success: false, error: `HTTP ${r.status}`, httpStatus: r.status }; + return await readCustomThemesResponse(r); } async function customThemesMultipartPost( @@ -85,17 +98,14 @@ export function createCustomThemesHandlers(deps: { return { success: false, error: "Not authenticated", httpStatus: 401 }; } const form = buildFormDataFromPayload(payload); - const r = await fetch(`${deps.apiBase()}${path}`, { + const url = `${deps.apiBase()}${path}`; + const r = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${token}` }, body: form, cache: "no-store", }); - const json = await deps.parseJsonResponse(r); - if (json && typeof json === "object") { - return { ...json, httpStatus: r.status }; - } - return { success: false, error: `HTTP ${r.status}`, httpStatus: r.status }; + return await readCustomThemesResponse(r); } function handleFetchCustomThemes(request: any, sendResponse: MessageSender): boolean { @@ -183,7 +193,8 @@ export function createCustomThemesHandlers(deps: { console.error("[Background] submitCustomTheme error:", err); sendResponse({ success: false, - error: err instanceof Error ? err.message : "Upload failed", + error: { message: err instanceof Error ? err.message : "Upload failed" }, + httpStatus: 0, }); } })(); diff --git a/src/background/searchThemeStockPhotos.ts b/src/background/searchThemeStockPhotos.ts new file mode 100644 index 00000000..08917489 --- /dev/null +++ b/src/background/searchThemeStockPhotos.ts @@ -0,0 +1,57 @@ +type MessageSender = { (response?: unknown): void }; + +type StockPhotoResult = { title: string; thumbUrl: string; imageUrl: string }; + +export function handleSearchThemeStockPhotos( + request: { query?: string; limit?: number }, + sendResponse: MessageSender, +): boolean { + const query = request.query?.trim(); + if (!query) { + sendResponse({ success: false, error: "Missing query" }); + return false; + } + const limit = Math.min(Math.max(request.limit ?? 8, 1), 12); + + void (async () => { + try { + const params = new URLSearchParams({ + action: "query", + origin: "*", + format: "json", + generator: "search", + gsrsearch: query, + gsrnamespace: "6", + gsrlimit: String(limit), + prop: "imageinfo", + iiprop: "url", + iiurlwidth: "1400", + }); + const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`); + const json = (await res.json()) as { + query?: { pages?: Record }; + }; + const pages = json.query?.pages ?? {}; + const results: StockPhotoResult[] = Object.values(pages) + .map((page) => { + const info = page.imageinfo?.[0]; + if (!info?.url) return null; + return { + title: page.title?.replace(/^File:/, "") ?? "Photo", + thumbUrl: info.thumburl ?? info.url, + imageUrl: info.url, + }; + }) + .filter((row): row is StockPhotoResult => row != null); + + sendResponse({ success: true, results }); + } catch (err) { + sendResponse({ + success: false, + error: err instanceof Error ? err.message : "Search failed", + }); + } + })(); + + return true; +} diff --git a/src/css/injected.scss b/src/css/injected.scss index d0b6486b..b78f8ca9 100644 --- a/src/css/injected.scss +++ b/src/css/injected.scss @@ -150,9 +150,10 @@ html:not(.dark) .legacy-root { #themeCreator { position: fixed; + top: 0; right: 0; height: 100%; - z-index: 100; + z-index: 10050; } .resizeBar { @@ -180,15 +181,15 @@ html:not(.dark) .legacy-root { } .themeCloseButton { - position: absolute !important; + position: fixed !important; color: var(--text-primary) !important; font-size: x-large !important; top: 5px; right: 5px; + z-index: 10060 !important; border-radius: 80px !important; padding: 8px; cursor: pointer; - z-index: 10000; } .modaliser-container { diff --git a/src/interface/components/Slider.svelte b/src/interface/components/Slider.svelte index c4a69d8c..b997a109 100644 --- a/src/interface/components/Slider.svelte +++ b/src/interface/components/Slider.svelte @@ -17,6 +17,7 @@ step={step} bind:value={state} style={`background: linear-gradient(to right, #30d259ad 0%, #30D259 ${percentage}%, #dddddd ${percentage}%)`} + oninput={(e) => onChange(Number(e.currentTarget.value))} onchange={(e) => onChange(Number(e.currentTarget.value))} class="w-full h-1 rounded-full appearance-none cursor-pointer slider" /> diff --git a/src/interface/components/communityThemes/BrowsePanel.svelte b/src/interface/components/communityThemes/BrowsePanel.svelte new file mode 100644 index 00000000..bbc28e6e --- /dev/null +++ b/src/interface/components/communityThemes/BrowsePanel.svelte @@ -0,0 +1,66 @@ + + +{#if state.browseLoading} +
+ {#each Array(6) as _, i (i)} + + {/each} +
+{:else if state.browseError} +
+

Couldn't load community themes

+

{state.browseError}

+ +
+{:else} + (state.displayTheme = theme)} + toggleFavorite={() => {}} + isLoggedIn={false} + installedThemeIds={state.currentThemes} + variant="community" + /> + {#if state.displayTheme} + (state.displayTheme = t)} + selectedThemeId={state.selectedThemeId} + installedThemeColors={state.installedThemeColors} + variant="community" + onInstall={async (themeId) => { + if (state.displayTheme) await state.installCommunityTheme(themeId, state.displayTheme); + }} + onRemove={(id) => void state.removeInstalledTheme(id)} + onApply={(id) => void state.applyInstalledTheme(id)} + /> + {/if} +{/if} diff --git a/src/interface/components/communityThemes/ModalFrame.svelte b/src/interface/components/communityThemes/ModalFrame.svelte new file mode 100644 index 00000000..9093ac87 --- /dev/null +++ b/src/interface/components/communityThemes/ModalFrame.svelte @@ -0,0 +1,38 @@ + + +{#if open} + +{/if} diff --git a/src/interface/components/communityThemes/MyThemesPanel.svelte b/src/interface/components/communityThemes/MyThemesPanel.svelte new file mode 100644 index 00000000..18fc3f3b --- /dev/null +++ b/src/interface/components/communityThemes/MyThemesPanel.svelte @@ -0,0 +1,226 @@ + + +{#if !state.cloudLoggedIn} +
+

Sign in to manage your themes

+

+ Submit themes for review and track pending, approved, or rejected submissions. +

+ +
+{:else} +
+

Themes on this device

+

+ Submit a custom theme you created or imported without opening the theme builder. +

+ {#if localSubmitError} +

{localSubmitError}

+ {/if} + {#if localThemesLoading} +
+ {#each Array(2) as _, i (i)} + + {/each} +
+ {:else if localThemes.length === 0} +

+ No local custom themes yet. Use Create & submit above or build one in Custom themes settings. +

+ {:else} +
    + {#each localThemes as theme (theme.id)} +
  • + {#if theme.coverImage} + + {:else} + + {/if} +
    + {theme.name || "Untitled theme"} + {#if theme.description} +

    {theme.description}

    + {/if} +
    +
    + + +
    +
  • + {/each} +
+ {/if} +
+ +

Community submissions

+
+ {#each statusFilters as status (status)} + + {/each} +
+ + {#if state.myLoading} +
+ {#each Array(4) as _, i (i)} + + {/each} +
+ {:else if state.myError} +

{state.myError}

+ {:else if state.myThemes.length === 0} +
+

No community submissions yet.

+ +
+ {:else} +
    + {#each state.myThemes as theme (theme.id)} +
  • + +
  • + {/each} +
+ {/if} +{/if} + +{#if state.showSignInOverlay} + (state.showSignInOverlay = false)} /> +{/if} diff --git a/src/interface/components/communityThemes/OwnerThemeDetailModal.svelte b/src/interface/components/communityThemes/OwnerThemeDetailModal.svelte new file mode 100644 index 00000000..cdb09ba7 --- /dev/null +++ b/src/interface/components/communityThemes/OwnerThemeDetailModal.svelte @@ -0,0 +1,190 @@ + + + state.closeDetail()} +> + {#if theme} +
+
+

{theme.name}

+ + {formatCustomThemeStatus(theme.status)} + +
+ +
+ + {#if theme.status === "rejected" && theme.rejection_reason} +
+

Rejection reason

+

{theme.rejection_reason}

+
+ {/if} + + {#if state.detailLoading} +
+ {:else} +
+
+
Submitted
+
{formatThemeDate(theme.created_at)}
+
+
+
Last updated
+
{formatThemeDate(theme.updated_at)}
+
+ {#if theme.reviewed_at} +
+
Reviewed
+
{formatThemeDate(theme.reviewed_at)}
+
+ {/if} + {#if theme.slug} +
+
Slug
+
{theme.slug}
+
+ {/if} +
+ + {#if state.detailFiles.length > 0} +
+

Files

+
    + {#each state.detailFiles as file (file.id)} +
  • {file.file_path} ({file.file_size.toLocaleString()} bytes)
  • + {/each} +
+
+ {/if} + + {#if canEditCustomTheme(theme)} +
+

Edit metadata

+ + + + + +

Replace files

+

Uploading new files resets review to pending.

+ { + state.replaceZipFile = (e.currentTarget as HTMLInputElement).files?.[0] ?? null; + }} + /> + +
+ {:else if theme.status === "approved"} +

+ Approved themes cannot be edited. Delete and re-submit if you need to publish an update. +

+ {/if} + + {#if state.detailError} +

+ {state.detailError} +

+ {/if} + +
+ {#if state.showDeleteConfirm} +
+ Delete permanently? + + +
+ {:else} + + {/if} + +
+ {/if} + {/if} +
diff --git a/src/interface/components/themes/ThemePlaceholderCover.svelte b/src/interface/components/themes/ThemePlaceholderCover.svelte new file mode 100644 index 00000000..8146ee3d --- /dev/null +++ b/src/interface/components/themes/ThemePlaceholderCover.svelte @@ -0,0 +1,15 @@ + + + diff --git a/src/interface/components/themes/ThemeSelector.svelte b/src/interface/components/themes/ThemeSelector.svelte index dd8718f4..ce629e69 100644 --- a/src/interface/components/themes/ThemeSelector.svelte +++ b/src/interface/components/themes/ThemeSelector.svelte @@ -7,8 +7,10 @@ import { cloudAuth } from '@/seqta/utils/CloudAuth' import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte' import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte' + import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte' import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters' import { closeExtensionPopup, SettingsClicked } from '@/seqta/utils/Closers/closeExtensionPopup' + import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors' const themeManager = ThemeManager.getInstance(); @@ -26,6 +28,8 @@ let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn); let prevLoggedIn = $state(false); let showSignInModal = $state(false); + let submittingThemeId = $state(null); + let submitError = $state(null); $effect(() => { const unsub = cloudAuth.subscribe((s) => { @@ -172,26 +176,31 @@ } const openThemeCreator = async (themeId?: string) => { - const { OpenThemeCreator } = await import('@/plugins/built-in/themes/ThemeCreator') - OpenThemeCreator(themeId) - if (!SettingsClicked) closeExtensionPopup() + const { launchPageThemeBuilder } = await import('@/seqta/utils/launchPageThemeBuilder') + await launchPageThemeBuilder(themeId) } const openCommunitySubmit = async () => { - if (SettingsClicked) { - const [{ requestSettingsDestination }, { requestOpenCommunityThemeSubmit }] = - await Promise.all([ - import('@/seqta/utils/settingsNavigation'), - import('@/seqta/utils/openCommunityThemeSubmit'), - ]) - requestOpenCommunityThemeSubmit() - requestSettingsDestination({ page: 'themes', view: 'community' }) - return - } - const { openCommunityThemeSubmit } = await import('@/seqta/utils/openCommunityThemeSubmit') await openCommunityThemeSubmit() - closeExtensionPopup() + } + + const submitCustomTheme = async (theme: CustomTheme, e: MouseEvent) => { + e.stopPropagation(); + submitError = null; + if (!cloudLoggedIn) { + showSignInModal = true; + return; + } + submittingThemeId = theme.id; + try { + const { submitThemeById } = await import('@/seqta/utils/customThemes/submitLocalTheme'); + await submitThemeById(theme.id, theme.description?.trim() || undefined); + } catch (err) { + submitError = formatCustomThemeApiError(err); + } finally { + submittingThemeId = null; + } } const customThemeActionClass = @@ -336,6 +345,18 @@ >
+ {#if listMode === 'custom'} +
void submitCustomTheme(theme, event)} + onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void submitCustomTheme(theme, event as unknown as MouseEvent) }} + role="button" + tabindex="-1" + title="Submit to community" + > + +
+ {/if} {/if}
{/if} @@ -347,6 +368,11 @@ alt={theme.name} class="object-cover absolute inset-0 z-0 w-full h-full pointer-events-none" /> + {:else} + {/if} {#if !theme.hideThemeName}
{theme.name}
@@ -423,6 +449,10 @@ {#if themes && (listMode === 'custom' || (showNavigation && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
+ {#if listMode === 'custom' && submitError} +

{submitError}

+ {/if} + {#if listMode === 'custom'}
{:else if listMode === 'downloaded'} diff --git a/src/interface/hooks/communityThemesState.svelte.ts b/src/interface/hooks/communityThemesState.svelte.ts new file mode 100644 index 00000000..53e3e3b2 --- /dev/null +++ b/src/interface/hooks/communityThemesState.svelte.ts @@ -0,0 +1,275 @@ +import browser from "webextension-polyfill"; +import type { Theme } from "@/interface/types/Theme"; +import { getCommunityInstalledThemeIds } from "@/interface/utils/themeListFilters"; +import { themeUpdates } from "@/interface/hooks/ThemeUpdates"; +import { ThemeManager } from "@/plugins/built-in/themes/theme-manager"; +import { cloudAuth } from "@/seqta/utils/CloudAuth"; +import { + deleteCustomTheme, + fetchCommunityThemes, + fetchMyCustomThemeDetail, + fetchMyCustomThemes, + replaceCustomThemeFiles, + updateCustomThemeMetadata, +} from "@/seqta/utils/customThemes/client"; +import { + buildUploadPartsFromZipFile, + mergeUploadPayload, +} from "@/seqta/utils/customThemes/buildThemeUploadFormData"; +import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors"; +import type { CustomThemeFile, CustomThemeOwner } from "@/seqta/utils/customThemes/types"; +import { + consumeOpenCommunityThemeSubmit, + consumePendingCommunitySubmitThemeId, + OPEN_COMMUNITY_SUBMIT_EVENT, +} from "@/seqta/utils/openCommunityThemeSubmit"; +export type CommunityThemesTab = "browse" | "mine"; + +export class CommunityThemesState { + innerTab = $state("browse"); + cloudLoggedIn = $state(cloudAuth.state.isLoggedIn); + + browseThemes = $state([]); + browseLoading = $state(true); + browseError = $state(null); + + myThemes = $state([]); + myLoading = $state(false); + myError = $state(null); + statusFilter = $state<"" | "pending" | "approved" | "rejected">(""); + + displayTheme = $state(null); + currentThemes = $state([]); + selectedThemeId = $state(""); + installedThemeColors = $state>({}); + + showSignInOverlay = $state(false); + + detailTheme = $state(null); + detailFiles = $state([]); + detailLoading = $state(false); + detailError = $state(null); + editName = $state(""); + editDescription = $state(""); + editNotes = $state(""); + detailBusy = $state(false); + replaceZipFile = $state(null); + showDeleteConfirm = $state(false); + + private readonly themeManager = ThemeManager.getInstance(); + + constructor(private readonly getSearchTerm: () => string) {} + + async refreshInstalledThemes() { + const themes = await this.themeManager.getAvailableThemes(); + this.currentThemes = getCommunityInstalledThemeIds(themes); + this.selectedThemeId = this.themeManager.getSelectedThemeId() || ""; + this.installedThemeColors = Object.fromEntries( + themes + .filter((t) => t != null && t.installedFromCommunity === true) + .map((t) => [t.id, t.defaultColour]), + ); + } + + async loadBrowseThemes() { + this.browseLoading = true; + this.browseError = null; + try { + const q = this.getSearchTerm().trim(); + const res = await fetchCommunityThemes({ + sort: "popular", + limit: 50, + search: q.length > 0 ? q : undefined, + }); + this.browseThemes = res.themes as Theme[]; + } catch (err) { + this.browseError = err instanceof Error ? err.message : "Could not load community themes"; + } finally { + this.browseLoading = false; + } + } + + async loadMyThemes() { + if (!this.cloudLoggedIn) return; + this.myLoading = true; + this.myError = null; + try { + const res = await fetchMyCustomThemes({ + limit: 50, + status: this.statusFilter || undefined, + }); + this.myThemes = res.themes; + } catch (err) { + this.myError = err instanceof Error ? err.message : "Could not load your themes"; + } finally { + this.myLoading = false; + } + } + + async openDetail(theme: CustomThemeOwner) { + this.detailTheme = theme; + this.detailFiles = []; + this.detailError = null; + this.editName = theme.name; + this.editDescription = theme.description ?? ""; + this.editNotes = theme.submission_notes ?? ""; + this.replaceZipFile = null; + this.showDeleteConfirm = false; + this.detailLoading = true; + try { + const res = await fetchMyCustomThemeDetail(theme.id); + this.detailTheme = res.theme; + this.detailFiles = res.files; + this.editName = res.theme.name; + this.editDescription = res.theme.description ?? ""; + this.editNotes = res.theme.submission_notes ?? ""; + } catch (err) { + this.detailError = err instanceof Error ? err.message : "Could not load theme details"; + } finally { + this.detailLoading = false; + } + } + + closeDetail() { + this.detailTheme = null; + this.detailFiles = []; + this.detailError = null; + this.showDeleteConfirm = false; + } + + async installCommunityTheme(themeId: string, meta: Theme) { + const row = this.browseThemes.find((x) => x.id === themeId) ?? meta; + const installedId = await this.themeManager.downloadCommunityTheme({ + id: themeId, + theme_json_url: row.theme_json_url, + updated_at: row.updated_at, + }); + await this.themeManager.setTheme(installedId); + themeUpdates.triggerUpdate(); + await this.refreshInstalledThemes(); + void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {}); + } + + async removeInstalledTheme(themeId: string) { + await this.themeManager.deleteTheme(themeId); + themeUpdates.triggerUpdate(); + await this.refreshInstalledThemes(); + } + + async applyInstalledTheme(themeId: string) { + await this.themeManager.setTheme(themeId); + this.selectedThemeId = themeId; + themeUpdates.triggerUpdate(); + void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {}); + } + + async saveMetadata() { + if (!this.detailTheme) return; + this.detailBusy = true; + this.detailError = null; + try { + const updated = await updateCustomThemeMetadata(this.detailTheme.id, { + name: this.editName.trim() || undefined, + description: this.editDescription.trim() || undefined, + submission_notes: this.editNotes.trim() || undefined, + }); + this.detailTheme = updated; + await this.loadMyThemes(); + } catch (err) { + this.detailError = formatCustomThemeApiError(err); + } finally { + this.detailBusy = false; + } + } + + async runReplaceFiles() { + if (!this.detailTheme || !this.replaceZipFile) return; + this.detailBusy = true; + this.detailError = null; + try { + const payload = mergeUploadPayload(await buildUploadPartsFromZipFile(this.replaceZipFile)); + const res = await replaceCustomThemeFiles(this.detailTheme.id, payload); + this.detailTheme = res.theme; + this.replaceZipFile = null; + await this.loadMyThemes(); + } catch (err) { + this.detailError = formatCustomThemeApiError(err); + } finally { + this.detailBusy = false; + } + } + + async runDelete() { + if (!this.detailTheme) return; + this.detailBusy = true; + this.detailError = null; + try { + await deleteCustomTheme(this.detailTheme.id); + this.closeDetail(); + await this.loadMyThemes(); + } catch (err) { + this.detailError = formatCustomThemeApiError(err); + } finally { + this.detailBusy = false; + this.showDeleteConfirm = false; + } + } + + bindReactiveLoads() { + $effect(() => { + const unsub = cloudAuth.subscribe((s) => { + this.cloudLoggedIn = s.isLoggedIn; + }); + return unsub; + }); + + $effect(() => { + if (this.innerTab === "browse") void this.loadBrowseThemes(); + }); + + $effect(() => { + this.getSearchTerm(); + if (this.innerTab === "browse") void this.loadBrowseThemes(); + }); + + $effect(() => { + if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes(); + }); + + $effect(() => { + this.statusFilter; + if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes(); + }); + } + + mount() { + const onThemesUpdated = () => void this.refreshInstalledThemes(); + themeUpdates.addListener(onThemesUpdated); + void this.refreshInstalledThemes(); + + const openPageBuilderForSubmit = () => { + const themeId = consumePendingCommunitySubmitThemeId() ?? undefined; + void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) => + launchPageThemeBuilder(themeId), + ); + }; + + if (consumeOpenCommunityThemeSubmit()) { + openPageBuilderForSubmit(); + } + + const onOpenCommunitySubmit = () => { + if (consumeOpenCommunityThemeSubmit()) openPageBuilderForSubmit(); + }; + window.addEventListener(OPEN_COMMUNITY_SUBMIT_EVENT, onOpenCommunitySubmit); + + return () => { + themeUpdates.removeListener(onThemesUpdated); + window.removeEventListener(OPEN_COMMUNITY_SUBMIT_EVENT, onOpenCommunitySubmit); + }; + } +} + +export function createCommunityThemesState(getSearchTerm: () => string) { + return new CommunityThemesState(getSearchTerm); +} diff --git a/src/interface/hooks/themeBuilderPanel.svelte.ts b/src/interface/hooks/themeBuilderPanel.svelte.ts new file mode 100644 index 00000000..85ff884a --- /dev/null +++ b/src/interface/hooks/themeBuilderPanel.svelte.ts @@ -0,0 +1,13 @@ +class ThemeBuilderPanelStore { + editingThemeId = $state(null); + + open(themeId?: string | null) { + this.editingThemeId = themeId ?? null; + } + + close() { + this.editingThemeId = null; + } +} + +export const themeBuilderPanel = new ThemeBuilderPanelStore(); diff --git a/src/interface/index.ts b/src/interface/index.ts index 459bb698..659da55d 100644 --- a/src/interface/index.ts +++ b/src/interface/index.ts @@ -34,6 +34,8 @@ if (!mountPoint) { void (async () => { await initializeSettingsState(); initVerboseLogging(); + const { syncApiBaseToBackground } = await import("@/seqta/utils/DevApiBase"); + syncApiBaseToBackground(); renderSvelte(Settings, mountPoint, { standalone: true }); })(); } diff --git a/src/interface/pages/communityThemes.svelte b/src/interface/pages/communityThemes.svelte index 1494df41..5e6c229e 100644 --- a/src/interface/pages/communityThemes.svelte +++ b/src/interface/pages/communityThemes.svelte @@ -1,364 +1,16 @@
@@ -367,32 +19,33 @@
- {#if innerTab === "mine"} - - {/if} +

Community themes are user-submitted and moderated separately from the official theme store. @@ -400,409 +53,12 @@

- {#if innerTab === "browse"} - {#if browseLoading} -
- {#each Array(6) as _, i (i)} - - {/each} -
- {:else if browseError} -
-

Couldn't load community themes

-

{browseError}

- -
- {:else} - (displayTheme = theme)} - toggleFavorite={() => {}} - isLoggedIn={false} - installedThemeIds={currentThemes} - variant="community" - /> - {#if displayTheme} - (displayTheme = t)} - {selectedThemeId} - {installedThemeColors} - variant="community" - onInstall={async (themeId) => { - if (displayTheme) await installCommunityTheme(themeId, displayTheme); - }} - onRemove={removeInstalledTheme} - onApply={applyInstalledTheme} - /> - {/if} - {/if} - {:else if !cloudLoggedIn} -
-

Sign in to manage your themes

-

- Submit themes for review and track pending, approved, or rejected submissions. -

- -
+ {#if state.innerTab === "browse"} + {:else} -
- {#each ["", "pending", "approved", "rejected"] as status (status)} - - {/each} -
- - {#if myLoading} -
- {#each Array(4) as _, i (i)} - - {/each} -
- {:else if myError} -

{myError}

- {:else if myThemes.length === 0} -
-

No submissions yet.

- -
- {:else} -
    - {#each myThemes as theme (theme.id)} -
  • - -
  • - {/each} -
- {/if} + {/if}
- {#if showSignInOverlay} - (showSignInOverlay = false)} /> - {/if} - - {#if showSubmitModal} - - {/if} - - {#if detailTheme} - - {/if} +
diff --git a/src/interface/pages/settings.svelte b/src/interface/pages/settings.svelte index 00240052..c2b045b3 100644 --- a/src/interface/pages/settings.svelte +++ b/src/interface/pages/settings.svelte @@ -523,82 +523,85 @@
- {#if isStoreView} -
- {#if activePage === "themes" && activeThemeView === "community-themes"} - (storeSearchTerm = term), - }} - /> - {:else} - { - activePage = tab; - if (tab === "themes") activeThemeView = "theme-store"; - else activeBackgroundView = "background-store"; - }, - setSearchTerm: (term: string) => (storeSearchTerm = term), - setBackgroundCategories: (categories: string[]) => - (backgroundCategories = categories), - }} - /> - {/if} -
- {:else} -
-
-

- {sectionTitle} -

-
-
- {#if activePage === "settings"} - {#if activeSection === "shortcuts" && !debouncedSettingsSearch.trim()} - - {:else} - - {#if debouncedSettingsSearch.trim()} - - {/if} - {/if} - {:else if activePage === "themes"} +
+ {#if isStoreView} +
+ {#if activePage === "themes" && activeThemeView === "community-themes"} (storeSearchTerm = term), + }} /> {:else} { + activePage = tab; + if (tab === "themes") activeThemeView = "theme-store"; + else activeBackgroundView = "background-store"; + }, + setSearchTerm: (term: string) => (storeSearchTerm = term), + setBackgroundCategories: (categories: string[]) => + (backgroundCategories = categories), + }} /> {/if}
-
- {/if} + {:else} +
+
+

+ {sectionTitle} +

+
+
+ {#if activePage === "settings"} + {#if activeSection === "shortcuts" && !debouncedSettingsSearch.trim()} + + {:else} + + {#if debouncedSettingsSearch.trim()} + + {/if} + {/if} + {:else if activePage === "themes"} + + {:else} + + {/if} +
+
+ {/if} + +
{/snippet} @@ -682,7 +685,7 @@ >
{@render settingsShell()} diff --git a/src/interface/pages/settings/sections/advanced.svelte b/src/interface/pages/settings/sections/advanced.svelte index afbae8a8..014c8d5e 100644 --- a/src/interface/pages/settings/sections/advanced.svelte +++ b/src/interface/pages/settings/sections/advanced.svelte @@ -7,7 +7,9 @@ import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/Openers/OpenThemeOfTheMonthPopup"; import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup"; import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync"; - import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase"; + import { getStoredOverride, PRODUCTION_API_BASE, setApiBase } from "@/seqta/utils/DevApiBase"; + + const isExtensionDevBuild = import.meta.env.DEV; import { matchesSearch, type SettingsSectionSharedProps } from "../shared"; let { searchQuery = "" }: SettingsSectionSharedProps = $props(); @@ -202,29 +204,38 @@

API Base URL (session only)

-

- Override the content API host for this browser session. Cleared on restart. Affects - themes, theme of the month, and other server-driven content. -

- {#if devApiBaseActive} -

- Override active: {devApiBaseActive} + {#if isExtensionDevBuild} +

+ Extension dev builds always use production ({PRODUCTION_API_BASE}) for the theme store, + community submit, and related APIs. Build a release package to test a staging host override.

+ {:else} +

+ Override the content API host for this browser session. Cleared on restart. Affects + themes, theme of the month, and other server-driven content. +

+ {#if devApiBaseActive} +

+ Override active: {devApiBaseActive} +

+ {/if} {/if}
-
- -
+ {#if !isExtensionDevBuild} +
+ +
+ {/if}
diff --git a/src/interface/pages/settings/theme.svelte b/src/interface/pages/settings/theme.svelte index 3b898ebf..44c3db7a 100644 --- a/src/interface/pages/settings/theme.svelte +++ b/src/interface/pages/settings/theme.svelte @@ -47,6 +47,19 @@ {/if} {#if showThemes} + {#if listMode === "custom"} + + {/if} {/if}
diff --git a/src/interface/pages/themeCreator.svelte b/src/interface/pages/themeCreator.svelte index 3fbeb547..1b43be5f 100644 --- a/src/interface/pages/themeCreator.svelte +++ b/src/interface/pages/themeCreator.svelte @@ -21,14 +21,28 @@ handleImageUpload, handleRemoveImage, handleImageVariableChange, - handleCoverImageUpload } from '../utils/themeImageHandlers'; import { ThemeManager } from '@/plugins/built-in/themes/theme-manager' import { themeUpdates } from '../hooks/ThemeUpdates' import { CloseThemeCreator } from '@/plugins/built-in/themes/ThemeCreator' - import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte' + import { submitLocalThemeToCommunity } from '@/seqta/utils/customThemes/submitLocalTheme' + import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors' + import { cloudAuth } from '@/seqta/utils/CloudAuth' import LucideMoon from '@/interface/components/icons/LucideMoon.svelte' import LucideSun from '@/interface/components/icons/LucideSun.svelte' + import SidebarAppearance from '@/interface/components/SidebarAppearance.svelte' + import { FONT_PRESETS, DEFAULT_FONT_ID } from '@/seqta/ui/fonts/presets' + import { applySelectedFont, ensureFontPickerFontsLoaded } from '@/seqta/ui/fonts/Manager' + import { + applySidebarSettings, + defaultThemeCreatorMeta, + mergeThemeWithCreatorMeta, + snapshotSidebarSettings, + type ThemeCreatorSidebarMeta, + } from '@/interface/utils/themeCreatorMeta' + import { ensureThemeCoverImage } from '@/interface/utils/themePlaceholderCover' + import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte' + import type { ThemeCreatorMeta } from '@/types/CustomThemes' const { themeID } = $props<{ themeID: string }>() const themeManager = ThemeManager.getInstance(); @@ -52,7 +66,73 @@ let closedAccordions = $state([]) let themeLoaded = $state(false); let codeEditorFullscreen = $state(false); - + let communityBusy = $state(false); + let communityError = $state(null); + let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn); + let panelDark = $state(Boolean(settingsState.DarkMode)); + let creatorMeta = $state(defaultThemeCreatorMeta()); + let originalSidebar = $state(null); + let originalFontId = $state(null); + /** When true, generated font/background CSS is merged for live preview and save. */ + let composeVisuals = $state(false); + + const previewTheme = $derived.by(() => { + if (!themeLoaded) return null; + if (composeVisuals || theme.creatorMeta || creatorMeta.pageBackgroundImageId) { + return mergeThemeWithCreatorMeta(theme, creatorMeta); + } + return { ...theme, creatorMeta }; + }); + + function touchVisuals() { + if (!composeVisuals && !theme.creatorMeta && !creatorMeta.userCustomCss.trim()) { + creatorMeta = { ...creatorMeta, userCustomCss: theme.CustomCSS }; + } + composeVisuals = true; + } + + function imageUsage(imageId: string): 'decorative' | 'page-background' | 'cover' { + if (creatorMeta.pageBackgroundImageId === imageId) return 'page-background'; + const image = theme.CustomImages.find((item) => item.id === imageId); + if (image && theme.coverImage === image.blob) return 'cover'; + return 'decorative'; + } + + function setImageUsage(imageId: string, usage: 'decorative' | 'page-background' | 'cover') { + const image = theme.CustomImages.find((item) => item.id === imageId); + if (!image) return; + + let nextMeta = { ...creatorMeta }; + let coverImage = theme.coverImage; + + if (usage === 'page-background') { + nextMeta = { ...nextMeta, pageBackgroundImageId: imageId }; + } else if (nextMeta.pageBackgroundImageId === imageId) { + nextMeta = { ...nextMeta, pageBackgroundImageId: null }; + } + + if (usage === 'cover') { + coverImage = image.blob; + } else if (coverImage === image.blob) { + coverImage = null; + } + + creatorMeta = nextMeta; + theme = { ...theme, coverImage }; + touchVisuals(); + } + + function onFontIdChange(fontId: string) { + creatorMeta = { ...creatorMeta, fontId }; + applySelectedFont(fontId); + touchVisuals(); + } + + function patchCreatorMeta(patch: Partial) { + creatorMeta = { ...creatorMeta, ...patch }; + touchVisuals(); + } + function toggleCodeEditorFullscreen(e: MouseEvent) { e.preventDefault(); codeEditorFullscreen = !codeEditorFullscreen; @@ -71,8 +151,38 @@ } } + async function prepareThemeClone() { + const themeClone = JSON.parse(JSON.stringify(theme)) as LoadedCustomTheme; + + themeClone.CustomImages = theme.CustomImages.map((image) => ({ + ...image, + blob: image.blob, + })); + themeClone.coverImage = theme.coverImage; + themeClone.userEdited = true; + + if (shouldForceThemeAppearance(themeClone)) { + themeClone.forceTheme = true; + } else { + themeClone.forceTheme = false; + themeClone.forceDark = undefined; + } + + const merged = mergeThemeWithCreatorMeta(themeClone, creatorMeta); + return await ensureThemeCoverImage(merged); + } + onMount(async () => { - await themeManager.disableTheme(); + const unsubCloud = cloudAuth.subscribe((s) => { + cloudLoggedIn = s.isLoggedIn; + }); + const unsubSettings = settingsState.subscribe((s) => { + panelDark = s.DarkMode; + }); + + void ensureFontPickerFontsLoaded(); + originalSidebar = snapshotSidebarSettings(); + originalFontId = settingsState.selectedFont ?? DEFAULT_FONT_ID; if (themeID) { const tempTheme = await themeManager.getTheme(themeID); @@ -85,59 +195,93 @@ tempTheme.forceTheme ?? (tempTheme.forceDark !== undefined ? true : undefined), }; - themeLoaded = true; - } else { - themeLoaded = true } + if (theme.creatorMeta) { + creatorMeta = { ...defaultThemeCreatorMeta(), ...theme.creatorMeta }; + applySidebarSettings(theme.creatorMeta.sidebar); + composeVisuals = true; + } else { + creatorMeta = defaultThemeCreatorMeta({ + userCustomCss: theme.CustomCSS, + fontId: settingsState.selectedFont ?? DEFAULT_FONT_ID, + }); + } + + applySelectedFont(creatorMeta.fontId); + themeLoaded = true; themeUpdates.triggerUpdate(); + + return () => { + unsubCloud(); + unsubSettings(); + if (originalSidebar) applySidebarSettings(originalSidebar); + if (originalFontId) applySelectedFont(originalFontId); + }; }); async function onImageUpload(event: Event) { - theme = await handleImageUpload(event, theme); + const updated = await handleImageUpload(event, theme); + if (updated === theme) return; + theme = updated as LoadedCustomTheme; + if (!creatorMeta.pageBackgroundImageId && theme.CustomImages.length === 1) { + creatorMeta = { ...creatorMeta, pageBackgroundImageId: theme.CustomImages[0].id }; + } + touchVisuals(); } function onRemoveImage(imageId: string) { + if (creatorMeta.pageBackgroundImageId === imageId) { + creatorMeta = { ...creatorMeta, pageBackgroundImageId: null }; + } theme = handleRemoveImage(imageId, theme); + touchVisuals(); } function onImageVariableChange(imageId: string, variableName: string) { theme = handleImageVariableChange(imageId, variableName, theme); - } - - async function onCoverImageUpload(event: Event) { - theme = await handleCoverImageUpload(event, theme); + touchVisuals(); } async function submitTheme() { - const themeClone = JSON.parse(JSON.stringify(theme)); + const themeClone = await prepareThemeClone(); - // re-insert blobs into themeClone - themeClone.CustomImages = theme.CustomImages.map((image) => ({ - ...image, - blob: image.blob - })) - themeClone.coverImage = theme.coverImage - themeClone.userEdited = true - - if (shouldForceThemeAppearance(themeClone)) { - themeClone.forceTheme = true; - } else { - themeClone.forceTheme = false; - themeClone.forceDark = undefined; - } - - themeManager.clearPreview(); await themeManager.saveTheme(themeClone); await themeManager.setTheme(themeClone.id); themeUpdates.triggerUpdate(); - CloseThemeCreator(); + await CloseThemeCreator({ restoreTheme: false }); + } + + async function submitThemeToCommunity() { + communityError = null; + if (!cloudLoggedIn) { + communityError = "Sign in with BetterSEQTA Cloud to submit themes."; + return; + } + if (!theme.name.trim()) { + communityError = "Add a theme name before submitting."; + return; + } + + communityBusy = true; + try { + const themeClone = await prepareThemeClone(); + await themeManager.saveTheme(themeClone); + await themeManager.setTheme(themeClone.id); + await submitLocalThemeToCommunity(themeClone, theme.description?.trim() || undefined); + themeUpdates.triggerUpdate(); + await CloseThemeCreator({ restoreTheme: false }); + } catch (err) { + communityError = formatCustomThemeApiError(err); + } finally { + communityBusy = false; + } } $effect(() => { - if (themeLoaded) { - void themeManager.updatePreviewDebounced(theme); - } + const snapshot = previewTheme; + if (!snapshot) return; + void themeManager.updatePreviewDebounced(snapshot); }); type SettingType = 'switch' | 'button' | 'slider' | 'colourPicker' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle'; @@ -221,20 +365,35 @@ {/if} {:else if item.type === 'imageUpload'} {#each theme.CustomImages as image (image.id)} -
-
- +
+
+
+ +
+ onImageVariableChange(image.id, e.currentTarget.value)} + placeholder="CSS variable name" + class="grow flex-3 rounded-lg border-0 bg-zinc-200 p-2 transition dark:bg-zinc-600/50 dark:placeholder-zinc-300 focus:bg-zinc-300/50 dark:focus:bg-zinc-600" + /> +
- onImageVariableChange(image.id, e.currentTarget.value)} - placeholder="CSS Variable Name" - class="p-2 w-full rounded-lg border-0 transition grow flex-3 dark:placeholder-zinc-300 bg-zinc-200 dark:bg-zinc-600/50 focus:bg-zinc-300/50 dark:focus:bg-zinc-600" - /> - +
{/each} @@ -270,7 +429,7 @@ {/if} {/snippet} -
+
{#if codeEditorFullscreen}
@@ -278,14 +437,27 @@

Custom CSS

- { theme = { ...theme, CustomCSS: value } }} /> + patchCreatorMeta({ userCustomCss: value })} + />
{/if} -
+
- -

Theme Creator

+
+

Theme Creator

+ +
{'\ueb44'} @@ -293,12 +465,6 @@ - -
@@ -322,19 +488,122 @@ -
-
- {'\uec60'} +
+

Accent colour

+

Default accent and gradient start colour.

+
+ { + theme = { ...theme, defaultColour: color }; + touchVisuals(); + }} + />
- {theme.coverImage ? 'Change' : 'Add'} cover image - - {#if !theme.hideThemeName && theme.coverImage} -
{theme.name}
- {/if} - {#if theme.coverImage} -
- - {/if} +
+ + + +
+

Interface font

+ +
+ + + +
+
+

Images & page background

+

+ Upload images, then choose how each one is used. Set one as the live SEQTA page background to preview it on the main page. +

+
+ + {#each theme.CustomImages as image (image.id)} +
+
+ + onImageVariableChange(image.id, e.currentTarget.value)} + placeholder="CSS variable" + class="min-w-0 flex-1 rounded-lg border-0 bg-zinc-100 p-2 text-sm dark:bg-zinc-600 dark:text-white" + /> + +
+ +
+ {/each} + + + + + + +
@@ -360,6 +629,12 @@ +
+ +
+ + + {#each [ { type: 'switch', @@ -401,34 +676,46 @@ } } }, - { - type: 'colourPicker', - title: 'Default Theme Colour', - description: 'Set the default color for your theme', - direction: 'vertical', - props: { - customState: theme.defaultColour, - customOnChange: (color: string) => theme = { ...theme, defaultColour: color } - } - }, - { - type: 'imageUpload', - title: 'Custom Images', - description: 'Add custom images to your theme', - direction: 'vertical', - }, { type: 'codeEditor', title: 'Custom CSS', - description: 'Add custom CSS to your theme', + description: 'Extra CSS appended after generated theme rules', direction: 'vertical', props: { - value: theme.CustomCSS, - onChange: (value: string) => { theme = { ...theme, CustomCSS: value } } + value: creatorMeta.userCustomCss, + onChange: (value: string) => patchCreatorMeta({ userCustomCss: value }) } } ] as SettingItem[] as setting} {@render settingItem(setting)} {/each} + +
+ + + {#if !cloudLoggedIn} +

+ Sign in with BetterSEQTA Cloud to submit themes to the community library. +

+ {/if} + {#if communityError} +

{communityError}

+ {/if} +
\ No newline at end of file diff --git a/src/interface/utils/buildSimpleTheme.test.ts b/src/interface/utils/buildSimpleTheme.test.ts new file mode 100644 index 00000000..63313b59 --- /dev/null +++ b/src/interface/utils/buildSimpleTheme.test.ts @@ -0,0 +1,37 @@ +import { buildSimpleTheme } from "./buildSimpleTheme"; +import { buildThemeBuilderCss } from "./themeBuilderDraft"; +import { getFontPreset } from "@/seqta/ui/fonts/presets"; + +describe("buildSimpleTheme", () => { + it("builds CSS with font import and image variables", () => { + const css = buildThemeBuilderCss( + getFontPreset("inter"), + ["theme-bg-0"], + { accentColor: "#00f", gradientEnd: "#f0f" }, + ); + expect(css).toContain("Inter"); + expect(css).toContain("var(--theme-bg-0)"); + expect(css).toContain("#title"); + }); + + it("creates a theme with photos as custom image variables", () => { + const theme = buildSimpleTheme({ + name: "Sunset", + accentColor: "#ff6600", + fontId: "rubik", + photoBlobs: [new Blob(["x"], { type: "image/png" })], + }); + expect(theme.name).toBe("Sunset"); + expect(theme.defaultColour).toBe("#ff6600"); + expect(theme.CustomImages).toHaveLength(1); + expect(theme.CustomImages[0].variableName).toBe("theme-bg-0"); + expect(theme.coverImage).toBeTruthy(); + expect(theme.hideThemeName).toBe(true); + }); + + it("requires a name", () => { + expect(() => + buildSimpleTheme({ name: " ", accentColor: "#000", photoBlobs: [] }), + ).toThrow("Theme name is required"); + }); +}); diff --git a/src/interface/utils/buildSimpleTheme.ts b/src/interface/utils/buildSimpleTheme.ts new file mode 100644 index 00000000..854777a9 --- /dev/null +++ b/src/interface/utils/buildSimpleTheme.ts @@ -0,0 +1,11 @@ +import type { LoadedCustomTheme } from "@/types/CustomThemes"; +import { buildThemeFromDraft, type ThemeBuilderDraft } from "./themeBuilderDraft"; + +export type SimpleThemeInput = ThemeBuilderDraft; + +export { buildThemeBuilderCss as buildSimpleThemeCss } from "./themeBuilderDraft"; + +/** @deprecated Use buildThemeFromDraft */ +export function buildSimpleTheme(input: SimpleThemeInput): LoadedCustomTheme { + return buildThemeFromDraft(input); +} diff --git a/src/interface/utils/themeBuilderDraft.ts b/src/interface/utils/themeBuilderDraft.ts new file mode 100644 index 00000000..9067c694 --- /dev/null +++ b/src/interface/utils/themeBuilderDraft.ts @@ -0,0 +1,138 @@ +import { generateImageId } from "@/interface/utils/themeImageHandlers"; +import { DEFAULT_FONT_ID, getFontPreset, type FontPreset } from "@/seqta/ui/fonts/presets"; +import type { LoadedCustomTheme } from "@/types/CustomThemes"; + +export type ThemeBuilderDraft = { + name: string; + description?: string; + accentColor: string; + gradientEnd?: string; + gradientAngle?: number; + backgroundBlurPx?: number; + overlayOpacity?: number; + fontId?: string; + photoBlobs: Blob[]; + customCssExtra?: string; + themeId?: string; +}; + +/** Keep the BetterSEQTA title bar opaque (generated themes must not use the old transparent #title hack). */ +const TITLEBAR_SOLID = `#title { + background: var(--background-primary) !important; +}`; + +function clamp(n: number, min: number, max: number): number { + return Math.min(max, Math.max(min, n)); +} + +export function buildThemeBuilderCss( + font: FontPreset, + imageVariables: string[], + draft: Pick< + ThemeBuilderDraft, + "accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" + >, +): string { + const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : ""; + const angle = draft.gradientAngle ?? 135; + const overlay = clamp(draft.overlayOpacity ?? 0.35, 0, 0.85); + const blurPx = clamp(draft.backgroundBlurPx ?? 0, 0, 24); + const endColor = (draft.gradientEnd ?? draft.accentColor).trim(); + + const rules: string[] = [ + `${importLine}body, #container, .dashboard { + font-family: ${font.stack} !important; +}`, + ]; + + const imageLayer = + imageVariables.length > 0 + ? imageVariables.map((name) => `var(--${name})`).join(", ") + : ""; + const gradientLayer = `linear-gradient(${angle}deg, color-mix(in srgb, ${draft.accentColor} ${Math.round(overlay * 100)}%, transparent), color-mix(in srgb, ${endColor} ${Math.round(overlay * 100)}%, transparent))`; + + rules.push(`#container { + isolation: isolate; + position: relative; +}`); + + if (imageLayer && blurPx > 0) { + rules.push(`#container::after { + content: ""; + position: fixed; + inset: 0; + z-index: -2; + pointer-events: none; + background-image: ${imageLayer}; + background-size: cover; + background-position: center; + background-attachment: fixed; + filter: blur(${blurPx}px); + transform: scale(1.04); +}`); + rules.push(`#container { + background-image: ${gradientLayer} !important; + background-size: cover !important; + background-position: center !important; + background-attachment: fixed !important; +}`); + } else { + const bgLayers: string[] = []; + if (imageLayer) bgLayers.push(imageLayer); + bgLayers.push(gradientLayer); + rules.push(`#container { + background-image: ${bgLayers.join(", ")} !important; + background-size: cover !important; + background-position: center !important; + background-attachment: fixed !important; +}`); + } + + rules.push(`#container::before { + display: none !important; + content: none !important; + backdrop-filter: none !important; + -webkit-backdrop-filter: none !important; +}`); + + if (!imageLayer || blurPx === 0) { + rules.push(`#container::after { + display: none !important; + content: none !important; + filter: none !important; +}`); + } + + rules.push(TITLEBAR_SOLID); + const extra = draft.customCssExtra?.trim(); + if (extra) rules.push(extra); + return rules.join("\n\n"); +} + +export function buildThemeFromDraft(draft: ThemeBuilderDraft): LoadedCustomTheme { + const name = draft.name.trim(); + if (!name) throw new Error("Theme name is required"); + + const font = getFontPreset(draft.fontId ?? DEFAULT_FONT_ID); + const photoBlobs = draft.photoBlobs.filter((blob) => blob.size > 0); + const CustomImages = photoBlobs.map((blob, index) => ({ + id: generateImageId(), + blob, + variableName: `theme-bg-${index}`, + })); + + return { + id: draft.themeId ?? crypto.randomUUID(), + name, + description: (draft.description ?? "").trim(), + defaultColour: draft.accentColor.trim() || "rgba(0, 123, 255, 1)", + CanChangeColour: true, + allowBackgrounds: true, + CustomCSS: buildThemeBuilderCss(font, CustomImages.map((i) => i.variableName), draft), + CustomImages, + coverImage: photoBlobs[0] ?? null, + isEditable: true, + hideThemeName: Boolean(photoBlobs[0]), + adaptiveCssVariables: [], + }; +} diff --git a/src/interface/utils/themeCreatorMeta.ts b/src/interface/utils/themeCreatorMeta.ts new file mode 100644 index 00000000..7870e815 --- /dev/null +++ b/src/interface/utils/themeCreatorMeta.ts @@ -0,0 +1,104 @@ +import { buildThemeBuilderCss } from "@/interface/utils/themeBuilderDraft"; +import { applySelectedFont } from "@/seqta/ui/fonts/Manager"; +import { DEFAULT_FONT_ID, getFontPreset } from "@/seqta/ui/fonts/presets"; +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import type { LoadedCustomTheme, ThemeCreatorMeta } from "@/types/CustomThemes"; + +export type ThemeCreatorSidebarMeta = { + sidebarStyle?: string; + sidebarDensity?: string; + sidebarCornerRadius?: number; + sidebarActiveIndicator?: string; + sidebarWidth?: string; + sidebarPosition?: string; + sidebarBlur?: number; + transparencyEffects?: boolean; +}; + +export function defaultThemeCreatorMeta( + overrides: Partial = {}, +): ThemeCreatorMeta { + return { + fontId: settingsState.selectedFont ?? DEFAULT_FONT_ID, + pageBackgroundImageId: null, + backgroundBlurPx: 0, + overlayOpacity: 0.35, + gradientAngle: 135, + gradientEnd: "", + userCustomCss: "", + ...overrides, + }; +} + +export function snapshotSidebarSettings(): ThemeCreatorSidebarMeta { + return { + sidebarStyle: settingsState.sidebarStyle, + sidebarDensity: settingsState.sidebarDensity, + sidebarCornerRadius: settingsState.sidebarCornerRadius, + sidebarActiveIndicator: settingsState.sidebarActiveIndicator, + sidebarWidth: settingsState.sidebarWidth, + sidebarPosition: settingsState.sidebarPosition, + sidebarBlur: settingsState.sidebarBlur, + transparencyEffects: settingsState.transparencyEffects, + }; +} + +export function applySidebarSettings(meta: ThemeCreatorSidebarMeta | undefined): void { + if (!meta) return; + if (meta.sidebarStyle !== undefined) settingsState.sidebarStyle = meta.sidebarStyle; + if (meta.sidebarDensity !== undefined) settingsState.sidebarDensity = meta.sidebarDensity; + if (meta.sidebarCornerRadius !== undefined) { + settingsState.sidebarCornerRadius = meta.sidebarCornerRadius; + } + if (meta.sidebarActiveIndicator !== undefined) { + settingsState.sidebarActiveIndicator = meta.sidebarActiveIndicator; + } + if (meta.sidebarWidth !== undefined) settingsState.sidebarWidth = meta.sidebarWidth; + if (meta.sidebarPosition !== undefined) settingsState.sidebarPosition = meta.sidebarPosition; + if (meta.sidebarBlur !== undefined) settingsState.sidebarBlur = meta.sidebarBlur; + if (meta.transparencyEffects !== undefined) { + settingsState.transparencyEffects = meta.transparencyEffects; + } +} + +export function composeThemeCustomCss( + theme: Pick, + meta: ThemeCreatorMeta, +): string { + const font = getFontPreset(meta.fontId ?? DEFAULT_FONT_ID); + const backgroundVariables: string[] = []; + if (meta.pageBackgroundImageId) { + const image = theme.CustomImages.find((item) => item.id === meta.pageBackgroundImageId); + if (image?.variableName) backgroundVariables.push(image.variableName); + } + + const gradientEnd = (meta.gradientEnd || theme.defaultColour).trim(); + + return buildThemeBuilderCss(font, backgroundVariables, { + accentColor: theme.defaultColour, + gradientEnd, + gradientAngle: meta.gradientAngle ?? 135, + backgroundBlurPx: meta.backgroundBlurPx ?? 0, + overlayOpacity: meta.overlayOpacity ?? 0.35, + customCssExtra: meta.userCustomCss ?? "", + }); +} + +export function applyThemeCreatorMetaToSettings(meta: ThemeCreatorMeta | undefined): void { + if (!meta) return; + if (meta.fontId) { + settingsState.selectedFont = meta.fontId; + applySelectedFont(meta.fontId); + } + applySidebarSettings(meta.sidebar); +} + +export function mergeThemeWithCreatorMeta( + theme: LoadedCustomTheme, + meta: ThemeCreatorMeta, +): LoadedCustomTheme { + const sidebar = snapshotSidebarSettings(); + const mergedMeta: ThemeCreatorMeta = { ...meta, sidebar }; + const CustomCSS = composeThemeCustomCss(theme, mergedMeta); + return { ...theme, creatorMeta: mergedMeta, CustomCSS }; +} diff --git a/src/interface/utils/themePlaceholderCover.test.ts b/src/interface/utils/themePlaceholderCover.test.ts new file mode 100644 index 00000000..85f6f318 --- /dev/null +++ b/src/interface/utils/themePlaceholderCover.test.ts @@ -0,0 +1,17 @@ +import { + createDefaultThemeCoverSvg, + defaultThemeCoverDataUrl, +} from "./themePlaceholderCover"; + +describe("themePlaceholderCover", () => { + it("builds an svg cover placeholder", () => { + const svg = createDefaultThemeCoverSvg("#3366ff"); + expect(svg).toContain(" { + expect(defaultThemeCoverDataUrl()).toMatch(/^data:image\/svg\+xml/); + }); +}); diff --git a/src/interface/utils/themePlaceholderCover.ts b/src/interface/utils/themePlaceholderCover.ts new file mode 100644 index 00000000..1fbb0158 --- /dev/null +++ b/src/interface/utils/themePlaceholderCover.ts @@ -0,0 +1,46 @@ +import type { LoadedCustomTheme } from "@/types/CustomThemes"; + +/** SVG cover used when a theme has no store/community cover image. */ +export function createDefaultThemeCoverSvg(accentHint = "#52525b"): string { + const accent = accentHint.startsWith("#") ? accentHint : "#52525b"; + return ` + + + + + + + + + + + + + + No cover image + Add one in Theme Creator +`; +} + +export function defaultThemeCoverDataUrl(accentHint?: string): string { + return `data:image/svg+xml;charset=utf-8,${encodeURIComponent( + createDefaultThemeCoverSvg(accentHint), + )}`; +} + +let cachedCoverBlob: Blob | null = null; + +export async function getDefaultThemeCoverBlob(accentHint?: string): Promise { + if (!cachedCoverBlob) { + cachedCoverBlob = new Blob([createDefaultThemeCoverSvg(accentHint)], { + type: "image/svg+xml", + }); + } + return cachedCoverBlob; +} + +export async function ensureThemeCoverImage(theme: LoadedCustomTheme): Promise { + if (theme.coverImage && theme.coverImage.size > 0) return theme; + const coverImage = await getDefaultThemeCoverBlob(theme.defaultColour); + return { ...theme, coverImage }; +} diff --git a/src/plugins/built-in/themes/ThemeCreator.ts b/src/plugins/built-in/themes/ThemeCreator.ts index 6909a8d3..8b4f7673 100644 --- a/src/plugins/built-in/themes/ThemeCreator.ts +++ b/src/plugins/built-in/themes/ThemeCreator.ts @@ -1,55 +1,59 @@ -import { ThemeManager } from "@/plugins/built-in/themes/theme-manager"; import { unmount } from "svelte"; +import { ThemeManager } from "@/plugins/built-in/themes/theme-manager"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import { themeBuilderPanel } from "@/interface/hooks/themeBuilderPanel.svelte"; +import { + clearThemeCreatorSession, + persistThemeCreatorSession, +} from "@/plugins/built-in/themes/themeCreatorPersistence"; +import { + applyThemeCreatorLayout, + clearThemeCreatorLayout, +} from "@/plugins/built-in/themes/themeCreatorLayout"; let themeCreatorSvelteApp: any = null; +let currentWidthPx = 400; /** - * Open the Theme Creator sidebar, it is an embedded page loaded similar to the extension popup - * @param themeID - The ID of the theme to load in the Theme Creator - * @returns void + * Open the interactive theme builder docked to the right of the SEQTA page (not inside settings). */ export async function OpenThemeCreator(themeID: string = "") { - CloseThemeCreator(); + await CloseThemeCreator(); - const [{ default: renderSvelte }, { default: themeCreator }] = - await Promise.all([ - import("@/interface/main"), - import("@/interface/pages/themeCreator.svelte"), - ]); + themeBuilderPanel.open(themeID || null); + persistThemeCreatorSession(themeID || null); - localStorage.setItem("themeCreatorOpen", "true"); - if (!themeID) { - localStorage.setItem("originalPreviewColor", settingsState.selectedColor); - } + ThemeManager.getInstance().beginThemeCreatorSession(); - const width = "310px"; + const [{ default: renderSvelte }, { default: ThemeCreatorPage }] = await Promise.all([ + import("@/interface/main"), + import("@/interface/pages/themeCreator.svelte"), + ]); + + const editingId = themeID || themeBuilderPanel.editingThemeId || ""; + + currentWidthPx = 460; + const width = `${currentWidthPx}px`; const themeCreatorDiv: HTMLDivElement = document.createElement("div"); themeCreatorDiv.id = "themeCreator"; themeCreatorDiv.style.width = width; + themeCreatorDiv.style.height = "100%"; + + if (settingsState.DarkMode) { + themeCreatorDiv.classList.add("dark"); + } const shadow = themeCreatorDiv.attachShadow({ mode: "open" }); - themeCreatorSvelteApp = renderSvelte(themeCreator, shadow, { - themeID: themeID, + themeCreatorSvelteApp = renderSvelte(ThemeCreatorPage, shadow, { + themeID: editingId, }); - const mainContent = document.querySelector("#container") as HTMLDivElement; - if (mainContent) mainContent.style.width = `calc(100% - ${width})`; - - const closeButton = document.createElement("button"); - closeButton.classList.add("themeCloseButton"); - closeButton.textContent = "×"; - closeButton.addEventListener("click", () => { - CloseThemeCreator(); - ThemeManager.getInstance().clearPreview(); - }); - - document.body.appendChild(closeButton); + applyThemeCreatorLayout(currentWidthPx); + themeCreatorDiv.style.color = "initial"; const resizeBar = document.createElement("div"); resizeBar.classList.add("resizeBar"); - resizeBar.style.right = "307.5px"; let isDragging = false; @@ -64,10 +68,10 @@ export async function OpenThemeCreator(themeID: string = "") { const mouseMoveHandler = (e: MouseEvent) => { if (!isDragging) return; const windowWidth = window.innerWidth; - const newWidth = Math.max(310, windowWidth - e.clientX); - themeCreatorDiv.style.width = `${newWidth}px`; - mainContent.style.width = `calc(100% - ${newWidth}px)`; - resizeBar.style.right = `${newWidth - 2.5}px`; + currentWidthPx = Math.max(320, windowWidth - e.clientX); + themeCreatorDiv.style.width = `${currentWidthPx}px`; + applyThemeCreatorLayout(currentWidthPx); + positionResizeBar(currentWidthPx, resizeBar); }; const mouseUpHandler = () => { @@ -79,34 +83,40 @@ export async function OpenThemeCreator(themeID: string = "") { }; resizeBar.addEventListener("mousedown", mouseDownHandler); - resizeBar.addEventListener( - "mouseover", - () => (resizeBar.style.opacity = "1"), - ); + resizeBar.addEventListener("mouseover", () => (resizeBar.style.opacity = "1")); resizeBar.addEventListener("mouseout", () => (resizeBar.style.opacity = "0")); document.body.appendChild(themeCreatorDiv); document.body.appendChild(resizeBar); + positionResizeBar(currentWidthPx, resizeBar); } -/** - * Close the Theme Creator sidebar - * @returns void - */ -export function CloseThemeCreator() { - localStorage.removeItem("themeCreatorOpen"); +function positionResizeBar(widthPx: number, resizeBar: HTMLDivElement) { + resizeBar.style.right = `${widthPx - 2.5}px`; +} + +export async function CloseThemeCreator(options?: { restoreTheme?: boolean }) { + const themeManager = ThemeManager.getInstance(); + if (options?.restoreTheme === false) { + themeManager.discardThemeCreatorRestore(); + themeManager.clearPreview(); + } else { + await themeManager.endThemeCreatorSession(); + } + clearThemeCreatorSession(); + themeBuilderPanel.close(); const themeCreator = document.getElementById("themeCreator"); - const closeButton = document.querySelector( - ".themeCloseButton", - ) as HTMLButtonElement; - const resizeBar = document.querySelector(".resizeBar") as HTMLDivElement; + const resizeBar = document.querySelector(".resizeBar") as HTMLDivElement | null; if (themeCreatorSvelteApp) unmount(themeCreatorSvelteApp); + themeCreatorSvelteApp = null; if (themeCreator) themeCreator.remove(); - if (closeButton) closeButton.remove(); if (resizeBar) resizeBar.remove(); - const mainContent = document.querySelector("#container") as HTMLDivElement; - if (mainContent) mainContent.style.width = "100%"; + clearThemeCreatorLayout(); +} + +export function isThemeCreatorOpen(): boolean { + return document.getElementById("themeCreator") != null; } diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index d76e817f..c4ff3b9b 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -74,6 +74,8 @@ export class ThemeManager { private lastSyncedImageKey: string | null = null; private originalPreviewColor: string | null = null; private originalPreviewTheme: boolean | null = null; + /** Theme id active before opening Theme Creator (restored on exit without save). */ + private themeCreatorSuspendedThemeId: string | null = null; private lastTransitionPoint: { x: number; y: number } = { x: 0, y: 0 }; private storeUpdateCheckRunning = false; @@ -233,13 +235,18 @@ export class ThemeManager { await localforage.setItem(neumorphicThemeId, theme); } - const themeCreatorOpen = localStorage.getItem("themeCreatorOpen"); - if (themeCreatorOpen === "true") { - verboseDebug( - "[ThemeManager] Theme creator was open, clearing preview state", + const { readThemeCreatorSession } = await import( + "@/plugins/built-in/themes/themeCreatorPersistence" + ); + const creatorSession = readThemeCreatorSession(); + if (creatorSession.open) { + verboseDebug("[ThemeManager] Restoring theme creator after navigation"); + const { OpenThemeCreator, isThemeCreatorOpen } = await import( + "@/plugins/built-in/themes/ThemeCreator" ); - this.clearPreview(); - localStorage.removeItem("themeCreatorOpen"); + if (!isThemeCreatorOpen()) { + void OpenThemeCreator(creatorSession.editingThemeId); + } } if (settingsState.selectedTheme) { @@ -373,6 +380,11 @@ export class ThemeManager { setCustomThemeAdaptiveCssVariables(theme.adaptiveCssVariables ?? []); + const { applyThemeCreatorMetaToSettings } = await import( + "@/interface/utils/themeCreatorMeta" + ); + applyThemeCreatorMetaToSettings(theme.creatorMeta); + injectThemeDom(theme.themeDom); } catch (error) { console.error("[ThemeManager] Error applying theme:", error); @@ -459,6 +471,23 @@ export class ThemeManager { /** * Stable key so preview updates can skip re-encoding image blobs when only CSS changed. */ + /** While Theme Creator is open, keep active theme image vars unless the draft replaces them. */ + private resolvePreviewImages( + theme: Partial, + ): Array<{ id: string; variableName: string; blob: Blob }> { + const draftImages = theme.CustomImages ?? []; + if (!this.themeCreatorSuspendedThemeId) return draftImages; + + const baseImages = this.currentTheme?.CustomImages ?? []; + if (draftImages.length === 0) return baseImages; + + const merged = new Map(baseImages.map((image) => [image.id, image])); + for (const image of draftImages) { + merged.set(image.id, image); + } + return [...merged.values()]; + } + private imageSyncKey( images: Array<{ id: string; variableName: string; blob: Blob }>, ): string { @@ -594,9 +623,9 @@ export class ThemeManager { name?: string; theme_json_url?: string; updated_at?: number; - }): Promise { + }): Promise { try { - await this.downloadAndInstallCommunityTheme(themeContent); + return await this.downloadAndInstallCommunityTheme(themeContent); } catch (error) { console.error("[ThemeManager] Error downloading community theme:", error); throw error; @@ -607,7 +636,7 @@ export class ThemeManager { id: string; theme_json_url?: string; updated_at?: number; - }): Promise { + }): Promise { verboseDebug("[ThemeManager] Downloading community theme:", themeContent.id); if (!themeContent.id) { throw new Error("Missing theme id"); @@ -629,11 +658,22 @@ export class ThemeManager { } const themeData = (await this.fetchFromUrl(themeJsonUrl)) as ThemeContent; - await this.installTheme(themeData, { - fromStore: true, - fromCommunity: true, - serverUpdatedAtSec: themeContent.updated_at, - }); + const catalogId = themeContent.id; + if (themeData.id && themeData.id !== catalogId) { + verboseDebug( + "[ThemeManager] Community theme.json id differs from catalog id; using catalog id", + { catalogId, themeJsonId: themeData.id }, + ); + } + await this.installTheme( + { ...themeData, id: catalogId }, + { + fromStore: false, + fromCommunity: true, + serverUpdatedAtSec: themeContent.updated_at, + }, + ); + return catalogId; } /** @@ -1013,15 +1053,21 @@ export class ThemeManager { } const syncInput: ThemePageSyncInput = {}; + const inCreatorSession = this.themeCreatorSuspendedThemeId !== null; if (theme.CustomCSS !== undefined) { syncInput.previewCss = theme.CustomCSS; } - if (theme.CustomImages) { - const imageKey = this.imageSyncKey(theme.CustomImages); - if (imageKey !== this.lastSyncedImageKey) { - syncInput.images = theme.CustomImages; + const previewImages = this.resolvePreviewImages(theme); + if (previewImages.length > 0) { + const imageKey = this.imageSyncKey(previewImages); + const shouldSyncImages = + inCreatorSession || + imageKey !== this.lastSyncedImageKey || + theme.CustomCSS !== undefined; + if (shouldSyncImages) { + syncInput.images = previewImages; this.lastSyncedImageKey = imageKey; } } @@ -1041,6 +1087,12 @@ export class ThemeManager { } setCustomThemeAdaptiveCssVariables(theme.adaptiveCssVariables ?? []); + + const { applyThemeCreatorMetaToSettings } = await import( + "@/interface/utils/themeCreatorMeta" + ); + applyThemeCreatorMetaToSettings(theme.creatorMeta); + void updateAllColors(); } catch (error) { console.error("[ThemeManager] Error updating theme preview:", error); @@ -1058,13 +1110,49 @@ export class ThemeManager { 2, ); + /** + * Start Theme Creator: keep the current theme on SEQTA; preview layers on top only. + */ + public beginThemeCreatorSession(): void { + const activeId = settingsState.selectedTheme?.trim() || ""; + this.themeCreatorSuspendedThemeId = activeId || null; + + if (this.originalPreviewColor === null) { + this.originalPreviewColor = settingsState.selectedColor; + } + if (this.originalPreviewTheme === null) { + this.originalPreviewTheme = settingsState.DarkMode; + } + + verboseDebug("[ThemeManager] Theme creator session started", { + suspendedThemeId: this.themeCreatorSuspendedThemeId, + }); + } + + /** + * End Theme Creator: drop preview CSS and re-apply the theme that was active before editing. + */ + public discardThemeCreatorRestore(): void { + this.themeCreatorSuspendedThemeId = null; + } + + public async endThemeCreatorSession(): Promise { + const restoreId = this.themeCreatorSuspendedThemeId; + this.themeCreatorSuspendedThemeId = null; + this.clearPreview(); + if (restoreId) { + verboseDebug("[ThemeManager] Restoring theme after creator exit:", restoreId); + await this.setTheme(restoreId, false); + } + } + /** * Clear theme preview */ public clearPreview(): void { verboseDebug("[ThemeManager] Clearing theme preview"); try { - void syncThemeToPage({ clearPreview: true, images: [] }); + void syncThemeToPage({ clearPreview: true }); this.lastSyncedImageKey = null; clearCustomThemeAdaptiveCssVariables(); diff --git a/src/plugins/built-in/themes/themeCreatorLayout.ts b/src/plugins/built-in/themes/themeCreatorLayout.ts new file mode 100644 index 00000000..80fc8283 --- /dev/null +++ b/src/plugins/built-in/themes/themeCreatorLayout.ts @@ -0,0 +1,34 @@ +let layoutObserver: MutationObserver | null = null; +let activePanelWidthPx = 0; + +export function applyThemeCreatorLayout(widthPx: number): void { + activePanelWidthPx = widthPx; + syncContainerWidth(); + startLayoutObserver(); +} + +export function clearThemeCreatorLayout(): void { + activePanelWidthPx = 0; + layoutObserver?.disconnect(); + layoutObserver = null; + const main = document.querySelector("#container") as HTMLElement | null; + if (main) main.style.width = "100%"; +} + +function syncContainerWidth(): void { + if (!activePanelWidthPx) return; + const main = document.querySelector("#container") as HTMLElement | null; + if (main) main.style.width = `calc(100% - ${activePanelWidthPx}px)`; +} + +function startLayoutObserver(): void { + layoutObserver?.disconnect(); + layoutObserver = new MutationObserver(() => { + if (!document.getElementById("themeCreator")) { + clearThemeCreatorLayout(); + return; + } + syncContainerWidth(); + }); + layoutObserver.observe(document.body, { childList: true, subtree: true }); +} diff --git a/src/plugins/built-in/themes/themeCreatorPersistence.ts b/src/plugins/built-in/themes/themeCreatorPersistence.ts new file mode 100644 index 00000000..d879f4d4 --- /dev/null +++ b/src/plugins/built-in/themes/themeCreatorPersistence.ts @@ -0,0 +1,24 @@ +const OPEN_KEY = "themeCreatorOpen"; +const EDITING_ID_KEY = "themeBuilderEditingId"; + +export function persistThemeCreatorSession(editingThemeId: string | null): void { + localStorage.setItem(OPEN_KEY, "true"); + if (editingThemeId) { + localStorage.setItem(EDITING_ID_KEY, editingThemeId); + } else { + localStorage.removeItem(EDITING_ID_KEY); + } +} + +export function clearThemeCreatorSession(): void { + localStorage.removeItem(OPEN_KEY); + localStorage.removeItem(EDITING_ID_KEY); + localStorage.removeItem("themeBuilderIntent"); +} + +export function readThemeCreatorSession(): { open: boolean; editingThemeId: string } { + return { + open: localStorage.getItem(OPEN_KEY) === "true", + editingThemeId: localStorage.getItem(EDITING_ID_KEY) ?? "", + }; +} diff --git a/src/seqta/utils/DevApiBase.test.ts b/src/seqta/utils/DevApiBase.test.ts new file mode 100644 index 00000000..fa9be59f --- /dev/null +++ b/src/seqta/utils/DevApiBase.test.ts @@ -0,0 +1,15 @@ +import { PRODUCTION_API_BASE, resolveApiBase } from "./apiBasePolicy"; + +describe("resolveApiBase", () => { + it("uses production during extension dev builds", () => { + expect(resolveApiBase("development", "http://localhost:3000")).toBe(PRODUCTION_API_BASE); + expect(resolveApiBase("development", null)).toBe(PRODUCTION_API_BASE); + }); + + it("honors session override in production builds", () => { + expect(resolveApiBase("production", "https://staging.example.test")).toBe( + "https://staging.example.test", + ); + expect(resolveApiBase("production", null)).toBe(PRODUCTION_API_BASE); + }); +}); diff --git a/src/seqta/utils/DevApiBase.ts b/src/seqta/utils/DevApiBase.ts index 49958da1..0f185fba 100644 --- a/src/seqta/utils/DevApiBase.ts +++ b/src/seqta/utils/DevApiBase.ts @@ -1,33 +1,54 @@ import browser from "webextension-polyfill"; +import { PRODUCTION_API_BASE, resolveApiBase } from "@/seqta/utils/apiBasePolicy"; + +export { PRODUCTION_API_BASE } from "@/seqta/utils/apiBasePolicy"; -const DEFAULT_BASE = "https://betterseqta.org"; const KEY = "bsplus_dev_api_base"; -/** - * Returns the current content-API base URL. - * - * Reads from `sessionStorage` so a developer can temporarily override the - * server for testing. The value is cleared when the browser session ends, - * leaving production traffic unaffected for normal users. - */ -export function getApiBase(): string { +function readSessionOverride(): string | null { try { - if (typeof sessionStorage === "undefined") return DEFAULT_BASE; + if (typeof sessionStorage === "undefined") return null; const v = sessionStorage.getItem(KEY); if (v && /^https?:\/\//.test(v)) return v.replace(/\/$/, ""); } catch { // sessionStorage may throw in some restricted contexts; fall back silently. } - return DEFAULT_BASE; + return null; +} + +function currentBuildMode(): "development" | "production" { + return import.meta.env.DEV ? "development" : "production"; +} + +/** + * Returns the current content-API base URL. + * + * In production builds, Advanced settings may set a session-only override for server testing. + * In extension dev builds, overrides are ignored and production is always used. + */ +export function getApiBase(): string { + return resolveApiBase(currentBuildMode(), readSessionOverride()); } /** * Persist a session-scoped override and broadcast it to the background script * so its `fetch` calls hit the same host. * - * Pass `null` to clear the override. + * Pass `null` to clear the override. No-op in extension dev builds. */ export function setApiBase(url: string | null): void { + if (import.meta.env.DEV) { + try { + sessionStorage.removeItem(KEY); + } catch { + // ignore + } + void browser.runtime + .sendMessage({ type: "setDevApiBase", url: null }) + .catch(() => {}); + return; + } + try { if (!url) { sessionStorage.removeItem(KEY); @@ -42,14 +63,10 @@ export function setApiBase(url: string | null): void { .catch(() => {}); } -/** Returns the override URL if one is currently set in this session. */ +/** Returns the override URL if one is currently active (production builds only). */ export function getStoredOverride(): string | null { - try { - if (typeof sessionStorage === "undefined") return null; - return sessionStorage.getItem(KEY); - } catch { - return null; - } + if (import.meta.env.DEV) return null; + return readSessionOverride(); } /** @@ -58,7 +75,7 @@ export function getStoredOverride(): string | null { * service-worker restarts. */ export function syncApiBaseToBackground(): void { - const override = getStoredOverride(); + const override = import.meta.env.DEV ? null : readSessionOverride(); void browser.runtime .sendMessage({ type: "setDevApiBase", url: override }) .catch(() => {}); diff --git a/src/seqta/utils/apiBasePolicy.ts b/src/seqta/utils/apiBasePolicy.ts new file mode 100644 index 00000000..9d6d64c7 --- /dev/null +++ b/src/seqta/utils/apiBasePolicy.ts @@ -0,0 +1,14 @@ +export const PRODUCTION_API_BASE = "https://betterseqta.org"; + +/** + * Resolves the content API host. Extension dev builds always use production + * so community theme submit and the theme store work against the live API. + */ +export function resolveApiBase( + buildMode: "development" | "production", + sessionOverride: string | null, +): string { + if (buildMode === "development") return PRODUCTION_API_BASE; + if (sessionOverride) return sessionOverride; + return PRODUCTION_API_BASE; +} diff --git a/src/seqta/utils/customThemes/apiErrors.ts b/src/seqta/utils/customThemes/apiErrors.ts new file mode 100644 index 00000000..1114d423 --- /dev/null +++ b/src/seqta/utils/customThemes/apiErrors.ts @@ -0,0 +1,16 @@ +import { CustomThemeApiError } from "./client"; +import { RATE_LIMIT_DAILY_MESSAGE, RATE_LIMIT_PENDING_MESSAGE } from "./constants"; + +export function formatCustomThemeApiError(err: unknown): string { + if (err instanceof CustomThemeApiError) { + if (err.status === 429) { + return err.message.includes("pending") ? RATE_LIMIT_PENDING_MESSAGE : RATE_LIMIT_DAILY_MESSAGE; + } + if (err.validationErrors.length > 0) { + return err.validationErrors.join("\n"); + } + return err.message; + } + return err instanceof Error ? err.message : "Something went wrong"; +} + \ No newline at end of file diff --git a/src/seqta/utils/customThemes/client.test.ts b/src/seqta/utils/customThemes/client.test.ts index d8e744b0..9f52b337 100644 --- a/src/seqta/utils/customThemes/client.test.ts +++ b/src/seqta/utils/customThemes/client.test.ts @@ -3,7 +3,12 @@ import { statusBadgeClass, canEditCustomTheme, } from "./client"; -import { parseApiError, parseValidationErrors } from "./parseApiEnvelope"; +import { + formatEnvelopeErrorMessage, + normalizeCustomThemeApiResponse, + parseApiError, + parseValidationErrors, +} from "./parseApiEnvelope"; describe("customThemes client helpers", () => { it("formats status labels", () => { @@ -26,6 +31,7 @@ describe("customThemes client helpers", () => { it("parses API envelope errors and validation details", () => { expect(parseApiError({ code: "INVALID_THEME_STRUCTURE", message: "Bad theme" })).toBe("Bad theme"); + expect(parseApiError(null, 500)).toBe("Request failed (HTTP 500)"); expect( parseValidationErrors({ code: "INVALID_THEME_STRUCTURE", @@ -33,5 +39,25 @@ describe("customThemes client helpers", () => { details: { errors: ["Missing CustomCSS", "Missing name"] }, }), ).toEqual(["Missing CustomCSS", "Missing name"]); + expect( + formatEnvelopeErrorMessage({ + success: false, + data: null, + error: { code: "INVALID_THEME_STRUCTURE", message: "Bad theme" }, + httpStatus: 422, + }), + ).toContain("Bad theme"); + }); + + it("normalizes Laravel validation bodies", () => { + const out = normalizeCustomThemeApiResponse( + { + message: "The given data was invalid.", + errors: { theme_zip: ["The theme zip field is required."] }, + }, + 422, + ); + expect(out.success).toBe(false); + expect((out.error as { message: string }).message).toContain("theme_zip"); }); }); diff --git a/src/seqta/utils/customThemes/client.ts b/src/seqta/utils/customThemes/client.ts index 0c432fba..5f88a01f 100644 --- a/src/seqta/utils/customThemes/client.ts +++ b/src/seqta/utils/customThemes/client.ts @@ -2,7 +2,7 @@ import browser from "webextension-polyfill"; import type { CustomThemeStatus } from "./constants"; import { formatThemeDate } from "./formatThemeDate"; import { normalizeCustomTheme } from "./normalizeCustomTheme"; -import { parseApiError, parseValidationErrors } from "./parseApiEnvelope"; +import { formatEnvelopeErrorMessage, parseValidationErrors } from "./parseApiEnvelope"; import type { CustomThemeApiEnvelope, CustomThemeDetailResponse, @@ -25,10 +25,25 @@ export class CustomThemeApiError extends Error { } const FETCH_TIMEOUT_MS = 25_000; +const EXTENSION_RELOAD_HINT = + "Extension reloaded — refresh the SEQTA tab and reopen settings after `pnpm dev` updates, then try again."; + +async function sendRuntimeMessage(message: object): Promise { + try { + if (!browser.runtime?.id) throw new Error(EXTENSION_RELOAD_HINT); + return (await browser.runtime.sendMessage(message)) as T; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if (/disconnected port|context invalidated|receiving end does not exist|message port closed/i.test(msg)) { + throw new Error(EXTENSION_RELOAD_HINT); + } + throw err; + } +} function sendMessageWithTimeout(message: object): Promise { return Promise.race([ - browser.runtime.sendMessage(message) as Promise, + sendRuntimeMessage(message), new Promise((_, reject) => { setTimeout( () => @@ -46,13 +61,14 @@ function sendMessageWithTimeout(message: object): Promise { function throwFromEnvelope( envelope: CustomThemeApiEnvelope & { httpStatus?: number }, ): never { - const status = envelope.httpStatus ?? 0; const errObj = envelope.error && typeof envelope.error === "object" ? envelope.error : undefined; - const message = parseApiError(envelope.error); - const code = errObj?.code; - const validationErrors = parseValidationErrors(errObj); - throw new CustomThemeApiError(message, status, code, validationErrors); + throw new CustomThemeApiError( + formatEnvelopeErrorMessage(envelope), + envelope.httpStatus ?? 0, + errObj?.code, + parseValidationErrors(errObj), + ); } export function formatCustomThemeStatus(status: CustomThemeStatus | string | undefined): string { @@ -140,11 +156,24 @@ export async function fetchMyCustomThemeDetail(id: string): Promise { - const res = await sendMessageWithTimeout>({ + const res = await sendMessageWithTimeout< + CustomThemeApiEnvelope & { httpStatus?: number } + >({ type: "submitCustomTheme", payload, }); - if (!res.success || !res.data?.theme) throwFromEnvelope(res); + if (!res || typeof res !== "object" || !res.success || !res.data?.theme) { + throwFromEnvelope( + res && typeof res === "object" + ? res + : { + success: false, + data: null, + error: "Empty response from extension background", + httpStatus: 0, + }, + ); + } return { theme: normalizeCustomTheme(res.data.theme as unknown as Record), validation: res.data.validation, diff --git a/src/seqta/utils/customThemes/parseApiEnvelope.ts b/src/seqta/utils/customThemes/parseApiEnvelope.ts index b170a813..764e42d0 100644 --- a/src/seqta/utils/customThemes/parseApiEnvelope.ts +++ b/src/seqta/utils/customThemes/parseApiEnvelope.ts @@ -1,10 +1,18 @@ import type { CustomThemeApiEnvelope, CustomThemeApiError } from "./types"; -export function parseApiError(error: CustomThemeApiEnvelope["error"]): string { - if (!error) return "Request failed"; - if (typeof error === "string") return error; - if (typeof error.message === "string" && error.message.length > 0) return error.message; - if (typeof error.code === "string") return error.code; +export function parseApiError( + error: CustomThemeApiEnvelope["error"], + httpStatus?: number, + envelope?: Record, +): string { + if (typeof error === "string" && error.length > 0) return error; + if (error && typeof error === "object") { + const err = error as CustomThemeApiError; + if (err.message) return err.message; + if (err.code) return err.code; + } + if (envelope?.message && typeof envelope.message === "string") return envelope.message; + if (httpStatus && httpStatus > 0) return `Request failed (HTTP ${httpStatus})`; return "Request failed"; } @@ -12,3 +20,77 @@ export function parseValidationErrors(error: CustomThemeApiError | null | undefi if (!error?.details?.errors || !Array.isArray(error.details.errors)) return []; return error.details.errors.filter((e): e is string => typeof e === "string"); } + +export function formatEnvelopeErrorMessage( + envelope: CustomThemeApiEnvelope & { httpStatus?: number }, +): string { + const status = envelope.httpStatus ?? 0; + const envRecord = envelope as Record; + const errObj = + envelope.error && typeof envelope.error === "object" + ? (envelope.error as CustomThemeApiError) + : undefined; + const base = parseApiError(envelope.error, status, envRecord); + const validationErrors = parseValidationErrors(errObj); + const code = errObj?.code ?? (typeof envRecord.code === "string" ? envRecord.code : undefined); + const parts = [base]; + if (code && !base.includes(code)) parts.push(`[${code}]`); + if (status > 0 && !base.includes(`HTTP ${status}`)) parts.push(`(HTTP ${status})`); + if (validationErrors.length) parts.push(validationErrors.join("\n")); + return parts.join(" ").trim() || `Request failed (HTTP ${status || "unknown"})`; +} + +/** Normalize fetch JSON into the custom-themes API envelope (incl. Laravel validation bodies). */ +export function normalizeCustomThemeApiResponse( + body: unknown, + httpStatus: number, + rawText?: string, +): Record { + if (!body || typeof body !== "object") { + const snippet = rawText?.trim().slice(0, 280); + return { + success: false, + data: null, + error: { + message: snippet + ? `Unexpected response (HTTP ${httpStatus}): ${snippet}` + : `Unexpected response (HTTP ${httpStatus})`, + }, + httpStatus, + }; + } + + const record = body as Record; + if (record.success === true) return { ...record, httpStatus }; + + let error = record.error; + if (!error) { + const flat = + record.errors && typeof record.errors === "object" + ? flattenValidationMap(record.errors as Record) + : []; + const topMessage = typeof record.message === "string" ? record.message : ""; + if (flat.length > 0) { + error = { message: flat.join("; "), details: { errors: flat } }; + } else if (topMessage) { + error = { message: topMessage }; + } + } + if (!error) error = { message: `Request failed (HTTP ${httpStatus})` }; + + return { success: false, data: record.data ?? null, error, httpStatus, meta: record.meta }; +} + +function flattenValidationMap(errors: Record): string[] { + const out: string[] = []; + for (const [field, value] of Object.entries(errors)) { + if (Array.isArray(value)) { + for (const item of value) { + if (typeof item === "string" && item.length > 0) out.push(`${field}: ${item}`); + } + } else if (typeof value === "string" && value.length > 0) { + out.push(`${field}: ${value}`); + } + } + return out; +} diff --git a/src/seqta/utils/customThemes/submitLocalTheme.ts b/src/seqta/utils/customThemes/submitLocalTheme.ts new file mode 100644 index 00000000..f05a9930 --- /dev/null +++ b/src/seqta/utils/customThemes/submitLocalTheme.ts @@ -0,0 +1,25 @@ +import { ensureThemeCoverImage } from "@/interface/utils/themePlaceholderCover"; +import { ThemeManager } from "@/plugins/built-in/themes/theme-manager"; +import { + buildUploadPartsFromLocalTheme, + mergeUploadPayload, +} from "@/seqta/utils/customThemes/buildThemeUploadFormData"; +import { submitCustomTheme } from "@/seqta/utils/customThemes/client"; +import type { LoadedCustomTheme } from "@/types/CustomThemes"; + +export async function submitLocalThemeToCommunity( + theme: LoadedCustomTheme, + submissionNotes?: string, +) { + const payload = mergeUploadPayload(await buildUploadPartsFromLocalTheme(theme), submissionNotes); + return await submitCustomTheme(payload); +} + +export async function submitThemeById(themeId: string, submissionNotes?: string) { + const theme = await ThemeManager.getInstance().getTheme(themeId); + if (!theme) throw new Error("Theme not found"); + return submitLocalThemeToCommunity( + await ensureThemeCoverImage(theme as LoadedCustomTheme), + submissionNotes, + ); +} diff --git a/src/seqta/utils/launchPageThemeBuilder.ts b/src/seqta/utils/launchPageThemeBuilder.ts new file mode 100644 index 00000000..31fbb523 --- /dev/null +++ b/src/seqta/utils/launchPageThemeBuilder.ts @@ -0,0 +1,8 @@ +/** Close settings (if open) and mount the theme builder on the SEQTA page body. */ +export async function launchPageThemeBuilder(themeId?: string): Promise { + const { closeExtensionPopup } = await import("@/seqta/utils/Closers/closeExtensionPopup"); + const { OpenThemeCreator } = await import("@/plugins/built-in/themes/ThemeCreator"); + + closeExtensionPopup(); + await OpenThemeCreator(themeId ?? ""); +} diff --git a/src/seqta/utils/openCommunityThemeSubmit.test.ts b/src/seqta/utils/openCommunityThemeSubmit.test.ts index 4dc5ac7f..31ae8c16 100644 --- a/src/seqta/utils/openCommunityThemeSubmit.test.ts +++ b/src/seqta/utils/openCommunityThemeSubmit.test.ts @@ -2,6 +2,7 @@ import { consumeOpenCommunityThemeSubmit, + consumePendingCommunitySubmitThemeId, requestOpenCommunityThemeSubmit, } from "./openCommunityThemeSubmit"; @@ -24,4 +25,10 @@ describe("openCommunityThemeSubmit", () => { expect(consumeOpenCommunityThemeSubmit()).toBe(true); expect(consumeOpenCommunityThemeSubmit()).toBe(false); }); + + it("hands off a theme id for the submit modal", () => { + requestOpenCommunityThemeSubmit("theme-abc"); + expect(consumePendingCommunitySubmitThemeId()).toBe("theme-abc"); + expect(consumePendingCommunitySubmitThemeId()).toBeNull(); + }); }); diff --git a/src/seqta/utils/openCommunityThemeSubmit.ts b/src/seqta/utils/openCommunityThemeSubmit.ts index ac05ae6a..f407e8aa 100644 --- a/src/seqta/utils/openCommunityThemeSubmit.ts +++ b/src/seqta/utils/openCommunityThemeSubmit.ts @@ -2,21 +2,40 @@ * Module-level handoff for "open Community themes → My themes → submit modal". */ const OPEN_COMMUNITY_SUBMIT_SESSION_KEY = "bsplus:open-community-theme-submit"; +const OPEN_COMMUNITY_SUBMIT_THEME_KEY = "bsplus:open-community-theme-submit-theme-id"; export const OPEN_COMMUNITY_SUBMIT_EVENT = "bsplus:open-community-submit"; let pendingOpenSubmit = false; +let pendingSubmitThemeId: string | null = null; -export function requestOpenCommunityThemeSubmit(): void { +export function requestOpenCommunityThemeSubmit(themeId?: string): void { pendingOpenSubmit = true; + if (themeId) pendingSubmitThemeId = themeId; try { sessionStorage.setItem(OPEN_COMMUNITY_SUBMIT_SESSION_KEY, "1"); + if (themeId) sessionStorage.setItem(OPEN_COMMUNITY_SUBMIT_THEME_KEY, themeId); } catch { /* ignore */ } window.dispatchEvent(new CustomEvent(OPEN_COMMUNITY_SUBMIT_EVENT)); } +export function consumePendingCommunitySubmitThemeId(): string | null { + let themeId = pendingSubmitThemeId; + pendingSubmitThemeId = null; + try { + const stored = sessionStorage.getItem(OPEN_COMMUNITY_SUBMIT_THEME_KEY); + if (stored) { + sessionStorage.removeItem(OPEN_COMMUNITY_SUBMIT_THEME_KEY); + themeId = stored; + } + } catch { + /* ignore */ + } + return themeId; +} + export function consumeOpenCommunityThemeSubmit(): boolean { let shouldOpen = pendingOpenSubmit; pendingOpenSubmit = false; @@ -33,13 +52,7 @@ export function consumeOpenCommunityThemeSubmit(): boolean { return shouldOpen; } -export async function openCommunityThemeSubmit(): Promise { - requestOpenCommunityThemeSubmit(); - const [{ requestSettingsDestination }, { openSettingsPopup }] = - await Promise.all([ - import("@/seqta/utils/settingsNavigation"), - import("@/seqta/utils/setupSettingsButton"), - ]); - requestSettingsDestination({ page: "themes", view: "community" }); - await openSettingsPopup(); +export async function openCommunityThemeSubmit(themeId?: string): Promise { + const { launchPageThemeBuilder } = await import("@/seqta/utils/launchPageThemeBuilder"); + await launchPageThemeBuilder(themeId); } diff --git a/src/seqta/utils/searchThemeStockPhotos.ts b/src/seqta/utils/searchThemeStockPhotos.ts new file mode 100644 index 00000000..d770612b --- /dev/null +++ b/src/seqta/utils/searchThemeStockPhotos.ts @@ -0,0 +1,25 @@ +import browser from "webextension-polyfill"; + +export type StockPhotoResult = { title: string; thumbUrl: string; imageUrl: string }; + +export async function searchThemeStockPhotos( + query: string, + limit = 8, +): Promise { + const res = (await browser.runtime.sendMessage({ + type: "searchThemeStockPhotos", + query, + limit, + })) as { success?: boolean; results?: StockPhotoResult[]; error?: string }; + + if (!res?.success || !res.results) { + throw new Error(res?.error ?? "Could not search photos"); + } + return res.results; +} + +export async function fetchStockPhotoBlob(imageUrl: string): Promise { + const res = await fetch(imageUrl); + if (!res.ok) throw new Error("Could not download photo"); + return await res.blob(); +} diff --git a/src/seqta/utils/themeImagePagePatch.js b/src/seqta/utils/themeImagePagePatch.js index 899e984e..a4fca4d7 100644 --- a/src/seqta/utils/themeImagePagePatch.js +++ b/src/seqta/utils/themeImagePagePatch.js @@ -131,6 +131,10 @@ if (payload.previewCss !== undefined) { setStyleText(PREVIEW_STYLE_ID, payload.previewCss || ""); + var previewStyle = document.getElementById(PREVIEW_STYLE_ID); + if (previewStyle) { + document.head.appendChild(previewStyle); + } } if (payload.clearPreview) { diff --git a/src/types/CustomThemes.ts b/src/types/CustomThemes.ts index 3eb2ff7a..817c81f0 100644 --- a/src/types/CustomThemes.ts +++ b/src/types/CustomThemes.ts @@ -41,6 +41,30 @@ export type CustomTheme = { flickers?: number; cityLayers?: boolean; }; + /** Theme Creator quick settings (font, page background, sidebar snapshot). */ + creatorMeta?: ThemeCreatorMeta; +}; + +export type ThemeCreatorMeta = { + fontId: string; + /** CustomImages entry used as the SEQTA page background layer. */ + pageBackgroundImageId: string | null; + backgroundBlurPx: number; + overlayOpacity: number; + gradientAngle: number; + gradientEnd: string; + /** Advanced CSS appended after generated builder rules. */ + userCustomCss: string; + sidebar?: { + sidebarStyle?: string; + sidebarDensity?: string; + sidebarCornerRadius?: number; + sidebarActiveIndicator?: string; + sidebarWidth?: string; + sidebarPosition?: string; + sidebarBlur?: number; + transparencyEffects?: boolean; + }; }; export type LoadedCustomTheme = CustomTheme & { From 7bc4c5561994db2265de9cf06068c8b45dc2dbac Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Tue, 29 Sep 2026 10:54:35 +0930 Subject: [PATCH 7/7] fix(test): mock DevApiBase in feedback client tests for Jest ESM Co-authored-by: Cursor --- src/seqta/utils/feedback/client.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/seqta/utils/feedback/client.test.ts b/src/seqta/utils/feedback/client.test.ts index ce0f4060..28213c0e 100644 --- a/src/seqta/utils/feedback/client.test.ts +++ b/src/seqta/utils/feedback/client.test.ts @@ -1,3 +1,7 @@ +jest.mock("@/seqta/utils/DevApiBase", () => ({ + getApiBase: () => "https://example.test", +})); + import browser from "webextension-polyfill"; import { addPendingFeedbackId,