Admin navigation: grouped sidebar, plainer labels, Backup page

Agreed with the site owner:
- Grouped sidebar (Website / Bookings / Settings) instead of a flat top
  bar that overflowed on phones; a drawer with a hamburger below lg.
  Signed-in email and Log out at the bottom.
- Labels: Globals → Site design, Items → Services & products,
  Calendar → Events, Export/Import → Backup (URLs unchanged); page headings
  and cross-references updated to match.
- Export/import moved from a navbar dropdown to a /backup page that says
  what is and isn't included.
- Admin event calendar starts weeks on Monday (createCalendarMonth gains an
  optional weekStartsOn; the public block is unchanged).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
This commit is contained in:
agent 2026-10-06 11:00:01 +00:00
parent 9264289813
commit fbcc71672b
11 changed files with 485 additions and 417 deletions

View file

@ -5,7 +5,7 @@
} }
/* Admin UI theme: DaisyUI light with a fixed sage primary. Deliberately NOT /* 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 a light brand colour can't make admin buttons unreadable. #647556 on white
text is ~5:1 contrast (WCAG AA). */ text is ~5:1 contrast (WCAG AA). */
@plugin 'daisyui/theme' { @plugin 'daisyui/theme' {

View file

@ -156,7 +156,7 @@
{/each} {/each}
</div> </div>
{:else} {: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} {/if}
</div> </div>
{:else if block.type === 'shop'} {:else if block.type === 'shop'}

View file

@ -21,7 +21,7 @@
const autoFilled: Record<string, string> = { const autoFilled: Record<string, string> = {
booking_details: 'Filled in automatically with the booked services, date and time, prices and the total paid.', 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.", 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> </script>

View file

@ -74,6 +74,6 @@
</div> </div>
</div> </div>
{:else} {: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} {/if}
</div> </div>

View file

@ -1,95 +1,55 @@
<script lang="ts"> <script lang="ts">
import '../app.css'; import '../app.css';
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import { afterNavigate } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte'; import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
let { children } = $props(); let { children, data } = $props();
let importStatus = $state<{ ok: boolean; message: string; errors?: string[] } | null>(null);
let importing = $state(false);
// Routes rendered without the admin shell: the login screen, and the // Routes rendered without the admin shell: the login screen, and the
// preview iframe (which must look like the public site, not the admin). // preview iframe (which must look like the public site, not the admin).
const BARE_ROUTES = ['/login', '/preview']; const BARE_ROUTES = ['/login', '/preview'];
let bare = $derived(BARE_ROUTES.includes(page.url.pathname)); let bare = $derived(BARE_ROUTES.includes(page.url.pathname));
const navLinks = [ // Sidebar navigation, grouped by what the studio is doing. Labels are
{ href: '/pages', label: 'Pages' }, // user-facing names; hrefs keep the original route names.
{ href: '/calendar', label: 'Calendar' }, const navGroups = [
{ href: '/items', label: 'Items' }, {
{ href: '/slots', label: 'Slots' }, title: 'Website',
{ href: '/orders', label: 'Orders' }, links: [
{ href: '/emails', label: 'Emails' }, { href: '/pages', label: 'Pages' },
{ href: '/globals', label: 'Globals' } { 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}/`); 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 // One basket store per layout instance — provided to all children
// (preview iframe block renderers). Never module-level state. // (preview iframe block renderers). Never module-level state.
// Admin doesn't have a real basket; pass null so the store starts empty. // Admin doesn't have a real basket; pass null so the store starts empty.
const basketStore = createBasketStore(null); const basketStore = createBasketStore(null);
setBasketContext(basketStore); 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> </script>
<svelte:head> <svelte:head>
@ -100,52 +60,47 @@
{#if bare} {#if bare}
{@render children()} {@render children()}
{:else} {:else}
<div class="admin-shell min-h-screen bg-base-200"> <div class="drawer lg:drawer-open">
<header class="navbar sticky top-0 z-30 gap-2 bg-base-100 px-4 shadow-sm"> <input id="admin-nav" type="checkbox" class="drawer-toggle" bind:checked={navOpen} />
<div class="flex-1">
<a class="text-lg font-bold tracking-tight" href="/pages">Massage CMS</a> <div class="drawer-content flex min-h-screen flex-col bg-base-200">
</div> <!-- Top bar only on small screens; the sidebar is always visible from lg up. -->
<nav class="flex flex-none flex-wrap items-center gap-1"> <header class="navbar sticky top-0 z-30 bg-base-100 px-2 shadow-sm lg:hidden">
{#each navLinks as link (link.href)} <label for="admin-nav" class="btn btn-square btn-ghost" aria-label="Open menu">
<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> <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>
{/each} </label>
<div class="dropdown dropdown-end"> <a class="ml-1 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
<button class="btn btn-ghost btn-sm" type="button" tabindex="0"> </header>
<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> <main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
Export/Import {@render children()}
</button> </main>
<ul class="menu dropdown-content z-40 mt-2 w-48 rounded-box bg-base-100 p-2 shadow"> </div>
<li><button type="button" onclick={handleExport}>Export all</button></li>
<li> <div class="drawer-side z-40">
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}> <label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label>
{importing ? 'Importing…' : 'Import'} <aside class="flex min-h-full w-64 flex-col border-r border-base-300 bg-base-100">
</button> <a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
</li> <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> </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> </div>
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} /> </aside>
<form method="POST" action="/login?/logout"> </div>
<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>
</div> </div>
{/if} {/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(''); let categoryText = $state('');
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
let month = $derived(createCalendarMonth(viewDate)); let month = $derived(createCalendarMonth(viewDate, new Date(), 1));
let action = $derived(draft.id ? '?/update' : '?/create'); let action = $derived(draft.id ? '?/update' : '?/create');
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local'); let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toZonedDatetimeInput(draft.start, data.timezone)); let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toZonedDatetimeInput(draft.start, data.timezone));
@ -86,13 +86,13 @@
} }
</script> </script>
<svelte:head><title>Calendar | CMS</title></svelte:head> <svelte:head><title>Events | CMS</title></svelte:head>
<div class="space-y-6"> <div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div> <div>
<h1 class="text-3xl font-bold">Calendar</h1> <h1 class="text-3xl font-bold">Events</h1>
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p> <p class="text-base-content/60">Workshops and events shown in Upcoming Calendar blocks.</p>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button> <button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
</div> </div>

View file

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

View file

@ -74,15 +74,15 @@
} }
</script> </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="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div> <div>
<h1 class="text-3xl font-bold">Items</h1> <h1 class="text-3xl font-bold">Services & products</h1>
<p class="text-base-content/60">Manage services and products shown in Shop blocks.</p> <p class="text-base-content/60">Bookable services and products, shown in Shop blocks.</p>
</div> </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> </div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if} {#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
@ -120,7 +120,7 @@
</div> </div>
</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"> <form method="POST" action={action} class="space-y-1">
<input type="hidden" name="id" value={draft.id} /> <input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="active" value={draft.active ? 'true' : 'false'} /> <input type="hidden" name="active" value={draft.active ? 'true' : 'false'} />
@ -196,7 +196,7 @@
{/if} {/if}
<div class="flex gap-2"> <div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> <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>
</div> </div>
</form> </form>

View file

@ -87,7 +87,7 @@
</td> </td>
</tr> </tr>
{:else} {: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} {/each}
</tbody> </tbody>
</table> </table>

View file

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