feat: allow admins to preview community themes b4 published

This commit is contained in:
AdenMGB committed 2026-10-30 18:51:58 +10:30
1 parent 325f194638
commit 009670e201
10 files changed
+346 -14

No files matched your search

+29 -6
View File
@@ -192,13 +192,36 @@ function handleFetchFromUrl(
sendResponse({ error: "URL not allowed" });
return false;
}
fetch(url, { cache: "no-store" })
.then((r) => r.json())
.then((data) => sendResponse({ data }))
.catch((err) => {
void (async () => {
try {
const headers: Record<string, string> = { Accept: "application/json" };
if (request.auth === true) {
const token = await getAccessTokenFromStorage();
if (!token) {
sendResponse({ error: "Not authenticated" });
return;
}
headers.Authorization = `Bearer ${token}`;
}
const r = await fetch(url, { cache: "no-store", headers });
const text = await r.text();
if (!r.ok) {
sendResponse({
error: text?.slice(0, 200) || `HTTP ${r.status}`,
httpStatus: r.status,
});
return;
}
try {
sendResponse({ data: text ? JSON.parse(text) : {} });
} catch {
sendResponse({ error: "Invalid JSON response" });
}
} catch (err) {
console.error("[Background] fetchFromUrl error:", err);
sendResponse({ error: err?.message });
});
sendResponse({ error: (err as Error)?.message });
}
})();
return true;
}
+37
View File
@@ -286,6 +286,41 @@ export function createCustomThemesHandlers(deps: {
return true;
}
function handleFetchBsplusAdminMe(_request: unknown, sendResponse: MessageSender): boolean {
void (async () => {
try {
sendResponse(await customThemesJsonFetch("/api/bsplus/admin/me", {}, true));
} catch (err) {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
function handleFetchBsplusAdminThemes(request: any, sendResponse: MessageSender): boolean {
void (async () => {
try {
const params = new URLSearchParams();
params.set("page", String(request.page ?? 1));
params.set("limit", String(Math.min(Number(request.limit ?? 20) || 20, 100)));
if (request.status) params.set("status", String(request.status));
if (request.source) params.set("source", String(request.source));
const search = request.search?.trim();
if (search) params.set("search", search);
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
} catch (err) {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
return {
fetchCustomThemes: handleFetchCustomThemes,
fetchMyCustomThemes: handleFetchMyCustomThemes,
@@ -294,5 +329,7 @@ export function createCustomThemesHandlers(deps: {
replaceCustomThemeFiles: handleReplaceCustomThemeFiles,
updateCustomThemeMetadata: handleUpdateCustomThemeMetadata,
deleteCustomTheme: handleDeleteCustomTheme,
fetchBsplusAdminMe: handleFetchBsplusAdminMe,
fetchBsplusAdminThemes: handleFetchBsplusAdminThemes,
};
}
@@ -0,0 +1,81 @@
<script lang="ts">
import ThemeGrid from "@/interface/components/store/ThemeGrid.svelte";
import ThemeModal from "@/interface/components/store/ThemeModal.svelte";
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
import Select from "@/interface/components/Select.svelte";
import type { CommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
let { communityState, searchTerm }: { communityState: CommunityThemesState; searchTerm: string } =
$props();
</script>
<div class="mb-6 flex flex-wrap items-end gap-4">
<div class="min-w-[10rem]">
<span class="mb-1 block text-sm font-medium">Status</span>
<Select
value={communityState.reviewStatusFilter}
onChange={(v) => (communityState.reviewStatusFilter = v as typeof communityState.reviewStatusFilter)}
options={[
{ value: "pending", label: "Pending" },
{ value: "approved", label: "Approved" },
{ value: "rejected", label: "Rejected" },
]}
/>
</div>
<div class="min-w-[10rem]">
<span class="mb-1 block text-sm font-medium">Source</span>
<Select
value={communityState.reviewSourceFilter}
onChange={(v) =>
(communityState.reviewSourceFilter = v as typeof communityState.reviewSourceFilter)}
options={[
{ value: "", label: "All sources" },
{ value: "marketplace", label: "Official store" },
{ value: "community", label: "Community" },
]}
/>
</div>
</div>
{#if communityState.reviewLoading}
<div class="grid grid-cols-1 gap-4 py-6 sm:grid-cols-2 lg:grid-cols-3">
{#each Array(6) as _, i (i)}
<SkeletonLoader width="100%" height="200px" />
{/each}
</div>
{:else if communityState.reviewError}
<p class="py-16 text-center text-red-600 dark:text-red-400">{communityState.reviewError}</p>
{:else if communityState.reviewThemes.length === 0}
<p class="py-16 text-center text-zinc-500">No themes match this filter.</p>
{:else}
<ThemeGrid
themes={communityState.reviewThemes}
{searchTerm}
setDisplayTheme={(t) => (communityState.displayTheme = t)}
toggleFavorite={() => {}}
isLoggedIn={false}
installedThemeIds={communityState.currentThemes}
variant="community"
/>
{#if communityState.displayTheme}
<ThemeModal
currentThemes={communityState.currentThemes}
allThemes={communityState.reviewThemes}
theme={communityState.displayTheme}
displayTheme={communityState.displayTheme}
setDisplayTheme={(t) => (communityState.displayTheme = t)}
selectedThemeId={communityState.selectedThemeId}
installedThemeColors={communityState.installedThemeColors}
variant="community"
adminPreviewMode
onInstall={(id) => void communityState.previewAdminTheme(id, communityState.displayTheme!)}
onRemove={(id) => void communityState.removeInstalledTheme(id)}
onApply={(id) => void communityState.applyInstalledTheme(id)}
/>
{#if communityState.reviewPreviewError}
<p class="fixed bottom-6 left-1/2 z-[100000] -translate-x-1/2 rounded-lg bg-red-600 px-4 py-2 text-sm text-white" role="alert">
{communityState.reviewPreviewError}
</p>
{/if}
{/if}
{/if}
@@ -29,6 +29,7 @@ onRequestSignIn,
selectedThemeId = '',
installedThemeColors = {},
variant = 'official',
adminPreviewMode = false,
} = $props<{
theme: Theme | null
currentThemes: string[]
@@ -46,7 +47,9 @@ onRequestSignIn?: () => void
selectedThemeId?: string
installedThemeColors?: Record<string, string>
variant?: 'official' | 'community'
adminPreviewMode?: boolean
}>()
const installActionLabel = $derived(adminPreviewMode ? 'Preview & apply' : 'Install')
const isCommunity = $derived(variant === 'community')
const showFavorites = $derived(!isCommunity)
function variantApplyStyles(variantId: string) {
@@ -254,12 +257,16 @@ By {theme.author}
</p>
{/if}
<div class="flex gap-4 mb-4 text-sm text-zinc-600 dark:text-zinc-400">
{#if !adminPreviewMode}
<span class="flex items-center gap-1.5">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
</svg>
{modalDisplayDownloadCount.toLocaleString()} downloads
</span>
{:else}
<span class="text-amber-700 dark:text-amber-300">Admin preview — does not count as a public download</span>
{/if}
{#if showFavorites}
<span class="flex items-center gap-1.5">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill={theme.is_favorited ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="1.5" class="w-4 h-4">
@@ -526,7 +533,7 @@ class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] text-bla
<path stroke="currentColor" fill="currentColor" class="origin-center animate-spin-fast" d="M2,12A11.2,11.2,0,0,1,13,1.05C12.67,1,12.34,1,12,1a11,11,0,0,0,0,22c.34,0,.67,0,1-.05C6,23,2,17.74,2,12Z"/>
</svg>
{/if}
<span class="{installingId === theme.id ? 'opacity-0' : 'opacity-100'}">Install</span>
<span class="{installingId === theme.id ? 'opacity-0' : 'opacity-100'}">{installActionLabel}</span>
</button>
{/if}
{/if}
@@ -1,9 +1,10 @@
import browser from "webextension-polyfill";
import type { Theme } from "@/interface/types/Theme";
import { getCommunityInstalledThemeIds } from "@/interface/utils/themeListFilters";
import { getCommunityInstalledThemeIds, getStoreInstalledThemeIds } from "@/interface/utils/themeListFilters";
import { normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { cloudAuth, isCloudAdmin } from "@/seqta/utils/CloudAuth";
import {
deleteCustomTheme,
fetchCommunityThemes,
@@ -23,16 +24,24 @@ import {
consumePendingCommunitySubmitThemeId,
OPEN_COMMUNITY_SUBMIT_EVENT,
} from "@/seqta/utils/openCommunityThemeSubmit";
export type CommunityThemesTab = "browse" | "mine";
export type CommunityThemesTab = "browse" | "mine" | "review";
export class CommunityThemesState {
innerTab = $state<CommunityThemesTab>("browse");
cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
isAdmin = $state(isCloudAdmin(cloudAuth.state.user));
browseThemes = $state<Theme[]>([]);
browseLoading = $state(true);
browseError = $state<string | null>(null);
reviewThemes = $state<Theme[]>([]);
reviewLoading = $state(false);
reviewError = $state<string | null>(null);
reviewStatusFilter = $state<"pending" | "approved" | "rejected">("pending");
reviewSourceFilter = $state<"" | "marketplace" | "community">("");
reviewPreviewError = $state<string | null>(null);
myThemes = $state<CustomThemeOwner[]>([]);
myLoading = $state(false);
myError = $state<string | null>(null);
@@ -62,7 +71,10 @@ export class CommunityThemesState {
async refreshInstalledThemes() {
const themes = await this.themeManager.getAvailableThemes();
this.currentThemes = getCommunityInstalledThemeIds(themes);
this.currentThemes = [
...getCommunityInstalledThemeIds(themes),
...getStoreInstalledThemeIds(themes),
];
this.selectedThemeId = this.themeManager.getSelectedThemeId() || "";
this.installedThemeColors = Object.fromEntries(
themes
@@ -71,6 +83,90 @@ export class CommunityThemesState {
);
}
async syncAdminAccess() {
if (!this.cloudLoggedIn) {
this.isAdmin = false;
return;
}
if (isCloudAdmin(cloudAuth.state.user)) {
this.isAdmin = true;
return;
}
try {
const res = (await browser.runtime.sendMessage({ type: "fetchBsplusAdminMe" })) as {
success?: boolean;
data?: { admin_level?: number; id?: string; username?: string };
httpStatus?: number;
};
if (res?.success && res.data && cloudAuth.state.user) {
await cloudAuth.setUser({
...cloudAuth.state.user,
admin_level: res.data.admin_level ?? cloudAuth.state.user.admin_level,
username: res.data.username ?? cloudAuth.state.user.username,
});
}
} catch {
// ignore — tab may need reload after extension update
}
this.isAdmin = isCloudAdmin(cloudAuth.state.user);
}
async loadReviewThemes() {
if (!this.isAdmin) return;
this.reviewLoading = true;
this.reviewError = null;
try {
const q = this.getSearchTerm().trim();
const res = (await browser.runtime.sendMessage({
type: "fetchBsplusAdminThemes",
status: this.reviewStatusFilter,
source: this.reviewSourceFilter || undefined,
search: q.length > 0 ? q : undefined,
limit: 50,
})) as { success?: boolean; data?: { themes?: unknown[] }; error?: unknown };
if (!res?.success || !Array.isArray(res.data?.themes)) {
throw new Error(
typeof res?.error === "string" ? res.error : "Could not load admin themes",
);
}
this.reviewThemes = res.data.themes
.map((row) => {
const theme = normalizeStoreTheme(row as Record<string, unknown>);
const source = (row as Record<string, unknown>).source;
theme.adminSource = source === "community" ? "community" : "marketplace";
const preview = (row as Record<string, unknown>).preview as
| { thumbnail?: string }
| undefined;
if (preview?.thumbnail) theme.coverImage = preview.thumbnail;
return theme;
})
.filter((t) => t.id.length > 0);
} catch (err) {
this.reviewError = err instanceof Error ? err.message : "Could not load admin themes";
} finally {
this.reviewLoading = false;
}
}
async previewAdminTheme(themeId: string, meta: Theme) {
const source = meta.adminSource ?? "community";
this.reviewPreviewError = null;
try {
const installedId = await this.themeManager.previewAdminTheme({
id: themeId,
source,
updated_at: meta.updated_at,
});
await this.themeManager.setTheme(installedId);
themeUpdates.triggerUpdate();
await this.refreshInstalledThemes();
this.selectedThemeId = installedId;
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
} catch (err) {
this.reviewPreviewError = err instanceof Error ? err.message : "Preview failed";
}
}
async loadBrowseThemes() {
this.browseLoading = true;
this.browseError = null;
@@ -141,7 +237,6 @@ export class CommunityThemesState {
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);
@@ -219,10 +314,16 @@ export class CommunityThemesState {
$effect(() => {
const unsub = cloudAuth.subscribe((s) => {
this.cloudLoggedIn = s.isLoggedIn;
this.isAdmin = isCloudAdmin(s.user);
});
return unsub;
});
$effect(() => {
if (this.cloudLoggedIn) void this.syncAdminAccess();
else this.isAdmin = false;
});
$effect(() => {
if (this.innerTab === "browse") void this.loadBrowseThemes();
});
@@ -240,12 +341,20 @@ export class CommunityThemesState {
this.statusFilter;
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
});
$effect(() => {
this.reviewStatusFilter;
this.reviewSourceFilter;
this.getSearchTerm();
if (this.innerTab === "review" && this.isAdmin) void this.loadReviewThemes();
});
}
mount() {
const onThemesUpdated = () => void this.refreshInstalledThemes();
themeUpdates.addListener(onThemesUpdated);
void this.refreshInstalledThemes();
void this.syncAdminAccess();
const openPageBuilderForSubmit = () => {
const themeId = consumePendingCommunitySubmitThemeId() ?? undefined;
+15 -1
View File
@@ -3,6 +3,7 @@
import Button from "@/interface/components/Button.svelte";
import BrowsePanel from "@/interface/components/communityThemes/BrowsePanel.svelte";
import MyThemesPanel from "@/interface/components/communityThemes/MyThemesPanel.svelte";
import ReviewPanel from "@/interface/components/communityThemes/ReviewPanel.svelte";
import OwnerThemeDetailModal from "@/interface/components/communityThemes/OwnerThemeDetailModal.svelte";
import { createCommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
@@ -36,6 +37,17 @@
>
My themes
</button>
{#if communityState.isAdmin}
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {communityState.innerTab === 'review'
? 'bg-white text-zinc-900 shadow dark:bg-zinc-700 dark:text-white'
: 'text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-white'}"
onclick={() => (communityState.innerTab = "review")}
>
Review queue
</button>
{/if}
</div>
<Button
variant="primary"
@@ -54,8 +66,10 @@
<main class="min-h-0 flex-1 overflow-y-auto bg-zinc-50/80 px-6 py-6 dark:bg-zinc-900/40 md:px-8 lg:px-10">
{#if communityState.innerTab === "browse"}
<BrowsePanel {communityState} {searchTerm} />
{:else}
{:else if communityState.innerTab === "mine"}
<MyThemesPanel {communityState} />
{:else if communityState.innerTab === "review"}
<ReviewPanel {communityState} {searchTerm} />
{/if}
</main>
+2
View File
@@ -35,6 +35,8 @@ export type Theme = {
master_id?: string;
/** Variants nested on master rows; installs use flavour `id` */
flavours?: ThemeFlavour[];
/** Admin review list: required for preview install (`marketplace` | `community`). */
adminSource?: "marketplace" | "community";
};
/** One marquee slide (cover hero or modal carousel). */
@@ -100,4 +100,29 @@ describe("cloud theme restoration", () => {
[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id",
});
});
it("installs via admin preview endpoints with auth", async () => {
const jsonUrl =
"https://betterseqta.org/api/bsplus/admin/themes/t1/theme.json?source=community";
(browser.runtime.sendMessage as jest.Mock).mockImplementation(async (msg) => {
if (msg.type === "fetchFromUrl" && msg.url.includes("/preview?")) {
return { data: { data: { theme_json_url: jsonUrl } } };
}
if (msg.type === "fetchFromUrl" && msg.url === jsonUrl && msg.auth === true) {
return {
data: { id: "t1", name: "Pending theme", CustomCSS: "body { color: green; }" },
};
}
return { error: "unexpected" };
});
const id = await ThemeManager.getInstance().previewAdminTheme({
id: "t1",
source: "community",
});
expect(id).toBe("t1");
expect(await localforage.getItem("t1")).toMatchObject({
installedFromCommunity: true,
});
});
});
+31 -1
View File
@@ -592,10 +592,11 @@ export class ThemeManager {
/**
* Fetch JSON from a URL via background script (avoids CORS when running inside SEQTA page)
*/
private async fetchFromUrl(url: string): Promise<any> {
private async fetchFromUrl(url: string, options?: { auth?: boolean }): Promise<any> {
const result = (await browser.runtime.sendMessage({
type: 'fetchFromUrl',
url,
auth: options?.auth === true,
})) as { data?: unknown; error?: string };
if (result?.error) throw new Error(result.error);
return result?.data;
@@ -637,6 +638,35 @@ export class ThemeManager {
}
}
public async previewAdminTheme(themeContent: {
id: string;
source: "marketplace" | "community";
updated_at?: number;
}): Promise<string> {
if (!themeContent.id) throw new Error("Missing theme id");
const previewBody = (await this.fetchFromUrl(
`${this.THEME_API_BASE}/bsplus/admin/themes/${themeContent.id}/preview?source=${themeContent.source}`,
{ auth: true },
)) as { data?: { theme_json_url?: string }; theme_json_url?: string };
const themeJsonUrl = previewBody?.data?.theme_json_url ?? previewBody?.theme_json_url;
if (!themeJsonUrl || !isAllowedFetchUrl(themeJsonUrl)) {
throw new Error("Failed to get admin theme preview URL");
}
const themeData = (await this.fetchFromUrl(themeJsonUrl, { auth: true })) as ThemeContent;
const fromCommunity = themeContent.source === "community";
await this.installTheme(
{ ...themeData, id: themeContent.id },
{
fromStore: !fromCommunity,
fromCommunity,
serverUpdatedAtSec: themeContent.updated_at,
},
);
return themeContent.id;
}
private async downloadAndInstallCommunityTheme(themeContent: {
id: string;
theme_json_url?: string;
+4
View File
@@ -36,6 +36,10 @@ export type CloudAuthState = {
user: CloudUser | null;
};
export function isCloudAdmin(user: CloudUser | null | undefined): boolean {
return (user?.admin_level ?? 0) >= 1;
}
/** Callback invoked when auth state changes */
type Listener = { (state: CloudAuthState): void };