Merge pull request #476 from StroepWafel/better-looking-theme-tab

User-generated themes support
This commit is contained in:
Aden Lindsay authored and GitHub committed 2026-09-29 11:03:43 +09:30
commit aaf03129a5
64 files changed
+4155 -435

No files matched your search

+15
View File
@@ -19,6 +19,8 @@ import {
registerGoogleCalendarMessageHandlers,
registerOutlookCalendarMessageHandlers,
} from "./background/calendarBackground";
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
/**
* Session-only dev-mode override of the content API base.
@@ -32,6 +34,8 @@ import {
const DEFAULT_API_BASE = "https://betterseqta.org";
let DEV_API_BASE: string | null = null;
function apiBase(): string {
// Extension dev builds always hit production (see DevApiBase.ts).
if (import.meta.env.DEV) return DEFAULT_API_BASE;
return DEV_API_BASE ?? DEFAULT_API_BASE;
}
@@ -469,6 +473,10 @@ function handleSetDevApiBase(
sender?: browser.Runtime.MessageSender,
): boolean {
if (!isTrustedSender(sender)) return false;
if (import.meta.env.DEV) {
DEV_API_BASE = null;
return false;
}
const url = typeof request?.url === "string" ? request.url.trim() : null;
if (url && /^https?:\/\//.test(url)) {
DEV_API_BASE = url.replace(/\/$/, "");
@@ -478,7 +486,14 @@ function handleSetDevApiBase(
return false;
}
const customThemesHandlers = createCustomThemesHandlers({
apiBase,
getAccessTokenFromStorage,
});
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
...customThemesHandlers,
searchThemeStockPhotos: handleSearchThemeStockPhotos,
reloadTabs: () => reloadSeqtaPages(),
setDevApiBase: handleSetDevApiBase,
extensionPages: (req) => {
+298
View File
@@ -0,0 +1,298 @@
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
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>;
}): Record<string, (request: any, sendResponse: MessageSender) => boolean> {
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
const text = await r.text();
let body: unknown = {};
try {
body = text ? JSON.parse(text) : {};
} catch {
body = null;
}
const normalized = normalizeCustomThemeApiResponse(body, r.status, text);
if (!r.ok || normalized.success === false) {
console.error("[BetterSEQTA+ CustomThemes]", r.status, r.url, normalized);
}
return normalized;
}
async function customThemesJsonFetch(
path: string,
init: RequestInit = {},
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 url = `${deps.apiBase()}${path}`;
const r = await fetch(url, {
...init,
headers,
cache: "no-store",
});
return await readCustomThemesResponse(r);
}
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 url = `${deps.apiBase()}${path}`;
const r = await fetch(url, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: form,
cache: "no-store",
});
return await readCustomThemesResponse(r);
}
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: { message: err instanceof Error ? err.message : "Upload failed" },
httpStatus: 0,
});
}
})();
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,
};
}
+57
View File
@@ -0,0 +1,57 @@
type MessageSender = { (response?: unknown): void };
type StockPhotoResult = { title: string; thumbUrl: string; imageUrl: string };
export function handleSearchThemeStockPhotos(
request: { query?: string; limit?: number },
sendResponse: MessageSender,
): boolean {
const query = request.query?.trim();
if (!query) {
sendResponse({ success: false, error: "Missing query" });
return false;
}
const limit = Math.min(Math.max(request.limit ?? 8, 1), 12);
void (async () => {
try {
const params = new URLSearchParams({
action: "query",
origin: "*",
format: "json",
generator: "search",
gsrsearch: query,
gsrnamespace: "6",
gsrlimit: String(limit),
prop: "imageinfo",
iiprop: "url",
iiurlwidth: "1400",
});
const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`);
const json = (await res.json()) as {
query?: { pages?: Record<string, { title?: string; imageinfo?: { thumburl?: string; url?: string }[] }> };
};
const pages = json.query?.pages ?? {};
const results: StockPhotoResult[] = Object.values(pages)
.map((page) => {
const info = page.imageinfo?.[0];
if (!info?.url) return null;
return {
title: page.title?.replace(/^File:/, "") ?? "Photo",
thumbUrl: info.thumburl ?? info.url,
imageUrl: info.url,
};
})
.filter((row): row is StockPhotoResult => row != null);
sendResponse({ success: true, results });
} catch (err) {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Search failed",
});
}
})();
return true;
}
+4 -3
View File
@@ -150,9 +150,10 @@ html:not(.dark) .legacy-root {
#themeCreator {
position: fixed;
top: 0;
right: 0;
height: 100%;
z-index: 100;
z-index: 10050;
}
.resizeBar {
@@ -180,15 +181,15 @@ html:not(.dark) .legacy-root {
}
.themeCloseButton {
position: absolute !important;
position: fixed !important;
color: var(--text-primary) !important;
font-size: x-large !important;
top: 5px;
right: 5px;
z-index: 10060 !important;
border-radius: 80px !important;
padding: 8px;
cursor: pointer;
z-index: 10000;
}
.modaliser-container {
@@ -1,5 +1,8 @@
<script lang="ts">
let { width, height} = $props<{width?: string, height?: string}>()
let { width, height } = $props<{ width?: string; height?: string }>();
</script>
<div style="width: {width ? width : '100%'}; height: {height ? height : '100%'}; background: #e0e0e0;" class="animate-pulse"></div>
<div
style="width: {width ? width : '100%'}; height: {height ? height : '100%'};"
class="animate-pulse rounded-xl border border-zinc-200 bg-zinc-200 dark:border-zinc-700/80 dark:bg-zinc-800"
></div>
+1
View File
@@ -17,6 +17,7 @@
step={step}
bind:value={state}
style={`background: linear-gradient(to right, #30d259ad 0%, #30D259 ${percentage}%, #dddddd ${percentage}%)`}
oninput={(e) => onChange(Number(e.currentTarget.value))}
onchange={(e) => onChange(Number(e.currentTarget.value))}
class="w-full h-1 rounded-full appearance-none cursor-pointer slider"
/>
@@ -0,0 +1,66 @@
<script lang="ts">
import ThemeGrid from "@/interface/components/store/ThemeGrid.svelte";
import ThemeModal from "@/interface/components/store/ThemeModal.svelte";
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
import type { CommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
let { state, searchTerm }: { state: CommunityThemesState; searchTerm: string } = $props();
const themes = $derived(
state.browseThemes.filter((theme) => {
const q = searchTerm.toLowerCase();
if (!q) return true;
return (
(theme.name ?? "").toLowerCase().includes(q) ||
(theme.description ?? "").toLowerCase().includes(q)
);
}),
);
</script>
{#if state.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 state.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">{state.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 state.loadBrowseThemes()}
>
Try again
</button>
</div>
{:else}
<ThemeGrid
{themes}
{searchTerm}
setDisplayTheme={(theme) => (state.displayTheme = theme)}
toggleFavorite={() => {}}
isLoggedIn={false}
installedThemeIds={state.currentThemes}
variant="community"
/>
{#if state.displayTheme}
<ThemeModal
currentThemes={state.currentThemes}
allThemes={themes}
theme={state.displayTheme}
displayTheme={state.displayTheme}
setDisplayTheme={(t) => (state.displayTheme = t)}
selectedThemeId={state.selectedThemeId}
installedThemeColors={state.installedThemeColors}
variant="community"
onInstall={async (themeId) => {
if (state.displayTheme) await state.installCommunityTheme(themeId, state.displayTheme);
}}
onRemove={(id) => void state.removeInstalledTheme(id)}
onApply={(id) => void state.applyInstalledTheme(id)}
/>
{/if}
{/if}
@@ -0,0 +1,38 @@
<script lang="ts">
import type { Snippet } from "svelte";
let {
open = false,
busy = false,
maxWidthClass = "max-w-lg",
labelledBy,
onClose,
children,
}: {
open?: boolean;
busy?: boolean;
maxWidthClass?: string;
labelledBy?: string;
onClose: () => void;
children: Snippet;
} = $props();
</script>
{#if open}
<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 && !busy) onClose();
}}
>
<div
class="max-h-[90dvh] w-full overflow-y-auto rounded-2xl border border-zinc-200 bg-white p-6 shadow-2xl dark:border-zinc-700 dark:bg-zinc-800 {maxWidthClass}"
role="dialog"
aria-modal="true"
aria-labelledby={labelledBy}
>
{@render children()}
</div>
</div>
{/if}
@@ -0,0 +1,226 @@
<script lang="ts">
import { onDestroy, onMount } from "svelte";
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
import SignInToFavoriteModal from "@/interface/components/SignInToFavoriteModal.svelte";
import type { CommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
import {
formatCustomThemeStatus,
formatThemeDate,
statusBadgeClass,
} from "@/seqta/utils/customThemes/client";
import ThemePlaceholderCover from "@/interface/components/themes/ThemePlaceholderCover.svelte";
import ThemeBlobImage from "@/interface/components/themes/ThemeBlobImage.svelte";
import type { CustomTheme } from "@/types/CustomThemes";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { filterThemesByMode } from "@/interface/utils/themeListFilters";
import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors";
let { state }: { state: CommunityThemesState } = $props();
const statusFilters = ["", "pending", "approved", "rejected"] as const;
const themeManager = ThemeManager.getInstance();
let localThemes = $state<CustomTheme[]>([]);
let localThemesLoading = $state(true);
let submittingLocalId = $state<string | null>(null);
let localSubmitError = $state<string | null>(null);
async function refreshLocalThemes() {
localThemesLoading = true;
try {
const all = await themeManager.getAvailableThemes();
localThemes = filterThemesByMode(all, "custom");
} finally {
localThemesLoading = false;
}
}
async function submitLocalTheme(theme: CustomTheme) {
localSubmitError = null;
if (!state.cloudLoggedIn) {
state.showSignInOverlay = true;
return;
}
submittingLocalId = theme.id;
try {
const { submitThemeById } = await import("@/seqta/utils/customThemes/submitLocalTheme");
await submitThemeById(theme.id, theme.description?.trim() || undefined);
await state.loadMyThemes();
} catch (err) {
localSubmitError = formatCustomThemeApiError(err);
} finally {
submittingLocalId = null;
}
}
function openInBuilder(themeId: string) {
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
launchPageThemeBuilder(themeId),
);
}
onMount(() => {
void refreshLocalThemes();
themeUpdates.addListener(refreshLocalThemes);
});
onDestroy(() => {
themeUpdates.removeListener(refreshLocalThemes);
});
</script>
{#if !state.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={() => (state.showSignInOverlay = true)}
>
Sign in with BetterSEQTA Cloud
</button>
</div>
{:else}
<section class="mb-8">
<h2 class="text-lg font-semibold text-zinc-900 dark:text-white">Themes on this device</h2>
<p class="mt-1 text-sm text-zinc-500 dark:text-zinc-400">
Submit a custom theme you created or imported without opening the theme builder.
</p>
{#if localSubmitError}
<p class="mt-2 whitespace-pre-line text-sm text-red-600 dark:text-red-400">{localSubmitError}</p>
{/if}
{#if localThemesLoading}
<div class="mt-3 grid grid-cols-1 gap-3">
{#each Array(2) as _, i (i)}
<SkeletonLoader width="100%" height="72px" />
{/each}
</div>
{:else if localThemes.length === 0}
<p class="mt-3 text-sm text-zinc-500 dark:text-zinc-400">
No local custom themes yet. Use Create &amp; submit above or build one in Custom themes settings.
</p>
{:else}
<ul class="mt-3 space-y-3">
{#each localThemes as theme (theme.id)}
<li
class="flex flex-wrap items-center gap-4 rounded-xl border border-zinc-200 bg-white p-4 dark:border-zinc-700 dark:bg-zinc-800"
>
{#if theme.coverImage}
<ThemeBlobImage
source={theme.coverImage}
alt=""
class="h-14 w-20 shrink-0 rounded-lg object-cover"
/>
{:else}
<ThemePlaceholderCover
accentHint={theme.defaultColour}
class="h-14 w-20 shrink-0 rounded-lg object-cover"
/>
{/if}
<div class="min-w-0 flex-1">
<span class="font-semibold text-zinc-900 dark:text-white">{theme.name || "Untitled theme"}</span>
{#if theme.description}
<p class="mt-1 truncate text-sm text-zinc-500 dark:text-zinc-400">{theme.description}</p>
{/if}
</div>
<div class="flex shrink-0 flex-wrap gap-2">
<button
type="button"
class="rounded-lg bg-zinc-200 px-3 py-2 text-sm font-medium text-zinc-900 transition hover:bg-zinc-300 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
onclick={() => openInBuilder(theme.id)}
>
Edit
</button>
<button
type="button"
class="rounded-lg bg-zinc-900 px-3 py-2 text-sm font-medium text-white transition hover:bg-zinc-700 disabled:opacity-50 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white"
disabled={submittingLocalId === theme.id}
onclick={() => void submitLocalTheme(theme)}
>
{submittingLocalId === theme.id ? "Submitting…" : "Submit"}
</button>
</div>
</li>
{/each}
</ul>
{/if}
</section>
<h2 class="text-lg font-semibold text-zinc-900 dark:text-white">Community submissions</h2>
<div class="mb-4 mt-3 flex flex-wrap gap-2">
{#each statusFilters as status (status)}
<button
type="button"
class="rounded-full px-3 py-1 text-sm font-medium transition {state.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={() => (state.statusFilter = status)}
>
{status === "" ? "All" : formatCustomThemeStatus(status)}
</button>
{/each}
</div>
{#if state.myLoading}
<div class="grid grid-cols-1 gap-3">
{#each Array(4) as _, i (i)}
<SkeletonLoader width="100%" height="72px" />
{/each}
</div>
{:else if state.myError}
<p class="text-red-600 dark:text-red-400">{state.myError}</p>
{:else if state.myThemes.length === 0}
<div class="py-10 text-center">
<p class="text-lg text-zinc-600 dark:text-zinc-300">No community 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={() =>
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
launchPageThemeBuilder(),
)}
>
Create &amp; submit a theme
</button>
</div>
{:else}
<ul class="space-y-3">
{#each state.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 state.openDetail(theme)}
>
{#if theme.coverImage}
<img src={theme.coverImage} alt="" class="h-14 w-20 shrink-0 rounded-lg object-cover" />
{:else}
<ThemePlaceholderCover class="h-14 w-20 shrink-0 rounded-lg object-cover" />
{/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}
{#if state.showSignInOverlay}
<SignInToFavoriteModal onClose={() => (state.showSignInOverlay = false)} />
{/if}
@@ -0,0 +1,190 @@
<script lang="ts">
import SkeletonLoader from "@/interface/components/SkeletonLoader.svelte";
import ModalFrame from "./ModalFrame.svelte";
import type { CommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
import {
canEditCustomTheme,
formatCustomThemeStatus,
formatThemeDate,
statusBadgeClass,
} from "@/seqta/utils/customThemes/client";
let { state }: { state: CommunityThemesState } = $props();
const theme = $derived(state.detailTheme);
</script>
<ModalFrame
open={theme != null}
busy={state.detailBusy}
maxWidthClass="max-w-2xl"
onClose={() => state.closeDetail()}
>
{#if theme}
<div class="flex items-start justify-between gap-4">
<div>
<h2 class="text-2xl font-bold">{theme.name}</h2>
<span
class="mt-1 inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {statusBadgeClass(theme.status)}"
>
{formatCustomThemeStatus(theme.status)}
</span>
</div>
<button
type="button"
class="rounded-lg p-2 hover:bg-zinc-100 dark:hover:bg-zinc-700"
aria-label="Close"
onclick={() => state.closeDetail()}
>
✕
</button>
</div>
{#if theme.status === "rejected" && theme.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">{theme.rejection_reason}</p>
</div>
{/if}
{#if state.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(theme.created_at)}</dd>
</div>
<div>
<dt class="text-zinc-500">Last updated</dt>
<dd>{formatThemeDate(theme.updated_at)}</dd>
</div>
{#if theme.reviewed_at}
<div>
<dt class="text-zinc-500">Reviewed</dt>
<dd>{formatThemeDate(theme.reviewed_at)}</dd>
</div>
{/if}
{#if theme.slug}
<div>
<dt class="text-zinc-500">Slug</dt>
<dd class="truncate">{theme.slug}</dd>
</div>
{/if}
</dl>
{#if state.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 state.detailFiles as file (file.id)}
<li>{file.file_path} ({file.file_size.toLocaleString()} bytes)</li>
{/each}
</ul>
</div>
{/if}
{#if canEditCustomTheme(theme)}
<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={state.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={state.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={state.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={state.detailBusy}
onclick={() => void state.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) => {
state.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={state.detailBusy || !state.replaceZipFile}
onclick={() => void state.runReplaceFiles()}
>
Upload revised files
</button>
</div>
{:else if theme.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 state.detailError}
<p class="mt-4 whitespace-pre-line text-sm text-red-600 dark:text-red-400">
{state.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 state.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={state.detailBusy}
onclick={() => void state.runDelete()}
>
Confirm delete
</button>
<button
type="button"
class="rounded-lg px-3 py-1.5 text-sm"
onclick={() => (state.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={() => (state.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={() => state.closeDetail()}
>
Close
</button>
</div>
{/if}
{/if}
</ModalFrame>
+1 -1
View File
@@ -71,7 +71,7 @@
role="tab"
aria-selected={activePage === tab.id}
onclick={() => setActivePage(tab.id)}
class="relative z-10 h-10 flex-1 whitespace-nowrap rounded-full px-4 text-base transition-colors duration-200
class="relative z-10 h-10 flex-1 whitespace-nowrap rounded-full px-4 text-lg transition-colors duration-200
{activePage === tab.id
? 'font-semibold text-zinc-900 dark:text-white'
: 'text-zinc-500 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-white'}"
@@ -4,9 +4,10 @@
masterGridDisplayDownloadCount,
gridCardPreviewImageUrls,
} from '@/interface/utils/themeStoreFlavours'
import { isStoreThemeInstalled } from '@/interface/utils/themeListFilters'
import emblaCarouselSvelte from 'embla-carousel-svelte';
import Autoplay from 'embla-carousel-autoplay';
let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows } = $props<{
let { theme, onClick, toggleFavorite, isLoggedIn, onRequestSignIn, allStoreThemeRows, installedThemeIds = [], variant = 'official' } = $props<{
theme: Theme;
onClick: () => void;
toggleFavorite: (theme: Theme) => void;
@@ -14,6 +15,8 @@
onRequestSignIn?: () => void;
/** Raw API themes (includes hidden slaves) for aggregated master download totals */
allStoreThemeRows?: Theme[];
installedThemeIds?: string[];
variant?: 'official' | 'community';
}>();
const displayDownloadCount = $derived(
@@ -47,6 +50,10 @@
];
});
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;
onClick();
@@ -72,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"
@@ -85,6 +102,20 @@
</span>
</div>
{/if}
{#if isInstalled}
<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"
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-3.5 h-3.5">
<path fill-rule="evenodd" d="M19.916 4.626a.75.75 0 01.208 1.04l-9 13.5a.75.75 0 01-1.154.114l-6-6a.75.75 0 011.06-1.06l5.353 5.353 8.493-12.739a.75.75 0 011.04-.208z" clip-rule="evenodd" />
</svg>
Installed
</span>
</div>
{/if}
{#if showFavorites}
<button
type="button"
data-theme-favorite
@@ -113,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}
@@ -125,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}
@@ -10,6 +10,8 @@
isLoggedIn,
onRequestSignIn,
allStoreThemeRows,
installedThemeIds = [],
variant = 'official',
} = $props<{
themes: Theme[];
searchTerm: string;
@@ -19,6 +21,8 @@
onRequestSignIn?: () => void;
/** Raw API list (includes `slave` rows) for master download aggregation */
allStoreThemeRows?: Theme[];
installedThemeIds?: string[];
variant?: 'official' | 'community';
}>();
let filteredThemes = $derived(themes.filter((theme: Theme) => {
@@ -39,21 +43,11 @@
{isLoggedIn}
{onRequestSignIn}
{allStoreThemeRows}
{installedThemeIds}
{variant}
/>
{/each}
{#if filteredThemes.length !== 0}
<a href="https://docs.betterseqta.org/theme-creation/" class="block relative z-0 hover:z-20 w-full cursor-pointer">
<div class="bg-zinc-50 h-48 w-full transition-[transform,box-shadow,border-color] duration-300 ease-out relative overflow-clip rounded-xl border group group/card flex flex-col justify-center items-center hover:scale-[1.02] hover:shadow-xl dark:hover:shadow-black/60 dark:bg-zinc-800 dark:border-white/[0.1]">
<div class="text-2xl font-IconFamily">{'\uecb3'}</div>
<div class="text-xl font-bold text-center transition-all duration-500 dark:text-white">
Got a Theme Idea?
<p class="text-lg font-light subtitle">Transform it into a stunning theme!</p>
</div>
</div>
</a>
{/if}
</div>
{#if filteredThemes.length === 0}
<div class="absolute top-0 flex flex-col items-center justify-center w-full text-center h-96">
+126 -26
View File
@@ -9,24 +9,33 @@ flavourCarouselImageUrl,
masterCarouselImageUrl,
masterGridDisplayDownloadCount,
} from '@/interface/utils/themeStoreFlavours'
import {
getThemeApplyButtonStyles,
resolveStoreVariantAccentColor,
} from '@/interface/utils/themeListFilters'
let {
theme,
currentThemes,
setDisplayTheme,
onInstall,
onRemove,
onApply,
allThemes,
allStoreThemeRows,
displayTheme,
toggleFavorite,
isLoggedIn,
onRequestSignIn,
selectedThemeId = '',
installedThemeColors = {},
variant = 'official',
} = $props<{
theme: Theme | null
currentThemes: string[]
setDisplayTheme: (theme: Theme | null) => void
onInstall: (themeId: string) => void | Promise<void>
onRemove: (themeId: string) => void | Promise<void>
onApply: (themeId: string) => void | Promise<void>
allThemes: Theme[]
/** Raw API themes (includes slaves) — same aggregation as grid download count */
allStoreThemeRows?: Theme[]
@@ -34,7 +43,20 @@ displayTheme: Theme | null
toggleFavorite?: (theme: Theme) => void
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)
}
return getThemeApplyButtonStyles(
resolveStoreVariantAccentColor(theme, variantId, installedThemeColors),
)
}
const modalDisplayDownloadCount = $derived.by(() => {
const t = theme
if (!t) return 0
@@ -106,7 +128,7 @@ $effect(() => {
if (displayTheme && modalElement) {
animate(
modalElement,
{ y: [500, 0], opacity: [0, 1] },
{ y: [16, 0], opacity: [0, 1], scale: [0.98, 1] },
{
type: 'spring',
stiffness: 150,
@@ -118,7 +140,7 @@ damping: 20,
const hideModal = (relatedTheme = null) => {
animate(
modalElement,
{ y: [10, 500], opacity: [1, 0] },
{ y: [0, 16], opacity: [1, 0], scale: [1, 0.98] },
{
type: 'spring',
stiffness: 150,
@@ -145,6 +167,14 @@ await onRemove(id)
installingId = null
}
}
async function runApply(id: string) {
installingId = id
try {
await onApply(id)
} finally {
installingId = null
}
}
async function onFlavourClick(flIdx: number, themeId: string, action: 'install' | 'remove') {
scrollHeroToFlavourIndex(flIdx)
if (action === 'install') await runInstall(themeId)
@@ -158,7 +188,7 @@ else await runRemove(theme.id)
}
</script>
<div
class="flex fixed inset-0 z-50 justify-center items-end bg-black/70 backdrop-blur-sm"
class="flex fixed inset-0 z-50 items-center justify-center bg-black/70 backdrop-blur-sm p-4 sm:p-6"
onclick={(e) => {
if (e.target === e.currentTarget) hideModal()
}}
@@ -171,7 +201,7 @@ transition:fade
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={modalElement}
class="w-full max-w-[600px] h-[95%] p-4 bg-white rounded-t-2xl dark:bg-zinc-800 overflow-y-auto overflow-x-hidden rounded-xl border border-zinc-200 dark:border-zinc-700 cursor-auto transition-colors duration-200"
class="flex w-full max-w-[600px] h-fit max-h-[calc(100dvh-3rem)] flex-col overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-2xl shadow-black/30 dark:border-zinc-700 dark:bg-zinc-800 cursor-auto transition-colors duration-200"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
role="dialog"
@@ -179,7 +209,7 @@ aria-modal="true"
tabindex="-1"
>
{#if theme}
<div class="relative h-auto">
<div class="relative flex max-h-[calc(100dvh-3rem)] flex-col overflow-y-auto overflow-x-hidden p-5 pb-8">
<div class="absolute top-0 right-0 flex gap-1 items-center">
<button
type="button"
@@ -194,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"
@@ -222,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}
@@ -277,12 +317,8 @@ aria-label="Next hero slide"
<p class="mb-2 text-sm font-semibold text-zinc-800 dark:text-zinc-100">Variants</p>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6 w-full">
{#if currentThemes.includes(theme.id)}
<button
type="button"
onclick={() => onMasterVariantClick('remove')}
disabled={installingId !== null}
class="relative w-full overflow-hidden rounded-2xl min-h-[9.5rem] sm:min-h-[11rem] text-left shadow-md border border-zinc-400/70 dark:border-zinc-500 transition-all duration-200 hover:scale-[1.02] active:scale-[0.98] focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-800 disabled:opacity-70 group ring-1 ring-black/10 dark:ring-white/10"
title="Remove {theme.name} (master)"
<div
class="relative w-full overflow-hidden rounded-2xl min-h-[9.5rem] sm:min-h-[11rem] text-left shadow-md border border-zinc-400/70 dark:border-zinc-500 group ring-1 ring-black/10 dark:ring-white/10"
>
{#if masterThumb}
<img src={masterThumb} alt="" class="absolute inset-0 w-full h-full object-cover transition-transform duration-200 group-hover:scale-[1.03]" draggable="false" />
@@ -297,11 +333,32 @@ title="Remove {theme.name} (master)"
</span>
{/if}
<span class="text-lg sm:text-xl font-bold text-white drop-shadow-md tracking-tight leading-snug">
Remove · {theme.name}
{theme.id === selectedThemeId ? 'Applied · ' : ''}{theme.name}
</span>
<span class="mt-1 text-sm font-medium text-white/85">Master</span>
</div>
<span class="mt-1 text-sm font-medium text-white/85">Master · Installed</span>
<div class="mt-3 flex flex-wrap gap-2">
{#if theme.id !== selectedThemeId}
<button
type="button"
onclick={(e) => { e.stopPropagation(); void runApply(theme.id) }}
disabled={installingId !== null}
style={variantApplyStyles(theme.id).apply}
class="px-3 py-1.5 text-sm font-semibold rounded-lg hover:brightness-90 disabled:opacity-70"
>
Apply
</button>
{/if}
<button
type="button"
onclick={(e) => { e.stopPropagation(); void onMasterVariantClick('remove') }}
disabled={installingId !== null}
class="px-3 py-1.5 text-sm font-semibold rounded-lg bg-white/20 text-white hover:bg-white/30 disabled:opacity-70"
>
Remove
</button>
</div>
</div>
</div>
{:else}
<button
type="button"
@@ -330,12 +387,8 @@ title="Install {theme.name} (master)"
{#each theme.flavours ?? [] as f, flavourIdx (f.id)}
{@const thumb = flavourCarouselImageUrl(f)}
{#if currentThemes.includes(f.id)}
<button
type="button"
onclick={() => onFlavourClick(flavourIdx, f.id, 'remove')}
disabled={installingId !== null}
class="relative w-full overflow-hidden rounded-2xl min-h-[9.5rem] sm:min-h-[11rem] text-left shadow-md border border-zinc-400/70 dark:border-zinc-500 transition-all duration-200 hover:scale-[1.02] active:scale-[0.98] focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-800 disabled:opacity-70 group ring-1 ring-black/10 dark:ring-white/10"
title="Remove {f.name}"
<div
class="relative w-full overflow-hidden rounded-2xl min-h-[9.5rem] sm:min-h-[11rem] text-left shadow-md border border-zinc-400/70 dark:border-zinc-500 group ring-1 ring-black/10 dark:ring-white/10"
>
{#if thumb}
<img src={thumb} alt="" class="absolute inset-0 w-full h-full object-cover transition-transform duration-200 group-hover:scale-[1.03]" draggable="false" />
@@ -350,10 +403,32 @@ title="Remove {f.name}"
</span>
{/if}
<span class="text-lg sm:text-xl font-bold text-white drop-shadow-md tracking-tight leading-snug">
Remove · {f.name}
{f.id === selectedThemeId ? 'Applied · ' : ''}{f.name}
</span>
</div>
<span class="mt-1 text-sm font-medium text-white/85">Installed</span>
<div class="mt-3 flex flex-wrap gap-2">
{#if f.id !== selectedThemeId}
<button
type="button"
onclick={(e) => { e.stopPropagation(); scrollHeroToFlavourIndex(flavourIdx); void runApply(f.id) }}
disabled={installingId !== null}
style={variantApplyStyles(f.id).apply}
class="px-3 py-1.5 text-sm font-semibold rounded-lg hover:brightness-90 disabled:opacity-70"
>
Apply
</button>
{/if}
<button
type="button"
onclick={(e) => { e.stopPropagation(); void onFlavourClick(flavourIdx, f.id, 'remove') }}
disabled={installingId !== null}
class="px-3 py-1.5 text-sm font-semibold rounded-lg bg-white/20 text-white hover:bg-white/30 disabled:opacity-70"
>
Remove
</button>
</div>
</div>
</div>
{:else}
<button
type="button"
@@ -385,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'}"
@@ -401,6 +476,31 @@ aria-label={theme.is_favorited ? 'Unfavorite' : 'Favorite'}
{/if}
{#if !hasFlavours}
{#if currentThemes.includes(theme.id)}
{#if theme.id === selectedThemeId}
<button
type="button"
disabled
style={variantApplyStyles(theme.id).applied}
class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] rounded-lg opacity-90"
>
Applied
</button>
{:else}
<button
type="button"
onclick={() => runApply(theme.id)}
disabled={installingId !== null}
style={variantApplyStyles(theme.id).apply}
class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] rounded-lg transition-all duration-200 hover:brightness-90 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-70"
>
{#if installingId === theme.id}
<svg class="absolute w-4 h-4 animate-spin" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke="currentColor" fill="currentColor" class="origin-center animate-spin-fast" d="M2,12A11.2,11.2,0,0,1,13,1.05C12.67,1,12.34,1,12,1a11,11,0,0,0,0,22c.34,0,.67,0,1-.05C6,23,2,17.74,2,12Z"/>
</svg>
{/if}
<span class="{installingId === theme.id ? 'opacity-0' : 'opacity-100'}">Apply</span>
</button>
{/if}
<button
type="button"
onclick={() => runRemove(theme.id)}
@@ -432,11 +532,11 @@ class="relative flex justify-center items-center px-4 py-2 min-w-[8rem] text-bla
{/if}
</div>
{#if relatedThemes.length > 0}
<div class="my-8 border-b border-zinc-200 dark:border-zinc-700"></div>
<div class="pt-6 mt-6 border-t border-zinc-200 dark:border-zinc-700"></div>
<h3 class="mb-4 text-lg font-bold text-zinc-900 dark:text-white">
Related themes
</h3>
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div class="grid grid-cols-1 gap-4 pb-2 sm:grid-cols-2">
{#each relatedThemes as relatedTheme (relatedTheme.id)}
<button
type="button"
@@ -458,7 +558,7 @@ class="relative z-0 hover:z-20 w-full cursor-pointer rounded-xl overflow-hidden
{/if}
</div>
{:else}
<div class="flex justify-center items-center h-full text-zinc-600 dark:text-zinc-300">
<div class="flex justify-center items-center p-8 text-zinc-600 dark:text-zinc-300">
<button
type="button"
class="px-4 py-2 rounded-lg bg-zinc-200 dark:bg-zinc-700 transition-all duration-200 hover:scale-105 active:scale-95 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-800"
@@ -0,0 +1,15 @@
<script lang="ts">
import { defaultThemeCoverDataUrl } from "@/interface/utils/themePlaceholderCover";
let {
accentHint = "#52525b",
class: className = "",
}: {
accentHint?: string;
class?: string;
} = $props();
const src = $derived(defaultThemeCoverDataUrl(accentHint));
</script>
<img src={src} alt="" class={className} draggable="false" />
@@ -3,25 +3,33 @@
import { onDestroy, onMount } from 'svelte'
import browser from 'webextension-polyfill'
import { themeUpdates } from '@/interface/hooks/ThemeUpdates'
import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup'
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
import { cloudAuth } from '@/seqta/utils/CloudAuth'
import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte'
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte'
import { filterThemesByMode, isLocalCustomTheme, type ThemeListMode } from '@/interface/utils/themeListFilters'
import { closeExtensionPopup, SettingsClicked } from '@/seqta/utils/Closers/closeExtensionPopup'
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
const themeManager = ThemeManager.getInstance();
let themes = $state<ThemeList | null>(null);
let { isEditMode, showNavigation = true } = $props<{
let { isEditMode, showNavigation = true, listMode = 'all' } = $props<{
isEditMode: boolean;
showNavigation?: boolean;
listMode?: ThemeListMode;
}>();
let isDragging = $state(false);
let dragDepth = $state(0);
let tempTheme = $state(null);
let fileInput = $state<HTMLInputElement | null>(null);
let favoriteStatus = $state<Record<string, boolean>>({});
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
let prevLoggedIn = $state(false);
let showSignInModal = $state(false);
let submittingThemeId = $state<string | null>(null);
let submitError = $state<string | null>(null);
$effect(() => {
const unsub = cloudAuth.subscribe((s) => {
@@ -70,21 +78,33 @@
}
}
const handleDragOver = (e: DragEvent) => {
const allowsFileImport = $derived(listMode === 'custom');
const handleDragEnter = (e: DragEvent) => {
if (!allowsFileImport) return;
e.preventDefault();
dragDepth += 1;
isDragging = true;
}
const handleDragLeave = () => {
isDragging = false;
const handleDragOver = (e: DragEvent) => {
if (!allowsFileImport) return;
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
isDragging = true;
}
const handleDrop = async (e: DragEvent) => {
const handleDragLeave = (e: DragEvent) => {
if (!allowsFileImport) return;
e.preventDefault();
isDragging = false;
const file = e.dataTransfer?.files[0];
if (!file) return;
dragDepth -= 1;
if (dragDepth <= 0) {
dragDepth = 0;
isDragging = false;
}
}
async function importThemeFromFile(file: File) {
const reader = new FileReader();
reader.onload = async (event: ProgressEvent<FileReader>) => {
try {
@@ -101,6 +121,27 @@
reader.readAsText(file);
}
const handleDrop = async (e: DragEvent) => {
if (!allowsFileImport) return;
e.preventDefault();
dragDepth = 0;
isDragging = false;
const file = e.dataTransfer?.files[0];
if (!file) return;
await importThemeFromFile(file);
}
const handleFileInputChange = async (e: Event) => {
const input = e.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (file) await importThemeFromFile(file);
input.value = '';
}
const triggerFileUpload = () => {
fileInput?.click();
}
const fetchThemes = async () => {
themes = {
themes: await themeManager.getAvailableThemes(),
@@ -135,11 +176,38 @@
}
const openThemeCreator = async (themeId?: string) => {
const { OpenThemeCreator } = await import('@/plugins/built-in/themes/ThemeCreator')
OpenThemeCreator(themeId)
closeExtensionPopup()
const { launchPageThemeBuilder } = await import('@/seqta/utils/launchPageThemeBuilder')
await launchPageThemeBuilder(themeId)
}
const openCommunitySubmit = async () => {
const { openCommunityThemeSubmit } = await import('@/seqta/utils/openCommunityThemeSubmit')
await openCommunityThemeSubmit()
}
const submitCustomTheme = async (theme: CustomTheme, e: MouseEvent) => {
e.stopPropagation();
submitError = null;
if (!cloudLoggedIn) {
showSignInModal = true;
return;
}
submittingThemeId = theme.id;
try {
const { submitThemeById } = await import('@/seqta/utils/customThemes/submitLocalTheme');
await submitThemeById(theme.id, theme.description?.trim() || undefined);
} catch (err) {
submitError = formatCustomThemeApiError(err);
} finally {
submittingThemeId = null;
}
}
const customThemeActionClass =
'flex h-12 items-center justify-center gap-2 w-full rounded-xl transition bg-zinc-100 text-xl dark:bg-zinc-900 dark:text-white hover:bg-zinc-200 dark:hover:bg-zinc-800'
const customThemeActionCompactClass = customThemeActionClass
const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => {
e.stopPropagation();
if (!cloudLoggedIn) {
@@ -165,34 +233,63 @@
onDestroy(() => {
themeUpdates.removeListener(fetchThemes);
})
const visibleThemes = $derived(
themes ? filterThemesByMode(themes.themes, listMode) : [],
);
const useTwoColumnLayout = $derived(listMode === 'downloaded' || listMode === 'custom');
</script>
<div
class="pt-5 mb-1 w-full max-w-lg mx-auto"
class="relative mb-1 w-full {useTwoColumnLayout ? '' : 'max-w-lg mx-auto'}"
role="list"
tabindex="-1"
ondragenter={handleDragEnter}
ondragover={handleDragOver}
ondragleave={handleDragLeave}
ondrop={handleDrop}
>
<div class="{isDragging ? 'opacity-100' : 'opacity-0'} transition pointer-events-none absolute w-full p-2 z-50">
<div class="sticky top-5 w-full h-64 bg-white rounded-xl shadow-xl dark:bg-zinc-900 dark:text-white outline-dashed outline-4 outline-zinc-200 dark:outline-zinc-700">
<div class="flex justify-center items-center h-full">
<div class="flex flex-col justify-center items-center">
<svg height="48" width="48" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">
<g fill="currentColor">
<path d="M44,31a1,1,0,0,0-1,1v8a3,3,0,0,1-3,3H8a3,3,0,0,1-3-3V32a1,1,0,0,0-2,0v8a5.006,5.006,0,0,0,5,5H40a5.006,5.006,0,0,0,5-5V32A1,1,0,0,0,44,31Z" fill="currentColor"/>
<path d="M23.2,33.6a1,1,0,0,0,1.6,0l9-12A1,1,0,0,0,33,20H26V5a2,2,0,0,0-4,0V20H15a1,1,0,0,0-.8,1.6Z" fill="currentColor"/>
</g>
</svg>
<span class="text-lg">Import Theme</span>
</div>
{#if allowsFileImport}
<input
bind:this={fileInput}
type="file"
accept=".json,application/json"
class="hidden"
onchange={(e) => void handleFileInputChange(e)}
/>
{/if}
{#if allowsFileImport && isDragging}
<div class="absolute inset-0 z-50 flex items-center justify-center p-3 pointer-events-none">
<div class="flex h-full w-full flex-col items-center justify-center gap-3 rounded-xl border-4 border-dashed border-zinc-300 bg-white/95 px-6 text-center shadow-xl dark:border-zinc-600 dark:bg-zinc-900/95 dark:text-white">
<svg height="48" width="48" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<g fill="currentColor">
<path d="M44,31a1,1,0,0,0-1,1v8a3,3,0,0,1-3,3H8a3,3,0,0,1-3-3V32a1,1,0,0,0-2,0v8a5.006,5.006,0,0,0,5,5H40a5.006,5.006,0,0,0,5-5V32A1,1,0,0,0,44,31Z" fill="currentColor"/>
<path d="M23.2,33.6a1,1,0,0,0,1.6,0l9-12A1,1,0,0,0,33,20H26V5a2,2,0,0,0-4,0V20H15a1,1,0,0,0-.8,1.6Z" fill="currentColor"/>
</g>
</svg>
<span class="text-lg font-medium">Drop theme file to import</span>
</div>
</div>
</div>
<div class="flex flex-col gap-2 px-2">
{/if}
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'}">
{#if allowsFileImport}
<button
type="button"
onclick={triggerFileUpload}
class="flex aspect-[10/1] w-full items-center justify-center gap-3 rounded-xl border-2 border-dashed border-zinc-300 bg-zinc-50 px-4 text-center transition hover:border-zinc-400 hover:bg-zinc-100 dark:border-zinc-600 dark:bg-zinc-900/40 dark:hover:border-zinc-500 dark:hover:bg-zinc-900 {useTwoColumnLayout ? 'col-span-2' : ''}"
>
<span class="text-xl font-IconFamily text-zinc-500 dark:text-zinc-400" aria-hidden="true">&#xe9fc;</span>
<div class="text-left">
<span class="block text-sm font-medium text-zinc-700 dark:text-zinc-200">Drag and drop theme files here</span>
<span class="block text-xs text-zinc-500 dark:text-zinc-400">or click to upload</span>
</div>
</button>
{/if}
{#if themes}
{#each themes.themes as theme (theme.id)}
{#each visibleThemes as theme (theme.id)}
<button
class="relative group w-full aspect-theme flex justify-center items-center rounded-xl transition ring dark:ring-white ring-zinc-300 {theme.id === themes.selectedTheme ? 'dark:ring-2 ring-4' : 'ring-0'}"
onclick={(e) => handleThemeClick(theme, e)}
@@ -210,36 +307,57 @@
{/if}
{#if !isEditMode}
<div
class="flex absolute right-24 top-1/4 z-20 place-items-center p-2 w-8 h-8 text-center rounded-full opacity-0 transition-all -translate-y-1/2 group-hover:opacity-100 group-hover:top-1/2 {(favoriteStatus[theme.id] ?? false) ? 'text-red-400' : 'text-white/80'} bg-black/50"
onclick={(event) => handleToggleFavorite(theme, event)}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }}
role="button"
tabindex="-1"
title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'}
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill={(favoriteStatus[theme.id] ?? false) ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="2" class="w-5 h-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>
</div>
<div
class="absolute z-20 flex w-8 h-8 p-2 text-white transition-all rounded-full delay-[20ms] opacity-0 top-1/4 right-2 bg-black/50 place-items-center group-hover:opacity-100 group-hover:top-1/2 -translate-y-1/2"
onclick={(event) => { event.stopPropagation(); void openThemeCreator(theme.id) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }}
role="button"
tabindex="-1"
>
<span class="text-lg font-IconFamily">&#xeaa5;</span>
</div>
<div class="absolute inset-y-0 right-3 z-20 flex items-center gap-2 opacity-0 transition-opacity group-hover:opacity-100">
{#if !isLocalCustomTheme(theme)}
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-center {(favoriteStatus[theme.id] ?? false) ? 'text-red-400' : 'text-white/80'}"
onclick={(event) => handleToggleFavorite(theme, event)}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleToggleFavorite(theme, event as any) }}
role="button"
tabindex="-1"
title={cloudLoggedIn ? ((favoriteStatus[theme.id] ?? false) ? 'Remove from favorites' : 'Add to favorites') : 'Sign in to favorite themes'}
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill={(favoriteStatus[theme.id] ?? false) ? 'currentColor' : 'none'} stroke="currentColor" stroke-width="2" class="h-5 w-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>
</div>
{/if}
<div
class="flex absolute right-12 top-1/4 z-20 place-items-center p-2 w-8 h-8 text-center rounded-full opacity-0 transition-all -translate-y-1/2 text-white/80 bg-black/50 group-hover:opacity-100 group-hover:top-1/2"
onclick={(event) => { event.stopPropagation(); handleShareTheme(theme) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }}
role="button"
tabindex="-1"
>
<span class="text-lg font-IconFamily">&#xecb3;</span>
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white/80"
onclick={(event) => { event.stopPropagation(); handleShareTheme(theme) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') handleShareTheme(theme) }}
role="button"
tabindex="-1"
title="Export theme"
>
<span class="text-lg font-IconFamily">&#xecb3;</span>
</div>
{#if isLocalCustomTheme(theme)}
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white"
onclick={(event) => { event.stopPropagation(); void openThemeCreator(theme.id) }}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }}
role="button"
tabindex="-1"
title="Edit theme"
>
<span class="text-lg font-IconFamily">&#xeaa5;</span>
</div>
{#if listMode === 'custom'}
<div
class="flex h-8 w-8 place-items-center rounded-full bg-black/50 p-2 text-white {submittingThemeId === theme.id ? 'opacity-60' : ''}"
onclick={(event) => void submitCustomTheme(theme, event)}
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void submitCustomTheme(theme, event as unknown as MouseEvent) }}
role="button"
tabindex="-1"
title="Submit to community"
>
<span class="text-lg font-IconFamily">&#xe9fc;</span>
</div>
{/if}
{/if}
</div>
{/if}
@@ -250,6 +368,11 @@
alt={theme.name}
class="object-cover absolute inset-0 z-0 w-full h-full pointer-events-none"
/>
{:else}
<ThemePlaceholderCover
accentHint={theme.defaultColour}
class="pointer-events-none absolute inset-0 z-0 h-full w-full object-cover"
/>
{/if}
{#if !theme.hideThemeName}
<div class="z-10 {theme.coverImage ? 'text-white' : ''}">{theme.name}</div>
@@ -260,7 +383,7 @@
{/if}
{#if tempTheme}
<div class="flex justify-center place-items-center w-full bg-gray-200 rounded-xl animate-pulse dark:bg-zinc-700/50 aspect-theme">
<div class="flex justify-center place-items-center w-full bg-gray-200 rounded-xl animate-pulse dark:bg-zinc-700/50 aspect-theme {useTwoColumnLayout ? 'col-span-2' : ''}">
<svg class="w-5 h-5 text-white animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
@@ -268,53 +391,123 @@
</div>
{/if}
{#if themes && themes.themes.length === 0 && !tempTheme}
<div class="flex min-h-56 flex-col items-center justify-center px-4 py-10 text-center">
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
No themes installed
</h3>
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
Install a theme from the store or create one of your own.
</p>
<div class="mt-6 grid w-full max-w-md grid-cols-1 gap-2 sm:grid-cols-2">
<button
type="button"
onclick={() => void openStorePage()}
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
>
<span class="font-IconFamily text-lg" aria-hidden="true">&#xecc5;</span>
Install a theme
</button>
<button
type="button"
onclick={() => void openThemeCreator()}
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
>
<span class="font-IconFamily text-lg" aria-hidden="true">&#xec60;</span>
Create a theme
</button>
</div>
{#if themes && visibleThemes.length === 0 && !tempTheme}
<div class="flex min-h-56 flex-col items-center justify-center px-4 py-10 text-center {useTwoColumnLayout ? 'col-span-2' : ''}">
{#if listMode === 'custom'}
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
No custom themes yet
</h3>
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
Drag and drop a theme file above, create your own theme, or follow our guide to get started.
</p>
{:else if listMode === 'downloaded'}
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
No downloaded themes
</h3>
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
Browse the theme store to find and install themes.
</p>
<div class="mt-6 grid w-full max-w-md grid-cols-1 gap-2">
<button
type="button"
onclick={() => void openStorePage()}
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
>
<span class="font-IconFamily text-lg" aria-hidden="true">&#xecc5;</span>
Browse the store
</button>
</div>
{:else}
<h3 class="text-xl font-semibold text-zinc-900 dark:text-white" style="text-wrap: balance">
No themes installed
</h3>
<p class="mt-2 max-w-md text-base text-zinc-500 dark:text-zinc-400" style="text-wrap: pretty">
Install a theme from the store or create one of your own.
</p>
<div class="mt-6 grid w-full max-w-md grid-cols-1 gap-2 sm:grid-cols-2">
<button
type="button"
onclick={() => void openStorePage()}
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
>
<span class="font-IconFamily text-lg" aria-hidden="true">&#xecc5;</span>
Install a theme
</button>
<button
type="button"
onclick={() => void openThemeCreator()}
class="flex h-11 items-center justify-center gap-2 rounded-lg bg-zinc-200 px-4 font-medium text-zinc-900 transition-[background-color,color,transform] duration-150 hover:bg-zinc-300 active:scale-[0.96] focus:outline-none focus:ring-2 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
>
<span class="font-IconFamily text-lg" aria-hidden="true">&#xec60;</span>
Create a theme
</button>
</div>
{/if}
</div>
{/if}
{#if showNavigation && themes && themes.themes.length > 0}
<div id="divider" class="w-full h-[1px] my-2 bg-zinc-100 dark:bg-zinc-600"></div>
{#if themes && (listMode === 'custom' || (showNavigation && visibleThemes.length > 0) || (listMode === 'downloaded' && visibleThemes.length > 0))}
<div id="divider" class="w-full h-[1px] my-2 bg-zinc-100 dark:bg-zinc-600 {useTwoColumnLayout ? 'col-span-2' : ''}"></div>
<button
onclick={() => void openStorePage()}
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
>
<span class="text-xl font-IconFamily">&#xecc5;</span>
<span class="ml-2">Theme Store</span>
</button>
{#if listMode === 'custom' && submitError}
<p class="col-span-2 whitespace-pre-line text-sm text-red-600 dark:text-red-400">{submitError}</p>
{/if}
<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"
>
<span class="text-xl font-IconFamily">&#xec60;</span>
<span class="ml-2">Create your own</span>
</button>
{#if listMode === 'custom'}
<div class="grid grid-cols-2 gap-2 {useTwoColumnLayout ? 'col-span-2' : ''}">
<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={customThemeActionCompactClass}
>
<span class="text-2xl font-IconFamily" aria-hidden="true">{'\uecb3'}</span>
<span>View docs</span>
</a>
<button
type="button"
onclick={() => void openCommunitySubmit()}
class="{customThemeActionClass} col-span-2"
>
<span class="text-2xl font-IconFamily" aria-hidden="true">&#xe9fc;</span>
<span>Create & submit</span>
</button>
</div>
{:else if listMode === 'downloaded'}
<button
onclick={() => void openStorePage()}
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">&#xecc5;</span>
<span class="ml-2">Theme Store</span>
</button>
{:else}
<button
onclick={() => void openStorePage()}
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
>
<span class="text-xl font-IconFamily">&#xecc5;</span>
<span class="ml-2">Theme Store</span>
</button>
<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"
>
<span class="text-xl font-IconFamily">&#xec60;</span>
<span class="ml-2">Create your own</span>
</button>
{/if}
{/if}
</div>
</div>
@@ -0,0 +1,275 @@
import browser from "webextension-polyfill";
import type { Theme } from "@/interface/types/Theme";
import { getCommunityInstalledThemeIds } from "@/interface/utils/themeListFilters";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import {
deleteCustomTheme,
fetchCommunityThemes,
fetchMyCustomThemeDetail,
fetchMyCustomThemes,
replaceCustomThemeFiles,
updateCustomThemeMetadata,
} from "@/seqta/utils/customThemes/client";
import {
buildUploadPartsFromZipFile,
mergeUploadPayload,
} from "@/seqta/utils/customThemes/buildThemeUploadFormData";
import { formatCustomThemeApiError } from "@/seqta/utils/customThemes/apiErrors";
import type { CustomThemeFile, CustomThemeOwner } from "@/seqta/utils/customThemes/types";
import {
consumeOpenCommunityThemeSubmit,
consumePendingCommunitySubmitThemeId,
OPEN_COMMUNITY_SUBMIT_EVENT,
} from "@/seqta/utils/openCommunityThemeSubmit";
export type CommunityThemesTab = "browse" | "mine";
export class CommunityThemesState {
innerTab = $state<CommunityThemesTab>("browse");
cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
browseThemes = $state<Theme[]>([]);
browseLoading = $state(true);
browseError = $state<string | null>(null);
myThemes = $state<CustomThemeOwner[]>([]);
myLoading = $state(false);
myError = $state<string | null>(null);
statusFilter = $state<"" | "pending" | "approved" | "rejected">("");
displayTheme = $state<Theme | null>(null);
currentThemes = $state<string[]>([]);
selectedThemeId = $state("");
installedThemeColors = $state<Record<string, string>>({});
showSignInOverlay = $state(false);
detailTheme = $state<CustomThemeOwner | null>(null);
detailFiles = $state<CustomThemeFile[]>([]);
detailLoading = $state(false);
detailError = $state<string | null>(null);
editName = $state("");
editDescription = $state("");
editNotes = $state("");
detailBusy = $state(false);
replaceZipFile = $state<File | null>(null);
showDeleteConfirm = $state(false);
private readonly themeManager = ThemeManager.getInstance();
constructor(private readonly getSearchTerm: () => string) {}
async refreshInstalledThemes() {
const themes = await this.themeManager.getAvailableThemes();
this.currentThemes = getCommunityInstalledThemeIds(themes);
this.selectedThemeId = this.themeManager.getSelectedThemeId() || "";
this.installedThemeColors = Object.fromEntries(
themes
.filter((t) => t != null && t.installedFromCommunity === true)
.map((t) => [t.id, t.defaultColour]),
);
}
async loadBrowseThemes() {
this.browseLoading = true;
this.browseError = null;
try {
const q = this.getSearchTerm().trim();
const res = await fetchCommunityThemes({
sort: "popular",
limit: 50,
search: q.length > 0 ? q : undefined,
});
this.browseThemes = res.themes as Theme[];
} catch (err) {
this.browseError = err instanceof Error ? err.message : "Could not load community themes";
} finally {
this.browseLoading = false;
}
}
async loadMyThemes() {
if (!this.cloudLoggedIn) return;
this.myLoading = true;
this.myError = null;
try {
const res = await fetchMyCustomThemes({
limit: 50,
status: this.statusFilter || undefined,
});
this.myThemes = res.themes;
} catch (err) {
this.myError = err instanceof Error ? err.message : "Could not load your themes";
} finally {
this.myLoading = false;
}
}
async openDetail(theme: CustomThemeOwner) {
this.detailTheme = theme;
this.detailFiles = [];
this.detailError = null;
this.editName = theme.name;
this.editDescription = theme.description ?? "";
this.editNotes = theme.submission_notes ?? "";
this.replaceZipFile = null;
this.showDeleteConfirm = false;
this.detailLoading = true;
try {
const res = await fetchMyCustomThemeDetail(theme.id);
this.detailTheme = res.theme;
this.detailFiles = res.files;
this.editName = res.theme.name;
this.editDescription = res.theme.description ?? "";
this.editNotes = res.theme.submission_notes ?? "";
} catch (err) {
this.detailError = err instanceof Error ? err.message : "Could not load theme details";
} finally {
this.detailLoading = false;
}
}
closeDetail() {
this.detailTheme = null;
this.detailFiles = [];
this.detailError = null;
this.showDeleteConfirm = false;
}
async installCommunityTheme(themeId: string, meta: Theme) {
const row = this.browseThemes.find((x) => x.id === themeId) ?? meta;
const installedId = await this.themeManager.downloadCommunityTheme({
id: themeId,
theme_json_url: row.theme_json_url,
updated_at: row.updated_at,
});
await this.themeManager.setTheme(installedId);
themeUpdates.triggerUpdate();
await this.refreshInstalledThemes();
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
}
async removeInstalledTheme(themeId: string) {
await this.themeManager.deleteTheme(themeId);
themeUpdates.triggerUpdate();
await this.refreshInstalledThemes();
}
async applyInstalledTheme(themeId: string) {
await this.themeManager.setTheme(themeId);
this.selectedThemeId = themeId;
themeUpdates.triggerUpdate();
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
}
async saveMetadata() {
if (!this.detailTheme) return;
this.detailBusy = true;
this.detailError = null;
try {
const updated = await updateCustomThemeMetadata(this.detailTheme.id, {
name: this.editName.trim() || undefined,
description: this.editDescription.trim() || undefined,
submission_notes: this.editNotes.trim() || undefined,
});
this.detailTheme = updated;
await this.loadMyThemes();
} catch (err) {
this.detailError = formatCustomThemeApiError(err);
} finally {
this.detailBusy = false;
}
}
async runReplaceFiles() {
if (!this.detailTheme || !this.replaceZipFile) return;
this.detailBusy = true;
this.detailError = null;
try {
const payload = mergeUploadPayload(await buildUploadPartsFromZipFile(this.replaceZipFile));
const res = await replaceCustomThemeFiles(this.detailTheme.id, payload);
this.detailTheme = res.theme;
this.replaceZipFile = null;
await this.loadMyThemes();
} catch (err) {
this.detailError = formatCustomThemeApiError(err);
} finally {
this.detailBusy = false;
}
}
async runDelete() {
if (!this.detailTheme) return;
this.detailBusy = true;
this.detailError = null;
try {
await deleteCustomTheme(this.detailTheme.id);
this.closeDetail();
await this.loadMyThemes();
} catch (err) {
this.detailError = formatCustomThemeApiError(err);
} finally {
this.detailBusy = false;
this.showDeleteConfirm = false;
}
}
bindReactiveLoads() {
$effect(() => {
const unsub = cloudAuth.subscribe((s) => {
this.cloudLoggedIn = s.isLoggedIn;
});
return unsub;
});
$effect(() => {
if (this.innerTab === "browse") void this.loadBrowseThemes();
});
$effect(() => {
this.getSearchTerm();
if (this.innerTab === "browse") void this.loadBrowseThemes();
});
$effect(() => {
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
});
$effect(() => {
this.statusFilter;
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
});
}
mount() {
const onThemesUpdated = () => void this.refreshInstalledThemes();
themeUpdates.addListener(onThemesUpdated);
void this.refreshInstalledThemes();
const openPageBuilderForSubmit = () => {
const themeId = consumePendingCommunitySubmitThemeId() ?? undefined;
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
launchPageThemeBuilder(themeId),
);
};
if (consumeOpenCommunityThemeSubmit()) {
openPageBuilderForSubmit();
}
const onOpenCommunitySubmit = () => {
if (consumeOpenCommunityThemeSubmit()) openPageBuilderForSubmit();
};
window.addEventListener(OPEN_COMMUNITY_SUBMIT_EVENT, onOpenCommunitySubmit);
return () => {
themeUpdates.removeListener(onThemesUpdated);
window.removeEventListener(OPEN_COMMUNITY_SUBMIT_EVENT, onOpenCommunitySubmit);
};
}
}
export function createCommunityThemesState(getSearchTerm: () => string) {
return new CommunityThemesState(getSearchTerm);
}
@@ -0,0 +1,13 @@
class ThemeBuilderPanelStore {
editingThemeId = $state<string | null>(null);
open(themeId?: string | null) {
this.editingThemeId = themeId ?? null;
}
close() {
this.editingThemeId = null;
}
}
export const themeBuilderPanel = new ThemeBuilderPanelStore();
+2
View File
@@ -34,6 +34,8 @@ if (!mountPoint) {
void (async () => {
await initializeSettingsState();
initVerboseLogging();
const { syncApiBaseToBackground } = await import("@/seqta/utils/DevApiBase");
syncApiBaseToBackground();
renderSvelte(Settings, mountPoint, { standalone: true });
})();
}
@@ -0,0 +1,64 @@
<script lang="ts">
import { onMount } from "svelte";
import BrowsePanel from "@/interface/components/communityThemes/BrowsePanel.svelte";
import MyThemesPanel from "@/interface/components/communityThemes/MyThemesPanel.svelte";
import OwnerThemeDetailModal from "@/interface/components/communityThemes/OwnerThemeDetailModal.svelte";
import { createCommunityThemesState } from "@/interface/hooks/communityThemesState.svelte";
let { searchTerm }: { searchTerm: string; setSearchTerm?: (term: string) => void } = $props();
const state = createCommunityThemesState(() => searchTerm);
state.bindReactiveLoads();
onMount(() => state.mount());
</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 {state.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={() => (state.innerTab = "browse")}
>
Browse
</button>
<button
type="button"
class="rounded-lg px-4 py-2 text-sm font-medium transition-colors {state.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={() => (state.innerTab = "mine")}
>
My themes
</button>
</div>
<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={() =>
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
launchPageThemeBuilder(),
)}
>
Create & submit
</button>
</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 state.innerTab === "browse"}
<BrowsePanel {state} {searchTerm} />
{:else}
<MyThemesPanel {state} />
{/if}
</main>
<OwnerThemeDetailModal {state} />
</div>
+108 -78
View File
@@ -33,13 +33,14 @@
} from "@/utils/githubReleaseUpdate";
type PageId = "settings" | "themes" | "backgrounds";
type StoreTab = "themes" | "backgrounds";
type ThemeView = "theme-settings" | "theme-store";
type ThemeView = "theme-settings" | "theme-store" | "community-themes" | "create-theme";
type BackgroundView = "background-settings" | "background-store";
const loadSettingsBody = () => import("./settings/SettingsBody.svelte");
const loadShortcuts = () => import("./settings/shortcuts.svelte");
const loadThemeSettings = () => import("./settings/theme.svelte");
const loadStore = () => import("./store.svelte");
const loadCommunityThemes = () => import("./communityThemes.svelte");
type NavItem = {
id: string;
@@ -105,9 +106,10 @@
{
label: "Themes",
items: [
{ id: "theme-store", label: "Store" },
{ id: "theme-settings", label: "Theme settings" },
{ id: "create-theme", label: "Create theme" },
{ id: "theme-store", label: "Theme store" },
{ id: "community-themes", label: "Community themes" },
{ id: "theme-settings", label: "Downloaded themes" },
{ id: "create-theme", label: "Custom themes" },
],
},
];
@@ -155,16 +157,33 @@
const sectionTitle = $derived.by(() => {
if (activePage === "settings" && debouncedSettingsSearch.trim()) return "Search results";
if (activePage === "themes") return "Themes";
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";
return [...userNav, ...appNav].find((item) => item.id === activeSection)?.label ?? "Settings";
});
const activeThemeListMode = $derived.by(() => {
if (activeThemeView === "create-theme") return "custom" as const;
if (activeThemeView === "theme-settings") return "downloaded" as const;
return "all" as const;
});
const isStoreView = $derived(
(activePage === "themes" && activeThemeView === "theme-store") ||
(activePage === "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";
@@ -293,11 +312,7 @@
}
if (activePage === "themes") {
if (id === "create-theme") {
void openThemeCreator();
} else {
activeThemeView = id as ThemeView;
}
activeThemeView = id as ThemeView;
return;
}
@@ -309,12 +324,6 @@
}
};
const openThemeCreator = async () => {
const { OpenThemeCreator } = await import("@/plugins/built-in/themes/ThemeCreator");
OpenThemeCreator();
closeExtensionPopup();
};
const applyDestination = (destination: SettingsDestination) => {
activePage = destination.page;
if (destination.page === "settings") {
@@ -326,7 +335,14 @@
settingsSearch = destination.search;
}
} else if (destination.page === "themes" && destination.view) {
activeThemeView = destination.view === "store" ? "theme-store" : "theme-settings";
activeThemeView =
destination.view === "store"
? "theme-store"
: 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";
}
@@ -410,7 +426,7 @@
activePage = page;
if (page === "themes") activeThemeView = "theme-store";
}}
showStoreTools={isStoreView}
showStoreTools={isOfficialStoreView || activeThemeView === "community-themes"}
onLogoClick={handleDevModeToggle}
onClose={handleClose}
/>
@@ -507,71 +523,85 @@
</div>
</nav>
{#if isStoreView}
<div class="min-w-0 min-h-0 flex-1">
<LazyPanel
loader={loadStore}
remountKey="store"
props={{
activeTab: activePage as StoreTab,
searchTerm: storeSearchTerm,
selectedBackgroundCategory,
setActiveTab: (tab: StoreTab) => {
activePage = tab;
if (tab === "themes") activeThemeView = "theme-store";
else activeBackgroundView = "background-store";
},
setSearchTerm: (term: string) => (storeSearchTerm = term),
setBackgroundCategories: (categories: string[]) =>
(backgroundCategories = categories),
}}
/>
</div>
{:else}
<div class="flex flex-col flex-1 min-w-0 min-h-0">
<div class="shrink-0 px-6 pt-5 pb-3">
<h1 class="text-3xl font-semibold tracking-tight text-zinc-900 dark:text-white">
{sectionTitle}
</h1>
</div>
<div class="flex-1 min-h-0 px-4 pb-8 overflow-y-auto no-scrollbar">
{#if activePage === "settings"}
{#if activeSection === "shortcuts" && !debouncedSettingsSearch.trim()}
<LazyPanel loader={loadShortcuts} remountKey="shortcuts-page" />
{:else}
<LazyPanel
loader={loadSettingsBody}
remountKey="settings-body"
props={{
...settingsSharedProps,
activeSection: debouncedSettingsSearch.trim() ? "all" : activeSection,
searchQuery: debouncedSettingsSearch,
}}
/>
{#if debouncedSettingsSearch.trim()}
<LazyPanel
loader={loadShortcuts}
remountKey="shortcuts-search"
props={{ searchQuery: debouncedSettingsSearch }}
/>
{/if}
{/if}
{:else if activePage === "themes"}
<div class="flex min-h-0 min-w-0 flex-1 overflow-hidden">
{#if isStoreView}
<div class="min-h-0 min-w-0 flex-1 overflow-hidden">
{#if activePage === "themes" && activeThemeView === "community-themes"}
<LazyPanel
loader={loadThemeSettings}
remountKey="theme-settings"
props={{ section: "themes" }}
loader={loadCommunityThemes}
remountKey="community-themes"
props={{
searchTerm: storeSearchTerm,
setSearchTerm: (term: string) => (storeSearchTerm = term),
}}
/>
{:else}
<LazyPanel
loader={loadThemeSettings}
remountKey="background-settings"
props={{ section: "backgrounds" }}
loader={loadStore}
remountKey="store"
props={{
activeTab: activePage as StoreTab,
searchTerm: storeSearchTerm,
selectedBackgroundCategory,
setActiveTab: (tab: StoreTab) => {
activePage = tab;
if (tab === "themes") activeThemeView = "theme-store";
else activeBackgroundView = "background-store";
},
setSearchTerm: (term: string) => (storeSearchTerm = term),
setBackgroundCategories: (categories: string[]) =>
(backgroundCategories = categories),
}}
/>
{/if}
</div>
</div>
{/if}
{:else}
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<div class="shrink-0 px-6 pt-5 pb-3">
<h1 class="text-3xl font-semibold tracking-tight text-zinc-900 dark:text-white">
{sectionTitle}
</h1>
</div>
<div class="min-h-0 flex-1 overflow-y-auto px-4 pb-8 no-scrollbar">
{#if activePage === "settings"}
{#if activeSection === "shortcuts" && !debouncedSettingsSearch.trim()}
<LazyPanel loader={loadShortcuts} remountKey="shortcuts-page" />
{:else}
<LazyPanel
loader={loadSettingsBody}
remountKey="settings-body"
props={{
...settingsSharedProps,
activeSection: debouncedSettingsSearch.trim() ? "all" : activeSection,
searchQuery: debouncedSettingsSearch,
}}
/>
{#if debouncedSettingsSearch.trim()}
<LazyPanel
loader={loadShortcuts}
remountKey="shortcuts-search"
props={{ searchQuery: debouncedSettingsSearch }}
/>
{/if}
{/if}
{:else if activePage === "themes"}
<LazyPanel
loader={loadThemeSettings}
remountKey={`theme-settings-${activeThemeListMode}`}
props={{ section: "themes", listMode: activeThemeListMode }}
/>
{:else}
<LazyPanel
loader={loadThemeSettings}
remountKey="background-settings"
props={{ section: "backgrounds" }}
/>
{/if}
</div>
</div>
{/if}
</div>
</div>
</div>
{/snippet}
@@ -655,7 +685,7 @@
></button>
<div
class="relative z-10 w-[min(1180px,96vw)] h-[min(860px,92vh)] no-scrollbar overflow-clip"
class="relative z-10 h-[min(860px,92vh)] w-[min(1180px,96vw)] no-scrollbar overflow-clip"
data-settings-panel
>
{@render settingsShell()}
@@ -7,7 +7,9 @@
import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/Openers/OpenThemeOfTheMonthPopup";
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync";
import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase";
import { getStoredOverride, PRODUCTION_API_BASE, setApiBase } from "@/seqta/utils/DevApiBase";
const isExtensionDevBuild = import.meta.env.DEV;
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
@@ -202,29 +204,38 @@
<div class="flex justify-between items-start gap-3">
<div class="pr-4">
<h2 class="text-xl font-bold">API Base URL (session only)</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
Override the content API host for this browser session. Cleared on restart. Affects
themes, theme of the month, and other server-driven content.
</p>
{#if devApiBaseActive}
<p class="text-xs mt-1 text-amber-600 dark:text-amber-400">
Override active: <span class="font-mono">{devApiBaseActive}</span>
{#if isExtensionDevBuild}
<p class="text-base text-zinc-600 dark:text-zinc-300">
Extension dev builds always use production ({PRODUCTION_API_BASE}) for the theme store,
community submit, and related APIs. Build a release package to test a staging host override.
</p>
{:else}
<p class="text-base text-zinc-600 dark:text-zinc-300">
Override the content API host for this browser session. Cleared on restart. Affects
themes, theme of the month, and other server-driven content.
</p>
{#if devApiBaseActive}
<p class="text-xs mt-1 text-amber-600 dark:text-amber-400">
Override active: <span class="font-mono">{devApiBaseActive}</span>
</p>
{/if}
{/if}
</div>
</div>
<div class="flex gap-2 items-center">
<input
type="text"
placeholder="https://betterseqta.org"
bind:value={devApiBaseInput}
class="flex-1 px-2 py-1 text-xs rounded border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100"
/>
<Button onClick={applyDevApiBase} text="Apply" />
{#if devApiBaseActive}
<Button onClick={clearDevApiBase} text="Clear" />
{/if}
</div>
{#if !isExtensionDevBuild}
<div class="flex gap-2 items-center">
<input
type="text"
placeholder="https://betterseqta.org"
bind:value={devApiBaseInput}
class="flex-1 px-2 py-1 text-xs rounded border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100"
/>
<Button onClick={applyDevApiBase} text="Apply" />
{#if devApiBaseActive}
<Button onClick={clearDevApiBase} text="Clear" />
{/if}
</div>
{/if}
</div>
<div class="flex flex-col gap-2 px-4 py-3">
<div>
+28 -9
View File
@@ -2,9 +2,11 @@
import BackgroundSelector from "@/interface/components/themes/BackgroundSelector.svelte"
import ThemeSelector from "@/interface/components/themes/ThemeSelector.svelte"
import { standalone } from "@/interface/utils/standalone.svelte"
import type { ThemeListMode } from "@/interface/utils/themeListFilters"
let { section = "all" } = $props<{
let { section = "all", listMode = "all" } = $props<{
section?: "all" | "themes" | "backgrounds";
listMode?: ThemeListMode;
}>();
// backgrounds
@@ -29,19 +31,36 @@
: clearTheme ? 'Clear Background' : 'No Background Selected'}
</button>
{/if}
<div class="relative w-full">
<button
onclick={() => editMode = !editMode}
class="absolute top-0 right-0 z-10 px-2 h-8 text-lg rounded-xl bg-zinc-100 dark:bg-zinc-700">
<span class="mr-2">{editMode ? 'Done' : 'Edit'}</span>
<span class="font-IconFamily">{editMode ? '\ue9e4' : '\uec38'}</span>
</button>
<div class="w-full">
{#if showThemes || showBackgrounds}
<div class="mb-3 flex justify-end">
<button
onclick={() => editMode = !editMode}
class="inline-flex h-8 items-center rounded-xl bg-zinc-100 px-3 text-lg dark:bg-zinc-700">
<span class="mr-2">{editMode ? 'Done' : 'Remove'}</span>
<span class="font-IconFamily">{editMode ? '\ue9e4' : '\uec38'}</span>
</button>
</div>
{/if}
{#if showBackgrounds}
<BackgroundSelector isEditMode={editMode} bind:selectedBackground={selectedBackground} bind:selectNoBackground={selectNoBackground} />
{/if}
{#if showThemes}
<ThemeSelector isEditMode={editMode} showNavigation={section === "all"} />
{#if listMode === "custom"}
<button
type="button"
class="mb-4 flex h-11 w-full items-center justify-center gap-2 rounded-xl bg-zinc-900 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
onclick={() =>
void import("@/seqta/utils/launchPageThemeBuilder").then(({ launchPageThemeBuilder }) =>
launchPageThemeBuilder(),
)}
>
<span class="font-IconFamily text-lg" aria-hidden="true">&#xec60;</span>
Open theme builder
</button>
{/if}
<ThemeSelector isEditMode={editMode} showNavigation={section === "all"} {listMode} />
{/if}
</div>
{:else}
+25 -2
View File
@@ -16,7 +16,7 @@
import Backgrounds from '../components/store/Backgrounds.svelte'
import { cloudAuth } from '@/seqta/utils/CloudAuth'
import SignInToFavoriteModal from '../components/SignInToFavoriteModal.svelte'
import { consumePendingHighlightThemeId } from '@/seqta/utils/openThemeStoreWithHighlight'
import { getStoreInstalledThemeIds } from '@/interface/utils/themeListFilters'
const themeManager = ThemeManager.getInstance();
type StoreTab = 'themes' | 'backgrounds';
@@ -53,6 +53,8 @@
let loading = $state(true);
let displayTheme = $state<Theme | null>(null);
let currentThemes = $state<string[]>([]);
let selectedThemeId = $state('');
let installedThemeColors = $state<Record<string, string>>({});
let error = $state<string | null>(null);
let fetchAttempt = $state(0);
@@ -73,7 +75,13 @@
const fetchCurrentThemes = async () => {
const themes = await themeManager.getAvailableThemes();
currentThemes = themes.filter(theme => theme !== null).map(theme => theme.id);
currentThemes = getStoreInstalledThemeIds(themes);
selectedThemeId = themeManager.getSelectedThemeId() || '';
installedThemeColors = Object.fromEntries(
themes
.filter((theme) => theme != null && theme.installedFromStore === true)
.map((theme) => [theme.id, theme.defaultColour]),
);
};
const setDisplayTheme = (theme: Theme | null) => {
@@ -174,6 +182,7 @@
// On mount
onMount(async () => {
window.addEventListener('bsplus:highlight-theme', onHighlightThemeEvent);
themeUpdates.addListener(fetchCurrentThemes);
const load = async () => {
await fetchThemes();
@@ -190,6 +199,7 @@
return () => {
window.removeEventListener('bsplus:highlight-theme', onHighlightThemeEvent);
themeUpdates.removeListener(fetchCurrentThemes);
};
});
@@ -226,6 +236,13 @@
await fetchCurrentThemes();
}
async function applyThemeFromStore(themeId: string) {
await themeManager.setTheme(themeId);
selectedThemeId = themeId;
themeUpdates.triggerUpdate();
void browser.runtime.sendMessage({ type: 'cloudSettingsRequestDebouncedUpload' }).catch(() => {});
}
$effect(() => {
loadBackground();
selectedBackground
@@ -294,6 +311,7 @@
{toggleFavorite}
isLoggedIn={cloudLoggedIn}
onRequestSignIn={() => (showSignInOverlay = true)}
installedThemeIds={currentThemes}
/>
{#if displayTheme}
@@ -307,6 +325,8 @@
{toggleFavorite}
isLoggedIn={cloudLoggedIn}
onRequestSignIn={() => (showSignInOverlay = true)}
{selectedThemeId}
{installedThemeColors}
onInstall={async (themeId: string) => {
if (displayTheme) await installThemeFromStore(themeId, displayTheme);
}}
@@ -314,6 +334,9 @@
console.debug('deleting theme', themeId);
await removeThemeFromStore(themeId);
}}
onApply={async (themeId: string) => {
await applyThemeFromStore(themeId);
}}
/>
{/if}
{:else if activeTab === 'backgrounds'}
+375 -88
View File
@@ -21,14 +21,28 @@
handleImageUpload,
handleRemoveImage,
handleImageVariableChange,
handleCoverImageUpload
} from '../utils/themeImageHandlers';
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
import { themeUpdates } from '../hooks/ThemeUpdates'
import { CloseThemeCreator } from '@/plugins/built-in/themes/ThemeCreator'
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
import { submitLocalThemeToCommunity } from '@/seqta/utils/customThemes/submitLocalTheme'
import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors'
import { cloudAuth } from '@/seqta/utils/CloudAuth'
import LucideMoon from '@/interface/components/icons/LucideMoon.svelte'
import LucideSun from '@/interface/components/icons/LucideSun.svelte'
import SidebarAppearance from '@/interface/components/SidebarAppearance.svelte'
import { FONT_PRESETS, DEFAULT_FONT_ID } from '@/seqta/ui/fonts/presets'
import { applySelectedFont, ensureFontPickerFontsLoaded } from '@/seqta/ui/fonts/Manager'
import {
applySidebarSettings,
defaultThemeCreatorMeta,
mergeThemeWithCreatorMeta,
snapshotSidebarSettings,
type ThemeCreatorSidebarMeta,
} from '@/interface/utils/themeCreatorMeta'
import { ensureThemeCoverImage } from '@/interface/utils/themePlaceholderCover'
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
import type { ThemeCreatorMeta } from '@/types/CustomThemes'
const { themeID } = $props<{ themeID: string }>()
const themeManager = ThemeManager.getInstance();
@@ -52,7 +66,73 @@
let closedAccordions = $state<string[]>([])
let themeLoaded = $state(false);
let codeEditorFullscreen = $state(false);
let communityBusy = $state(false);
let communityError = $state<string | null>(null);
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
let panelDark = $state(Boolean(settingsState.DarkMode));
let creatorMeta = $state<ThemeCreatorMeta>(defaultThemeCreatorMeta());
let originalSidebar = $state<ThemeCreatorSidebarMeta | null>(null);
let originalFontId = $state<string | null>(null);
/** When true, generated font/background CSS is merged for live preview and save. */
let composeVisuals = $state(false);
const previewTheme = $derived.by(() => {
if (!themeLoaded) return null;
if (composeVisuals || theme.creatorMeta || creatorMeta.pageBackgroundImageId) {
return mergeThemeWithCreatorMeta(theme, creatorMeta);
}
return { ...theme, creatorMeta };
});
function touchVisuals() {
if (!composeVisuals && !theme.creatorMeta && !creatorMeta.userCustomCss.trim()) {
creatorMeta = { ...creatorMeta, userCustomCss: theme.CustomCSS };
}
composeVisuals = true;
}
function imageUsage(imageId: string): 'decorative' | 'page-background' | 'cover' {
if (creatorMeta.pageBackgroundImageId === imageId) return 'page-background';
const image = theme.CustomImages.find((item) => item.id === imageId);
if (image && theme.coverImage === image.blob) return 'cover';
return 'decorative';
}
function setImageUsage(imageId: string, usage: 'decorative' | 'page-background' | 'cover') {
const image = theme.CustomImages.find((item) => item.id === imageId);
if (!image) return;
let nextMeta = { ...creatorMeta };
let coverImage = theme.coverImage;
if (usage === 'page-background') {
nextMeta = { ...nextMeta, pageBackgroundImageId: imageId };
} else if (nextMeta.pageBackgroundImageId === imageId) {
nextMeta = { ...nextMeta, pageBackgroundImageId: null };
}
if (usage === 'cover') {
coverImage = image.blob;
} else if (coverImage === image.blob) {
coverImage = null;
}
creatorMeta = nextMeta;
theme = { ...theme, coverImage };
touchVisuals();
}
function onFontIdChange(fontId: string) {
creatorMeta = { ...creatorMeta, fontId };
applySelectedFont(fontId);
touchVisuals();
}
function patchCreatorMeta(patch: Partial<ThemeCreatorMeta>) {
creatorMeta = { ...creatorMeta, ...patch };
touchVisuals();
}
function toggleCodeEditorFullscreen(e: MouseEvent) {
e.preventDefault();
codeEditorFullscreen = !codeEditorFullscreen;
@@ -71,8 +151,38 @@
}
}
async function prepareThemeClone() {
const themeClone = JSON.parse(JSON.stringify(theme)) as LoadedCustomTheme;
themeClone.CustomImages = theme.CustomImages.map((image) => ({
...image,
blob: image.blob,
}));
themeClone.coverImage = theme.coverImage;
themeClone.userEdited = true;
if (shouldForceThemeAppearance(themeClone)) {
themeClone.forceTheme = true;
} else {
themeClone.forceTheme = false;
themeClone.forceDark = undefined;
}
const merged = mergeThemeWithCreatorMeta(themeClone, creatorMeta);
return await ensureThemeCoverImage(merged);
}
onMount(async () => {
await themeManager.disableTheme();
const unsubCloud = cloudAuth.subscribe((s) => {
cloudLoggedIn = s.isLoggedIn;
});
const unsubSettings = settingsState.subscribe((s) => {
panelDark = s.DarkMode;
});
void ensureFontPickerFontsLoaded();
originalSidebar = snapshotSidebarSettings();
originalFontId = settingsState.selectedFont ?? DEFAULT_FONT_ID;
if (themeID) {
const tempTheme = await themeManager.getTheme(themeID);
@@ -85,59 +195,93 @@
tempTheme.forceTheme ??
(tempTheme.forceDark !== undefined ? true : undefined),
};
themeLoaded = true;
} else {
themeLoaded = true
}
if (theme.creatorMeta) {
creatorMeta = { ...defaultThemeCreatorMeta(), ...theme.creatorMeta };
applySidebarSettings(theme.creatorMeta.sidebar);
composeVisuals = true;
} else {
creatorMeta = defaultThemeCreatorMeta({
userCustomCss: theme.CustomCSS,
fontId: settingsState.selectedFont ?? DEFAULT_FONT_ID,
});
}
applySelectedFont(creatorMeta.fontId);
themeLoaded = true;
themeUpdates.triggerUpdate();
return () => {
unsubCloud();
unsubSettings();
if (originalSidebar) applySidebarSettings(originalSidebar);
if (originalFontId) applySelectedFont(originalFontId);
};
});
async function onImageUpload(event: Event) {
theme = await handleImageUpload(event, theme);
const updated = await handleImageUpload(event, theme);
if (updated === theme) return;
theme = updated as LoadedCustomTheme;
if (!creatorMeta.pageBackgroundImageId && theme.CustomImages.length === 1) {
creatorMeta = { ...creatorMeta, pageBackgroundImageId: theme.CustomImages[0].id };
}
touchVisuals();
}
function onRemoveImage(imageId: string) {
if (creatorMeta.pageBackgroundImageId === imageId) {
creatorMeta = { ...creatorMeta, pageBackgroundImageId: null };
}
theme = handleRemoveImage(imageId, theme);
touchVisuals();
}
function onImageVariableChange(imageId: string, variableName: string) {
theme = handleImageVariableChange(imageId, variableName, theme);
}
async function onCoverImageUpload(event: Event) {
theme = await handleCoverImageUpload(event, theme);
touchVisuals();
}
async function submitTheme() {
const themeClone = JSON.parse(JSON.stringify(theme));
const themeClone = await prepareThemeClone();
// re-insert blobs into themeClone
themeClone.CustomImages = theme.CustomImages.map((image) => ({
...image,
blob: image.blob
}))
themeClone.coverImage = theme.coverImage
themeClone.userEdited = true
if (shouldForceThemeAppearance(themeClone)) {
themeClone.forceTheme = true;
} else {
themeClone.forceTheme = false;
themeClone.forceDark = undefined;
}
themeManager.clearPreview();
await themeManager.saveTheme(themeClone);
await themeManager.setTheme(themeClone.id);
themeUpdates.triggerUpdate();
CloseThemeCreator();
await CloseThemeCreator({ restoreTheme: false });
}
async function submitThemeToCommunity() {
communityError = null;
if (!cloudLoggedIn) {
communityError = "Sign in with BetterSEQTA Cloud to submit themes.";
return;
}
if (!theme.name.trim()) {
communityError = "Add a theme name before submitting.";
return;
}
communityBusy = true;
try {
const themeClone = await prepareThemeClone();
await themeManager.saveTheme(themeClone);
await themeManager.setTheme(themeClone.id);
await submitLocalThemeToCommunity(themeClone, theme.description?.trim() || undefined);
themeUpdates.triggerUpdate();
await CloseThemeCreator({ restoreTheme: false });
} catch (err) {
communityError = formatCustomThemeApiError(err);
} finally {
communityBusy = false;
}
}
$effect(() => {
if (themeLoaded) {
void themeManager.updatePreviewDebounced(theme);
}
const snapshot = previewTheme;
if (!snapshot) return;
void themeManager.updatePreviewDebounced(snapshot);
});
type SettingType = 'switch' | 'button' | 'slider' | 'colourPicker' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle';
@@ -221,20 +365,35 @@
{/if}
{:else if item.type === 'imageUpload'}
{#each theme.CustomImages as image (image.id)}
<div class="flex gap-2 items-center px-2 py-2 mb-4 h-16 bg-white rounded-lg shadow-lg dark:bg-zinc-700">
<div class="h-full">
<ThemeBlobImage source={image.blob} alt={image.variableName} class="object-contain h-full rounded" />
<div class="mb-4 space-y-2 rounded-lg bg-white px-2 py-2 shadow-lg dark:bg-zinc-700">
<div class="flex h-16 items-center gap-2">
<div class="h-full">
<ThemeBlobImage source={image.blob} alt={image.variableName} class="object-contain h-full rounded" />
</div>
<input
type="text"
value={image.variableName}
oninput={(e) => onImageVariableChange(image.id, e.currentTarget.value)}
placeholder="CSS variable name"
class="grow flex-3 rounded-lg border-0 bg-zinc-200 p-2 transition dark:bg-zinc-600/50 dark:placeholder-zinc-300 focus:bg-zinc-300/50 dark:focus:bg-zinc-600"
/>
<button onclick={() => onRemoveImage(image.id)} class="p-2 transition dark:text-white" type="button">
<span class='text-xl font-IconFamily'>{'\ued8c'}</span>
</button>
</div>
<input
type="text"
bind:value={image.variableName}
oninput={(e) => onImageVariableChange(image.id, e.currentTarget.value)}
placeholder="CSS Variable Name"
class="p-2 w-full rounded-lg border-0 transition grow flex-3 dark:placeholder-zinc-300 bg-zinc-200 dark:bg-zinc-600/50 focus:bg-zinc-300/50 dark:focus:bg-zinc-600"
/>
<button onclick={() => onRemoveImage(image.id)} class="p-2 transition dark:text-white">
<span class='text-xl font-IconFamily'>{'\ued8c'}</span>
</button>
<label class="block text-xs text-zinc-600 dark:text-zinc-300">
Use as
<select
class="mt-1 w-full rounded-lg border-0 bg-zinc-200 px-2 py-1.5 text-sm dark:bg-zinc-600"
value={imageUsage(image.id)}
onchange={(e) =>
setImageUsage(image.id, e.currentTarget.value as 'decorative' | 'page-background' | 'cover')}
>
<option value="decorative">Decorative (CSS variable only)</option>
<option value="page-background">SEQTA page background</option>
<option value="cover">Theme store cover image</option>
</select>
</label>
</div>
{/each}
@@ -270,7 +429,7 @@
{/if}
{/snippet}
<div class='h-screen overflow-y-scroll {$settingsState.DarkMode && "dark"} no-scrollbar'>
<div class:dark={panelDark} class="h-full min-h-0 overflow-y-scroll no-scrollbar">
{#if codeEditorFullscreen}
<div class="absolute inset-0 bg-white z-[10000] dark:bg-zinc-900 dark:text-white">
<div class="sticky top-0 px-2 h-screen">
@@ -278,14 +437,27 @@
<h2 class="text-xl font-bold">Custom CSS</h2>
<button onclick={toggleCodeEditorFullscreen} class="pr-14 text-xl font-IconFamily">{'\uec06'}</button>
</div>
<CodeEditor className="editorHeight" value={theme.CustomCSS} onChange={(value: string) => { theme = { ...theme, CustomCSS: value } }} />
<CodeEditor
className="editorHeight"
value={creatorMeta.userCustomCss}
onChange={(value: string) => patchCreatorMeta({ userCustomCss: value })}
/>
</div>
</div>
{/if}
<div class='flex relative flex-col p-2 w-full min-h-screen bg-zinc-100 dark:bg-zinc-800 dark:text-white'>
<div class="relative flex min-h-full w-full flex-col bg-zinc-100 p-2 text-zinc-900 dark:bg-zinc-800 dark:text-white">
<h1 class='text-xl font-semibold'>Theme Creator</h1>
<div class="mb-2 flex items-start justify-between gap-2">
<h1 class="text-xl font-semibold">Theme Creator</h1>
<button
type="button"
class="rounded-lg p-2 text-zinc-500 transition hover:bg-zinc-200 dark:hover:bg-zinc-700"
aria-label="Close theme creator"
onclick={() => void CloseThemeCreator()}
>
✕
</button>
</div>
<a href='https://docs.betterseqta.org/theme-creation/' target='_blank' rel='noopener noreferrer' class='text-sm font-light text-zinc-500 dark:text-zinc-400'>
<span class='pr-0.5 no-underline font-IconFamily'>{'\ueb44'}</span>
<span class='underline'>
@@ -316,19 +488,122 @@
<Divider />
<div class="flex overflow-hidden relative gap-1 justify-center place-items-center w-full rounded-lg transition aspect-theme group bg-zinc-200 dark:bg-zinc-700">
<div class={`transition pointer-events-none z-30 font-IconFamily ${ theme.coverImage ? 'opacity-0 group-hover:opacity-100' : ''}`}>
{'\uec60'}
<div class="py-3">
<h2 class="text-sm font-bold">Accent colour</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-400">Default accent and gradient start colour.</p>
<div class="mt-2">
<ColourPicker
savePresets={false}
standalone={true}
customState={theme.defaultColour}
customOnChange={(color: string) => {
theme = { ...theme, defaultColour: color };
touchVisuals();
}}
/>
</div>
<span class={`dark:text-white pointer-events-none z-30 transition ${ theme.coverImage ? 'opacity-0 group-hover:opacity-100' : ''}`}>{theme.coverImage ? 'Change' : 'Add'} cover image</span>
<input type="file" accept='image/*' onchange={onCoverImageUpload} class="absolute inset-0 z-10 w-full h-full opacity-0 cursor-pointer" />
{#if !theme.hideThemeName && theme.coverImage}
<div class="absolute z-30 opacity-100 transition-opacity pointer-events-none group-hover:opacity-0">{theme.name}</div>
{/if}
{#if theme.coverImage}
<div class="absolute z-20 w-full h-full opacity-0 transition-opacity pointer-events-none group-hover:opacity-100 bg-black/20"></div>
<ThemeBlobImage source={theme.coverImage} alt="Cover" class="object-cover absolute z-0 w-full h-full rounded" />
{/if}
</div>
<Divider />
<div class="py-3">
<h2 class="text-sm font-bold">Interface font</h2>
<select
class="mt-2 w-full rounded-lg border-0 bg-zinc-200 p-2 text-sm dark:bg-zinc-700"
value={creatorMeta.fontId}
onchange={(e) => onFontIdChange(e.currentTarget.value)}
>
{#each FONT_PRESETS as preset (preset.id)}
<option value={preset.id}>{preset.name}</option>
{/each}
</select>
</div>
<Divider />
<div class="py-3 space-y-3">
<div>
<h2 class="text-sm font-bold">Images &amp; page background</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-400">
Upload images, then choose how each one is used. Set one as the live SEQTA page background to preview it on the main page.
</p>
</div>
{#each theme.CustomImages as image (image.id)}
<div class="space-y-2 rounded-lg bg-zinc-200/80 px-2 py-2 dark:bg-zinc-700/80">
<div class="flex h-16 items-center gap-2">
<ThemeBlobImage source={image.blob} alt="" class="h-full rounded object-contain" />
<input
type="text"
value={image.variableName}
oninput={(e) => onImageVariableChange(image.id, e.currentTarget.value)}
placeholder="CSS variable"
class="min-w-0 flex-1 rounded-lg border-0 bg-zinc-100 p-2 text-sm dark:bg-zinc-600 dark:text-white"
/>
<button type="button" class="p-2 dark:text-white" onclick={() => onRemoveImage(image.id)}>
<span class="text-xl font-IconFamily">{'\ued8c'}</span>
</button>
</div>
<select
class="w-full rounded-lg border-0 bg-zinc-100 px-2 py-1.5 text-sm dark:bg-zinc-600"
value={imageUsage(image.id)}
onchange={(e) =>
setImageUsage(image.id, e.currentTarget.value as 'decorative' | 'page-background' | 'cover')}
>
<option value="decorative">Decorative only (CSS variable)</option>
<option value="page-background">SEQTA page background</option>
<option value="cover">Theme store cover</option>
</select>
</div>
{/each}
<label class="flex h-10 cursor-pointer items-center justify-center gap-2 rounded-lg bg-zinc-200 dark:bg-zinc-700">
<span class="font-IconFamily">{'\uec60'}</span>
<span class="text-sm dark:text-white">Add image</span>
<input type="file" accept="image/*" class="hidden" onchange={onImageUpload} />
</label>
<label class="block text-sm">
Gradient end
<div class="mt-1">
<ColourPicker
savePresets={false}
standalone={true}
customState={creatorMeta.gradientEnd || theme.defaultColour}
customOnChange={(color: string) => patchCreatorMeta({ gradientEnd: color })}
/>
</div>
</label>
<label class="block text-sm">
Gradient angle ({creatorMeta.gradientAngle}°)
<Slider
state={creatorMeta.gradientAngle}
min={0}
max={360}
step={1}
onChange={(value) => patchCreatorMeta({ gradientAngle: value })}
/>
</label>
<label class="block text-sm">
Colour overlay ({Math.round(creatorMeta.overlayOpacity * 100)}%)
<Slider
state={creatorMeta.overlayOpacity}
min={0}
max={0.85}
step={0.05}
onChange={(value) => patchCreatorMeta({ overlayOpacity: value })}
/>
</label>
<label class="block text-sm">
Background blur ({creatorMeta.backgroundBlurPx}px)
<Slider
state={creatorMeta.backgroundBlurPx}
min={0}
max={24}
step={1}
onChange={(value) => patchCreatorMeta({ backgroundBlurPx: value })}
/>
</label>
</div>
<Divider />
@@ -354,6 +629,12 @@
<Divider />
<div class="theme-creator-sidebar -mx-2">
<SidebarAppearance />
</div>
<Divider />
{#each [
{
type: 'switch',
@@ -395,40 +676,46 @@
}
}
},
{
type: 'colourPicker',
title: 'Default Theme Colour',
description: 'Set the default color for your theme',
direction: 'vertical',
props: {
customState: theme.defaultColour,
customOnChange: (color: string) => theme = { ...theme, defaultColour: color }
}
},
{
type: 'imageUpload',
title: 'Custom Images',
description: 'Add custom images to your theme',
direction: 'vertical',
},
{
type: 'codeEditor',
title: 'Custom CSS',
description: 'Add custom CSS to your theme',
description: 'Extra CSS appended after generated theme rules',
direction: 'vertical',
props: {
value: theme.CustomCSS,
onChange: (value: string) => { theme = { ...theme, CustomCSS: value } }
value: creatorMeta.userCustomCss,
onChange: (value: string) => patchCreatorMeta({ userCustomCss: value })
}
}
] as SettingItem[] as setting}
{@render settingItem(setting)}
{/each}
<button
onclick={submitTheme}
class="w-full px-4 py-2 mt-3 text-[13px] dark:text-white transition rounded-xl bg-zinc-200 dark:bg-zinc-700/50">
Save Theme
</button>
<div
class="sticky bottom-0 z-10 -mx-2 mt-4 space-y-2 border-t border-zinc-200/80 bg-zinc-100 p-3 pb-4 dark:border-zinc-700/60 dark:bg-zinc-800"
>
<button
type="button"
onclick={submitTheme}
class="w-full rounded-xl bg-zinc-900 px-4 py-3 text-[13px] font-medium text-white transition hover:bg-zinc-700 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white"
>
Save & apply
</button>
<button
type="button"
disabled={communityBusy || !theme.name.trim() || !cloudLoggedIn}
onclick={() => void submitThemeToCommunity()}
class="w-full rounded-xl bg-zinc-200 px-4 py-3 text-[13px] font-medium text-zinc-900 transition hover:bg-zinc-300 disabled:opacity-50 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600"
>
{communityBusy ? "Submitting…" : "Save & submit to community"}
</button>
{#if !cloudLoggedIn}
<p class="text-xs text-zinc-500 dark:text-zinc-400">
Sign in with BetterSEQTA Cloud to submit themes to the community library.
</p>
{/if}
{#if communityError}
<p class="whitespace-pre-line text-sm text-red-600 dark:text-red-400">{communityError}</p>
{/if}
</div>
</div>
</div>
@@ -0,0 +1,37 @@
import { buildSimpleTheme } from "./buildSimpleTheme";
import { buildThemeBuilderCss } from "./themeBuilderDraft";
import { getFontPreset } from "@/seqta/ui/fonts/presets";
describe("buildSimpleTheme", () => {
it("builds CSS with font import and image variables", () => {
const css = buildThemeBuilderCss(
getFontPreset("inter"),
["theme-bg-0"],
{ accentColor: "#00f", gradientEnd: "#f0f" },
);
expect(css).toContain("Inter");
expect(css).toContain("var(--theme-bg-0)");
expect(css).toContain("#title");
});
it("creates a theme with photos as custom image variables", () => {
const theme = buildSimpleTheme({
name: "Sunset",
accentColor: "#ff6600",
fontId: "rubik",
photoBlobs: [new Blob(["x"], { type: "image/png" })],
});
expect(theme.name).toBe("Sunset");
expect(theme.defaultColour).toBe("#ff6600");
expect(theme.CustomImages).toHaveLength(1);
expect(theme.CustomImages[0].variableName).toBe("theme-bg-0");
expect(theme.coverImage).toBeTruthy();
expect(theme.hideThemeName).toBe(true);
});
it("requires a name", () => {
expect(() =>
buildSimpleTheme({ name: " ", accentColor: "#000", photoBlobs: [] }),
).toThrow("Theme name is required");
});
});
+11
View File
@@ -0,0 +1,11 @@
import type { LoadedCustomTheme } from "@/types/CustomThemes";
import { buildThemeFromDraft, type ThemeBuilderDraft } from "./themeBuilderDraft";
export type SimpleThemeInput = ThemeBuilderDraft;
export { buildThemeBuilderCss as buildSimpleThemeCss } from "./themeBuilderDraft";
/** @deprecated Use buildThemeFromDraft */
export function buildSimpleTheme(input: SimpleThemeInput): LoadedCustomTheme {
return buildThemeFromDraft(input);
}
+138
View File
@@ -0,0 +1,138 @@
import { generateImageId } from "@/interface/utils/themeImageHandlers";
import { DEFAULT_FONT_ID, getFontPreset, type FontPreset } from "@/seqta/ui/fonts/presets";
import type { LoadedCustomTheme } from "@/types/CustomThemes";
export type ThemeBuilderDraft = {
name: string;
description?: string;
accentColor: string;
gradientEnd?: string;
gradientAngle?: number;
backgroundBlurPx?: number;
overlayOpacity?: number;
fontId?: string;
photoBlobs: Blob[];
customCssExtra?: string;
themeId?: string;
};
/** Keep the BetterSEQTA title bar opaque (generated themes must not use the old transparent #title hack). */
const TITLEBAR_SOLID = `#title {
background: var(--background-primary) !important;
}`;
function clamp(n: number, min: number, max: number): number {
return Math.min(max, Math.max(min, n));
}
export function buildThemeBuilderCss(
font: FontPreset,
imageVariables: string[],
draft: Pick<
ThemeBuilderDraft,
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity"
>,
): string {
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
const angle = draft.gradientAngle ?? 135;
const overlay = clamp(draft.overlayOpacity ?? 0.35, 0, 0.85);
const blurPx = clamp(draft.backgroundBlurPx ?? 0, 0, 24);
const endColor = (draft.gradientEnd ?? draft.accentColor).trim();
const rules: string[] = [
`${importLine}body, #container, .dashboard {
font-family: ${font.stack} !important;
}`,
];
const imageLayer =
imageVariables.length > 0
? imageVariables.map((name) => `var(--${name})`).join(", ")
: "";
const gradientLayer = `linear-gradient(${angle}deg, color-mix(in srgb, ${draft.accentColor} ${Math.round(overlay * 100)}%, transparent), color-mix(in srgb, ${endColor} ${Math.round(overlay * 100)}%, transparent))`;
rules.push(`#container {
isolation: isolate;
position: relative;
}`);
if (imageLayer && blurPx > 0) {
rules.push(`#container::after {
content: "";
position: fixed;
inset: 0;
z-index: -2;
pointer-events: none;
background-image: ${imageLayer};
background-size: cover;
background-position: center;
background-attachment: fixed;
filter: blur(${blurPx}px);
transform: scale(1.04);
}`);
rules.push(`#container {
background-image: ${gradientLayer} !important;
background-size: cover !important;
background-position: center !important;
background-attachment: fixed !important;
}`);
} else {
const bgLayers: string[] = [];
if (imageLayer) bgLayers.push(imageLayer);
bgLayers.push(gradientLayer);
rules.push(`#container {
background-image: ${bgLayers.join(", ")} !important;
background-size: cover !important;
background-position: center !important;
background-attachment: fixed !important;
}`);
}
rules.push(`#container::before {
display: none !important;
content: none !important;
backdrop-filter: none !important;
-webkit-backdrop-filter: none !important;
}`);
if (!imageLayer || blurPx === 0) {
rules.push(`#container::after {
display: none !important;
content: none !important;
filter: none !important;
}`);
}
rules.push(TITLEBAR_SOLID);
const extra = draft.customCssExtra?.trim();
if (extra) rules.push(extra);
return rules.join("\n\n");
}
export function buildThemeFromDraft(draft: ThemeBuilderDraft): LoadedCustomTheme {
const name = draft.name.trim();
if (!name) throw new Error("Theme name is required");
const font = getFontPreset(draft.fontId ?? DEFAULT_FONT_ID);
const photoBlobs = draft.photoBlobs.filter((blob) => blob.size > 0);
const CustomImages = photoBlobs.map((blob, index) => ({
id: generateImageId(),
blob,
variableName: `theme-bg-${index}`,
}));
return {
id: draft.themeId ?? crypto.randomUUID(),
name,
description: (draft.description ?? "").trim(),
defaultColour: draft.accentColor.trim() || "rgba(0, 123, 255, 1)",
CanChangeColour: true,
allowBackgrounds: true,
CustomCSS: buildThemeBuilderCss(font, CustomImages.map((i) => i.variableName), draft),
CustomImages,
coverImage: photoBlobs[0] ?? null,
isEditable: true,
hideThemeName: Boolean(photoBlobs[0]),
adaptiveCssVariables: [],
};
}
+104
View File
@@ -0,0 +1,104 @@
import { buildThemeBuilderCss } from "@/interface/utils/themeBuilderDraft";
import { applySelectedFont } from "@/seqta/ui/fonts/Manager";
import { DEFAULT_FONT_ID, getFontPreset } from "@/seqta/ui/fonts/presets";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import type { LoadedCustomTheme, ThemeCreatorMeta } from "@/types/CustomThemes";
export type ThemeCreatorSidebarMeta = {
sidebarStyle?: string;
sidebarDensity?: string;
sidebarCornerRadius?: number;
sidebarActiveIndicator?: string;
sidebarWidth?: string;
sidebarPosition?: string;
sidebarBlur?: number;
transparencyEffects?: boolean;
};
export function defaultThemeCreatorMeta(
overrides: Partial<ThemeCreatorMeta> = {},
): ThemeCreatorMeta {
return {
fontId: settingsState.selectedFont ?? DEFAULT_FONT_ID,
pageBackgroundImageId: null,
backgroundBlurPx: 0,
overlayOpacity: 0.35,
gradientAngle: 135,
gradientEnd: "",
userCustomCss: "",
...overrides,
};
}
export function snapshotSidebarSettings(): ThemeCreatorSidebarMeta {
return {
sidebarStyle: settingsState.sidebarStyle,
sidebarDensity: settingsState.sidebarDensity,
sidebarCornerRadius: settingsState.sidebarCornerRadius,
sidebarActiveIndicator: settingsState.sidebarActiveIndicator,
sidebarWidth: settingsState.sidebarWidth,
sidebarPosition: settingsState.sidebarPosition,
sidebarBlur: settingsState.sidebarBlur,
transparencyEffects: settingsState.transparencyEffects,
};
}
export function applySidebarSettings(meta: ThemeCreatorSidebarMeta | undefined): void {
if (!meta) return;
if (meta.sidebarStyle !== undefined) settingsState.sidebarStyle = meta.sidebarStyle;
if (meta.sidebarDensity !== undefined) settingsState.sidebarDensity = meta.sidebarDensity;
if (meta.sidebarCornerRadius !== undefined) {
settingsState.sidebarCornerRadius = meta.sidebarCornerRadius;
}
if (meta.sidebarActiveIndicator !== undefined) {
settingsState.sidebarActiveIndicator = meta.sidebarActiveIndicator;
}
if (meta.sidebarWidth !== undefined) settingsState.sidebarWidth = meta.sidebarWidth;
if (meta.sidebarPosition !== undefined) settingsState.sidebarPosition = meta.sidebarPosition;
if (meta.sidebarBlur !== undefined) settingsState.sidebarBlur = meta.sidebarBlur;
if (meta.transparencyEffects !== undefined) {
settingsState.transparencyEffects = meta.transparencyEffects;
}
}
export function composeThemeCustomCss(
theme: Pick<LoadedCustomTheme, "defaultColour" | "CustomImages">,
meta: ThemeCreatorMeta,
): string {
const font = getFontPreset(meta.fontId ?? DEFAULT_FONT_ID);
const backgroundVariables: string[] = [];
if (meta.pageBackgroundImageId) {
const image = theme.CustomImages.find((item) => item.id === meta.pageBackgroundImageId);
if (image?.variableName) backgroundVariables.push(image.variableName);
}
const gradientEnd = (meta.gradientEnd || theme.defaultColour).trim();
return buildThemeBuilderCss(font, backgroundVariables, {
accentColor: theme.defaultColour,
gradientEnd,
gradientAngle: meta.gradientAngle ?? 135,
backgroundBlurPx: meta.backgroundBlurPx ?? 0,
overlayOpacity: meta.overlayOpacity ?? 0.35,
customCssExtra: meta.userCustomCss ?? "",
});
}
export function applyThemeCreatorMetaToSettings(meta: ThemeCreatorMeta | undefined): void {
if (!meta) return;
if (meta.fontId) {
settingsState.selectedFont = meta.fontId;
applySelectedFont(meta.fontId);
}
applySidebarSettings(meta.sidebar);
}
export function mergeThemeWithCreatorMeta(
theme: LoadedCustomTheme,
meta: ThemeCreatorMeta,
): LoadedCustomTheme {
const sidebar = snapshotSidebarSettings();
const mergedMeta: ThemeCreatorMeta = { ...meta, sidebar };
const CustomCSS = composeThemeCustomCss(theme, mergedMeta);
return { ...theme, creatorMeta: mergedMeta, CustomCSS };
}
@@ -0,0 +1,123 @@
import type { CustomTheme } from '@/types/CustomThemes';
import type { Theme } from '@/interface/types/Theme';
import {
filterThemesByMode,
getThemeApplyButtonStyles,
getCommunityInstalledThemeIds,
getStoreInstalledThemeIds,
isStoreThemeInstalled,
resolveLocalThemeInstallId,
resolveStoreVariantAccentColor,
} from './themeListFilters';
function makeCustomTheme(overrides: Partial<CustomTheme> & Pick<CustomTheme, 'id' | 'name'>): CustomTheme {
return {
description: '',
defaultColour: '#000000',
CanChangeColour: true,
allowBackgrounds: true,
CustomCSS: '',
CustomImages: [],
coverImage: null,
isEditable: false,
hideThemeName: false,
...overrides,
};
}
function makeStoreTheme(overrides: Partial<Theme> & Pick<Theme, 'id' | 'name'>): Theme {
return {
description: '',
coverImage: '',
...overrides,
};
}
describe('resolveLocalThemeInstallId', () => {
it('keeps store ids and forks local imports that collide with store copies', () => {
expect(resolveLocalThemeInstallId('theme-1', null, true, false)).toBe('theme-1');
const forked = resolveLocalThemeInstallId(
'theme-1',
makeCustomTheme({ id: 'theme-1', name: 'Store', installedFromStore: true }),
false,
false,
);
expect(forked).not.toBe('theme-1');
expect(
resolveLocalThemeInstallId(
'theme-1',
makeCustomTheme({ id: 'theme-1', name: 'Local' }),
false,
false,
),
).toBe('theme-1');
});
});
describe('filterThemesByMode', () => {
const storeTheme = makeCustomTheme({
id: 'store-1',
name: 'Store Theme',
installedFromStore: true,
});
const communityTheme = makeCustomTheme({
id: 'community-1',
name: 'Community Theme',
installedFromCommunity: true,
});
const localTheme = makeCustomTheme({ id: 'local-1', name: 'Local Theme' });
it('splits store, community, and local themes by mode', () => {
const all = [storeTheme, communityTheme, localTheme];
expect(filterThemesByMode(all, 'all')).toEqual(all);
expect(filterThemesByMode(all, 'downloaded')).toEqual([storeTheme, communityTheme]);
expect(filterThemesByMode(all, 'custom')).toEqual([localTheme]);
});
});
describe('installed theme id helpers', () => {
it('returns store-only and community-only ids', () => {
const themes = [
makeCustomTheme({ id: 'store-1', name: 'Store', installedFromStore: true }),
makeCustomTheme({ id: 'community-1', name: 'Community', installedFromCommunity: true }),
makeCustomTheme({ id: 'local-1', name: 'Local' }),
];
expect(getStoreInstalledThemeIds(themes)).toEqual(['store-1']);
expect(getCommunityInstalledThemeIds(themes)).toEqual(['community-1']);
});
});
describe('isStoreThemeInstalled', () => {
it('matches master or flavour ids', () => {
const theme = makeStoreTheme({
id: 'master-1',
name: 'Master',
flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#000', cover_image: '' }],
});
expect(isStoreThemeInstalled(theme, ['master-1'])).toBe(true);
expect(isStoreThemeInstalled(theme, ['flavour-1'])).toBe(true);
expect(isStoreThemeInstalled(theme, ['other'])).toBe(false);
});
});
describe('resolveStoreVariantAccentColor', () => {
it('prefers installed colours then flavour accents', () => {
const theme = makeStoreTheme({
id: 'master-1',
name: 'Master',
flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#112233', cover_image: '' }],
});
expect(resolveStoreVariantAccentColor(theme, 'flavour-1', { 'flavour-1': '#ff0000' })).toBe(
'#ff0000',
);
expect(resolveStoreVariantAccentColor(theme, 'flavour-1')).toBe('#112233');
});
});
describe('getThemeApplyButtonStyles', () => {
it('derives apply and applied styles from the accent colour', () => {
const styles = getThemeApplyButtonStyles('#ff0000');
expect(styles.apply).toContain('background-color: #FF0000');
expect(styles.applied).toContain('color: #FF0000');
});
});
+95
View File
@@ -0,0 +1,95 @@
import type { CustomTheme } from '@/types/CustomThemes';
import type { Theme } from '@/interface/types/Theme';
import { parseCssColor } from '@/seqta/ui/colors/parseCssColor';
export type ThemeListMode = 'downloaded' | 'custom' | 'all';
const DEFAULT_THEME_ACCENT = 'rgba(0, 123, 255, 1)';
/** Local themes: created in the editor or imported from a file (not store/community). */
export function isLocalCustomTheme(theme: CustomTheme): boolean {
return theme.installedFromStore !== true && theme.installedFromCommunity !== true;
}
/** Themes installed from the official store or community API. */
export function isDownloadedTheme(theme: CustomTheme): boolean {
return theme.installedFromStore === true || theme.installedFromCommunity === true;
}
/**
* When importing a local copy of a theme whose id already belongs to a store/community
* install, use a new id so both copies can coexist.
*/
export function resolveLocalThemeInstallId(
themeId: string,
existing: Pick<CustomTheme, 'installedFromStore' | 'installedFromCommunity'> | null,
fromStore: boolean,
fromCommunity: boolean,
): string {
if (fromStore || fromCommunity) return themeId;
if (
existing &&
(existing.installedFromStore === true || existing.installedFromCommunity === true)
) {
return crypto.randomUUID();
}
return themeId;
}
export function filterThemesByMode(themes: CustomTheme[], mode: ThemeListMode): CustomTheme[] {
if (mode === 'all') return themes;
if (mode === 'custom') return themes.filter(isLocalCustomTheme);
return themes.filter(isDownloadedTheme);
}
/** Installed theme ids from the official store only (excludes file imports / custom copies). */
export function getStoreInstalledThemeIds(themes: CustomTheme[]): string[] {
return themes.filter((theme) => theme.installedFromStore === true).map((theme) => theme.id);
}
/** Installed theme ids from the community API only (excludes file imports / custom copies). */
export function getCommunityInstalledThemeIds(themes: CustomTheme[]): string[] {
return themes
.filter((theme) => theme.installedFromCommunity === true)
.map((theme) => theme.id);
}
export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean {
const installed = new Set(installedIds);
if (installed.has(theme.id)) return true;
return (theme.flavours ?? []).some((flavour) => installed.has(flavour.id));
}
export function resolveStoreVariantAccentColor(
theme: Theme,
variantId: string,
installedThemeColors: Record<string, string> = {},
): string {
const installed = installedThemeColors[variantId]?.trim();
if (installed) return installed;
const flavour = theme.flavours?.find((entry) => entry.id === variantId);
if (flavour?.accent_color?.trim()) return flavour.accent_color.trim();
if (variantId === theme.id) {
const firstFlavourAccent = theme.flavours?.find((entry) => entry.accent_color?.trim())?.accent_color?.trim();
if (firstFlavourAccent) return firstFlavourAccent;
}
return DEFAULT_THEME_ACCENT;
}
export type ThemeApplyButtonStyles = {
apply: string;
applied: string;
};
export function getThemeApplyButtonStyles(accentColor: string | undefined): ThemeApplyButtonStyles {
const parsed = parseCssColor(accentColor?.trim() || DEFAULT_THEME_ACCENT, DEFAULT_THEME_ACCENT);
const onAccent = parsed.lightness() >= 60 ? '#18181b' : '#ffffff';
return {
apply: `background-color: ${parsed.hex()}; color: ${onAccent};`,
applied: `background-color: ${parsed.alpha(0.18).string()}; color: ${parsed.hex()};`,
};
}
@@ -0,0 +1,17 @@
import {
createDefaultThemeCoverSvg,
defaultThemeCoverDataUrl,
} from "./themePlaceholderCover";
describe("themePlaceholderCover", () => {
it("builds an svg cover placeholder", () => {
const svg = createDefaultThemeCoverSvg("#3366ff");
expect(svg).toContain("<svg");
expect(svg).toContain("No cover image");
expect(svg).toContain("#3366ff");
});
it("builds a data url", () => {
expect(defaultThemeCoverDataUrl()).toMatch(/^data:image\/svg\+xml/);
});
});
@@ -0,0 +1,46 @@
import type { LoadedCustomTheme } from "@/types/CustomThemes";
/** SVG cover used when a theme has no store/community cover image. */
export function createDefaultThemeCoverSvg(accentHint = "#52525b"): string {
const accent = accentHint.startsWith("#") ? accentHint : "#52525b";
return `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="450" viewBox="0 0 800 450" role="img" aria-label="Theme cover placeholder">
<defs>
<linearGradient id="bsplus-theme-cover-grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="${accent}" stop-opacity="0.45"/>
<stop offset="55%" stop-color="#27272a" stop-opacity="0.95"/>
<stop offset="100%" stop-color="#09090b"/>
</linearGradient>
</defs>
<rect width="800" height="450" fill="url(#bsplus-theme-cover-grad)"/>
<g fill="none" stroke="#fafafa" stroke-opacity="0.35" stroke-width="2">
<rect x="280" y="130" width="240" height="160" rx="16"/>
<path d="M310 250 L350 190 L390 230 L430 170 L490 250 Z" fill="#fafafa" fill-opacity="0.12" stroke="none"/>
<circle cx="430" cy="175" r="14" fill="#fafafa" fill-opacity="0.2" stroke="none"/>
</g>
<text x="400" y="330" text-anchor="middle" fill="#fafafa" fill-opacity="0.85" font-family="system-ui,Segoe UI,sans-serif" font-size="22" font-weight="600">No cover image</text>
<text x="400" y="360" text-anchor="middle" fill="#fafafa" fill-opacity="0.5" font-family="system-ui,Segoe UI,sans-serif" font-size="14">Add one in Theme Creator</text>
</svg>`;
}
export function defaultThemeCoverDataUrl(accentHint?: string): string {
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
createDefaultThemeCoverSvg(accentHint),
)}`;
}
let cachedCoverBlob: Blob | null = null;
export async function getDefaultThemeCoverBlob(accentHint?: string): Promise<Blob> {
if (!cachedCoverBlob) {
cachedCoverBlob = new Blob([createDefaultThemeCoverSvg(accentHint)], {
type: "image/svg+xml",
});
}
return cachedCoverBlob;
}
export async function ensureThemeCoverImage(theme: LoadedCustomTheme): Promise<LoadedCustomTheme> {
if (theme.coverImage && theme.coverImage.size > 0) return theme;
const coverImage = await getDefaultThemeCoverBlob(theme.defaultColour);
return { ...theme, coverImage };
}
+61 -51
View File
@@ -1,55 +1,59 @@
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { unmount } from "svelte";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { themeBuilderPanel } from "@/interface/hooks/themeBuilderPanel.svelte";
import {
clearThemeCreatorSession,
persistThemeCreatorSession,
} from "@/plugins/built-in/themes/themeCreatorPersistence";
import {
applyThemeCreatorLayout,
clearThemeCreatorLayout,
} from "@/plugins/built-in/themes/themeCreatorLayout";
let themeCreatorSvelteApp: any = null;
let currentWidthPx = 400;
/**
* Open the Theme Creator sidebar, it is an embedded page loaded similar to the extension popup
* @param themeID - The ID of the theme to load in the Theme Creator
* @returns void
* Open the interactive theme builder docked to the right of the SEQTA page (not inside settings).
*/
export async function OpenThemeCreator(themeID: string = "") {
CloseThemeCreator();
await CloseThemeCreator();
const [{ default: renderSvelte }, { default: themeCreator }] =
await Promise.all([
import("@/interface/main"),
import("@/interface/pages/themeCreator.svelte"),
]);
themeBuilderPanel.open(themeID || null);
persistThemeCreatorSession(themeID || null);
localStorage.setItem("themeCreatorOpen", "true");
if (!themeID) {
localStorage.setItem("originalPreviewColor", settingsState.selectedColor);
}
ThemeManager.getInstance().beginThemeCreatorSession();
const width = "310px";
const [{ default: renderSvelte }, { default: ThemeCreatorPage }] = await Promise.all([
import("@/interface/main"),
import("@/interface/pages/themeCreator.svelte"),
]);
const editingId = themeID || themeBuilderPanel.editingThemeId || "";
currentWidthPx = 460;
const width = `${currentWidthPx}px`;
const themeCreatorDiv: HTMLDivElement = document.createElement("div");
themeCreatorDiv.id = "themeCreator";
themeCreatorDiv.style.width = width;
themeCreatorDiv.style.height = "100%";
if (settingsState.DarkMode) {
themeCreatorDiv.classList.add("dark");
}
const shadow = themeCreatorDiv.attachShadow({ mode: "open" });
themeCreatorSvelteApp = renderSvelte(themeCreator, shadow, {
themeID: themeID,
themeCreatorSvelteApp = renderSvelte(ThemeCreatorPage, shadow, {
themeID: editingId,
});
const mainContent = document.querySelector("#container") as HTMLDivElement;
if (mainContent) mainContent.style.width = `calc(100% - ${width})`;
const closeButton = document.createElement("button");
closeButton.classList.add("themeCloseButton");
closeButton.textContent = "×";
closeButton.addEventListener("click", () => {
CloseThemeCreator();
ThemeManager.getInstance().clearPreview();
});
document.body.appendChild(closeButton);
applyThemeCreatorLayout(currentWidthPx);
themeCreatorDiv.style.color = "initial";
const resizeBar = document.createElement("div");
resizeBar.classList.add("resizeBar");
resizeBar.style.right = "307.5px";
let isDragging = false;
@@ -64,10 +68,10 @@ export async function OpenThemeCreator(themeID: string = "") {
const mouseMoveHandler = (e: MouseEvent) => {
if (!isDragging) return;
const windowWidth = window.innerWidth;
const newWidth = Math.max(310, windowWidth - e.clientX);
themeCreatorDiv.style.width = `${newWidth}px`;
mainContent.style.width = `calc(100% - ${newWidth}px)`;
resizeBar.style.right = `${newWidth - 2.5}px`;
currentWidthPx = Math.max(320, windowWidth - e.clientX);
themeCreatorDiv.style.width = `${currentWidthPx}px`;
applyThemeCreatorLayout(currentWidthPx);
positionResizeBar(currentWidthPx, resizeBar);
};
const mouseUpHandler = () => {
@@ -79,34 +83,40 @@ export async function OpenThemeCreator(themeID: string = "") {
};
resizeBar.addEventListener("mousedown", mouseDownHandler);
resizeBar.addEventListener(
"mouseover",
() => (resizeBar.style.opacity = "1"),
);
resizeBar.addEventListener("mouseover", () => (resizeBar.style.opacity = "1"));
resizeBar.addEventListener("mouseout", () => (resizeBar.style.opacity = "0"));
document.body.appendChild(themeCreatorDiv);
document.body.appendChild(resizeBar);
positionResizeBar(currentWidthPx, resizeBar);
}
/**
* Close the Theme Creator sidebar
* @returns void
*/
export function CloseThemeCreator() {
localStorage.removeItem("themeCreatorOpen");
function positionResizeBar(widthPx: number, resizeBar: HTMLDivElement) {
resizeBar.style.right = `${widthPx - 2.5}px`;
}
export async function CloseThemeCreator(options?: { restoreTheme?: boolean }) {
const themeManager = ThemeManager.getInstance();
if (options?.restoreTheme === false) {
themeManager.discardThemeCreatorRestore();
themeManager.clearPreview();
} else {
await themeManager.endThemeCreatorSession();
}
clearThemeCreatorSession();
themeBuilderPanel.close();
const themeCreator = document.getElementById("themeCreator");
const closeButton = document.querySelector(
".themeCloseButton",
) as HTMLButtonElement;
const resizeBar = document.querySelector(".resizeBar") as HTMLDivElement;
const resizeBar = document.querySelector(".resizeBar") as HTMLDivElement | null;
if (themeCreatorSvelteApp) unmount(themeCreatorSvelteApp);
themeCreatorSvelteApp = null;
if (themeCreator) themeCreator.remove();
if (closeButton) closeButton.remove();
if (resizeBar) resizeBar.remove();
const mainContent = document.querySelector("#container") as HTMLDivElement;
if (mainContent) mainContent.style.width = "100%";
clearThemeCreatorLayout();
}
export function isThemeCreatorOpen(): boolean {
return document.getElementById("themeCreator") != null;
}
+166 -14
View File
@@ -24,6 +24,7 @@ import {
type ThemePageSyncInput,
} from "@/seqta/utils/patchThemeImagesPageContext";
import { verboseDebug, verboseInfo } from "@/utils/verboseLog";
import { resolveLocalThemeInstallId } from "@/interface/utils/themeListFilters";
import {
clearThemeRuntime,
injectThemeDom,
@@ -58,6 +59,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;
@@ -71,6 +74,8 @@ export class ThemeManager {
private lastSyncedImageKey: string | null = null;
private originalPreviewColor: string | null = null;
private originalPreviewTheme: boolean | null = null;
/** Theme id active before opening Theme Creator (restored on exit without save). */
private themeCreatorSuspendedThemeId: string | null = null;
private lastTransitionPoint: { x: number; y: number } = { x: 0, y: 0 };
private storeUpdateCheckRunning = false;
@@ -230,13 +235,18 @@ export class ThemeManager {
await localforage.setItem(neumorphicThemeId, theme);
}
const themeCreatorOpen = localStorage.getItem("themeCreatorOpen");
if (themeCreatorOpen === "true") {
verboseDebug(
"[ThemeManager] Theme creator was open, clearing preview state",
const { readThemeCreatorSession } = await import(
"@/plugins/built-in/themes/themeCreatorPersistence"
);
const creatorSession = readThemeCreatorSession();
if (creatorSession.open) {
verboseDebug("[ThemeManager] Restoring theme creator after navigation");
const { OpenThemeCreator, isThemeCreatorOpen } = await import(
"@/plugins/built-in/themes/ThemeCreator"
);
this.clearPreview();
localStorage.removeItem("themeCreatorOpen");
if (!isThemeCreatorOpen()) {
void OpenThemeCreator(creatorSession.editingThemeId);
}
}
if (settingsState.selectedTheme) {
@@ -370,6 +380,11 @@ export class ThemeManager {
setCustomThemeAdaptiveCssVariables(theme.adaptiveCssVariables ?? []);
const { applyThemeCreatorMetaToSettings } = await import(
"@/interface/utils/themeCreatorMeta"
);
applyThemeCreatorMetaToSettings(theme.creatorMeta);
injectThemeDom(theme.themeDom);
} catch (error) {
console.error("[ThemeManager] Error applying theme:", error);
@@ -456,6 +471,23 @@ export class ThemeManager {
/**
* Stable key so preview updates can skip re-encoding image blobs when only CSS changed.
*/
/** While Theme Creator is open, keep active theme image vars unless the draft replaces them. */
private resolvePreviewImages(
theme: Partial<LoadedCustomTheme>,
): Array<{ id: string; variableName: string; blob: Blob }> {
const draftImages = theme.CustomImages ?? [];
if (!this.themeCreatorSuspendedThemeId) return draftImages;
const baseImages = this.currentTheme?.CustomImages ?? [];
if (draftImages.length === 0) return baseImages;
const merged = new Map(baseImages.map((image) => [image.id, image]));
for (const image of draftImages) {
merged.set(image.id, image);
}
return [...merged.values()];
}
private imageSyncKey(
images: Array<{ id: string; variableName: string; blob: Blob }>,
): string {
@@ -583,6 +615,67 @@ 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<string> {
try {
return 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<string> {
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;
const catalogId = themeContent.id;
if (themeData.id && themeData.id !== catalogId) {
verboseDebug(
"[ThemeManager] Community theme.json id differs from catalog id; using catalog id",
{ catalogId, themeJsonId: themeData.id },
);
}
await this.installTheme(
{ ...themeData, id: catalogId },
{
fromStore: false,
fromCommunity: true,
serverUpdatedAtSec: themeContent.updated_at,
},
);
return catalogId;
}
/**
* Fetch theme.json from the store and install (throws on failure).
*/
@@ -651,7 +744,17 @@ export class ThemeManager {
}
const fromStore = meta?.fromStore ?? false;
const fromCommunity = meta?.fromCommunity ?? false;
const serverUpdatedAtSec = meta?.serverUpdatedAtSec;
const isLocalInstall = !fromStore && !fromCommunity;
const existingTheme = (await localforage.getItem(themeData.id)) as CustomTheme | null;
const themeId = resolveLocalThemeInstallId(
themeData.id,
existingTheme,
fromStore,
fromCommunity,
);
// Handle cover image (optional)
let coverImageBlob = null;
@@ -688,20 +791,21 @@ export class ThemeManager {
.filter((img) => img !== null) ?? [];
const theme: LoadedCustomTheme = {
id: themeData.id,
id: themeId,
name: themeData.name,
description: themeData.description || "",
webURL: themeData.id,
webURL: themeId,
coverImage: coverImageBlob,
CustomImages: images,
CustomCSS: themeData.CustomCSS || "",
defaultColour: themeData.defaultColour || "rgba(0, 123, 255, 1)",
CanChangeColour: themeData.CanChangeColour ?? true,
allowBackgrounds: true,
isEditable: false,
isEditable: isLocalInstall,
hideThemeName: themeData.hideThemeName ?? false,
forceDark: themeData.forceDark,
installedFromStore: fromStore,
installedFromCommunity: fromCommunity || undefined,
userEdited: fromStore ? false : undefined,
storeSyncedAtSec:
fromStore && serverUpdatedAtSec != null
@@ -949,15 +1053,21 @@ export class ThemeManager {
}
const syncInput: ThemePageSyncInput = {};
const inCreatorSession = this.themeCreatorSuspendedThemeId !== null;
if (theme.CustomCSS !== undefined) {
syncInput.previewCss = theme.CustomCSS;
}
if (theme.CustomImages) {
const imageKey = this.imageSyncKey(theme.CustomImages);
if (imageKey !== this.lastSyncedImageKey) {
syncInput.images = theme.CustomImages;
const previewImages = this.resolvePreviewImages(theme);
if (previewImages.length > 0) {
const imageKey = this.imageSyncKey(previewImages);
const shouldSyncImages =
inCreatorSession ||
imageKey !== this.lastSyncedImageKey ||
theme.CustomCSS !== undefined;
if (shouldSyncImages) {
syncInput.images = previewImages;
this.lastSyncedImageKey = imageKey;
}
}
@@ -977,6 +1087,12 @@ export class ThemeManager {
}
setCustomThemeAdaptiveCssVariables(theme.adaptiveCssVariables ?? []);
const { applyThemeCreatorMetaToSettings } = await import(
"@/interface/utils/themeCreatorMeta"
);
applyThemeCreatorMetaToSettings(theme.creatorMeta);
void updateAllColors();
} catch (error) {
console.error("[ThemeManager] Error updating theme preview:", error);
@@ -994,13 +1110,49 @@ export class ThemeManager {
2,
);
/**
* Start Theme Creator: keep the current theme on SEQTA; preview layers on top only.
*/
public beginThemeCreatorSession(): void {
const activeId = settingsState.selectedTheme?.trim() || "";
this.themeCreatorSuspendedThemeId = activeId || null;
if (this.originalPreviewColor === null) {
this.originalPreviewColor = settingsState.selectedColor;
}
if (this.originalPreviewTheme === null) {
this.originalPreviewTheme = settingsState.DarkMode;
}
verboseDebug("[ThemeManager] Theme creator session started", {
suspendedThemeId: this.themeCreatorSuspendedThemeId,
});
}
/**
* End Theme Creator: drop preview CSS and re-apply the theme that was active before editing.
*/
public discardThemeCreatorRestore(): void {
this.themeCreatorSuspendedThemeId = null;
}
public async endThemeCreatorSession(): Promise<void> {
const restoreId = this.themeCreatorSuspendedThemeId;
this.themeCreatorSuspendedThemeId = null;
this.clearPreview();
if (restoreId) {
verboseDebug("[ThemeManager] Restoring theme after creator exit:", restoreId);
await this.setTheme(restoreId, false);
}
}
/**
* Clear theme preview
*/
public clearPreview(): void {
verboseDebug("[ThemeManager] Clearing theme preview");
try {
void syncThemeToPage({ clearPreview: true, images: [] });
void syncThemeToPage({ clearPreview: true });
this.lastSyncedImageKey = null;
clearCustomThemeAdaptiveCssVariables();
@@ -0,0 +1,34 @@
let layoutObserver: MutationObserver | null = null;
let activePanelWidthPx = 0;
export function applyThemeCreatorLayout(widthPx: number): void {
activePanelWidthPx = widthPx;
syncContainerWidth();
startLayoutObserver();
}
export function clearThemeCreatorLayout(): void {
activePanelWidthPx = 0;
layoutObserver?.disconnect();
layoutObserver = null;
const main = document.querySelector("#container") as HTMLElement | null;
if (main) main.style.width = "100%";
}
function syncContainerWidth(): void {
if (!activePanelWidthPx) return;
const main = document.querySelector("#container") as HTMLElement | null;
if (main) main.style.width = `calc(100% - ${activePanelWidthPx}px)`;
}
function startLayoutObserver(): void {
layoutObserver?.disconnect();
layoutObserver = new MutationObserver(() => {
if (!document.getElementById("themeCreator")) {
clearThemeCreatorLayout();
return;
}
syncContainerWidth();
});
layoutObserver.observe(document.body, { childList: true, subtree: true });
}
@@ -0,0 +1,24 @@
const OPEN_KEY = "themeCreatorOpen";
const EDITING_ID_KEY = "themeBuilderEditingId";
export function persistThemeCreatorSession(editingThemeId: string | null): void {
localStorage.setItem(OPEN_KEY, "true");
if (editingThemeId) {
localStorage.setItem(EDITING_ID_KEY, editingThemeId);
} else {
localStorage.removeItem(EDITING_ID_KEY);
}
}
export function clearThemeCreatorSession(): void {
localStorage.removeItem(OPEN_KEY);
localStorage.removeItem(EDITING_ID_KEY);
localStorage.removeItem("themeBuilderIntent");
}
export function readThemeCreatorSession(): { open: boolean; editingThemeId: string } {
return {
open: localStorage.getItem(OPEN_KEY) === "true",
editingThemeId: localStorage.getItem(EDITING_ID_KEY) ?? "",
};
}
+2 -1
View File
@@ -7,7 +7,6 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { getAdaptiveColour } from "@/seqta/utils/adaptiveThemeColour";
import { adaptiveThemeTransitionEnabled, transparencyEnabled } from "@/seqta/utils/performanceMode";
import { getCustomThemeAdaptiveCssVariableBindings } from "@/seqta/ui/colors/customThemeAdaptiveBindings";
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
import darkLogo from "@/resources/icons/betterseqta-light-full.png";
import lightLogo from "@/resources/icons/betterseqta-dark-full.png";
@@ -129,6 +128,8 @@ function getRepresentativeRgbChannels(s: string): { r: number; g: number; b: num
function applyColorsWith(selectedColor: string) {
if (transparencyEnabled()) {
document.documentElement.classList.add("transparencyEffects");
} else {
document.documentElement.classList.remove("transparencyEffects");
}
// Common properties, always applied
+15
View File
@@ -0,0 +1,15 @@
import { PRODUCTION_API_BASE, resolveApiBase } from "./apiBasePolicy";
describe("resolveApiBase", () => {
it("uses production during extension dev builds", () => {
expect(resolveApiBase("development", "http://localhost:3000")).toBe(PRODUCTION_API_BASE);
expect(resolveApiBase("development", null)).toBe(PRODUCTION_API_BASE);
});
it("honors session override in production builds", () => {
expect(resolveApiBase("production", "https://staging.example.test")).toBe(
"https://staging.example.test",
);
expect(resolveApiBase("production", null)).toBe(PRODUCTION_API_BASE);
});
});
+37 -20
View File
@@ -1,33 +1,54 @@
import browser from "webextension-polyfill";
import { PRODUCTION_API_BASE, resolveApiBase } from "@/seqta/utils/apiBasePolicy";
export { PRODUCTION_API_BASE } from "@/seqta/utils/apiBasePolicy";
const DEFAULT_BASE = "https://betterseqta.org";
const KEY = "bsplus_dev_api_base";
/**
* Returns the current content-API base URL.
*
* Reads from `sessionStorage` so a developer can temporarily override the
* server for testing. The value is cleared when the browser session ends,
* leaving production traffic unaffected for normal users.
*/
export function getApiBase(): string {
function readSessionOverride(): string | null {
try {
if (typeof sessionStorage === "undefined") return DEFAULT_BASE;
if (typeof sessionStorage === "undefined") return null;
const v = sessionStorage.getItem(KEY);
if (v && /^https?:\/\//.test(v)) return v.replace(/\/$/, "");
} catch {
// sessionStorage may throw in some restricted contexts; fall back silently.
}
return DEFAULT_BASE;
return null;
}
function currentBuildMode(): "development" | "production" {
return import.meta.env.DEV ? "development" : "production";
}
/**
* Returns the current content-API base URL.
*
* In production builds, Advanced settings may set a session-only override for server testing.
* In extension dev builds, overrides are ignored and production is always used.
*/
export function getApiBase(): string {
return resolveApiBase(currentBuildMode(), readSessionOverride());
}
/**
* Persist a session-scoped override and broadcast it to the background script
* so its `fetch` calls hit the same host.
*
* Pass `null` to clear the override.
* Pass `null` to clear the override. No-op in extension dev builds.
*/
export function setApiBase(url: string | null): void {
if (import.meta.env.DEV) {
try {
sessionStorage.removeItem(KEY);
} catch {
// ignore
}
void browser.runtime
.sendMessage({ type: "setDevApiBase", url: null })
.catch(() => {});
return;
}
try {
if (!url) {
sessionStorage.removeItem(KEY);
@@ -42,14 +63,10 @@ export function setApiBase(url: string | null): void {
.catch(() => {});
}
/** Returns the override URL if one is currently set in this session. */
/** Returns the override URL if one is currently active (production builds only). */
export function getStoredOverride(): string | null {
try {
if (typeof sessionStorage === "undefined") return null;
return sessionStorage.getItem(KEY);
} catch {
return null;
}
if (import.meta.env.DEV) return null;
return readSessionOverride();
}
/**
@@ -58,7 +75,7 @@ export function getStoredOverride(): string | null {
* service-worker restarts.
*/
export function syncApiBaseToBackground(): void {
const override = getStoredOverride();
const override = import.meta.env.DEV ? null : readSessionOverride();
void browser.runtime
.sendMessage({ type: "setDevApiBase", url: override })
.catch(() => {});
+14
View File
@@ -0,0 +1,14 @@
export const PRODUCTION_API_BASE = "https://betterseqta.org";
/**
* Resolves the content API host. Extension dev builds always use production
* so community theme submit and the theme store work against the live API.
*/
export function resolveApiBase(
buildMode: "development" | "production",
sessionOverride: string | null,
): string {
if (buildMode === "development") return PRODUCTION_API_BASE;
if (sessionOverride) return sessionOverride;
return PRODUCTION_API_BASE;
}
+16
View File
@@ -0,0 +1,16 @@
import { CustomThemeApiError } from "./client";
import { RATE_LIMIT_DAILY_MESSAGE, RATE_LIMIT_PENDING_MESSAGE } from "./constants";
export function formatCustomThemeApiError(err: unknown): string {
if (err instanceof CustomThemeApiError) {
if (err.status === 429) {
return err.message.includes("pending") ? RATE_LIMIT_PENDING_MESSAGE : RATE_LIMIT_DAILY_MESSAGE;
}
if (err.validationErrors.length > 0) {
return err.validationErrors.join("\n");
}
return err.message;
}
return err instanceof Error ? err.message : "Something went wrong";
}
@@ -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,63 @@
import {
formatCustomThemeStatus,
statusBadgeClass,
canEditCustomTheme,
} from "./client";
import {
formatEnvelopeErrorMessage,
normalizeCustomThemeApiResponse,
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(parseApiError(null, 500)).toBe("Request failed (HTTP 500)");
expect(
parseValidationErrors({
code: "INVALID_THEME_STRUCTURE",
message: "Bad theme",
details: { errors: ["Missing CustomCSS", "Missing name"] },
}),
).toEqual(["Missing CustomCSS", "Missing name"]);
expect(
formatEnvelopeErrorMessage({
success: false,
data: null,
error: { code: "INVALID_THEME_STRUCTURE", message: "Bad theme" },
httpStatus: 422,
}),
).toContain("Bad theme");
});
it("normalizes Laravel validation bodies", () => {
const out = normalizeCustomThemeApiResponse(
{
message: "The given data was invalid.",
errors: { theme_zip: ["The theme zip field is required."] },
},
422,
);
expect(out.success).toBe(false);
expect((out.error as { message: string }).message).toContain("theme_zip");
});
});
+222
View File
@@ -0,0 +1,222 @@
import browser from "webextension-polyfill";
import type { CustomThemeStatus } from "./constants";
import { formatThemeDate } from "./formatThemeDate";
import { normalizeCustomTheme } from "./normalizeCustomTheme";
import { formatEnvelopeErrorMessage, 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;
const EXTENSION_RELOAD_HINT =
"Extension reloaded — refresh the SEQTA tab and reopen settings after `pnpm dev` updates, then try again.";
async function sendRuntimeMessage<T>(message: object): Promise<T> {
try {
if (!browser.runtime?.id) throw new Error(EXTENSION_RELOAD_HINT);
return (await browser.runtime.sendMessage(message)) as T;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (/disconnected port|context invalidated|receiving end does not exist|message port closed/i.test(msg)) {
throw new Error(EXTENSION_RELOAD_HINT);
}
throw err;
}
}
function sendMessageWithTimeout<T>(message: object): Promise<T> {
return Promise.race([
sendRuntimeMessage<T>(message),
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 errObj =
envelope.error && typeof envelope.error === "object" ? envelope.error : undefined;
throw new CustomThemeApiError(
formatEnvelopeErrorMessage(envelope),
envelope.httpStatus ?? 0,
errObj?.code,
parseValidationErrors(errObj),
);
}
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> & { httpStatus?: number }
>({
type: "submitCustomTheme",
payload,
});
if (!res || typeof res !== "object" || !res.success || !res.data?.theme) {
throwFromEnvelope(
res && typeof res === "object"
? res
: {
success: false,
data: null,
error: "Empty response from extension background",
httpStatus: 0,
},
);
}
return {
theme: normalizeCustomTheme(res.data.theme as unknown as Record<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,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,96 @@
import type { CustomThemeApiEnvelope, CustomThemeApiError } from "./types";
export function parseApiError(
error: CustomThemeApiEnvelope<unknown>["error"],
httpStatus?: number,
envelope?: Record<string, unknown>,
): string {
if (typeof error === "string" && error.length > 0) return error;
if (error && typeof error === "object") {
const err = error as CustomThemeApiError;
if (err.message) return err.message;
if (err.code) return err.code;
}
if (envelope?.message && typeof envelope.message === "string") return envelope.message;
if (httpStatus && httpStatus > 0) return `Request failed (HTTP ${httpStatus})`;
return "Request failed";
}
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 formatEnvelopeErrorMessage(
envelope: CustomThemeApiEnvelope<unknown> & { httpStatus?: number },
): string {
const status = envelope.httpStatus ?? 0;
const envRecord = envelope as Record<string, unknown>;
const errObj =
envelope.error && typeof envelope.error === "object"
? (envelope.error as CustomThemeApiError)
: undefined;
const base = parseApiError(envelope.error, status, envRecord);
const validationErrors = parseValidationErrors(errObj);
const code = errObj?.code ?? (typeof envRecord.code === "string" ? envRecord.code : undefined);
const parts = [base];
if (code && !base.includes(code)) parts.push(`[${code}]`);
if (status > 0 && !base.includes(`HTTP ${status}`)) parts.push(`(HTTP ${status})`);
if (validationErrors.length) parts.push(validationErrors.join("\n"));
return parts.join(" ").trim() || `Request failed (HTTP ${status || "unknown"})`;
}
/** Normalize fetch JSON into the custom-themes API envelope (incl. Laravel validation bodies). */
export function normalizeCustomThemeApiResponse(
body: unknown,
httpStatus: number,
rawText?: string,
): Record<string, unknown> {
if (!body || typeof body !== "object") {
const snippet = rawText?.trim().slice(0, 280);
return {
success: false,
data: null,
error: {
message: snippet
? `Unexpected response (HTTP ${httpStatus}): ${snippet}`
: `Unexpected response (HTTP ${httpStatus})`,
},
httpStatus,
};
}
const record = body as Record<string, unknown>;
if (record.success === true) return { ...record, httpStatus };
let error = record.error;
if (!error) {
const flat =
record.errors && typeof record.errors === "object"
? flattenValidationMap(record.errors as Record<string, unknown>)
: [];
const topMessage = typeof record.message === "string" ? record.message : "";
if (flat.length > 0) {
error = { message: flat.join("; "), details: { errors: flat } };
} else if (topMessage) {
error = { message: topMessage };
}
}
if (!error) error = { message: `Request failed (HTTP ${httpStatus})` };
return { success: false, data: record.data ?? null, error, httpStatus, meta: record.meta };
}
function flattenValidationMap(errors: Record<string, unknown>): string[] {
const out: string[] = [];
for (const [field, value] of Object.entries(errors)) {
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item === "string" && item.length > 0) out.push(`${field}: ${item}`);
}
} else if (typeof value === "string" && value.length > 0) {
out.push(`${field}: ${value}`);
}
}
return out;
}
@@ -0,0 +1,25 @@
import { ensureThemeCoverImage } from "@/interface/utils/themePlaceholderCover";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
import {
buildUploadPartsFromLocalTheme,
mergeUploadPayload,
} from "@/seqta/utils/customThemes/buildThemeUploadFormData";
import { submitCustomTheme } from "@/seqta/utils/customThemes/client";
import type { LoadedCustomTheme } from "@/types/CustomThemes";
export async function submitLocalThemeToCommunity(
theme: LoadedCustomTheme,
submissionNotes?: string,
) {
const payload = mergeUploadPayload(await buildUploadPartsFromLocalTheme(theme), submissionNotes);
return await submitCustomTheme(payload);
}
export async function submitThemeById(themeId: string, submissionNotes?: string) {
const theme = await ThemeManager.getInstance().getTheme(themeId);
if (!theme) throw new Error("Theme not found");
return submitLocalThemeToCommunity(
await ensureThemeCoverImage(theme as LoadedCustomTheme),
submissionNotes,
);
}
+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[] };
};
+4
View File
@@ -1,3 +1,7 @@
jest.mock("@/seqta/utils/DevApiBase", () => ({
getApiBase: () => "https://example.test",
}));
import browser from "webextension-polyfill";
import {
addPendingFeedbackId,
@@ -0,0 +1,8 @@
/** Close settings (if open) and mount the theme builder on the SEQTA page body. */
export async function launchPageThemeBuilder(themeId?: string): Promise<void> {
const { closeExtensionPopup } = await import("@/seqta/utils/Closers/closeExtensionPopup");
const { OpenThemeCreator } = await import("@/plugins/built-in/themes/ThemeCreator");
closeExtensionPopup();
await OpenThemeCreator(themeId ?? "");
}
@@ -1,6 +1,5 @@
import { settingsState } from "./SettingsState";
import { updateAllColors } from "@/seqta/ui/colors/Manager";
import { applySelectedFont } from "@/seqta/ui/fonts/Manager";
// Shortcuts rendering
import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts";
@@ -0,0 +1,34 @@
/** @jest-environment jsdom */
import {
consumeOpenCommunityThemeSubmit,
consumePendingCommunitySubmitThemeId,
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);
});
it("hands off a theme id for the submit modal", () => {
requestOpenCommunityThemeSubmit("theme-abc");
expect(consumePendingCommunitySubmitThemeId()).toBe("theme-abc");
expect(consumePendingCommunitySubmitThemeId()).toBeNull();
});
});
@@ -0,0 +1,58 @@
/**
* Module-level handoff for "open Community themes → My themes → submit modal".
*/
const OPEN_COMMUNITY_SUBMIT_SESSION_KEY = "bsplus:open-community-theme-submit";
const OPEN_COMMUNITY_SUBMIT_THEME_KEY = "bsplus:open-community-theme-submit-theme-id";
export const OPEN_COMMUNITY_SUBMIT_EVENT = "bsplus:open-community-submit";
let pendingOpenSubmit = false;
let pendingSubmitThemeId: string | null = null;
export function requestOpenCommunityThemeSubmit(themeId?: string): void {
pendingOpenSubmit = true;
if (themeId) pendingSubmitThemeId = themeId;
try {
sessionStorage.setItem(OPEN_COMMUNITY_SUBMIT_SESSION_KEY, "1");
if (themeId) sessionStorage.setItem(OPEN_COMMUNITY_SUBMIT_THEME_KEY, themeId);
} catch {
/* ignore */
}
window.dispatchEvent(new CustomEvent(OPEN_COMMUNITY_SUBMIT_EVENT));
}
export function consumePendingCommunitySubmitThemeId(): string | null {
let themeId = pendingSubmitThemeId;
pendingSubmitThemeId = null;
try {
const stored = sessionStorage.getItem(OPEN_COMMUNITY_SUBMIT_THEME_KEY);
if (stored) {
sessionStorage.removeItem(OPEN_COMMUNITY_SUBMIT_THEME_KEY);
themeId = stored;
}
} catch {
/* ignore */
}
return themeId;
}
export function consumeOpenCommunityThemeSubmit(): boolean {
let shouldOpen = pendingOpenSubmit;
pendingOpenSubmit = false;
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(themeId?: string): Promise<void> {
const { launchPageThemeBuilder } = await import("@/seqta/utils/launchPageThemeBuilder");
await launchPageThemeBuilder(themeId);
}
+25
View File
@@ -0,0 +1,25 @@
import browser from "webextension-polyfill";
export type StockPhotoResult = { title: string; thumbUrl: string; imageUrl: string };
export async function searchThemeStockPhotos(
query: string,
limit = 8,
): Promise<StockPhotoResult[]> {
const res = (await browser.runtime.sendMessage({
type: "searchThemeStockPhotos",
query,
limit,
})) as { success?: boolean; results?: StockPhotoResult[]; error?: string };
if (!res?.success || !res.results) {
throw new Error(res?.error ?? "Could not search photos");
}
return res.results;
}
export async function fetchStockPhotoBlob(imageUrl: string): Promise<Blob> {
const res = await fetch(imageUrl);
if (!res.ok) throw new Error("Could not download photo");
return await res.blob();
}
+4 -1
View File
@@ -1,6 +1,9 @@
export type SettingsDestination =
| { page: "settings"; section?: string; search?: string }
| { page: "themes" | "backgrounds"; view?: "settings" | "store" };
| {
page: "themes" | "backgrounds";
view?: "settings" | "store" | "community" | "custom";
};
export const SETTINGS_NAVIGATION_EVENT = "bsplus:navigate-settings";
-1
View File
@@ -3,7 +3,6 @@ import {
closeExtensionPopup,
SettingsClicked,
} from "./Closers/closeExtensionPopup";
import { settingsState } from "./listeners/SettingsState";
import {
animateSettingsOpen,
prefetchSettingsShell,
+4
View File
@@ -131,6 +131,10 @@
if (payload.previewCss !== undefined) {
setStyleText(PREVIEW_STYLE_ID, payload.previewCss || "");
var previewStyle = document.getElementById(PREVIEW_STYLE_ID);
if (previewStyle) {
document.head.appendChild(previewStyle);
}
}
if (payload.clearPreview) {
+18 -3
View File
@@ -18,13 +18,28 @@ function toHexByte(value: number): string {
}
function createColor(channels: ColorChannels) {
const hex = () =>
`#${toHexByte(channels.r)}${toHexByte(channels.g)}${toHexByte(channels.b)}`.toUpperCase();
const color = {
red: () => clampByte(channels.r),
green: () => clampByte(channels.g),
blue: () => clampByte(channels.b),
alpha: () => clampAlpha(channels.a),
hex: () =>
`#${toHexByte(channels.r)}${toHexByte(channels.g)}${toHexByte(channels.b)}`,
hex,
lightness: () => {
const r = channels.r / 255;
const g = channels.g / 255;
const b = channels.b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
return ((max + min) / 2) * 100;
},
string: () => {
if (channels.a < 1) {
return `rgba(${clampByte(channels.r)}, ${clampByte(channels.g)}, ${clampByte(channels.b)}, ${clampAlpha(channels.a)})`;
}
return hex();
},
};
return {
+26
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. */
@@ -39,6 +41,30 @@ export type CustomTheme = {
flickers?: number;
cityLayers?: boolean;
};
/** Theme Creator quick settings (font, page background, sidebar snapshot). */
creatorMeta?: ThemeCreatorMeta;
};
export type ThemeCreatorMeta = {
fontId: string;
/** CustomImages entry used as the SEQTA page background layer. */
pageBackgroundImageId: string | null;
backgroundBlurPx: number;
overlayOpacity: number;
gradientAngle: number;
gradientEnd: string;
/** Advanced CSS appended after generated builder rules. */
userCustomCss: string;
sidebar?: {
sidebarStyle?: string;
sidebarDensity?: string;
sidebarCornerRadius?: number;
sidebarActiveIndicator?: string;
sidebarWidth?: string;
sidebarPosition?: string;
sidebarBlur?: number;
transparencyEffects?: boolean;
};
};
export type LoadedCustomTheme = CustomTheme & {