feat: allow pasting of theme json for testing

This commit is contained in:
AdenMGB committed 2026-11-18 13:14:01 +10:30
1 parent b6728561d1
commit e3a0426e26
3 files changed
+180 -3

No files matched your search

+74 -3
View File
@@ -42,6 +42,7 @@
import { ensureThemeCoverImage } from '@/interface/utils/themePlaceholderCover'
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
import type { ThemeCreatorMeta } from '@/types/customThemes'
import { parseThemeBuilderJson } from '@/interface/utils/parseThemeBuilderJson'
const { themeID }: { themeID: string } = $props()
const themeManager = ThemeManager.getInstance();
@@ -62,7 +63,11 @@
forceDark: undefined,
adaptiveCssVariables: [],
})
let closedAccordions = $state<string[]>([])
let closedAccordions = $state<string[]>(['Advanced'])
let themeJsonDraft = $state('')
let themeJsonError = $state<string | null>(null)
/** After JSON import, preview CustomCSS as-is until the user edits generated visuals. */
let jsonImportRawPreview = $state(false)
let themeLoaded = $state(false);
let codeEditorFullscreen = $state(false);
let communityBusy = $state(false);
@@ -75,6 +80,9 @@
const previewTheme = $derived.by(() => {
if (!themeLoaded) return null;
if (jsonImportRawPreview) {
return { ...theme, creatorMeta };
}
if (composeVisuals || theme.creatorMeta || creatorMeta.pageBackgroundImageId) {
return mergeThemeWithCreatorMeta(theme, creatorMeta);
}
@@ -82,12 +90,42 @@
});
function touchVisuals() {
jsonImportRawPreview = false;
if (!composeVisuals && !theme.creatorMeta && !creatorMeta.userCustomCss.trim()) {
creatorMeta = { ...creatorMeta, userCustomCss: theme.CustomCSS };
}
composeVisuals = true;
}
function applyImportedThemeJson() {
themeJsonError = null;
try {
const parsed = parseThemeBuilderJson(themeJsonDraft);
jsonImportRawPreview = true;
composeVisuals = false;
theme = {
...parsed,
creatorMeta: undefined,
adaptiveCssVariables: parsed.adaptiveCssVariables ?? [],
forceTheme:
parsed.forceTheme ?? (parsed.forceDark !== undefined ? true : undefined),
};
if (parsed.creatorMeta) {
creatorMeta = { ...defaultThemeCreatorMeta(), ...parsed.creatorMeta };
applySidebarSettings(parsed.creatorMeta.sidebar);
} else {
creatorMeta = defaultThemeCreatorMeta({
userCustomCss: "",
fontId: settingsState.selectedFont ?? DEFAULT_FONT_ID,
});
}
applySelectedFont(creatorMeta.fontId);
themeUpdates.triggerUpdate();
} catch (err) {
themeJsonError = err instanceof Error ? err.message : "Could not load theme JSON";
}
}
function imageUsage(imageId: string): 'decorative' | 'page-background' | 'cover' {
if (creatorMeta.pageBackgroundImageId === imageId) return 'page-background';
const image = theme.CustomImages.find((item) => item.id === imageId);
@@ -277,7 +315,9 @@
void themeManager.updatePreviewDebounced(snapshot);
});
type SettingType = 'switch' | 'button' | 'slider' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle';
type SettingType = 'switch' | 'button' | 'slider' | 'select' | 'codeEditor' | 'imageUpload' | 'conditional' | 'lightDarkToggle' | 'themeJson';
type ThemeJsonProps = { value: string; onChange: (value: string) => void; onApply: () => void; error: string | null };
type SwitchProps = { state: boolean; onChange: (value: boolean) => void };
type ButtonProps = { onClick: () => void; text: string };
@@ -292,7 +332,7 @@
children: SettingItem;
};
type ComponentProps = SwitchProps | ButtonProps | SliderProps | SelectProps | CodeEditorProps | LightDarkToggleProps | ConditionalProps;
type ComponentProps = SwitchProps | ButtonProps | SliderProps | SelectProps | CodeEditorProps | LightDarkToggleProps | ConditionalProps | ThemeJsonProps;
type SettingItem = {
type: SettingType;
@@ -392,6 +432,25 @@
<span class='dark:text-white'>Add image</span>
<input type="file" accept='image/*' onchange={onImageUpload} class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" />
</div>
{:else if item.type === 'themeJson'}
{@const jsonProps = item.props as ThemeJsonProps}
<textarea
value={jsonProps.value}
oninput={(e) => jsonProps.onChange(e.currentTarget.value)}
placeholder={'{ "name": "My theme", "CustomCSS": "...", "images": [...] }'}
spellcheck="false"
class="h-40 w-full resize-y rounded-lg border-0 bg-zinc-200 p-2 font-mono text-xs dark:bg-zinc-700 dark:text-white"
></textarea>
<button
type="button"
class="mt-2 w-full rounded-lg bg-zinc-900 px-3 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={jsonProps.onApply}
>
Load into builder
</button>
{#if jsonProps.error}
<p class="mt-2 text-sm text-red-600 dark:text-red-400">{jsonProps.error}</p>
{/if}
{:else if item.type === 'lightDarkToggle'}
<button
class="overflow-hidden relative flex justify-center items-center px-4 py-1 text-xl font-medium rounded-lg transition bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600"
@@ -666,6 +725,18 @@
}
}
},
{
type: 'themeJson',
title: 'Advanced',
description: 'Paste a theme.json to load into the builder (images as base64 in images[])',
direction: 'vertical',
props: {
value: themeJsonDraft,
onChange: (value: string) => (themeJsonDraft = value),
onApply: applyImportedThemeJson,
error: themeJsonError,
}
},
{
type: 'codeEditor',
title: 'Custom CSS',
@@ -0,0 +1,19 @@
import { parseThemeBuilderJson } from "./parseThemeBuilderJson";
describe("parseThemeBuilderJson", () => {
it("parses minimal theme.json", () => {
const theme = parseThemeBuilderJson(
JSON.stringify({
name: "Test",
CustomCSS: "body { color: red; }",
}),
);
expect(theme.name).toBe("Test");
expect(theme.CustomCSS).toContain("red");
expect(theme.CustomImages).toHaveLength(0);
});
it("rejects invalid JSON", () => {
expect(() => parseThemeBuilderJson("{")).toThrow("Invalid JSON");
});
});
@@ -0,0 +1,87 @@
import { base64ToBlob, stripBase64Prefix } from "@/seqta/utils/base64";
import type { LoadedCustomTheme, ThemeCreatorMeta } from "@/types/customThemes";
function parseImageBlobs(data: Record<string, unknown>): LoadedCustomTheme["CustomImages"] {
const raw = Array.isArray(data.images)
? data.images
: Array.isArray(data.CustomImages)
? data.CustomImages
: [];
const images: LoadedCustomTheme["CustomImages"] = [];
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const row = entry as Record<string, unknown>;
let blob: Blob | null = null;
if (row.blob instanceof Blob) {
blob = row.blob;
} else if (typeof row.data === "string" && row.data) {
try {
blob = base64ToBlob(stripBase64Prefix(row.data));
} catch {
continue;
}
}
if (!blob) continue;
images.push({
id: typeof row.id === "string" && row.id ? row.id : crypto.randomUUID(),
variableName:
typeof row.variableName === "string" && row.variableName
? row.variableName
: `custom-image-${images.length}`,
blob,
});
}
return images;
}
/** Parse pasted theme.json (export or upload format) into builder state. */
export function parseThemeBuilderJson(text: string): LoadedCustomTheme {
const trimmed = text.trim();
if (!trimmed) throw new Error("Paste theme JSON first");
let data: Record<string, unknown>;
try {
data = JSON.parse(trimmed) as Record<string, unknown>;
} catch {
throw new Error("Invalid JSON");
}
const name = typeof data.name === "string" ? data.name.trim() : "";
if (!name) throw new Error('Theme JSON must include "name"');
const CustomImages = parseImageBlobs(data);
let coverImage: Blob | null = null;
if (typeof data.coverImage === "string" && data.coverImage) {
try {
coverImage = base64ToBlob(stripBase64Prefix(data.coverImage));
} catch {
coverImage = null;
}
}
const creatorMeta =
data.creatorMeta && typeof data.creatorMeta === "object"
? (data.creatorMeta as ThemeCreatorMeta)
: undefined;
return {
id: typeof data.id === "string" && data.id.trim() ? data.id.trim() : crypto.randomUUID(),
name,
description: typeof data.description === "string" ? data.description : "",
defaultColour:
typeof data.defaultColour === "string" ? data.defaultColour : "rgba(0, 123, 255, 1)",
CanChangeColour: data.CanChangeColour !== false,
allowBackgrounds: data.allowBackgrounds !== false,
CustomCSS: typeof data.CustomCSS === "string" ? data.CustomCSS : "",
CustomImages,
coverImage,
isEditable: true,
hideThemeName: data.hideThemeName === true,
forceTheme: typeof data.forceTheme === "boolean" ? data.forceTheme : undefined,
forceDark: typeof data.forceDark === "boolean" ? data.forceDark : undefined,
adaptiveCssVariables: Array.isArray(data.adaptiveCssVariables)
? (data.adaptiveCssVariables as string[])
: [],
creatorMeta,
};
}