moved page rendering to a different service and access is now behind

admin.DOMAIN
www.DOMAIN
db.DOMAIN
This commit is contained in:
Jakub Dorfman 2026-08-19 17:58:19 +02:00
parent c7f6b30b87
commit 1027da989e
126 changed files with 6356 additions and 1516 deletions

View file

@ -0,0 +1,63 @@
<script lang="ts">
import type { BlockType, ContentBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults';
let { blocks = [], selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
blocks: ContentBlock[];
selectedId?: string;
onSelect?: (id: string) => void;
onDelete?: (id: string) => void;
onMove?: (from: number, to: number) => void;
}>();
let dragIndex = $state<number | null>(null);
let holdingId = $state('');
let holdTimer: ReturnType<typeof setTimeout> | null = null;
function startHold(id: string) {
holdingId = id;
holdTimer = setTimeout(() => {
const idx = blocks.findIndex((b: ContentBlock) => b.id === id);
onDelete(id);
onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || '');
holdingId = '';
}, 1000);
}
function endHold() {
if (holdTimer) clearTimeout(holdTimer);
holdingId = '';
}
</script>
<div class="space-y-3">
{#each blocks as block, i (block.id)}
<div
role="listitem"
class="rounded-box border bg-base-100 p-3 shadow-sm cursor-pointer"
class:border-primary={selectedId === block.id}
draggable="true"
onclick={() => onSelect(block.id)}
ondragstart={() => (dragIndex = i)}
ondragover={(e) => e.preventDefault()}
ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }}
>
<div class="flex items-center gap-2">
<span class="cursor-grab text-xl text-base-content/40">☰</span>
<div class="flex-1 font-semibold">{blockLabels[block.type as BlockType]}</div>
<button
class="btn btn-xs btn-error btn-outline relative overflow-hidden"
class:btn-disabled={holdingId && holdingId !== block.id}
class:delete-holding={holdingId === block.id}
type="button"
onpointerdown={() => startHold(block.id)}
onpointerup={endHold}
onpointerleave={endHold}
>
<span class="delete-fill" class:animating={holdingId === block.id}></span>
<span class="relative z-10 text-error">Delete</span>
</button>
</div>
</div>
{/each}
</div>

View file

@ -0,0 +1,86 @@
import { v4 as uuid } from 'uuid';
import type { BlockType, ContentBlock } from '$lib/types';
export const blockLabels: Record<BlockType, string> = {
text: 'Text',
image_text: 'Image + Text',
timeline: 'Timeline',
hero: 'Hero',
button: 'Button',
spacer: 'Spacer',
testimonials: 'Testimonials',
upcoming_calendar: 'Upcoming Calendar',
shop: 'Shop',
checkout: 'Checkout'
};
export const blockTypes = Object.keys(blockLabels) as BlockType[];
export function createBlock(type: BlockType): ContentBlock {
const base = { id: uuid(), type, data: {} as Record<string, any> };
switch (type) {
case 'text':
base.data = { content: '<h2>New text block</h2><p>Add your copy here.</p>' };
break;
case 'image_text':
base.data = { url: '', alt: '', content: '<h2>Image and text</h2><p>Add content here.</p>', imagePosition: 'left' };
break;
case 'timeline':
base.data = { items: [{ title: 'Milestone', description: 'Describe this moment.' }] };
break;
case 'hero':
base.data = {
heading: 'Holistic and Experiential Learning about Happiness',
subheading: 'Individual sessions, workshops and events in Oslo',
buttonLabel: 'BOOK NOW',
buttonUrl: '/book'
};
break;
case 'button':
base.data = {
label: 'Learn More',
href: '/',
variant: 'primary',
size: 'md',
alignment: 'center'
};
break;
case 'spacer':
base.data = { height: 64 };
break;
case 'testimonials':
base.data = {
title: 'What They Say About Me',
items: [
{ text: 'Recently I started to experience incredible whole-body orgasms. And now I know how it works. My awareness around sexuality changed for good and I feel like a boss of my own life. What a joy to have this freedom of choice.', title: 'Anne' },
{ text: 'I never thought it was possible to sense so much pleasure in my body without intense stimulations I got used to. After the series of sessions, I could feel something like a trance state by receiving only a gentle touch. That was a totally new experience for me.', title: 'Espen' },
{ text: "Eva's sexual healing methods should be accessible to everyone. I am amazed by the depth and integrity of the message she conveys through her work. I was meeting Eva for healing my body and, as a result, I reconnected with my heart and soul too.", title: 'Marie' },
{ text: "It is hard to surprise me with any sexual activity since I had many exciting experiments in my life. But I always suspected that there might be something more I have not yet felt and tried. Thanks to Eva I realised how much power I've got. Under her guidance, I have learnt to maximise my orgasmic potential and consciously play with arousal. By the way, my wife is also happy that I became enthusiastic about new sexual practices.", title: 'Jan' }
]
};
break;
case 'upcoming_calendar':
base.data = {
title: 'Upcoming Events',
categories: []
};
break;
case 'shop':
base.data = {
title: 'Our Services',
itemTypeFilter: 'all',
itemIds: [],
layout: 'grid'
};
break;
case 'checkout':
base.data = {
title: 'Checkout',
heading: 'Complete your booking',
notesLabel: 'Notes or special requests'
};
break;
}
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base;
}

View file

@ -0,0 +1,301 @@
<script lang="ts">
import type { BlockType, ContentBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults';
import RichTextEditor from './RichTextEditor.svelte';
import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte';
import ShopBlockEditor from './ShopBlockEditor.svelte';
import CheckoutBlockEditor from './CheckoutBlockEditor.svelte';
let { block, eventCategories = [], items = [], onChange = (block: ContentBlock) => {} } = $props<{
block: ContentBlock | null;
eventCategories?: string[];
items?: { id: string; name: string; type: string }[];
onChange?: (block: ContentBlock) => void;
}>();
function updateData(patch: Record<string, any>) {
if (!block) return;
block = { ...block, data: { ...block.data, ...patch } };
onChange(block);
}
function updateArray(key: string, index: number, patch: Record<string, any>) {
if (!block) return;
const items = [...(block.data[key] || [])];
items[index] = { ...items[index], ...patch };
updateData({ [key]: items });
}
function addArrayItem(key: string, item: Record<string, any>) {
if (!block) return;
updateData({ [key]: [...(block.data[key] || []), item] });
}
function removeArrayItem(key: string, index: number) {
if (!block) return;
updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) });
}
function toggleCategory(category: string) {
if (!block) return;
const categories = block.data.categories || [];
updateData({
categories: categories.includes(category)
? categories.filter((item: string) => item !== category)
: [...categories, category]
});
}
function titleCase(value: string | number) {
const text = String(value);
return text.charAt(0).toUpperCase() + text.slice(1);
}
</script>
{#if !block}
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">Select a block to edit.</div>
{:else}
<div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">{blockLabels[block.type as BlockType]}</h2>
{#if block.type === 'text'}
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
{:else if block.type === 'image_text'}
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
<div class="form-control mt-3">
<label class="label cursor-pointer justify-start gap-3">
<span class="label-text">Image position</span>
<input type="checkbox" class="toggle toggle-primary" checked={block.data.imagePosition === 'right'} onchange={(e) => updateData({ imagePosition: e.currentTarget.checked ? 'right' : 'left' })} />
<span class="text-sm text-base-content/60">{block.data.imagePosition === 'right' ? 'Right' : 'Left'}</span>
</label>
</div>
<div class="mt-3"><RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /></div>
{:else if block.type === 'timeline'}
{#each block.data.items || [] as item, i}
<div class="rounded-box mb-3 border border-base-300 p-3">
<input class="input input-bordered mb-2 w-full" placeholder="Title" value={item.title} oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })} />
<textarea class="textarea textarea-bordered w-full" placeholder="Description" value={item.description} oninput={(e) => updateArray('items', i, { description: e.currentTarget.value })}></textarea>
<button class="btn btn-error btn-sm mt-2" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div>
{/each}
<button class="btn" type="button" onclick={() => addArrayItem('items', { title: '', description: '' })}>Add item</button>
{:else if block.type === 'hero'}
<label class="form-control w-full">
<div class="label"><span class="label-text">Heading</span></div>
<input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
</label>
<label class="form-control w-full mt-3">
<div class="label"><span class="label-text">Subheading</span></div>
<input class="input input-bordered w-full" value={block.data.subheading || ''} oninput={(e) => updateData({ subheading: e.currentTarget.value })} />
</label>
<label class="form-control w-full mt-3">
<div class="label"><span class="label-text">Button label</span></div>
<input class="input input-bordered w-full" value={block.data.buttonLabel || ''} oninput={(e) => updateData({ buttonLabel: e.currentTarget.value })} />
</label>
<label class="form-control w-full mt-3">
<div class="label"><span class="label-text">Button URL</span></div>
<input class="input input-bordered w-full" value={block.data.buttonUrl || ''} oninput={(e) => updateData({ buttonUrl: e.currentTarget.value })} />
</label>
{:else if block.type === 'button'}
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Button label</span></div>
<input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">URL</span></div>
<input class="input input-bordered w-full" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
</label>
<div class="form-control mt-5">
<SegmentedControl
label="Variant"
options={['primary', 'secondary']}
value={block.data.variant || 'primary'}
onChange={(v) => updateData({ variant: v })}
/>
</div>
<div class="form-control">
<SegmentedControl
label="Alignment"
options={['left', 'center', 'right']}
value={block.data.alignment || 'left'}
onChange={(v) => updateData({ alignment: v })}
formatLabel={titleCase}
/>
</div>
<div class="form-control">
<SegmentedControl
label="Size"
options={['xs', 'sm', 'md', 'lg']}
value={block.data.size || 'md'}
onChange={(v) => updateData({ size: v })}
formatLabel={(v) => String({ xs: 'Extra Small', sm: 'Small', md: 'Medium', lg: 'Large' }[String(v)] || v)}
/>
</div>
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Color</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data.color || 'var(--color-primary)'} oninput={(e) => updateData({ color: e.currentTarget.value })} />
<input class="input input-bordered flex-1" placeholder="Leave empty to use global primary" value={block.data.color || ''} oninput={(e) => updateData({ color: e.currentTarget.value })} />
</div>
</div>
</div>
</div>
{:else if block.type === 'spacer'}
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Height (px)</span></div>
<input type="number" class="input input-bordered w-full" value={block.data.height || 64} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 64 })} />
</label>
</div>
{:else if block.type === 'testimonials'}
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Section Title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
{#each block.data.items || [] as item, i}
<div class="rounded-box mb-3 border border-base-300 p-4">
<textarea
class="textarea textarea-bordered w-full mb-2"
placeholder="Testimonial text"
rows="3"
value={item.text}
oninput={(e) => updateArray('items', i, { text: e.currentTarget.value })}
></textarea>
<input
class="input input-bordered w-full"
placeholder="Author name"
value={item.title}
oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })}
/>
<button class="btn btn-error btn-sm mt-2" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div>
{/each}
<button class="btn" type="button" onclick={() => addArrayItem('items', { text: '', title: '' })}>Add testimonial</button>
</div>
{:else if block.type === 'upcoming_calendar'}
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Section title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
<div class="rounded-box border border-base-300 p-4">
<div class="mb-3">
<h3 class="font-semibold">Category filters</h3>
<p class="text-sm text-base-content/60">Choose categories to show in this block. Leave all unchecked to show every published event.</p>
</div>
{#if eventCategories?.length}
<div class="flex flex-wrap gap-2">
{#each eventCategories as category}
<label class="btn btn-sm" class:btn-primary={(block.data.categories || []).includes(category)}>
<input class="hidden" type="checkbox" checked={(block.data.categories || []).includes(category)} onchange={() => toggleCategory(category)} />
{category}
</label>
{/each}
</div>
{:else}
<p class="text-sm text-base-content/60">No event categories exist yet. Create events in the Calendar admin page first.</p>
{/if}
</div>
</div>
{:else if block.type === 'shop'}
<ShopBlockEditor {block} {items} {onChange} />
{:else if block.type === 'checkout'}
<CheckoutBlockEditor {block} {onChange} />
{/if}
<div class="rounded-box border border-base-300 p-4 mt-4">
<!-- Background Type Selector -->
<div class="mb-4">
<SegmentedControl
label="Background"
labelStyle="font-weight: 1000;"
options={['none', 'color', 'image']}
value={block.data._background?.type || 'none'}
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), type: v } })}
/>
</div>
{#if block.data._background?.type === 'color'}
<div class="space-y-3">
<label class="form-control">
<span class="label-text text-sm">Color</span>
<div class="flex items-center gap-2">
<input class="input input-bordered w-12 h-10 p-1 cursor-pointer" type="color" value={block.data._background?.color || '#66755d'} oninput={(e) => updateData({ _background: { ...(block.data._background || {}), color: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#66755d or sage" value={block.data._background?.color || ''} oninput={(e) => updateData({ _background: { ...(block.data._background || {}), color: e.currentTarget.value } })} />
</div>
</label>
</div>
{/if}
{#if block.data._background?.type === 'image'}
<div class="space-y-4">
<ImageUploader url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateData({ _background: { ...(block.data._background || {}), imageUrl: image.url, imageAlt: image.alt } })} />
<SegmentedControl
label="Attachment"
options={['scroll', 'fixed']}
value={block.data._background?.attachment || 'scroll'}
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), attachment: v } })}
/>
<SegmentedControl
label="Overlay"
options={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]}
value={block.data._background?.overlayOpacity ?? 0}
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), overlay: true, overlayOpacity: v } })}
formatLabel={(v) => `${v}%`}
/>
</div>
{/if}
<hr class="border-base-content/10 my-4" />
<SegmentedControl
label="Foreground"
labelStyle="font-weight: 1000;"
options={['default', 'custom']}
value={block.data._foreground?.mode || 'default'}
onChange={(v) => updateData({ _foreground: { ...(block.data._foreground || {}), mode: v } })}
/>
{#if block.data._foreground?.mode === 'custom'}
<div class="mt-4 space-y-3">
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Heading</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.headingColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.headingColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} />
</div>
</div>
</div>
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Sub heading</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.subheadingColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.subheadingColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} />
</div>
</div>
</div>
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Text</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.textColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.textColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} />
</div>
</div>
</div>
</div>
{/if}
</div>
</div>
{/if}

View file

@ -0,0 +1,31 @@
<script lang="ts">
import type { ContentBlock, CheckoutBlockData } from '$lib/types';
let {
block,
onChange = (b: ContentBlock) => {}
} = $props<{
block: ContentBlock;
onChange?: (b: ContentBlock) => void;
}>();
function updateData(patch: Partial<CheckoutBlockData>) {
onChange({ ...block, data: { ...block.data, ...patch } });
}
</script>
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Heading</span></div>
<input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Notes label</span></div>
<input class="input input-bordered w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} />
</label>
<p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p>
</div>

View file

@ -0,0 +1,105 @@
<script lang="ts">
import { uploadMedia } from '$lib/pb';
let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{
url?: string;
alt?: string;
onChange?: (value: { url: string; alt: string }) => void;
}>();
let uploading = $state(false);
let error = $state('');
let fileInput = $state<HTMLInputElement>();
// Local state synced from props so reactivity works reliably in Svelte 5
let localUrl = $state(urlProp);
let localAlt = $state(altProp);
$effect(() => { localUrl = urlProp; });
$effect(() => { localAlt = altProp; });
function emitChange() {
onChange({ url: localUrl, alt: localAlt });
}
async function handleFile(event: Event) {
const file = (event.currentTarget as HTMLInputElement).files?.[0];
if (!file) return;
uploading = true;
error = '';
try {
const result = await uploadMedia(file);
localUrl = result.url;
emitChange();
} catch (e) {
error = e instanceof Error ? e.message : 'Upload failed';
console.error('Image upload error:', e);
} finally {
uploading = false;
}
}
function removeImage() {
localUrl = '';
localAlt = '';
emitChange();
if (fileInput) fileInput.value = '';
}
</script>
<div class="grid grid-cols-[1fr_1.5fr] gap-4">
<!-- Drop zone / upload area -->
<div
class="flex h-32 cursor-pointer flex-col items-center justify-center rounded-box border-2 border-dashed p-3 transition-colors hover:border-primary {localUrl ? 'border-success/40' : 'border-base-300'}"
role="button"
tabindex="0"
onclick={() => fileInput?.click()}
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
>
{#if uploading}
<span class="loading loading-spinner loading-lg text-primary"></span>
<p class="mt-3 text-sm text-base-content/60">Uploading…</p>
{:else if localUrl}
<div class="relative w-full">
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
<button
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
type="button"
onclick={(e) => { e.stopPropagation(); removeImage(); }}
title="Remove image"
>✕</button>
</div>
{:else}
<svg class="mb-2 size-8 text-base-content/40" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" />
</svg>
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p>
<p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
{/if}
</div>
{#if error}
<div class="alert alert-error col-span-full text-sm">{error}</div>
{/if}
<input
class="hidden"
type="file"
accept="image/*"
onchange={handleFile}
disabled={uploading}
bind:this={fileInput}
/>
<!-- URL & Alt fields -->
<div class="space-y-3">
<label class="form-control w-full">
<div class="label"><span class="label-text">Image URL</span></div>
<input class="input input-bordered w-full" bind:value={localUrl} oninput={() => emitChange()} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Alt text</span></div>
<input class="input input-bordered w-full" bind:value={localAlt} oninput={() => emitChange()} />
</label>
</div>
</div>

View file

@ -0,0 +1,78 @@
<script lang="ts">
import { browser } from '$app/environment';
import { onMount } from 'svelte';
let { value = '', onChange = (html: string) => {} } = $props<{ value?: string; onChange?: (html: string) => void }>();
let editorEl: HTMLDivElement | undefined = $state();
let mounted = $state(false);
onMount(() => {
mounted = true;
if (editorEl) {
editorEl.innerHTML = value || '';
}
});
// Sync content from props when a different block is selected,
// without overwriting content while the user is actively editing.
$effect(() => {
if (mounted && editorEl && value !== undefined) {
if (editorEl.innerHTML !== value) {
editorEl.innerHTML = value || '';
}
}
});
function exec(cmd: string, val?: string) {
if (!browser) return;
editorEl?.focus();
document.execCommand(cmd, false, val);
emit();
}
function emit() {
if (editorEl) onChange(editorEl.innerHTML);
}
function setLink() {
const url = prompt('Link URL', 'https://');
if (url) exec('createLink', url);
}
function clearFormatting() {
if (!browser) return;
editorEl?.focus();
document.execCommand('formatBlock', false, '<p>');
document.execCommand('removeFormat');
emit();
}
function handleInput() {
emit();
}
</script>
{#if mounted}
<div class="rounded-box border border-base-300 bg-base-100">
<div class="flex flex-wrap gap-2 border-b border-base-300 p-2">
<button class="btn btn-xs" onclick={() => exec('bold')} type="button"><b>B</b></button>
<button class="btn btn-xs" onclick={() => exec('italic')} type="button"><i>I</i></button>
<button class="btn btn-xs" onclick={() => exec('formatBlock', '<h2>')} type="button">H2</button>
<button class="btn btn-xs" onclick={() => exec('formatBlock', '<h3>')} type="button">H3</button>
<button class="btn btn-xs" onclick={() => exec('insertUnorderedList')} type="button">List</button>
<button class="btn btn-xs" onclick={setLink} type="button">Link</button>
<button class="btn btn-xs" onclick={clearFormatting} type="button">Clear</button>
</div>
<div
bind:this={editorEl}
contenteditable
role="textbox"
aria-multiline="true"
class="min-h-40 p-4 outline-none"
oninput={handleInput}
onkeydown={(e) => { if (e.key === 'Tab') { e.preventDefault(); exec('insertHTML', '&emsp;'); } }}
></div>
</div>
{:else}
<div class="rounded-box border border-base-300 bg-base-100 p-4 text-base-content/50">Loading editor…</div>
{/if}

View file

@ -0,0 +1,38 @@
<script lang="ts">
let {
label,
options,
value,
onChange,
formatLabel = (v: string | number) => String(v),
labelStyle = '',
class: className = ''
}: {
label?: string;
options: (string | number)[];
value: string | number;
onChange: (value: string | number) => void;
formatLabel?: (value: string | number) => string;
labelStyle?: string;
class?: string;
} = $props();
</script>
<div class="form-control {className}">
<div class="flex items-center justify-between">
{#if label}
<span class="label-text w-24" style={labelStyle}>{label}</span>
{/if}
<div class="grid flex-1" style="grid-template-columns: repeat({options.length}, 1fr)">
{#each options as option, i}
<button
type="button"
class="btn btn-sm {i === 0 ? 'rounded-r-none' : ''} {i === options.length - 1 ? 'rounded-l-none' : ''} {value === option ? 'btn-active' : ''}"
onclick={() => onChange(option)}
>
{formatLabel(option)}
</button>
{/each}
</div>
</div>
</div>

View file

@ -0,0 +1,79 @@
<script lang="ts">
import type { ContentBlock, ShopBlockData } from '$lib/types';
import SegmentedControl from './SegmentedControl.svelte';
let {
block,
items = [],
onChange = (b: ContentBlock) => {}
} = $props<{
block: ContentBlock;
items?: { id: string; name: string; type: string }[];
onChange?: (b: ContentBlock) => void;
}>();
function updateData(patch: Partial<ShopBlockData>) {
onChange({ ...block, data: { ...block.data, ...patch } });
}
function toggleItem(id: string) {
const current: string[] = block.data.itemIds || [];
updateData({
itemIds: current.includes(id)
? current.filter((itemId) => itemId !== id)
: [...current, id]
});
}
const typeFilterLabels: Record<string, string> = {
all: 'All',
item: 'Products',
item_with_time: 'Services'
};
</script>
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
<SegmentedControl
label="Layout"
options={['grid', 'list']}
value={block.data.layout || 'grid'}
onChange={(v) => updateData({ layout: v as 'grid' | 'list' })}
formatLabel={(v) => String(v).charAt(0).toUpperCase() + String(v).slice(1)}
/>
<SegmentedControl
label="Item type"
options={['all', 'item', 'item_with_time']}
value={block.data.itemTypeFilter || 'all'}
onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })}
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
/>
{#if items.length}
<div class="rounded-box border border-base-300 p-4">
<div class="mb-3">
<h3 class="font-semibold">Items</h3>
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p>
</div>
<div class="flex flex-wrap gap-2">
{#each items as item}
<button
type="button"
class="btn btn-xs"
class:btn-primary={(block.data.itemIds || []).includes(item.id)}
onclick={() => toggleItem(item.id)}
>
{item.name}
</button>
{/each}
</div>
</div>
{:else}
<p class="text-sm text-base-content/60">No items yet — create some under Items in the admin.</p>
{/if}
</div>

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -0,0 +1,94 @@
import { getContext, setContext } from 'svelte';
import type { Basket, BasketLine } from '$lib/types';
const BASKET_KEY = 'basket';
export type BasketStore = ReturnType<typeof createBasketStore>;
export function createBasketStore(initial: Basket | null) {
let lines = $state<BasketLine[]>(initial?.lines ?? []);
let status = $state<Basket['status']>(initial?.status ?? 'active');
const total = $derived(
lines.reduce((sum, line) => sum + (line.itemPrice ?? 0) * line.quantity, 0)
);
const count = $derived(lines.reduce((sum, line) => sum + line.quantity, 0));
async function callApi(body: Record<string, unknown>): Promise<Basket | null> {
const res = await fetch('/api/basket', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Basket request failed (${res.status})`);
}
const data = await res.json();
return data.basket as Basket | null;
}
function applyBasket(basket: Basket | null) {
lines = basket?.lines ?? [];
status = basket?.status ?? 'active';
}
async function refresh() {
const res = await fetch('/api/basket');
if (!res.ok) return;
const data = await res.json();
applyBasket(data.basket);
}
/** Overwrite local state from server-provided layout data. */
function syncFrom(basket: Basket | null) {
applyBasket(basket);
}
async function addItemLine(itemId: string, quantity = 1) {
applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
}
async function addSlotLine(slotId: string) {
applyBasket(await callApi({ action: 'add_slot', slotId }));
}
async function updateQuantity(lineId: string, quantity: number) {
applyBasket(await callApi({ action: 'update_quantity', lineId, quantity }));
}
async function removeLine(lineId: string) {
applyBasket(await callApi({ action: 'remove_line', lineId }));
}
return {
get lines() {
return lines;
},
get total() {
return total;
},
get count() {
return count;
},
get status() {
return status;
},
refresh,
syncFrom,
addItemLine,
addSlotLine,
updateQuantity,
removeLine
};
}
export function setBasketContext(store: BasketStore) {
setContext(BASKET_KEY, store);
}
export function getBasketContext(): BasketStore {
const store = getContext<BasketStore>(BASKET_KEY);
if (!store) throw new Error('Basket store not found in context — is this component inside the public layout?');
return store;
}

View file

@ -0,0 +1,54 @@
<script lang="ts">
import type { BlockBackground, BlockForeground } from '$lib/types';
let {
background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground,
foreground = {} as BlockForeground,
children
} = $props<{
background?: BlockBackground;
foreground?: BlockForeground;
children?: import('svelte').Snippet;
}>();
function bgStyle() {
const parts: string[] = [];
if (background.type === 'color' && background.color) {
parts.push(`background-color: ${background.color};`);
}
if (background.type === 'image' && background.imageUrl) {
parts.push(`background-image: url(${background.imageUrl});`);
parts.push(`background-size: cover;`);
parts.push(`background-position: center;`);
parts.push(`background-repeat: no-repeat;`);
parts.push(`background-attachment: ${background.attachment};`);
}
return parts.join(' ');
}
function fgStyle() {
const parts: string[] = [];
if (foreground.headingColor) {
parts.push(`--fg-heading: ${foreground.headingColor};`);
}
if (foreground.textColor) {
parts.push(`--fg-body: ${foreground.textColor};`);
}
if (foreground.subheadingColor) {
parts.push(`--fg-subheading: ${foreground.subheadingColor};`);
}
return parts.join(' ');
}
</script>
<div style={bgStyle() + ' ' + fgStyle()} class="relative">
{#if background.type === 'image' && background.overlay && background.imageUrl}
<div
class="pointer-events-none absolute inset-0"
style={`background-color: rgba(0,0,0,${background.overlayOpacity / 100});`}
></div>
{/if}
<div class="relative z-10">
{@render children()}
</div>
</div>

View file

@ -0,0 +1,55 @@
<script lang="ts">
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord, SlotRecord } from '$lib/types';
import BackgroundWrapper from './BackgroundWrapper.svelte';
import TextBlock from './TextBlock.svelte';
import ImageTextBlock from './ImageTextBlock.svelte';
import TimelineBlock from './TimelineBlock.svelte';
import HeroBlock from './HeroBlock.svelte';
import ButtonBlock from './ButtonBlock.svelte';
import SpacerBlock from './SpacerBlock.svelte';
import TestimonialsBlock from './TestimonialsBlock.svelte';
import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte';
import ShopBlock from './ShopBlock.svelte';
import CheckoutBlock from './CheckoutBlock.svelte';
let { blocks = [], calendarEvents = [], items = [], slots = [] } = $props<{
blocks: ContentBlock[];
calendarEvents?: CalendarEventRecord[];
items?: ItemRecord[];
slots?: SlotRecord[];
}>();
function getBg(block: ContentBlock): BlockBackground {
return (block.data._background as BlockBackground) || { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
}
function getFg(block: ContentBlock): BlockForeground {
return (block.data._foreground as BlockForeground) || {};
}
</script>
{#each blocks as block (block.id)}
<BackgroundWrapper background={getBg(block)} foreground={getFg(block)}>
{#if block.type === 'text'}
<TextBlock data={block.data} />
{:else if block.type === 'image_text'}
<ImageTextBlock data={block.data} />
{:else if block.type === 'timeline'}
<TimelineBlock data={block.data} />
{:else if block.type === 'hero'}
<HeroBlock data={block.data} />
{:else if block.type === 'button'}
<ButtonBlock data={block.data} />
{:else if block.type === 'spacer'}
<SpacerBlock data={block.data} />
{:else if block.type === 'testimonials'}
<TestimonialsBlock data={block.data} />
{:else if block.type === 'upcoming_calendar'}
<UpcomingCalendarBlock data={block.data} events={calendarEvents} />
{:else if block.type === 'shop'}
<ShopBlock data={block.data} {items} {slots} />
{:else if block.type === 'checkout'}
<CheckoutBlock data={block.data} />
{/if}
</BackgroundWrapper>
{/each}

View file

@ -0,0 +1,26 @@
<script lang="ts">
let { data } = $props<{ data: Record<string, any> }>();
const alignmentClasses: Record<string, string> = {
left: 'justify-start',
center: 'justify-center',
right: 'justify-end'
};
const sizeClasses: Record<string, string> = {
xs: 'btn-xs',
sm: 'btn-sm',
md: '',
lg: 'btn-lg'
};
</script>
<div class="flex {alignmentClasses[data.alignment] || 'justify-center'}">
<a
href={data.href || '#'}
class="btn btn-{data.variant || 'primary'} {sizeClasses[data.size] || ''}"
style={data.color ? `background-color: ${data.color}; border-color: ${data.color};` : ''}
>
{data.label || 'Button'}
</a>
</div>

View file

@ -0,0 +1,402 @@
<script lang="ts">
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import type { CheckoutBlockData } from '$lib/types';
import { getBasketContext } from '$lib/basket.svelte';
import { loadStripe } from '$lib/stripe-client';
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
let { data = {} } = $props<{ data: CheckoutBlockData }>();
const basket = getBasketContext();
const customer = $state({ name: '', email: '', phone: '', notes: '' });
let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle');
let errorMsg = $state('');
let paymentDiv = $state<HTMLDivElement | null>(null);
let stripe: Stripe | null = null;
let elements: StripeElements | null = null;
let paymentElement: StripePaymentElement | null = null;
let mountedForClientSecret: string | null = null;
// Tracks lines that have an update/remove request in flight, to disable their controls.
let pendingLines = $state<Set<string>>(new Set());
// Reset the mounted Payment Element back to 'idle' when the basket changes
// after the intent was created, so a new intent is made with the new total.
let lastSig = '';
let basketChanged = $state(false);
$effect(() => {
const sig = basket.lines.map((l) => `${l.id}:${l.quantity}`).join('|') + `@${basket.total}`;
if (lastSig && sig !== lastSig && (payState === 'ready' || payState === 'creating')) {
resetPayment();
basketChanged = true;
} else if (sig === lastSig) {
basketChanged = false;
}
lastSig = sig;
});
const currency = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
const payLabel = $derived(
payState === 'confirming'
? 'Confirming…'
: payState === 'creating'
? 'Preparing payment…'
: `Pay ${currency.format(basket.total)}`
);
function formatSlotTime(iso: string) {
return new Date(iso).toLocaleString(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
function resetPayment() {
paymentElement?.unmount();
paymentElement = null;
elements = null;
mountedForClientSecret = null;
payState = 'idle';
}
function validateCustomer(): boolean {
if (!customer.name.trim() || !customer.email.trim()) {
errorMsg = 'Please fill in your name and email address.';
return false;
}
return true;
}
async function startPayment() {
errorMsg = '';
basketChanged = false;
if (!validateCustomer()) return;
payState = 'creating';
try {
// Refresh from server first — slot holds may have lapsed (10-min TTL)
// and the client store would still show stale lines. The server
// re-reserves any slot that is still held, so a service won't vanish
// just because its hold expired while you were filling in this form.
const slotLinesBefore = basket.lines.filter((l) => l.lineType === 'slot');
await basket.refresh();
const lostSlots = slotLinesBefore.filter(
(l) => !basket.lines.some((nl) => nl.id === l.id)
);
if (basket.lines.length === 0) {
throw new Error('Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
}
if (lostSlots.length) {
const names = lostSlots.map((l) => l.itemName).filter(Boolean).join(', ');
throw new Error(
names
? `Your time slot for ${names} is no longer available (it may have expired or been booked by someone else). Please pick another slot from the shop.`
: 'A time slot in your basket is no longer available — please pick another slot from the shop.'
);
}
const res = await fetch('/api/checkout/create-intent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...customer })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(
err?.message ||
`Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.`
);
}
const { clientSecret } = await res.json();
stripe = await loadStripe();
if (!stripe) throw new Error('Payment system failed to load. Please refresh and try again.');
if (mountedForClientSecret !== clientSecret) {
resetPayment();
elements = stripe.elements({
clientSecret,
appearance: {
theme: 'flat',
variables: {
colorPrimary: '#8a9a7b',
colorBackground: '#ffffff',
colorText: '#2c2c2c',
colorDanger: '#c9825f',
fontFamily: 'DM Sans, sans-serif',
borderRadius: '12px'
}
}
});
paymentElement = elements.create('payment');
if (browser && paymentDiv) {
paymentElement.mount(paymentDiv);
mountedForClientSecret = clientSecret;
}
}
payState = 'ready';
} catch (e) {
errorMsg = e instanceof Error ? e.message : 'Something went wrong. Please try again.';
payState = 'idle';
}
}
async function confirmPayment() {
if (!stripe || !elements || !mountedForClientSecret) return;
errorMsg = '';
payState = 'confirming';
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: window.location.origin + '/checkout/return',
receipt_email: customer.email
},
redirect: 'if_required'
});
if (error) {
errorMsg = error.message ?? 'Payment failed. Please try again.';
payState = 'ready';
} else {
const intentId = mountedForClientSecret.split('_secret_')[0];
goto('/checkout/return?payment_intent=' + encodeURIComponent(intentId));
}
}
async function changeQuantity(lineId: string, current: number, delta: number) {
const qty = current + delta;
if (qty < 1 || pendingLines.has(lineId)) return;
pendingLines = new Set(pendingLines).add(lineId);
try {
await basket.updateQuantity(lineId, qty);
} catch (e) {
errorMsg = e instanceof Error ? e.message : 'Failed to update quantity.';
} finally {
const next = new Set(pendingLines);
next.delete(lineId);
pendingLines = next;
}
}
async function removeLine(lineId: string) {
if (pendingLines.has(lineId)) return;
pendingLines = new Set(pendingLines).add(lineId);
try {
await basket.removeLine(lineId);
} catch (e) {
errorMsg = e instanceof Error ? e.message : 'Failed to remove item.';
} finally {
const next = new Set(pendingLines);
next.delete(lineId);
pendingLines = next;
}
}
</script>
<section class="mx-auto max-w-3xl px-6 py-16">
{#if data.title}
<h2 class="font-serif text-3xl font-bold md:text-4xl">{data.title}</h2>
{/if}
{#if data.heading}
<p class="mt-2 text-fg-body/70">{data.heading}</p>
{/if}
{#if basket.lines.length === 0}
<div class="mt-12 rounded-2xl border border-charcoal/10 bg-white/60 px-6 py-16 text-center">
<p class="font-serif text-xl">Your basket is empty</p>
<p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
</div>
{:else}
<!-- Basket lines -->
<ul class="mt-8 space-y-4">
{#each basket.lines as line (line.id)}
{@const pending = pendingLines.has(line.id)}
<li class="flex items-center gap-4 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
{#if line.itemImageUrl}
<img
src={line.itemImageUrl}
alt={line.itemName ?? 'Item'}
class="h-16 w-16 shrink-0 rounded-xl object-cover"
/>
{:else}
<div class="flex h-16 w-16 shrink-0 items-center justify-center rounded-xl bg-sage/15 font-serif text-xl text-sage-dark">
{(line.itemName ?? '?').charAt(0).toUpperCase()}
</div>
{/if}
<div class="min-w-0 flex-1">
<p class="truncate font-medium">{line.itemName ?? 'Item'}</p>
{#if line.lineType === 'slot' && line.slotStart}
<p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p>
{/if}
<p class="text-sm text-fg-body/70">{currency.format(line.itemPrice ?? 0)}</p>
</div>
{#if line.lineType === 'item'}
<div class="flex items-center gap-2">
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
disabled={pending || line.quantity <= 1}
aria-label="Decrease quantity"
onclick={() => changeQuantity(line.id, line.quantity, -1)}
>
−
</button>
<span class="w-6 text-center">{line.quantity}</span>
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
disabled={pending}
aria-label="Increase quantity"
onclick={() => changeQuantity(line.id, line.quantity, 1)}
>
+
</button>
</div>
{/if}
<p class="w-20 shrink-0 text-right font-medium">
{currency.format((line.itemPrice ?? 0) * line.quantity)}
</p>
<button
type="button"
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-charcoal/50 transition-colors hover:bg-terracotta/10 hover:text-terracotta disabled:opacity-40"
disabled={pending}
aria-label="Remove {line.itemName ?? 'item'}"
onclick={() => removeLine(line.id)}
>
✕
</button>
</li>
{/each}
</ul>
<!-- Totals -->
<div class="mt-6 rounded-2xl border border-charcoal/10 bg-white p-5">
<div class="flex items-center justify-between">
<span class="text-fg-body/70">Subtotal</span>
<span class="font-serif text-xl font-bold">{currency.format(basket.total)}</span>
</div>
</div>
<div class="mt-10 grid gap-10 md:grid-cols-2">
<!-- Customer details -->
<form
class="space-y-4"
novalidate
onsubmit={(e) => {
e.preventDefault();
startPayment();
}}
>
<h3 class="font-serif text-xl font-bold">Your details</h3>
<div>
<label class="mb-1 block text-sm font-medium" for="checkout-name">Name *</label>
<input
id="checkout-name"
type="text"
required
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
bind:value={customer.name}
autocomplete="name"
/>
</div>
<div>
<label class="mb-1 block text-sm font-medium" for="checkout-email">Email *</label>
<input
id="checkout-email"
type="email"
required
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
bind:value={customer.email}
autocomplete="email"
/>
</div>
<div>
<label class="mb-1 block text-sm font-medium" for="checkout-phone">Phone</label>
<input
id="checkout-phone"
type="tel"
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
bind:value={customer.phone}
autocomplete="tel"
/>
</div>
<div>
<label class="mb-1 block text-sm font-medium" for="checkout-notes">
{data.notesLabel || 'Notes or special requests'}
</label>
<textarea
id="checkout-notes"
rows="3"
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
bind:value={customer.notes}
></textarea>
</div>
{#if payState === 'idle' || payState === 'creating'}
<button
type="submit"
class="btn w-full rounded-full border-0 text-white"
style="background-color: var(--color-primary, #8a9a7b);"
disabled={payState === 'creating'}
>
{payLabel}
</button>
{/if}
</form>
<!-- Payment -->
<div>
<h3 class="font-serif text-xl font-bold">Payment</h3>
{#if errorMsg}
<div class="mt-4 flex items-start justify-between gap-3 rounded-xl border border-terracotta/40 bg-terracotta/10 px-4 py-3 text-sm text-charcoal" role="alert">
<span>{errorMsg}</span>
<button type="button" class="shrink-0 font-bold" aria-label="Dismiss" onclick={() => (errorMsg = '')}>✕</button>
</div>
{/if}
{#if basketChanged}
<p class="mt-4 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm">
Basket changed — please press Pay again.
</p>
{/if}
<div
bind:this={paymentDiv}
class="mt-4 rounded-xl border border-charcoal/15 bg-white p-4 {payState === 'ready' || payState === 'confirming' ? '' : 'hidden'}"
hidden={payState !== 'ready' && payState !== 'confirming'}
></div>
{#if payState === 'ready' || payState === 'confirming'}
<button
type="button"
class="btn mt-4 w-full rounded-full border-0 text-white"
style="background-color: var(--color-primary, #8a9a7b);"
disabled={payState === 'confirming'}
onclick={confirmPayment}
>
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${currency.format(basket.total)}`}
</button>
{/if}
{#if payState === 'idle' && !errorMsg}
<p class="mt-4 text-sm text-fg-body/70">
Fill in your details and press Pay to continue to secure payment.
</p>
{/if}
</div>
</div>
{/if}
</section>

View file

@ -0,0 +1,30 @@
<script lang="ts">
let { data } = $props<{
data: {
heading?: string;
subheading?: string;
buttonLabel?: string;
buttonUrl?: string;
};
}>();
</script>
<section class="relative flex min-h-[80vh] items-center justify-center overflow-hidden px-6 py-20 md:min-h-[90vh]">
<div class="relative z-10 mx-auto max-w-4xl text-center">
<h1 class="animate-fade-in text-5xl leading-tight text-fg-heading md:text-7xl lg:text-8xl" style="font-family: 'Playfair Display', Georgia, serif;">
{data.heading || 'Holistic and Experiential Learning about Happiness'}
</h1>
{#if data.subheading}
<p class="animate-fade-in mx-auto mt-6 max-w-2xl text-lg leading-relaxed text-fg-subheading/70 md:text-xl" style="animation-delay: 0.15s;">
{data.subheading}
</p>
{/if}
{#if data.buttonLabel}
<div class="animate-fade-in mt-10" style="animation-delay: 0.3s;">
<a class="btn rounded-full border-0 bg-sage px-10 py-3 text-lg text-white shadow-lg transition hover:bg-sage-dark hover:shadow-xl" href={data.buttonUrl || '/book'}>
{data.buttonLabel}
</a>
</div>
{/if}
</div>
</section>

View file

@ -0,0 +1,22 @@
<script lang="ts">
import { scrollReveal } from '$lib/scrollReveal';
let { data } = $props<{
data: { url?: string; alt?: string; content?: string; imagePosition?: 'left' | 'right' };
}>();
</script>
<section use:scrollReveal class="reveal mx-auto max-w-6xl px-6 py-14 md:py-20">
<div class="grid items-center gap-10 md:grid-cols-2">
<div class:md:order-2={data.imagePosition === 'right'} class="overflow-hidden rounded-[2rem] bg-sage/10 shadow-sm">
{#if data.url}
<img class="aspect-[4/5] w-full object-cover" src={data.url} alt={data.alt || ''} />
{:else}
<div class="grid aspect-[4/5] place-items-center text-sage-dark">Upload an image</div>
{/if}
</div>
<div class="prose-wellness text-lg text-fg-body/80">
{@html data.content || '<h2>A gentler rhythm</h2><p>Pair meaningful copy with a calming studio image.</p>'}
</div>
</div>
</section>

View file

@ -0,0 +1,313 @@
<script lang="ts">
import type { ShopBlockData, ItemRecord, SlotRecord } from '$lib/types';
import { getBasketContext } from '$lib/basket.svelte';
import { getCurrentAndNextMonths } from '$lib/calendar';
let { data = {}, items = [], slots = [] } = $props<{
data: ShopBlockData;
items?: ItemRecord[];
slots?: SlotRecord[];
}>();
const basket = getBasketContext();
// Per-card interaction state. Instances are created per component instance
// (never shared at module level); keyed by item id so each card is independent.
class CardState {
pickerOpen = $state(false);
selectedDayKey = $state<string | null>(null);
adding = $state(false);
errorMsg = $state<string | null>(null);
justAdded = $state(false);
pendingSlotId = $state<string | null>(null);
}
let cardStates = $state<Record<string, CardState>>({});
const months = getCurrentAndNextMonths();
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
let visibleItems: ItemRecord[] = $derived.by(() => {
let result: ItemRecord[] = items;
if (data.itemTypeFilter === 'item' || data.itemTypeFilter === 'item_with_time') {
result = result.filter((i) => i.type === data.itemTypeFilter);
}
if (data.itemIds?.length) {
const wanted = new Set(data.itemIds);
result = result
.filter((i) => wanted.has(i.id))
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
}
return result;
});
// item id -> day key ('YYYY-MM-DD') -> slots on that day, sorted by start time
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
const map = new Map<string, Map<string, SlotRecord[]>>();
for (const slot of slots) {
const day = new Date(slot.start);
if (Number.isNaN(day.getTime())) continue;
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
let itemMap = map.get(slot.item);
if (!itemMap) {
itemMap = new Map();
map.set(slot.item, itemMap);
}
const list = itemMap.get(key);
if (list) list.push(slot);
else itemMap.set(key, [slot]);
}
for (const itemMap of map.values()) {
for (const list of itemMap.values()) {
list.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
}
}
return map;
});
let isList = $derived(data.layout === 'list');
// Lazily create card state for whatever items are rendered.
$effect(() => {
for (const item of visibleItems) {
if (!cardStates[item.id]) cardStates[item.id] = new CardState();
}
});
function togglePicker(itemId: string) {
const state = cardStates[itemId];
if (!state) return;
state.pickerOpen = !state.pickerOpen;
state.errorMsg = null;
state.justAdded = false;
state.selectedDayKey = null;
}
function errorMessage(e: unknown, fallback: string) {
return e instanceof Error && e.message ? e.message : fallback;
}
async function addItem(itemId: string) {
const state = cardStates[itemId];
if (!state || state.adding) return;
state.adding = true;
state.errorMsg = null;
try {
await basket.addItemLine(itemId, 1);
} catch (e) {
state.errorMsg = errorMessage(e, 'Could not add this item to your basket.');
} finally {
state.adding = false;
}
}
async function addSlot(itemId: string, slotId: string) {
const state = cardStates[itemId];
if (!state || state.adding) return;
state.adding = true;
state.pendingSlotId = slotId;
state.errorMsg = null;
try {
await basket.addSlotLine(slotId);
state.justAdded = true;
} catch (e) {
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
} finally {
state.adding = false;
state.pendingSlotId = null;
}
}
function formatTime(iso: string) {
return new Date(iso).toLocaleTimeString(undefined, timeFormat);
}
</script>
<section class="mx-auto max-w-6xl px-6 py-16">
{#if data.title}
<h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2>
{/if}
<div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}>
{#each visibleItems as item (item.id)}
{@const ui = cardStates[item.id]}
{@const itemSlotsByDay = slotsByDay.get(item.id)}
{@const isService = item.type === 'item_with_time'}
{@const soldOut = !isService && item.stock === 0}
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
<article
class={isList
? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:gap-6'
: 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'}
>
{#if item.imageUrl}
<img
src={item.imageUrl}
alt={item.name}
class={isList ? 'h-44 w-full rounded-xl object-cover sm:h-auto sm:w-56 sm:shrink-0' : 'h-52 w-full object-cover'}
/>
{:else}
<div
class={isList
? 'flex h-44 w-full items-center justify-center rounded-xl bg-sage/15 font-serif text-5xl text-sage-dark sm:h-auto sm:w-56 sm:shrink-0'
: 'flex h-52 w-full items-center justify-center bg-sage/15 font-serif text-5xl text-sage-dark'}
aria-hidden="true"
>
{item.name.trim().charAt(0).toUpperCase() || '·'}
</div>
{/if}
<div class={isList ? 'mt-4 flex min-w-0 flex-1 flex-col sm:mt-0' : 'flex flex-1 flex-col p-5'}>
<h3 class="font-serif text-xl text-charcoal">{item.name}</h3>
{#if item.description}
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
{/if}
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
<span class="text-lg font-semibold text-sage-dark">{priceFormatter.format(item.price)}</span>
{#if isService && item.duration != null}
<span class="text-xs text-charcoal/60">{item.duration} min</span>
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Only {item.stock} left
</span>
{:else if soldOut}
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Sold out
</span>
{/if}
</div>
{#if ui?.errorMsg}
<div
class="mt-3 flex items-start justify-between gap-2 rounded-lg border border-terracotta/30 bg-terracotta/10 px-3 py-2 text-sm text-charcoal"
role="alert"
>
<span>{ui.errorMsg}</span>
<button
type="button"
class="shrink-0 leading-none text-charcoal/60 hover:text-charcoal"
aria-label="Dismiss error"
onclick={() => (ui.errorMsg = null)}
>
&times;
</button>
</div>
{/if}
<div class="mt-4 flex items-center gap-3">
{#if isService}
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen
? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
: itemSlotsByDay?.size
? 'bg-sage text-white hover:bg-sage-dark'
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
disabled={!itemSlotsByDay?.size && !ui?.pickerOpen}
onclick={() => togglePicker(item.id)}
>
{itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'}
</button>
{:else}
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-full bg-sage px-6 py-2.5 text-sm font-medium text-white transition hover:bg-sage-dark disabled:cursor-not-allowed disabled:bg-charcoal/10 disabled:text-charcoal/50"
disabled={soldOut || ui?.adding}
onclick={() => addItem(item.id)}
>
{#if ui?.adding}<span class="loading loading-spinner loading-xs"></span>{/if}
{soldOut ? 'Sold out' : itemInBasket ? 'Add another' : 'Add to basket'}
</button>
{#if itemInBasket}
<a
href="/book"
class="inline-flex items-center gap-1 text-sm font-medium text-sage-dark underline-offset-2 hover:underline"
>✓ In basket</a
>
{/if}
{/if}
</div>
</div>
{#if isService && ui?.pickerOpen && itemSlotsByDay}
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
<p class="mb-3 text-sm font-medium text-charcoal/70">Select a date</p>
<div class="grid gap-6 sm:grid-cols-2">
{#each months as month (month.label)}
<div>
<p class="mb-2 text-center text-sm font-medium text-charcoal/70">{month.label}</p>
<div class="grid grid-cols-7 gap-1 text-center">
{#each weekdayLetters as letter, i (i)}
<span class="py-1 text-xs text-charcoal/40">{letter}</span>
{/each}
{#each month.days as day (day.dateKey)}
{@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)}
{@const selected = selectable && ui.selectedDayKey === day.dateKey}
<button
type="button"
disabled={!selectable}
aria-pressed={selected}
onclick={() => (ui.selectedDayKey = day.dateKey)}
class="aspect-square rounded-full text-sm transition {selected
? 'bg-sage font-semibold text-white'
: selectable
? 'cursor-pointer bg-sage/15 font-medium text-charcoal hover:bg-sage/35'
: 'cursor-default text-charcoal/25'} {!day.inMonth ? 'opacity-40' : ''} {day.isToday &&
!selected
? 'ring-1 ring-sage/60'
: ''}"
>
{day.dayNumber}
</button>
{/each}
</div>
</div>
{/each}
</div>
{#if ui.selectedDayKey}
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">Available times</p>
<div class="flex flex-wrap gap-2">
{#each daySlots as slot (slot.id)}
{@const slotInBasket = basket.lines.some((l) => l.slot === slot.id)}
<button
type="button"
disabled={slotInBasket || ui.adding}
onclick={() => addSlot(item.id, slot.id)}
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {slotInBasket
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
!slotInBasket
? 'cursor-wait'
: ''}"
>
{#if ui.pendingSlotId === slot.id}
<span class="loading loading-spinner loading-xs"></span>
{/if}
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{slotInBasket
? ' · In basket'
: ''}
</button>
{/each}
</div>
{:else}
<p class="mt-4 text-sm text-charcoal/60">
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
</p>
{/if}
{#if ui.justAdded}
<p class="mt-3 text-sm font-medium text-sage-dark">
Added ✓ — <a href="/book" class="underline underline-offset-2 hover:no-underline">view basket</a>
</p>
{/if}
</div>
{/if}
</article>
{/each}
</div>
</section>

View file

@ -0,0 +1,7 @@
<script lang="ts">
let { data } = $props<{ data: Record<string, any> }>();
const height = $derived(data.height ?? 64);
</script>
<div style="height: {height}px;" class="w-full"></div>

View file

@ -0,0 +1,87 @@
<script lang="ts">
let { data } = $props<{ data: Record<string, any> }>();
const testimonials = data.items || [
{ text: 'Recently I started to experience incredible whole-body orgasms. And now I know how it works. My awareness around sexuality changed for good and I feel like a boss of my own life. What a joy to have this freedom of choice.', title: 'Anne' },
{ text: 'I never thought it was possible to sense so much pleasure in my body without intense stimulations I got used to. After the series of sessions, I could feel something like a trance state by receiving only a gentle touch. That was a totally new experience for me.', title: 'Espen' },
{ text: "Eva's sexual healing methods should be accessible to everyone. I am amazed by the depth and integrity of the message she conveys through her work. I was meeting Eva for healing my body and, as a result, I reconnected with my heart and soul too.", title: 'Marie' },
{ text: "It is hard to surprise me with any sexual activity since I had many exciting experiments in my life. But I always suspected that there might be something more I have not yet felt and tried. Thanks to Eva I realised how much power I've got. Under her guidance, I have learnt to maximise my orgasmic potential and consciously play with arousal. By the way, my wife is also happy that I became enthusiastic about new sexual practices.", title: 'Jan' }
];
const title = data.title || 'What They Say About Me';
// Simple state for carousel
let currentIndex = $state(0);
const totalSlides = testimonials.length;
function next() {
currentIndex = (currentIndex + 1) % totalSlides;
}
function prev() {
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
}
</script>
<div class="relative min-h-[400px]">
<div class="flex flex-col items-center px-4 py-12 min-h-[400px]">
<!-- Title -->
<h2 class="text-fg-heading text-2xl md:text-3xl font-light tracking-wide">
{title}
</h2>
<!-- Testimonial carousel - fills remaining space and centers content vertically -->
<div class="w-full max-w-3xl flex-1 flex items-center justify-center">
<!-- Slides are stacked in a grid so the carousel keeps the height of the tallest testimonial. -->
<div class="grid px-8 text-center w-full pt-4 md:pt-8">
{#each testimonials as testimonial, i}
<div class="col-start-1 row-start-1 transition-opacity duration-300 {i === currentIndex ? 'opacity-100' : 'pointer-events-none opacity-0'}" aria-hidden={i !== currentIndex}>
<p class="text-fg-body/85 text-lg md:text-xl font-light leading-relaxed mb-8">
"{testimonial.text}"
</p>
<p class="text-fg-subheading font-medium tracking-wider">
— {testimonial.title}
</p>
</div>
{/each}
</div>
</div>
<!-- Navigation arrows -->
<div class="flex justify-center items-center gap-8">
<button
type="button"
onclick={prev}
class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
aria-label="Previous slide"
>
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
<polyline points="6.5,0.5 1.5,6.5 6.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
</svg>
</button>
<!-- Dots/bullets -->
<div class="flex text-fg-heading gap-3">
{#each testimonials as _, i}
<button
type="button"
class="w-2.5 h-2.5 rounded-full border-2 transition-colors {i === currentIndex ? 'bg-current' : 'border-current'}"
aria-label="Go to slide {i + 1}"
onclick={() => (currentIndex = i)}
></button>
{/each}
</div>
<button
type="button"
onclick={next}
class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
aria-label="Next slide"
>
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
<polyline points="0.5,0.5 5.5,6.5 0.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
</svg>
</button>
</div>
</div>
</div>

View file

@ -0,0 +1,11 @@
<script lang="ts">
import { scrollReveal } from '$lib/scrollReveal';
let { data } = $props<{ data: { content?: string } }>();
</script>
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
<div class="prose-wellness text-lg text-fg-body/85">
{@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'}
</div>
</section>

View file

@ -0,0 +1,31 @@
<script lang="ts">
import { scrollReveal } from '$lib/scrollReveal';
type TimelineItem = { title: string; description: string };
let { data } = $props<{ data: { items?: TimelineItem[] } }>();
let items = $derived(data.items?.length ? data.items : [
{ title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' }
]);
let widths = $derived(items.map((_: TimelineItem, i: number) => {
const opts = ['w-[78%]', 'w-[85%]', 'w-[90%]', 'w-[95%]', 'w-[98%]'];
return opts[(i * 7 + 3) % opts.length];
}));
</script>
<section class="mx-auto max-w-7xl px-6 py-12">
<div class="mb-8 text-center">
<p class="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-sage-dark">Journey</p>
<h2 class="text-3xl md:text-4xl" use:scrollReveal>A practice shaped over time</h2>
</div>
<div class="relative md:before:absolute md:before:left-1/2 md:before:top-0 md:before:h-full md:before:w-px md:before:bg-sage/30">
{#each items as item, index}
<div use:scrollReveal class="reveal relative mb-[-1rem] grid gap-4 md:grid-cols-2 md:gap-8">
<div class="hidden md:block" class:md:order-2={index % 2 === 0}></div>
<article class="rounded-2xl bg-white/75 p-5 shadow-sm ring-1 ring-charcoal/5 -mt-4 {widths[index]} {index % 2 === 0 ? 'md:ml-auto md:text-right' : ''}">
<h3 class="text-xl">{item.title}</h3>
<p class="mt-2 text-sm leading-6 text-fg-body/70">{item.description}</p>
</article>
</div>
{/each}
</div>
</section>

View file

@ -0,0 +1,125 @@
<script lang="ts">
import type { CalendarEventRecord, UpcomingCalendarBlockData } from '$lib/types';
import {
dateKey,
eventMatchesCategories,
eventOverlapsDay,
eventRange,
formatEventDateRange,
getCurrentAndNextMonths,
isExternalLink,
normalizeLink,
sortEvents
} from '$lib/calendar';
let { data = {}, events = [] } = $props<{
data: UpcomingCalendarBlockData;
events?: CalendarEventRecord[];
}>();
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let months = $derived(getCurrentAndNextMonths());
let selectedCategories = $derived(data.categories || []);
let visibleEvents = $derived(sortEvents(events.filter((event: CalendarEventRecord) => event.published && eventMatchesCategories(event, selectedCategories))));
function eventsForDay(date: Date) {
return visibleEvents.filter((event) => eventOverlapsDay(event, date));
}
function eventStyle(event: CalendarEventRecord) {
return `--event-color: ${event.color || '#8a9a7b'};`;
}
function segmentMeta(event: CalendarEventRecord, date: Date) {
const { start, end } = eventRange(event);
const isStart = dateKey(start) === dateKey(date);
const isEnd = dateKey(end) === dateKey(date);
const startsWeek = date.getDay() === 0;
const endsWeek = date.getDay() === 6;
const visualStart = isStart || startsWeek;
const visualEnd = isEnd || endsWeek;
return {
showLabel: visualStart,
classes: [
visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3',
visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3',
visualStart && visualEnd ? 'mx-0' : '',
!visualStart && !visualEnd ? '-mx-3' : ''
].filter(Boolean).join(' ')
};
}
</script>
<section class="mx-auto max-w-7xl px-6 py-16">
<div class="mb-10 text-center">
<h2 class="font-display mt-2 text-4xl text-charcoal md:text-5xl">{data.title}</h2>
</div>
{#if visibleEvents.length === 0}
<div class="mx-auto max-w-2xl rounded-[2rem] border border-sage/20 bg-white/70 p-8 text-center shadow-sm">
<p class="text-charcoal/70">No upcoming events are available for the selected categories.</p>
</div>
{:else}
<div class="isolate grid gap-8 lg:grid-cols-2">
{#each months as month}
<div class="relative z-0 overflow-visible rounded-[2rem] border border-sage/15 bg-white/80 p-5 shadow-sm backdrop-blur hover:z-[9000] focus-within:z-[9000]">
<h3 class="font-display mb-5 text-center text-3xl text-charcoal">{month.label}</h3>
<div class="mb-2 grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase tracking-wide text-charcoal/45">
{#each weekdays as weekday}<div>{weekday}</div>{/each}
</div>
<div class="grid grid-cols-7 gap-1 overflow-visible">
{#each month.days as day}
<div class="relative min-h-28 overflow-visible rounded-2xl border p-2 {day.inMonth ? 'border-sage/10 bg-warm/60' : 'border-sage/5 bg-warm/25'}" class:ring-2={day.isToday} class:ring-sage={day.isToday}>
<div class="mb-1 flex items-center justify-between">
<span class="text-sm font-semibold {day.inMonth ? 'text-charcoal/70' : 'text-charcoal/30'}">{day.dayNumber}</span>
</div>
<div class="space-y-1">
{#each eventsForDay(day.date) as event}
{@const href = normalizeLink(event.link)}
{@const label = `${event.name}${event.description ? `: ${event.description}` : ''}`}
{@const segment = segmentMeta(event, day.date)}
{#if href}
<a
class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] hover:shadow-md focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
href={href}
target={isExternalLink(href) ? '_blank' : undefined}
rel={isExternalLink(href) ? 'noreferrer' : undefined}
style={eventStyle(event)}
aria-label={label}
>
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
<span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
<span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
<strong class="block">{event.name}</strong>
<span class="block opacity-80">{formatEventDateRange(event)}</span>
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
</span>
</a>
{:else}
<span
class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
style={eventStyle(event)}
tabindex="0"
role="button"
aria-label={label}
>
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
<span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
<span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
<strong class="block">{event.name}</strong>
<span class="block opacity-80">{formatEventDateRange(event)}</span>
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
</span>
</span>
{/if}
{/each}
</div>
</div>
{/each}
</div>
</div>
{/each}
</div>
{/if}
</section>

View file

@ -0,0 +1 @@
export * from '$shared/calendar';

View file

@ -0,0 +1,139 @@
import type { CalendarEventRecord, ContentBlock } from '$lib/types';
/**
* The portable export format.
* Images are stored as base64 data-URIs so the file is fully self-contained.
*/
export type SiteExport = {
version: 1;
exportedAt: string;
pages: {
slug: string;
title: string;
blocks: ContentBlock[];
published: boolean;
}[];
globals: {
key: string;
data: Record<string, unknown>;
}[];
events?: Omit<CalendarEventRecord, 'id'>[];
/** Maps original PocketBase file URLs → base64 data-URI */
images: Record<string, string>;
};
/** Regex to match PocketBase file URLs */
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
/**
* Extract all PocketBase image URLs from a value (recursive).
*/
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
if (typeof value === 'string') {
let match: RegExpExecArray | null;
const re = new RegExp(PB_FILE_RE.source, 'g');
while ((match = re.exec(value)) !== null) {
urls.add(match[0]);
}
} else if (Array.isArray(value)) {
for (const item of value) extractImageUrls(item, urls);
} else if (value && typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
}
return urls;
}
/**
* Replace all PocketBase URLs in a value with a placeholder key.
*/
export function replaceUrlsWithKeys(
value: unknown,
urlToKey: Map<string, string>
): unknown {
if (typeof value === 'string') {
let result = value;
for (const [url, key] of urlToKey) {
result = result.replace(url, `__IMG__${key}__`);
}
return result;
}
if (Array.isArray(value)) {
return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
}
if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = replaceUrlsWithKeys(v, urlToKey);
}
return obj;
}
return value;
}
/**
* Restore image placeholders back to real URLs after import.
*/
export function restorePlaceholders(
value: unknown,
keyToUrl: Map<string, string>
): unknown {
if (typeof value === 'string') {
let result = value;
for (const [key, url] of keyToUrl) {
result = result.replace(`__IMG__${key}__`, url);
}
return result;
}
if (Array.isArray(value)) {
return value.map((item) => restorePlaceholders(item, keyToUrl));
}
if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = restorePlaceholders(v, keyToUrl);
}
return obj;
}
return value;
}
/**
* Generate a short unique key for an image URL.
*/
export function urlToKey(url: string): string {
const parts = url.split('/');
const filename = parts[parts.length - 1] || 'img';
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
return `${id}_${filename}`;
}
/**
* Fetch an image and return it as a base64 data-URI string.
*/
export async function fetchImageAsBase64(url: string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
const blob = await response.blob();
const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
return `data:${blob.type};base64,${base64}`;
}
/**
* Convert a base64 data-URI back to a File object for upload.
*/
export function dataUriToFile(dataUri: string, filename: string): File {
const [header, base64] = dataUri.split(',');
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return new File([bytes], filename, { type: mime });
}

37
app-admin/src/lib/pb.ts Normal file
View file

@ -0,0 +1,37 @@
import PocketBase from 'pocketbase';
import { env } from '$env/dynamic/public';
import { browser } from '$app/environment';
export const pbUrl = env.PUBLIC_POCKETBASE_URL;
export function createPocketBase(authCookie?: string, url = pbUrl) {
const pb = new PocketBase(url);
pb.autoCancellation(false);
if (authCookie) {
pb.authStore.loadFromCookie(authCookie, 'pb_auth');
} else if (browser) {
pb.authStore.loadFromCookie(document.cookie, 'pb_auth');
}
return pb;
}
export const pb = createPocketBase();
export function getFileUrl(collectionIdOrName: string, recordId: string, filename: string) {
return `${pbUrl}/api/files/${collectionIdOrName}/${recordId}/${filename}`;
}
export async function uploadMedia(file: File) {
const formData = new FormData();
formData.append('file', file);
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Upload failed (${res.status})`);
}
return res.json();
}

View file

@ -0,0 +1,30 @@
/**
* Scroll reveal Svelte action — applies a CSS class when the element enters the viewport.
* Usage: <div use:scrollReveal class="reveal">...</div>
* The `reveal` class is hidden initially; `reveal-visible` is added on intersection.
*/
export function scrollReveal(node: HTMLElement, delay: number = 0) {
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
if (delay > 0) {
node.style.transitionDelay = `${delay}s`;
}
node.classList.add('reveal-visible');
observer.unobserve(node);
}
}
},
{ threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
);
observer.observe(node);
return {
destroy() {
observer.disconnect();
}
};
}

View file

@ -0,0 +1,187 @@
import type PocketBase from 'pocketbase';
import type { Basket, BasketLine } from '$lib/types';
import { getFileUrl } from '$lib/pb';
export const BASKET_COOKIE = 'basket_id';
/** Basket lifetime — refreshed on every basket API call. */
export const BASKET_TTL_MS = 24 * 60 * 60 * 1000; // 24h
/** How long a slot stays held once added to a basket / after a failed payment. */
export const SLOT_HOLD_MS = 10 * 60 * 1000; // 10 min
/** Hold extended to this once a payment is in progress, so the slot survives
* the customer entering card details / retrying a declined card. */
export const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000; // 30 min
function now() {
return new Date();
}
function iso(date: Date) {
return date.toISOString();
}
/**
* Release any slots whose hold has expired, removing their basket lines
* and flipping them back to `available`. Also marks expired active
* baskets as `abandoned`. Runs lazily on basket reads / checkout.
*
* The expiry check is done in JS (parsing `heldUntil` as a UTC date) rather
* than via a PocketBase date-string filter, so a slot is never released
* *before* its hold genuinely lapses — regardless of how PocketBase stores /
* compares the date field. A slot is held for the full SLOT_HOLD_MS (or
* SLOT_CHECKOUT_HOLD_MS during payment).
*/
export async function sweepExpiredHolds(pb: PocketBase) {
const nowMs = Date.now();
// 1. Release expired slot holds (and drop the lines holding them)
const heldSlots = await pb
.collection('slots')
.getFullList({ filter: `status = 'held'` })
.catch(() => []);
for (const slot of heldSlots) {
const heldUntilMs = slot.heldUntil ? Date.parse(slot.heldUntil) : NaN;
// Still valid, or no parseable hold to judge by — leave it alone.
if (Number.isNaN(heldUntilMs) || heldUntilMs > nowMs) continue;
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: `slot = "${slot.id}"` })
.catch(() => []);
for (const line of lines) {
await pb.collection('basket_lines').delete(line.id).catch(() => {});
}
await pb
.collection('slots')
.update(slot.id, { status: 'available', heldUntil: null })
.catch(() => {});
}
// 2. Abandon expired active baskets (their slot holds were already
// covered by heldUntil above — same 10-min window < 24h basket TTL)
const nowIso = iso(now());
await pb
.collection('baskets')
.getFullList({ filter: `status = 'active' && expiresAt < "${nowIso}"` })
.then(async (expired) => {
for (const basket of expired) {
await pb.collection('baskets').update(basket.id, { status: 'abandoned' }).catch(() => {});
}
})
.catch(() => {});
}
/** Map raw PB records (with expand) to our Basket type. */
function mapBasket(record: Record<string, any>, lines: Record<string, any>[]): Basket {
const mappedLines: BasketLine[] = lines.map((line) => {
const item = line.expand?.item;
const slot = line.expand?.slot;
const media = item?.expand?.image;
return {
id: line.id,
basket: line.basket,
item: line.item,
slot: line.slot || null,
quantity: line.quantity,
lineType: line.lineType,
itemName: item?.name,
itemPrice: item?.price,
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
slotStart: slot?.start,
slotEnd: slot?.end
};
});
return {
id: record.id,
status: record.status,
expiresAt: record.expiresAt,
email: record.email || null,
customerDetails: record.customerDetails || null,
stripePaymentIntentId: record.stripePaymentIntentId || null,
lines: mappedLines
};
}
/** Load a basket + its lines (with item/slot expand) by basket id. */
export async function loadBasket(pb: PocketBase, basketId: string): Promise<Basket | null> {
try {
const record = await pb.collection('baskets').getOne(basketId);
if (record.status !== 'active') return null;
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot,item.image' });
return mapBasket(record, lines);
} catch {
return null;
}
}
/** Create a fresh active basket. */
export async function createBasket(pb: PocketBase): Promise<Basket> {
const record = await pb.collection('baskets').create({
status: 'active',
expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS))
});
return {
id: record.id,
status: 'active',
expiresAt: record.expiresAt,
email: null,
customerDetails: null,
stripePaymentIntentId: null,
lines: []
};
}
/** Touch the basket expiry (rolling TTL). */
export async function touchBasket(pb: PocketBase, basketId: string) {
await pb
.collection('baskets')
.update(basketId, { expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) })
.catch(() => {});
}
/** Release a slot hold for a basket line (slot back to available). */
export async function releaseLineHold(pb: PocketBase, line: { slot?: string | null }) {
if (!line.slot) return;
await pb
.collection('slots')
.update(line.slot, { status: 'available', heldUntil: null })
.catch(() => {});
}
/**
* Re-reserve (extend) the hold on every slot line in a basket, as long as
* the slot is still in `held` status. Used:
* - at checkout start (create-intent) with SLOT_CHECKOUT_HOLD_MS, so a
* service survives the customer entering card details / retrying a
* declined card;
* - after a failed payment (webhook) with SLOT_HOLD_MS, so the customer
* can retry within a fresh 10-minute window.
* The slot is genuinely still the customer's (nobody else could grab it
* while `held`), so renewing is safe. Slots whose status is no longer
* `held` (e.g. released and re-booked by someone else) are returned so the
* caller can inform the user.
*/
export async function extendBasketHolds(
pb: PocketBase,
basketId: string,
durationMs = SLOT_HOLD_MS
): Promise<string[]> {
const unheld: string[] = [];
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: `basket = "${basketId}" && lineType = "slot"` })
.catch(() => []);
const until = iso(new Date(Date.now() + durationMs));
for (const line of lines) {
const slotId = line.slot;
if (!slotId) continue;
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
if (slot && slot.status === 'held') {
await pb.collection('slots').update(slotId, { heldUntil: until }).catch(() => {});
} else {
unheld.push(line.id);
}
}
return unheld;
}

View file

@ -0,0 +1,53 @@
import PocketBase, { ClientResponseError } from 'pocketbase';
import { env } from '$env/dynamic/private';
let adminPb: PocketBase | null = null;
let authPromise: Promise<PocketBase> | null = null;
async function authenticate(): Promise<PocketBase> {
const url = env.POCKETBASE_INTERNAL_URL;
const pb = new PocketBase(url);
pb.autoCancellation(false);
const email = env.POCKETBASE_ADMIN_EMAIL;
const password = env.POCKETBASE_ADMIN_PASSWORD;
if (!email || !password) throw new Error('POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD must be set');
await pb.collection('_superusers').authWithPassword(email, password);
adminPb = pb;
return pb;
}
/**
* Server-only PocketBase client authenticated as admin.
* Used by basket/checkout/webhook API routes that need to bypass
* collection-level API rules (create baskets, hold slots, create orders).
*
* Concurrent callers share one in-flight auth attempt; if the cached token
* has since been invalidated (401 on first use), we re-authenticate once.
*/
export async function getAdminPb(): Promise<PocketBase> {
if (adminPb?.authStore.isValid) return adminPb;
authPromise ??= authenticate().finally(() => {
authPromise = null;
});
return authPromise;
}
/**
* Run `fn` with the admin client; on a 401 (stale/invalidated token),
* re-authenticate and retry exactly once.
*/
export async function withAdminPb<T>(fn: (pb: PocketBase) => Promise<T>): Promise<T> {
const pb = await getAdminPb();
try {
return await fn(pb);
} catch (e) {
if (e instanceof ClientResponseError && e.status === 401) {
pb.authStore.clear();
adminPb = null;
return fn(await getAdminPb());
}
throw e;
}
}

View file

@ -0,0 +1,15 @@
import { loadStripe as _loadStripe } from '@stripe/stripe-js';
import { env } from '$env/dynamic/public';
import { browser } from '$app/environment';
let stripePromise: ReturnType<typeof _loadStripe> | null = null;
export function loadStripe() {
if (!browser) return null;
if (!stripePromise) {
const key = env.PUBLIC_STRIPE_PUBLISHABLE_KEY;
if (!key) throw new Error('PUBLIC_STRIPE_PUBLISHABLE_KEY is not set');
stripePromise = _loadStripe(key);
}
return stripePromise;
}

View file

@ -0,0 +1 @@
export * from '$shared/types';