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
4 changed files with 303 additions and 188 deletions
Showing only changes of commit cfe4e2062d - Show all commits

View file

@ -1,64 +1,115 @@
<script lang="ts"> <script lang="ts">
import type { ContentBlock, EmailBlock } from '$lib/types'; import { onDestroy } from 'svelte';
import { blockLabels } from '$lib/admin/blockDefaults'; import type { ContentBlock, EmailBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults';
let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
blocks: (ContentBlock | EmailBlock)[]; let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
labels?: Record<string, string>; blocks: (ContentBlock | EmailBlock)[];
selectedId?: string; labels?: Record<string, string>;
onSelect?: (id: string) => void; selectedId?: string;
onDelete?: (id: string) => void; onSelect?: (id: string) => void;
onMove?: (from: number, to: number) => void; onDelete?: (id: string) => void;
}>(); onMove?: (from: number, to: number) => void;
}>();
let dragIndex = $state<number | null>(null);
let holdingId = $state(''); let dragIndex = $state<number | null>(null);
let holdTimer: ReturnType<typeof setTimeout> | null = null; let dropIndex = $state<number | null>(null);
let holdingId = $state('');
function startHold(id: string) { let holdTimer: ReturnType<typeof setTimeout> | null = null;
holdingId = id;
holdTimer = setTimeout(() => { // Delete is press-and-hold (1s) so a stray click can't remove a block.
const idx = blocks.findIndex((b: ContentBlock | EmailBlock) => b.id === id); // The parent picks the next selection.
onDelete(id); function startHold(id: string) {
onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || ''); endHold();
holdingId = ''; holdingId = id;
}, 1000); holdTimer = setTimeout(() => {
} holdTimer = null;
holdingId = '';
function endHold() { onDelete(id);
if (holdTimer) clearTimeout(holdTimer); }, 1000);
holdingId = ''; }
}
</script> function endHold() {
if (holdTimer) clearTimeout(holdTimer);
<div class="space-y-3"> holdTimer = null;
{#each blocks as block, i (block.id)} holdingId = '';
<div }
role="listitem"
class="rounded-box border bg-base-100 p-3 shadow-sm cursor-pointer" onDestroy(endHold);
class:border-primary={selectedId === block.id}
draggable="true" function drop(index: number) {
onclick={() => onSelect(block.id)} if (dragIndex !== null && dragIndex !== index) onMove(dragIndex, index);
ondragstart={() => (dragIndex = i)} dragIndex = null;
ondragover={(e) => e.preventDefault()} dropIndex = null;
ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }} }
>
<div class="flex items-center gap-2"> function moveBy(index: number, delta: number) {
<span class="cursor-grab text-xl text-base-content/40">☰</span> const to = index + delta;
<div class="flex-1 font-semibold">{labels[block.type] ?? block.type}</div> if (to >= 0 && to < blocks.length) onMove(index, to);
<button }
class="btn btn-xs btn-error btn-outline relative overflow-hidden" </script>
class:btn-disabled={holdingId && holdingId !== block.id}
class:delete-holding={holdingId === block.id} <ul class="space-y-2">
type="button" {#each blocks as block, i (block.id)}
onpointerdown={() => startHold(block.id)} <li
onpointerup={endHold} class="flex items-center gap-2 rounded-box border bg-base-100 p-2 pl-3 shadow-sm transition-colors {selectedId === block.id ? 'border-primary ring-1 ring-primary' : 'border-base-300 hover:border-base-content/30'}"
onpointerleave={endHold} class:opacity-50={dragIndex === i}
> class:border-dashed={dropIndex === i && dragIndex !== i}
<span class="delete-fill" class:animating={holdingId === block.id}></span> draggable="true"
<span class="relative z-10 text-error">Delete</span> ondragstart={(e) => {
</button> dragIndex = i;
</div> // Firefox won't start a drag without data.
</div> e.dataTransfer?.setData('text/plain', block.id);
{/each} if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
</div> }}
ondragover={(e) => {
e.preventDefault();
dropIndex = i;
}}
ondragleave={() => dropIndex === i && (dropIndex = null)}
ondrop={(e) => {
e.preventDefault();
drop(i);
}}
ondragend={() => {
dragIndex = null;
dropIndex = null;
}}
>
<span class="cursor-grab select-none text-lg text-base-content/40" aria-hidden="true" title="Drag to reorder">⠿</span>
<button
type="button"
class="flex-1 truncate py-1 text-left font-semibold"
aria-current={selectedId === block.id ? 'true' : undefined}
onclick={() => onSelect(block.id)}
onkeydown={(e) => {
// Keyboard reordering: Alt + ↑/↓
if (e.altKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
e.preventDefault();
moveBy(i, e.key === 'ArrowUp' ? -1 : 1);
}
}}
>
{labels[block.type] ?? block.type}
</button>
<button
class="btn btn-xs btn-error btn-outline relative overflow-hidden"
class:btn-disabled={holdingId && holdingId !== block.id}
class:delete-holding={holdingId === block.id}
type="button"
title="Hold to delete"
onpointerdown={() => startHold(block.id)}
onpointerup={endHold}
onpointerleave={endHold}
onpointercancel={endHold}
onkeydown={(e) => (e.key === 'Enter' || e.key === ' ') && !e.repeat && startHold(block.id)}
onkeyup={endHold}
>
<span class="delete-fill" class:animating={holdingId === block.id}></span>
<span class="relative z-10 text-error">Delete</span>
</button>
</li>
{:else}
<li class="rounded-box border border-dashed border-base-300 p-4 text-center text-sm text-base-content/60">No blocks yet — use “Add block”.</li>
{/each}
</ul>

View file

@ -0,0 +1,15 @@
import { beforeNavigate } from '$app/navigation';
/**
* Warn before leaving a page with unsaved edits. Call during component init.
* Form submissions are allowed through (they are the save).
*/
export function warnOnUnsavedChanges(isDirty: () => boolean) {
beforeNavigate(({ cancel, type }) => {
if (!isDirty() || type === 'form') return;
// Closing the tab/reloading: browsers only allow their own prompt,
// which `cancel()` triggers. confirm() is ignored there.
if (type === 'leave') return cancel();
if (!confirm('You have unsaved changes. Leave anyway?')) cancel();
});
}

View file

@ -1,9 +1,9 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { beforeNavigate } from '$app/navigation';
import BlockList from '$lib/admin/BlockList.svelte'; import BlockList from '$lib/admin/BlockList.svelte';
import EmailBlockEditor from '$lib/admin/editors/EmailBlockEditor.svelte'; import EmailBlockEditor from '$lib/admin/editors/EmailBlockEditor.svelte';
import { createEmailBlock, emailBlockLabels, emailBlockTypes } from '$lib/admin/emailBlockDefaults'; import { createEmailBlock, emailBlockLabels, emailBlockTypes } from '$lib/admin/emailBlockDefaults';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
import { emailPlaceholders, renderEmail, sampleEmailContext } from '$lib/email'; import { emailPlaceholders, renderEmail, sampleEmailContext } from '$lib/email';
import type { EmailBlock, EmailBlockType } from '$lib/types'; import type { EmailBlock, EmailBlockType } from '$lib/types';
@ -31,9 +31,7 @@
let rendered = $derived(renderEmail({ subject, blocks }, context)); let rendered = $derived(renderEmail({ subject, blocks }, context));
let isAlert = $derived(data.key === 'client_alert'); let isAlert = $derived(data.key === 'client_alert');
beforeNavigate(({ cancel, type }) => { warnOnUnsavedChanges(() => dirty);
if (dirty && type !== 'form' && !confirm('You have unsaved changes. Leave anyway?')) cancel();
});
function addBlock(type: EmailBlockType) { function addBlock(type: EmailBlockType) {
const block = createEmailBlock(type); const block = createEmailBlock(type);
@ -46,8 +44,9 @@
} }
function deleteBlock(id: string) { function deleteBlock(id: string) {
const index = blocks.findIndex((block) => block.id === id);
blocks = blocks.filter((block) => block.id !== id); blocks = blocks.filter((block) => block.id !== id);
if (selectedId === id) selectedId = blocks[0]?.id || ''; if (selectedId === id) selectedId = (blocks[index] ?? blocks[index - 1])?.id || '';
} }
function moveBlock(from: number, to: number) { function moveBlock(from: number, to: number) {
@ -100,24 +99,22 @@
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div> <div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if} {/if}
<div class="rounded-box space-y-4 bg-base-100 p-5 shadow"> <div class="space-y-2 rounded-box bg-base-100 p-5 shadow">
<label class="label cursor-pointer justify-start gap-3"> <label class="label cursor-pointer gap-3 text-base-content">
<input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} /> <input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} />
<span class="label-text">{enabled ? 'This email is sent automatically' : 'This email is turned off'}</span> {enabled ? 'This email is sent automatically' : 'This email is turned off'}
</label> </label>
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Subject</span></div> <span class="fieldset-legend">Subject</span>
<input class="input input-bordered w-full" name="subject" bind:value={subject} /> <input class="input w-full" name="subject" bind:value={subject} />
</label> </label>
{#if isAlert} {#if isAlert}
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Send to (comma-separated)</span></div> <span class="fieldset-legend">Send to (comma-separated)</span>
<input class="input input-bordered w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} /> <input class="input w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} />
<div class="label"> <span class="label">
<span class="label-text-alt text-base-content/60"> {#if data.settings.business.email}Leave empty to use the footer email ({data.settings.business.email}).{:else}No footer email is set — enter at least one address.{/if}
{#if data.settings.business.email}Leave empty to use the footer email ({data.settings.business.email}).{:else}No footer email is set — enter at least one address.{/if} </span>
</span>
</div>
</label> </label>
{:else} {:else}
<input type="hidden" name="recipients" value="" /> <input type="hidden" name="recipients" value="" />
@ -209,7 +206,7 @@
<input type="hidden" name="subject" value={subject} /> <input type="hidden" name="subject" value={subject} />
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} /> <input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<div class="flex flex-col gap-2 sm:flex-row"> <div class="flex flex-col gap-2 sm:flex-row">
<input class="input input-bordered flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required /> <input class="input flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required />
<button class="btn" type="submit" disabled={testing}>{testing ? 'Sending…' : 'Send test'}</button> <button class="btn" type="submit" disabled={testing}>{testing ? 'Sending…' : 'Send test'}</button>
</div> </div>
{#if form?.action === 'test' && form.message} {#if form?.action === 'test' && form.message}

View file

@ -1,104 +1,156 @@
<script lang="ts"> <script lang="ts">
import BlockList from '$lib/admin/BlockList.svelte'; import { enhance } from '$app/forms';
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults'; import BlockList from '$lib/admin/BlockList.svelte';
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte'; import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
import type { ContentBlock } from '$lib/types'; import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
let { data, form } = $props(); import type { ContentBlock } from '$lib/types';
let page = $state(data.page);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || [])); let { data, form } = $props();
let selectedId = $state(blocks[0]?.id || ''); // Local editable copies; the server data is only the starting point.
let previewMode = $state<'desktop' | 'mobile'>('desktop'); let slug = $state(data.page.slug);
let showPreview = $state(false); let title = $state(data.page.title);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null); let selectedId = $state(data.page.blocks?.[0]?.id || '');
let published = $derived(data.page.published);
function addBlock(type: keyof typeof blockLabels) { let previewMode = $state<'desktop' | 'mobile'>('desktop');
const block = createBlock(type); let showPreview = $state(false);
blocks = [...blocks, block]; let saving = $state<'' | 'save' | 'publish'>('');
selectedId = block.id;
} const serialize = () => JSON.stringify({ slug, title, blocks });
let savedSnapshot = $state(serialize());
function updateBlock(updated: ContentBlock) { let dirty = $derived(serialize() !== savedSnapshot);
blocks = blocks.map((block) => (block.id === updated.id ? updated : block)); warnOnUnsavedChanges(() => dirty);
}
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
function deleteBlock(id: string) {
blocks = blocks.filter((block) => block.id !== id); function addBlock(type: keyof typeof blockLabels) {
if (selectedId === id) selectedId = blocks[0]?.id || ''; const block = createBlock(type);
} blocks = [...blocks, block];
selectedId = block.id;
function moveBlock(from: number, to: number) { (document.activeElement as HTMLElement | null)?.blur(); // close the dropdown
const copy = [...blocks]; }
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item); function updateBlock(updated: ContentBlock) {
blocks = copy; blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
} }
function openPreview() { function deleteBlock(id: string) {
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks)); const index = blocks.findIndex((block) => block.id === id);
showPreview = true; blocks = blocks.filter((block) => block.id !== id);
} if (selectedId === id) selectedId = (blocks[index] ?? blocks[index - 1])?.id || '';
}
function markPublish(event: MouseEvent) {
const form = (event.currentTarget as HTMLButtonElement).form; function moveBlock(from: number, to: number) {
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null; const copy = [...blocks];
if (input) input.value = 'true'; const [item] = copy.splice(from, 1);
} copy.splice(to, 0, item);
</script> blocks = copy;
}
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
function openPreview() {
<form method="POST" action="?/save" class="space-y-6"> sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
<input type="hidden" name="id" value={page.id} /> showPreview = true;
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} /> }
<input type="hidden" name="publish" value="false" /> </script>
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <svelte:head><title>Edit {title || 'page'} | CMS</title></svelte:head>
<div>
<h1 class="text-3xl font-bold">Edit page</h1> <svelte:window onkeydown={(e) => showPreview && e.key === 'Escape' && (showPreview = false)} />
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
</div> <form
<div class="flex flex-wrap gap-2"> method="POST"
<button class="btn" type="button" onclick={openPreview}>Preview</button> action="?/save"
<button class="btn btn-outline" type="submit">Save draft</button> class="space-y-6"
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button> use:enhance={({ submitter }) => {
</div> saving = submitter?.getAttribute('value') === 'publish' ? 'publish' : 'save';
</div> return async ({ result, update }) => {
await update({ reset: false });
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if} saving = '';
if (result.type === 'success' || result.type === 'redirect') {
<div class="grid gap-4 md:grid-cols-2"> // Adopt what the server stored (it normalises the slug).
<label class="form-control w-full"><div class="label"><span class="label-text">Slug</span></div><input class="input input-bordered w-full" name="slug" bind:value={page.slug} /></label> slug = data.page.slug;
<label class="form-control w-full"><div class="label"><span class="label-text">Title</span></div><input class="input input-bordered w-full" name="title" bind:value={page.title} /></label> title = data.page.title;
</div> savedSnapshot = serialize();
}
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]"> };
<aside class="space-y-4"> }}
<div class="rounded-box bg-base-100 p-4 shadow"> >
<div class="dropdown w-full"> <input type="hidden" name="id" value={data.page.id} />
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button> <input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each blockTypes as type} <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li> <div>
{/each} <a class="link link-hover text-sm text-base-content/60" href="/pages">← Pages</a>
</ul> <div class="flex flex-wrap items-center gap-3">
</div> <h1 class="text-3xl font-bold">Edit page</h1>
</div> <span class="badge" class:badge-success={published}>{published ? 'Published' : 'Draft'}</span>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} /> </div>
</aside> <p class="text-base-content/60">
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} /> {published ? 'This page is live — saved changes appear on the site immediately.' : 'Not visible on the site until you publish it.'}
</div> </p>
</form> </div>
<div class="flex flex-wrap items-center gap-2">
{#if showPreview} {#if dirty}<span class="badge badge-warning">Unsaved changes</span>{/if}
<div class="fixed inset-0 z-50 bg-black/60 p-4"> <button class="btn" type="button" onclick={openPreview}>Preview</button>
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl"> <button class="btn btn-outline" type="submit" name="intent" value="save" disabled={saving !== ''}>
<div class="mb-3 flex items-center justify-between gap-3"> {#if saving === 'save'}<span class="loading loading-spinner loading-sm"></span>{/if}
<div class="join"><button class="btn join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button><button class="btn join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button></div> {published ? 'Save' : 'Save draft'}
<button class="btn" onclick={() => (showPreview = false)}>Close</button> </button>
</div> {#if !published}
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe> <button class="btn btn-primary" type="submit" name="intent" value="publish" disabled={saving !== ''}>
</div> {#if saving === 'publish'}<span class="loading loading-spinner loading-sm"></span>{/if}
</div> Save & publish
{/if} </button>
{/if}
</div>
</div>
{#if form?.message}
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok} role="status">{form.message}</div>
{/if}
<div class="grid gap-4 rounded-box bg-base-100 p-5 shadow md:grid-cols-2">
<label class="fieldset py-0">
<span class="fieldset-legend">Title</span>
<input class="input w-full" name="title" required bind:value={title} />
</label>
<label class="fieldset py-0">
<span class="fieldset-legend">Slug</span>
<input class="input w-full font-mono" name="slug" required bind:value={slug} />
</label>
</div>
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
<aside class="space-y-4">
<div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full">
<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">
{#each blockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li>
{/each}
</ul>
</div>
</div>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside>
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} />
</div>
</form>
{#if showPreview}
<div class="fixed inset-0 z-50 bg-black/60 p-4" role="dialog" aria-modal="true" aria-label="Page preview">
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl">
<div class="mb-3 flex items-center justify-between gap-3">
<div class="join">
<button class="btn btn-sm join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button>
<button class="btn btn-sm join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button>
</div>
<p class="hidden text-sm text-base-content/60 sm:block">Unsaved draft preview</p>
<button class="btn btn-sm" onclick={() => (showPreview = false)}>Close</button>
</div>
<iframe class="mx-auto h-full rounded-box border border-base-300" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
</div>
</div>
{/if}