Compare commits

..

3 commits

Author SHA1 Message Date
d29f101b29 Merge pull request 'Visual text editor; Cards, FAQ and HTML blocks instead of HTML in text' (#10) from visual-editor-blocks into main
Reviewed-on: #10
2026-10-26 14:19:13 +01:00
25632d85e2 Backup: evashafik-enhanced uses Cards/FAQ blocks instead of HTML
Same text: cards, steps, Read next and programme prices are Cards
blocks, the FAQs FAQ blocks, pull quotes quotes, references small text.
#prices, #buy and #book are block anchors (#book on /sessions had lost
its target with the price table).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-26 12:58:16 +00:00
f86c2251dc Visual text editor; Cards, FAQ and HTML blocks; block anchors
The text editor (Tiptap) only produces simple HTML: headings, bold,
italic, strikethrough, links, lists, pull quotes, lines. Layouts that
were hand-written HTML in text blocks get their own blocks (Cards with
pictures or numbered steps, FAQ), one-offs and embeds go in an HTML
block, and every block can have an anchor for #links. Text blocks get
alignment and a small (footnote) size.

Existing text blocks the editor can't represent become HTML blocks that
render exactly as before (migration, and backup import for old files);
text that is only centred becomes centred text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-26 12:58:15 +00:00
19 changed files with 540 additions and 73 deletions

View file

@ -99,12 +99,14 @@ All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `o
### Block System ### Block System
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `packages/shared/src/types.ts` (re-exported via `$lib/types` in each app): Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `packages/shared/src/types.ts` (re-exported via `$lib/types` in each app):
`text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout` `text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout | cards | faq | html`
- **Renderers (shared)**: `packages/shared/src/blocks/<Type>Block.svelte` — one renderer per type, imported by both apps via `$shared/blocks/...`. The admin preview iframe uses the same shared renderers. - **Renderers (shared)**: `packages/shared/src/blocks/<Type>Block.svelte` — one renderer per type, imported by both apps via `$shared/blocks/...`. The admin preview iframe uses the same shared renderers.
- **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type - **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
- **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults - **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
- **Block list**: `app-admin/src/lib/admin/BlockList.svelte` — draggable reorder, select, delete - **Block list**: `app-admin/src/lib/admin/BlockList.svelte` — draggable reorder, select, delete
- **Settings on every block** (keys starting with `_`, edited below each block's own fields): `_background`, `_foreground` (colours) and `_anchor` (id for `#anchor` links), applied by `BackgroundWrapper.svelte`.
- **Text is edited visually**: `RichTextEditor.svelte` (Tiptap) only produces `p, h2, h3, strong, em, s, a, ul, ol, li, blockquote, br, hr` — no inline styles or layout HTML. That list is `EDITOR_TAGS` in `packages/shared/src/richText.ts`; keep it and the editor's extensions in step. A layout people keep needing becomes a block (as Cards and FAQ did), never HTML in a text block; one-offs and embeds go in an `html` block. Old text blocks holding other HTML are turned into `html` blocks (or centred text) by `upgradeLegacyBlocks()` on backup import and by migration `1793300000_text_blocks_visual_editor.js`.
To add a new block type: add to `BlockType` union in `packages/shared/src/types.ts`, create renderer in `packages/shared/src/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in `packages/shared/src/blocks/BlockRenderer.svelte`. To add a new block type: add to `BlockType` union in `packages/shared/src/types.ts`, create renderer in `packages/shared/src/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in `packages/shared/src/blocks/BlockRenderer.svelte`.
@ -149,7 +151,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
- Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`. - Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`.
- **Dates, times and prices shown to people** use `DISPLAY_LOCALE` (`en-GB`: day-month-year, 24-hour clock) and the helpers in `$shared/calendar` (`formatInstant`, `formatPrice` with the shop `currency`, `formatDateTime`) — never `toLocale*(undefined)`, which renders US formats on the server. Booking times on the public site are shown in `SITE_TIMEZONE` too (layout data `timezone`, read by blocks via `page.data.timezone`). Native `<input type="date">` fields follow the visitor's browser language and can't be changed from the page. - **Dates, times and prices shown to people** use `DISPLAY_LOCALE` (`en-GB`: day-month-year, 24-hour clock) and the helpers in `$shared/calendar` (`formatInstant`, `formatPrice` with the shop `currency`, `formatDateTime`) — never `toLocale*(undefined)`, which renders US formats on the server. Booking times on the public site are shown in `SITE_TIMEZONE` too (layout data `timezone`, read by blocks via `page.data.timezone`). Native `<input type="date">` fields follow the visitor's browser language and can't be changed from the page.
- **Dates/times in admin**: entered and displayed in `SITE_TIMEZONE` (layout data `timezone`), via `toZonedDatetimeInput`, `zonedInputToIso`, `formatDateTime` in `$shared/calendar`. Never `new Date(localInput)` on the server — the container runs in UTC. - **Dates/times in admin**: entered and displayed in `SITE_TIMEZONE` (layout data `timezone`), via `toZonedDatetimeInput`, `zonedInputToIso`, `formatDateTime` in `$shared/calendar`. Never `new Date(localInput)` on the server — the container runs in UTC.
- **Prose**: `.prose-wellness` class for rich text content styling - **Prose**: `.prose-wellness` class for rich text content styling (in both apps' `app.css`, which must stay alike: the admin preview uses it). A *Quote* in the editor is the pull quote (`blockquote`).
### Routing ### Routing
- **Admin app** (`app-admin`): All routes except `/login` are auth-guarded in `hooks.server.ts` (which also refreshes the token per request and sets the cookie's `Secure` flag from the real scheme). The root layout renders the admin shell (grouped sidebar) except on `/login` and `/preview`. The `/preview` route reads `sessionStorage` set by the page editor (same-origin, so it works). - **Admin app** (`app-admin`): All routes except `/login` are auth-guarded in `hooks.server.ts` (which also refreshes the token per request and sets the cookie's `Secure` flag from the real scheme). The root layout renders the admin shell (grouped sidebar) except on `/login` and `/preview`. The `/preview` route reads `sessionStorage` set by the page editor (same-origin, so it works).

View file

@ -136,7 +136,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/login` — sign in - `/login` — sign in
- `/pages` — list/create pages - `/pages` — list/create pages
- `/pages/[slug]` — block editor with draft preview - `/pages/[slug]` — block editor with draft preview. Text is edited visually (headings, bold, italic, strikethrough, links, lists, pull quotes, lines; alignment and a small *footnote* size per block). Layouts have their own blocks: **Cards** (pictures or numbered steps, optionally linked — e.g. *Who I work with*, *Read next*, *How it works*) and **FAQ** (questions that open to show the answer). An **HTML** block takes raw HTML for embeds and one-offs (inline styles only; anything it loads from another site shares visitors' IPs). Every block has an *Anchor*, so a button or link to `#prices` jumps to it.
- `/calendar` — events shown by Upcoming Calendar blocks - `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services, products and bundles shown in Shop blocks - `/items` — services, products and bundles shown in Shop blocks
- `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). Windows may not overlap each other, nor sessions of the same service; bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it. - `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). Windows may not overlap each other, nor sessions of the same service; bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it.

View file

@ -109,6 +109,36 @@ h4 {
padding-left: 1.5rem; padding-left: 1.5rem;
} }
/* The visual editor wraps list items in <p>. */
.prose-wellness li > p {
margin: 0;
}
.prose-wellness ol {
list-style: decimal;
padding-left: 1.5rem;
}
/* Pull quote: a "Quote" in the visual editor. */
.prose-wellness blockquote {
margin: 0.75rem 0;
padding-left: 1.25rem;
border-left: 3px solid var(--color-primary, #8a9a7b);
font-family: 'Playfair Display', Georgia, serif;
font-size: 1.35rem;
font-style: italic;
}
.prose-wellness.text-center blockquote {
border-left: 0;
padding-left: 0;
}
.prose-wellness hr {
margin: 2rem 0;
border-color: color-mix(in srgb, currentColor 20%, transparent);
}
.prose-wellness a { .prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline; text-decoration: underline;
@ -147,3 +177,15 @@ h4 {
html { html {
scroll-behavior: smooth; scroll-behavior: smooth;
} }
/* Visual editor (RichTextEditor): roughly how the site shows text, sized for the sidebar. */
.rich-text h2 { font-size: 1.5rem; font-weight: 700; margin: 0.75rem 0 0.25rem; }
.rich-text h3 { font-size: 1.2rem; font-weight: 700; margin: 0.75rem 0 0.25rem; }
.rich-text p { margin: 0.4rem 0; }
.rich-text ul { list-style: disc; padding-left: 1.5rem; }
.rich-text ol { list-style: decimal; padding-left: 1.5rem; }
.rich-text blockquote { border-left: 3px solid var(--color-primary); padding-left: 1rem; font-style: italic; }
.rich-text hr { margin: 1rem 0; border-color: var(--color-base-300); }
.rich-text a { text-decoration: underline; }
.rich-text > :first-child { margin-top: 0; }
.rich-text li > p { margin: 0; }

View file

@ -11,7 +11,10 @@ export const blockLabels: Record<BlockType, string> = {
testimonials: 'Testimonials', testimonials: 'Testimonials',
upcoming_calendar: 'Upcoming Calendar', upcoming_calendar: 'Upcoming Calendar',
shop: 'Shop', shop: 'Shop',
checkout: 'Checkout' checkout: 'Checkout',
cards: 'Cards',
faq: 'FAQ',
html: 'HTML'
}; };
export const blockTypes = Object.keys(blockLabels) as BlockType[]; export const blockTypes = Object.keys(blockLabels) as BlockType[];
@ -80,6 +83,24 @@ export function createBlock(type: BlockType): ContentBlock {
notesLabel: 'Notes or special requests' notesLabel: 'Notes or special requests'
}; };
break; break;
case 'cards':
base.data = {
heading: 'Section heading',
intro: '',
align: 'center',
style: 'image',
items: [1, 2, 3].map((n) => ({ imageUrl: '', imageAlt: '', title: `Card ${n}`, subtitle: '', text: '<p>A sentence or two.</p>', href: '', linkLabel: '' }))
};
break;
case 'faq':
base.data = {
heading: 'Questions people ask',
items: [{ question: 'What happens in the first session?', answer: '<p>Answer it here.</p>' }]
};
break;
case 'html':
base.data = { html: '' };
break;
} }
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 }; base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base; return base;

View file

@ -38,6 +38,18 @@
updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) }); updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) });
} }
function moveArrayItem(key: string, index: number, by: number) {
if (!block) return;
const items = [...(block.data[key] || [])];
const to = index + by;
if (to < 0 || to >= items.length) return;
[items[index], items[to]] = [items[to], items[index]];
updateData({ [key]: items });
}
// "#prices" links jump to the block with anchor "prices"; keep it to characters that work in an address.
const toAnchor = (value: string) => value.trim().toLowerCase().replace(/^#/, '').replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
function toggleCategory(category: string) { function toggleCategory(category: string) {
if (!block) return; if (!block) return;
const categories = block.data.categories || []; const categories = block.data.categories || [];
@ -76,6 +88,10 @@
{#if block.type === 'text'} {#if block.type === 'text'}
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /> <RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
<div class="mt-4 space-y-3">
<SegmentedControl label="Alignment" options={['left', 'center']} value={block.data.align === 'center' ? 'center' : 'left'} onChange={(v) => updateData({ align: v })} />
<SegmentedControl label="Text size" options={['normal', 'small']} value={block.data.size === 'small' ? 'small' : 'normal'} onChange={(v) => updateData({ size: v })} formatLabel={(v) => (v === 'small' ? 'Small (footnote)' : 'Normal')} />
</div>
{:else if block.type === 'image_text'} {:else if block.type === 'image_text'}
<div class="space-y-4"> <div class="space-y-4">
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} /> <ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
@ -163,9 +179,77 @@
<ShopBlockEditor {block} {items} {onChange} /> <ShopBlockEditor {block} {items} {onChange} />
{:else if block.type === 'checkout'} {:else if block.type === 'checkout'}
<CheckoutBlockEditor {block} {onChange} /> <CheckoutBlockEditor {block} {onChange} />
{:else if block.type === 'cards'}
{@render field('Heading', block.data.heading || '', (heading) => updateData({ heading }), 'Optional')}
<label class="fieldset">
<span class="fieldset-legend">Intro</span>
<textarea class="textarea w-full" rows="2" placeholder="Optional" value={block.data.intro || ''} oninput={(e) => updateData({ intro: e.currentTarget.value })}></textarea>
</label>
<div class="mt-2 space-y-3">
<SegmentedControl label="Heading" options={['left', 'center']} value={block.data.align === 'center' ? 'center' : 'left'} onChange={(v) => updateData({ align: v })} />
<SegmentedControl label="Cards show" options={['image', 'numbered']} value={block.data.style === 'numbered' ? 'numbered' : 'image'} onChange={(v) => updateData({ style: v })} formatLabel={(v) => (v === 'image' ? 'A picture' : 'A number')} />
</div>
<div class="mt-4 space-y-3">
{#each block.data.items || [] as card, i}
<div class="rounded-box border border-base-300 p-3">
<div class="mb-2 flex items-center gap-1">
<span class="flex-1 text-sm font-semibold text-base-content/60">Card {i + 1}</span>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move card up" disabled={i === 0} onclick={() => moveArrayItem('items', i, -1)}>↑</button>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move card down" disabled={i === block.data.items.length - 1} onclick={() => moveArrayItem('items', i, 1)}>↓</button>
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div>
{#if block.data.style !== 'numbered'}
<ImageUploader url={card.imageUrl} alt={card.imageAlt} onChange={(image) => updateArray('items', i, { imageUrl: image.url, imageAlt: image.alt })} />
{/if}
<div class="grid gap-x-3 md:grid-cols-2">
{@render field('Title', card.title || '', (title) => updateArray('items', i, { title }))}
{@render field('Subtitle', card.subtitle || '', (subtitle) => updateArray('items', i, { subtitle }), 'Optional, shown lighter')}
</div>
<span class="fieldset-legend">Text</span>
<RichTextEditor compact value={card.text} onChange={(text) => updateArray('items', i, { text })} />
<div class="grid gap-x-3 md:grid-cols-2">
{@render field('Link', card.href || '', (href) => updateArray('items', i, { href }), '/page, #anchor or https://…')}
{@render field('Link text', card.linkLabel || '', (linkLabel) => updateArray('items', i, { linkLabel }), 'Optional, e.g. Read more')}
</div>
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={() => addArrayItem('items', { imageUrl: '', imageAlt: '', title: '', subtitle: '', text: '', href: '', linkLabel: '' })}>Add card</button>
<p class="text-sm text-base-content/60">With a link, the whole card is clickable.</p>
</div>
{:else if block.type === 'faq'}
{@render field('Heading', block.data.heading || '', (heading) => updateData({ heading }), 'Optional')}
<div class="mt-3 space-y-3">
{#each block.data.items || [] as item, i}
<div class="rounded-box border border-base-300 p-3">
<div class="mb-2 flex items-center gap-1">
<span class="flex-1 text-sm font-semibold text-base-content/60">Question {i + 1}</span>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move question up" disabled={i === 0} onclick={() => moveArrayItem('items', i, -1)}>↑</button>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move question down" disabled={i === block.data.items.length - 1} onclick={() => moveArrayItem('items', i, 1)}>↓</button>
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div>
<input class="input mb-2 w-full" aria-label="Question" placeholder="Question" value={item.question} oninput={(e) => updateArray('items', i, { question: e.currentTarget.value })} />
<RichTextEditor compact value={item.answer} onChange={(answer) => updateArray('items', i, { answer })} />
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={() => addArrayItem('items', { question: '', answer: '' })}>Add question</button>
<p class="text-sm text-base-content/60">Visitors click a question to show its answer.</p>
</div>
{:else if block.type === 'html'}
<label class="fieldset">
<span class="fieldset-legend">HTML</span>
<textarea class="textarea w-full font-mono text-xs" rows="14" spellcheck="false" value={block.data.html || ''} oninput={(e) => updateData({ html: e.currentTarget.value })}></textarea>
<span class="label">For embeds (a map, a video) and one-offs. Use inline styles: CSS classes from elsewhere don't apply here. Scripts don't run. Anything loaded from another site (an embed, an image) sends visitors' IP addresses there, so it may need mentioning in the privacy policy.</span>
</label>
{/if} {/if}
<div class="mt-6 space-y-3 rounded-box border border-base-300 p-4"> <div class="mt-6 space-y-3 rounded-box border border-base-300 p-4">
<label class="flex items-center gap-3">
<span class="w-28 shrink-0 text-sm font-bold">Anchor</span>
<input class="input input-sm flex-1" placeholder="e.g. prices — then link to #prices" value={block.data._anchor || ''} onchange={(e) => updateData({ _anchor: toAnchor(e.currentTarget.value) })} />
</label>
<hr class="border-base-300" />
<SegmentedControl label="Background" strong options={['none', 'color', 'image']} value={block.data._background?.type || 'none'} onChange={(type) => updateBackground({ type })} /> <SegmentedControl label="Background" strong options={['none', 'color', 'image']} value={block.data._background?.type || 'none'} onChange={(type) => updateBackground({ type })} />
{#if block.data._background?.type === 'color'} {#if block.data._background?.type === 'color'}

View file

@ -1,78 +1,127 @@
<script lang="ts"> <script lang="ts">
import { browser } from '$app/environment'; import { onMount, untrack } from 'svelte';
import { onMount } from 'svelte'; import { Editor } from '@tiptap/core';
import StarterKit from '@tiptap/starter-kit';
let { value = '', onChange = (html: string) => {} } = $props<{ value?: string; onChange?: (html: string) => void }>(); // The visual editor for text in blocks and emails. It can only produce what
let editorEl: HTMLDivElement | undefined = $state(); // the toolbar offers (see EDITOR_TAGS in $shared/richText): no inline styles
let mounted = $state(false); // or layout HTML, so pages stay consistent. Layouts are blocks (Cards, FAQ);
// anything else goes in an HTML block.
let {
value = '',
onChange = (html: string) => {},
compact = false
} = $props<{ value?: string; onChange?: (html: string) => void; compact?: boolean }>();
let element: HTMLDivElement | undefined = $state();
let editor: Editor | undefined = $state();
// Bumped on every editor transaction so the toolbar's active states re-render.
let tick = $state(0);
onMount(() => { onMount(() => {
mounted = true; editor = new Editor({
if (editorEl) { element,
editorEl.innerHTML = value || ''; extensions: [
} StarterKit.configure({
heading: { levels: [2, 3] },
code: false,
codeBlock: false,
underline: false,
// It appends an empty paragraph after a closing heading or list, which changed content just by
// opening a block (and looped with the value sync below).
trailingNode: false,
// No target/rel: most links are to the site's own pages, which shouldn't open a new tab.
link: { openOnClick: false, autolink: true, defaultProtocol: 'https', HTMLAttributes: { target: null, rel: null } }
})
],
content: value || '',
editorProps: { attributes: { class: 'rich-text min-h-32 p-4 outline-none', role: 'textbox', 'aria-multiline': 'true' } },
onTransaction: () => tick++,
onUpdate: ({ editor }) => onChange(editor.isEmpty ? '' : editor.getHTML())
});
return () => editor?.destroy();
}); });
// Sync content from props when a different block is selected, // Another block selected: show its content (not echoed back, so nothing is marked unsaved).
// without overwriting content while the user is actively editing. // Untracked: setContent runs onTransaction (tick++), which must not become a dependency here.
$effect(() => { $effect(() => {
if (mounted && editorEl && value !== undefined) { const html = value || '';
if (editorEl.innerHTML !== value) { const current = editor;
editorEl.innerHTML = value || ''; if (!current) return;
} untrack(() => {
} if (html !== (current.isEmpty ? '' : current.getHTML())) current.commands.setContent(html, { emitUpdate: false });
});
}); });
function exec(cmd: string, val?: string) { function active(name: string, attrs?: Record<string, unknown>) {
if (!browser) return; tick;
editorEl?.focus(); return editor?.isActive(name, attrs) ?? false;
document.execCommand(cmd, false, val);
emit();
}
function emit() {
if (editorEl) onChange(editorEl.innerHTML);
} }
function setLink() { function setLink() {
const url = prompt('Link URL', 'https://'); if (!editor) return;
if (url) exec('createLink', url); const current = editor.getAttributes('link').href || '';
const href = prompt('Link address (/page, #anchor or https://…). Empty removes the link.', current);
if (href === null) return;
const chain = editor.chain().focus().extendMarkRange('link');
if (href.trim()) chain.setLink({ href: href.trim() }).run();
else chain.unsetLink().run();
} }
function clearFormatting() { type Tool = { label: string; title: string; run: () => void; on?: () => boolean; class?: string };
if (!browser) return; let tools = $derived.by((): Tool[][] => {
editorEl?.focus(); const c = () => editor!.chain().focus();
document.execCommand('formatBlock', false, '<p>'); // Compact (cards, FAQ answers): no headings, quotes or lines inside small text.
document.execCommand('removeFormat'); return [
emit(); compact ? [] : [
} { label: 'Text', title: 'Paragraph', run: () => c().setParagraph().run(), on: () => active('paragraph') },
{ label: 'H2', title: 'Heading', run: () => c().toggleHeading({ level: 2 }).run(), on: () => active('heading', { level: 2 }) },
function handleInput() { { label: 'H3', title: 'Subheading', run: () => c().toggleHeading({ level: 3 }).run(), on: () => active('heading', { level: 3 }) }
emit(); ],
} [
{ label: 'B', title: 'Bold', run: () => c().toggleBold().run(), on: () => active('bold'), class: 'font-bold' },
{ label: 'I', title: 'Italic', run: () => c().toggleItalic().run(), on: () => active('italic'), class: 'italic' },
{ label: 'S', title: 'Strikethrough', run: () => c().toggleStrike().run(), on: () => active('strike'), class: 'line-through' },
{ label: 'Link', title: 'Link', run: setLink, on: () => active('link') }
],
[
{ label: '• List', title: 'Bulleted list', run: () => c().toggleBulletList().run(), on: () => active('bulletList') },
{ label: '1. List', title: 'Numbered list', run: () => c().toggleOrderedList().run(), on: () => active('orderedList') },
...(compact
? []
: [
{ label: 'Quote', title: 'Pull quote', run: () => c().toggleBlockquote().run(), on: () => active('blockquote') },
{ label: '— Line', title: 'Divider line', run: () => c().setHorizontalRule().run() }
])
],
[
{ label: 'Clear', title: 'Remove formatting', run: () => c().unsetAllMarks().clearNodes().run() },
{ label: '↶', title: 'Undo', run: () => c().undo().run() },
{ label: '↷', title: 'Redo', run: () => c().redo().run() }
]
].filter((group) => group.length);
});
</script> </script>
{#if mounted}
<div class="rounded-box border border-base-300 bg-base-100"> <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"> <div class="flex flex-wrap gap-1 border-b border-base-300 p-2" role="toolbar" aria-label="Text formatting">
<button class="btn btn-xs" onclick={() => exec('bold')} type="button"><b>B</b></button> {#each tools as group, g (g)}
<button class="btn btn-xs" onclick={() => exec('italic')} type="button"><i>I</i></button> {#if g > 0}<span class="mx-1 w-px self-stretch bg-base-300" aria-hidden="true"></span>{/if}
<button class="btn btn-xs" onclick={() => exec('formatBlock', '<h2>')} type="button">H2</button> {#each group as tool (tool.title)}
<button class="btn btn-xs" onclick={() => exec('formatBlock', '<h3>')} type="button">H3</button> <button
<button class="btn btn-xs" onclick={() => exec('insertUnorderedList')} type="button">List</button> type="button"
<button class="btn btn-xs" onclick={setLink} type="button">Link</button> class="btn btn-xs {tool.class || ''}"
<button class="btn btn-xs" onclick={clearFormatting} type="button">Clear</button> class:btn-primary={tool.on?.()}
aria-pressed={tool.on ? tool.on() : undefined}
title={tool.title}
disabled={!editor}
onmousedown={(e) => e.preventDefault()}
onclick={tool.run}>{tool.label}</button
>
{/each}
{/each}
</div>
<div bind:this={element}>
{#if !editor}<div class="p-4 text-base-content/50">Loading editor…</div>{/if}
</div> </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> </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

@ -7,6 +7,8 @@ import {
validateSiteExport, validateSiteExport,
type SiteExport type SiteExport
} from '$lib/exportImport'; } from '$lib/exportImport';
import { upgradeLegacyBlocks } from '$shared/richText';
import type { ContentBlock } from '$lib/types';
export const POST: RequestHandler = async ({ request, locals }) => { export const POST: RequestHandler = async ({ request, locals }) => {
let body: SiteExport; let body: SiteExport;
@ -54,7 +56,8 @@ export const POST: RequestHandler = async ({ request, locals }) => {
// 2. Import pages // 2. Import pages
for (const page of body.pages) { for (const page of body.pages) {
try { try {
const blocks = restorePlaceholders(page.blocks, keyToUrl); // Files exported before the visual editor may hold raw HTML in text blocks.
const blocks = upgradeLegacyBlocks(restorePlaceholders(page.blocks, keyToUrl) as ContentBlock[]);
// Try to find existing page by slug // Try to find existing page by slug
let existing; let existing;

View file

@ -99,6 +99,36 @@ h4 {
padding-left: 1.5rem; padding-left: 1.5rem;
} }
/* The visual editor wraps list items in <p>. */
.prose-wellness li > p {
margin: 0;
}
.prose-wellness ol {
list-style: decimal;
padding-left: 1.5rem;
}
/* Pull quote: a "Quote" in the visual editor. */
.prose-wellness blockquote {
margin: 0.75rem 0;
padding-left: 1.25rem;
border-left: 3px solid var(--color-primary, #8a9a7b);
font-family: 'Playfair Display', Georgia, serif;
font-size: 1.35rem;
font-style: italic;
}
.prose-wellness.text-center blockquote {
border-left: 0;
padding-left: 0;
}
.prose-wellness hr {
margin: 2rem 0;
border-color: color-mix(in srgb, currentColor 20%, transparent);
}
.prose-wellness a { .prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline; text-decoration: underline;

View file

@ -50,6 +50,13 @@ Same text and photos, plus:
and an FAQ. The FAQ answers come only from what the site already says and an FAQ. The FAQ answers come only from what the site already says
(boundaries, no intercourse, the first session is a talk, prices). Each (boundaries, no intercourse, the first session is a talk, prices). Each
article ends with a booking prompt and "Read next". article ends with a booking prompt and "Read next".
- **No HTML in text**: the cards, steps, "Read next" and programme prices are
Cards blocks, the FAQs are FAQ blocks, pull quotes are quotes and article
references are small (footnote) text, so everything is editable in the
visual editor. `#prices`, `#buy` and `#book` are block anchors.
Older export files (with HTML layouts inside text blocks) still import: those
text blocks become HTML blocks that look the same.
Both versions fix obvious typos ("Complete Cirсle" with a Cyrillic с, "Cirle", Both versions fix obvious typos ("Complete Cirсle" with a Cyrillic с, "Cirle",
"advansed") and the broken "More about sessions" link (`http://`), which now "advansed") and the broken "More about sessions" link (`http://`), which now
goes to `/sessions`. goes to `/sessions`.

File diff suppressed because one or more lines are too long

View file

@ -4,10 +4,13 @@
let { let {
background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground, background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground,
foreground = {} as BlockForeground, foreground = {} as BlockForeground,
anchor = '',
children children
} = $props<{ } = $props<{
background?: BlockBackground; background?: BlockBackground;
foreground?: BlockForeground; foreground?: BlockForeground;
/** Block setting: lets links like "#prices" jump here. */
anchor?: string;
children?: import('svelte').Snippet; children?: import('svelte').Snippet;
}>(); }>();
@ -41,7 +44,8 @@
} }
</script> </script>
<div style={bgStyle() + ' ' + fgStyle()} class="relative"> <!-- scroll-mt keeps an #anchor target clear of the sticky header. -->
<div id={anchor || undefined} style={bgStyle() + ' ' + fgStyle()} class="relative scroll-mt-20">
{#if background.type === 'image' && background.overlay && background.imageUrl} {#if background.type === 'image' && background.overlay && background.imageUrl}
<div <div
class="pointer-events-none absolute inset-0" class="pointer-events-none absolute inset-0"

View file

@ -11,6 +11,9 @@
import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte'; import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte';
import ShopBlock from './ShopBlock.svelte'; import ShopBlock from './ShopBlock.svelte';
import CheckoutBlock from './CheckoutBlock.svelte'; import CheckoutBlock from './CheckoutBlock.svelte';
import CardsBlock from './CardsBlock.svelte';
import FaqBlock from './FaqBlock.svelte';
import HtmlBlock from './HtmlBlock.svelte';
let { blocks = [], calendarEvents = [], items = [] } = $props<{ let { blocks = [], calendarEvents = [], items = [] } = $props<{
blocks: ContentBlock[]; blocks: ContentBlock[];
@ -28,7 +31,7 @@
</script> </script>
{#each blocks as block (block.id)} {#each blocks as block (block.id)}
<BackgroundWrapper background={getBg(block)} foreground={getFg(block)}> <BackgroundWrapper background={getBg(block)} foreground={getFg(block)} anchor={block.data._anchor}>
{#if block.type === 'text'} {#if block.type === 'text'}
<TextBlock data={block.data} /> <TextBlock data={block.data} />
{:else if block.type === 'image_text'} {:else if block.type === 'image_text'}
@ -49,6 +52,12 @@
<ShopBlock data={block.data} {items} /> <ShopBlock data={block.data} {items} />
{:else if block.type === 'checkout'} {:else if block.type === 'checkout'}
<CheckoutBlock data={block.data} /> <CheckoutBlock data={block.data} />
{:else if block.type === 'cards'}
<CardsBlock data={block.data} />
{:else if block.type === 'faq'}
<FaqBlock data={block.data} />
{:else if block.type === 'html'}
<HtmlBlock data={block.data} />
{/if} {/if}
</BackgroundWrapper> </BackgroundWrapper>
{/each} {/each}

View file

@ -0,0 +1,54 @@
<script lang="ts">
import { scrollReveal } from '$shared/scrollReveal';
type Card = { imageUrl?: string; imageAlt?: string; title?: string; subtitle?: string; text?: string; href?: string; linkLabel?: string };
let { data } = $props<{
data: { heading?: string; intro?: string; align?: 'left' | 'center'; style?: 'image' | 'numbered'; items?: Card[] };
}>();
let numbered = $derived(data.style === 'numbered');
</script>
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
{#if data.heading || data.intro}
<div class="prose-wellness text-lg text-fg-body/85" class:text-center={data.align === 'center'}>
{#if data.heading}<h2>{data.heading}</h2>{/if}
{#if data.intro}<p>{data.intro}</p>{/if}
</div>
{/if}
<div class="mt-6 grid gap-6 grid-cols-[repeat(auto-fit,minmax(200px,1fr))]">
{#each data.items || [] as card, i (i)}
<!-- Cards are white whatever the block's colours, so they use the site's own text colour. -->
<div class="relative overflow-hidden rounded-[1.25rem] bg-white text-[color-mix(in_srgb,var(--color-text,#2c2c2c)_85%,transparent)] shadow-[0_1px_6px_rgba(0,0,0,0.08)] transition-shadow {card.href ? 'hover:shadow-lg' : ''}">
{#if !numbered && card.imageUrl}
<img class="block aspect-[4/3] w-full object-cover" src={card.imageUrl} alt={card.imageAlt || ''} />
{/if}
<div class={numbered ? 'p-6' : 'px-5 pt-4 pb-5'}>
{#if numbered}
<span class="inline-grid size-9 place-items-center rounded-full bg-sage font-semibold text-[var(--color-primary-content,#fff)]">{i + 1}</span>
{/if}
<!-- Not an h3: the site's h1–h4 rule (serif, heading colour) would override these classes. -->
<strong class="block text-[1.15rem]" class:mt-3={numbered}>
<!-- The title's link covers the whole card (::after), so the card is one click target. -->
{#if card.href}<a class="after:absolute after:inset-0" href={card.href}>{card.title}</a>{:else}{card.title}{/if}
</strong>
{#if card.subtitle}<p class="mt-1 text-[0.95rem] opacity-75">{card.subtitle}</p>{/if}
{#if card.text}<div class="card-text mt-1 text-[0.95rem]">{@html card.text}</div>{/if}
{#if card.href && card.linkLabel}
<p class="mt-3 font-semibold text-sage-dark underline underline-offset-4">{card.linkLabel}</p>
{/if}
</div>
</div>
{/each}
</div>
</section>
<style>
/* Card text comes from the visual editor; links inside it stay clickable above the card's own link. */
.card-text :global(p) { margin: 0.35rem 0 0; }
.card-text :global(ul) { list-style: disc; padding-left: 1.25rem; margin: 0.5rem 0; }
.card-text :global(ol) { list-style: decimal; padding-left: 1.25rem; margin: 0.5rem 0; }
.card-text :global(li > p) { margin: 0; }
.card-text :global(a) { position: relative; z-index: 1; text-decoration: underline; }
.card-text :global(strong) { font-weight: 700; }
</style>

View file

@ -0,0 +1,21 @@
<script lang="ts">
import { scrollReveal } from '$shared/scrollReveal';
type Question = { question?: string; answer?: string };
let { data } = $props<{ data: { heading?: string; items?: Question[] } }>();
</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">
{#if data.heading}<h2>{data.heading}</h2>{/if}
{#each data.items || [] as item, i (i)}
<details class="group border-b border-current/15 py-3.5">
<summary class="flex cursor-pointer list-none items-center justify-between gap-4 text-[1.1rem] font-semibold [&::-webkit-details-marker]:hidden">
{item.question}
<span class="shrink-0 text-2xl leading-none font-light transition-transform group-open:rotate-45" aria-hidden="true">+</span>
</summary>
{@html item.answer || ''}
</details>
{/each}
</div>
</section>

View file

@ -0,0 +1,14 @@
<script lang="ts">
import { scrollReveal } from '$shared/scrollReveal';
let { data } = $props<{ data: { html?: string } }>();
</script>
<!-- Written by an admin as-is, for embeds and one-off layouts. Same frame and text styles as a
Text block (old text blocks with layout HTML became HTML blocks and must look unchanged).
Tailwind classes in it get no styles (only classes found in this repo are generated). -->
<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.html || ''}
</div>
</section>

View file

@ -1,11 +1,15 @@
<script lang="ts"> <script lang="ts">
import { scrollReveal } from '$shared/scrollReveal'; import { scrollReveal } from '$shared/scrollReveal';
let { data } = $props<{ data: { content?: string } }>(); let { data } = $props<{ data: { content?: string; align?: 'left' | 'center'; size?: 'normal' | 'small' } }>();
</script> </script>
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16"> <!-- Small text is a footnote to the block above (references, terms), so it sits right under it. -->
<div class="prose-wellness text-lg text-fg-body/85"> <section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 {data.size === 'small' ? 'pb-12 md:pb-16' : 'py-12 md:py-16'}">
<div
class="prose-wellness {data.size === 'small' ? 'text-base text-fg-body/75' : 'text-lg text-fg-body/85'}"
class:text-center={data.align === 'center'}
>
{@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'} {@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'}
</div> </div>
</section> </section>

View file

@ -0,0 +1,46 @@
import type { ContentBlock } from './types';
// Text blocks hold the HTML the admin's visual editor (Tiptap, see
// app-admin RichTextEditor.svelte) produces: these tags, and attributes only
// on links. Anything else (layouts, inline styles, embeds) belongs in an HTML
// block. Keep this list and the editor's extensions in step, and mirror changes
// in pocketbase/pb_migrations/1793300000_text_blocks_visual_editor.js.
const EDITOR_TAGS = new Set(['p', 'h2', 'h3', 'strong', 'b', 'em', 'i', 's', 'a', 'ul', 'ol', 'li', 'blockquote', 'br', 'hr']);
const LINK_ATTRS = new Set(['href', 'target', 'rel']);
/** Whether `html` only uses what the visual editor can produce (so editing it loses nothing). */
export function isEditorHtml(html: string): boolean {
for (const [, name, attrs] of html.matchAll(/<\/?([a-zA-Z][a-zA-Z0-9]*)([^>]*)>/g)) {
const tag = name.toLowerCase();
if (!EDITOR_TAGS.has(tag)) return false;
for (const [, attr] of attrs.matchAll(/([a-zA-Z-]+)\s*=/g)) {
if (tag !== 'a' || !LINK_ATTRS.has(attr.toLowerCase())) return false;
}
}
return true;
}
const CENTRED = /\s+style="text-align:\s*center;?"/gi;
const BLOCK_START = /<(p|h2|h3|ul|ol|blockquote)\b/gi;
/**
* Text blocks written before the visual editor (raw HTML) become what they can
* be without losing anything: clean text (with `align: 'center'` when every
* paragraph and heading was centred), or else an HTML block that renders them
* exactly as before. Other blocks are returned unchanged.
*/
export function upgradeLegacyBlock(block: ContentBlock): ContentBlock {
if (block.type !== 'text') return block;
const { content = '', ...rest } = block.data;
if (isEditorHtml(content)) return block;
const centred = (content.match(CENTRED) || []).length;
const stripped = content.replace(CENTRED, '');
if (centred && centred === (stripped.match(BLOCK_START) || []).length && isEditorHtml(stripped)) {
return { ...block, data: { ...rest, content: stripped, align: 'center' } };
}
return { ...block, type: 'html', data: { ...rest, html: content } };
}
export function upgradeLegacyBlocks(blocks: ContentBlock[]): ContentBlock[] {
return Array.isArray(blocks) ? blocks.map(upgradeLegacyBlock) : blocks;
}

View file

@ -8,7 +8,10 @@ export type BlockType =
| 'testimonials' | 'testimonials'
| 'upcoming_calendar' | 'upcoming_calendar'
| 'shop' | 'shop'
| 'checkout'; | 'checkout'
| 'cards'
| 'faq'
| 'html';
export type BlockBackground = { export type BlockBackground = {
type: 'none' | 'color' | 'image'; type: 'none' | 'color' | 'image';

View file

@ -0,0 +1,74 @@
/// <reference path="../pb_data/types.d.ts" />
// Text blocks get a visual editor (Tiptap) that only produces simple HTML:
// paragraphs, h2/h3, bold, italic, strikethrough, links, lists, quotes,
// lines. Layouts that used to be written as HTML in a text block have their
// own blocks now (Cards, FAQ), and anything else goes in an `html` block.
//
// Existing text blocks the editor can't represent would be mangled the first
// time someone edits them, so they become `html` blocks (rendering exactly as
// before), except text that is simply centred everywhere: that becomes clean
// text with `align: 'center'`. Same rule as upgradeLegacyBlock() in
// packages/shared/src/richText.ts, which backup import uses; keep them alike.
//
// Data only (blocks is JSON); no schema change.
const EDITOR_TAGS = ['p', 'h2', 'h3', 'strong', 'b', 'em', 'i', 's', 'a', 'ul', 'ol', 'li', 'blockquote', 'br', 'hr'];
const LINK_ATTRS = ['href', 'target', 'rel'];
function isEditorHtml(html) {
const tags = /<\/?([a-zA-Z][a-zA-Z0-9]*)([^>]*)>/g;
let match;
while ((match = tags.exec(html))) {
const tag = match[1].toLowerCase();
if (EDITOR_TAGS.indexOf(tag) < 0) return false;
const attrs = /([a-zA-Z-]+)\s*=/g;
let attr;
while ((attr = attrs.exec(match[2]))) {
if (tag !== 'a' || LINK_ATTRS.indexOf(attr[1].toLowerCase()) < 0) return false;
}
}
return true;
}
function upgrade(block) {
if (!block || block.type !== 'text' || !block.data) return block;
const content = String(block.data.content || '');
if (isEditorHtml(content)) return block;
const centredRe = /\s+style="text-align:\s*center;?"/gi;
const centred = (content.match(centredRe) || []).length;
const stripped = content.replace(centredRe, '');
const starts = (stripped.match(/<(p|h2|h3|ul|ol|blockquote)\b/gi) || []).length;
const data = Object.assign({}, block.data);
delete data.content;
if (centred && centred === starts && isEditorHtml(stripped)) {
return Object.assign({}, block, { data: Object.assign(data, { content: stripped, align: 'center' }) });
}
return Object.assign({}, block, { type: 'html', data: Object.assign(data, { html: content }) });
}
migrate(
(app) => {
let pages;
try {
pages = app.findAllRecords('pages');
} catch (e) {
return; // fresh install: no pages yet
}
for (const page of pages) {
try {
const blocks = JSON.parse(page.getString('blocks') || '[]');
if (!Array.isArray(blocks)) continue;
const upgraded = blocks.map(upgrade);
if (JSON.stringify(upgraded) === JSON.stringify(blocks)) continue;
page.set('blocks', upgraded);
app.saveNoValidate(page);
} catch (e) {
console.log(`[migration] could not upgrade the text blocks of page ${page.id}: ${e}`);
}
}
},
() => {
// Nothing to undo: html blocks render the same HTML the text blocks had.
}
);