Admin polish: stability fixes, schema security, consistent UI + sidebar #1

Merged
reudy merged 21 commits from session/polish into main 2026-10-07 16:30:40 +02:00
7 changed files with 98 additions and 40 deletions
Showing only changes of commit 3399daf951 - Show all commits

View file

@ -4,16 +4,9 @@
themes: light --default; themes: light --default;
} }
/* Admin UI theme: DaisyUI light with a fixed sage primary. Deliberately NOT /* Admin primary/secondary come from the site's colours (Site design →
tied to the site's colours (Site design → Colors) (those only apply inside /preview), so Colors) via $shared/theme, rendered in the root layout's <head> with an
a light brand colour can't make admin buttons unreadable. #647556 on white automatically readable text colour. */
text is ~5:1 contrast (WCAG AA). */
@plugin 'daisyui/theme' {
name: 'light';
default: true;
--color-primary: #647556;
--color-primary-content: #ffffff;
}
/* Hint text under form fields: DaisyUI's .label is nowrap, which stretched /* Hint text under form fields: DaisyUI's .label is nowrap, which stretched
fields to fit long hints. */ fields to fit long hints. */

View file

@ -4,6 +4,7 @@
import { afterNavigate } from '$app/navigation'; import { afterNavigate } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte'; import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { brandThemeVars, rootStyleTag } from '$shared/theme';
let { children, data } = $props(); let { children, data } = $props();
@ -12,6 +13,9 @@
const BARE_ROUTES = ['/login', '/preview']; const BARE_ROUTES = ['/login', '/preview'];
let bare = $derived(BARE_ROUTES.includes(page.url.pathname)); let bare = $derived(BARE_ROUTES.includes(page.url.pathname));
// The active item is marked with a tint + bar in the brand colour, never
// brand-coloured text: the site's primary may be too light to read as text.
// Sidebar navigation, grouped by what the studio is doing. Labels are // Sidebar navigation, grouped by what the studio is doing. Labels are
// user-facing names; hrefs keep the original route names. // user-facing names; hrefs keep the original route names.
const navGroups = [ const navGroups = [
@ -55,6 +59,8 @@
<svelte:head> <svelte:head>
<link rel="icon" href={favicon} /> <link rel="icon" href={favicon} />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Admin buttons/highlights use the site's Primary and Accent colours (sanitised; readable text picked automatically). -->
{@html rootStyleTag(brandThemeVars(data.colors))}
</svelte:head> </svelte:head>
{#if bare} {#if bare}
@ -86,7 +92,7 @@
<li class="menu-title mt-3 first:mt-0">{group.title}</li> <li class="menu-title mt-3 first:mt-0">{group.title}</li>
{#each group.links as link (link.href)} {#each group.links as link (link.href)}
<li> <li>
<a href={link.href} class={isActive(link.href) ? 'bg-primary/10 font-semibold text-primary' : ''} aria-current={isActive(link.href) ? 'page' : undefined}>{link.label}</a> <a href={link.href} class={isActive(link.href) ? 'bg-primary/20 font-semibold shadow-[inset_3px_0_0_var(--color-primary)]' : ''} aria-current={isActive(link.href) ? 'page' : undefined}>{link.label}</a>
</li> </li>
{/each} {/each}
{/each} {/each}

View file

@ -128,7 +128,7 @@
<div class="grid gap-2 sm:grid-cols-2"> <div class="grid gap-2 sm:grid-cols-2">
{#each emailPlaceholders as placeholder} {#each emailPlaceholders as placeholder}
<button type="button" class="btn btn-ghost btn-sm justify-start font-normal" onclick={() => copyPlaceholder(placeholder.key)}> <button type="button" class="btn btn-ghost btn-sm justify-start font-normal" onclick={() => copyPlaceholder(placeholder.key)}>
<code class="text-primary">{`{{${placeholder.key}}}`}</code> <code class="font-semibold">{`{{${placeholder.key}}}`}</code>
<span class="text-base-content/60">{copied === placeholder.key ? 'Copied!' : placeholder.description}</span> <span class="text-base-content/60">{copied === placeholder.key ? 'Copied!' : placeholder.description}</span>
</button> </button>
{/each} {/each}
@ -142,7 +142,7 @@
<div class="rounded-box bg-base-100 p-4 shadow"> <div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full"> <div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button> <button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow"> <ul class="menu dropdown-content z-20 mt-2 w-full rounded-box bg-base-100 p-2 shadow-lg">
{#each emailBlockTypes as type} {#each emailBlockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{emailBlockLabels[type]}</button></li> <li><button type="button" onclick={() => addBlock(type)}>{emailBlockLabels[type]}</button></li>
{/each} {/each}

View file

@ -37,7 +37,8 @@
const submit: SubmitFunction = ({ formData }) => { const submit: SubmitFunction = ({ formData }) => {
saving = String(formData.get('section')); saving = String(formData.get('section'));
return async ({ update }) => { return async ({ update }) => {
await update({ reset: false, invalidateAll: false }); // Re-run loads so the admin theme picks up saved colours immediately.
await update({ reset: false });
saving = ''; saving = '';
}; };
}; };

View file

@ -2,25 +2,13 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import BlockRenderer from '$shared/blocks/BlockRenderer.svelte'; import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
import type { ContentBlock } from '$lib/types'; import type { ContentBlock } from '$lib/types';
import { rootStyleTag, siteThemeVars } from '$shared/theme';
let { data } = $props(); let { data } = $props();
let blocks = $state<ContentBlock[]>([]); let blocks = $state<ContentBlock[]>([]);
let error = $state(''); let error = $state('');
onMount(() => { onMount(() => {
// Apply the site's colors so the preview matches the public site. Only
// here: these variable names overlap DaisyUI's theme (--color-primary,
// --color-accent), so setting them in the admin shell restyled the admin.
if (data.colors) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
const raw = sessionStorage.getItem('cms-preview-blocks'); const raw = sessionStorage.getItem('cms-preview-blocks');
if (!raw) return; if (!raw) return;
try { try {
@ -34,6 +22,8 @@
<svelte:head> <svelte:head>
<title>Preview</title> <title>Preview</title>
<!-- Full site colours so the draft looks like the public site. -->
{@html rootStyleTag(siteThemeVars(data.colors))}
</svelte:head> </svelte:head>
{#if blocks.length} {#if blocks.length}

View file

@ -4,7 +4,7 @@
import Header from '$lib/components/Header.svelte'; import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte'; import Footer from '$lib/components/Footer.svelte';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte'; import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { onMount } from 'svelte'; import { rootStyleTag, siteThemeVars } from '$shared/theme';
let { children, data } = $props(); let { children, data } = $props();
@ -16,23 +16,14 @@
// Keep the store in sync when layout data refreshes (e.g. after checkout // Keep the store in sync when layout data refreshes (e.g. after checkout
// clears the cookie and data.basket becomes null). // clears the cookie and data.basket becomes null).
$effect(() => basketStore.syncFrom(data.basket ?? null)); $effect(() => basketStore.syncFrom(data.basket ?? null));
onMount(() => {
if (data.colors) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
});
</script> </script>
<svelte:head> <svelte:head>
<link rel="icon" href={favicon} /> <link rel="icon" href={favicon} />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Site colours, rendered server-side (previously applied in onMount, which
flashed the defaults on every page load). Values are sanitised. -->
{@html rootStyleTag(siteThemeVars(data.colors))}
</svelte:head> </svelte:head>
<Header header={data.header} /> <Header header={data.header} />

View file

@ -0,0 +1,77 @@
import { defaultColors, type ColorsGlobal } from './types';
// Site colours (Site design → Colors) as CSS variables, rendered server-side
// into a <style> tag so pages don't flash the default colours on load.
//
// Mapping onto DaisyUI's theme: primary = site Primary, secondary = site
// Accent (so `btn-secondary` follows the site instead of DaisyUI's default
// pink), each with a text colour picked for contrast.
// Colours are admin-entered free text that ends up inside <style>, so only
// plain colour values are allowed through.
const SAFE_COLOR = /^(#[0-9a-f]{3,8}|[a-z]{3,30}|(rgb|rgba|hsl|hsla|oklch|oklab|lab|lch)\([0-9a-z.,%\s/+-]{1,60}\))$/i;
export function safeColor(value: unknown, fallback: string): string {
const color = String(value ?? '').trim();
return SAFE_COLOR.test(color) ? color : fallback;
}
function hexToRgb(hex: string): [number, number, number] | null {
let h = hex.replace('#', '');
if (h.length === 3 || h.length === 4) h = [...h.slice(0, 3)].map((c) => c + c).join('');
if (h.length !== 6 && h.length !== 8) return null;
const n = parseInt(h.slice(0, 6), 16);
return Number.isNaN(n) ? null : [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function luminance([r, g, b]: [number, number, number]) {
const lin = (c: number) => {
const s = c / 255;
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
}
const LIGHT_TEXT = '#ffffff';
const DARK_TEXT = '#1f2937';
/** White or dark text, whichever contrasts more with `color` (white if it isn't a hex colour). */
export function readableTextOn(color: string): string {
const rgb = color.startsWith('#') ? hexToRgb(color) : null;
if (!rgb) return LIGHT_TEXT;
const l = luminance(rgb);
const darkL = luminance(hexToRgb(DARK_TEXT)!);
return (1.05 / (l + 0.05)) >= (l + 0.05) / (darkL + 0.05) ? LIGHT_TEXT : DARK_TEXT;
}
/** DaisyUI brand variables only — used by the admin, whose own text/background stay neutral. */
export function brandThemeVars(colors: Partial<ColorsGlobal> | null | undefined): Record<string, string> {
const primary = safeColor(colors?.primary, defaultColors.primary);
const secondary = safeColor(colors?.accent, defaultColors.accent);
return {
'--color-primary': primary,
'--color-primary-content': readableTextOn(primary),
'--color-secondary': secondary,
'--color-secondary-content': readableTextOn(secondary)
};
}
/** Every site colour variable — public site and the admin preview. */
export function siteThemeVars(colors: Partial<ColorsGlobal> | null | undefined): Record<string, string> {
return {
'--color-bg': safeColor(colors?.background, defaultColors.background),
'--color-heading': safeColor(colors?.heading, defaultColors.heading),
'--color-subheading': safeColor(colors?.subheading, defaultColors.subheading),
'--color-text': safeColor(colors?.text, defaultColors.text),
'--color-accent': safeColor(colors?.accent, defaultColors.accent),
...brandThemeVars(colors)
};
}
/** `<style>` element setting `vars` on :root, for `{@html}` in <svelte:head>. Values are already sanitised. */
export function rootStyleTag(vars: Record<string, string>): string {
const body = Object.entries(vars)
.map(([name, value]) => `${name}:${value}`)
.join(';');
return `<style>:root{${body}}</style>`;
}