added reverse proxy
This commit is contained in:
parent
afd7fd7686
commit
246b1990ca
57 changed files with 4174 additions and 4139 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = ({ locals }) => {
|
||||
return { user: locals.user };
|
||||
};
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
export const load: LayoutServerLoad = ({ locals }) => {
|
||||
return { user: locals.user };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,94 +1,94 @@
|
|||
<script lang="ts">
|
||||
let { children } = $props();
|
||||
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
|
||||
let importing = $state(false);
|
||||
|
||||
async function handleExport() {
|
||||
try {
|
||||
const res = await fetch('/admin/api/export');
|
||||
if (!res.ok) throw new Error(`Export failed (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
importing = true;
|
||||
importStatus = null;
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
const res = await fetch('/admin/api/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(json)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Import failed (${res.status})`);
|
||||
}
|
||||
const result = await res.json();
|
||||
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
|
||||
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
|
||||
setTimeout(() => location.reload(), 1500);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
} finally {
|
||||
importing = false;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="min-h-screen bg-base-200">
|
||||
<div class="navbar bg-base-100 shadow-sm">
|
||||
<div class="flex-1">
|
||||
<a class="btn btn-ghost text-xl" href="/admin/pages">Massage CMS</a>
|
||||
</div>
|
||||
<div class="flex-none gap-2">
|
||||
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
|
||||
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a>
|
||||
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
|
||||
<div class="dropdown dropdown-end">
|
||||
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
|
||||
Export/Import
|
||||
</button>
|
||||
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
|
||||
<li><button type="button" onclick={handleExport}>Export all</button></li>
|
||||
<li>
|
||||
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
|
||||
{importing ? 'Importing…' : 'Import'}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
|
||||
<form class="inline" method="POST" action="/admin/login?/logout">
|
||||
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{#if importStatus}
|
||||
<div class="mx-auto max-w-7xl px-4 pt-2">
|
||||
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
|
||||
{importStatus.message}
|
||||
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
<script lang="ts">
|
||||
let { children } = $props();
|
||||
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
|
||||
let importing = $state(false);
|
||||
|
||||
async function handleExport() {
|
||||
try {
|
||||
const res = await fetch('/admin/api/export');
|
||||
if (!res.ok) throw new Error(`Export failed (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
importing = true;
|
||||
importStatus = null;
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
const res = await fetch('/admin/api/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(json)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Import failed (${res.status})`);
|
||||
}
|
||||
const result = await res.json();
|
||||
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
|
||||
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
|
||||
setTimeout(() => location.reload(), 1500);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
} finally {
|
||||
importing = false;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="min-h-screen bg-base-200">
|
||||
<div class="navbar bg-base-100 shadow-sm">
|
||||
<div class="flex-1">
|
||||
<a class="btn btn-ghost text-xl" href="/admin/pages">Massage CMS</a>
|
||||
</div>
|
||||
<div class="flex-none gap-2">
|
||||
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
|
||||
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a>
|
||||
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
|
||||
<div class="dropdown dropdown-end">
|
||||
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
|
||||
Export/Import
|
||||
</button>
|
||||
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
|
||||
<li><button type="button" onclick={handleExport}>Export all</button></li>
|
||||
<li>
|
||||
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
|
||||
{importing ? 'Importing…' : 'Import'}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
|
||||
<form class="inline" method="POST" action="/admin/login?/logout">
|
||||
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{#if importStatus}
|
||||
<div class="mx-auto max-w-7xl px-4 pt-2">
|
||||
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
|
||||
{importStatus.message}
|
||||
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,89 +1,89 @@
|
|||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
extractImageUrls,
|
||||
fetchImageAsBase64,
|
||||
replaceUrlsWithKeys,
|
||||
urlToKey,
|
||||
type SiteExport
|
||||
} from '$lib/exportImport';
|
||||
import { normalizeEvent } from '$lib/calendar';
|
||||
|
||||
export const GET: RequestHandler = async ({ locals }) => {
|
||||
// Fetch all pages
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
|
||||
// Fetch all globals
|
||||
const globals = await locals.pb.collection('globals').getFullList();
|
||||
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
|
||||
// Collect all image URLs from pages and globals
|
||||
const allUrls = new Set<string>();
|
||||
for (const page of pages) {
|
||||
for (const url of extractImageUrls(page)) allUrls.add(url);
|
||||
}
|
||||
for (const g of globals) {
|
||||
for (const url of extractImageUrls(g)) allUrls.add(url);
|
||||
}
|
||||
|
||||
// Fetch each image as base64
|
||||
const images: Record<string, string> = {};
|
||||
for (const url of allUrls) {
|
||||
try {
|
||||
const key = urlToKey(url);
|
||||
images[key] = await fetchImageAsBase64(url);
|
||||
} catch (e) {
|
||||
console.warn(`Could not fetch image: ${url}`, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Build URL → key mapping
|
||||
const urlToKeyMap = new Map<string, string>();
|
||||
for (const url of allUrls) {
|
||||
urlToKeyMap.set(url, urlToKey(url));
|
||||
}
|
||||
|
||||
// Replace URLs with placeholders in pages
|
||||
const exportPages = pages.map((p) => ({
|
||||
slug: p.slug,
|
||||
title: p.title,
|
||||
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
|
||||
published: p.published
|
||||
}));
|
||||
|
||||
// Replace URLs with placeholders in globals
|
||||
const exportGlobals = globals.map((g) => ({
|
||||
key: g.key,
|
||||
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
|
||||
}));
|
||||
|
||||
const exportEvents = events.map((record) => {
|
||||
const event = normalizeEvent(record);
|
||||
return {
|
||||
name: event.name,
|
||||
start: event.start,
|
||||
end: event.end,
|
||||
description: event.description,
|
||||
color: event.color,
|
||||
link: event.link,
|
||||
categories: event.categories,
|
||||
published: event.published,
|
||||
allDay: event.allDay
|
||||
};
|
||||
});
|
||||
|
||||
const exportData: SiteExport = {
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
pages: exportPages,
|
||||
globals: exportGlobals,
|
||||
events: exportEvents,
|
||||
images
|
||||
};
|
||||
|
||||
return json(exportData, {
|
||||
headers: {
|
||||
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
|
||||
}
|
||||
});
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
extractImageUrls,
|
||||
fetchImageAsBase64,
|
||||
replaceUrlsWithKeys,
|
||||
urlToKey,
|
||||
type SiteExport
|
||||
} from '$lib/exportImport';
|
||||
import { normalizeEvent } from '$lib/calendar';
|
||||
|
||||
export const GET: RequestHandler = async ({ locals }) => {
|
||||
// Fetch all pages
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
|
||||
// Fetch all globals
|
||||
const globals = await locals.pb.collection('globals').getFullList();
|
||||
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
|
||||
// Collect all image URLs from pages and globals
|
||||
const allUrls = new Set<string>();
|
||||
for (const page of pages) {
|
||||
for (const url of extractImageUrls(page)) allUrls.add(url);
|
||||
}
|
||||
for (const g of globals) {
|
||||
for (const url of extractImageUrls(g)) allUrls.add(url);
|
||||
}
|
||||
|
||||
// Fetch each image as base64
|
||||
const images: Record<string, string> = {};
|
||||
for (const url of allUrls) {
|
||||
try {
|
||||
const key = urlToKey(url);
|
||||
images[key] = await fetchImageAsBase64(url);
|
||||
} catch (e) {
|
||||
console.warn(`Could not fetch image: ${url}`, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Build URL → key mapping
|
||||
const urlToKeyMap = new Map<string, string>();
|
||||
for (const url of allUrls) {
|
||||
urlToKeyMap.set(url, urlToKey(url));
|
||||
}
|
||||
|
||||
// Replace URLs with placeholders in pages
|
||||
const exportPages = pages.map((p) => ({
|
||||
slug: p.slug,
|
||||
title: p.title,
|
||||
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
|
||||
published: p.published
|
||||
}));
|
||||
|
||||
// Replace URLs with placeholders in globals
|
||||
const exportGlobals = globals.map((g) => ({
|
||||
key: g.key,
|
||||
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
|
||||
}));
|
||||
|
||||
const exportEvents = events.map((record) => {
|
||||
const event = normalizeEvent(record);
|
||||
return {
|
||||
name: event.name,
|
||||
start: event.start,
|
||||
end: event.end,
|
||||
description: event.description,
|
||||
color: event.color,
|
||||
link: event.link,
|
||||
categories: event.categories,
|
||||
published: event.published,
|
||||
allDay: event.allDay
|
||||
};
|
||||
});
|
||||
|
||||
const exportData: SiteExport = {
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
pages: exportPages,
|
||||
globals: exportGlobals,
|
||||
events: exportEvents,
|
||||
images
|
||||
};
|
||||
|
||||
return json(exportData, {
|
||||
headers: {
|
||||
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
|
||||
}
|
||||
});
|
||||
};
|
||||
|
|
@ -1,140 +1,140 @@
|
|||
import { env } from '$env/dynamic/public';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
dataUriToFile,
|
||||
restorePlaceholders,
|
||||
type SiteExport
|
||||
} from '$lib/exportImport';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const body = (await request.json()) as SiteExport;
|
||||
|
||||
if (!body || body.version !== 1) {
|
||||
throw error(400, 'Invalid or unsupported export file.');
|
||||
}
|
||||
|
||||
const results = {
|
||||
imagesUploaded: 0,
|
||||
pagesImported: 0,
|
||||
globalsImported: 0,
|
||||
eventsImported: 0,
|
||||
errors: [] as string[]
|
||||
};
|
||||
|
||||
// 1. Upload images to PocketBase media collection
|
||||
// Build a map: placeholder key → new PocketBase URL
|
||||
const keyToUrl = new Map<string, string>();
|
||||
|
||||
for (const [key, dataUri] of Object.entries(body.images)) {
|
||||
try {
|
||||
// Derive a filename from the key (e.g. "abc12345_logo.png")
|
||||
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
|
||||
const file = dataUriToFile(dataUri, filename);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||
|
||||
const record = await locals.pb.collection('media').create(formData);
|
||||
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
|
||||
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||
|
||||
keyToUrl.set(key, newUrl);
|
||||
results.imagesUploaded++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Import pages
|
||||
for (const page of body.pages) {
|
||||
try {
|
||||
const blocks = restorePlaceholders(page.blocks, keyToUrl);
|
||||
|
||||
// Try to find existing page by slug
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('pages').update(existing.id, {
|
||||
title: page.title,
|
||||
blocks,
|
||||
published: page.published
|
||||
});
|
||||
} else {
|
||||
await locals.pb.collection('pages').create({
|
||||
slug: page.slug,
|
||||
title: page.title,
|
||||
blocks,
|
||||
published: page.published
|
||||
});
|
||||
}
|
||||
results.pagesImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Import globals
|
||||
for (const g of body.globals) {
|
||||
try {
|
||||
const data = restorePlaceholders(g.data, keyToUrl);
|
||||
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('globals').update(existing.id, { data });
|
||||
} else {
|
||||
await locals.pb.collection('globals').create({ key: g.key, data });
|
||||
}
|
||||
results.globalsImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Import events
|
||||
for (const event of body.events || []) {
|
||||
try {
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: event.name,
|
||||
start: event.start,
|
||||
end: event.end || null,
|
||||
description: event.description || '',
|
||||
color: event.color || '#8a9a7b',
|
||||
link: event.link || '',
|
||||
categories: event.categories || [],
|
||||
published: Boolean(event.published),
|
||||
allDay: event.allDay !== false
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('events').update(existing.id, payload);
|
||||
} else {
|
||||
await locals.pb.collection('events').create(payload);
|
||||
}
|
||||
results.eventsImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return json(results);
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
dataUriToFile,
|
||||
restorePlaceholders,
|
||||
type SiteExport
|
||||
} from '$lib/exportImport';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const body = (await request.json()) as SiteExport;
|
||||
|
||||
if (!body || body.version !== 1) {
|
||||
throw error(400, 'Invalid or unsupported export file.');
|
||||
}
|
||||
|
||||
const results = {
|
||||
imagesUploaded: 0,
|
||||
pagesImported: 0,
|
||||
globalsImported: 0,
|
||||
eventsImported: 0,
|
||||
errors: [] as string[]
|
||||
};
|
||||
|
||||
// 1. Upload images to PocketBase media collection
|
||||
// Build a map: placeholder key → new PocketBase URL
|
||||
const keyToUrl = new Map<string, string>();
|
||||
|
||||
for (const [key, dataUri] of Object.entries(body.images)) {
|
||||
try {
|
||||
// Derive a filename from the key (e.g. "abc12345_logo.png")
|
||||
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
|
||||
const file = dataUriToFile(dataUri, filename);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||
|
||||
const record = await locals.pb.collection('media').create(formData);
|
||||
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080';
|
||||
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||
|
||||
keyToUrl.set(key, newUrl);
|
||||
results.imagesUploaded++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Import pages
|
||||
for (const page of body.pages) {
|
||||
try {
|
||||
const blocks = restorePlaceholders(page.blocks, keyToUrl);
|
||||
|
||||
// Try to find existing page by slug
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('pages').update(existing.id, {
|
||||
title: page.title,
|
||||
blocks,
|
||||
published: page.published
|
||||
});
|
||||
} else {
|
||||
await locals.pb.collection('pages').create({
|
||||
slug: page.slug,
|
||||
title: page.title,
|
||||
blocks,
|
||||
published: page.published
|
||||
});
|
||||
}
|
||||
results.pagesImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Import globals
|
||||
for (const g of body.globals) {
|
||||
try {
|
||||
const data = restorePlaceholders(g.data, keyToUrl);
|
||||
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('globals').update(existing.id, { data });
|
||||
} else {
|
||||
await locals.pb.collection('globals').create({ key: g.key, data });
|
||||
}
|
||||
results.globalsImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Import events
|
||||
for (const event of body.events || []) {
|
||||
try {
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: event.name,
|
||||
start: event.start,
|
||||
end: event.end || null,
|
||||
description: event.description || '',
|
||||
color: event.color || '#8a9a7b',
|
||||
link: event.link || '',
|
||||
categories: event.categories || [],
|
||||
published: Boolean(event.published),
|
||||
allDay: event.allDay !== false
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('events').update(existing.id, payload);
|
||||
} else {
|
||||
await locals.pb.collection('events').create(payload);
|
||||
}
|
||||
results.eventsImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return json(results);
|
||||
};
|
||||
|
|
@ -1,27 +1,27 @@
|
|||
import { env } from '$env/dynamic/public';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
const alt = formData.get('alt') as string | null;
|
||||
|
||||
if (!file) {
|
||||
throw error(400, 'No file provided');
|
||||
}
|
||||
|
||||
const uploadForm = new FormData();
|
||||
uploadForm.append('file', file);
|
||||
if (alt) uploadForm.append('alt', alt);
|
||||
|
||||
try {
|
||||
const record = await locals.pb.collection('media').create(uploadForm);
|
||||
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
|
||||
const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||
return json({ record, url });
|
||||
} catch (e) {
|
||||
console.error('Media upload error:', e);
|
||||
throw error(500, 'Upload failed');
|
||||
}
|
||||
};
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
const alt = formData.get('alt') as string | null;
|
||||
|
||||
if (!file) {
|
||||
throw error(400, 'No file provided');
|
||||
}
|
||||
|
||||
const uploadForm = new FormData();
|
||||
uploadForm.append('file', file);
|
||||
if (alt) uploadForm.append('alt', alt);
|
||||
|
||||
try {
|
||||
const record = await locals.pb.collection('media').create(uploadForm);
|
||||
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080';
|
||||
const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||
return json({ record, url });
|
||||
} catch (e) {
|
||||
console.error('Media upload error:', e);
|
||||
throw error(500, 'Upload failed');
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,54 +1,54 @@
|
|||
import { fail } from '@sveltejs/kit';
|
||||
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
function eventPayload(data: FormData) {
|
||||
const allDay = String(data.get('allDay')) === 'true';
|
||||
const start = String(data.get('start') || '').trim();
|
||||
const end = String(data.get('end') || '').trim();
|
||||
const name = String(data.get('name') || '').trim();
|
||||
|
||||
return {
|
||||
name,
|
||||
start: dateInputToPocketBase(start, allDay),
|
||||
end: end ? dateInputToPocketBase(end, allDay) : null,
|
||||
description: String(data.get('description') || '').trim(),
|
||||
color: String(data.get('color') || '#8a9a7b').trim(),
|
||||
link: String(data.get('link') || '').trim(),
|
||||
categories: normalizeCategories(String(data.get('categories') || '')),
|
||||
published: String(data.get('published')) === 'true',
|
||||
allDay
|
||||
};
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
const events = records.map((record) => normalizeEvent(record));
|
||||
return { events };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const payload = eventPayload(data);
|
||||
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
|
||||
await locals.pb.collection('events').create(payload);
|
||||
return { ok: true };
|
||||
},
|
||||
update: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
const payload = eventPayload(data);
|
||||
if (!id) return fail(400, { message: 'Event id is required.' });
|
||||
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
|
||||
await locals.pb.collection('events').update(id, payload);
|
||||
return { ok: true };
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
if (!id) return fail(400, { message: 'Event id is required.' });
|
||||
await locals.pb.collection('events').delete(id);
|
||||
return { ok: true };
|
||||
}
|
||||
};
|
||||
import { fail } from '@sveltejs/kit';
|
||||
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
function eventPayload(data: FormData) {
|
||||
const allDay = String(data.get('allDay')) === 'true';
|
||||
const start = String(data.get('start') || '').trim();
|
||||
const end = String(data.get('end') || '').trim();
|
||||
const name = String(data.get('name') || '').trim();
|
||||
|
||||
return {
|
||||
name,
|
||||
start: dateInputToPocketBase(start, allDay),
|
||||
end: end ? dateInputToPocketBase(end, allDay) : null,
|
||||
description: String(data.get('description') || '').trim(),
|
||||
color: String(data.get('color') || '#8a9a7b').trim(),
|
||||
link: String(data.get('link') || '').trim(),
|
||||
categories: normalizeCategories(String(data.get('categories') || '')),
|
||||
published: String(data.get('published')) === 'true',
|
||||
allDay
|
||||
};
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
const events = records.map((record) => normalizeEvent(record));
|
||||
return { events };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const payload = eventPayload(data);
|
||||
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
|
||||
await locals.pb.collection('events').create(payload);
|
||||
return { ok: true };
|
||||
},
|
||||
update: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
const payload = eventPayload(data);
|
||||
if (!id) return fail(400, { message: 'Event id is required.' });
|
||||
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
|
||||
await locals.pb.collection('events').update(id, payload);
|
||||
return { ok: true };
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
if (!id) return fail(400, { message: 'Event id is required.' });
|
||||
await locals.pb.collection('events').delete(id);
|
||||
return { ok: true };
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,236 +1,236 @@
|
|||
<script lang="ts">
|
||||
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar';
|
||||
import type { CalendarEventRecord } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let events = $derived(sortEvents(data.events || []));
|
||||
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
|
||||
let showEditor = $state(false);
|
||||
let draft = $state<CalendarEventRecord>({
|
||||
id: '',
|
||||
name: '',
|
||||
start: toDateInput(new Date().toISOString()),
|
||||
end: '',
|
||||
description: '',
|
||||
color: '#8a9a7b',
|
||||
link: '',
|
||||
categories: [],
|
||||
published: false,
|
||||
allDay: true
|
||||
});
|
||||
let categoryText = $state('');
|
||||
|
||||
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
let month = $derived(createCalendarMonth(viewDate));
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
|
||||
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start));
|
||||
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end));
|
||||
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
|
||||
|
||||
function eventsForDay(date: Date) {
|
||||
return events.filter((event) => eventOverlapsDay(event, date));
|
||||
}
|
||||
|
||||
function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
|
||||
return {
|
||||
id: '',
|
||||
name: '',
|
||||
start,
|
||||
end: '',
|
||||
description: '',
|
||||
color: '#8a9a7b',
|
||||
link: '',
|
||||
categories: [],
|
||||
published: false,
|
||||
allDay: true
|
||||
};
|
||||
}
|
||||
|
||||
function createEvent(start?: string) {
|
||||
draft = emptyDraft(start);
|
||||
categoryText = '';
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editEvent(event: CalendarEventRecord) {
|
||||
draft = structuredClone(event);
|
||||
categoryText = event.categories.join(', ');
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function previousMonth() {
|
||||
viewDate = addMonths(viewDate, -1);
|
||||
}
|
||||
|
||||
function nextMonth() {
|
||||
viewDate = addMonths(viewDate, 1);
|
||||
}
|
||||
|
||||
function addCategory(category: string) {
|
||||
if (!category || draft.categories.includes(category)) return;
|
||||
draft = { ...draft, categories: [...draft.categories, category] };
|
||||
categoryText = draft.categories.join(', ');
|
||||
}
|
||||
|
||||
function removeCategory(category: string) {
|
||||
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
|
||||
categoryText = draft.categories.join(', ');
|
||||
}
|
||||
|
||||
function syncCategoryText(value: string) {
|
||||
categoryText = value;
|
||||
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Calendar | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Calendar</h1>
|
||||
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
|
||||
<h2 class="text-2xl font-bold">{month.label}</h2>
|
||||
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
|
||||
{#each weekdays as weekday}<div>{weekday}</div>{/each}
|
||||
</div>
|
||||
<div class="mt-2 grid grid-cols-7 gap-2">
|
||||
{#each month.days as day}
|
||||
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
|
||||
<button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
|
||||
<div class="space-y-1">
|
||||
{#each eventsForDay(day.date) as event}
|
||||
<button class="w-full rounded-lg px-2 py-1 text-left text-xs font-semibold text-white shadow" style={`background:${event.color || '#8a9a7b'}`} type="button" onclick={() => editEvent(event)}>
|
||||
<span class="block truncate">{event.name}</span>
|
||||
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<h2 class="mb-4 text-xl font-bold">All events</h2>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each events as event}
|
||||
<tr>
|
||||
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
|
||||
<td>{formatEventDateRange(event)}</td>
|
||||
<td>{event.categories.join(', ')}</td>
|
||||
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showEditor}
|
||||
<div class="fixed inset-0 z-50 bg-black/50 p-4">
|
||||
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
|
||||
<div class="mb-4 flex items-center justify-between gap-3">
|
||||
<h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2>
|
||||
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
|
||||
</div>
|
||||
|
||||
<form method="POST" action={action} class="space-y-4">
|
||||
<input type="hidden" name="id" value={draft.id} />
|
||||
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
|
||||
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
|
||||
<input type="hidden" name="categories" value={categoryText} />
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Name</span></div>
|
||||
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Start</span></div>
|
||||
<input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">End optional</span></div>
|
||||
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
|
||||
<span class="label-text">All-day event</span>
|
||||
</label>
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
|
||||
<span class="label-text">Published</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Description</span></div>
|
||||
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Color</span></div>
|
||||
<div class="flex gap-2">
|
||||
<input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} />
|
||||
<input class="input input-bordered flex-1" name="color" bind:value={draft.color} />
|
||||
</div>
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Link optional</span></div>
|
||||
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Categories comma-separated</span></div>
|
||||
<input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
|
||||
</label>
|
||||
{#if allCategories.length}
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
{#each allCategories as category}
|
||||
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-between gap-2 pt-2">
|
||||
{#if draft.id}
|
||||
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Save event</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<script lang="ts">
|
||||
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar';
|
||||
import type { CalendarEventRecord } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let events = $derived(sortEvents(data.events || []));
|
||||
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
|
||||
let showEditor = $state(false);
|
||||
let draft = $state<CalendarEventRecord>({
|
||||
id: '',
|
||||
name: '',
|
||||
start: toDateInput(new Date().toISOString()),
|
||||
end: '',
|
||||
description: '',
|
||||
color: '#8a9a7b',
|
||||
link: '',
|
||||
categories: [],
|
||||
published: false,
|
||||
allDay: true
|
||||
});
|
||||
let categoryText = $state('');
|
||||
|
||||
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
let month = $derived(createCalendarMonth(viewDate));
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
|
||||
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start));
|
||||
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end));
|
||||
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
|
||||
|
||||
function eventsForDay(date: Date) {
|
||||
return events.filter((event) => eventOverlapsDay(event, date));
|
||||
}
|
||||
|
||||
function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
|
||||
return {
|
||||
id: '',
|
||||
name: '',
|
||||
start,
|
||||
end: '',
|
||||
description: '',
|
||||
color: '#8a9a7b',
|
||||
link: '',
|
||||
categories: [],
|
||||
published: false,
|
||||
allDay: true
|
||||
};
|
||||
}
|
||||
|
||||
function createEvent(start?: string) {
|
||||
draft = emptyDraft(start);
|
||||
categoryText = '';
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editEvent(event: CalendarEventRecord) {
|
||||
draft = structuredClone(event);
|
||||
categoryText = event.categories.join(', ');
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function previousMonth() {
|
||||
viewDate = addMonths(viewDate, -1);
|
||||
}
|
||||
|
||||
function nextMonth() {
|
||||
viewDate = addMonths(viewDate, 1);
|
||||
}
|
||||
|
||||
function addCategory(category: string) {
|
||||
if (!category || draft.categories.includes(category)) return;
|
||||
draft = { ...draft, categories: [...draft.categories, category] };
|
||||
categoryText = draft.categories.join(', ');
|
||||
}
|
||||
|
||||
function removeCategory(category: string) {
|
||||
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
|
||||
categoryText = draft.categories.join(', ');
|
||||
}
|
||||
|
||||
function syncCategoryText(value: string) {
|
||||
categoryText = value;
|
||||
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Calendar | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Calendar</h1>
|
||||
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
|
||||
<h2 class="text-2xl font-bold">{month.label}</h2>
|
||||
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
|
||||
{#each weekdays as weekday}<div>{weekday}</div>{/each}
|
||||
</div>
|
||||
<div class="mt-2 grid grid-cols-7 gap-2">
|
||||
{#each month.days as day}
|
||||
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
|
||||
<button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
|
||||
<div class="space-y-1">
|
||||
{#each eventsForDay(day.date) as event}
|
||||
<button class="w-full rounded-lg px-2 py-1 text-left text-xs font-semibold text-white shadow" style={`background:${event.color || '#8a9a7b'}`} type="button" onclick={() => editEvent(event)}>
|
||||
<span class="block truncate">{event.name}</span>
|
||||
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<h2 class="mb-4 text-xl font-bold">All events</h2>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each events as event}
|
||||
<tr>
|
||||
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
|
||||
<td>{formatEventDateRange(event)}</td>
|
||||
<td>{event.categories.join(', ')}</td>
|
||||
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showEditor}
|
||||
<div class="fixed inset-0 z-50 bg-black/50 p-4">
|
||||
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
|
||||
<div class="mb-4 flex items-center justify-between gap-3">
|
||||
<h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2>
|
||||
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
|
||||
</div>
|
||||
|
||||
<form method="POST" action={action} class="space-y-4">
|
||||
<input type="hidden" name="id" value={draft.id} />
|
||||
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
|
||||
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
|
||||
<input type="hidden" name="categories" value={categoryText} />
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Name</span></div>
|
||||
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Start</span></div>
|
||||
<input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">End optional</span></div>
|
||||
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
|
||||
<span class="label-text">All-day event</span>
|
||||
</label>
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
|
||||
<span class="label-text">Published</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Description</span></div>
|
||||
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Color</span></div>
|
||||
<div class="flex gap-2">
|
||||
<input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} />
|
||||
<input class="input input-bordered flex-1" name="color" bind:value={draft.color} />
|
||||
</div>
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Link optional</span></div>
|
||||
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Categories comma-separated</span></div>
|
||||
<input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
|
||||
</label>
|
||||
{#if allCategories.length}
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
{#each allCategories as category}
|
||||
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-between gap-2 pt-2">
|
||||
{#if draft.id}
|
||||
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Save event</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
|||
|
|
@ -1,31 +1,31 @@
|
|||
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
||||
try {
|
||||
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
|
||||
} catch {
|
||||
return await pb.collection('globals').create({ key, data: fallback });
|
||||
}
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const [header, footer, colors] = await Promise.all([
|
||||
getGlobal(locals.pb, 'header', defaultHeader),
|
||||
getGlobal(locals.pb, 'footer', defaultFooter),
|
||||
getGlobal(locals.pb, 'colors', defaultColors)
|
||||
]);
|
||||
|
||||
// Fetch all pages for the home page selector
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
|
||||
return { header, footer, colors, pages };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
save: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id'));
|
||||
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) });
|
||||
}
|
||||
};
|
||||
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
||||
try {
|
||||
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
|
||||
} catch {
|
||||
return await pb.collection('globals').create({ key, data: fallback });
|
||||
}
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const [header, footer, colors] = await Promise.all([
|
||||
getGlobal(locals.pb, 'header', defaultHeader),
|
||||
getGlobal(locals.pb, 'footer', defaultFooter),
|
||||
getGlobal(locals.pb, 'colors', defaultColors)
|
||||
]);
|
||||
|
||||
// Fetch all pages for the home page selector
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
|
||||
return { header, footer, colors, pages };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
save: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id'));
|
||||
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) });
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,96 +1,96 @@
|
|||
<script lang="ts">
|
||||
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
let header = $state(structuredClone(data.header.data));
|
||||
let footer = $state(structuredClone(data.footer.data));
|
||||
let colors = $state(structuredClone(data.colors.data));
|
||||
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
|
||||
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Globals | CMS</title></svelte:head>
|
||||
|
||||
<div class="mb-6">
|
||||
<h1 class="text-3xl font-bold">Global sections</h1>
|
||||
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 xl:grid-cols-3">
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.header.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(header)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Header</h2>
|
||||
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
|
||||
<h3 class="mt-6 font-bold">Navigation</h3>
|
||||
{#each header.navLinks || [] as link, i}
|
||||
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
|
||||
<input class="input input-bordered" bind:value={link.label} placeholder="Label" />
|
||||
<input class="input input-bordered" bind:value={link.href} placeholder="Href" />
|
||||
<button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button>
|
||||
<h3 class="mt-6 font-bold">CTA button</h3>
|
||||
<input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" />
|
||||
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
|
||||
<h3 class="mt-6 font-bold">Home page</h3>
|
||||
<select class="select select-bordered w-full" bind:value={header.homePage}>
|
||||
<option value="">— Select a page —</option>
|
||||
{#each data.pages as page}
|
||||
<option value={page.slug}>{page.title} [{page.slug}]</option>
|
||||
{/each}
|
||||
</select>
|
||||
<p class="text-sm text-base-content/60 mt-1">The page that "/" will redirect to.</p>
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save header</button>
|
||||
</form>
|
||||
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.footer.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(footer)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Footer</h2>
|
||||
{#each ['businessName', 'tagline', 'address', 'phone', 'email', 'copyrightText'] as field}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">{field}</span></div>
|
||||
<input class="input input-bordered w-full" bind:value={footer[field]} />
|
||||
</label>
|
||||
{/each}
|
||||
<h3 class="mt-6 font-bold">Social links</h3>
|
||||
{#each footer.socialLinks || [] as link, i}
|
||||
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
|
||||
<input class="input input-bordered" bind:value={link.platform} placeholder="Platform" />
|
||||
<input class="input input-bordered" bind:value={link.url} placeholder="URL" />
|
||||
<button class="btn btn-error btn-outline" type="button" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn btn-sm" type="button" onclick={addSocial}>Add social link</button>
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save footer</button>
|
||||
</form>
|
||||
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.colors.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(colors)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Colors</h2>
|
||||
<p class="text-sm text-base-content/60 mb-4">These colors are applied across the site as defaults.</p>
|
||||
{#each [
|
||||
{ key: 'background', label: 'Background color' },
|
||||
{ key: 'heading', label: 'Heading color' },
|
||||
{ key: 'subheading', label: 'Subheading color' },
|
||||
{ key: 'text', label: 'Text color' },
|
||||
{ key: 'primary', label: 'Primary color (buttons, links)' },
|
||||
{ key: 'accent', label: 'Accent color (highlights)' }
|
||||
] as { key, label }}
|
||||
<label class="form-control w-full mb-3">
|
||||
<div class="label"><span class="label-text">{label}</span></div>
|
||||
<div class="flex gap-2">
|
||||
<input type="color" class="cursor-pointer" bind:value={colors[key]} />
|
||||
<input type="text" class="input input-bordered flex-1 font-mono text-sm" bind:value={colors[key]} />
|
||||
</div>
|
||||
</label>
|
||||
{/each}
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save colors</button>
|
||||
</form>
|
||||
</div>
|
||||
<script lang="ts">
|
||||
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
let header = $state(structuredClone(data.header.data));
|
||||
let footer = $state(structuredClone(data.footer.data));
|
||||
let colors = $state(structuredClone(data.colors.data));
|
||||
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
|
||||
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Globals | CMS</title></svelte:head>
|
||||
|
||||
<div class="mb-6">
|
||||
<h1 class="text-3xl font-bold">Global sections</h1>
|
||||
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 xl:grid-cols-3">
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.header.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(header)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Header</h2>
|
||||
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
|
||||
<h3 class="mt-6 font-bold">Navigation</h3>
|
||||
{#each header.navLinks || [] as link, i}
|
||||
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
|
||||
<input class="input input-bordered" bind:value={link.label} placeholder="Label" />
|
||||
<input class="input input-bordered" bind:value={link.href} placeholder="Href" />
|
||||
<button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button>
|
||||
<h3 class="mt-6 font-bold">CTA button</h3>
|
||||
<input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" />
|
||||
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
|
||||
<h3 class="mt-6 font-bold">Home page</h3>
|
||||
<select class="select select-bordered w-full" bind:value={header.homePage}>
|
||||
<option value="">— Select a page —</option>
|
||||
{#each data.pages as page}
|
||||
<option value={page.slug}>{page.title} [{page.slug}]</option>
|
||||
{/each}
|
||||
</select>
|
||||
<p class="text-sm text-base-content/60 mt-1">The page that "/" will redirect to.</p>
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save header</button>
|
||||
</form>
|
||||
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.footer.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(footer)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Footer</h2>
|
||||
{#each ['businessName', 'tagline', 'address', 'phone', 'email', 'copyrightText'] as field}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">{field}</span></div>
|
||||
<input class="input input-bordered w-full" bind:value={footer[field]} />
|
||||
</label>
|
||||
{/each}
|
||||
<h3 class="mt-6 font-bold">Social links</h3>
|
||||
{#each footer.socialLinks || [] as link, i}
|
||||
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
|
||||
<input class="input input-bordered" bind:value={link.platform} placeholder="Platform" />
|
||||
<input class="input input-bordered" bind:value={link.url} placeholder="URL" />
|
||||
<button class="btn btn-error btn-outline" type="button" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn btn-sm" type="button" onclick={addSocial}>Add social link</button>
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save footer</button>
|
||||
</form>
|
||||
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.colors.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(colors)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Colors</h2>
|
||||
<p class="text-sm text-base-content/60 mb-4">These colors are applied across the site as defaults.</p>
|
||||
{#each [
|
||||
{ key: 'background', label: 'Background color' },
|
||||
{ key: 'heading', label: 'Heading color' },
|
||||
{ key: 'subheading', label: 'Subheading color' },
|
||||
{ key: 'text', label: 'Text color' },
|
||||
{ key: 'primary', label: 'Primary color (buttons, links)' },
|
||||
{ key: 'accent', label: 'Accent color (highlights)' }
|
||||
] as { key, label }}
|
||||
<label class="form-control w-full mb-3">
|
||||
<div class="label"><span class="label-text">{label}</span></div>
|
||||
<div class="flex gap-2">
|
||||
<input type="color" class="cursor-pointer" bind:value={colors[key]} />
|
||||
<input type="text" class="input input-bordered flex-1 font-mono text-sm" bind:value={colors[key]} />
|
||||
</div>
|
||||
</label>
|
||||
{/each}
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save colors</button>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,27 +1,27 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions } from './$types';
|
||||
|
||||
export const actions: Actions = {
|
||||
login: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const email = String(data.get('email') || '');
|
||||
const password = String(data.get('password') || '');
|
||||
|
||||
try {
|
||||
try {
|
||||
await locals.pb.admins.authWithPassword(email, password);
|
||||
} catch {
|
||||
await locals.pb.collection('users').authWithPassword(email, password);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login failed for', email, err);
|
||||
return fail(400, { message: 'Invalid email or password.' });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/pages');
|
||||
},
|
||||
logout: async ({ locals }) => {
|
||||
locals.pb.authStore.clear();
|
||||
throw redirect(303, '/admin/login');
|
||||
}
|
||||
};
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions } from './$types';
|
||||
|
||||
export const actions: Actions = {
|
||||
login: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const email = String(data.get('email') || '');
|
||||
const password = String(data.get('password') || '');
|
||||
|
||||
try {
|
||||
try {
|
||||
await locals.pb.admins.authWithPassword(email, password);
|
||||
} catch {
|
||||
await locals.pb.collection('users').authWithPassword(email, password);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login failed for', email, err);
|
||||
return fail(400, { message: 'Invalid email or password.' });
|
||||
}
|
||||
|
||||
throw redirect(303, '/admin/pages');
|
||||
},
|
||||
logout: async ({ locals }) => {
|
||||
locals.pb.authStore.clear();
|
||||
throw redirect(303, '/admin/login');
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
<script lang="ts">
|
||||
let { form } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Admin login</title></svelte:head>
|
||||
|
||||
<div class="grid min-h-screen place-items-center bg-base-200 p-6">
|
||||
<form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login">
|
||||
<div class="card-body">
|
||||
<h1 class="card-title text-3xl">Sign in</h1>
|
||||
<p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p>
|
||||
{#if form?.message}
|
||||
<div class="alert alert-error mt-4">{form.message}</div>
|
||||
{/if}
|
||||
<label class="form-control mt-4">
|
||||
<span class="label-text">Email</span>
|
||||
<input class="input input-bordered" name="email" type="email" required />
|
||||
</label>
|
||||
<label class="form-control">
|
||||
<span class="label-text">Password</span>
|
||||
<input class="input input-bordered" name="password" type="password" required />
|
||||
</label>
|
||||
<button class="btn btn-primary mt-4" type="submit">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<script lang="ts">
|
||||
let { form } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Admin login</title></svelte:head>
|
||||
|
||||
<div class="grid min-h-screen place-items-center bg-base-200 p-6">
|
||||
<form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login">
|
||||
<div class="card-body">
|
||||
<h1 class="card-title text-3xl">Sign in</h1>
|
||||
<p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p>
|
||||
{#if form?.message}
|
||||
<div class="alert alert-error mt-4">{form.message}</div>
|
||||
{/if}
|
||||
<label class="form-control mt-4">
|
||||
<span class="label-text">Email</span>
|
||||
<input class="input input-bordered" name="email" type="email" required />
|
||||
</label>
|
||||
<label class="form-control">
|
||||
<span class="label-text">Password</span>
|
||||
<input class="input input-bordered" name="password" type="password" required />
|
||||
</label>
|
||||
<button class="btn btn-primary mt-4" type="submit">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,29 +1,29 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
return { pages };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
const title = String(data.get('title') || '').trim();
|
||||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
|
||||
throw redirect(303, `/admin/pages/${slug}`);
|
||||
},
|
||||
toggle: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
await locals.pb.collection('pages').update(String(data.get('id')), {
|
||||
published: String(data.get('published')) !== 'true'
|
||||
});
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
await locals.pb.collection('pages').delete(String(data.get('id')));
|
||||
}
|
||||
};
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
return { pages };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
const title = String(data.get('title') || '').trim();
|
||||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
|
||||
throw redirect(303, `/admin/pages/${slug}`);
|
||||
},
|
||||
toggle: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
await locals.pb.collection('pages').update(String(data.get('id')), {
|
||||
published: String(data.get('published')) !== 'true'
|
||||
});
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
await locals.pb.collection('pages').delete(String(data.get('id')));
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,65 +1,65 @@
|
|||
<script lang="ts">
|
||||
let { data, form } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Pages | CMS</title></svelte:head>
|
||||
|
||||
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Pages</h1>
|
||||
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}
|
||||
<div class="alert alert-error mb-4">{form.message}</div>
|
||||
{/if}
|
||||
|
||||
<div class="overflow-x-auto rounded-box bg-base-100 shadow">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each data.pages as page}
|
||||
<tr>
|
||||
<td class="font-mono">{page.slug}</td>
|
||||
<td>{page.title}</td>
|
||||
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="flex justify-end gap-2">
|
||||
<a class="btn btn-sm" href={`/admin/pages/${page.slug}`}>Edit</a>
|
||||
<a class="btn btn-sm" href={page.slug === 'home' ? '/' : `/${page.slug}`} target="_blank">Preview</a>
|
||||
<form method="POST" action="?/toggle">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="published" value={page.published} />
|
||||
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
|
||||
</form>
|
||||
<form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}>
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<dialog id="new-page" class="modal">
|
||||
<form class="modal-box" method="POST" action="?/create">
|
||||
<h2 class="text-2xl font-bold">Create page</h2>
|
||||
<label class="form-control w-full mt-4">
|
||||
<div class="label"><span class="label-text">Slug</span></div>
|
||||
<input class="input input-bordered w-full" name="slug" placeholder="about" required />
|
||||
</label>
|
||||
<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" placeholder="About" required />
|
||||
</label>
|
||||
<div class="modal-action">
|
||||
<button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Create</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
<script lang="ts">
|
||||
let { data, form } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Pages | CMS</title></svelte:head>
|
||||
|
||||
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Pages</h1>
|
||||
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}
|
||||
<div class="alert alert-error mb-4">{form.message}</div>
|
||||
{/if}
|
||||
|
||||
<div class="overflow-x-auto rounded-box bg-base-100 shadow">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each data.pages as page}
|
||||
<tr>
|
||||
<td class="font-mono">{page.slug}</td>
|
||||
<td>{page.title}</td>
|
||||
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="flex justify-end gap-2">
|
||||
<a class="btn btn-sm" href={`/admin/pages/${page.slug}`}>Edit</a>
|
||||
<a class="btn btn-sm" href={page.slug === 'home' ? '/' : `/${page.slug}`} target="_blank">Preview</a>
|
||||
<form method="POST" action="?/toggle">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="published" value={page.published} />
|
||||
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
|
||||
</form>
|
||||
<form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}>
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<dialog id="new-page" class="modal">
|
||||
<form class="modal-box" method="POST" action="?/create">
|
||||
<h2 class="text-2xl font-bold">Create page</h2>
|
||||
<label class="form-control w-full mt-4">
|
||||
<div class="label"><span class="label-text">Slug</span></div>
|
||||
<input class="input input-bordered w-full" name="slug" placeholder="about" required />
|
||||
</label>
|
||||
<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" placeholder="About" required />
|
||||
</label>
|
||||
<div class="modal-action">
|
||||
<button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Create</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
|
|
|||
|
|
@ -1,25 +1,25 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import { extractCategories, normalizeEvent } from '$lib/calendar';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, locals }) => {
|
||||
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
|
||||
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
|
||||
return { page, eventCategories };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
save: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id'));
|
||||
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
const title = String(data.get('title') || '').trim();
|
||||
const blocks = JSON.parse(String(data.get('blocks') || '[]'));
|
||||
const publish = String(data.get('publish')) === 'true';
|
||||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
|
||||
throw redirect(303, `/admin/pages/${slug}`);
|
||||
}
|
||||
};
|
||||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import { extractCategories, normalizeEvent } from '$lib/calendar';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, locals }) => {
|
||||
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
|
||||
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
|
||||
return { page, eventCategories };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
save: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id'));
|
||||
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
const title = String(data.get('title') || '').trim();
|
||||
const blocks = JSON.parse(String(data.get('blocks') || '[]'));
|
||||
const publish = String(data.get('publish')) === 'true';
|
||||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
|
||||
throw redirect(303, `/admin/pages/${slug}`);
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,104 +1,104 @@
|
|||
<script lang="ts">
|
||||
import BlockList from '$lib/admin/BlockList.svelte';
|
||||
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
|
||||
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
|
||||
import type { ContentBlock } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let page = $state(data.page);
|
||||
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
|
||||
let selectedId = $state(blocks[0]?.id || '');
|
||||
let previewMode = $state<'desktop' | 'mobile'>('desktop');
|
||||
let showPreview = $state(false);
|
||||
|
||||
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
|
||||
|
||||
function addBlock(type: keyof typeof blockLabels) {
|
||||
const block = createBlock(type);
|
||||
blocks = [...blocks, block];
|
||||
selectedId = block.id;
|
||||
}
|
||||
|
||||
function updateBlock(updated: ContentBlock) {
|
||||
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
|
||||
}
|
||||
|
||||
function deleteBlock(id: string) {
|
||||
blocks = blocks.filter((block) => block.id !== id);
|
||||
if (selectedId === id) selectedId = blocks[0]?.id || '';
|
||||
}
|
||||
|
||||
function moveBlock(from: number, to: number) {
|
||||
const copy = [...blocks];
|
||||
const [item] = copy.splice(from, 1);
|
||||
copy.splice(to, 0, item);
|
||||
blocks = copy;
|
||||
}
|
||||
|
||||
function openPreview() {
|
||||
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
|
||||
showPreview = true;
|
||||
}
|
||||
|
||||
function markPublish(event: MouseEvent) {
|
||||
const form = (event.currentTarget as HTMLButtonElement).form;
|
||||
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null;
|
||||
if (input) input.value = 'true';
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
|
||||
|
||||
<form method="POST" action="?/save" class="space-y-6">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
|
||||
<input type="hidden" name="publish" value="false" />
|
||||
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Edit page</h1>
|
||||
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button class="btn" type="button" onclick={openPreview}>Preview</button>
|
||||
<button class="btn btn-outline" type="submit">Save draft</button>
|
||||
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<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>
|
||||
<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>
|
||||
</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 || []} onChange={updateBlock} />
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{#if showPreview}
|
||||
<div class="fixed inset-0 z-50 bg-black/60 p-4">
|
||||
<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 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>
|
||||
<button class="btn" onclick={() => (showPreview = false)}>Close</button>
|
||||
</div>
|
||||
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<script lang="ts">
|
||||
import BlockList from '$lib/admin/BlockList.svelte';
|
||||
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
|
||||
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
|
||||
import type { ContentBlock } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let page = $state(data.page);
|
||||
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
|
||||
let selectedId = $state(blocks[0]?.id || '');
|
||||
let previewMode = $state<'desktop' | 'mobile'>('desktop');
|
||||
let showPreview = $state(false);
|
||||
|
||||
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
|
||||
|
||||
function addBlock(type: keyof typeof blockLabels) {
|
||||
const block = createBlock(type);
|
||||
blocks = [...blocks, block];
|
||||
selectedId = block.id;
|
||||
}
|
||||
|
||||
function updateBlock(updated: ContentBlock) {
|
||||
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
|
||||
}
|
||||
|
||||
function deleteBlock(id: string) {
|
||||
blocks = blocks.filter((block) => block.id !== id);
|
||||
if (selectedId === id) selectedId = blocks[0]?.id || '';
|
||||
}
|
||||
|
||||
function moveBlock(from: number, to: number) {
|
||||
const copy = [...blocks];
|
||||
const [item] = copy.splice(from, 1);
|
||||
copy.splice(to, 0, item);
|
||||
blocks = copy;
|
||||
}
|
||||
|
||||
function openPreview() {
|
||||
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
|
||||
showPreview = true;
|
||||
}
|
||||
|
||||
function markPublish(event: MouseEvent) {
|
||||
const form = (event.currentTarget as HTMLButtonElement).form;
|
||||
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null;
|
||||
if (input) input.value = 'true';
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
|
||||
|
||||
<form method="POST" action="?/save" class="space-y-6">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
|
||||
<input type="hidden" name="publish" value="false" />
|
||||
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Edit page</h1>
|
||||
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button class="btn" type="button" onclick={openPreview}>Preview</button>
|
||||
<button class="btn btn-outline" type="submit">Save draft</button>
|
||||
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<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>
|
||||
<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>
|
||||
</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 || []} onChange={updateBlock} />
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{#if showPreview}
|
||||
<div class="fixed inset-0 z-50 bg-black/60 p-4">
|
||||
<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 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>
|
||||
<button class="btn" onclick={() => (showPreview = false)}>Close</button>
|
||||
</div>
|
||||
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue