added reverse proxy

This commit is contained in:
Jakub Dorfman 2026-06-05 15:32:23 +02:00
parent afd7fd7686
commit 246b1990ca
57 changed files with 4174 additions and 4139 deletions

View file

@ -1,6 +1,6 @@
node_modules
app/node_modules
app/.svelte-kit
app/build
.git
pocketbase/pb_data
node_modules
app/node_modules
app/.svelte-kit
app/build
.git
pocketbase/pb_data

View file

@ -1,2 +1,2 @@
PUBLIC_POCKETBASE_URL=http://localhost:8090
POCKETBASE_INTERNAL_URL=http://localhost:8090
PUBLIC_POCKETBASE_URL=http://localhost:8090
POCKETBASE_INTERNAL_URL=http://localhost:8090

211
AGENTS.md
View file

@ -1,105 +1,106 @@
# Massage Studio Website CMS — Agent Guidelines
## Stack
- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc.
- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage.
- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site.
- **Docker Compose** — two services: `app` (SvelteKit) and `pocketbase`.
## Project Structure
```
app/ # SvelteKit application
├── src/
│ ├── lib/
│ │ ├── admin/ # Admin UI components (BlockList, editors)
│ │ ├── blocks/ # Public block renderers (one per BlockType)
│ │ ├── components/ # Header.svelte, Footer.svelte
│ │ ├── pb.ts # PocketBase client factory + helpers
│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal
│ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin vs public shell)
│ │ ├── +page.svelte # Home page (slug=home)
│ │ ├── [slug]/ # Dynamic CMS pages
│ │ ├── admin/ # Admin area (login, pages, globals)
│ │ └── preview/ # Draft preview via sessionStorage
│ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets
├── build/ # Production build output
├── svelte.config.js # Adapter-node, runes mode forced
├── vite.config.ts # Tailwind v4 + SvelteKit plugins
└── package.json
pocketbase/pb_data/ # PocketBase data (mounted volume-mounted)
docker-compose.yml # app + pocketbase services
Dockerfile # Multi-stage Node 22 build
```
## Key Conventions
### Svelte 5 Runes Mode
All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use:
- `$props()` for component props
- `$state()` for reactive local state
- `$derived()` for computed values
- `$effect()` / `onMount` for side effects
- `{@render children()}` for slots
- `onclick={handler}` (not `on:click`)
### Block System
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`:
`text | image | image_text | timeline | testimonials | services | cta | spacer | horizontal_cards`
- **Public renderers**: `$lib/blocks/<Type>Block.svelte` — one per type, receives `data` prop. Currently active: `TextBlock`, `ImageTextBlock`, `TimelineBlock`, `HeroBlock`.
- **Admin editors**: `$lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
- **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete
To add a new block type: add to `BlockType` union in `types.ts`, create renderer in `$lib/blocks/`, add editor case in `BlockEditor.svelte`, add default in `blockDefaults.ts`, add import in `BlockRenderer.svelte`.
### PocketBase Integration
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()`
- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt)
- Server load functions use `locals.pb.collection('pages').getFirstListItem()`
### Styling
- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings).
- **Admin area**: DaisyUI utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.)
- **Prose**: `.prose-wellness` class for rich text content styling
### Routing
- `+layout.server.ts` fetches header/footer globals for every public page
- `+page.server.ts` for home fetches `slug = "home" && published = true`
- `[slug]/+page.server.ts` fetches by dynamic slug
- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated
## Build & Dev Commands
```sh
# Development (from app/)
cd app
npm install
npm run dev # http://localhost:5173
# Production build
npm run build
# Type checking
npm run check
# Docker full stack
docker compose up --build
# App: http://localhost:3000
# PocketBase admin: http://localhost:8090/_/
# PocketBase only (for local dev)
docker compose up pocketbase
```
## Environment
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (default `http://localhost:8090`)
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`)
- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:3000`)
- Copy `app/.env.example` → `app/.env` for local dev
# Massage Studio Website CMS — Agent Guidelines
## Stack
- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc.
- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage.
- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site.
- **Docker Compose** — three services: `app` (SvelteKit), `pocketbase`, and `caddy` (reverse proxy).
## Project Structure
```
app/ # SvelteKit application
├── src/
│ ├── lib/
│ │ ├── admin/ # Admin UI components (BlockList, editors)
│ │ ├── blocks/ # Public block renderers (one per BlockType)
│ │ ├── components/ # Header.svelte, Footer.svelte
│ │ ├── pb.ts # PocketBase client factory + helpers
│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal
│ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin vs public shell)
│ │ ├── +page.svelte # Home page (slug=home)
│ │ ├── [slug]/ # Dynamic CMS pages
│ │ ├── admin/ # Admin area (login, pages, globals)
│ │ └── preview/ # Draft preview via sessionStorage
│ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets
├── build/ # Production build output
├── svelte.config.js # Adapter-node, runes mode forced
├── vite.config.ts # Tailwind v4 + SvelteKit plugins
└── package.json
pocketbase/pb_data/ # PocketBase data (mounted volume-mounted)
docker-compose.yml # app + pocketbase services
Dockerfile # Multi-stage Node 22 build
```
## Key Conventions
### Svelte 5 Runes Mode
All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use:
- `$props()` for component props
- `$state()` for reactive local state
- `$derived()` for computed values
- `$effect()` / `onMount` for side effects
- `{@render children()}` for slots
- `onclick={handler}` (not `on:click`)
### Block System
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`:
`text | image | image_text | timeline | testimonials | services | cta | spacer | horizontal_cards`
- **Public renderers**: `$lib/blocks/<Type>Block.svelte` — one per type, receives `data` prop. Currently active: `TextBlock`, `ImageTextBlock`, `TimelineBlock`, `HeroBlock`.
- **Admin editors**: `$lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
- **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete
To add a new block type: add to `BlockType` union in `types.ts`, create renderer in `$lib/blocks/`, add editor case in `BlockEditor.svelte`, add default in `blockDefaults.ts`, add import in `BlockRenderer.svelte`.
### PocketBase Integration
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()`
- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt)
- Server load functions use `locals.pb.collection('pages').getFirstListItem()`
### Styling
- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings).
- **Admin area**: DaisyUI utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.)
- **Prose**: `.prose-wellness` class for rich text content styling
### Routing
- `+layout.server.ts` fetches header/footer globals for every public page
- `+page.server.ts` for home fetches `slug = "home" && published = true`
- `[slug]/+page.server.ts` fetches by dynamic slug
- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated
## Build & Dev Commands
```sh
# Development (from app/)
cd app
npm install
npm run dev # http://localhost:5173
# Production build
npm run build
# Type checking
npm run check
# Docker full stack (single entry point on port 8080)
docker compose up --build
# App + PocketBase via Caddy: http://localhost:8080
# PocketBase admin: http://localhost:8080/_/
# PocketBase only (for local dev outside Docker)
docker compose up pocketbase
# Direct access: http://localhost:8090/_/
```
## Environment
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL, now accessed through the Caddy reverse proxy (default `http://localhost:8080`)
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`)
- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:8080`)
- Copy `app/.env.example` → `app/.env` for local dev

View file

@ -1,208 +1,208 @@
# SOFTWARE DEVELOPMENT AGREEMENT
This Software Development Agreement ("Agreement") is entered into on [DATE]
between
**Developer:**
[YOUR NAME]
[ADDRESS]
[IČO / REGISTRATION NUMBER, IF APPLICABLE]
Email: [EMAIL]
and
**Client:**
[CLIENT NAME]
[CLIENT ADDRESS]
Email: [EMAIL]
---
## 1. Subject of the Agreement
The Developer agrees to design and develop a new website for the Client, built on the Developer's custom CMS platform.
The scope of work includes:
- implementation of a custom CMS, including a block-based page builder allowing the Client to create and manage static pages independently,
- move the current website (www.evashafik.com) from Tilda to the new CMS system,
- a services and pricing catalogue (add, edit, hide or reactivate services including name, description, duration and price),
- a an editable calendar displaying practitioner availability, events, workshops and courses,
- a custom booking system for the Client's services and treatments, including service selection, time slot availability, optional add-ons and automatic price calculation,
- Stripe integration for online payment processing,
- booking confirmations and notifications for both the Client and end customers,
- integration with Client's google calendar
- buffer time and minimum lead time configuration per service,
- co-worker profiles with direct contact information (no online booking required for co-workers),
- deployment and configuration of hosting infrastructure under the Client's ownership,
- migration of existing content necessary for operation of the website.
Any functionality not explicitly listed above shall be considered outside the scope of this Agreement and may be subject to a separate agreement or additional fees.
---
## 2. Project Duration
The estimated duration of the project is five (5) months from the Effective Date of this Agreement.
The parties acknowledge that this timeline is an estimate and may be extended in accordance with Section 8 (Client Cooperation).
If the Developer anticipates that the project cannot be completed within the estimated timeline, the Developer shall notify the Client in writing as soon as reasonably practicable. The parties shall then agree in good faith on a revised timeline.
---
## 3. Compensation
The total project fee shall be:
**EUR 2,500**
The Client shall pay the fee in five monthly installments of:
**EUR 500 per month**
Invoices shall be due within fourteen (14) days of issuance.
In the event of late payment, the Developer shall be entitled to suspend work until all outstanding amounts have been paid.
The Developer is not obligated to continue providing services while any invoice remains overdue.
Any suspension caused by late payment shall automatically extend project deadlines by the duration of the suspension.
---
## 4. Hosting
Hosting services, domain registrations, and third-party services shall be registered and owned by the Client.
The Developer will assist with setup, configuration, and administration of such services.
The Client shall be solely responsible for all fees charged by hosting providers, registrars, and third-party service providers.
---
## 5. Intellectual Property
Upon full payment of all amounts due under this Agreement, the Client shall own the project-specific code and assets created exclusively for this project, including custom templates, design implementation, and project-specific configuration.
The Client acknowledges that the delivered website is built on top of the Developer's general-purpose CMS platform, which contains components intended for reuse across multiple projects. The Developer retains full ownership of that platform, including its core framework, modules, libraries, and underlying architecture.
The Client receives a perpetual, non-exclusive license to run the platform as part of their website. This license allows the Client to use, modify, and maintain the website freely, including engaging other developers to work on it.
The Developer retains the right to use, improve, and build commercial products from the CMS platform independently of this project.
---
## 6. Content Management
The CMS is designed to allow the Client to manage routine content independently without developer involvement. The following tasks can be performed directly by the Client:
- adding, editing, deleting and hiding co-worker profiles,
- adding, editing, deleting and hiding services and pricing,
- adding, editing, deleting and managing events, workshops and courses in the calendar,
- creating new pages using the block-based page builder.
The following tasks will typically require developer involvement:
- new third-party integrations,
- structural or architectural changes to the website,
- new features or functionality outside the current scope,
- custom development beyond standard CMS capabilities.
Future developer assistance will be available at an agreed hourly rate or fixed price per task, as discussed separately.
---
## 7. Change Requests
Any requests that materially extend or alter the agreed scope of work may be treated as additional work and may require a separate agreement regarding scope, timeline, and compensation.
---
## 8. Client Cooperation
The Client agrees to provide all necessary information, materials, approvals, and feedback required for completion of the project.
If the Client fails to respond to requests for information, approvals, or feedback for a period exceeding thirty (30) consecutive days:
- all project deadlines shall be automatically extended by at least the duration of such delay,
- the Developer shall not be considered in breach of any delivery deadlines affected by such delay.
The Developer may pause work until the required cooperation is provided.
Communication by email or WhatsApp shall be considered sufficient for all approvals, feedback, and project-related decisions.
---
## 9. Acceptance
The Client shall review delivered work within fourteen (14) days after delivery.
If no substantial objections are communicated within that period, the delivered work shall be deemed accepted.
---
## 10. Termination
Either party may terminate this Agreement by written notice.
In the event of termination, the Client shall pay for all work completed up to the termination date.
Any payments already made are non-refundable for work already performed.
---
## 11. Limitation of Liability
The Developer shall not be liable for:
- downtime caused by third-party providers,
- hosting provider failures,
- domain registrar failures,
- third-party software or service outages,
- indirect or consequential damages.
The Developer's total liability under this Agreement shall not exceed the total amount paid by the Client under this Agreement.
---
## 12. Governing Law and Jurisdiction
This Agreement shall be governed by and construed in accordance with the laws of the Czech Republic.
Any disputes arising out of or in connection with this Agreement shall be subject to the exclusive jurisdiction of the courts of the Czech Republic.
---
## 13. Entire Agreement
This Agreement constitutes the entire agreement between the parties and supersedes all prior discussions, negotiations, and understandings regarding the subject matter herein.
Any amendments must be made in writing and agreed by both parties.
---
## 14. Data Protection
The Developer shall implement standard GDPR-compliant features within the website and booking system, including consent checkboxes for the collection and processing of personal data, a privacy policy page, and tools allowing the Client to manage customer data in accordance with data subject rights (including the ability to edit, export, and delete customer records). The Client shall be solely responsible for ensuring the content of the privacy policy is accurate and up to date, and that their overall use of the website and collected data complies with applicable data protection laws.
---
**Developer**
Name: __________________________
Signature: ______________________
Date: ___________________________
---
**Client**
Name: __________________________
Signature: ______________________
# SOFTWARE DEVELOPMENT AGREEMENT
This Software Development Agreement ("Agreement") is entered into on [DATE]
between
**Developer:**
[YOUR NAME]
[ADDRESS]
[IČO / REGISTRATION NUMBER, IF APPLICABLE]
Email: [EMAIL]
and
**Client:**
[CLIENT NAME]
[CLIENT ADDRESS]
Email: [EMAIL]
---
## 1. Subject of the Agreement
The Developer agrees to design and develop a new website for the Client, built on the Developer's custom CMS platform.
The scope of work includes:
- implementation of a custom CMS, including a block-based page builder allowing the Client to create and manage static pages independently,
- move the current website (www.evashafik.com) from Tilda to the new CMS system,
- a services and pricing catalogue (add, edit, hide or reactivate services including name, description, duration and price),
- a an editable calendar displaying practitioner availability, events, workshops and courses,
- a custom booking system for the Client's services and treatments, including service selection, time slot availability, optional add-ons and automatic price calculation,
- Stripe integration for online payment processing,
- booking confirmations and notifications for both the Client and end customers,
- integration with Client's google calendar
- buffer time and minimum lead time configuration per service,
- co-worker profiles with direct contact information (no online booking required for co-workers),
- deployment and configuration of hosting infrastructure under the Client's ownership,
- migration of existing content necessary for operation of the website.
Any functionality not explicitly listed above shall be considered outside the scope of this Agreement and may be subject to a separate agreement or additional fees.
---
## 2. Project Duration
The estimated duration of the project is five (5) months from the Effective Date of this Agreement.
The parties acknowledge that this timeline is an estimate and may be extended in accordance with Section 8 (Client Cooperation).
If the Developer anticipates that the project cannot be completed within the estimated timeline, the Developer shall notify the Client in writing as soon as reasonably practicable. The parties shall then agree in good faith on a revised timeline.
---
## 3. Compensation
The total project fee shall be:
**EUR 2,500**
The Client shall pay the fee in five monthly installments of:
**EUR 500 per month**
Invoices shall be due within fourteen (14) days of issuance.
In the event of late payment, the Developer shall be entitled to suspend work until all outstanding amounts have been paid.
The Developer is not obligated to continue providing services while any invoice remains overdue.
Any suspension caused by late payment shall automatically extend project deadlines by the duration of the suspension.
---
## 4. Hosting
Hosting services, domain registrations, and third-party services shall be registered and owned by the Client.
The Developer will assist with setup, configuration, and administration of such services.
The Client shall be solely responsible for all fees charged by hosting providers, registrars, and third-party service providers.
---
## 5. Intellectual Property
Upon full payment of all amounts due under this Agreement, the Client shall own the project-specific code and assets created exclusively for this project, including custom templates, design implementation, and project-specific configuration.
The Client acknowledges that the delivered website is built on top of the Developer's general-purpose CMS platform, which contains components intended for reuse across multiple projects. The Developer retains full ownership of that platform, including its core framework, modules, libraries, and underlying architecture.
The Client receives a perpetual, non-exclusive license to run the platform as part of their website. This license allows the Client to use, modify, and maintain the website freely, including engaging other developers to work on it.
The Developer retains the right to use, improve, and build commercial products from the CMS platform independently of this project.
---
## 6. Content Management
The CMS is designed to allow the Client to manage routine content independently without developer involvement. The following tasks can be performed directly by the Client:
- adding, editing, deleting and hiding co-worker profiles,
- adding, editing, deleting and hiding services and pricing,
- adding, editing, deleting and managing events, workshops and courses in the calendar,
- creating new pages using the block-based page builder.
The following tasks will typically require developer involvement:
- new third-party integrations,
- structural or architectural changes to the website,
- new features or functionality outside the current scope,
- custom development beyond standard CMS capabilities.
Future developer assistance will be available at an agreed hourly rate or fixed price per task, as discussed separately.
---
## 7. Change Requests
Any requests that materially extend or alter the agreed scope of work may be treated as additional work and may require a separate agreement regarding scope, timeline, and compensation.
---
## 8. Client Cooperation
The Client agrees to provide all necessary information, materials, approvals, and feedback required for completion of the project.
If the Client fails to respond to requests for information, approvals, or feedback for a period exceeding thirty (30) consecutive days:
- all project deadlines shall be automatically extended by at least the duration of such delay,
- the Developer shall not be considered in breach of any delivery deadlines affected by such delay.
The Developer may pause work until the required cooperation is provided.
Communication by email or WhatsApp shall be considered sufficient for all approvals, feedback, and project-related decisions.
---
## 9. Acceptance
The Client shall review delivered work within fourteen (14) days after delivery.
If no substantial objections are communicated within that period, the delivered work shall be deemed accepted.
---
## 10. Termination
Either party may terminate this Agreement by written notice.
In the event of termination, the Client shall pay for all work completed up to the termination date.
Any payments already made are non-refundable for work already performed.
---
## 11. Limitation of Liability
The Developer shall not be liable for:
- downtime caused by third-party providers,
- hosting provider failures,
- domain registrar failures,
- third-party software or service outages,
- indirect or consequential damages.
The Developer's total liability under this Agreement shall not exceed the total amount paid by the Client under this Agreement.
---
## 12. Governing Law and Jurisdiction
This Agreement shall be governed by and construed in accordance with the laws of the Czech Republic.
Any disputes arising out of or in connection with this Agreement shall be subject to the exclusive jurisdiction of the courts of the Czech Republic.
---
## 13. Entire Agreement
This Agreement constitutes the entire agreement between the parties and supersedes all prior discussions, negotiations, and understandings regarding the subject matter herein.
Any amendments must be made in writing and agreed by both parties.
---
## 14. Data Protection
The Developer shall implement standard GDPR-compliant features within the website and booking system, including consent checkboxes for the collection and processing of personal data, a privacy policy page, and tools allowing the Client to manage customer data in accordance with data subject rights (including the ability to edit, export, and delete customer records). The Client shall be solely responsible for ensuring the content of the privacy policy is accurate and up to date, and that their overall use of the website and collected data complies with applicable data protection laws.
---
**Developer**
Name: __________________________
Signature: ______________________
Date: ___________________________
---
**Client**
Name: __________________________
Signature: ______________________
Date: ___________________________

17
Caddyfile Normal file
View file

@ -0,0 +1,17 @@
# Reverse proxy — single port for both the SvelteKit app and PocketBase
# Route: /api/* and /_/* → PocketBase
# everything else → SvelteKit app
:8080 {
handle /api/* {
reverse_proxy pocketbase:80
}
handle /_/* {
reverse_proxy pocketbase:80
}
handle {
reverse_proxy app:3000
}
}

View file

@ -1,23 +1,23 @@
# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS build
WORKDIR /app
ENV NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false
COPY app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
COPY app/ ./
RUN npm run build
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production \
NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false
COPY --from=build /app/build ./build
COPY --from=build /app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
EXPOSE 3000
CMD ["node", "build"]
# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS build
WORKDIR /app
ENV NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false
COPY app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
COPY app/ ./
RUN npm run build
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production \
NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false
COPY --from=build /app/build ./build
COPY --from=build /app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
EXPOSE 3000
CMD ["node", "build"]

227
README.md
View file

@ -1,112 +1,115 @@
# Massage Studio Website CMS
A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase provides auth, database records, and image storage. The public site is warm and minimal; the admin UI uses DaisyUI components.
## Stack
- SvelteKit + SSR
- PocketBase REST API via the `pocketbase` SDK
- Tailwind CSS v4 + DaisyUI
- Docker Compose with two services: `app` and `pocketbase`
## Local development
1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin.
2. Copy the app env file:
```sh
cp app/.env.example app/.env
```
3. Start PocketBase on port `8090`. With Docker:
```sh
docker compose up pocketbase
```
4. In another terminal:
```sh
cd app
npm install
npm run dev
```
5. Visit `http://localhost:5173`.
## Docker Compose
Run the full stack:
```sh
docker compose up --build
```
If dependency installation is slow on the first build, enable BuildKit explicitly:
```sh
DOCKER_BUILDKIT=1 docker compose build --progress=plain app
docker compose up
```
Subsequent builds reuse the npm cache declared in the `Dockerfile`.
- Public SvelteKit app: `http://localhost:3000`
- PocketBase admin UI: `http://localhost:8090/_/`
The app container uses two PocketBase URLs:
- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image.
- `PUBLIC_POCKETBASE_URL=http://localhost:8090` for browser-side admin uploads and public file URLs during local Docker development.
In production, set `PUBLIC_POCKETBASE_URL` to the browser-accessible PocketBase URL, or to the reverse-proxied PocketBase path/origin you expose publicly.
## PocketBase setup
1. Open `http://localhost:8090/_/`.
2. Create the first PocketBase admin user when prompted.
3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below.
4. Create starter records:
- `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array.
- `globals`: key `header`, data matching the header JSON in the project prompt.
- `globals`: key `footer`, data matching the footer JSON in the project prompt.
If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them.
### Manual collection fields fallback
If schema import fails because of a PocketBase version mismatch, create these collections manually:
- `pages`
- `slug`: text, required, unique
- `title`: text, required
- `blocks`: json
- `published`: bool
- `globals`
- `key`: text, required, unique
- `data`: json
- `media`
- `file`: file, required, max select `1`, image mime types
- `alt`: text
## Authentication
Admin routes live under `/admin`. Login accepts either:
- a PocketBase admin account, or
- a record from a `users` auth collection if you create one.
All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`.
## CMS routes
- `/admin/login` — sign in
- `/admin/pages` — list/create pages
- `/admin/pages/[slug]` — block editor with draft preview
- `/admin/globals` — header/footer editor
## Public routes
- `/` renders `pages.slug = "home"`
- `/[slug]` renders any other published page
- Unpublished pages return `404`
## Notes
- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON.
- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe.
- The page editor includes draggable reordering using native HTML drag events for compatibility; the requested DnD packages are installed and can be swapped in later if desired.
# Massage Studio Website CMS
A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase provides auth, database records, and image storage. The public site is warm and minimal; the admin UI uses DaisyUI components.
## Stack
- SvelteKit + SSR
- PocketBase REST API via the `pocketbase` SDK
- Tailwind CSS v4 + DaisyUI
- Docker Compose with three services: `app`, `pocketbase`, and `caddy` (reverse proxy)
## Local development
1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin.
2. Copy the app env file:
```sh
cp app/.env.example app/.env
```
3. Start PocketBase on port `8090`. With Docker:
```sh
docker compose up pocketbase
```
4. In another terminal:
```sh
cd app
npm install
npm run dev
```
5. Visit `http://localhost:5173`.
> **Note:** During local development (outside Docker), PocketBase is accessed directly at `http://localhost:8090`. When running the full Docker stack, everything goes through the Caddy reverse proxy on port `8080`.
## Docker Compose
Run the full stack:
```sh
docker compose up --build
```
If dependency installation is slow on the first build, enable BuildKit explicitly:
```sh
DOCKER_BUILDKIT=1 docker compose build --progress=plain app
docker compose up
```
Subsequent builds reuse the npm cache declared in the `Dockerfile`.
- Single entry point (Caddy reverse proxy): **`http://localhost:8080`**
- SvelteKit app: `http://localhost:8080/` (or any non-API path)
- PocketBase admin UI: `http://localhost:8080/_/`
- PocketBase REST API: `http://localhost:8080/api/`
- PocketBase direct access (internal only, not exposed): `http://localhost:8090`
The app container uses two PocketBase URLs:
- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image.
- `PUBLIC_POCKETBASE_URL=http://localhost:8080` for browser-side admin uploads and public file URLs. Since the Caddy reverse proxy routes `/api/*` to PocketBase, the public URL points to the proxy.
## PocketBase setup
1. Open `http://localhost:8080/_/` (or `http://localhost:8090/_/` for direct access).
2. Create the first PocketBase admin user when prompted.
3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below.
4. Create starter records:
- `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array.
- `globals`: key `header`, data matching the header JSON in the project prompt.
- `globals`: key `footer`, data matching the footer JSON in the project prompt.
If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them.
### Manual collection fields fallback
If schema import fails because of a PocketBase version mismatch, create these collections manually:
- `pages`
- `slug`: text, required, unique
- `title`: text, required
- `blocks`: json
- `published`: bool
- `globals`
- `key`: text, required, unique
- `data`: json
- `media`
- `file`: file, required, max select `1`, image mime types
- `alt`: text
## Authentication
Admin routes live under `/admin`. Login accepts either:
- a PocketBase admin account, or
- a record from a `users` auth collection if you create one.
All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`.
## CMS routes
- `/admin/login` — sign in
- `/admin/pages` — list/create pages
- `/admin/pages/[slug]` — block editor with draft preview
- `/admin/globals` — header/footer editor
## Public routes
- `/` renders `pages.slug = "home"`
- `/[slug]` renders any other published page
- Unpublished pages return `404`
## Notes
- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON.
- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe.
- The page editor includes draggable reordering using native HTML drag events for compatibility; the requested DnD packages are installed and can be swapped in later if desired.

View file

@ -1 +1 @@
PUBLIC_POCKETBASE_URL=http://localhost:8090
PUBLIC_POCKETBASE_URL=http://localhost:8080

View file

@ -1,140 +1,140 @@
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap');
@import 'tailwindcss';
@plugin 'daisyui' {
themes: light --default;
}
@theme {
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
--font-serif: 'Playfair Display', Georgia, serif;
--color-warm: var(--color-bg, #faf8f5);
--color-charcoal: var(--color-heading, #2c2c2c);
--color-sage: var(--color-primary, #8a9a7b);
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
--color-terracotta: var(--color-accent, #c9825f);
}
@keyframes shrink {
from { scale: 0 1; }
to { scale: 1 1; }
}
.delete-fill {
position: absolute;
inset: 0;
background: transparent;
transform-origin: left;
}
.delete-fill.animating {
animation: shrink 1s ease-in-out forwards;
background: var(--error, #f43f5e);
}
.btn.delete-holding {
color: white !important;
}
.btn.delete-holding .text-error {
color: white !important;
}
:root {
--fg-heading: var(--color-heading, #2c2c2c);
--fg-subheading: var(--color-subheading, #4a4a4a);
--fg-body: var(--color-text, #2c2c2c);
background: var(--color-bg, #faf8f5);
color: var(--fg-body);
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
}
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
.text-fg-body { color: var(--fg-body, #2c2c2c); }
.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); }
.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); }
.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); }
.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); }
.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
.text-fg-heading { color: var(--fg-heading, #2c2c2c); }
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); }
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); }
.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); }
.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); }
.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); }
.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); }
body {
min-height: 100vh;
margin: 0;
background:
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
var(--color-bg, #faf8f5);
}
h1,
h2,
h3,
h4 {
font-family: 'Playfair Display', Georgia, serif;
color: var(--fg-heading, #2c2c2c);
}
.prose-wellness p {
margin: 0.75rem 0;
line-height: 1.8;
}
.prose-wellness h2 {
margin: 1.25rem 0 0.5rem;
font-size: clamp(2rem, 4vw, 3.25rem);
line-height: 1.05;
}
.prose-wellness h3 {
margin: 1rem 0 0.5rem;
font-size: 1.6rem;
}
.prose-wellness ul {
list-style: disc;
padding-left: 1.5rem;
}
.prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline;
text-underline-offset: 3px;
}
/* ── Scroll-reveal animations ── */
.reveal {
opacity: 0;
transform: translateY(30px);
transition:
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
}
.reveal-visible {
opacity: 1;
transform: translateY(0);
}
/* ── Hero fade-in stagger ── */
.animate-fade-in {
opacity: 0;
transform: translateY(20px);
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
}
@keyframes fadeInUp {
to {
opacity: 1;
transform: translateY(0);
}
}
/* ── Smooth scroll ── */
html {
scroll-behavior: smooth;
}
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap');
@import 'tailwindcss';
@plugin 'daisyui' {
themes: light --default;
}
@theme {
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
--font-serif: 'Playfair Display', Georgia, serif;
--color-warm: var(--color-bg, #faf8f5);
--color-charcoal: var(--color-heading, #2c2c2c);
--color-sage: var(--color-primary, #8a9a7b);
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
--color-terracotta: var(--color-accent, #c9825f);
}
@keyframes shrink {
from { scale: 0 1; }
to { scale: 1 1; }
}
.delete-fill {
position: absolute;
inset: 0;
background: transparent;
transform-origin: left;
}
.delete-fill.animating {
animation: shrink 1s ease-in-out forwards;
background: var(--error, #f43f5e);
}
.btn.delete-holding {
color: white !important;
}
.btn.delete-holding .text-error {
color: white !important;
}
:root {
--fg-heading: var(--color-heading, #2c2c2c);
--fg-subheading: var(--color-subheading, #4a4a4a);
--fg-body: var(--color-text, #2c2c2c);
background: var(--color-bg, #faf8f5);
color: var(--fg-body);
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
}
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
.text-fg-body { color: var(--fg-body, #2c2c2c); }
.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); }
.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); }
.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); }
.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); }
.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
.text-fg-heading { color: var(--fg-heading, #2c2c2c); }
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); }
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); }
.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); }
.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); }
.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); }
.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); }
body {
min-height: 100vh;
margin: 0;
background:
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
var(--color-bg, #faf8f5);
}
h1,
h2,
h3,
h4 {
font-family: 'Playfair Display', Georgia, serif;
color: var(--fg-heading, #2c2c2c);
}
.prose-wellness p {
margin: 0.75rem 0;
line-height: 1.8;
}
.prose-wellness h2 {
margin: 1.25rem 0 0.5rem;
font-size: clamp(2rem, 4vw, 3.25rem);
line-height: 1.05;
}
.prose-wellness h3 {
margin: 1rem 0 0.5rem;
font-size: 1.6rem;
}
.prose-wellness ul {
list-style: disc;
padding-left: 1.5rem;
}
.prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline;
text-underline-offset: 3px;
}
/* ── Scroll-reveal animations ── */
.reveal {
opacity: 0;
transform: translateY(30px);
transition:
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
}
.reveal-visible {
opacity: 1;
transform: translateY(0);
}
/* ── Hero fade-in stagger ── */
.animate-fade-in {
opacity: 0;
transform: translateY(20px);
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
}
@keyframes fadeInUp {
to {
opacity: 1;
transform: translateY(0);
}
}
/* ── Smooth scroll ── */
html {
scroll-behavior: smooth;
}

View file

@ -1,28 +1,28 @@
import { redirect, type Handle } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { createPocketBase } from '$lib/pb';
export const handle: Handle = async ({ event, resolve }) => {
event.locals.pb = createPocketBase(
event.request.headers.get('cookie') ?? '',
env.POCKETBASE_INTERNAL_URL || env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090'
);
event.locals.user = event.locals.pb.authStore.record;
const path = event.url.pathname;
const isAdminRoute = path.startsWith('/admin');
const isLoginRoute = path === '/admin/login';
const isAuthed = event.locals.pb.authStore.isValid;
if (isAdminRoute && !isLoginRoute && !isAuthed) {
throw redirect(303, '/admin/login');
}
if (isLoginRoute && isAuthed) {
throw redirect(303, '/admin/pages');
}
const response = await resolve(event);
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
return response;
};
import { redirect, type Handle } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { createPocketBase } from '$lib/pb';
export const handle: Handle = async ({ event, resolve }) => {
event.locals.pb = createPocketBase(
event.request.headers.get('cookie') ?? '',
env.POCKETBASE_INTERNAL_URL || env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080'
);
event.locals.user = event.locals.pb.authStore.record;
const path = event.url.pathname;
const isAdminRoute = path.startsWith('/admin');
const isLoginRoute = path === '/admin/login';
const isAuthed = event.locals.pb.authStore.isValid;
if (isAdminRoute && !isLoginRoute && !isAuthed) {
throw redirect(303, '/admin/login');
}
if (isLoginRoute && isAuthed) {
throw redirect(303, '/admin/pages');
}
const response = await resolve(event);
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
return response;
};

View file

@ -1,63 +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>
<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

@ -1,69 +1,69 @@
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'
};
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;
}
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base;
}
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'
};
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;
}
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base;
}

View file

@ -1,294 +1,294 @@
<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';
let { block, eventCategories = [], onChange = (block: ContentBlock) => {} } = $props<{
block: ContentBlock | null;
eventCategories?: 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>
{/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}
<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';
let { block, eventCategories = [], onChange = (block: ContentBlock) => {} } = $props<{
block: ContentBlock | null;
eventCategories?: 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>
{/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

@ -1,105 +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>
<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

@ -1,78 +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}
<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

@ -1,38 +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>
<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

@ -1,54 +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>
<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

@ -1,44 +1,44 @@
<script lang="ts">
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground } 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';
let { blocks = [], calendarEvents = [] } = $props<{ blocks: ContentBlock[]; calendarEvents?: CalendarEventRecord[] }>();
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} />
{/if}
</BackgroundWrapper>
{/each}
<script lang="ts">
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground } 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';
let { blocks = [], calendarEvents = [] } = $props<{ blocks: ContentBlock[]; calendarEvents?: CalendarEventRecord[] }>();
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} />
{/if}
</BackgroundWrapper>
{/each}

View file

@ -1,26 +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>
<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

@ -1,30 +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>
<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

@ -1,22 +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>
<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

@ -1,7 +1,7 @@
<script lang="ts">
let { data } = $props<{ data: Record<string, any> }>();
const height = $derived(data.height ?? 64);
</script>
<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

@ -1,87 +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 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>
<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 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

@ -1,11 +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>
<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

@ -1,31 +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>
<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

@ -1,126 +1,126 @@
<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">
<p class="text-sm uppercase tracking-[0.3em] text-sage-dark/75">Calendar</p>
<h2 class="font-display mt-2 text-4xl text-charcoal md:text-5xl">{data.title || 'Upcoming Events'}</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>
<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">
<p class="text-sm uppercase tracking-[0.3em] text-sage-dark/75">Calendar</p>
<h2 class="font-display mt-2 text-4xl text-charcoal md:text-5xl">{data.title || 'Upcoming Events'}</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

@ -1,199 +1,199 @@
import type { CalendarEventRecord, ContentBlock } from '$lib/types';
type UnknownRecord = Record<string, unknown>;
export type CalendarDay = {
date: Date;
dateKey: string;
dayNumber: number;
inMonth: boolean;
isToday: boolean;
};
export type CalendarMonth = {
date: Date;
label: string;
days: CalendarDay[];
};
export function hasUpcomingCalendarBlock(blocks: ContentBlock[] = []) {
return blocks.some((block) => block.type === 'upcoming_calendar');
}
export function toDateInput(value?: string | null) {
if (!value) return '';
return value.slice(0, 10);
}
export function toDatetimeInput(value?: string | null) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value.slice(0, 16);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60_000);
return local.toISOString().slice(0, 16);
}
export function dateInputToPocketBase(value: string, allDay = true) {
if (!value) return '';
if (!allDay && value.includes('T')) {
return new Date(value).toISOString();
}
return `${value.slice(0, 10)} 00:00:00.000Z`;
}
export function parseEventDate(value?: string | null) {
if (!value) return null;
const datePart = value.slice(0, 10);
const [year, month, day] = datePart.split('-').map(Number);
if (!year || !month || !day) return null;
return new Date(year, month - 1, day);
}
export function dateKey(date: Date) {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
return `${year}-${month}-${day}`;
}
export function addDays(date: Date, days: number) {
const copy = new Date(date);
copy.setDate(copy.getDate() + days);
return copy;
}
export function addMonths(date: Date, months: number) {
return new Date(date.getFullYear(), date.getMonth() + months, 1);
}
export function startOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
export function endOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
export function getUpcomingCalendarRange(reference = new Date()) {
const start = startOfMonth(reference);
const end = endOfMonth(addMonths(reference, 1));
return { start, end };
}
export function createCalendarMonth(monthDate: Date, reference = new Date()): CalendarMonth {
const first = startOfMonth(monthDate);
const monthEnd = endOfMonth(monthDate);
const gridStart = addDays(first, -first.getDay());
const gridEnd = addDays(monthEnd, 6 - monthEnd.getDay());
const todayKey = dateKey(reference);
const days: CalendarDay[] = [];
for (let day = new Date(gridStart); day <= gridEnd; day = addDays(day, 1)) {
days.push({
date: new Date(day),
dateKey: dateKey(day),
dayNumber: day.getDate(),
inMonth: day.getMonth() === first.getMonth(),
isToday: dateKey(day) === todayKey
});
}
return {
date: first,
label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }),
days
};
}
export function getCurrentAndNextMonths(reference = new Date()) {
const current = startOfMonth(reference);
return [createCalendarMonth(current, reference), createCalendarMonth(addMonths(current, 1), reference)];
}
export function rangesOverlap(startA: Date, endA: Date, startB: Date, endB: Date) {
return startA <= endB && endA >= startB;
}
export function eventRange(event: Pick<CalendarEventRecord, 'start' | 'end'>) {
const start = parseEventDate(event.start) || new Date();
const end = parseEventDate(event.end) || start;
return end < start ? { start: end, end: start } : { start, end };
}
export function eventOverlapsDay(event: CalendarEventRecord, day: Date) {
const { start, end } = eventRange(event);
return rangesOverlap(start, end, day, day);
}
export function eventOverlapsRange(event: CalendarEventRecord, start: Date, end: Date) {
const range = eventRange(event);
return rangesOverlap(range.start, range.end, start, end);
}
export function normalizeEvent(record: UnknownRecord): CalendarEventRecord {
return {
id: String(record.id || ''),
name: String(record.name || ''),
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
description: record.description ? String(record.description) : '',
color: String(record.color || '#8a9a7b'),
link: record.link ? String(record.link) : '',
categories: normalizeCategories(record.categories),
published: Boolean(record.published),
allDay: record.allDay !== false
};
}
export function normalizeCategories(value: unknown): string[] {
if (Array.isArray(value)) {
return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))];
}
if (typeof value === 'string') {
return [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
}
return [];
}
export function categoriesToText(categories: string[] = []) {
return categories.join(', ');
}
export function extractCategories(events: CalendarEventRecord[]) {
return [...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b));
}
export function eventMatchesCategories(event: CalendarEventRecord, categories: string[] = []) {
if (!categories.length) return true;
return event.categories?.some((category) => categories.includes(category));
}
export function sortEvents(events: CalendarEventRecord[]) {
return [...events].sort((a, b) => {
const startA = parseEventDate(a.start)?.getTime() ?? 0;
const startB = parseEventDate(b.start)?.getTime() ?? 0;
return startA - startB || a.name.localeCompare(b.name);
});
}
export function formatEventDateRange(event: CalendarEventRecord) {
const start = parseEventDate(event.start);
const end = parseEventDate(event.end);
if (!start) return '';
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
return `${formatter.format(start)} – ${formatter.format(end)}`;
}
export function normalizeLink(link?: string) {
const value = String(link || '').trim();
if (!value) return '';
if (value.startsWith('/') || value.startsWith('#') || value.startsWith('mailto:') || value.startsWith('tel:')) return value;
if (/^https?:\/\//i.test(value)) return value;
return `/${value.replace(/^\/+/, '')}`;
}
export function isExternalLink(link?: string) {
return /^https?:\/\//i.test(String(link || ''));
}
import type { CalendarEventRecord, ContentBlock } from '$lib/types';
type UnknownRecord = Record<string, unknown>;
export type CalendarDay = {
date: Date;
dateKey: string;
dayNumber: number;
inMonth: boolean;
isToday: boolean;
};
export type CalendarMonth = {
date: Date;
label: string;
days: CalendarDay[];
};
export function hasUpcomingCalendarBlock(blocks: ContentBlock[] = []) {
return blocks.some((block) => block.type === 'upcoming_calendar');
}
export function toDateInput(value?: string | null) {
if (!value) return '';
return value.slice(0, 10);
}
export function toDatetimeInput(value?: string | null) {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value.slice(0, 16);
const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60_000);
return local.toISOString().slice(0, 16);
}
export function dateInputToPocketBase(value: string, allDay = true) {
if (!value) return '';
if (!allDay && value.includes('T')) {
return new Date(value).toISOString();
}
return `${value.slice(0, 10)} 00:00:00.000Z`;
}
export function parseEventDate(value?: string | null) {
if (!value) return null;
const datePart = value.slice(0, 10);
const [year, month, day] = datePart.split('-').map(Number);
if (!year || !month || !day) return null;
return new Date(year, month - 1, day);
}
export function dateKey(date: Date) {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const day = `${date.getDate()}`.padStart(2, '0');
return `${year}-${month}-${day}`;
}
export function addDays(date: Date, days: number) {
const copy = new Date(date);
copy.setDate(copy.getDate() + days);
return copy;
}
export function addMonths(date: Date, months: number) {
return new Date(date.getFullYear(), date.getMonth() + months, 1);
}
export function startOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
export function endOfMonth(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
export function getUpcomingCalendarRange(reference = new Date()) {
const start = startOfMonth(reference);
const end = endOfMonth(addMonths(reference, 1));
return { start, end };
}
export function createCalendarMonth(monthDate: Date, reference = new Date()): CalendarMonth {
const first = startOfMonth(monthDate);
const monthEnd = endOfMonth(monthDate);
const gridStart = addDays(first, -first.getDay());
const gridEnd = addDays(monthEnd, 6 - monthEnd.getDay());
const todayKey = dateKey(reference);
const days: CalendarDay[] = [];
for (let day = new Date(gridStart); day <= gridEnd; day = addDays(day, 1)) {
days.push({
date: new Date(day),
dateKey: dateKey(day),
dayNumber: day.getDate(),
inMonth: day.getMonth() === first.getMonth(),
isToday: dateKey(day) === todayKey
});
}
return {
date: first,
label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }),
days
};
}
export function getCurrentAndNextMonths(reference = new Date()) {
const current = startOfMonth(reference);
return [createCalendarMonth(current, reference), createCalendarMonth(addMonths(current, 1), reference)];
}
export function rangesOverlap(startA: Date, endA: Date, startB: Date, endB: Date) {
return startA <= endB && endA >= startB;
}
export function eventRange(event: Pick<CalendarEventRecord, 'start' | 'end'>) {
const start = parseEventDate(event.start) || new Date();
const end = parseEventDate(event.end) || start;
return end < start ? { start: end, end: start } : { start, end };
}
export function eventOverlapsDay(event: CalendarEventRecord, day: Date) {
const { start, end } = eventRange(event);
return rangesOverlap(start, end, day, day);
}
export function eventOverlapsRange(event: CalendarEventRecord, start: Date, end: Date) {
const range = eventRange(event);
return rangesOverlap(range.start, range.end, start, end);
}
export function normalizeEvent(record: UnknownRecord): CalendarEventRecord {
return {
id: String(record.id || ''),
name: String(record.name || ''),
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
description: record.description ? String(record.description) : '',
color: String(record.color || '#8a9a7b'),
link: record.link ? String(record.link) : '',
categories: normalizeCategories(record.categories),
published: Boolean(record.published),
allDay: record.allDay !== false
};
}
export function normalizeCategories(value: unknown): string[] {
if (Array.isArray(value)) {
return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))];
}
if (typeof value === 'string') {
return [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
}
return [];
}
export function categoriesToText(categories: string[] = []) {
return categories.join(', ');
}
export function extractCategories(events: CalendarEventRecord[]) {
return [...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b));
}
export function eventMatchesCategories(event: CalendarEventRecord, categories: string[] = []) {
if (!categories.length) return true;
return event.categories?.some((category) => categories.includes(category));
}
export function sortEvents(events: CalendarEventRecord[]) {
return [...events].sort((a, b) => {
const startA = parseEventDate(a.start)?.getTime() ?? 0;
const startB = parseEventDate(b.start)?.getTime() ?? 0;
return startA - startB || a.name.localeCompare(b.name);
});
}
export function formatEventDateRange(event: CalendarEventRecord) {
const start = parseEventDate(event.start);
const end = parseEventDate(event.end);
if (!start) return '';
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
return `${formatter.format(start)} – ${formatter.format(end)}`;
}
export function normalizeLink(link?: string) {
const value = String(link || '').trim();
if (!value) return '';
if (value.startsWith('/') || value.startsWith('#') || value.startsWith('mailto:') || value.startsWith('tel:')) return value;
if (/^https?:\/\//i.test(value)) return value;
return `/${value.replace(/^\/+/, '')}`;
}
export function isExternalLink(link?: string) {
return /^https?:\/\//i.test(String(link || ''));
}

View file

@ -1,26 +1,26 @@
<script lang="ts">
import type { FooterGlobal } from '$lib/types';
let { footer } = $props<{ footer: FooterGlobal }>();
</script>
<footer class="mt-12 border-t border-charcoal/5 bg-white/45">
<div class="mx-auto grid max-w-6xl gap-10 px-6 py-12 md:grid-cols-[1.2fr_1fr_1fr]">
<div>
<h2 class="text-3xl">{footer.businessName}</h2>
<p class="mt-4 max-w-sm leading-7 text-charcoal/65">{footer.tagline}</p>
</div>
<div class="space-y-2 text-charcoal/70">
{#if footer.address}<p>{footer.address}</p>{/if}
{#if footer.phone}<p><a class="hover:text-sage-dark" href={`tel:${footer.phone}`}>{footer.phone}</a></p>{/if}
{#if footer.email}<p><a class="hover:text-sage-dark" href={`mailto:${footer.email}`}>{footer.email}</a></p>{/if}
</div>
<div class="space-y-3">
{#each footer.socialLinks || [] as link}
{#if link.url}
<a class="block font-semibold capitalize text-sage-dark hover:text-terracotta" href={link.url} target="_blank" rel="noreferrer">{link.platform}</a>
{/if}
{/each}
</div>
</div>
<div class="border-t border-charcoal/5 px-6 py-5 text-center text-sm text-charcoal/55">{footer.copyrightText}</div>
</footer>
<script lang="ts">
import type { FooterGlobal } from '$lib/types';
let { footer } = $props<{ footer: FooterGlobal }>();
</script>
<footer class="mt-12 border-t border-charcoal/5 bg-white/45">
<div class="mx-auto grid max-w-6xl gap-10 px-6 py-12 md:grid-cols-[1.2fr_1fr_1fr]">
<div>
<h2 class="text-3xl">{footer.businessName}</h2>
<p class="mt-4 max-w-sm leading-7 text-charcoal/65">{footer.tagline}</p>
</div>
<div class="space-y-2 text-charcoal/70">
{#if footer.address}<p>{footer.address}</p>{/if}
{#if footer.phone}<p><a class="hover:text-sage-dark" href={`tel:${footer.phone}`}>{footer.phone}</a></p>{/if}
{#if footer.email}<p><a class="hover:text-sage-dark" href={`mailto:${footer.email}`}>{footer.email}</a></p>{/if}
</div>
<div class="space-y-3">
{#each footer.socialLinks || [] as link}
{#if link.url}
<a class="block font-semibold capitalize text-sage-dark hover:text-terracotta" href={link.url} target="_blank" rel="noreferrer">{link.platform}</a>
{/if}
{/each}
</div>
</div>
<div class="border-t border-charcoal/5 px-6 py-5 text-center text-sm text-charcoal/55">{footer.copyrightText}</div>
</footer>

View file

@ -1,27 +1,27 @@
<script lang="ts">
import type { HeaderGlobal } from '$lib/types';
let { header } = $props<{ header: HeaderGlobal }>();
</script>
<header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/90 backdrop-blur">
<div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-6 py-4">
<a class="flex items-center gap-3" href="/" aria-label="Home">
{#if header.logo?.url}
<img class="h-12 w-12 rounded-full object-cover" src={header.logo.url} alt={header.logo.alt || ''} />
{:else}
<span class="grid h-12 w-12 place-items-center rounded-full bg-sage text-lg font-bold text-white">ES</span>
{/if}
<span class="font-serif text-xl font-bold">Eva Shafik</span>
</a>
<nav class="hidden items-center gap-7 md:flex" aria-label="Main navigation">
{#each header.navLinks || [] as link}
<a class="text-sm font-semibold text-charcoal/75 transition hover:text-sage-dark" href={link.href}>{link.label}</a>
{/each}
</nav>
{#if header.ctaButton?.label}
<a class="btn rounded-full border-0 px-6 text-white hover:opacity-90" style="background-color: var(--color-primary, #8a9a7b);" href={header.ctaButton.href}>{header.ctaButton.label}</a>
{/if}
</div>
</header>
<script lang="ts">
import type { HeaderGlobal } from '$lib/types';
let { header } = $props<{ header: HeaderGlobal }>();
</script>
<header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/90 backdrop-blur">
<div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-6 py-4">
<a class="flex items-center gap-3" href="/" aria-label="Home">
{#if header.logo?.url}
<img class="h-12 w-12 rounded-full object-cover" src={header.logo.url} alt={header.logo.alt || ''} />
{:else}
<span class="grid h-12 w-12 place-items-center rounded-full bg-sage text-lg font-bold text-white">ES</span>
{/if}
<span class="font-serif text-xl font-bold">Eva Shafik</span>
</a>
<nav class="hidden items-center gap-7 md:flex" aria-label="Main navigation">
{#each header.navLinks || [] as link}
<a class="text-sm font-semibold text-charcoal/75 transition hover:text-sage-dark" href={link.href}>{link.label}</a>
{/each}
</nav>
{#if header.ctaButton?.label}
<a class="btn rounded-full border-0 px-6 text-white hover:opacity-90" style="background-color: var(--color-primary, #8a9a7b);" href={header.ctaButton.href}>{header.ctaButton.label}</a>
{/if}
</div>
</header>

View file

@ -1,139 +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 });
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 });
}

View file

@ -1,37 +1,37 @@
import PocketBase from 'pocketbase';
import { env } from '$env/dynamic/public';
import { browser } from '$app/environment';
export const pbUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
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('/admin/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();
}
import PocketBase from 'pocketbase';
import { env } from '$env/dynamic/public';
import { browser } from '$app/environment';
export const pbUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080';
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('/admin/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

@ -1,30 +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();
}
};
/**
* 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

@ -1,113 +1,113 @@
export type BlockType =
| 'text'
| 'image_text'
| 'timeline'
| 'hero'
| 'button'
| 'spacer'
| 'testimonials'
| 'upcoming_calendar';
export type BlockBackground = {
type: 'none' | 'color' | 'image';
color: string;
imageUrl: string;
attachment: 'scroll' | 'fixed';
overlay: boolean;
overlayOpacity: number; // 0–100
};
export type BlockForeground = {
mode: 'default' | 'custom';
headingColor: string;
subheadingColor: string;
textColor: string;
};
export type ContentBlock = {
id: string;
type: BlockType;
data: Record<string, any>;
};
export type PageRecord = {
id: string;
slug: string;
title: string;
blocks: ContentBlock[];
published: boolean;
};
export type CalendarEventRecord = {
id: string;
name: string;
start: string;
end?: string;
description?: string;
color: string;
link?: string;
categories: string[];
published: boolean;
allDay: boolean;
};
export type UpcomingCalendarBlockData = {
title?: string;
categories?: string[];
};
export type HeaderGlobal = {
logo: { url: string; alt: string };
navLinks: { label: string; href: string }[];
ctaButton: { label: string; href: string };
homePage: string;
};
export type FooterGlobal = {
businessName: string;
tagline: string;
address: string;
phone: string;
email: string;
socialLinks: { platform: string; url: string }[];
copyrightText: string;
};
export const defaultHeader: HeaderGlobal = {
logo: { url: '', alt: 'Massage studio logo' },
navLinks: [
{ label: 'Home', href: '/' },
{ label: 'About', href: '/about' },
{ label: 'Services', href: '/services' }
],
ctaButton: { label: 'Book Now', href: '/book' },
homePage: 'home'
};
export const defaultFooter: FooterGlobal = {
businessName: 'Eva Shafik Massage',
tagline: 'Warm, restorative massage therapy for everyday wellbeing.',
address: '',
phone: '',
email: '',
socialLinks: [{ platform: 'instagram', url: '' }],
copyrightText: `© ${new Date().getFullYear()} Eva Shafik Massage. All rights reserved.`
};
export type ColorsGlobal = {
background: string;
heading: string;
subheading: string;
text: string;
primary: string;
accent: string;
};
export const defaultColors: ColorsGlobal = {
background: '#faf8f5',
heading: '#2c2c2c',
subheading: '#4a4a4a',
text: '#2c2c2c',
primary: '#8a9a7b',
accent: '#c9825f'
};
export type BlockType =
| 'text'
| 'image_text'
| 'timeline'
| 'hero'
| 'button'
| 'spacer'
| 'testimonials'
| 'upcoming_calendar';
export type BlockBackground = {
type: 'none' | 'color' | 'image';
color: string;
imageUrl: string;
attachment: 'scroll' | 'fixed';
overlay: boolean;
overlayOpacity: number; // 0–100
};
export type BlockForeground = {
mode: 'default' | 'custom';
headingColor: string;
subheadingColor: string;
textColor: string;
};
export type ContentBlock = {
id: string;
type: BlockType;
data: Record<string, any>;
};
export type PageRecord = {
id: string;
slug: string;
title: string;
blocks: ContentBlock[];
published: boolean;
};
export type CalendarEventRecord = {
id: string;
name: string;
start: string;
end?: string;
description?: string;
color: string;
link?: string;
categories: string[];
published: boolean;
allDay: boolean;
};
export type UpcomingCalendarBlockData = {
title?: string;
categories?: string[];
};
export type HeaderGlobal = {
logo: { url: string; alt: string };
navLinks: { label: string; href: string }[];
ctaButton: { label: string; href: string };
homePage: string;
};
export type FooterGlobal = {
businessName: string;
tagline: string;
address: string;
phone: string;
email: string;
socialLinks: { platform: string; url: string }[];
copyrightText: string;
};
export const defaultHeader: HeaderGlobal = {
logo: { url: '', alt: 'Massage studio logo' },
navLinks: [
{ label: 'Home', href: '/' },
{ label: 'About', href: '/about' },
{ label: 'Services', href: '/services' }
],
ctaButton: { label: 'Book Now', href: '/book' },
homePage: 'home'
};
export const defaultFooter: FooterGlobal = {
businessName: 'Eva Shafik Massage',
tagline: 'Warm, restorative massage therapy for everyday wellbeing.',
address: '',
phone: '',
email: '',
socialLinks: [{ platform: 'instagram', url: '' }],
copyrightText: `© ${new Date().getFullYear()} Eva Shafik Massage. All rights reserved.`
};
export type ColorsGlobal = {
background: string;
heading: string;
subheading: string;
text: string;
primary: string;
accent: string;
};
export const defaultColors: ColorsGlobal = {
background: '#faf8f5',
heading: '#2c2c2c',
subheading: '#4a4a4a',
text: '#2c2c2c',
primary: '#8a9a7b',
accent: '#c9825f'
};

View file

@ -1,23 +1,23 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try {
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
return record.data || fallback;
} catch {
return fallback;
}
}
export const load: LayoutServerLoad = async ({ locals, url }) => {
const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter),
getGlobal(locals.pb, 'colors', defaultColors)
]);
if (!header.homePage) header.homePage = defaultHeader.homePage;
return { header, footer, colors, user: locals.user, url: { pathname: url.pathname } };
};
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try {
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
return record.data || fallback;
} catch {
return fallback;
}
}
export const load: LayoutServerLoad = async ({ locals, url }) => {
const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter),
getGlobal(locals.pb, 'colors', defaultColors)
]);
if (!header.homePage) header.homePage = defaultHeader.homePage;
return { header, footer, colors, user: locals.user, url: { pathname: url.pathname } };
};

View file

@ -1,35 +1,35 @@
<script lang="ts">
import '../app.css';
import favicon from '$lib/assets/favicon.svg';
import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte';
import { onMount } from 'svelte';
let { children, data } = $props();
let isAdmin = $derived(data.url?.pathname?.startsWith('/admin'));
onMount(() => {
if (data.colors && !isAdmin) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
});
</script>
<svelte:head>
<link rel="icon" href={favicon} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</svelte:head>
{#if isAdmin}
{@render children()}
{:else}
<Header header={data.header} />
<main>{@render children()}</main>
<Footer footer={data.footer} />
{/if}
<script lang="ts">
import '../app.css';
import favicon from '$lib/assets/favicon.svg';
import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte';
import { onMount } from 'svelte';
let { children, data } = $props();
let isAdmin = $derived(data.url?.pathname?.startsWith('/admin'));
onMount(() => {
if (data.colors && !isAdmin) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
});
</script>
<svelte:head>
<link rel="icon" href={favicon} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</svelte:head>
{#if isAdmin}
{@render children()}
{:else}
<Header header={data.header} />
<main>{@render children()}</main>
<Footer footer={data.footer} />
{/if}

View file

@ -1,33 +1,33 @@
import { error } from '@sveltejs/kit';
import { defaultHeader, type CalendarEventRecord } from '$lib/types';
import { eventOverlapsRange, getUpcomingCalendarRange, hasUpcomingCalendarBlock, normalizeEvent } from '$lib/calendar';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
// Get home page slug from header global, fallback to 'home'
let homeSlug = defaultHeader.homePage;
try {
const header = await locals.pb.collection('globals').getFirstListItem('key = "header"');
homeSlug = header.data?.homePage || homeSlug;
} catch {
// Use default
}
try {
const page = await locals.pb
.collection('pages')
.getFirstListItem(`slug = "${homeSlug}" && published = true`);
let calendarEvents: CalendarEventRecord[] = [];
if (hasUpcomingCalendarBlock(page.blocks || [])) {
const range = getUpcomingCalendarRange();
const events = await locals.pb.collection('events').getFullList({
filter: `published = true && start <= "${range.end.toISOString()}"`,
sort: 'start'
});
calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
}
return { page, calendarEvents };
} catch {
throw error(404, 'Page not found');
}
};
import { error } from '@sveltejs/kit';
import { defaultHeader, type CalendarEventRecord } from '$lib/types';
import { eventOverlapsRange, getUpcomingCalendarRange, hasUpcomingCalendarBlock, normalizeEvent } from '$lib/calendar';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
// Get home page slug from header global, fallback to 'home'
let homeSlug = defaultHeader.homePage;
try {
const header = await locals.pb.collection('globals').getFirstListItem('key = "header"');
homeSlug = header.data?.homePage || homeSlug;
} catch {
// Use default
}
try {
const page = await locals.pb
.collection('pages')
.getFirstListItem(`slug = "${homeSlug}" && published = true`);
let calendarEvents: CalendarEventRecord[] = [];
if (hasUpcomingCalendarBlock(page.blocks || [])) {
const range = getUpcomingCalendarRange();
const events = await locals.pb.collection('events').getFullList({
filter: `published = true && start <= "${range.end.toISOString()}"`,
sort: 'start'
});
calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
}
return { page, calendarEvents };
} catch {
throw error(404, 'Page not found');
}
};

View file

@ -1,24 +1,24 @@
import { error } from '@sveltejs/kit';
import { eventOverlapsRange, getUpcomingCalendarRange, hasUpcomingCalendarBlock, normalizeEvent } from '$lib/calendar';
import type { CalendarEventRecord } from '$lib/types';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, locals }) => {
try {
const page = await locals.pb
.collection('pages')
.getFirstListItem(`slug = "${params.slug}" && published = true`);
let calendarEvents: CalendarEventRecord[] = [];
if (hasUpcomingCalendarBlock(page.blocks || [])) {
const range = getUpcomingCalendarRange();
const events = await locals.pb.collection('events').getFullList({
filter: `published = true && start <= "${range.end.toISOString()}"`,
sort: 'start'
});
calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
}
return { page, calendarEvents };
} catch {
throw error(404, 'Page not found');
}
};
import { error } from '@sveltejs/kit';
import { eventOverlapsRange, getUpcomingCalendarRange, hasUpcomingCalendarBlock, normalizeEvent } from '$lib/calendar';
import type { CalendarEventRecord } from '$lib/types';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, locals }) => {
try {
const page = await locals.pb
.collection('pages')
.getFirstListItem(`slug = "${params.slug}" && published = true`);
let calendarEvents: CalendarEventRecord[] = [];
if (hasUpcomingCalendarBlock(page.blocks || [])) {
const range = getUpcomingCalendarRange();
const events = await locals.pb.collection('events').getFullList({
filter: `published = true && start <= "${range.end.toISOString()}"`,
sort: 'start'
});
calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
}
return { page, calendarEvents };
} catch {
throw error(404, 'Page not found');
}
};

View file

@ -1,10 +1,10 @@
<script lang="ts">
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
let { data } = $props();
</script>
<svelte:head>
<title>{data.page.title}</title>
</svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} />
<script lang="ts">
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
let { data } = $props();
</script>
<svelte:head>
<title>{data.page.title}</title>
</svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} />

View file

@ -1,5 +1,5 @@
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = ({ locals }) => {
return { user: locals.user };
};
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = ({ locals }) => {
return { user: locals.user };
};

View file

@ -1,94 +1,94 @@
<script lang="ts">
let { children } = $props();
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
let importing = $state(false);
async function handleExport() {
try {
const res = await fetch('/admin/api/export');
if (!res.ok) throw new Error(`Export failed (${res.status})`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
} catch (e) {
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
}
}
async function handleImport(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
importing = true;
importStatus = null;
try {
const text = await file.text();
const json = JSON.parse(text);
const res = await fetch('/admin/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(json)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Import failed (${res.status})`);
}
const result = await res.json();
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
setTimeout(() => location.reload(), 1500);
} catch (e) {
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
} finally {
importing = false;
input.value = '';
}
}
</script>
<div class="min-h-screen bg-base-200">
<div class="navbar bg-base-100 shadow-sm">
<div class="flex-1">
<a class="btn btn-ghost text-xl" href="/admin/pages">Massage CMS</a>
</div>
<div class="flex-none gap-2">
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a>
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
<div class="dropdown dropdown-end">
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
Export/Import
</button>
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
<li><button type="button" onclick={handleExport}>Export all</button></li>
<li>
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
{importing ? 'Importing…' : 'Import'}
</button>
</li>
</ul>
</div>
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
<form class="inline" method="POST" action="/admin/login?/logout">
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
</form>
</div>
</div>
{#if importStatus}
<div class="mx-auto max-w-7xl px-4 pt-2">
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
{importStatus.message}
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
</div>
</div>
{/if}
<main class="mx-auto max-w-7xl p-4 md:p-8">
{@render children()}
</main>
</div>
<script lang="ts">
let { children } = $props();
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
let importing = $state(false);
async function handleExport() {
try {
const res = await fetch('/admin/api/export');
if (!res.ok) throw new Error(`Export failed (${res.status})`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
} catch (e) {
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
}
}
async function handleImport(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
importing = true;
importStatus = null;
try {
const text = await file.text();
const json = JSON.parse(text);
const res = await fetch('/admin/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(json)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Import failed (${res.status})`);
}
const result = await res.json();
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
setTimeout(() => location.reload(), 1500);
} catch (e) {
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
} finally {
importing = false;
input.value = '';
}
}
</script>
<div class="min-h-screen bg-base-200">
<div class="navbar bg-base-100 shadow-sm">
<div class="flex-1">
<a class="btn btn-ghost text-xl" href="/admin/pages">Massage CMS</a>
</div>
<div class="flex-none gap-2">
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a>
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
<div class="dropdown dropdown-end">
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
Export/Import
</button>
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
<li><button type="button" onclick={handleExport}>Export all</button></li>
<li>
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
{importing ? 'Importing…' : 'Import'}
</button>
</li>
</ul>
</div>
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
<form class="inline" method="POST" action="/admin/login?/logout">
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
</form>
</div>
</div>
{#if importStatus}
<div class="mx-auto max-w-7xl px-4 pt-2">
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
{importStatus.message}
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
</div>
</div>
{/if}
<main class="mx-auto max-w-7xl p-4 md:p-8">
{@render children()}
</main>
</div>

View file

@ -1,89 +1,89 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
extractImageUrls,
fetchImageAsBase64,
replaceUrlsWithKeys,
urlToKey,
type SiteExport
} from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals
const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals
const allUrls = new Set<string>();
for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url);
}
for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url);
}
// Fetch each image as base64
const images: Record<string, string> = {};
for (const url of allUrls) {
try {
const key = urlToKey(url);
images[key] = await fetchImageAsBase64(url);
} catch (e) {
console.warn(`Could not fetch image: ${url}`, e);
}
}
// Build URL → key mapping
const urlToKeyMap = new Map<string, string>();
for (const url of allUrls) {
urlToKeyMap.set(url, urlToKey(url));
}
// Replace URLs with placeholders in pages
const exportPages = pages.map((p) => ({
slug: p.slug,
title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
published: p.published
}));
// Replace URLs with placeholders in globals
const exportGlobals = globals.map((g) => ({
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
}));
const exportEvents = events.map((record) => {
const event = normalizeEvent(record);
return {
name: event.name,
start: event.start,
end: event.end,
description: event.description,
color: event.color,
link: event.link,
categories: event.categories,
published: event.published,
allDay: event.allDay
};
});
const exportData: SiteExport = {
version: 1,
exportedAt: new Date().toISOString(),
pages: exportPages,
globals: exportGlobals,
events: exportEvents,
images
};
return json(exportData, {
headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
}
});
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
extractImageUrls,
fetchImageAsBase64,
replaceUrlsWithKeys,
urlToKey,
type SiteExport
} from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals
const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals
const allUrls = new Set<string>();
for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url);
}
for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url);
}
// Fetch each image as base64
const images: Record<string, string> = {};
for (const url of allUrls) {
try {
const key = urlToKey(url);
images[key] = await fetchImageAsBase64(url);
} catch (e) {
console.warn(`Could not fetch image: ${url}`, e);
}
}
// Build URL → key mapping
const urlToKeyMap = new Map<string, string>();
for (const url of allUrls) {
urlToKeyMap.set(url, urlToKey(url));
}
// Replace URLs with placeholders in pages
const exportPages = pages.map((p) => ({
slug: p.slug,
title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
published: p.published
}));
// Replace URLs with placeholders in globals
const exportGlobals = globals.map((g) => ({
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
}));
const exportEvents = events.map((record) => {
const event = normalizeEvent(record);
return {
name: event.name,
start: event.start,
end: event.end,
description: event.description,
color: event.color,
link: event.link,
categories: event.categories,
published: event.published,
allDay: event.allDay
};
});
const exportData: SiteExport = {
version: 1,
exportedAt: new Date().toISOString(),
pages: exportPages,
globals: exportGlobals,
events: exportEvents,
images
};
return json(exportData, {
headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
}
});
};

View file

@ -1,140 +1,140 @@
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
dataUriToFile,
restorePlaceholders,
type SiteExport
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
const body = (await request.json()) as SiteExport;
if (!body || body.version !== 1) {
throw error(400, 'Invalid or unsupported export file.');
}
const results = {
imagesUploaded: 0,
pagesImported: 0,
globalsImported: 0,
eventsImported: 0,
errors: [] as string[]
};
// 1. Upload images to PocketBase media collection
// Build a map: placeholder key → new PocketBase URL
const keyToUrl = new Map<string, string>();
for (const [key, dataUri] of Object.entries(body.images)) {
try {
// Derive a filename from the key (e.g. "abc12345_logo.png")
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename);
const formData = new FormData();
formData.append('file', file);
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const record = await locals.pb.collection('media').create(formData);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
keyToUrl.set(key, newUrl);
results.imagesUploaded++;
} catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 2. Import pages
for (const page of body.pages) {
try {
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// Try to find existing page by slug
let existing;
try {
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('pages').update(existing.id, {
title: page.title,
blocks,
published: page.published
});
} else {
await locals.pb.collection('pages').create({
slug: page.slug,
title: page.title,
blocks,
published: page.published
});
}
results.pagesImported++;
} catch (e) {
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 3. Import globals
for (const g of body.globals) {
try {
const data = restorePlaceholders(g.data, keyToUrl);
let existing;
try {
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('globals').update(existing.id, { data });
} else {
await locals.pb.collection('globals').create({ key: g.key, data });
}
results.globalsImported++;
} catch (e) {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 4. Import events
for (const event of body.events || []) {
try {
let existing;
try {
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
} catch {
existing = null;
}
const payload = {
name: event.name,
start: event.start,
end: event.end || null,
description: event.description || '',
color: event.color || '#8a9a7b',
link: event.link || '',
categories: event.categories || [],
published: Boolean(event.published),
allDay: event.allDay !== false
};
if (existing) {
await locals.pb.collection('events').update(existing.id, payload);
} else {
await locals.pb.collection('events').create(payload);
}
results.eventsImported++;
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
dataUriToFile,
restorePlaceholders,
type SiteExport
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
const body = (await request.json()) as SiteExport;
if (!body || body.version !== 1) {
throw error(400, 'Invalid or unsupported export file.');
}
const results = {
imagesUploaded: 0,
pagesImported: 0,
globalsImported: 0,
eventsImported: 0,
errors: [] as string[]
};
// 1. Upload images to PocketBase media collection
// Build a map: placeholder key → new PocketBase URL
const keyToUrl = new Map<string, string>();
for (const [key, dataUri] of Object.entries(body.images)) {
try {
// Derive a filename from the key (e.g. "abc12345_logo.png")
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename);
const formData = new FormData();
formData.append('file', file);
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const record = await locals.pb.collection('media').create(formData);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080';
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
keyToUrl.set(key, newUrl);
results.imagesUploaded++;
} catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 2. Import pages
for (const page of body.pages) {
try {
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// Try to find existing page by slug
let existing;
try {
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('pages').update(existing.id, {
title: page.title,
blocks,
published: page.published
});
} else {
await locals.pb.collection('pages').create({
slug: page.slug,
title: page.title,
blocks,
published: page.published
});
}
results.pagesImported++;
} catch (e) {
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 3. Import globals
for (const g of body.globals) {
try {
const data = restorePlaceholders(g.data, keyToUrl);
let existing;
try {
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('globals').update(existing.id, { data });
} else {
await locals.pb.collection('globals').create({ key: g.key, data });
}
results.globalsImported++;
} catch (e) {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 4. Import events
for (const event of body.events || []) {
try {
let existing;
try {
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
} catch {
existing = null;
}
const payload = {
name: event.name,
start: event.start,
end: event.end || null,
description: event.description || '',
color: event.color || '#8a9a7b',
link: event.link || '',
categories: event.categories || [],
published: Boolean(event.published),
allDay: event.allDay !== false
};
if (existing) {
await locals.pb.collection('events').update(existing.id, payload);
} else {
await locals.pb.collection('events').create(payload);
}
results.eventsImported++;
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
};

View file

@ -1,27 +1,27 @@
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
export const POST: RequestHandler = async ({ request, locals }) => {
const formData = await request.formData();
const file = formData.get('file') as File | null;
const alt = formData.get('alt') as string | null;
if (!file) {
throw error(400, 'No file provided');
}
const uploadForm = new FormData();
uploadForm.append('file', file);
if (alt) uploadForm.append('alt', alt);
try {
const record = await locals.pb.collection('media').create(uploadForm);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8090';
const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
return json({ record, url });
} catch (e) {
console.error('Media upload error:', e);
throw error(500, 'Upload failed');
}
};
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
export const POST: RequestHandler = async ({ request, locals }) => {
const formData = await request.formData();
const file = formData.get('file') as File | null;
const alt = formData.get('alt') as string | null;
if (!file) {
throw error(400, 'No file provided');
}
const uploadForm = new FormData();
uploadForm.append('file', file);
if (alt) uploadForm.append('alt', alt);
try {
const record = await locals.pb.collection('media').create(uploadForm);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080';
const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
return json({ record, url });
} catch (e) {
console.error('Media upload error:', e);
throw error(500, 'Upload failed');
}
};

View file

@ -1,54 +1,54 @@
import { fail } from '@sveltejs/kit';
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
import type { Actions, PageServerLoad } from './$types';
function eventPayload(data: FormData) {
const allDay = String(data.get('allDay')) === 'true';
const start = String(data.get('start') || '').trim();
const end = String(data.get('end') || '').trim();
const name = String(data.get('name') || '').trim();
return {
name,
start: dateInputToPocketBase(start, allDay),
end: end ? dateInputToPocketBase(end, allDay) : null,
description: String(data.get('description') || '').trim(),
color: String(data.get('color') || '#8a9a7b').trim(),
link: String(data.get('link') || '').trim(),
categories: normalizeCategories(String(data.get('categories') || '')),
published: String(data.get('published')) === 'true',
allDay
};
}
export const load: PageServerLoad = async ({ locals }) => {
const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const events = records.map((record) => normalizeEvent(record));
return { events };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const payload = eventPayload(data);
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
await locals.pb.collection('events').create(payload);
return { ok: true };
},
update: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
const payload = eventPayload(data);
if (!id) return fail(400, { message: 'Event id is required.' });
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
await locals.pb.collection('events').update(id, payload);
return { ok: true };
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Event id is required.' });
await locals.pb.collection('events').delete(id);
return { ok: true };
}
};
import { fail } from '@sveltejs/kit';
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
import type { Actions, PageServerLoad } from './$types';
function eventPayload(data: FormData) {
const allDay = String(data.get('allDay')) === 'true';
const start = String(data.get('start') || '').trim();
const end = String(data.get('end') || '').trim();
const name = String(data.get('name') || '').trim();
return {
name,
start: dateInputToPocketBase(start, allDay),
end: end ? dateInputToPocketBase(end, allDay) : null,
description: String(data.get('description') || '').trim(),
color: String(data.get('color') || '#8a9a7b').trim(),
link: String(data.get('link') || '').trim(),
categories: normalizeCategories(String(data.get('categories') || '')),
published: String(data.get('published')) === 'true',
allDay
};
}
export const load: PageServerLoad = async ({ locals }) => {
const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const events = records.map((record) => normalizeEvent(record));
return { events };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const payload = eventPayload(data);
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
await locals.pb.collection('events').create(payload);
return { ok: true };
},
update: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
const payload = eventPayload(data);
if (!id) return fail(400, { message: 'Event id is required.' });
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
await locals.pb.collection('events').update(id, payload);
return { ok: true };
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Event id is required.' });
await locals.pb.collection('events').delete(id);
return { ok: true };
}
};

View file

@ -1,236 +1,236 @@
<script lang="ts">
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar';
import type { CalendarEventRecord } from '$lib/types';
let { data, form } = $props();
let events = $derived(sortEvents(data.events || []));
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
let showEditor = $state(false);
let draft = $state<CalendarEventRecord>({
id: '',
name: '',
start: toDateInput(new Date().toISOString()),
end: '',
description: '',
color: '#8a9a7b',
link: '',
categories: [],
published: false,
allDay: true
});
let categoryText = $state('');
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let month = $derived(createCalendarMonth(viewDate));
let action = $derived(draft.id ? '?/update' : '?/create');
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start));
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end));
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
function eventsForDay(date: Date) {
return events.filter((event) => eventOverlapsDay(event, date));
}
function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
return {
id: '',
name: '',
start,
end: '',
description: '',
color: '#8a9a7b',
link: '',
categories: [],
published: false,
allDay: true
};
}
function createEvent(start?: string) {
draft = emptyDraft(start);
categoryText = '';
showEditor = true;
}
function editEvent(event: CalendarEventRecord) {
draft = structuredClone(event);
categoryText = event.categories.join(', ');
showEditor = true;
}
function previousMonth() {
viewDate = addMonths(viewDate, -1);
}
function nextMonth() {
viewDate = addMonths(viewDate, 1);
}
function addCategory(category: string) {
if (!category || draft.categories.includes(category)) return;
draft = { ...draft, categories: [...draft.categories, category] };
categoryText = draft.categories.join(', ');
}
function removeCategory(category: string) {
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
categoryText = draft.categories.join(', ');
}
function syncCategoryText(value: string) {
categoryText = value;
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
}
</script>
<svelte:head><title>Calendar | CMS</title></svelte:head>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Calendar</h1>
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
</div>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
<h2 class="text-2xl font-bold">{month.label}</h2>
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
</div>
<div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
{#each weekdays as weekday}<div>{weekday}</div>{/each}
</div>
<div class="mt-2 grid grid-cols-7 gap-2">
{#each month.days as day}
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
<button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
<div class="space-y-1">
{#each eventsForDay(day.date) as event}
<button class="w-full rounded-lg px-2 py-1 text-left text-xs font-semibold text-white shadow" style={`background:${event.color || '#8a9a7b'}`} type="button" onclick={() => editEvent(event)}>
<span class="block truncate">{event.name}</span>
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
</button>
{/each}
</div>
</div>
{/each}
</div>
</div>
<div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-xl font-bold">All events</h2>
<div class="overflow-x-auto">
<table class="table">
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each events as event}
<tr>
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
<td>{formatEventDateRange(event)}</td>
<td>{event.categories.join(', ')}</td>
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
</div>
{#if showEditor}
<div class="fixed inset-0 z-50 bg-black/50 p-4">
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<div class="mb-4 flex items-center justify-between gap-3">
<h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2>
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
</div>
<form method="POST" action={action} class="space-y-4">
<input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
<input type="hidden" name="categories" value={categoryText} />
<label class="form-control w-full">
<div class="label"><span class="label-text">Name</span></div>
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
</label>
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full">
<div class="label"><span class="label-text">Start</span></div>
<input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">End optional</span></div>
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
</label>
</div>
<div class="flex flex-wrap gap-4">
<label class="label cursor-pointer justify-start gap-3">
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
<span class="label-text">All-day event</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
<span class="label-text">Published</span>
</label>
</div>
<label class="form-control w-full">
<div class="label"><span class="label-text">Description</span></div>
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
</label>
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full">
<div class="label"><span class="label-text">Color</span></div>
<div class="flex gap-2">
<input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} />
<input class="input input-bordered flex-1" name="color" bind:value={draft.color} />
</div>
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Link optional</span></div>
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
</label>
</div>
<div class="rounded-box border border-base-300 p-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Categories comma-separated</span></div>
<input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
</label>
{#if allCategories.length}
<div class="mt-3 flex flex-wrap gap-2">
{#each allCategories as category}
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button>
{/each}
</div>
{/if}
</div>
<div class="flex justify-between gap-2 pt-2">
{#if draft.id}
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
{:else}
<span></span>
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save event</button>
</div>
</div>
</form>
</div>
</div>
{/if}
<script lang="ts">
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar';
import type { CalendarEventRecord } from '$lib/types';
let { data, form } = $props();
let events = $derived(sortEvents(data.events || []));
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
let showEditor = $state(false);
let draft = $state<CalendarEventRecord>({
id: '',
name: '',
start: toDateInput(new Date().toISOString()),
end: '',
description: '',
color: '#8a9a7b',
link: '',
categories: [],
published: false,
allDay: true
});
let categoryText = $state('');
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let month = $derived(createCalendarMonth(viewDate));
let action = $derived(draft.id ? '?/update' : '?/create');
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start));
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end));
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
function eventsForDay(date: Date) {
return events.filter((event) => eventOverlapsDay(event, date));
}
function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
return {
id: '',
name: '',
start,
end: '',
description: '',
color: '#8a9a7b',
link: '',
categories: [],
published: false,
allDay: true
};
}
function createEvent(start?: string) {
draft = emptyDraft(start);
categoryText = '';
showEditor = true;
}
function editEvent(event: CalendarEventRecord) {
draft = structuredClone(event);
categoryText = event.categories.join(', ');
showEditor = true;
}
function previousMonth() {
viewDate = addMonths(viewDate, -1);
}
function nextMonth() {
viewDate = addMonths(viewDate, 1);
}
function addCategory(category: string) {
if (!category || draft.categories.includes(category)) return;
draft = { ...draft, categories: [...draft.categories, category] };
categoryText = draft.categories.join(', ');
}
function removeCategory(category: string) {
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
categoryText = draft.categories.join(', ');
}
function syncCategoryText(value: string) {
categoryText = value;
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
}
</script>
<svelte:head><title>Calendar | CMS</title></svelte:head>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Calendar</h1>
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
</div>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
<h2 class="text-2xl font-bold">{month.label}</h2>
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
</div>
<div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
{#each weekdays as weekday}<div>{weekday}</div>{/each}
</div>
<div class="mt-2 grid grid-cols-7 gap-2">
{#each month.days as day}
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
<button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
<div class="space-y-1">
{#each eventsForDay(day.date) as event}
<button class="w-full rounded-lg px-2 py-1 text-left text-xs font-semibold text-white shadow" style={`background:${event.color || '#8a9a7b'}`} type="button" onclick={() => editEvent(event)}>
<span class="block truncate">{event.name}</span>
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
</button>
{/each}
</div>
</div>
{/each}
</div>
</div>
<div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-xl font-bold">All events</h2>
<div class="overflow-x-auto">
<table class="table">
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each events as event}
<tr>
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
<td>{formatEventDateRange(event)}</td>
<td>{event.categories.join(', ')}</td>
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
</div>
{#if showEditor}
<div class="fixed inset-0 z-50 bg-black/50 p-4">
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<div class="mb-4 flex items-center justify-between gap-3">
<h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2>
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
</div>
<form method="POST" action={action} class="space-y-4">
<input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
<input type="hidden" name="categories" value={categoryText} />
<label class="form-control w-full">
<div class="label"><span class="label-text">Name</span></div>
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
</label>
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full">
<div class="label"><span class="label-text">Start</span></div>
<input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">End optional</span></div>
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
</label>
</div>
<div class="flex flex-wrap gap-4">
<label class="label cursor-pointer justify-start gap-3">
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
<span class="label-text">All-day event</span>
</label>
<label class="label cursor-pointer justify-start gap-3">
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
<span class="label-text">Published</span>
</label>
</div>
<label class="form-control w-full">
<div class="label"><span class="label-text">Description</span></div>
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
</label>
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full">
<div class="label"><span class="label-text">Color</span></div>
<div class="flex gap-2">
<input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} />
<input class="input input-bordered flex-1" name="color" bind:value={draft.color} />
</div>
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Link optional</span></div>
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
</label>
</div>
<div class="rounded-box border border-base-300 p-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Categories comma-separated</span></div>
<input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
</label>
{#if allCategories.length}
<div class="mt-3 flex flex-wrap gap-2">
{#each allCategories as category}
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button>
{/each}
</div>
{/if}
</div>
<div class="flex justify-between gap-2 pt-2">
{#if draft.id}
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
{:else}
<span></span>
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save event</button>
</div>
</div>
</form>
</div>
</div>
{/if}

View file

@ -1,31 +1,31 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try {
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
} catch {
return await pb.collection('globals').create({ key, data: fallback });
}
}
export const load: PageServerLoad = async ({ locals }) => {
const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter),
getGlobal(locals.pb, 'colors', defaultColors)
]);
// Fetch all pages for the home page selector
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
return { header, footer, colors, pages };
};
export const actions: Actions = {
save: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id'));
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) });
}
};
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try {
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
} catch {
return await pb.collection('globals').create({ key, data: fallback });
}
}
export const load: PageServerLoad = async ({ locals }) => {
const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter),
getGlobal(locals.pb, 'colors', defaultColors)
]);
// Fetch all pages for the home page selector
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
return { header, footer, colors, pages };
};
export const actions: Actions = {
save: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id'));
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) });
}
};

View file

@ -1,96 +1,96 @@
<script lang="ts">
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
let { data } = $props();
let header = $state(structuredClone(data.header.data));
let footer = $state(structuredClone(data.footer.data));
let colors = $state(structuredClone(data.colors.data));
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
</script>
<svelte:head><title>Globals | CMS</title></svelte:head>
<div class="mb-6">
<h1 class="text-3xl font-bold">Global sections</h1>
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
</div>
<div class="grid gap-6 xl:grid-cols-3">
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="id" value={data.header.id} />
<input type="hidden" name="data" value={JSON.stringify(header)} />
<h2 class="mb-4 text-2xl font-bold">Header</h2>
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
<h3 class="mt-6 font-bold">Navigation</h3>
{#each header.navLinks || [] as link, i}
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
<input class="input input-bordered" bind:value={link.label} placeholder="Label" />
<input class="input input-bordered" bind:value={link.href} placeholder="Href" />
<button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button>
<h3 class="mt-6 font-bold">CTA button</h3>
<input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" />
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
<h3 class="mt-6 font-bold">Home page</h3>
<select class="select select-bordered w-full" bind:value={header.homePage}>
<option value="">— Select a page —</option>
{#each data.pages as page}
<option value={page.slug}>{page.title} [{page.slug}]</option>
{/each}
</select>
<p class="text-sm text-base-content/60 mt-1">The page that "/" will redirect to.</p>
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save header</button>
</form>
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="id" value={data.footer.id} />
<input type="hidden" name="data" value={JSON.stringify(footer)} />
<h2 class="mb-4 text-2xl font-bold">Footer</h2>
{#each ['businessName', 'tagline', 'address', 'phone', 'email', 'copyrightText'] as field}
<label class="form-control w-full">
<div class="label"><span class="label-text">{field}</span></div>
<input class="input input-bordered w-full" bind:value={footer[field]} />
</label>
{/each}
<h3 class="mt-6 font-bold">Social links</h3>
{#each footer.socialLinks || [] as link, i}
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
<input class="input input-bordered" bind:value={link.platform} placeholder="Platform" />
<input class="input input-bordered" bind:value={link.url} placeholder="URL" />
<button class="btn btn-error btn-outline" type="button" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={addSocial}>Add social link</button>
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save footer</button>
</form>
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="id" value={data.colors.id} />
<input type="hidden" name="data" value={JSON.stringify(colors)} />
<h2 class="mb-4 text-2xl font-bold">Colors</h2>
<p class="text-sm text-base-content/60 mb-4">These colors are applied across the site as defaults.</p>
{#each [
{ key: 'background', label: 'Background color' },
{ key: 'heading', label: 'Heading color' },
{ key: 'subheading', label: 'Subheading color' },
{ key: 'text', label: 'Text color' },
{ key: 'primary', label: 'Primary color (buttons, links)' },
{ key: 'accent', label: 'Accent color (highlights)' }
] as { key, label }}
<label class="form-control w-full mb-3">
<div class="label"><span class="label-text">{label}</span></div>
<div class="flex gap-2">
<input type="color" class="cursor-pointer" bind:value={colors[key]} />
<input type="text" class="input input-bordered flex-1 font-mono text-sm" bind:value={colors[key]} />
</div>
</label>
{/each}
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save colors</button>
</form>
</div>
<script lang="ts">
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
let { data } = $props();
let header = $state(structuredClone(data.header.data));
let footer = $state(structuredClone(data.footer.data));
let colors = $state(structuredClone(data.colors.data));
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
</script>
<svelte:head><title>Globals | CMS</title></svelte:head>
<div class="mb-6">
<h1 class="text-3xl font-bold">Global sections</h1>
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
</div>
<div class="grid gap-6 xl:grid-cols-3">
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="id" value={data.header.id} />
<input type="hidden" name="data" value={JSON.stringify(header)} />
<h2 class="mb-4 text-2xl font-bold">Header</h2>
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
<h3 class="mt-6 font-bold">Navigation</h3>
{#each header.navLinks || [] as link, i}
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
<input class="input input-bordered" bind:value={link.label} placeholder="Label" />
<input class="input input-bordered" bind:value={link.href} placeholder="Href" />
<button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button>
<h3 class="mt-6 font-bold">CTA button</h3>
<input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" />
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
<h3 class="mt-6 font-bold">Home page</h3>
<select class="select select-bordered w-full" bind:value={header.homePage}>
<option value="">— Select a page —</option>
{#each data.pages as page}
<option value={page.slug}>{page.title} [{page.slug}]</option>
{/each}
</select>
<p class="text-sm text-base-content/60 mt-1">The page that "/" will redirect to.</p>
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save header</button>
</form>
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="id" value={data.footer.id} />
<input type="hidden" name="data" value={JSON.stringify(footer)} />
<h2 class="mb-4 text-2xl font-bold">Footer</h2>
{#each ['businessName', 'tagline', 'address', 'phone', 'email', 'copyrightText'] as field}
<label class="form-control w-full">
<div class="label"><span class="label-text">{field}</span></div>
<input class="input input-bordered w-full" bind:value={footer[field]} />
</label>
{/each}
<h3 class="mt-6 font-bold">Social links</h3>
{#each footer.socialLinks || [] as link, i}
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
<input class="input input-bordered" bind:value={link.platform} placeholder="Platform" />
<input class="input input-bordered" bind:value={link.url} placeholder="URL" />
<button class="btn btn-error btn-outline" type="button" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={addSocial}>Add social link</button>
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save footer</button>
</form>
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="id" value={data.colors.id} />
<input type="hidden" name="data" value={JSON.stringify(colors)} />
<h2 class="mb-4 text-2xl font-bold">Colors</h2>
<p class="text-sm text-base-content/60 mb-4">These colors are applied across the site as defaults.</p>
{#each [
{ key: 'background', label: 'Background color' },
{ key: 'heading', label: 'Heading color' },
{ key: 'subheading', label: 'Subheading color' },
{ key: 'text', label: 'Text color' },
{ key: 'primary', label: 'Primary color (buttons, links)' },
{ key: 'accent', label: 'Accent color (highlights)' }
] as { key, label }}
<label class="form-control w-full mb-3">
<div class="label"><span class="label-text">{label}</span></div>
<div class="flex gap-2">
<input type="color" class="cursor-pointer" bind:value={colors[key]} />
<input type="text" class="input input-bordered flex-1 font-mono text-sm" bind:value={colors[key]} />
</div>
</label>
{/each}
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save colors</button>
</form>
</div>

View file

@ -1,27 +1,27 @@
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
login: async ({ request, locals }) => {
const data = await request.formData();
const email = String(data.get('email') || '');
const password = String(data.get('password') || '');
try {
try {
await locals.pb.admins.authWithPassword(email, password);
} catch {
await locals.pb.collection('users').authWithPassword(email, password);
}
} catch (err) {
console.error('Login failed for', email, err);
return fail(400, { message: 'Invalid email or password.' });
}
throw redirect(303, '/admin/pages');
},
logout: async ({ locals }) => {
locals.pb.authStore.clear();
throw redirect(303, '/admin/login');
}
};
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
login: async ({ request, locals }) => {
const data = await request.formData();
const email = String(data.get('email') || '');
const password = String(data.get('password') || '');
try {
try {
await locals.pb.admins.authWithPassword(email, password);
} catch {
await locals.pb.collection('users').authWithPassword(email, password);
}
} catch (err) {
console.error('Login failed for', email, err);
return fail(400, { message: 'Invalid email or password.' });
}
throw redirect(303, '/admin/pages');
},
logout: async ({ locals }) => {
locals.pb.authStore.clear();
throw redirect(303, '/admin/login');
}
};

View file

@ -1,26 +1,26 @@
<script lang="ts">
let { form } = $props();
</script>
<svelte:head><title>Admin login</title></svelte:head>
<div class="grid min-h-screen place-items-center bg-base-200 p-6">
<form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login">
<div class="card-body">
<h1 class="card-title text-3xl">Sign in</h1>
<p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p>
{#if form?.message}
<div class="alert alert-error mt-4">{form.message}</div>
{/if}
<label class="form-control mt-4">
<span class="label-text">Email</span>
<input class="input input-bordered" name="email" type="email" required />
</label>
<label class="form-control">
<span class="label-text">Password</span>
<input class="input input-bordered" name="password" type="password" required />
</label>
<button class="btn btn-primary mt-4" type="submit">Login</button>
</div>
</form>
</div>
<script lang="ts">
let { form } = $props();
</script>
<svelte:head><title>Admin login</title></svelte:head>
<div class="grid min-h-screen place-items-center bg-base-200 p-6">
<form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login">
<div class="card-body">
<h1 class="card-title text-3xl">Sign in</h1>
<p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p>
{#if form?.message}
<div class="alert alert-error mt-4">{form.message}</div>
{/if}
<label class="form-control mt-4">
<span class="label-text">Email</span>
<input class="input input-bordered" name="email" type="email" required />
</label>
<label class="form-control">
<span class="label-text">Password</span>
<input class="input input-bordered" name="password" type="password" required />
</label>
<button class="btn btn-primary mt-4" type="submit">Login</button>
</div>
</form>
</div>

View file

@ -1,29 +1,29 @@
import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
return { pages };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
const title = String(data.get('title') || '').trim();
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
throw redirect(303, `/admin/pages/${slug}`);
},
toggle: async ({ request, locals }) => {
const data = await request.formData();
await locals.pb.collection('pages').update(String(data.get('id')), {
published: String(data.get('published')) !== 'true'
});
},
delete: async ({ request, locals }) => {
const data = await request.formData();
await locals.pb.collection('pages').delete(String(data.get('id')));
}
};
import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
return { pages };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
const title = String(data.get('title') || '').trim();
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
throw redirect(303, `/admin/pages/${slug}`);
},
toggle: async ({ request, locals }) => {
const data = await request.formData();
await locals.pb.collection('pages').update(String(data.get('id')), {
published: String(data.get('published')) !== 'true'
});
},
delete: async ({ request, locals }) => {
const data = await request.formData();
await locals.pb.collection('pages').delete(String(data.get('id')));
}
};

View file

@ -1,65 +1,65 @@
<script lang="ts">
let { data, form } = $props();
</script>
<svelte:head><title>Pages | CMS</title></svelte:head>
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div>
<h1 class="text-3xl font-bold">Pages</h1>
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
</div>
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
</div>
{#if form?.message}
<div class="alert alert-error mb-4">{form.message}</div>
{/if}
<div class="overflow-x-auto rounded-box bg-base-100 shadow">
<table class="table">
<thead>
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
</thead>
<tbody>
{#each data.pages as page}
<tr>
<td class="font-mono">{page.slug}</td>
<td>{page.title}</td>
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
<td class="flex justify-end gap-2">
<a class="btn btn-sm" href={`/admin/pages/${page.slug}`}>Edit</a>
<a class="btn btn-sm" href={page.slug === 'home' ? '/' : `/${page.slug}`} target="_blank">Preview</a>
<form method="POST" action="?/toggle">
<input type="hidden" name="id" value={page.id} />
<input type="hidden" name="published" value={page.published} />
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
</form>
<form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}>
<input type="hidden" name="id" value={page.id} />
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
</form>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<dialog id="new-page" class="modal">
<form class="modal-box" method="POST" action="?/create">
<h2 class="text-2xl font-bold">Create page</h2>
<label class="form-control w-full mt-4">
<div class="label"><span class="label-text">Slug</span></div>
<input class="input input-bordered w-full" name="slug" placeholder="about" required />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Title</span></div>
<input class="input input-bordered w-full" name="title" placeholder="About" required />
</label>
<div class="modal-action">
<button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button>
<button class="btn btn-primary" type="submit">Create</button>
</div>
</form>
</dialog>
<script lang="ts">
let { data, form } = $props();
</script>
<svelte:head><title>Pages | CMS</title></svelte:head>
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div>
<h1 class="text-3xl font-bold">Pages</h1>
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
</div>
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
</div>
{#if form?.message}
<div class="alert alert-error mb-4">{form.message}</div>
{/if}
<div class="overflow-x-auto rounded-box bg-base-100 shadow">
<table class="table">
<thead>
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
</thead>
<tbody>
{#each data.pages as page}
<tr>
<td class="font-mono">{page.slug}</td>
<td>{page.title}</td>
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
<td class="flex justify-end gap-2">
<a class="btn btn-sm" href={`/admin/pages/${page.slug}`}>Edit</a>
<a class="btn btn-sm" href={page.slug === 'home' ? '/' : `/${page.slug}`} target="_blank">Preview</a>
<form method="POST" action="?/toggle">
<input type="hidden" name="id" value={page.id} />
<input type="hidden" name="published" value={page.published} />
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
</form>
<form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}>
<input type="hidden" name="id" value={page.id} />
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
</form>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
<dialog id="new-page" class="modal">
<form class="modal-box" method="POST" action="?/create">
<h2 class="text-2xl font-bold">Create page</h2>
<label class="form-control w-full mt-4">
<div class="label"><span class="label-text">Slug</span></div>
<input class="input input-bordered w-full" name="slug" placeholder="about" required />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Title</span></div>
<input class="input input-bordered w-full" name="title" placeholder="About" required />
</label>
<div class="modal-action">
<button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button>
<button class="btn btn-primary" type="submit">Create</button>
</div>
</form>
</dialog>

View file

@ -1,25 +1,25 @@
import { fail, redirect } from '@sveltejs/kit';
import { extractCategories, normalizeEvent } from '$lib/calendar';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, locals }) => {
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
return { page, eventCategories };
};
export const actions: Actions = {
save: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id'));
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
const title = String(data.get('title') || '').trim();
const blocks = JSON.parse(String(data.get('blocks') || '[]'));
const publish = String(data.get('publish')) === 'true';
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
throw redirect(303, `/admin/pages/${slug}`);
}
};
import { fail, redirect } from '@sveltejs/kit';
import { extractCategories, normalizeEvent } from '$lib/calendar';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, locals }) => {
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
return { page, eventCategories };
};
export const actions: Actions = {
save: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id'));
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
const title = String(data.get('title') || '').trim();
const blocks = JSON.parse(String(data.get('blocks') || '[]'));
const publish = String(data.get('publish')) === 'true';
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
throw redirect(303, `/admin/pages/${slug}`);
}
};

View file

@ -1,104 +1,104 @@
<script lang="ts">
import BlockList from '$lib/admin/BlockList.svelte';
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
import type { ContentBlock } from '$lib/types';
let { data, form } = $props();
let page = $state(data.page);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
let selectedId = $state(blocks[0]?.id || '');
let previewMode = $state<'desktop' | 'mobile'>('desktop');
let showPreview = $state(false);
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
function addBlock(type: keyof typeof blockLabels) {
const block = createBlock(type);
blocks = [...blocks, block];
selectedId = block.id;
}
function updateBlock(updated: ContentBlock) {
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
}
function deleteBlock(id: string) {
blocks = blocks.filter((block) => block.id !== id);
if (selectedId === id) selectedId = blocks[0]?.id || '';
}
function moveBlock(from: number, to: number) {
const copy = [...blocks];
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item);
blocks = copy;
}
function openPreview() {
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
showPreview = true;
}
function markPublish(event: MouseEvent) {
const form = (event.currentTarget as HTMLButtonElement).form;
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null;
if (input) input.value = 'true';
}
</script>
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
<form method="POST" action="?/save" class="space-y-6">
<input type="hidden" name="id" value={page.id} />
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<input type="hidden" name="publish" value="false" />
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Edit page</h1>
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
</div>
<div class="flex flex-wrap gap-2">
<button class="btn" type="button" onclick={openPreview}>Preview</button>
<button class="btn btn-outline" type="submit">Save draft</button>
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button>
</div>
</div>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full"><div class="label"><span class="label-text">Slug</span></div><input class="input input-bordered w-full" name="slug" bind:value={page.slug} /></label>
<label class="form-control w-full"><div class="label"><span class="label-text">Title</span></div><input class="input input-bordered w-full" name="title" bind:value={page.title} /></label>
</div>
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
<aside class="space-y-4">
<div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each blockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li>
{/each}
</ul>
</div>
</div>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside>
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} onChange={updateBlock} />
</div>
</form>
{#if showPreview}
<div class="fixed inset-0 z-50 bg-black/60 p-4">
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl">
<div class="mb-3 flex items-center justify-between gap-3">
<div class="join"><button class="btn join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button><button class="btn join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button></div>
<button class="btn" onclick={() => (showPreview = false)}>Close</button>
</div>
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
</div>
</div>
{/if}
<script lang="ts">
import BlockList from '$lib/admin/BlockList.svelte';
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
import type { ContentBlock } from '$lib/types';
let { data, form } = $props();
let page = $state(data.page);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
let selectedId = $state(blocks[0]?.id || '');
let previewMode = $state<'desktop' | 'mobile'>('desktop');
let showPreview = $state(false);
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
function addBlock(type: keyof typeof blockLabels) {
const block = createBlock(type);
blocks = [...blocks, block];
selectedId = block.id;
}
function updateBlock(updated: ContentBlock) {
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
}
function deleteBlock(id: string) {
blocks = blocks.filter((block) => block.id !== id);
if (selectedId === id) selectedId = blocks[0]?.id || '';
}
function moveBlock(from: number, to: number) {
const copy = [...blocks];
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item);
blocks = copy;
}
function openPreview() {
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
showPreview = true;
}
function markPublish(event: MouseEvent) {
const form = (event.currentTarget as HTMLButtonElement).form;
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null;
if (input) input.value = 'true';
}
</script>
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
<form method="POST" action="?/save" class="space-y-6">
<input type="hidden" name="id" value={page.id} />
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<input type="hidden" name="publish" value="false" />
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Edit page</h1>
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
</div>
<div class="flex flex-wrap gap-2">
<button class="btn" type="button" onclick={openPreview}>Preview</button>
<button class="btn btn-outline" type="submit">Save draft</button>
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button>
</div>
</div>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full"><div class="label"><span class="label-text">Slug</span></div><input class="input input-bordered w-full" name="slug" bind:value={page.slug} /></label>
<label class="form-control w-full"><div class="label"><span class="label-text">Title</span></div><input class="input input-bordered w-full" name="title" bind:value={page.title} /></label>
</div>
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
<aside class="space-y-4">
<div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each blockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li>
{/each}
</ul>
</div>
</div>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside>
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} onChange={updateBlock} />
</div>
</form>
{#if showPreview}
<div class="fixed inset-0 z-50 bg-black/60 p-4">
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl">
<div class="mb-3 flex items-center justify-between gap-3">
<div class="join"><button class="btn join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button><button class="btn join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button></div>
<button class="btn" onclick={() => (showPreview = false)}>Close</button>
</div>
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
</div>
</div>
{/if}

View file

@ -1,25 +1,25 @@
<script lang="ts">
import { onMount } from 'svelte';
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
import type { ContentBlock } from '$lib/types';
let blocks = $state<ContentBlock[]>([]);
onMount(() => {
const raw = sessionStorage.getItem('cms-preview-blocks');
if (raw) blocks = JSON.parse(raw);
});
</script>
<svelte:head>
<title>Preview</title>
</svelte:head>
{#if blocks.length}
<BlockRenderer {blocks} />
{:else}
<section class="mx-auto max-w-3xl px-6 py-20 text-center">
<h1 class="text-4xl">No preview content</h1>
<p class="mt-4 text-charcoal/65">Open preview from the page editor to view the current draft.</p>
</section>
{/if}
<script lang="ts">
import { onMount } from 'svelte';
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
import type { ContentBlock } from '$lib/types';
let blocks = $state<ContentBlock[]>([]);
onMount(() => {
const raw = sessionStorage.getItem('cms-preview-blocks');
if (raw) blocks = JSON.parse(raw);
});
</script>
<svelte:head>
<title>Preview</title>
</svelte:head>
{#if blocks.length}
<BlockRenderer {blocks} />
{:else}
<section class="mx-auto max-w-3xl px-6 py-20 text-center">
<h1 class="text-4xl">No preview content</h1>
<p class="mt-4 text-charcoal/65">Open preview from the page editor to view the current draft.</p>
</section>
{/if}

View file

@ -1,347 +1,347 @@
{
"version": 1,
"exportedAt": "2026-05-27T12:07:00.306Z",
"pages": [
{
"slug": "about",
"title": "About Me",
"blocks": [
{
"data": {
"_background": {
"attachment": "fixed",
"color": "",
"imageAlt": "",
"imageUrl": "https://static.tildacdn.one/tild3164-6166-4138-a264-313437663833/chelsea-shapouri-ZN2.jpg",
"overlay": true,
"overlayOpacity": 40,
"type": "image"
},
"_foreground": {
"headingColor": "#ffffff",
"mode": "custom",
"subheadingColor": "#eacb8b",
"textColor": "#eaca85"
},
"buttonLabel": "",
"buttonUrl": "",
"heading": "About Me",
"subheading": "I am often asked about my journey, and would therefore like to give you a little background on my own process of healing and transformation up to this moment."
},
"id": "7f01e183-62ea-4f3c-ab69-a312d8b5df01",
"type": "hero"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#903c49",
"mode": "custom"
},
"alt": "",
"content": "<p><h2>Hi, My name is Eva Shafik</h2>I have dedicated the last 10 years to my work with holistic sexology applying the most progressive and up-to-date methods to improve intimate life.</p>",
"imagePosition": "right",
"url": "https://static.tildacdn.one/tild6363-3837-4530-a330-616562363438/2_DSC3595_web.jpg"
},
"id": "47a5dbed-a891-4d3f-92d9-e5dddcdeb61c",
"type": "image_text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#041b65",
"mode": "custom"
},
"content": "<p><h2>How It All Started</h2>I was born in Poland, where I grew up, studied and graduated from the Business Academy as an economist. In 1997 I moved to Oslo and started my interpreter career. I was quite satisfied with my life: I had a good job, husband, friends. But I always wished to find the work which would be also my passion, something I would love with all my heart till the end of my life.</p><p><br></p><p>In 2009 I attended Shiatsu training in Poland which showed me the power of present touch and compassionate environment. Since then I knew I wanted to work helping people to live healthier and happier lives. When one of my friends, who had already worked as a professional sex-educator, offered me individual lessons on tantric massage and a job in his tantra massage studio I immediately said yes, even without knowing exactly what this work was about.</p><p><br><h2>Awakening Senses</h2>From 2014, at the beginning of my professional career as a Tantric massage therapist and sex-educator, I experienced a great somatic awakening. I experimented a lot with my body by receiving Tantric massages, sexological bodywork and de-armouring sessions, practising different kinds of meditations, yoga and conscious kink. As a result, my level of sensitivity grew and I could experience multiple orgasms and extended erotic states. I was so inspired by the results of embodiment practices that I decided to go deeper into the study of human sexuality.</p>"
},
"id": "2643c5a0-0530-4ac6-928f-203bda471021",
"type": "text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"imageAlt": "",
"imageUrl": "https://static.tildacdn.one/tild3862-3762-4666-b036-613061613862/image4.jpg",
"overlay": true,
"overlayOpacity": 40,
"type": "image"
},
"_foreground": {
"headingColor": "#ffffff",
"mode": "custom",
"subheadingColor": "#ff0000",
"textColor": "#ffffff"
},
"content": "<p><h2>Restoring Heart-Genital Connection</h2>In my work with massages, I met many people who had problems with chronic tension, numbness and other issues on the body level that were holding them back from experiencing sexual bliss. I realized that most of them had a problem not only with physical blockages but also with fear to connect to others on a deep emotional level. To learn how to cope with relational and sexual problems I finished education in the Heart School Tantra where they taught a combination of methods from Gestalt therapy, Primal therapy, trauma healing, couple therapy, sexological bodywork and Tantra. I use a lot of those teachings to help my clients to feel the juiciness of real intimacy and closeness without fears, tension, shame and other restrictions.</p>"
},
"id": "b9e5d1a2-511b-43b8-9b59-3c9183b1a56c",
"type": "text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#041b65",
"mode": "custom"
},
"content": "<p></p><h2>Sexuality and Spirituality</h2>Searching for the best ways to enhance intimacy I came to the conclusion that I cannot avoid the spiritual aspect of sexuality on my path. If you want to experience bliss and ecstasy too, sooner or later you will discover that these states emerge from the deepest feeling of unconditional love, connectedness, trust, peace of mind and highest view on surrounding people and phenomena. I have spent many years on healing the body from the influence of past negative experiences, but I have also realized that if I keep on supporting repeating negative tendencies of my mind there will not be much development and stable results in the future.<div><br>Very big insight and awakening of my awareness happened in 2016 after a very painful breakup and deep emotional crisis. In order to survive I was forced to find the methods to revise my system of beliefs. I questioned many concepts, stiff ideas and negative thoughts that made me feel stressed and, as a result, my body, mind and heart opened even more. I incorporated this Mind Work in my professional activity and it shows very fast and significant results in combination with embodiment practices.<p></p></div>"
},
"id": "67e65e53-010a-410b-ac0c-2b027a1fbe76",
"type": "text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#903c49",
"mode": "custom"
},
"alt": "",
"content": "<p><h2>Where I am now</h2>At this moment, I study Traditional Chinese Medicine at the Zen Shiatsu School and apply for work with subtle energies of the body in my practice with clients. This knowledge helps me to harmonize and restore normal functioning of inner organs that can boost not only sexual activity but the general emotional and physical health.<br><br>On the basis of my experience, I can tailor sessions according to individual needs of my clients. They can be both healing and educational. I can help my clients to find the easiest and most efficient approach through the work with the mind, body, energy or combination of them to open the door to sexual bliss and healthier life. I have also created several programs that consist of a series of sessions that can give you a new perspective on human sexuality and take your skills as a lover to a totally new level.</p>",
"imagePosition": "left",
"url": "https://static.tildacdn.one/tild3066-3831-4130-a130-313234333461/_DSC3507_web.jpg"
},
"id": "7ac7781f-a989-4850-b16d-4c5154428c22",
"type": "image_text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"alignment": "center",
"href": "/book",
"label": "MORE ABOUT SESSIONS",
"size": "lg",
"variant": "primary"
},
"id": "fbc3a78d-77b4-445e-8880-f9bc731fc483",
"type": "button"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"height": 64
},
"id": "67e8c713-80e8-48a2-9a8b-804b14d8405a",
"type": "spacer"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "#eaca85",
"overlay": false,
"overlayOpacity": 40,
"type": "color"
},
"_foreground": {
"headingColor": "#903c49",
"mode": "custom"
},
"items": [
{
"description": "2023, Los Angeles, 100 hours",
"title": "School Of The Work Of Byron Katie"
},
{
"description": "2018 - 2025, Oslo Norway (Ane Grimsæth)\nShiatsu Norge is a part of European Shiatsu School. The teaching consist of three years of advansed educational program based on TCM, 1500 hours",
"title": "Zen Shiatsu School"
},
{
"description": "2020, Mundekulla, Sweden (with Ernest Holm Svendsen), 50 hours",
"title": "Scandinavian Summer Camp, The Work of Byron Katie"
},
{
"description": "2017, Prague, Czech Republic (Peter Walker), 20 hours",
"title": "Baby Massage Course"
},
{
"description": "2016, Nowa Morawa, Poland, 80 hours",
"title": " Shaman's course \"Dancing With Gods\""
},
{
"description": "2015 - 2017 Acupressure online course, California Acupressure Institute (Michael Reed Gach), 10 months, 120 hours",
"title": "Acupressure Master Program"
},
{
"description": "2009 - 2017 detoxing, health restoring fasting on water, macrobiotic lifestyle, shiatsu massage, nutrition education, every spring, Poland, (Agnieszka Olędzka), 480 hours",
"title": "Fasting Courses"
},
{
"description": "2016, Course for professional Tantric massouse, Republic (Daniela Lukesova), 50 hours",
"title": "Holistic Sensual Massage"
},
{
"description": "2014 - 2016, Poland (Mario and Gaya Wisniewski), 400 hours",
"title": "2 Year Training in Heart Tantra School"
},
{
"description": "2016, Hammar, Norway, 2 weekends per year, 110 hours",
"title": "Tai Chi Course"
},
{
"description": "2012 - 2016, Oslo, Norway, 100 hours",
"title": "Karate Training"
},
{
"description": "2012 - 2016, 3 times a year intense course in self-development (Kenny Johnnson), 650 hours",
"title": "The Three Trainings of 3TH2N"
},
{
"description": "2012 - 2016, Norway and Spain (Kenny Johnson) + once a week training, 400 hours",
"title": "Chi Kung, Tai Chi, Eternal Youth Yoga System"
},
{
"description": "2014, Winna Góra, Poland, 80 hours",
"title": "Shaman's seminar \"The Hero's Journey\""
},
{
"description": "2013, levels 1 and 2, Krakow, Poland (Choa Kok Sui) 30 hours",
"title": "Prana Healing Course"
},
{
"description": "2001 - 2010, Kuan Um school, group retreat in Poland, Hungary, Czech Republic and Norway, approximately 500 hours",
"title": "Zen Meditation Course in KUSZ"
},
{
"description": "1987 - 1992, Business and Economics, Statistics, Econometrics, Administration, Graduate Civil Economist, Wroclaw, Poland",
"title": "Business Academy"
}
]
},
"id": "6c3affd2-4ce5-463f-8702-225a8c393354",
"type": "timeline"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "#eaca85",
"overlay": false,
"overlayOpacity": 40,
"type": "color"
},
"alignment": "center",
"href": "/book",
"label": "BOOK A SESSION",
"size": "lg",
"variant": "primary"
},
"id": "c17182a2-5dfc-43e0-ba2a-6d0718e5df38",
"type": "button"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "#eaca85",
"overlay": false,
"overlayOpacity": 40,
"type": "color"
},
"height": 64
},
"id": "86b8787d-7fa6-40ab-8d96-24ab9dea9396",
"type": "spacer"
}
],
"published": true
}
],
"globals": [
{
"key": "header",
"data": {
"ctaButton": {
"href": "/book",
"label": "Book Now"
},
"logo": {
"alt": "Massage studio logo",
"url": ""
},
"navLinks": [
{
"href": "/",
"label": "Home"
},
{
"href": "/about",
"label": "About"
},
{
"href": "/services",
"label": "Services"
}
]
}
},
{
"key": "colors",
"data": {
"accent": "#eacb8b",
"background": "#faf8f5",
"heading": "#2c2c2c",
"primary": "#903c49",
"subheading": "#4a4a4a",
"text": "#2c2c2c"
}
},
{
"key": "footer",
"data": {
"address": "",
"businessName": "Eva Shafik Massage",
"copyrightText": "© 2026 Eva Shafik Massage. All rights reserved.",
"email": "",
"phone": "",
"socialLinks": [
{
"platform": "instagram",
"url": ""
}
],
"tagline": "Warm, restorative massage therapy for everyday wellbeing."
}
}
],
"images": {}
{
"version": 1,
"exportedAt": "2026-05-27T12:07:00.306Z",
"pages": [
{
"slug": "about",
"title": "About Me",
"blocks": [
{
"data": {
"_background": {
"attachment": "fixed",
"color": "",
"imageAlt": "",
"imageUrl": "https://static.tildacdn.one/tild3164-6166-4138-a264-313437663833/chelsea-shapouri-ZN2.jpg",
"overlay": true,
"overlayOpacity": 40,
"type": "image"
},
"_foreground": {
"headingColor": "#ffffff",
"mode": "custom",
"subheadingColor": "#eacb8b",
"textColor": "#eaca85"
},
"buttonLabel": "",
"buttonUrl": "",
"heading": "About Me",
"subheading": "I am often asked about my journey, and would therefore like to give you a little background on my own process of healing and transformation up to this moment."
},
"id": "7f01e183-62ea-4f3c-ab69-a312d8b5df01",
"type": "hero"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#903c49",
"mode": "custom"
},
"alt": "",
"content": "<p><h2>Hi, My name is Eva Shafik</h2>I have dedicated the last 10 years to my work with holistic sexology applying the most progressive and up-to-date methods to improve intimate life.</p>",
"imagePosition": "right",
"url": "https://static.tildacdn.one/tild6363-3837-4530-a330-616562363438/2_DSC3595_web.jpg"
},
"id": "47a5dbed-a891-4d3f-92d9-e5dddcdeb61c",
"type": "image_text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#041b65",
"mode": "custom"
},
"content": "<p><h2>How It All Started</h2>I was born in Poland, where I grew up, studied and graduated from the Business Academy as an economist. In 1997 I moved to Oslo and started my interpreter career. I was quite satisfied with my life: I had a good job, husband, friends. But I always wished to find the work which would be also my passion, something I would love with all my heart till the end of my life.</p><p><br></p><p>In 2009 I attended Shiatsu training in Poland which showed me the power of present touch and compassionate environment. Since then I knew I wanted to work helping people to live healthier and happier lives. When one of my friends, who had already worked as a professional sex-educator, offered me individual lessons on tantric massage and a job in his tantra massage studio I immediately said yes, even without knowing exactly what this work was about.</p><p><br><h2>Awakening Senses</h2>From 2014, at the beginning of my professional career as a Tantric massage therapist and sex-educator, I experienced a great somatic awakening. I experimented a lot with my body by receiving Tantric massages, sexological bodywork and de-armouring sessions, practising different kinds of meditations, yoga and conscious kink. As a result, my level of sensitivity grew and I could experience multiple orgasms and extended erotic states. I was so inspired by the results of embodiment practices that I decided to go deeper into the study of human sexuality.</p>"
},
"id": "2643c5a0-0530-4ac6-928f-203bda471021",
"type": "text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"imageAlt": "",
"imageUrl": "https://static.tildacdn.one/tild3862-3762-4666-b036-613061613862/image4.jpg",
"overlay": true,
"overlayOpacity": 40,
"type": "image"
},
"_foreground": {
"headingColor": "#ffffff",
"mode": "custom",
"subheadingColor": "#ff0000",
"textColor": "#ffffff"
},
"content": "<p><h2>Restoring Heart-Genital Connection</h2>In my work with massages, I met many people who had problems with chronic tension, numbness and other issues on the body level that were holding them back from experiencing sexual bliss. I realized that most of them had a problem not only with physical blockages but also with fear to connect to others on a deep emotional level. To learn how to cope with relational and sexual problems I finished education in the Heart School Tantra where they taught a combination of methods from Gestalt therapy, Primal therapy, trauma healing, couple therapy, sexological bodywork and Tantra. I use a lot of those teachings to help my clients to feel the juiciness of real intimacy and closeness without fears, tension, shame and other restrictions.</p>"
},
"id": "b9e5d1a2-511b-43b8-9b59-3c9183b1a56c",
"type": "text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#041b65",
"mode": "custom"
},
"content": "<p></p><h2>Sexuality and Spirituality</h2>Searching for the best ways to enhance intimacy I came to the conclusion that I cannot avoid the spiritual aspect of sexuality on my path. If you want to experience bliss and ecstasy too, sooner or later you will discover that these states emerge from the deepest feeling of unconditional love, connectedness, trust, peace of mind and highest view on surrounding people and phenomena. I have spent many years on healing the body from the influence of past negative experiences, but I have also realized that if I keep on supporting repeating negative tendencies of my mind there will not be much development and stable results in the future.<div><br>Very big insight and awakening of my awareness happened in 2016 after a very painful breakup and deep emotional crisis. In order to survive I was forced to find the methods to revise my system of beliefs. I questioned many concepts, stiff ideas and negative thoughts that made me feel stressed and, as a result, my body, mind and heart opened even more. I incorporated this Mind Work in my professional activity and it shows very fast and significant results in combination with embodiment practices.<p></p></div>"
},
"id": "67e65e53-010a-410b-ac0c-2b027a1fbe76",
"type": "text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"_foreground": {
"headingColor": "#903c49",
"mode": "custom"
},
"alt": "",
"content": "<p><h2>Where I am now</h2>At this moment, I study Traditional Chinese Medicine at the Zen Shiatsu School and apply for work with subtle energies of the body in my practice with clients. This knowledge helps me to harmonize and restore normal functioning of inner organs that can boost not only sexual activity but the general emotional and physical health.<br><br>On the basis of my experience, I can tailor sessions according to individual needs of my clients. They can be both healing and educational. I can help my clients to find the easiest and most efficient approach through the work with the mind, body, energy or combination of them to open the door to sexual bliss and healthier life. I have also created several programs that consist of a series of sessions that can give you a new perspective on human sexuality and take your skills as a lover to a totally new level.</p>",
"imagePosition": "left",
"url": "https://static.tildacdn.one/tild3066-3831-4130-a130-313234333461/_DSC3507_web.jpg"
},
"id": "7ac7781f-a989-4850-b16d-4c5154428c22",
"type": "image_text"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"alignment": "center",
"href": "/book",
"label": "MORE ABOUT SESSIONS",
"size": "lg",
"variant": "primary"
},
"id": "fbc3a78d-77b4-445e-8880-f9bc731fc483",
"type": "button"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "",
"overlay": false,
"overlayOpacity": 40,
"type": "none"
},
"height": 64
},
"id": "67e8c713-80e8-48a2-9a8b-804b14d8405a",
"type": "spacer"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "#eaca85",
"overlay": false,
"overlayOpacity": 40,
"type": "color"
},
"_foreground": {
"headingColor": "#903c49",
"mode": "custom"
},
"items": [
{
"description": "2023, Los Angeles, 100 hours",
"title": "School Of The Work Of Byron Katie"
},
{
"description": "2018 - 2025, Oslo Norway (Ane Grimsæth)\nShiatsu Norge is a part of European Shiatsu School. The teaching consist of three years of advansed educational program based on TCM, 1500 hours",
"title": "Zen Shiatsu School"
},
{
"description": "2020, Mundekulla, Sweden (with Ernest Holm Svendsen), 50 hours",
"title": "Scandinavian Summer Camp, The Work of Byron Katie"
},
{
"description": "2017, Prague, Czech Republic (Peter Walker), 20 hours",
"title": "Baby Massage Course"
},
{
"description": "2016, Nowa Morawa, Poland, 80 hours",
"title": " Shaman's course \"Dancing With Gods\""
},
{
"description": "2015 - 2017 Acupressure online course, California Acupressure Institute (Michael Reed Gach), 10 months, 120 hours",
"title": "Acupressure Master Program"
},
{
"description": "2009 - 2017 detoxing, health restoring fasting on water, macrobiotic lifestyle, shiatsu massage, nutrition education, every spring, Poland, (Agnieszka Olędzka), 480 hours",
"title": "Fasting Courses"
},
{
"description": "2016, Course for professional Tantric massouse, Republic (Daniela Lukesova), 50 hours",
"title": "Holistic Sensual Massage"
},
{
"description": "2014 - 2016, Poland (Mario and Gaya Wisniewski), 400 hours",
"title": "2 Year Training in Heart Tantra School"
},
{
"description": "2016, Hammar, Norway, 2 weekends per year, 110 hours",
"title": "Tai Chi Course"
},
{
"description": "2012 - 2016, Oslo, Norway, 100 hours",
"title": "Karate Training"
},
{
"description": "2012 - 2016, 3 times a year intense course in self-development (Kenny Johnnson), 650 hours",
"title": "The Three Trainings of 3TH2N"
},
{
"description": "2012 - 2016, Norway and Spain (Kenny Johnson) + once a week training, 400 hours",
"title": "Chi Kung, Tai Chi, Eternal Youth Yoga System"
},
{
"description": "2014, Winna Góra, Poland, 80 hours",
"title": "Shaman's seminar \"The Hero's Journey\""
},
{
"description": "2013, levels 1 and 2, Krakow, Poland (Choa Kok Sui) 30 hours",
"title": "Prana Healing Course"
},
{
"description": "2001 - 2010, Kuan Um school, group retreat in Poland, Hungary, Czech Republic and Norway, approximately 500 hours",
"title": "Zen Meditation Course in KUSZ"
},
{
"description": "1987 - 1992, Business and Economics, Statistics, Econometrics, Administration, Graduate Civil Economist, Wroclaw, Poland",
"title": "Business Academy"
}
]
},
"id": "6c3affd2-4ce5-463f-8702-225a8c393354",
"type": "timeline"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "#eaca85",
"overlay": false,
"overlayOpacity": 40,
"type": "color"
},
"alignment": "center",
"href": "/book",
"label": "BOOK A SESSION",
"size": "lg",
"variant": "primary"
},
"id": "c17182a2-5dfc-43e0-ba2a-6d0718e5df38",
"type": "button"
},
{
"data": {
"_background": {
"attachment": "scroll",
"color": "#eaca85",
"overlay": false,
"overlayOpacity": 40,
"type": "color"
},
"height": 64
},
"id": "86b8787d-7fa6-40ab-8d96-24ab9dea9396",
"type": "spacer"
}
],
"published": true
}
],
"globals": [
{
"key": "header",
"data": {
"ctaButton": {
"href": "/book",
"label": "Book Now"
},
"logo": {
"alt": "Massage studio logo",
"url": ""
},
"navLinks": [
{
"href": "/",
"label": "Home"
},
{
"href": "/about",
"label": "About"
},
{
"href": "/services",
"label": "Services"
}
]
}
},
{
"key": "colors",
"data": {
"accent": "#eacb8b",
"background": "#faf8f5",
"heading": "#2c2c2c",
"primary": "#903c49",
"subheading": "#4a4a4a",
"text": "#2c2c2c"
}
},
{
"key": "footer",
"data": {
"address": "",
"businessName": "Eva Shafik Massage",
"copyrightText": "© 2026 Eva Shafik Massage. All rights reserved.",
"email": "",
"phone": "",
"socialLinks": [
{
"platform": "instagram",
"url": ""
}
],
"tagline": "Warm, restorative massage therapy for everyday wellbeing."
}
}
],
"images": {}
}

View file

@ -1,29 +1,43 @@
services:
pocketbase:
image: spectado/pocketbase:latest
container_name: massage-pocketbase
restart: unless-stopped
ports:
- "8090:80"
volumes:
- pocketbase:/pb/pb_data
app:
build:
context: .
dockerfile: Dockerfile
container_name: massage-app
restart: unless-stopped
depends_on:
- pocketbase
environment:
POCKETBASE_INTERNAL_URL: http://pocketbase:80
PUBLIC_POCKETBASE_URL: http://localhost:8090
ORIGIN: http://localhost:3000
BODY_SIZE_LIMIT: 5242880 # 5MB
ports:
- "3000:3000"
volumes:
pocketbase:
services:
pocketbase:
image: spectado/pocketbase:latest
container_name: massage-pocketbase
restart: unless-stopped
# Internal only — accessed via the caddy reverse proxy
expose:
- "80"
volumes:
- pocketbase:/pb/pb_data
app:
build:
context: .
dockerfile: Dockerfile
container_name: massage-app
restart: unless-stopped
depends_on:
- pocketbase
environment:
POCKETBASE_INTERNAL_URL: http://pocketbase:80
PUBLIC_POCKETBASE_URL: http://localhost:8080
ORIGIN: http://localhost:8080
BODY_SIZE_LIMIT: 5242880 # 5MB
# Internal only — served via the caddy reverse proxy
expose:
- "3000"
caddy:
image: caddy:2-alpine
container_name: massage-caddy
restart: unless-stopped
ports:
- "8080:8080"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
depends_on:
- app
- pocketbase
volumes:
pocketbase:

View file

@ -1,294 +1,294 @@
[
{
"id": "pbc_pages000001",
"name": "pages",
"type": "base",
"system": false,
"listRule": "published = true || @request.auth.id != ''",
"viewRule": "published = true || @request.auth.id != ''",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "text_slug00001",
"name": "slug",
"type": "text",
"system": false,
"required": true,
"presentable": true,
"unique": true,
"options": {
"min": null,
"max": 120,
"pattern": ""
}
},
{
"id": "text_title0001",
"name": "title",
"type": "text",
"system": false,
"required": true,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 180,
"pattern": ""
}
},
{
"id": "json_blocks001",
"name": "blocks",
"type": "json",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSize": 2000000
}
},
{
"id": "bool_published",
"name": "published",
"type": "bool",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {}
}
],
"indexes": [],
"options": {}
},
{
"id": "pbc_globals0001",
"name": "globals",
"type": "base",
"system": false,
"listRule": "",
"viewRule": "",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "text_key000001",
"name": "key",
"type": "text",
"system": false,
"required": true,
"presentable": true,
"unique": true,
"options": {
"min": null,
"max": 80,
"pattern": ""
}
},
{
"id": "json_data00001",
"name": "data",
"type": "json",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSize": 1000000
}
}
],
"indexes": [],
"options": {}
},
{
"id": "pbc_media00001",
"name": "media",
"type": "base",
"system": false,
"listRule": "",
"viewRule": "",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "file_file00001",
"name": "file",
"type": "file",
"system": false,
"required": true,
"presentable": false,
"unique": false,
"options": {
"mimeTypes": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"image/svg+xml"
],
"thumbs": [
"300x300",
"1200x0"
],
"maxSelect": 1,
"maxSize": 10485760,
"protected": false
}
},
{
"id": "text_alt000001",
"name": "alt",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 180,
"pattern": ""
}
}
],
"indexes": [],
"options": {}
},
{
"id": "pbc_events0001",
"name": "events",
"type": "base",
"system": false,
"listRule": "published = true || @request.auth.id != ''",
"viewRule": "published = true || @request.auth.id != ''",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "text_eventname",
"name": "name",
"type": "text",
"system": false,
"required": true,
"presentable": true,
"unique": false,
"options": {
"min": null,
"max": 180,
"pattern": ""
}
},
{
"id": "date_eventstart",
"name": "start",
"type": "date",
"system": false,
"required": true,
"presentable": false,
"unique": false,
"options": {
"min": "",
"max": ""
}
},
{
"id": "date_eventend",
"name": "end",
"type": "date",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": "",
"max": ""
}
},
{
"id": "text_eventdesc",
"name": "description",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 2000,
"pattern": ""
}
},
{
"id": "text_eventcolor",
"name": "color",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 32,
"pattern": ""
}
},
{
"id": "url_eventlink",
"name": "link",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 500,
"pattern": ""
}
},
{
"id": "json_eventcats",
"name": "categories",
"type": "json",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSize": 200000
}
},
{
"id": "bool_eventpub",
"name": "published",
"type": "bool",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {}
},
{
"id": "bool_eventallday",
"name": "allDay",
"type": "bool",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {}
}
],
"indexes": [
"CREATE INDEX `idx_events_start` ON `events` (`start`)",
"CREATE INDEX `idx_events_published` ON `events` (`published`)"
],
"options": {}
}
]
[
{
"id": "pbc_pages000001",
"name": "pages",
"type": "base",
"system": false,
"listRule": "published = true || @request.auth.id != ''",
"viewRule": "published = true || @request.auth.id != ''",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "text_slug00001",
"name": "slug",
"type": "text",
"system": false,
"required": true,
"presentable": true,
"unique": true,
"options": {
"min": null,
"max": 120,
"pattern": ""
}
},
{
"id": "text_title0001",
"name": "title",
"type": "text",
"system": false,
"required": true,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 180,
"pattern": ""
}
},
{
"id": "json_blocks001",
"name": "blocks",
"type": "json",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSize": 2000000
}
},
{
"id": "bool_published",
"name": "published",
"type": "bool",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {}
}
],
"indexes": [],
"options": {}
},
{
"id": "pbc_globals0001",
"name": "globals",
"type": "base",
"system": false,
"listRule": "",
"viewRule": "",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "text_key000001",
"name": "key",
"type": "text",
"system": false,
"required": true,
"presentable": true,
"unique": true,
"options": {
"min": null,
"max": 80,
"pattern": ""
}
},
{
"id": "json_data00001",
"name": "data",
"type": "json",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSize": 1000000
}
}
],
"indexes": [],
"options": {}
},
{
"id": "pbc_media00001",
"name": "media",
"type": "base",
"system": false,
"listRule": "",
"viewRule": "",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "file_file00001",
"name": "file",
"type": "file",
"system": false,
"required": true,
"presentable": false,
"unique": false,
"options": {
"mimeTypes": [
"image/jpeg",
"image/png",
"image/webp",
"image/gif",
"image/svg+xml"
],
"thumbs": [
"300x300",
"1200x0"
],
"maxSelect": 1,
"maxSize": 10485760,
"protected": false
}
},
{
"id": "text_alt000001",
"name": "alt",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 180,
"pattern": ""
}
}
],
"indexes": [],
"options": {}
},
{
"id": "pbc_events0001",
"name": "events",
"type": "base",
"system": false,
"listRule": "published = true || @request.auth.id != ''",
"viewRule": "published = true || @request.auth.id != ''",
"createRule": "@request.auth.id != ''",
"updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''",
"fields": [
{
"id": "text_eventname",
"name": "name",
"type": "text",
"system": false,
"required": true,
"presentable": true,
"unique": false,
"options": {
"min": null,
"max": 180,
"pattern": ""
}
},
{
"id": "date_eventstart",
"name": "start",
"type": "date",
"system": false,
"required": true,
"presentable": false,
"unique": false,
"options": {
"min": "",
"max": ""
}
},
{
"id": "date_eventend",
"name": "end",
"type": "date",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": "",
"max": ""
}
},
{
"id": "text_eventdesc",
"name": "description",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 2000,
"pattern": ""
}
},
{
"id": "text_eventcolor",
"name": "color",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 32,
"pattern": ""
}
},
{
"id": "url_eventlink",
"name": "link",
"type": "text",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"min": null,
"max": 500,
"pattern": ""
}
},
{
"id": "json_eventcats",
"name": "categories",
"type": "json",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {
"maxSize": 200000
}
},
{
"id": "bool_eventpub",
"name": "published",
"type": "bool",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {}
},
{
"id": "bool_eventallday",
"name": "allDay",
"type": "bool",
"system": false,
"required": false,
"presentable": false,
"unique": false,
"options": {}
}
],
"indexes": [
"CREATE INDEX `idx_events_start` ON `events` (`start`)",
"CREATE INDEX `idx_events_published` ON `events` (`published`)"
],
"options": {}
}
]