add custom user themes!

This commit is contained in:
StroepWafel committed 2026-08-26 20:41:51 +09:30
1 parent 1ce95f64e9
commit d980c01c81
26 files changed
+2876 -40

No files matched your search

+8
View File
@@ -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<string, MessageHandler> = {
...customThemesHandlers,
reloadTabs: () => reloadSeqtaPages(),
setDevApiBase: handleSetDevApiBase,
extensionPages: (req) => {
+287
View File
@@ -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<string | null>;
parseJsonResponse: (r: Response) => Promise<any>;
}): Record<string, (request: any, sendResponse: MessageSender) => boolean> {
async function customThemesJsonFetch(
path: string,
init: RequestInit = {},
requireAuth = false,
): Promise<Record<string, unknown>> {
const headers: Record<string, string> = {
Accept: "application/json",
...(init.headers as Record<string, string> | 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<Record<string, unknown>> {
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,
};
}
@@ -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 @@
<div
class="theme-card isolate bg-gray-50 w-full transition-[transform,box-shadow,border-color] duration-300 ease-out relative group flex flex-col rounded-xl overflow-clip border hover:scale-[1.02] hover:shadow-xl dark:hover:shadow-black/60 dark:bg-zinc-800 dark:border-white/[0.1] h-auto"
>
{#if theme.featured === true}
{#if isCommunity}
<div class="absolute top-2 left-2 z-20 pointer-events-none">
<span
class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-sky-100 text-sky-900 dark:bg-sky-950 dark:text-sky-100 shadow-sm"
aria-label="Community theme"
>
Community
</span>
</div>
{/if}
{#if theme.featured === true}
<div class="absolute top-2 z-20 pointer-events-none {isCommunity ? 'left-[5.75rem]' : 'left-2'}">
<span
class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100 shadow-sm"
aria-label="Featured theme"
@@ -90,7 +103,7 @@
</div>
{/if}
{#if isInstalled}
<div class="absolute top-2 z-20 pointer-events-none {theme.featured === true ? 'left-[5.5rem]' : 'left-2'}">
<div class="absolute top-2 z-20 pointer-events-none {theme.featured === true ? (isCommunity ? 'left-[11rem]' : 'left-[5.5rem]') : isCommunity ? 'left-[5.75rem]' : 'left-2'}">
<span
class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-900 dark:bg-emerald-950 dark:text-emerald-100 shadow-sm"
aria-label="Installed"
@@ -102,6 +115,7 @@
</span>
</div>
{/if}
{#if showFavorites}
<button
type="button"
data-theme-favorite
@@ -130,6 +144,7 @@
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 0 1 6.364 0L12 7.636l1.318-1.318a4.5 4.5 0 0 1 6.364 6.364L12 20.364l-7.682-7.682a4.5 4.5 0 0 1 0-6.364Z" />
</svg>
</button>
{/if}
<div class="absolute bottom-1 left-3 right-3 z-10 mb-1 flex flex-col gap-0.5">
<span class="text-xl font-bold text-white drop-shadow-md">{theme.name}</span>
{#if theme.author}
@@ -142,12 +157,14 @@
</svg>
{displayDownloadCount.toLocaleString()}
</span>
{#if showFavorites}
<span class="flex items-center gap-1">
<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-3.5 h-3.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
{(theme.favorite_count ?? 0).toLocaleString()}
</span>
{/if}
</div>
</div>
{#if gridRotatorUrls.length === 0}
@@ -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}
@@ -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<string, string>
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"
<h2 class="text-2xl font-bold text-zinc-900 dark:text-white">
{theme.name}
</h2>
{#if isCommunity}
<span
class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-sky-100 text-sky-900 dark:bg-sky-950 dark:text-sky-100"
aria-label="Community theme"
>
Community
</span>
{/if}
{#if theme.featured === true}
<span
class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100"
@@ -248,12 +260,14 @@ By {theme.author}
</svg>
{modalDisplayDownloadCount.toLocaleString()} downloads
</span>
{#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">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
{(theme.favorite_count ?? 0).toLocaleString()} favorites
</span>
{/if}
</div>
{#if heroSlides.length > 0}
{#key theme?.id}
@@ -446,7 +460,7 @@ title="Install {f.name}"
{theme.description}
</p>
<div class="flex flex-wrap gap-2 mt-4 justify-start sm:justify-end items-center">
{#if toggleFavorite && theme}
{#if showFavorites && toggleFavorite && theme}
<button
type="button"
class="flex items-center gap-2 px-4 py-2 rounded-full transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-800 {theme.is_favorited ? 'text-red-500 bg-red-500/10 dark:bg-red-500/20' : 'bg-zinc-200 dark:bg-zinc-700 dark:text-white hover:bg-zinc-300 dark:hover:bg-zinc-600'}"
@@ -142,6 +142,18 @@
closeExtensionPopup()
}
const openCommunitySubmit = async () => {
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'
const customThemeActionCompactClass =
`${customThemeActionClass} h-full min-h-0`
const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => {
e.stopPropagation();
if (!cloudLoggedIn) {
@@ -347,23 +359,37 @@
<div id="divider" class="w-full h-[1px] my-2 bg-zinc-100 dark:bg-zinc-600 {useTwoColumnLayout ? 'col-span-2' : ''}"></div>
{#if listMode === 'custom'}
<button
onclick={() => void openThemeCreator()}
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white {useTwoColumnLayout ? 'col-span-2' : ''}"
>
<span class="text-xl font-IconFamily">&#xec60;</span>
<span class="ml-2">Create theme</span>
</button>
<div class="grid gap-2 {useTwoColumnLayout ? 'col-span-2' : ''}">
<div class="grid w-full grid-cols-2 gap-2 aspect-[10/1]">
<button
type="button"
onclick={() => void openThemeCreator()}
class={customThemeActionCompactClass}
>
<span class="text-2xl font-IconFamily" aria-hidden="true">&#xec60;</span>
<span>Create theme</span>
</button>
<a
href="https://docs.betterseqta.org/theme-creation/"
target="_blank"
rel="noopener noreferrer"
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800 {useTwoColumnLayout ? 'col-span-2' : ''}"
>
<span class="text-xl font-IconFamily">{'\uecb3'}</span>
<span class="ml-2">View theme creation docs</span>
</a>
<a
href="https://docs.betterseqta.org/theme-creation/"
target="_blank"
rel="noopener noreferrer"
class={customThemeActionCompactClass}
>
<span class="text-2xl font-IconFamily" aria-hidden="true">{'\uecb3'}</span>
<span>View docs</span>
</a>
</div>
<button
type="button"
onclick={() => void openCommunitySubmit()}
class="{customThemeActionClass} aspect-[10/1]"
>
<span class="text-2xl font-IconFamily" aria-hidden="true">&#xe9fc;</span>
<span>Submit theme</span>
</button>
</div>
{:else if listMode === 'downloaded'}
<button
onclick={() => void openStorePage()}
+806
View File
@@ -0,0 +1,806 @@
<script lang="ts">
import { onMount, tick } from "svelte";
import browser from "webextension-polyfill";
import ThemeGrid from "@/interface/components/store/ThemeGrid.svelte";
import ThemeModal from "@/interface/components/store/ThemeModal.svelte";
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
import SignInToFavoriteModal from "@/interface/components/SignInToFavoriteModal.svelte";
import type { Theme } from "@/interface/types/Theme";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import {
CustomThemeApiError,
canEditCustomTheme,
deleteCustomTheme,
fetchCommunityThemes,
fetchMyCustomThemeDetail,
fetchMyCustomThemes,
formatCustomThemeStatus,
formatThemeDate,
replaceCustomThemeFiles,
statusBadgeClass,
submitCustomTheme,
updateCustomThemeMetadata,
} from "@/seqta/utils/customThemes/client";
import {
RATE_LIMIT_DAILY_MESSAGE,
RATE_LIMIT_PENDING_MESSAGE,
} from "@/seqta/utils/customThemes/constants";
import {
buildUploadPartsFromLocalTheme,
buildUploadPartsFromZipFile,
mergeUploadPayload,
} from "@/seqta/utils/customThemes/buildThemeUploadFormData";
import type { CustomThemeOwner, CustomThemeFile } from "@/seqta/utils/customThemes/types";
import type { LoadedCustomTheme } from "@/types/CustomThemes";
import { consumeOpenCommunityThemeSubmit, OPEN_COMMUNITY_SUBMIT_EVENT } from "@/seqta/utils/openCommunityThemeSubmit";
let {
searchTerm,
} = $props<{
searchTerm: string;
setSearchTerm?: (term: string) => void;
}>();
type InnerTab = "browse" | "mine";
const themeManager = ThemeManager.getInstance();
let innerTab = $state<InnerTab>("browse");
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
let browseThemes = $state<Theme[]>([]);
let browseLoading = $state(true);
let browseError = $state<string | null>(null);
let myThemes = $state<CustomThemeOwner[]>([]);
let myLoading = $state(false);
let myError = $state<string | null>(null);
let statusFilter = $state<"" | "pending" | "approved" | "rejected">("");
let displayTheme = $state<Theme | null>(null);
let currentThemes = $state<string[]>([]);
let selectedThemeId = $state("");
let installedThemeColors = $state<Record<string, string>>({});
let showSignInOverlay = $state(false);
let showSubmitModal = $state(false);
let submitNotes = $state("");
let submitBusy = $state(false);
let submitError = $state<string | null>(null);
let submitValidationErrors = $state<string[]>([]);
let selectedZipFile = $state<File | null>(null);
let selectedLocalThemeId = $state("");
let editableThemes = $state<LoadedCustomTheme[]>([]);
let detailTheme = $state<CustomThemeOwner | null>(null);
let detailFiles = $state<CustomThemeFile[]>([]);
let detailLoading = $state(false);
let detailError = $state<string | null>(null);
let editName = $state("");
let editDescription = $state("");
let editNotes = $state("");
let detailBusy = $state(false);
let replaceZipFile = $state<File | null>(null);
let showDeleteConfirm = $state(false);
$effect(() => {
const unsub = cloudAuth.subscribe((s) => {
cloudLoggedIn = s.isLoggedIn;
});
return unsub;
});
async function refreshInstalledThemes() {
const themes = await themeManager.getAvailableThemes();
currentThemes = themes.filter((t) => t !== null).map((t) => t.id);
selectedThemeId = themeManager.getSelectedThemeId() || "";
installedThemeColors = Object.fromEntries(
themes.filter((t) => t != null).map((t) => [t.id, t.defaultColour]),
);
}
async function loadBrowseThemes() {
browseLoading = true;
browseError = null;
try {
const q = searchTerm.trim();
const res = await fetchCommunityThemes({
sort: "popular",
limit: 50,
search: q.length > 0 ? q : undefined,
});
browseThemes = res.themes as Theme[];
} catch (err) {
browseError = err instanceof Error ? err.message : "Could not load community themes";
} finally {
browseLoading = false;
}
}
async function loadMyThemes() {
if (!cloudLoggedIn) return;
myLoading = true;
myError = null;
try {
const res = await fetchMyCustomThemes({
limit: 50,
status: statusFilter || undefined,
});
myThemes = res.themes;
} catch (err) {
myError = err instanceof Error ? err.message : "Could not load your themes";
} finally {
myLoading = false;
}
}
async function loadEditableThemes() {
const all = await themeManager.getAvailableThemes();
editableThemes = all.filter((t) => t.isEditable === true) as LoadedCustomTheme[];
}
async function openDetail(theme: CustomThemeOwner) {
detailTheme = theme;
detailFiles = [];
detailError = null;
editName = theme.name;
editDescription = theme.description ?? "";
editNotes = theme.submission_notes ?? "";
replaceZipFile = null;
showDeleteConfirm = false;
detailLoading = true;
try {
const res = await fetchMyCustomThemeDetail(theme.id);
detailTheme = res.theme;
detailFiles = res.files;
editName = res.theme.name;
editDescription = res.theme.description ?? "";
editNotes = res.theme.submission_notes ?? "";
} catch (err) {
detailError = err instanceof Error ? err.message : "Could not load theme details";
} finally {
detailLoading = false;
}
}
function closeDetail() {
detailTheme = null;
detailFiles = [];
detailError = null;
showDeleteConfirm = false;
}
async function installCommunityTheme(themeId: string, meta: Theme) {
const row = browseThemes.find((x) => x.id === themeId) ?? meta;
await themeManager.downloadCommunityTheme({
id: themeId,
theme_json_url: row.theme_json_url,
updated_at: row.updated_at,
});
await themeManager.setTheme(themeId);
themeUpdates.triggerUpdate();
await refreshInstalledThemes();
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
}
async function removeInstalledTheme(themeId: string) {
await themeManager.deleteTheme(themeId);
themeUpdates.triggerUpdate();
await refreshInstalledThemes();
}
async function applyInstalledTheme(themeId: string) {
await themeManager.setTheme(themeId);
selectedThemeId = themeId;
themeUpdates.triggerUpdate();
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
}
function handleApiError(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";
}
async function runSubmit() {
submitBusy = true;
submitError = null;
submitValidationErrors = [];
try {
let payload;
if (selectedZipFile) {
payload = mergeUploadPayload(await buildUploadPartsFromZipFile(selectedZipFile), submitNotes);
} else if (selectedLocalThemeId) {
const local = (await themeManager.getTheme(selectedLocalThemeId)) as LoadedCustomTheme | null;
if (!local || !local.isEditable) throw new Error("Select a custom theme to submit");
payload = mergeUploadPayload(await buildUploadPartsFromLocalTheme(local), submitNotes);
} else {
throw new Error("Choose a ZIP file or a custom theme");
}
const res = await submitCustomTheme(payload);
showSubmitModal = false;
submitNotes = "";
selectedZipFile = null;
selectedLocalThemeId = "";
innerTab = "mine";
await loadMyThemes();
await openDetail(res.theme);
} catch (err) {
if (err instanceof CustomThemeApiError && err.validationErrors.length > 0) {
submitValidationErrors = err.validationErrors;
}
submitError = handleApiError(err);
} finally {
submitBusy = false;
}
}
async function saveMetadata() {
if (!detailTheme) return;
detailBusy = true;
detailError = null;
try {
const updated = await updateCustomThemeMetadata(detailTheme.id, {
name: editName.trim() || undefined,
description: editDescription.trim() || undefined,
submission_notes: editNotes.trim() || undefined,
});
detailTheme = updated;
await loadMyThemes();
} catch (err) {
detailError = handleApiError(err);
} finally {
detailBusy = false;
}
}
async function runReplaceFiles() {
if (!detailTheme || !replaceZipFile) return;
detailBusy = true;
detailError = null;
try {
const payload = mergeUploadPayload(await buildUploadPartsFromZipFile(replaceZipFile));
const res = await replaceCustomThemeFiles(detailTheme.id, payload);
detailTheme = res.theme;
replaceZipFile = null;
await loadMyThemes();
} catch (err) {
detailError = handleApiError(err);
} finally {
detailBusy = false;
}
}
async function runDelete() {
if (!detailTheme) return;
detailBusy = true;
detailError = null;
try {
await deleteCustomTheme(detailTheme.id);
closeDetail();
await loadMyThemes();
} catch (err) {
detailError = handleApiError(err);
} finally {
detailBusy = false;
showDeleteConfirm = false;
}
}
$effect(() => {
if (innerTab === "browse") {
void loadBrowseThemes();
}
});
$effect(() => {
searchTerm;
if (innerTab === "browse") void loadBrowseThemes();
});
$effect(() => {
if (innerTab === "mine" && cloudLoggedIn) void loadMyThemes();
});
$effect(() => {
statusFilter;
if (innerTab === "mine" && cloudLoggedIn) void loadMyThemes();
});
function navigateToSubmitTheme() {
innerTab = "mine";
void tick().then(() => openSubmitModal());
}
onMount(() => {
themeUpdates.addListener(refreshInstalledThemes);
void refreshInstalledThemes();
if (consumeOpenCommunityThemeSubmit()) {
navigateToSubmitTheme();
}
const onOpenCommunitySubmit = () => navigateToSubmitTheme();
window.addEventListener(OPEN_COMMUNITY_SUBMIT_EVENT, onOpenCommunitySubmit);
return () => {
themeUpdates.removeListener(refreshInstalledThemes);
window.removeEventListener(OPEN_COMMUNITY_SUBMIT_EVENT, onOpenCommunitySubmit);
};
});
function openSubmitModal() {
if (!cloudLoggedIn) {
showSignInOverlay = true;
return;
}
void loadEditableThemes();
showSubmitModal = true;
submitError = null;
submitValidationErrors = [];
}
let filteredBrowse = $derived(
browseThemes.filter((theme) => {
const q = searchTerm.toLowerCase();
if (!q) return true;
return (
(theme.name ?? "").toLowerCase().includes(q) ||
(theme.description ?? "").toLowerCase().includes(q)
);
}),
);
</script>
<div class="relative flex h-full min-h-0 flex-col overflow-hidden text-zinc-900 dark:text-white">
<div class="shrink-0 border-b border-zinc-200/60 px-6 py-4 dark:border-zinc-700/50">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="inline-flex rounded-xl bg-zinc-200/80 p-1 dark:bg-zinc-800/80">
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {innerTab === 'browse'
? '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={() => (innerTab = "browse")}
>
Browse
</button>
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {innerTab === 'mine'
? '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={() => (innerTab = "mine")}
>
My themes
</button>
</div>
{#if innerTab === "mine"}
<button
type="button"
class="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white transition hover:bg-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white"
onclick={openSubmitModal}
>
Submit theme
</button>
{/if}
</div>
<p class="mt-2 text-sm text-zinc-500 dark:text-zinc-400">
Community themes are user-submitted and moderated separately from the official theme store.
</p>
</div>
<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 innerTab === "browse"}
{#if browseLoading}
<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 browseError}
<div class="flex flex-col items-center justify-center py-24 text-center">
<h2 class="text-2xl font-bold">Couldn&apos;t load community themes</h2>
<p class="mt-3 text-zinc-600 dark:text-zinc-300">{browseError}</p>
<button
type="button"
class="mt-6 rounded-lg bg-zinc-900 px-4 py-2 font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
onclick={() => void loadBrowseThemes()}
>
Try again
</button>
</div>
{:else}
<ThemeGrid
themes={filteredBrowse}
{searchTerm}
setDisplayTheme={(theme) => (displayTheme = theme)}
toggleFavorite={() => {}}
isLoggedIn={false}
installedThemeIds={currentThemes}
variant="community"
/>
{#if displayTheme}
<ThemeModal
currentThemes={currentThemes}
allThemes={filteredBrowse}
theme={displayTheme}
{displayTheme}
setDisplayTheme={(t) => (displayTheme = t)}
{selectedThemeId}
{installedThemeColors}
variant="community"
onInstall={async (themeId) => {
if (displayTheme) await installCommunityTheme(themeId, displayTheme);
}}
onRemove={removeInstalledTheme}
onApply={applyInstalledTheme}
/>
{/if}
{/if}
{:else if !cloudLoggedIn}
<div class="mx-auto flex max-w-md flex-col items-center py-20 text-center">
<h2 class="text-2xl font-bold">Sign in to manage your themes</h2>
<p class="mt-3 text-zinc-600 dark:text-zinc-300">
Submit themes for review and track pending, approved, or rejected submissions.
</p>
<button
type="button"
class="mt-6 rounded-lg bg-zinc-900 px-5 py-2.5 font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
onclick={() => (showSignInOverlay = true)}
>
Sign in with BetterSEQTA Cloud
</button>
</div>
{:else}
<div class="mb-4 flex flex-wrap gap-2">
{#each ["", "pending", "approved", "rejected"] as status (status)}
<button
type="button"
class="rounded-full px-3 py-1 text-sm font-medium transition {statusFilter === status
? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
: 'bg-zinc-200 text-zinc-700 hover:bg-zinc-300 dark:bg-zinc-800 dark:text-zinc-300'}"
onclick={() => (statusFilter = status as typeof statusFilter)}
>
{status === "" ? "All" : formatCustomThemeStatus(status)}
</button>
{/each}
</div>
{#if myLoading}
<div class="grid grid-cols-1 gap-3">
{#each Array(4) as _, i (i)}
<SkeletonLoader width="100%" height="72px" />
{/each}
</div>
{:else if myError}
<p class="text-red-600 dark:text-red-400">{myError}</p>
{:else if myThemes.length === 0}
<div class="py-16 text-center">
<p class="text-lg text-zinc-600 dark:text-zinc-300">No submissions yet.</p>
<button
type="button"
class="mt-4 rounded-lg bg-zinc-900 px-4 py-2 font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
onclick={openSubmitModal}
>
Submit your first theme
</button>
</div>
{:else}
<ul class="space-y-3">
{#each myThemes as theme (theme.id)}
<li>
<button
type="button"
class="flex w-full items-center gap-4 rounded-xl border border-zinc-200 bg-white p-4 text-left transition hover:border-zinc-300 hover:shadow-sm dark:border-zinc-700 dark:bg-zinc-800 dark:hover:border-zinc-600"
onclick={() => void openDetail(theme)}
>
{#if theme.coverImage}
<img
src={theme.coverImage}
alt=""
class="h-14 w-20 shrink-0 rounded-lg object-cover"
/>
{:else}
<div class="h-14 w-20 shrink-0 rounded-lg bg-zinc-200 dark:bg-zinc-700"></div>
{/if}
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<span class="font-semibold text-zinc-900 dark:text-white">{theme.name}</span>
<span class="rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(theme.status)}">
{formatCustomThemeStatus(theme.status)}
</span>
</div>
<p class="mt-1 truncate text-sm text-zinc-500 dark:text-zinc-400">
Submitted {formatThemeDate(theme.created_at)}
</p>
</div>
</button>
</li>
{/each}
</ul>
{/if}
{/if}
</main>
{#if showSignInOverlay}
<SignInToFavoriteModal onClose={() => (showSignInOverlay = false)} />
{/if}
{#if showSubmitModal}
<div
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
role="presentation"
onclick={(e) => {
if (e.target === e.currentTarget && !submitBusy) showSubmitModal = false;
}}
>
<div
class="max-h-[90dvh] w-full max-w-lg overflow-y-auto rounded-2xl border border-zinc-200 bg-white p-6 shadow-2xl dark:border-zinc-700 dark:bg-zinc-800"
role="dialog"
aria-modal="true"
aria-labelledby="submit-theme-title"
>
<h2 id="submit-theme-title" class="text-xl font-bold">Submit a theme</h2>
<p class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
Upload a ZIP with theme.json or submit one of your custom themes.
</p>
<div class="mt-4 space-y-4">
<label class="block">
<span class="text-sm font-medium">Theme ZIP</span>
<input
type="file"
accept=".zip,application/zip"
class="mt-1 block w-full text-sm"
onchange={(e) => {
const file = (e.currentTarget as HTMLInputElement).files?.[0] ?? null;
selectedZipFile = file;
if (file) selectedLocalThemeId = "";
}}
/>
</label>
<div class="text-center text-xs text-zinc-400">or</div>
<label class="block">
<span class="text-sm font-medium">From custom themes</span>
<select
class="mt-1 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-900"
bind:value={selectedLocalThemeId}
onchange={() => {
if (selectedLocalThemeId) selectedZipFile = null;
}}
>
<option value="">Select a theme…</option>
{#each editableThemes as t (t.id)}
<option value={t.id}>{t.name}</option>
{/each}
</select>
</label>
<label class="block">
<span class="text-sm font-medium">Notes for reviewers (optional)</span>
<textarea
class="mt-1 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-900"
rows="3"
bind:value={submitNotes}
placeholder="Anything reviewers should know…"
></textarea>
</label>
{#if submitValidationErrors.length > 0}
<ul class="rounded-lg bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950 dark:text-red-200">
{#each submitValidationErrors as msg (msg)}
<li>{msg}</li>
{/each}
</ul>
{/if}
{#if submitError}
<p class="text-sm text-red-600 dark:text-red-400 whitespace-pre-line">{submitError}</p>
{/if}
</div>
<div class="mt-6 flex justify-end gap-2">
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium text-zinc-700 hover:bg-zinc-100 dark:text-zinc-300 dark:hover:bg-zinc-700"
disabled={submitBusy}
onclick={() => (showSubmitModal = false)}
>
Cancel
</button>
<button
type="button"
class="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
disabled={submitBusy}
onclick={() => void runSubmit()}
>
{submitBusy ? "Uploading…" : "Submit for review"}
</button>
</div>
</div>
</div>
{/if}
{#if detailTheme}
<div
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
role="presentation"
onclick={(e) => {
if (e.target === e.currentTarget && !detailBusy) closeDetail();
}}
>
<div
class="max-h-[90dvh] w-full max-w-2xl overflow-y-auto rounded-2xl border border-zinc-200 bg-white p-6 shadow-2xl dark:border-zinc-700 dark:bg-zinc-800"
role="dialog"
aria-modal="true"
>
<div class="flex items-start justify-between gap-4">
<div>
<h2 class="text-2xl font-bold">{detailTheme.name}</h2>
<span class="mt-1 inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(detailTheme.status)}">
{formatCustomThemeStatus(detailTheme.status)}
</span>
</div>
<button
type="button"
class="rounded-lg p-2 hover:bg-zinc-100 dark:hover:bg-zinc-700"
aria-label="Close"
onclick={closeDetail}
>
✕
</button>
</div>
{#if detailTheme.status === "rejected" && detailTheme.rejection_reason}
<div class="mt-4 rounded-lg border border-red-200 bg-red-50 p-4 text-sm text-red-900 dark:border-red-900 dark:bg-red-950 dark:text-red-100">
<p class="font-semibold">Rejection reason</p>
<p class="mt-1 whitespace-pre-wrap">{detailTheme.rejection_reason}</p>
</div>
{/if}
{#if detailLoading}
<div class="py-8"><SkeletonLoader width="100%" height="120px" /></div>
{:else}
<dl class="mt-4 grid grid-cols-2 gap-3 text-sm">
<div>
<dt class="text-zinc-500">Submitted</dt>
<dd>{formatThemeDate(detailTheme.created_at)}</dd>
</div>
<div>
<dt class="text-zinc-500">Last updated</dt>
<dd>{formatThemeDate(detailTheme.updated_at)}</dd>
</div>
{#if detailTheme.reviewed_at}
<div>
<dt class="text-zinc-500">Reviewed</dt>
<dd>{formatThemeDate(detailTheme.reviewed_at)}</dd>
</div>
{/if}
{#if detailTheme.slug}
<div>
<dt class="text-zinc-500">Slug</dt>
<dd class="truncate">{detailTheme.slug}</dd>
</div>
{/if}
</dl>
{#if detailFiles.length > 0}
<div class="mt-4">
<h3 class="text-sm font-semibold">Files</h3>
<ul class="mt-2 space-y-1 text-sm text-zinc-600 dark:text-zinc-400">
{#each detailFiles as file (file.id)}
<li>{file.file_path} ({file.file_size.toLocaleString()} bytes)</li>
{/each}
</ul>
</div>
{/if}
{#if canEditCustomTheme(detailTheme)}
<div class="mt-6 space-y-3 border-t border-zinc-200 pt-4 dark:border-zinc-700">
<h3 class="font-semibold">Edit metadata</h3>
<input
class="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-900"
bind:value={editName}
placeholder="Name"
/>
<textarea
class="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-900"
rows="2"
bind:value={editDescription}
placeholder="Description"
></textarea>
<textarea
class="w-full rounded-lg border border-zinc-300 px-3 py-2 text-sm dark:border-zinc-600 dark:bg-zinc-900"
rows="2"
bind:value={editNotes}
placeholder="Submission notes"
></textarea>
<button
type="button"
class="rounded-lg bg-zinc-200 px-4 py-2 text-sm font-medium dark:bg-zinc-700"
disabled={detailBusy}
onclick={() => void saveMetadata()}
>
Save metadata
</button>
<h3 class="pt-2 font-semibold">Replace files</h3>
<p class="text-sm text-zinc-500">Uploading new files resets review to pending.</p>
<input
type="file"
accept=".zip,application/zip"
class="block w-full text-sm"
onchange={(e) => {
replaceZipFile = (e.currentTarget as HTMLInputElement).files?.[0] ?? null;
}}
/>
<button
type="button"
class="rounded-lg bg-zinc-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900"
disabled={detailBusy || !replaceZipFile}
onclick={() => void runReplaceFiles()}
>
Upload revised files
</button>
</div>
{:else if detailTheme.status === "approved"}
<p class="mt-4 text-sm text-zinc-500">
Approved themes cannot be edited. Delete and re-submit if you need to publish an update.
</p>
{/if}
{#if detailError}
<p class="mt-4 text-sm text-red-600 dark:text-red-400 whitespace-pre-line">{detailError}</p>
{/if}
<div class="mt-6 flex flex-wrap justify-between gap-2 border-t border-zinc-200 pt-4 dark:border-zinc-700">
{#if showDeleteConfirm}
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm text-red-600 dark:text-red-400">Delete permanently?</span>
<button
type="button"
class="rounded-lg bg-red-600 px-3 py-1.5 text-sm font-medium text-white"
disabled={detailBusy}
onclick={() => void runDelete()}
>
Confirm delete
</button>
<button
type="button"
class="rounded-lg px-3 py-1.5 text-sm"
onclick={() => (showDeleteConfirm = false)}
>
Cancel
</button>
</div>
{:else}
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 dark:hover:bg-red-950"
onclick={() => (showDeleteConfirm = true)}
>
Delete theme
</button>
{/if}
<button
type="button"
class="rounded-lg bg-zinc-200 px-4 py-2 text-sm font-medium dark:bg-zinc-700"
onclick={closeDetail}
>
Close
</button>
</div>
{/if}
</div>
</div>
{/if}
</div>
+34 -19
View File
@@ -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}
<div class="min-w-0 min-h-0 flex-1">
<Store
activeTab={activePage as StoreTab}
searchTerm={storeSearchTerm}
{selectedBackgroundCategory}
setActiveTab={(tab) => {
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"}
<CommunityThemes searchTerm={storeSearchTerm} setSearchTerm={(term) => (storeSearchTerm = term)} />
{:else}
<Store
activeTab={activePage as StoreTab}
searchTerm={storeSearchTerm}
{selectedBackgroundCategory}
setActiveTab={(tab) => {
activePage = tab;
if (tab === "themes") activeThemeView = "theme-store";
else activeBackgroundView = "background-store";
}}
setSearchTerm={(term) => (storeSearchTerm = term)}
setBackgroundCategories={(categories) => (backgroundCategories = categories)}
/>
{/if}
</div>
{:else}
<div class="flex flex-col flex-1 min-w-0 min-h-0">
@@ -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<void> {
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<void> {
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
@@ -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();
});
});
@@ -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<CustomThemeUploadPayload> {
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<CustomThemeUploadPayload> {
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<string> {
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;
}
@@ -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"]);
});
});
+193
View File
@@ -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<T>(message: object): Promise<T> {
return Promise.race([
browser.runtime.sendMessage(message) as Promise<T>,
new Promise<T>((_, reject) => {
setTimeout(
() =>
reject(
new Error(
"Community themes request timed out — reload the SEQTA page after updating the extension.",
),
),
FETCH_TIMEOUT_MS,
);
}),
]);
}
function throwFromEnvelope<T>(
envelope: CustomThemeApiEnvelope<T> & { 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<string, string> = {
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<CustomThemeListResponse> {
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<string, unknown>))
.filter((t) => t.id.length > 0),
pagination: res.data.pagination,
};
}
export async function fetchMyCustomThemes(options?: {
page?: number;
limit?: number;
status?: CustomThemeStatus;
}): Promise<CustomThemeListResponse> {
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<string, unknown>))
.filter((t) => t.id.length > 0),
pagination: res.data.pagination,
};
}
export async function fetchMyCustomThemeDetail(id: string): Promise<CustomThemeDetailResponse> {
const res = await sendMessageWithTimeout<CustomThemeApiEnvelope<CustomThemeDetailResponse>>({
type: "fetchMyCustomThemeDetail",
themeId: id,
});
if (!res.success || !res.data?.theme) throwFromEnvelope(res);
return {
theme: normalizeCustomTheme(res.data.theme as unknown as Record<string, unknown>),
files: Array.isArray(res.data.files) ? res.data.files : [],
};
}
export async function submitCustomTheme(
payload: CustomThemeUploadPayload,
): Promise<CustomThemeSubmitResponse> {
const res = await sendMessageWithTimeout<CustomThemeApiEnvelope<CustomThemeSubmitResponse>>({
type: "submitCustomTheme",
payload,
});
if (!res.success || !res.data?.theme) throwFromEnvelope(res);
return {
theme: normalizeCustomTheme(res.data.theme as unknown as Record<string, unknown>),
validation: res.data.validation,
};
}
export async function replaceCustomThemeFiles(
id: string,
payload: CustomThemeUploadPayload,
): Promise<CustomThemeSubmitResponse> {
const res = await sendMessageWithTimeout<CustomThemeApiEnvelope<CustomThemeSubmitResponse>>({
type: "replaceCustomThemeFiles",
themeId: id,
payload,
});
if (!res.success || !res.data?.theme) throwFromEnvelope(res);
return {
theme: normalizeCustomTheme(res.data.theme as unknown as Record<string, unknown>),
validation: res.data.validation,
};
}
export async function updateCustomThemeMetadata(
id: string,
body: { name?: string; description?: string; submission_notes?: string },
): Promise<CustomThemeOwner> {
const res = await sendMessageWithTimeout<CustomThemeApiEnvelope<{ theme?: unknown }>>({
type: "updateCustomThemeMetadata",
themeId: id,
body,
});
if (!res.success || !res.data?.theme) throwFromEnvelope(res);
return normalizeCustomTheme(res.data.theme as Record<string, unknown>);
}
export async function deleteCustomTheme(id: string): Promise<void> {
const res = await sendMessageWithTimeout<CustomThemeApiEnvelope<{ id?: string }>>({
type: "deleteCustomTheme",
themeId: id,
});
if (!res.success) throwFromEnvelope(res);
}
export function canEditCustomTheme(theme: CustomThemeOwner): boolean {
return theme.status === "pending" || theme.status === "rejected";
}
+12
View File
@@ -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.";
@@ -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("—");
});
});
@@ -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();
}
@@ -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");
});
});
@@ -0,0 +1,80 @@
import type { CustomThemeOwner } from "./types";
function pickString(row: Record<string, unknown>, ...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<string, unknown>, ...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<string, unknown>, ...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<string, unknown>): 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,
};
}
@@ -0,0 +1,21 @@
import type { CustomThemeApiEnvelope, CustomThemeApiError } from "./types";
export function parseApiError(error: CustomThemeApiEnvelope<unknown>["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");
}
+68
View File
@@ -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<T> = {
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[] };
};
@@ -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);
});
});
@@ -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<void> {
requestOpenCommunityThemeSubmit();
const [{ requestSettingsDestination }, { openSettingsPopup }] =
await Promise.all([
import("@/seqta/utils/settingsNavigation"),
import("@/seqta/utils/setupSettingsButton"),
]);
requestSettingsDestination({ page: "themes", view: "community" });
await openSettingsPopup();
}
+1 -1
View File
@@ -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";
+2
View File
@@ -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. */
@@ -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 <token>` |
| 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)
@@ -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 <access_token>` 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`.