clove/pkviewer
web/src/lib/components/manage/ThemeEditor.svelte
back to web/src/lib/components/manage
<!-- web/src/lib/components/manage/ThemeEditor.svelte -->
<script lang="ts">
import {
FONTS,
FONT_IDS,
PRESETS,
THEME_TOKENS,
resolveTheme,
themeToCssVars,
type TokenDef,
} from "@pkviewer/shared";
import { useUnsavedGuard } from "$lib/unsavedGuard.svelte.ts";
import type { ActionResult } from "$lib/types.ts";
import Icon from "../Icon.svelte";
import SaveBar, { type SaveState } from "./SaveBar.svelte";
import Section from "./Section.svelte";
import ThemePreview from "./ThemePreview.svelte";
/**
* One editor, two levels: a system sets the default, a member overrides it.
* Inheritance is UI, never data the user authors: a control either follows
* what it inherits or is set, with a button to move between the two.
*/
type Level = "system" | "member";
let {
level,
initialValues,
inheritedFrom,
onSave,
previewName,
}: {
level: Level;
/** Values explicitly set at THIS level. Absent key = inheriting. */
initialValues: Record<string, string | null>;
/** The layer beneath: platform defaults for a system, system theme for a member. */
inheritedFrom: Record<string, string>;
onSave: (values: Record<string, string | null>) => Promise<ActionResult>;
previewName: string;
} = $props();
const GROUPS: Array<{ title: string; hint: string; keys: string[] }> = [
{
title: "Colours",
hint: "The palette your pages are drawn from. Every other setting uses these.",
keys: ["color.page", "color.surface", "color.text", "color.muted", "color.accent", "color.border"],
},
{
title: "Typography",
hint: "The typefaces and reading size your pages use.",
keys: ["font.body", "font.heading", "font.size"],
},
{
title: "Shape and surfaces",
hint: "How cards, edges and avatars are drawn.",
keys: ["shape.radius", "surface.style", "avatar.shape"],
},
{
title: "Spacing",
hint: "How much room everything is given.",
keys: ["density"],
},
{
title: "Light and dark",
hint: "Follow the reader's device, or commit to one.",
keys: ["color.scheme"],
},
];
// svelte-ignore state_referenced_locally
let values = $state<Record<string, string | null>>({ ...initialValues });
// svelte-ignore state_referenced_locally
let saved = $state<Record<string, string | null>>({ ...initialValues });
let status = $state<"idle" | "saving" | "ok" | "error">("idle");
let message = $state<string | null>(null);
let presetNote = $state<string | null>(null);
const dirty = $derived(JSON.stringify(values) !== JSON.stringify(saved));
useUnsavedGuard(() => dirty);
// Resolved through the SAME functions the public renderer uses: one source of truth
const preview = $derived.by(() => {
const current = $state.snapshot(values);
const resolved =
level === "system" ? resolveTheme(current, {}) : resolveTheme(inheritedFrom, current);
return {
vars: themeToCssVars(resolved.light),
darkVars: themeToCssVars(resolved.dark),
scheme: resolved.scheme,
};
});
const editableKeys = $derived(
new Set(THEME_TOKENS.filter((token) => level === "system" || token.memberOverridable).map((token) => token.key)),
);
function setValue(key: string, value: string) {
values[key] = value;
status = "idle";
}
// Back to inheriting: the key is removed, which is exactly what "absent means inherit" is
function inherit(key: string) {
delete values[key];
status = "idle";
}
// Member-only: the explicit-null state, pinning a control to the platform default
function resetToPlatform(key: string) {
values[key] = null;
status = "idle";
}
function applyPreset(presetId: string) {
const preset = PRESETS.find((entry) => entry.id === presetId);
if (!preset) return;
// At member level a preset becomes member configuration; it never changes the system
for (const [key, value] of Object.entries(preset.tokens)) {
if (editableKeys.has(key)) values[key] = value;
}
status = "idle";
presetNote = `${preset.name} applied — review it below, then save.`;
}
async function save() {
status = "saving";
message = null;
const outcome = await onSave($state.snapshot(values));
if (outcome.ok) {
saved = { ...values };
status = "ok";
presetNote = null;
} else {
status = "error";
message = outcome.error ?? null;
}
}
const saveState: SaveState = $derived(
status === "saving"
? "saving"
: status === "error"
? "error"
: dirty
? "dirty"
: status === "ok"
? "saved"
: "clean",
);
function sentence(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1).replace(/-/g, " ");
}
</script>
{#snippet control(def: TokenDef, id: string, value: string)}
{#if def.type === "color"}
<span class="mg-colour">
<input
type="color"
{id}
value={/^#[0-9A-Fa-f]{6}$/.test(value) ? value : "#000000"}
aria-describedby="{id}-desc"
oninput={(event) => setValue(def.key, event.currentTarget.value.toUpperCase())}
/>
<input
type="text"
{value}
aria-label="{def.label} hex value"
spellcheck="false"
oninput={(event) => setValue(def.key, event.currentTarget.value.toUpperCase())}
/>
</span>
{:else if def.type === "font"}
<select
{id}
value={FONT_IDS.includes(value as never) ? value : def.default}
aria-describedby="{id}-desc"
onchange={(event) => setValue(def.key, event.currentTarget.value)}
>
{#each FONT_IDS as fontId (fontId)}
<option value={fontId}>{FONTS[fontId].label} — {FONTS[fontId].note}</option>
{/each}
</select>
{:else if def.type === "enum"}
<select
{id}
value={def.values.includes(value) ? value : def.default}
aria-describedby="{id}-desc"
onchange={(event) => setValue(def.key, event.currentTarget.value)}
>
{#each def.values as option (option)}
<option value={option}>{sentence(option)}</option>
{/each}
</select>
{:else}
<input
type="text"
{id}
{value}
aria-describedby="{id}-desc"
oninput={(event) => setValue(def.key, event.currentTarget.value)}
/>
{/if}
{/snippet}
{#snippet tokenField(def: TokenDef)}
{@const id = `tok-${def.key.replace(/\./g, "-")}`}
{@const value = values[def.key]}
{@const explicitlySet = Object.hasOwn(values, def.key)}
{@const isReset = explicitlySet && value === null}
{@const fieldState = explicitlySet ? "override" : "inherit"}
{@const effective = explicitlySet && typeof value === "string" ? value : (inheritedFrom[def.key] ?? "")}
<!-- State is a word and a border, never colour alone -->
<div class="mg-field" data-state={fieldState}>
<div class="mg-field-head">
<label for={id}>{def.label}</label>
<span class="spacer"></span>
<span class="mg-inherit" data-state={fieldState}>
{#if explicitlySet}<Icon name="pencil-square" />{/if}
{level === "system"
? explicitlySet ? "Custom" : "Default"
: isReset ? "Platform default" : explicitlySet ? "Custom" : "Using system appearance"}
</span>
</div>
{@render control(def, id, effective)}
<span class="desc" id="{id}-desc">{def.help}</span>
{#if explicitlySet}
<span>
<button type="button" class="ghost" onclick={() => inherit(def.key)}>
<Icon name="arrow-counterclockwise" />
{level === "system" ? "Use pkviewer default" : "Use system appearance"}
</button>
</span>
{:else if level === "member"}
<span>
<button type="button" class="ghost" onclick={() => setValue(def.key, effective)}>
<Icon name="pencil-square" />
Override for this member
</button>
<button type="button" class="ghost" onclick={() => resetToPlatform(def.key)}>
Use pkviewer default instead
</button>
</span>
{/if}
</div>
{/snippet}
<Section
title="Start from a preset"
description={level === "system"
? "A preset fills in every setting below. You can change anything afterwards."
: "Applying a preset here sets these values for this member only. It does not change the system."}
>
<div class="mg-presets">
{#each PRESETS as preset (preset.id)}
<button type="button" class="mg-preset" onclick={() => applyPreset(preset.id)}>
<span class="pname">{preset.name}</span>
<span class="mg-swatches" aria-hidden="true">
{#each ["color.page", "color.surface", "color.text", "color.accent"] as key (key)}
<span class="mg-swatch" style="background: {preset.tokens[key] ?? '#fff'}"></span>
{/each}
</span>
<span class="pchar">{preset.character}</span>
</button>
{/each}
</div>
{#if presetNote}
<p class="mg-note" role="status" style="margin-top: var(--mg-3)">
<span>{presetNote}</span>
</p>
{/if}
</Section>
<Section
title="Preview"
description="A representative sample. Open the public page to see the real thing."
>
<ThemePreview
vars={preview.vars}
darkVars={preview.darkVars}
scheme={preview.scheme}
name={previewName}
/>
</Section>
{#each GROUPS as group (group.title)}
{@const keys = group.keys.filter((key) => editableKeys.has(key))}
{#if keys.length > 0}
<Section title={group.title} description={group.hint}>
<div class="mg-grid">
{#each keys as key (key)}
{@const def = THEME_TOKENS.find((token) => token.key === key)}
{#if def}
{@render tokenField(def)}
{/if}
{/each}
</div>
</Section>
{/if}
{/each}
<SaveBar
state={saveState}
{message}
saveLabel="Save appearance"
onSave={save}
onDiscard={() => {
values = { ...saved };
status = "idle";
message = null;
presetNote = null;
}}
/>