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
11 changed files with 485 additions and 417 deletions
Showing only changes of commit fbcc71672b - Show all commits

View file

@ -5,7 +5,7 @@
}
/* Admin UI theme: DaisyUI light with a fixed sage primary. Deliberately NOT
tied to the site's Globals → Colors (those only apply inside /preview), so
tied to the site's colours (Site design → Colors) (those only apply inside /preview), so
a light brand colour can't make admin buttons unreadable. #647556 on white
text is ~5:1 contrast (WCAG AA). */
@plugin 'daisyui/theme' {

View file

@ -156,7 +156,7 @@
{/each}
</div>
{:else}
<p class="text-sm text-base-content/60">No event categories exist yet. Add categories to events in Calendar first.</p>
<p class="text-sm text-base-content/60">No event categories exist yet. Add categories to events under Events first.</p>
{/if}
</div>
{:else if block.type === 'shop'}

View file

@ -21,7 +21,7 @@
const autoFilled: Record<string, string> = {
booking_details: 'Filled in automatically with the booked services, date and time, prices and the total paid.',
customer_details: "Filled in automatically with the customer's name, email, phone and checkout notes.",
contact_info: 'Filled in automatically from the business name, address, phone and email in Globals → Footer.'
contact_info: 'Filled in automatically from the business name, address, phone and email in Site design → Footer.'
};
</script>

View file

@ -74,6 +74,6 @@
</div>
</div>
{:else}
<p class="text-sm text-base-content/60">No items yet — create some under Items in the admin.</p>
<p class="text-sm text-base-content/60">Nothing to sell yet — add some under Services & products.</p>
{/if}
</div>

View file

@ -1,95 +1,55 @@
<script lang="ts">
import '../app.css';
import favicon from '$lib/assets/favicon.svg';
import { afterNavigate } from '$app/navigation';
import { page } from '$app/state';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
let { children } = $props();
let importStatus = $state<{ ok: boolean; message: string; errors?: string[] } | null>(null);
let importing = $state(false);
let { children, data } = $props();
// Routes rendered without the admin shell: the login screen, and the
// preview iframe (which must look like the public site, not the admin).
const BARE_ROUTES = ['/login', '/preview'];
let bare = $derived(BARE_ROUTES.includes(page.url.pathname));
const navLinks = [
{ href: '/pages', label: 'Pages' },
{ href: '/calendar', label: 'Calendar' },
{ href: '/items', label: 'Items' },
{ href: '/slots', label: 'Slots' },
{ href: '/orders', label: 'Orders' },
{ href: '/emails', label: 'Emails' },
{ href: '/globals', label: 'Globals' }
// Sidebar navigation, grouped by what the studio is doing. Labels are
// user-facing names; hrefs keep the original route names.
const navGroups = [
{
title: 'Website',
links: [
{ href: '/pages', label: 'Pages' },
{ href: '/globals', label: 'Site design' }
]
},
{
title: 'Bookings',
links: [
{ href: '/orders', label: 'Orders' },
{ href: '/slots', label: 'Slots' },
{ href: '/items', label: 'Services & products' },
{ href: '/calendar', label: 'Events' }
]
},
{
title: 'Settings',
links: [
{ href: '/emails', label: 'Emails' },
{ href: '/backup', label: 'Backup' }
]
}
];
const isActive = (href: string) => page.url.pathname === href || page.url.pathname.startsWith(`${href}/`);
// Mobile: the drawer is open while this is true; close it after navigating.
let navOpen = $state(false);
afterNavigate(() => (navOpen = false));
// One basket store per layout instance — provided to all children
// (preview iframe block renderers). Never module-level state.
// Admin doesn't have a real basket; pass null so the store starts empty.
const basketStore = createBasketStore(null);
setBasketContext(basketStore);
async function handleExport() {
try {
const res = await fetch('/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;
if (!confirm(`Import "${file.name}"? Pages, globals and events with the same slug/key/name will be overwritten.`)) {
input.value = '';
return;
}
importing = true;
importStatus = null;
try {
const text = await file.text();
let json: unknown;
try {
json = JSON.parse(text);
} catch {
throw new Error('The file is not valid JSON.');
}
const res = await fetch('/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).`;
if (result.errors?.length) {
// Keep the message up so the errors can be read; no auto-reload.
importStatus = { ok: false, message: `${msg} ${result.errors.length} error(s) — reload to see the imported content.`, errors: result.errors };
} else {
importStatus = { ok: true, message: 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>
<svelte:head>
@ -100,52 +60,47 @@
{#if bare}
{@render children()}
{:else}
<div class="admin-shell min-h-screen bg-base-200">
<header class="navbar sticky top-0 z-30 gap-2 bg-base-100 px-4 shadow-sm">
<div class="flex-1">
<a class="text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
</div>
<nav class="flex flex-none flex-wrap items-center gap-1">
{#each navLinks as link (link.href)}
<a class="btn btn-ghost btn-sm" class:btn-active={isActive(link.href)} aria-current={isActive(link.href) ? 'page' : undefined} href={link.href}>{link.label}</a>
{/each}
<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="size-4" 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-40 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>
<div class="drawer lg:drawer-open">
<input id="admin-nav" type="checkbox" class="drawer-toggle" bind:checked={navOpen} />
<div class="drawer-content flex min-h-screen flex-col bg-base-200">
<!-- Top bar only on small screens; the sidebar is always visible from lg up. -->
<header class="navbar sticky top-0 z-30 bg-base-100 px-2 shadow-sm lg:hidden">
<label for="admin-nav" class="btn btn-square btn-ghost" aria-label="Open menu">
<svg xmlns="http://www.w3.org/2000/svg" class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16" /></svg>
</label>
<a class="ml-1 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
</header>
<main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
{@render children()}
</main>
</div>
<div class="drawer-side z-40">
<label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label>
<aside class="flex min-h-full w-64 flex-col border-r border-base-300 bg-base-100">
<a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
<nav class="flex-1" aria-label="Main">
<ul class="menu w-full gap-0.5 px-3">
{#each navGroups as group (group.title)}
<li class="menu-title mt-3 first:mt-0">{group.title}</li>
{#each group.links as link (link.href)}
<li>
<a href={link.href} class={isActive(link.href) ? 'bg-primary/10 font-semibold text-primary' : ''} aria-current={isActive(link.href) ? 'page' : undefined}>{link.label}</a>
</li>
{/each}
{/each}
</ul>
</nav>
<div class="border-t border-base-300 p-4">
{#if data.user?.email}
<p class="mb-2 truncate text-sm text-base-content/60" title={data.user.email}>{data.user.email}</p>
{/if}
<form method="POST" action="/login?/logout">
<button class="btn btn-outline btn-sm w-full" type="submit">Log out</button>
</form>
</div>
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
<form method="POST" action="/login?/logout">
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
</form>
</nav>
</header>
{#if importStatus}
<div class="mx-auto max-w-7xl px-4 pt-4 md:px-8">
<div class="alert items-start" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
<div class="flex-1">
<p>{importStatus.message}</p>
{#if importStatus.errors?.length}
<ul class="mt-2 list-disc pl-5 text-sm">
{#each importStatus.errors as err}<li>{err}</li>{/each}
</ul>
{/if}
</div>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Dismiss" onclick={() => (importStatus = null)}>✕</button>
</div>
</div>
{/if}
<main class="mx-auto max-w-7xl p-4 md:p-8">
{@render children()}
</main>
</aside>
</div>
</div>
{/if}

View file

@ -0,0 +1,112 @@
<script lang="ts">
let importStatus = $state<{ ok: boolean; message: string; errors?: string[] } | null>(null);
let importing = $state(false);
let exporting = $state(false);
let fileInput: HTMLInputElement | undefined = $state();
async function handleExport() {
exporting = true;
importStatus = null;
try {
const res = await fetch('/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)}` };
} finally {
exporting = false;
}
}
async function handleImport(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
if (!confirm(`Import "${file.name}"? Pages, site design and events with the same slug/key/name will be overwritten.`)) {
input.value = '';
return;
}
importing = true;
importStatus = null;
try {
let json: unknown;
try {
json = JSON.parse(await file.text());
} catch {
throw new Error('The file is not valid JSON.');
}
const res = await fetch('/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 message = `Imported ${result.pagesImported} page(s), ${result.globalsImported} site design section(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
importStatus = result.errors?.length
? { ok: false, message: `${message} ${result.errors.length} item(s) failed:`, errors: result.errors }
: { ok: true, message };
} catch (e) {
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
} finally {
importing = false;
input.value = '';
}
}
</script>
<svelte:head><title>Backup | CMS</title></svelte:head>
<div class="mb-6">
<h1 class="text-3xl font-bold">Backup</h1>
<p class="text-base-content/60">Download the website content as a single file, or restore it from one.</p>
</div>
{#if importStatus}
<div class="alert mb-6 items-start" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok} role="status">
<div>
<p>{importStatus.message}</p>
{#if importStatus.errors?.length}
<ul class="mt-2 list-disc pl-5 text-sm">
{#each importStatus.errors as err}<li>{err}</li>{/each}
</ul>
{/if}
</div>
</div>
{/if}
<div class="grid gap-6 md:grid-cols-2">
<div class="flex flex-col rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-2 text-2xl font-bold">Export</h2>
<p class="text-sm text-base-content/60">
Pages, site design, colors and events, with their images embedded. Services, slots, orders and email templates are not included.
</p>
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 w-full" type="button" disabled={exporting} onclick={handleExport}>
{#if exporting}<span class="loading loading-spinner loading-sm"></span>{/if}
Download export
</button>
</div>
<div class="flex flex-col rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-2 text-2xl font-bold">Import</h2>
<p class="text-sm text-base-content/60">
Restores an export file. Pages with the same slug, site design sections and matching events are overwritten; everything else is kept.
</p>
<div class="flex-grow"></div>
<input class="hidden" type="file" accept=".json,application/json" bind:this={fileInput} onchange={handleImport} />
<button class="btn btn-outline mt-6 w-full" type="button" disabled={importing} onclick={() => fileInput?.click()}>
{#if importing}<span class="loading loading-spinner loading-sm"></span> Importing…{:else}Choose export file…{/if}
</button>
</div>
</div>

View file

@ -22,8 +22,8 @@
});
let categoryText = $state('');
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let month = $derived(createCalendarMonth(viewDate));
const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
let month = $derived(createCalendarMonth(viewDate, new Date(), 1));
let action = $derived(draft.id ? '?/update' : '?/create');
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toZonedDatetimeInput(draft.start, data.timezone));
@ -86,13 +86,13 @@
}
</script>
<svelte:head><title>Calendar | CMS</title></svelte:head>
<svelte:head><title>Events | 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>
<h1 class="text-3xl font-bold">Events</h1>
<p class="text-base-content/60">Workshops and events shown in Upcoming Calendar blocks.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
</div>

View file

@ -43,7 +43,7 @@
};
</script>
<svelte:head><title>Globals | CMS</title></svelte:head>
<svelte:head><title>Site design | CMS</title></svelte:head>
{#snippet status(section: string)}
{#if form?.section === section && form.message}
@ -61,8 +61,8 @@
{/snippet}
<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>
<h1 class="text-3xl font-bold">Site design</h1>
<p class="text-base-content/60">The header, footer and colors shared by every page of the site.</p>
</div>
<div class="grid gap-6 xl:grid-cols-3">

View file

@ -74,15 +74,15 @@
}
</script>
<svelte:head><title>Items | CMS</title></svelte:head>
<svelte:head><title>Services & products | 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">Items</h1>
<p class="text-base-content/60">Manage services and products shown in Shop blocks.</p>
<h1 class="text-3xl font-bold">Services & products</h1>
<p class="text-base-content/60">Bookable services and products, shown in Shop blocks.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Create item</button>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
</div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
@ -120,7 +120,7 @@
</div>
</div>
<Modal bind:open={showEditor} title={draft.id ? 'Edit item' : 'Create item'} wide>
<Modal bind:open={showEditor} title={draft.id ? `Edit “${draft.name}”` : 'New service or product'} wide>
<form method="POST" action={action} class="space-y-1">
<input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="active" value={draft.active ? 'true' : 'false'} />
@ -196,7 +196,7 @@
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit" disabled={uploading}>Save item</button>
<button class="btn btn-primary" type="submit" disabled={uploading}>Save</button>
</div>
</div>
</form>

View file

@ -87,7 +87,7 @@
</td>
</tr>
{:else}
<tr><td colspan="5" class="py-10 text-center text-base-content/60">{items.length ? 'No slots yet — create one so customers can book.' : 'Create a bookable service under Items first.'}</td></tr>
<tr><td colspan="5" class="py-10 text-center text-base-content/60">{items.length ? 'No slots yet — create one so customers can book.' : 'Add a bookable service under Services & products first.'}</td></tr>
{/each}
</tbody>
</table>

View file

@ -1,281 +1,282 @@
import type { CalendarEventRecord, ContentBlock } from './types';
type UnknownRecord = Record<string, unknown>;
export type CalendarDay = {
date: Date;
dateKey: string;
dayNumber: number;
inMonth: boolean;
isToday: boolean;
};
export type CalendarMonth = {
date: Date;
label: string;
days: CalendarDay[];
};
export function hasUpcomingCalendarBlock(blocks: ContentBlock[] = []) {
return blocks.some((block) => block.type === 'upcoming_calendar');
}
export function toDateInput(value?: string | null) {
if (!value) return '';
return value.slice(0, 10);
}
export function toDatetimeInput(value?: string | null) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value.slice(0, 16);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60_000);
return local.toISOString().slice(0, 16);
}
/**
* Convert a form date value to PocketBase format. All-day dates are stored as
* UTC midnight of that calendar date. Timed values (`YYYY-MM-DDTHH:mm` from a
* datetime-local input) are wall-clock times in `timeZone` — NOT the server's
* zone, which is UTC in the container and silently shifted every save.
*/
export function dateInputToPocketBase(value: string, allDay = true, timeZone = 'UTC') {
if (!value) return '';
if (!allDay && value.includes('T')) {
return zonedInputToIso(value, timeZone);
}
return `${value.slice(0, 10)} 00:00:00.000Z`;
}
// ── Site-timezone helpers ──────────────────────────────────────────────
// Admin forms and listings work in the site's timezone (SITE_TIMEZONE), so
// what the admin types is what customers book, and the server render (UTC
// container) matches the browser render.
const LOCAL_INPUT_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/;
function zonedParts(date: Date, timeZone: string) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).formatToParts(date);
const get = (type: string) => parts.find((part) => part.type === type)?.value ?? '00';
return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour'), minute: get('minute'), second: get('second') };
}
/** Milliseconds `timeZone` is ahead of UTC at instant `date`. */
function zoneOffsetMs(date: Date, timeZone: string) {
const p = zonedParts(date, timeZone);
const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
}
function parseInstant(value?: string | null) {
if (!value) return null;
const date = new Date(value.replace(' ', 'T'));
return Number.isNaN(date.getTime()) ? null : date;
}
/** `2026-10-08T10:00` as a wall-clock time in `timeZone` → ISO UTC string ('' if invalid). */
export function zonedInputToIso(value: string, timeZone: string) {
const m = LOCAL_INPUT_RE.exec(value);
if (!m) return '';
const wallClockAsUtc = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]);
let instant = wallClockAsUtc - zoneOffsetMs(new Date(wallClockAsUtc), timeZone);
// Re-check at the candidate instant in case a DST change lies in between.
const corrected = wallClockAsUtc - zoneOffsetMs(new Date(instant), timeZone);
if (corrected !== instant) instant = corrected;
return new Date(instant).toISOString();
}
/**
* A stored instant → `YYYY-MM-DDTHH:mm` in `timeZone`, for datetime-local
* inputs. Values that are already wall-clock input strings pass through; a
* bare date becomes midnight.
*/
export function toZonedDatetimeInput(value: string | null | undefined, timeZone: string) {
if (!value) return '';
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) return value;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00`;
const date = parseInstant(value);
if (!date) return '';
const p = zonedParts(date, timeZone);
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
}
/** "8 Oct 2026, 10:00" in `timeZone`. Fixed locale so SSR and browser agree. */
export function formatDateTime(value: string | null | undefined, timeZone: string) {
const date = parseInstant(value);
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date);
}
/** "10:00" in `timeZone`. */
export function formatTime(value: string | null | undefined, timeZone: string) {
const date = parseInstant(value);
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, timeStyle: 'short' }).format(date);
}
export function parseEventDate(value?: string | null) {
if (!value) return null;
const datePart = value.slice(0, 10);
const [year, month, day] = datePart.split('-').map(Number);
if (!year || !month || !day) return null;
return new Date(year, month - 1, day);
}
export function dateKey(date: Date) {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
return `${year}-${month}-${day}`;
}
export function addDays(date: Date, days: number) {
const copy = new Date(date);
copy.setDate(copy.getDate() + days);
return copy;
}
export function addMonths(date: Date, months: number) {
return new Date(date.getFullYear(), date.getMonth() + months, 1);
}
export function startOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
export function endOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
export function getUpcomingCalendarRange(reference = new Date()) {
const start = startOfMonth(reference);
const end = endOfMonth(addMonths(reference, 1));
return { start, end };
}
export function createCalendarMonth(monthDate: Date, reference = new Date()): CalendarMonth {
const first = startOfMonth(monthDate);
const monthEnd = endOfMonth(monthDate);
const gridStart = addDays(first, -first.getDay());
const gridEnd = addDays(monthEnd, 6 - monthEnd.getDay());
const todayKey = dateKey(reference);
const days: CalendarDay[] = [];
for (let day = new Date(gridStart); day <= gridEnd; day = addDays(day, 1)) {
days.push({
date: new Date(day),
dateKey: dateKey(day),
dayNumber: day.getDate(),
inMonth: day.getMonth() === first.getMonth(),
isToday: dateKey(day) === todayKey
});
}
return {
date: first,
label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }),
days
};
}
export function getCurrentAndNextMonths(reference = new Date()) {
const current = startOfMonth(reference);
return [createCalendarMonth(current, reference), createCalendarMonth(addMonths(current, 1), reference)];
}
export function rangesOverlap(startA: Date, endA: Date, startB: Date, endB: Date) {
return startA <= endB && endA >= startB;
}
export function eventRange(event: Pick<CalendarEventRecord, 'start' | 'end'>) {
const start = parseEventDate(event.start) || new Date();
const end = parseEventDate(event.end) || start;
return end < start ? { start: end, end: start } : { start, end };
}
export function eventOverlapsDay(event: CalendarEventRecord, day: Date) {
const { start, end } = eventRange(event);
return rangesOverlap(start, end, day, day);
}
export function eventOverlapsRange(event: CalendarEventRecord, start: Date, end: Date) {
const range = eventRange(event);
return rangesOverlap(range.start, range.end, start, end);
}
export function normalizeEvent(record: UnknownRecord): CalendarEventRecord {
return {
id: String(record.id || ''),
name: String(record.name || ''),
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
description: record.description ? String(record.description) : '',
color: String(record.color || '#8a9a7b'),
link: record.link ? String(record.link) : '',
categories: normalizeCategories(record.categories),
published: Boolean(record.published),
allDay: record.allDay !== false
};
}
export function normalizeCategories(value: unknown): string[] {
if (Array.isArray(value)) {
return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))];
}
if (typeof value === 'string') {
return [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
}
return [];
}
export function categoriesToText(categories: string[] = []) {
return categories.join(', ');
}
export function extractCategories(events: CalendarEventRecord[]) {
return [...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b));
}
export function eventMatchesCategories(event: CalendarEventRecord, categories: string[] = []) {
if (!categories.length) return true;
return event.categories?.some((category) => categories.includes(category));
}
export function sortEvents(events: CalendarEventRecord[]) {
return [...events].sort((a, b) => {
const startA = parseEventDate(a.start)?.getTime() ?? 0;
const startB = parseEventDate(b.start)?.getTime() ?? 0;
return startA - startB || a.name.localeCompare(b.name);
});
}
export function formatEventDateRange(event: CalendarEventRecord) {
const start = parseEventDate(event.start);
const end = parseEventDate(event.end);
if (!start) return '';
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
return `${formatter.format(start)} – ${formatter.format(end)}`;
}
export function normalizeLink(link?: string) {
const value = String(link || '').trim();
if (!value) return '';
if (value.startsWith('/') || value.startsWith('#') || value.startsWith('mailto:') || value.startsWith('tel:')) return value;
if (/^https?:\/\//i.test(value)) return value;
return `/${value.replace(/^\/+/, '')}`;
}
export function isExternalLink(link?: string) {
return /^https?:\/\//i.test(String(link || ''));
}
import type { CalendarEventRecord, ContentBlock } from './types';
type UnknownRecord = Record<string, unknown>;
export type CalendarDay = {
date: Date;
dateKey: string;
dayNumber: number;
inMonth: boolean;
isToday: boolean;
};
export type CalendarMonth = {
date: Date;
label: string;
days: CalendarDay[];
};
export function hasUpcomingCalendarBlock(blocks: ContentBlock[] = []) {
return blocks.some((block) => block.type === 'upcoming_calendar');
}
export function toDateInput(value?: string | null) {
if (!value) return '';
return value.slice(0, 10);
}
export function toDatetimeInput(value?: string | null) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value.slice(0, 16);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60_000);
return local.toISOString().slice(0, 16);
}
/**
* Convert a form date value to PocketBase format. All-day dates are stored as
* UTC midnight of that calendar date. Timed values (`YYYY-MM-DDTHH:mm` from a
* datetime-local input) are wall-clock times in `timeZone` — NOT the server's
* zone, which is UTC in the container and silently shifted every save.
*/
export function dateInputToPocketBase(value: string, allDay = true, timeZone = 'UTC') {
if (!value) return '';
if (!allDay && value.includes('T')) {
return zonedInputToIso(value, timeZone);
}
return `${value.slice(0, 10)} 00:00:00.000Z`;
}
// ── Site-timezone helpers ──────────────────────────────────────────────
// Admin forms and listings work in the site's timezone (SITE_TIMEZONE), so
// what the admin types is what customers book, and the server render (UTC
// container) matches the browser render.
const LOCAL_INPUT_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/;
function zonedParts(date: Date, timeZone: string) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).formatToParts(date);
const get = (type: string) => parts.find((part) => part.type === type)?.value ?? '00';
return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour'), minute: get('minute'), second: get('second') };
}
/** Milliseconds `timeZone` is ahead of UTC at instant `date`. */
function zoneOffsetMs(date: Date, timeZone: string) {
const p = zonedParts(date, timeZone);
const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
}
function parseInstant(value?: string | null) {
if (!value) return null;
const date = new Date(value.replace(' ', 'T'));
return Number.isNaN(date.getTime()) ? null : date;
}
/** `2026-10-08T10:00` as a wall-clock time in `timeZone` → ISO UTC string ('' if invalid). */
export function zonedInputToIso(value: string, timeZone: string) {
const m = LOCAL_INPUT_RE.exec(value);
if (!m) return '';
const wallClockAsUtc = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]);
let instant = wallClockAsUtc - zoneOffsetMs(new Date(wallClockAsUtc), timeZone);
// Re-check at the candidate instant in case a DST change lies in between.
const corrected = wallClockAsUtc - zoneOffsetMs(new Date(instant), timeZone);
if (corrected !== instant) instant = corrected;
return new Date(instant).toISOString();
}
/**
* A stored instant → `YYYY-MM-DDTHH:mm` in `timeZone`, for datetime-local
* inputs. Values that are already wall-clock input strings pass through; a
* bare date becomes midnight.
*/
export function toZonedDatetimeInput(value: string | null | undefined, timeZone: string) {
if (!value) return '';
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) return value;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00`;
const date = parseInstant(value);
if (!date) return '';
const p = zonedParts(date, timeZone);
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
}
/** "8 Oct 2026, 10:00" in `timeZone`. Fixed locale so SSR and browser agree. */
export function formatDateTime(value: string | null | undefined, timeZone: string) {
const date = parseInstant(value);
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date);
}
/** "10:00" in `timeZone`. */
export function formatTime(value: string | null | undefined, timeZone: string) {
const date = parseInstant(value);
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, timeStyle: 'short' }).format(date);
}
export function parseEventDate(value?: string | null) {
if (!value) return null;
const datePart = value.slice(0, 10);
const [year, month, day] = datePart.split('-').map(Number);
if (!year || !month || !day) return null;
return new Date(year, month - 1, day);
}
export function dateKey(date: Date) {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
return `${year}-${month}-${day}`;
}
export function addDays(date: Date, days: number) {
const copy = new Date(date);
copy.setDate(copy.getDate() + days);
return copy;
}
export function addMonths(date: Date, months: number) {
return new Date(date.getFullYear(), date.getMonth() + months, 1);
}
export function startOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
export function endOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
export function getUpcomingCalendarRange(reference = new Date()) {
const start = startOfMonth(reference);
const end = endOfMonth(addMonths(reference, 1));
return { start, end };
}
/** `weekStartsOn`: 0 = Sunday (default), 1 = Monday. */
export function createCalendarMonth(monthDate: Date, reference = new Date(), weekStartsOn: 0 | 1 = 0): CalendarMonth {
const first = startOfMonth(monthDate);
const monthEnd = endOfMonth(monthDate);
const gridStart = addDays(first, -((first.getDay() - weekStartsOn + 7) % 7));
const gridEnd = addDays(monthEnd, 6 - ((monthEnd.getDay() - weekStartsOn + 7) % 7));
const todayKey = dateKey(reference);
const days: CalendarDay[] = [];
for (let day = new Date(gridStart); day <= gridEnd; day = addDays(day, 1)) {
days.push({
date: new Date(day),
dateKey: dateKey(day),
dayNumber: day.getDate(),
inMonth: day.getMonth() === first.getMonth(),
isToday: dateKey(day) === todayKey
});
}
return {
date: first,
label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }),
days
};
}
export function getCurrentAndNextMonths(reference = new Date()) {
const current = startOfMonth(reference);
return [createCalendarMonth(current, reference), createCalendarMonth(addMonths(current, 1), reference)];
}
export function rangesOverlap(startA: Date, endA: Date, startB: Date, endB: Date) {
return startA <= endB && endA >= startB;
}
export function eventRange(event: Pick<CalendarEventRecord, 'start' | 'end'>) {
const start = parseEventDate(event.start) || new Date();
const end = parseEventDate(event.end) || start;
return end < start ? { start: end, end: start } : { start, end };
}
export function eventOverlapsDay(event: CalendarEventRecord, day: Date) {
const { start, end } = eventRange(event);
return rangesOverlap(start, end, day, day);
}
export function eventOverlapsRange(event: CalendarEventRecord, start: Date, end: Date) {
const range = eventRange(event);
return rangesOverlap(range.start, range.end, start, end);
}
export function normalizeEvent(record: UnknownRecord): CalendarEventRecord {
return {
id: String(record.id || ''),
name: String(record.name || ''),
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
description: record.description ? String(record.description) : '',
color: String(record.color || '#8a9a7b'),
link: record.link ? String(record.link) : '',
categories: normalizeCategories(record.categories),
published: Boolean(record.published),
allDay: record.allDay !== false
};
}
export function normalizeCategories(value: unknown): string[] {
if (Array.isArray(value)) {
return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))];
}
if (typeof value === 'string') {
return [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
}
return [];
}
export function categoriesToText(categories: string[] = []) {
return categories.join(', ');
}
export function extractCategories(events: CalendarEventRecord[]) {
return [...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b));
}
export function eventMatchesCategories(event: CalendarEventRecord, categories: string[] = []) {
if (!categories.length) return true;
return event.categories?.some((category) => categories.includes(category));
}
export function sortEvents(events: CalendarEventRecord[]) {
return [...events].sort((a, b) => {
const startA = parseEventDate(a.start)?.getTime() ?? 0;
const startB = parseEventDate(b.start)?.getTime() ?? 0;
return startA - startB || a.name.localeCompare(b.name);
});
}
export function formatEventDateRange(event: CalendarEventRecord) {
const start = parseEventDate(event.start);
const end = parseEventDate(event.end);
if (!start) return '';
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
return `${formatter.format(start)} – ${formatter.format(end)}`;
}
export function normalizeLink(link?: string) {
const value = String(link || '').trim();
if (!value) return '';
if (value.startsWith('/') || value.startsWith('#') || value.startsWith('mailto:') || value.startsWith('tel:')) return value;
if (/^https?:\/\//i.test(value)) return value;
return `/${value.replace(/^\/+/, '')}`;
}
export function isExternalLink(link?: string) {
return /^https?:\/\//i.test(String(link || ''));
}